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
155 changes: 111 additions & 44 deletions vortex-duckdb/src/file_reader.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

use std::num::NonZeroUsize;
use std::ops::Range;
use std::sync::Arc;
use std::sync::OnceLock;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;

use futures::FutureExt;
use futures::StreamExt;
use object_store::registry::ObjectStoreRegistry;
use url::Url;
use vortex::array::ArrayRef;
Expand All @@ -31,10 +34,15 @@ use vortex::io::object_store::ObjectStoreFileSystem;
use vortex::io::runtime::BlockingRuntime as _;
use vortex::io::std_file::StdFileSystem;
use vortex::layout::LayoutReaderRef;
use vortex::layout::scan::layout::LayoutReaderDataSource;
use vortex::layout::scan::scan_builder::ScanBuilder;
use vortex::layout::scan::v2::ScanBuilder as V2ScanBuilder;
use vortex::layout::scan::v2::ScanFile;
use vortex::mask::Mask;
use vortex::scan::DataSource as _;
use vortex::scan::ScanRequest;
use vortex::scan::stream::Claims;
use vortex::scan::stream::ScanExec;
use vortex::session::SessionExt as _;

use crate::REGISTRY;
Expand Down Expand Up @@ -111,17 +119,14 @@ fn resolve_filesystem(url: &Url) -> VortexResult<(FileSystemRef, String)> {
}

pub struct OpenFileReader {
/// The layout reader and conversion cache of the file. `None` after the file is skipped or
/// all its splits are taken.
/// The layout reader, scan and conversion cache of the file. `None` after the file is skipped
/// or no thread can join it any more.
///
/// DuckDB releases its last reference to a file while it holds the global lock of the
/// multi-file scan, and dropping this state takes long. So every local state that scans the
/// file holds a reference too, and the file gives its own reference to a local state before
/// DuckDB releases the file. The last local state drops the state outside the lock.
scan_state: Option<Arc<FileScanState>>,
/// File splits stored in inverse order
pub splits: Vec<Split>,
total_splits: usize,
}

/// The state of an open file that the threads scanning it share.
Expand All @@ -132,9 +137,27 @@ pub struct FileScanState {
/// The file's V2 scan, which every thread scanning the file drives. Set when the file is
/// initialized for a V2 scan.
v2: OnceLock<FileScan>,
/// The opened V1 scan of the file, which each thread scanning the file reads a stream of. Set
/// when the file is initialized for a V1 scan.
exec: OnceLock<ScanExec>,
cache: ConversionCache,
}

impl FileScanState {
/// The scan work a thread joining the file would take, or `None` once the file has none.
fn next_split(&self) -> Option<Split> {
if let Some(scan) = self.v2.get() {
return (!scan.is_exhausted()).then_some(Split::V2);
}
// A thread joins the file until its last split is claimed, then moves on to the next file
// while the threads holding the last splits finish them: no thread waits for the rest of
// a file to drain. The thread creates its stream on its first scan call, outside DuckDB's
// lock.
let exec = self.exec.get()?;
(!exec.is_exhausted()).then_some(Split::V1(None))
}
}

impl OpenFileReader {
async fn open(path: String) -> VortexResult<Self> {
let (fs, fs_path) = resolve_filesystem(&parse_uri_or_path(&path)?)?;
Expand All @@ -147,10 +170,9 @@ impl OpenFileReader {
reader: file.layout_reader()?,
scan_file,
v2: OnceLock::new(),
exec: OnceLock::new(),
cache: ConversionCache::default(),
})),
splits: vec![],
total_splits: 0,
})
}

Expand Down Expand Up @@ -219,7 +241,7 @@ pub fn reader_initialize(file: &mut OpenFileReader, global: &GlobalState) -> Vor
return Ok(true);
}

// Getting splits, or planning a V2 scan, is non-trivial work so we prefer
// Opening the file's scan, or planning a V2 scan, is non-trivial work so we prefer
// doing it here under file lock and not in reader_try_initialize_scan under
// global lock.
if global.scan_v2 {
Expand All @@ -240,33 +262,44 @@ pub fn reader_initialize(file: &mut OpenFileReader, global: &GlobalState) -> Vor
return Ok(false);
}

let reader = Arc::clone(file.reader());
let state = file.scan_state();
let filter = &global.filter;
let builder = ScanBuilder::new(SESSION.clone(), reader)
.with_projection(global.projection.clone())
.with_some_filter(filter.filter.clone())
.with_selection(filter.row_selection.clone());
let scan = builder.prepare()?;
let mut splits: Vec<Split> = scan
.execute(filter.row_range.clone())?
.into_iter()
.map(Split::V1)
.collect();

// threads take last element of file.splits so we need to reverse
splits.reverse();
file.total_splits = splits.len();
file.splits = splits;
let request = ScanRequest {
projection: global.projection_expr.clone(),
filter: filter.expr.clone(),
row_range: Some(file_rows(state, filter)),
selection: filter.row_selection.clone(),
ordered: false,
// DuckDB runs one thread per core, so its threads are the scan's parallelism: each runs
// one split at a time, polling it itself. A clone with room for more would claim splits
// other threads could have run, leaving them nothing on a file with few splits.
split_concurrency: Some(NonZeroUsize::MIN),
..ScanRequest::default()
};
// An unordered scan without a limit opens onto a queue of the file's splits, whose streams
// each claim the next split once they have finished their last.
let source = LayoutReaderDataSource::new(Arc::clone(&state.reader), SESSION.clone());
let exec = RUNTIME.block_on(source.scan(request))?.open()?;
if state.exec.set(exec).is_err() {
vortex_panic!("file initialized twice");
}
Ok(false)
}

/// The rows of the file that the scan's row range keeps. A `file_row_number` filter can bound
/// the range past the end of the file, up to `u64::MAX`.
fn file_rows(state: &FileScanState, filter: &Filter) -> Range<u64> {
let row_count = state.reader.row_count();
filter.row_range.as_ref().map_or(0..row_count, |range| {
let end = range.end.min(row_count);
range.start.min(end)..end
})
}

/// The V2 scan of the file's rows that the scan's row range and selection keep.
fn v2_builder(state: &FileScanState, global: &GlobalState) -> V2ScanBuilder {
let filter = &global.filter;
let row_count = state.reader.row_count();
let rows = filter.row_range.as_ref().map_or(0..row_count, |range| {
range.start.min(row_count)..range.end.min(row_count)
});
let rows = file_rows(state, filter);
V2ScanBuilder::new(SESSION.clone(), state.scan_file.clone())
.with_projection(global.projection.clone())
.with_some_filter(filter.filter.clone())
Expand All @@ -287,9 +320,31 @@ enum SplitItem {
fn next_split_item(local: &mut LocalState) -> VortexResult<SplitItem> {
match local.split.take() {
None => Ok(SplitItem::Done),
Some(Split::V1(task)) => Ok(RUNTIME
.block_on(task)?
.map_or(SplitItem::Empty, SplitItem::Array)),
Some(Split::V1(stream)) => {
let mut stream = match stream {
Some(stream) => stream,
None => local
.file
.as_ref()
.vortex_expect("split without a file")
.exec
.get()
.vortex_expect("V1 split of a file without a V1 scan")
.stream(),
};
let Some(array) = RUNTIME.block_on(stream.next()).transpose()? else {
// Dropping the last stream drops the file's split queue; do that outside DuckDB's
// locks.
local.retired_splits.push(Split::V1(Some(stream)));
return Ok(SplitItem::Done);
};
local.split = Some(Split::V1(Some(stream)));
Ok(if array.is_empty() {
SplitItem::Empty
} else {
SplitItem::Array(array)
})
}
Some(Split::V2) => {
let file = local.file.as_ref().vortex_expect("split without a file");
let scan = file
Expand Down Expand Up @@ -333,14 +388,14 @@ fn next_split_item(local: &mut LocalState) -> VortexResult<SplitItem> {
/// the global lock. It only moves references between the file and the local
/// state, and reader_scan drops the retired ones.
pub fn reader_try_initialize_scan(file: &mut OpenFileReader, local: &mut LocalState) -> bool {
// A V2 scan's threads take chunks from the file's scan until it has spawned
// them all, so the file has work for another thread until then.
let v2 = file
// A thread joins a file while its V2 scan has chunks left to spawn or its V1
// scan has a split left to claim. Either check is one load of a flag that is
// written once, so it is cheap under the global lock.
let split = file
.scan_state
.as_ref()
.and_then(|state| state.v2.get())
.map(|scan| (!scan.is_exhausted()).then_some(Split::V2));
let Some(split) = v2.unwrap_or_else(|| file.splits.pop()) else {
.and_then(|state| state.next_split());
let Some(split) = split else {
// DuckDB releases the file after this call, under the global lock.
// Give the reference of the file to this thread so it drops outside.
local.retired_files.extend(file.scan_state.take());
Expand All @@ -360,7 +415,7 @@ pub fn reader_try_initialize_scan(file: &mut OpenFileReader, local: &mut LocalSt
local.retired_files.extend(previous);
}

local.split = Some(split);
local.retired_splits.extend(local.split.replace(split));
true
}

Expand All @@ -372,7 +427,8 @@ pub fn reader_scan(
local: &mut LocalState,
chunk: &mut DataChunkRef,
) -> VortexResult<bool> {
// No lock is held here, so drop the scan states of files this thread left.
// No lock is held here, so drop the splits and scan states this thread left.
local.retired_splits.clear();
local.retired_files.clear();

if !global.aggregates.is_empty() {
Expand Down Expand Up @@ -453,13 +509,24 @@ pub fn reader_get_statistics(
/// Called from a separate thread (not related to threads for Vortex
/// table function) under global lock.
pub fn reader_get_progress_in_file(file: &OpenFileReader) -> f64 {
if let Some(scan) = file.scan_state.as_ref().and_then(|state| state.v2.get()) {
// A file without a scan state was skipped or has every split taken.
let Some(state) = file.scan_state.as_ref() else {
return 100.0;
};
if let Some(scan) = state.v2.get() {
return scan.progress();
}
let total = file.total_splits;
let left = file.splits.len();
let denom = total + (total == 0) as usize;
100.0 * (total - left) as f64 / denom as f64
state
.exec
.get()
.and_then(ScanExec::progress)
.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
7 changes: 6 additions & 1 deletion vortex-duckdb/src/projection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,8 @@ impl Projection {

pub struct Filter {
pub filter: Option<BoundExpression>,
/// `filter` before binding, for scans that bind it against each file.
pub expr: Option<Expression>,
pub row_selection: Selection,
pub row_range: Option<Range<u64>>,
pub has_non_optional_filter: bool,
Expand Down Expand Up @@ -257,12 +259,15 @@ impl Filter {
}
};

let filter = and_collect(table_filter_exprs)
let expr = and_collect(table_filter_exprs);
let filter = expr
.as_ref()
.map(|expr| expr.bind(dtype)?.optimize_recursive())
.transpose()?;

let out = Self {
filter,
expr,
row_selection,
row_range,
has_non_optional_filter,
Expand Down
20 changes: 14 additions & 6 deletions vortex-duckdb/src/table_function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ use std::sync::atomic::Ordering;

#[cfg(unix)]
use custom_labels::CURRENT_LABELSET;
use futures::future::BoxFuture;
use itertools::Itertools;
use num_traits::AsPrimitive;
use parking_lot::Mutex;
Expand Down Expand Up @@ -43,6 +42,7 @@ use vortex::metrics::tracing::get_global_labels;
use vortex::proto::expr as expr_pb;
use vortex::scalar::Scalar;
use vortex::scan::planning::driver::Run;
use vortex::scan::stream::ScanStream;
use vortex_utils::aliases::hash_map::HashMap;

use crate::SESSION;
Expand Down Expand Up @@ -183,6 +183,8 @@ impl<'a> TableInitInput<'a> {

pub struct GlobalState {
pub projection: BoundExpression,
/// The projection before binding, for scans that bind it against each file.
pub projection_expr: Expression,
pub filter: Filter,
pub file_row_number_column_pos: Option<usize>,
/// Whether the scan runs on the planner-driven V2 executor.
Expand All @@ -203,10 +205,12 @@ pub struct AggregateState {
}
assert_impl_all!(GlobalState: Send, Sync);

/// A unit of scan work that one thread takes at a time.
/// The scan work that one thread does on a file.
pub enum Split {
/// A V1 scan task yielding one array, or `None` if the filter removed every row.
V1(BoxFuture<'static, VortexResult<Option<ArrayRef>>>),
/// A stream of the file's V1 scan, which the thread polls inline. It claims the file's splits
/// as it has room for them until none is left, and yields only the splits it claimed. `None`
/// until the thread's first scan call creates it, outside DuckDB's lock.
V1(Option<ScanStream>),
/// Chunks of the file's V2 scan, taken by the thread until the scan has none left.
V2,
}
Expand All @@ -220,12 +224,13 @@ pub struct LocalState {
pub split: Option<Split>,
/// The scan state of the file that this thread scans.
pub(crate) file: Option<Arc<FileScanState>>,
/// Scan states that this thread no longer uses. They are dropped outside
/// Scan states and splits that this thread no longer uses. They are dropped outside
/// DuckDB's global multi-file lock; see `OpenFileReader`.
pub(crate) retired_files: Vec<Arc<FileScanState>>,
pub(crate) retired_splits: Vec<Split>,
/// The planning run on which this thread runs the chunks of V2 scans.
pub(crate) run: Run,
/// Chunks of a V2 batch that this thread has yet to export, in reverse order.
/// Chunks of an array that this thread has yet to export, in reverse order.
pub(crate) pending: Vec<ArrayRef>,

/// Empty for non-aggregate scan
Expand Down Expand Up @@ -352,9 +357,11 @@ pub fn init_global(init_input: &TableInitInput) -> VortexResult<GlobalState> {
"table function scan input"
);

let projection_expr = projection.clone();
let projection = optimize_and_bind(projection, &bind_data.dtype)?;
Ok(GlobalState {
projection,
projection_expr,
filter,
aggregates: bind_data.aggregates.clone(),
has_count_star,
Expand Down Expand Up @@ -430,6 +437,7 @@ pub fn init_local(bind_data: &BindState, global: &GlobalState) -> LocalState {
split: None,
file: None,
retired_files: Vec::new(),
retired_splits: Vec::new(),
run: Run::new(),
pending: Vec::new(),
finished: false,
Expand Down
Loading