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
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
46 changes: 33 additions & 13 deletions vortex-scan/src/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,20 @@ use crate::DataSourceScanRef;
/// Starts a new worker over the shared work of an opened scan.
type NewWorker = dyn Fn() -> BoxStream<'static, VortexResult<ArrayRef>> + Send + Sync;

/// Reads the fraction of an opened scan's work that its clones have taken.
type Progress = dyn Fn() -> f64 + Send + Sync;
/// Reads how many units of an opened scan's work its clones have claimed.
type ReadClaims = dyn Fn() -> Claims + Send + Sync;

/// How many units of an opened scan's work its clones have claimed, out of how many in all.
///
/// A unit is what one clone claims at a time, such as a split of a layout scan. Claims only grow,
/// and `claimed` never exceeds `total`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Claims {
/// The units that clones have claimed so far.
pub claimed: usize,
/// The units of the scan in all.
pub total: usize,
}

/// The arrays of an opened scan, which host threads read by each polling a clone.
///
Expand All @@ -37,7 +49,7 @@ type Progress = dyn Fn() -> f64 + Send + Sync;
pub struct ScanStream {
dtype: DType,
new_worker: Arc<NewWorker>,
progress: Option<Arc<Progress>>,
claims: Option<Arc<ReadClaims>>,
worker: Option<BoxStream<'static, VortexResult<ArrayRef>>>,
}

Expand All @@ -53,22 +65,30 @@ impl ScanStream {
Self {
dtype,
new_worker: Arc::new(new_worker),
progress: None,
claims: None,
worker: None,
}
}

/// This stream, reporting its progress through `progress`, which returns the fraction of the
/// scan's work that its clones have taken, from 0.0 to 1.0, and must never block.
pub fn with_progress(mut self, progress: impl Fn() -> f64 + Send + Sync + 'static) -> Self {
self.progress = Some(Arc::new(progress));
/// This stream, reporting through `claims` how many units of its work its clones have
/// claimed, out of how many in all. `claims` must never block.
pub fn with_claims(mut self, claims: impl Fn() -> Claims + Send + Sync + 'static) -> Self {
self.claims = Some(Arc::new(claims));
self
}

/// The fraction of the scan's work that its clones have taken, from 0.0 to 1.0, for a host's
/// progress bar, or `None` when the scan does not track it. Never blocks.
pub fn progress(&self) -> Option<f64> {
self.progress.as_ref().map(|progress| progress())
/// How many units of the scan's work its clones have claimed, out of how many in all, or
/// `None` when the source does not know its total up front, as for a stream from
/// [`Self::from_partitions`]. Never blocks.
///
/// A host derives its progress from this. It also bounds how many clones a host needs: a
/// host that hands out clones under its own lock may stop once it has handed out `total`
/// clones, or once `claimed` reaches `total`, because the clones already handed out keep
/// claiming units until none is left and so drain the rest. A clone handed out after that
/// would find nothing to claim. When this is `None` the host cannot bound its clones this
/// way, and learns that no work is left only when a clone ends.
pub fn claims(&self) -> Option<Claims> {
self.claims.as_ref().map(|claims| claims())
}

/// A stream whose clones take the partitions of `scan` one at a time.
Expand Down Expand Up @@ -99,7 +119,7 @@ impl Clone for ScanStream {
Self {
dtype: self.dtype.clone(),
new_worker: Arc::clone(&self.new_worker),
progress: self.progress.clone(),
claims: self.claims.clone(),
worker: None,
}
}
Expand Down
Loading