Skip to content
Closed
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
114 changes: 74 additions & 40 deletions vortex-duckdb/src/file_reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;

use futures::FutureExt;
use futures::StreamExt as _;
use futures::TryStreamExt as _;
use object_store::registry::ObjectStoreRegistry;
use url::Url;
use vortex::array::ArrayRef;
Expand All @@ -20,6 +22,7 @@ use vortex::error::VortexExpect;
use vortex::error::VortexResult;
use vortex::error::vortex_err;
use vortex::error::vortex_panic;
use vortex::expr::stats::Precision;
use vortex::file::Footer;
use vortex::file::multi::MultiFileSession;
use vortex::file::multi::open_cached;
Expand All @@ -31,10 +34,12 @@ 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::session::SessionExt as _;

use crate::REGISTRY;
Expand Down Expand Up @@ -209,49 +214,38 @@ pub fn reader_bind(file: &OpenFileReader, result: &mut BindResultRef) -> VortexR
}

/// Called once per file by one thread under file-local lock. Determines
/// whether the opened file should be skipped. If this function returns false,
/// whether the opened file should be skipped. If this function returns true,
/// duckdb closes the file and doesn't call reader_try_initialize_scan on it.
///
/// Planning the file's scan is non-trivial work so we prefer doing it here
/// under file lock and not in reader_try_initialize_scan under global lock.
pub fn reader_initialize(file: &mut OpenFileReader, global: &GlobalState) -> VortexResult<bool> {
if file.can_skip(&global.filter)? {
// DuckDB releases a skipped file under the global lock. Here only the
// file-local lock is held, so drop the scan state now.
file.scan_state = None;
return Ok(true);
}

// Getting splits, 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 {
let state = file.scan_state();
let splits = ScanBuilder::new(SESSION.clone(), Arc::clone(&state.reader))
.with_projection(global.projection.clone())
.with_some_filter(global.filter.filter.clone())
.full_file_splits()?;
let dynamic = global
.filter
.filter
.as_ref()
.is_some_and(|filter| DynamicExprUpdates::new(filter).is_some());
let scan = FileScan::try_new(v2_builder(state, global), &splits, dynamic)?;
if state.v2.set(scan).is_err() {
vortex_panic!("file initialized twice");
}
return Ok(false);
initialize_v2(file, global)
} else {
initialize_v1(file, global)
}
}

let reader = Arc::clone(file.reader());
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())?
/// Plans the file's V1 scan through the Scan API. Each partition is one
/// layout split, which a thread claims whole.
fn initialize_v1(file: &mut OpenFileReader, global: &GlobalState) -> VortexResult<bool> {
let source = LayoutReaderDataSource::new(Arc::clone(file.reader()), SESSION.clone())
.with_layout_split_partitions();
let partitions = RUNTIME.block_on(async {
let scan = source.scan(global.scan_request.clone()).await?;
scan.partitions().try_collect::<Vec<_>>().await
})?;
let mut splits = partitions
.into_iter()
.map(Split::V1)
.collect();
.filter(|partition| !matches!(partition.row_count(), Precision::Exact(0)))
.map(|partition| partition.execute().map(Split::V1))
.collect::<VortexResult<Vec<_>>>()?;

if splits.is_empty() {
skip_file(file);
return Ok(true);
}

// threads take last element of file.splits so we need to reverse
splits.reverse();
Expand All @@ -260,6 +254,37 @@ pub fn reader_initialize(file: &mut OpenFileReader, global: &GlobalState) -> Vor
Ok(false)
}

fn initialize_v2(file: &mut OpenFileReader, global: &GlobalState) -> VortexResult<bool> {
if file.can_skip(&global.filter)? {
skip_file(file);
return Ok(true);
}

let state = file.scan_state();
let splits = ScanBuilder::new(SESSION.clone(), Arc::clone(&state.reader))
.with_projection(global.projection.clone())
.with_some_filter(global.filter.filter.clone())
.full_file_splits()?;
let dynamic = global
.filter
.filter
.as_ref()
.is_some_and(|filter| DynamicExprUpdates::new(filter).is_some());
let scan = FileScan::try_new(v2_builder(state, global), &splits, dynamic)?;
if state.v2.set(scan).is_err() {
vortex_panic!("file initialized twice");
}
Ok(false)
}

/// Releases the scan state of a file that DuckDB will skip.
///
/// DuckDB releases a skipped file under the global lock. Here only the
/// file-local lock is held, so drop the scan state now.
fn skip_file(file: &mut OpenFileReader) {
file.scan_state = None;
}

/// 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;
Expand Down Expand Up @@ -287,9 +312,18 @@ 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(mut stream)) => {
let Some(array) = RUNTIME.block_on(stream.next()) else {
return Ok(SplitItem::Done);
};
let array = array?;
local.split = Some(Split::V1(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
8 changes: 7 additions & 1 deletion vortex-duckdb/src/projection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,9 @@ impl Projection {
}

pub struct Filter {
/// The conjunction of the pushed-down filters, as the Scan API takes it.
pub expression: Option<Expression>,
/// `expression` bound to the scan's dtype.
pub filter: Option<BoundExpression>,
pub row_selection: Selection,
pub row_range: Option<Range<u64>>,
Expand Down Expand Up @@ -257,11 +260,14 @@ impl Filter {
}
};

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

let out = Self {
expression,
filter,
row_selection,
row_range,
Expand Down
17 changes: 14 additions & 3 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 All @@ -24,6 +23,7 @@ use vortex::array::Canonical;
use vortex::array::ExecutionCtx;
use vortex::array::arrays::Struct;
use vortex::array::arrays::StructArray;
use vortex::array::stream::SendableArrayStream;
use vortex::dtype::DType;
use vortex::dtype::Nullability;
use vortex::dtype::PType;
Expand All @@ -42,6 +42,7 @@ use vortex::expr::proto::ExprSerializeProtoExt;
use vortex::metrics::tracing::get_global_labels;
use vortex::proto::expr as expr_pb;
use vortex::scalar::Scalar;
use vortex::scan::ScanRequest;
use vortex::scan::planning::driver::Run;
use vortex_utils::aliases::hash_map::HashMap;

Expand Down Expand Up @@ -182,6 +183,8 @@ impl<'a> TableInitInput<'a> {
}

pub struct GlobalState {
/// The request the V1 scan sends to each file's Scan API source.
pub scan_request: ScanRequest,
pub projection: BoundExpression,
pub filter: Filter,
pub file_row_number_column_pos: Option<usize>,
Expand All @@ -205,8 +208,8 @@ assert_impl_all!(GlobalState: Send, Sync);

/// A unit of scan work that one thread takes at a time.
pub enum Split {
/// A V1 scan task yielding one array, or `None` if the filter removed every row.
V1(BoxFuture<'static, VortexResult<Option<ArrayRef>>>),
/// The stream of a Scan API partition of the file: one layout split of a V1 scan.
V1(SendableArrayStream),
/// Chunks of the file's V2 scan, taken by the thread until the scan has none left.
V2,
}
Expand Down Expand Up @@ -352,8 +355,16 @@ pub fn init_global(init_input: &TableInitInput) -> VortexResult<GlobalState> {
"table function scan input"
);

let scan_request = ScanRequest {
projection: projection.clone(),
filter: filter.expression.clone(),
row_range: filter.row_range.clone(),
selection: filter.row_selection.clone(),
..ScanRequest::default()
};
let projection = optimize_and_bind(projection, &bind_data.dtype)?;
Ok(GlobalState {
scan_request,
projection,
filter,
aggregates: bind_data.aggregates.clone(),
Expand Down
Loading