Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 25 additions & 5 deletions vortex-duckdb/src/file_reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::ops::Range;
use std::sync::Arc;
use std::sync::OnceLock;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;

use futures::FutureExt;
Expand Down Expand Up @@ -39,6 +40,7 @@ use vortex::mask::Mask;
use vortex::scan::DataSource as _;
use vortex::scan::DataSourceRef;
use vortex::scan::ScanRequest;
use vortex::scan::stream::Claims;
use vortex::scan::stream::ScanStream;
use vortex::session::SessionExt as _;

Expand Down Expand Up @@ -135,6 +137,8 @@ pub struct FileScanState {
stream: OnceLock<FileStream>,
/// Whether a clone of `stream` has ended, so no work of the file is left to take.
finished: AtomicBool,
/// How many threads have joined the file, each with its own clone of `stream`.
joined: AtomicUsize,
cache: ConversionCache,
}

Expand All @@ -156,9 +160,18 @@ impl FileScanState {
if self.finished.load(Ordering::Acquire) {
return None;
}
self.stream
.get()
.map(|stream| Split(stream.stream.lock().clone()))
let stream = self.stream.get()?.stream.lock();
// A clone claims its first unit of work, a V1 split or a V2 part, only when its thread
// first polls it, outside DuckDB's lock, so without a bound every thread would join before
// any had claimed. As many clones as units drain the file, so a later thread moves on
// instead.
if let Some(Claims { claimed, total }) = stream.claims()
&& (claimed >= total || self.joined.load(Ordering::Relaxed) >= total)
{
return None;
}
self.joined.fetch_add(1, Ordering::Relaxed);
Some(Split(stream.clone()))
}
}

Expand All @@ -177,6 +190,7 @@ impl OpenFileReader {
plan_source: file.plan_data_source(),
stream: OnceLock::new(),
finished: AtomicBool::new(false),
joined: AtomicUsize::new(0),
cache: ConversionCache::default(),
})),
})
Expand Down Expand Up @@ -473,8 +487,14 @@ pub fn reader_get_progress_in_file(file: &OpenFileReader) -> f64 {
state
.stream
.get()
.and_then(|stream| stream.stream.lock().progress())
.map_or(0.0, |progress| 100.0 * progress)
.and_then(|stream| stream.stream.lock().claims())
.map_or(0.0, |Claims { claimed, total }| {
if total == 0 {
100.0
} else {
100.0 * claimed as f64 / total as f64
}
})
}

/// Called by one thread in planning phase
Expand Down
22 changes: 20 additions & 2 deletions vortex-io/src/runtime/current.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
// SPDX-FileCopyrightText: Copyright the Vortex contributors

use std::future::Future;
use std::pin::pin;
use std::sync::Arc;

use async_channel::TryRecvError;
use futures::FutureExt;
use futures::SinkExt;
use futures::Stream;
use futures::StreamExt;
Expand Down Expand Up @@ -136,7 +138,7 @@ impl BlockingRuntime for CurrentThreadRuntime {
where
Fut: Future<Output = R>,
{
block_on(self.executor.run(fut))
drive(&self.executor, fut)
}

fn block_on_stream<'a, S, R>(&self, stream: S) -> Self::BlockingIterator<'a, R>
Expand All @@ -151,6 +153,22 @@ impl BlockingRuntime for CurrentThreadRuntime {
}
}

/// Drives `fut` to completion on the calling thread.
///
/// The future is polled once before entering the executor and returned from directly if it is
/// ready. Each entry into [`smol::Executor::run`] registers the thread with the executor's shared
/// state, under a write lock that every thread entering the runtime contends on, and a caller that
/// blocks on many futures which are mostly ready already, such as one batch of a scan after
/// another, would otherwise pay that for each of them. A future that is not ready is polled again
/// inside the executor, which runs the runtime's tasks while the thread waits for it.
fn drive<Fut: Future>(executor: &SmolExecutor, fut: Fut) -> Fut::Output {
let mut fut = pin!(fut);
if let Some(output) = fut.as_mut().now_or_never() {
return output;
}
block_on(executor.run(fut))
}

/// An iterator that wraps up a stream to drive it using the current thread execution.
pub struct CurrentThreadIterator<'a, T> {
executor: Arc<SmolExecutor>,
Expand All @@ -161,7 +179,7 @@ impl<T> Iterator for CurrentThreadIterator<'_, T> {
type Item = T;

fn next(&mut self) -> Option<Self::Item> {
block_on(self.executor.run(self.stream.next()))
drive(&self.executor, self.stream.next())
}
}

Expand Down
20 changes: 17 additions & 3 deletions vortex-layout/src/scan/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,10 +329,10 @@ impl DataSourceScan for LayoutReaderScan {
.prepare()?
.execute(Some(self.next_row..self.end_row))?;
let queue = Arc::new(SplitQueue::new(self.session.handle(), per_worker, splits));
let progress = Arc::clone(&queue);
let claims = Arc::clone(&queue);
Ok(
ScanStream::new(self.dtype, move || Arc::clone(&queue).worker())
.with_progress(move || progress.progress()),
.with_claims(move || claims.claims()),
)
}

Expand Down Expand Up @@ -760,6 +760,7 @@ mod split_open_tests {
use vortex_io::runtime::single::SingleThreadRuntime;
use vortex_scan::DataSource;
use vortex_scan::ScanRequest;
use vortex_scan::stream::Claims;

use super::LayoutReaderDataSource;
use super::group_contiguous;
Expand All @@ -782,12 +783,25 @@ mod split_open_tests {
let stream = runtime
.block_on(source(&runtime).scan(ScanRequest::default()))?
.open()?;
assert_eq!(
stream.claims(),
Some(Claims {
claimed: 0,
total: 16
})
);
let workers = (0..3).map(|_| stream.clone().try_collect::<Vec<_>>());
let arrays = runtime.block_on(try_join_all(workers))?;
let mut values = collect_scan_values(arrays.into_iter().flatten().map(Ok))?;
values.sort_unstable();
assert_eq!(values, (0..64).collect::<Vec<_>>());
assert_eq!(stream.progress(), Some(1.0));
assert_eq!(
stream.claims(),
Some(Claims {
claimed: 16,
total: 16
})
);
Ok(())
}

Expand Down
11 changes: 6 additions & 5 deletions vortex-layout/src/scan/split_queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ use parking_lot::Mutex;
use vortex_array::ArrayRef;
use vortex_error::VortexResult;
use vortex_io::runtime::Handle;
use vortex_scan::stream::Claims;

use crate::scan::repeated_scan::ScanTasks;

Expand Down Expand Up @@ -68,12 +69,12 @@ impl SplitQueue {
Some(split)
}

/// The fraction of the splits that the stream's clones have claimed.
pub(crate) fn progress(&self) -> f64 {
if self.total == 0 {
return 1.0;
/// How many of the splits the stream's clones have claimed, out of how many in all.
pub(crate) fn claims(&self) -> Claims {
Claims {
claimed: self.claimed.load(Ordering::Relaxed).min(self.total),
total: self.total,
}
(self.claimed.load(Ordering::Relaxed) as f64 / self.total as f64).min(1.0)
}

/// A new worker over the shared queue, which one clone of the scan's stream polls.
Expand Down
53 changes: 18 additions & 35 deletions vortex-scan/src/source/plan_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,7 @@ use std::future;
use std::iter;
use std::ops::Range;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;

use futures::StreamExt;
Expand All @@ -60,30 +59,27 @@ use crate::planning::planner::Planner;
use crate::planning::planner::WorkScope;
use crate::prepare::PreparedScan;
use crate::prepare::part_root;
use crate::stream::Claims;
use crate::stream::ScanStream;

/// The parts of an unordered scan, cut when the scan is made.
pub(super) struct Planned {
work: Vec<Work>,
/// The rows of the scan's units.
total_rows: u64,
}

/// Prepares each of the scan's `units` once and runs its root, awaiting the zone maps a dynamic
/// filter's root reads, and returns the work the roots produce, in unit and row order.
pub(super) async fn plan(state: &ScanState, units: &[Unit]) -> VortexResult<Planned> {
let mut work = Vec::new();
let mut total_rows = 0;
for unit in units {
let rows = state.unit_rows(unit)?;
if rows.is_empty() {
continue;
}
total_rows += rows.end - rows.start;
let (child, root) = prepare(state, unit, rows)?;
work.extend(run_root(child, root).await?);
}
Ok(Planned { work, total_rows })
Ok(Planned { work })
}

/// Opens the stream of a scan of `units`. An unordered scan reads the parts it `planned`.
Expand All @@ -107,12 +103,11 @@ pub(super) fn open(

let planned = planned.vortex_expect("an unordered scan cuts its parts when it is made");
let queue = Arc::new(Queue {
exhausted: AtomicBool::new(planned.work.is_empty()),
total: planned.work.len(),
work: Mutex::new(planned.work.into()),
total_rows: planned.total_rows,
rows_taken: AtomicU64::new(0),
taken: AtomicUsize::new(0),
});
let progress = Arc::clone(&queue);
let claims = Arc::clone(&queue);
Ok(ScanStream::new(dtype, move || {
let worker = Worker {
queue: Arc::clone(&queue),
Expand All @@ -131,7 +126,7 @@ pub(super) fn open(
.boxed();
limited(arrays, limit.clone())
})
.with_progress(move || progress.progress()))
.with_claims(move || claims.claims()))
}

/// One child's prepared scan, shared by the parts of it that clones run.
Expand Down Expand Up @@ -215,38 +210,26 @@ enum Work {
struct Queue {
/// The work no clone has taken yet, in unit and row order.
work: Mutex<VecDeque<Work>>,
/// Set once a clone has taken the last of `work`.
exhausted: AtomicBool,
/// The rows of the scan's units.
total_rows: u64,
/// The rows of the parts clones have taken.
rows_taken: AtomicU64,
/// The work the queue started with.
total: usize,
/// The work clones have taken.
taken: AtomicUsize,
}

impl Queue {
/// Takes the next work, or `None` once every one has been taken.
fn take(&self) -> Option<Work> {
let mut queue = self.work.lock();
let work = queue.pop_front()?;
if queue.is_empty() {
self.exhausted.store(true, Ordering::Release);
}
if let Work::Part(part) = &work {
self.rows_taken.fetch_add(
part.scope.rows.end - part.scope.rows.start,
Ordering::Relaxed,
);
}
let work = self.work.lock().pop_front()?;
self.taken.fetch_add(1, Ordering::Relaxed);
Some(work)
}

/// The fraction of the scan's rows whose parts clones have taken. Pruning can leave rows that
/// no part covers, so a queue with nothing left to take has made all of its progress.
fn progress(&self) -> f64 {
if self.total_rows == 0 || self.exhausted.load(Ordering::Relaxed) {
return 1.0;
/// How much of the queue's work clones have taken, out of how much in all.
fn claims(&self) -> Claims {
Claims {
claimed: self.taken.load(Ordering::Relaxed).min(self.total),
total: self.total,
}
(self.rows_taken.load(Ordering::Relaxed) as f64 / self.total_rows as f64).min(1.0)
}
}

Expand Down
6 changes: 5 additions & 1 deletion vortex-scan/src/source/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,11 @@ async fn clones_share_the_scan() -> VortexResult<()> {
.map(|clone| clone.try_collect::<Vec<ArrayRef>>()),
)
.await?;
assert_eq!(stream.progress(), Some(1.0));
assert!(
stream
.claims()
.is_some_and(|claims| claims.total > 0 && claims.claimed == claims.total)
);
let mut ctx = VortexSession::empty().create_execution_ctx();
let mut values = Vec::new();
for batch in batches.into_iter().flatten() {
Expand Down
Loading
Loading