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
92 changes: 85 additions & 7 deletions vortex-file/src/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use vortex_buffer::ByteBuffer;
use vortex_error::VortexResult;
use vortex_io::request::SegmentReader;
use vortex_layout::LayoutReader;
use vortex_layout::layouts::list::List;
use vortex_layout::scan::layout::LayoutReaderDataSource;
use vortex_layout::scan::metrics::ScanUsage;
use vortex_layout::scan::scan_builder::ScanBuilder;
Expand All @@ -29,6 +30,7 @@ use vortex_layout::segments::UsageSegmentSource;
use vortex_scan::DataSourceRef;
use vortex_scan::prepare::ScanCache;
use vortex_scan::prepare::SegmentLocation;
use vortex_scan::source::PlanDataSource;
use vortex_session::VortexSession;
use vortex_utils::aliases::hash_map::HashMap;

Expand Down Expand Up @@ -72,6 +74,29 @@ struct FileScanCache {
plans: ScanCache,
}

/// Whether a layout tree of `dtype` may contain a list layout.
///
/// A list layout only ever holds a [`DType::List`], and the writer only decomposes the lists it
/// reaches through struct fields and list elements. Maps and variants are conservatively assumed
/// to contain one too, since their storage may be laid out as lists.
fn may_contain_list_layout(dtype: &DType) -> bool {
match dtype {
DType::List(..) | DType::Map(..) | DType::Variant(_) => true,
DType::Null
| DType::Bool(_)
| DType::Primitive(..)
| DType::Decimal(..)
| DType::Utf8(_)
| DType::Binary(_) => false,
DType::FixedSizeList(element, ..) => may_contain_list_layout(element),
DType::Struct(fields, _) => fields.fields().any(|field| may_contain_list_layout(&field)),
DType::Union(variants, _) => variants
.variants()
.any(|variant| may_contain_list_layout(&variant)),
DType::Extension(ext) => may_contain_list_layout(ext.storage_dtype()),
}
}

fn layout_reader(
segment_source: Arc<dyn SegmentSource>,
footer: &Footer,
Expand Down Expand Up @@ -124,9 +149,10 @@ impl VortexFile {

/// Enable layout reader and V2 scan caching.
///
/// Repeated calls to [`layout_reader`](Self::layout_reader), [`scan`](Self::scan), and
/// [`data_source`](Self::data_source) will share the same reader tree. Repeated V2 scans of
/// [`scan_file`](Self::scan_file) will share its segment locations and a [`ScanCache`].
/// Repeated calls to [`layout_reader`](Self::layout_reader) and [`scan`](Self::scan), and to
/// [`data_source`](Self::data_source) for a file it scans with the layout reader, will share the
/// same reader tree. Repeated V2 scans of [`scan_file`](Self::scan_file), and so of the plan
/// data sources, will share its segment locations and a [`ScanCache`].
pub fn with_caching(self) -> Self {
let scan_cache = FileScanCache {
locations: self.footer.segment_locations(),
Expand Down Expand Up @@ -257,18 +283,70 @@ impl VortexFile {

/// Create a [`DataSource`](vortex_scan::DataSource) from this file for scanning.
///
/// Wraps the file's layout reader with [`FileStatsLayoutReader`] (when file-level
/// statistics are available) and [`LayoutReaderDataSource`]. Stored footer aggregates are
/// available through the source statistics methods without reading payloads.
/// Scans run on the planner-driven executor, as with
/// [`plan_data_source`](Self::plan_data_source), unless the file has a layout that
/// executor cannot read yet. Such files are scanned on the layout reader instead, as with
/// [`layout_reader_data_source`](Self::layout_reader_data_source). Either way, a scan whose
/// filter the file-level statistics prove false reads nothing, and stored footer aggregates
/// are available through the source statistics methods without reading payloads.
pub fn data_source(&self) -> VortexResult<DataSourceRef> {
let reader = self.layout_reader()?;
if self.planned_scan_supported()? {
return Ok(self.plan_data_source());
}
self.layout_reader_data_source()
}

/// Create a [`DataSource`](vortex_scan::DataSource) that scans this file with its
/// [layout reader](Self::layout_reader), whatever its layouts.
///
/// Use [`data_source`](Self::data_source) unless the layout reader is required, for example
/// to compare it with [`plan_data_source`](Self::plan_data_source). Stored footer aggregates
/// are available through the source statistics methods without reading payloads.
pub fn layout_reader_data_source(&self) -> VortexResult<DataSourceRef> {
let reader = self.layout_reader()?;
Ok(Arc::new(FileDataSource::new(
LayoutReaderDataSource::new(reader, self.session.clone()),
self.file_stats().cloned(),
)))
}

/// Whether the planner-driven executor can scan this file, which
/// [`data_source`](Self::data_source) uses to choose its executor.
///
/// The planner-driven executor cannot read list layouts yet (tracked with making it the
/// default in #11502), so files that contain one are scanned by the layout reader instead. The
/// layout tree is only walked when the file's dtype could hold a list layout.
pub(crate) fn planned_scan_supported(&self) -> VortexResult<bool> {
if !may_contain_list_layout(self.dtype()) {
return Ok(true);
}
for layout in self.footer.layout().depth_first_traversal() {
if layout?.is::<List>() {
return Ok(false);
}
}
Ok(true)
}

/// Create a [`DataSource`](vortex_scan::DataSource) from this file whose scans run on the
/// planner-driven executor.
///
/// A scan has one partition covering the requested rows, which runs it with
/// [`ScanDriver`](crate::v2::ScanDriver) from
/// [`Partition::execute`](vortex_scan::Partition::execute). Every scan of the source shares
/// one [`ScanCache`]: the file's, with [caching](Self::with_caching), or else one of its own.
/// A scan whose filter the file-level statistics prove false has no partitions. Stored footer
/// aggregates are available through the source statistics methods. Opening the source reads
/// nothing and builds no layout reader.
pub fn plan_data_source(&self) -> DataSourceRef {
let source = PlanDataSource::new(self.session.clone(), self.scan_file().into())
.with_row_count(self.row_count());
Arc::new(
FileDataSource::new(source, self.file_stats().cloned())
.with_file_pruning(self.row_count(), self.session.clone()),
)
}

/// Initiate a scan of the file, returning a builder for projection, filtering, selection, and
/// execution options.
pub fn scan(&self) -> VortexResult<ScanBuilder<ArrayRef>> {
Expand Down
87 changes: 79 additions & 8 deletions vortex-file/src/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,79 @@
// SPDX-FileCopyrightText: Copyright the Vortex contributors

use async_trait::async_trait;
use futures::StreamExt;
use futures::stream;
use vortex_array::aggregate_fn::AggregateFnRef;
use vortex_array::dtype::DType;
use vortex_array::dtype::FieldPath;
use vortex_array::expr::Expression;
use vortex_array::expr::stats::Precision;
use vortex_array::scalar::Scalar;
use vortex_array::stats::StatsSet;
use vortex_error::VortexResult;
use vortex_layout::scan::layout::LayoutReaderDataSource;
use vortex_scan::DataSource;
use vortex_scan::DataSourceScan;
use vortex_scan::DataSourceScanRef;
use vortex_scan::PartitionRef;
use vortex_scan::PartitionStream;
use vortex_scan::ScanRequest;
use vortex_session::VortexSession;

use crate::FileStatistics;
use crate::pruning::is_falsified_by_file_stats;

pub(crate) struct FileDataSource {
source: LayoutReaderDataSource,
/// A file's scans with the statistics of its footer.
pub(crate) struct FileDataSource<S> {
source: S,
statistics: Option<FileStatistics>,
/// Set when the inner source does not prune with the file's statistics itself.
pruning: Option<FilePruning>,
}

impl FileDataSource {
pub(crate) fn new(source: LayoutReaderDataSource, statistics: Option<FileStatistics>) -> Self {
Self { source, statistics }
/// What [`FileDataSource`] needs to prove a scan's filter false over the whole file.
struct FilePruning {
row_count: u64,
session: VortexSession,
}

impl<S: DataSource> FileDataSource<S> {
pub(crate) fn new(source: S, statistics: Option<FileStatistics>) -> Self {
Self {
source,
statistics,
pruning: None,
}
}

/// Skip scans whose filter the file's statistics prove false over all `row_count` rows of
/// the file, before the inner source reads anything.
pub(crate) fn with_file_pruning(mut self, row_count: u64, session: VortexSession) -> Self {
self.pruning = Some(FilePruning { row_count, session });
self
}

/// Whether the file's statistics prove `filter` false for every row of the file, and so for
/// every row range of it.
///
/// A filter that does not bind is not pruned: the inner scan reports the error.
fn is_pruned(&self, filter: Option<&Expression>) -> VortexResult<bool> {
let (Some(pruning), Some(statistics), Some(filter)) =
(&self.pruning, &self.statistics, filter)
else {
return Ok(false);
};
let Ok(filter) = filter
.bind(self.source.dtype())
.and_then(|filter| filter.optimize_recursive())
else {
return Ok(false);
};
is_falsified_by_file_stats(&filter, pruning.row_count, statistics, &pruning.session)
}
}

#[async_trait]
impl DataSource for FileDataSource {
impl<S: DataSource> DataSource for FileDataSource<S> {
fn dtype(&self) -> &DType {
self.source.dtype()
}
Expand All @@ -52,7 +96,15 @@ impl DataSource for FileDataSource {
}

async fn scan(&self, request: ScanRequest) -> VortexResult<DataSourceScanRef> {
self.source.scan(request).await
let filter = request.filter.clone();
let scan = self.source.scan(request).await?;
Ok(if self.is_pruned(filter.as_ref())? {
Box::new(PrunedScan {
dtype: scan.dtype().clone(),
})
} else {
scan
})
}

async fn field_statistics(&self, field_path: &FieldPath) -> VortexResult<StatsSet> {
Expand Down Expand Up @@ -84,3 +136,22 @@ impl DataSource for FileDataSource {
.map_or(Precision::Absent, Precision::Exact))
}
}

/// A scan of a file whose statistics rule out every row: it has no partitions.
struct PrunedScan {
dtype: DType,
}

impl DataSourceScan for PrunedScan {
fn dtype(&self) -> &DType {
&self.dtype
}

fn partition_count(&self) -> Precision<usize> {
Precision::exact(0usize)
}

fn partitions(self: Box<Self>) -> PartitionStream {
stream::empty().boxed()
}
}
Loading