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
74 changes: 69 additions & 5 deletions vortex-file/src/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ use vortex_layout::segments::UsageSegmentSource;
use vortex_scan::DataSourceRef;
use vortex_scan::prepare::ScanCache;
use vortex_scan::prepare::SegmentLocation;
use vortex_scan::source::PlanChild;
use vortex_scan::source::PlanDataSource;
use vortex_session::VortexSession;
use vortex_utils::aliases::hash_map::HashMap;

Expand Down Expand Up @@ -68,6 +70,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.
pub(crate) 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 @@ -116,7 +141,8 @@ impl VortexFile {
///
/// 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`].
/// [`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 @@ -245,18 +271,56 @@ 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 file's [layout reader](Self::layout_reader), as with
/// [`layout_reader_data_source`](Self::layout_reader_data_source). 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()?;
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(),
)))
}

/// Create a [`DataSource`](vortex_scan::DataSource) from this file whose scans run on the
/// planner-driven executor.
///
/// The source is a [`PlanDataSource`] over [`plan_file`](Self::plan_child): hosts read its
/// scans through native `split` and `open`, or through 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 reads nothing. 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::from_child(self.session.clone(), self.plan_child());
Arc::new(FileDataSource::new(source, self.file_stats().cloned()))
}

/// This file as a child of a [`PlanDataSource`]: its V2 scan input, row count, and a pruner
/// that skips scans whose filter the file-level statistics prove false.
pub fn plan_child(&self) -> PlanChild {
let file = PlanChild::new(self.scan_file().into()).with_row_count(self.row_count());
let Some(statistics) = self.file_stats().cloned() else {
return file;
};
let (row_count, session) = (self.row_count(), self.session.clone());
file.with_pruner(Arc::new(move |filter| {
is_falsified_by_file_stats(filter, row_count, &statistics, &session)
}))
}

/// 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
128 changes: 102 additions & 26 deletions vortex-file/src/multi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,19 @@ use vortex_layout::LayoutReaderRef;
use vortex_layout::scan::multi::LayoutReaderFactory;
use vortex_layout::scan::multi::MultiLayoutDataSource;
use vortex_scan::DataSource;
use vortex_scan::DataSourceRef;
use vortex_scan::source::DeferredPlanChild;
use vortex_scan::source::PlanDataSource;
use vortex_scan::source::PlanSourceChild;
use vortex_session::VortexSession;

use crate::OpenOptionsSessionExt;
use crate::VortexFile;
use crate::VortexOpenOptions;
use crate::file::may_contain_list_layout;

/// Adjusts the options each file of a [`MultiFileDataSource`] is opened with.
type OpenOptionsFn = Arc<dyn Fn(VortexOpenOptions) -> VortexOpenOptions + Send + Sync>;

/// A builder that discovers multiple Vortex files from glob patterns and constructs a
/// [`MultiLayoutDataSource`] to scan them as a single data source.
Expand Down Expand Up @@ -122,6 +130,52 @@ impl MultiFileDataSource {
/// Discovers files via glob, opens the first file eagerly to determine the schema,
/// and creates lazy factories for the remaining files.
pub async fn build(self) -> VortexResult<MultiLayoutDataSource> {
let session = self.session.clone();
let open_options_fn = Arc::clone(&self.open_options_fn);
let (first_file, all_files) = self.discover().await?;
layout_source(&session, &open_options_fn, &first_file, &all_files)
}

/// Build a [`DataSource`] whose scans run on the planner-driven executor.
///
/// Discovers files as [`build`](Self::build) does and opens the first file for the schema.
/// The source is a [`PlanDataSource`] whose remaining files are opened when a scan reaches
/// them, as units of the scan's work. The planner-driven executor cannot read list layouts
/// yet, so when the schema could hold one, this returns [`build`](Self::build)'s layout
/// reader source instead.
pub async fn build_plan(self) -> VortexResult<DataSourceRef> {
let session = self.session.clone();
let open_options_fn = Arc::clone(&self.open_options_fn);
let (first_file, all_files) = self.discover().await?;
if may_contain_list_layout(first_file.dtype()) {
return Ok(Arc::new(layout_source(
&session,
&open_options_fn,
&first_file,
&all_files,
)?));
}
let mut files = vec![PlanSourceChild::Ready(first_file.plan_child())];
files.extend(
all_files[1..]
.iter()
.map(|(file, fs)| PlanSourceChild::Deferred {
child: Arc::new(DeferredVortexFile {
fs: Arc::clone(fs),
file: file.clone(),
session: session.clone(),
open_options_fn: Arc::clone(&open_options_fn),
}),
byte_size: file.size,
}),
);
let source = PlanDataSource::from_children(session, first_file.dtype().clone(), files);
debug!(file_count = all_files.len(), dtype = %source.dtype(), "built a plan MultiFileDataSource");
Ok(Arc::new(source))
}

/// Discovers the files of the globs, in order, and opens the first.
async fn discover(self) -> VortexResult<(VortexFile, Vec<(FileListing, FileSystemRef)>)> {
if self.glob_sources.is_empty() {
vortex_bail!("MultiFileDataSource requires at least one glob pattern");
}
Expand Down Expand Up @@ -173,35 +227,35 @@ impl MultiFileDataSource {
let (first_file_listing, first_fs) = &all_files[0];
let open_fn = self.open_options_fn.as_ref();
let first_file = open_file(first_fs, first_file_listing, &self.session, open_fn).await?;
let first_reader = first_file.layout_reader()?;

let byte_sizes: Vec<Option<u64>> = all_files.iter().map(|(file, _)| file.size).collect();

let factories: Vec<Arc<dyn LayoutReaderFactory>> = all_files[1..]
.iter()
.map(|(file, fs)| {
Arc::new(VortexFileReaderFactory {
fs: Arc::clone(fs),
file: file.clone(),
session: self.session.clone(),
open_options_fn: Arc::clone(&self.open_options_fn),
}) as Arc<dyn LayoutReaderFactory>
})
.collect();

let inner = MultiLayoutDataSource::new_with_first(
first_reader,
factories,
byte_sizes,
&self.session,
);

debug!(file_count, dtype = %inner.dtype(), "built MultiFileDataSource");

Ok(inner)
Ok((first_file, all_files))
}
}

/// The layout reader source over `all_files`, whose first is open as `first_file`.
fn layout_source(
session: &VortexSession,
open_options_fn: &OpenOptionsFn,
first_file: &VortexFile,
all_files: &[(FileListing, FileSystemRef)],
) -> VortexResult<MultiLayoutDataSource> {
let first_reader = first_file.layout_reader()?;
let byte_sizes: Vec<Option<u64>> = all_files.iter().map(|(file, _)| file.size).collect();
let factories: Vec<Arc<dyn LayoutReaderFactory>> = all_files[1..]
.iter()
.map(|(file, fs)| {
Arc::new(VortexFileReaderFactory {
fs: Arc::clone(fs),
file: file.clone(),
session: session.clone(),
open_options_fn: Arc::clone(open_options_fn),
}) as Arc<dyn LayoutReaderFactory>
})
.collect();
let inner = MultiLayoutDataSource::new_with_first(first_reader, factories, byte_sizes, session);
debug!(file_count = all_files.len(), dtype = %inner.dtype(), "built MultiFileDataSource");
Ok(inner)
}

/// Creates a local filesystem backed by `object_store::local::LocalFileSystem`.
// TODO(ngates): create a native file system without an object_store dependency.
// Turns out it's not a trivial change because we have always used object_store with its own
Expand Down Expand Up @@ -297,6 +351,28 @@ impl LayoutReaderFactory for VortexFileReaderFactory {
}
}

/// A [`DeferredPlanChild`] that opens a single Vortex file when a scan reaches it.
struct DeferredVortexFile {
fs: FileSystemRef,
file: FileListing,
session: VortexSession,
open_options_fn: OpenOptionsFn,
}

#[async_trait]
impl DeferredPlanChild for DeferredVortexFile {
async fn expand(&self) -> VortexResult<Vec<PlanSourceChild>> {
let file = open_file(
&self.fs,
&self.file,
&self.session,
self.open_options_fn.as_ref(),
)
.await?;
Ok(vec![PlanSourceChild::Ready(file.plan_child())])
}
}

#[cfg(test)]
mod tests {
use std::fmt;
Expand Down
12 changes: 6 additions & 6 deletions vortex-file/src/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ 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::DataSourceScanRef;
use vortex_scan::PartitionRef;
Expand All @@ -18,19 +17,20 @@ use vortex_session::VortexSession;

use crate::FileStatistics;

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>,
}

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

#[async_trait]
impl DataSource for FileDataSource {
impl<S: DataSource> DataSource for FileDataSource<S> {
fn dtype(&self) -> &DType {
self.source.dtype()
}
Expand Down
62 changes: 62 additions & 0 deletions vortex-file/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,9 @@ use vortex_layout::scan::scan_builder::ScanBuilder;
use vortex_layout::scan::split_by::DEFAULT_MAX_SPLIT_ROWS;
use vortex_layout::scan::split_by::SplitBy;
use vortex_layout::session::LayoutSession;
use vortex_scan::DataSourceRef;
use vortex_scan::PartitionRef;
use vortex_scan::ScanRequest;
use vortex_scan::strict_sorted_buffer::StrictSortedBuffer;
use vortex_session::VortexSession;
use vortex_session::registry::Id;
Expand Down Expand Up @@ -2595,6 +2598,65 @@ async fn file_data_source_returns_mergeable_partials() -> VortexResult<()> {
Ok(())
}

/// Scans `source` and concatenates the rows of all its partitions, returning how many partitions
/// the scan had.
async fn scan_source(
source: &DataSourceRef,
request: ScanRequest,
) -> VortexResult<(usize, ArrayRef)> {
let scan = source.scan(request).await?;
let dtype = scan.dtype().clone();
let partitions: Vec<PartitionRef> = scan.partitions().try_collect().await?;
let partition_count = partitions.len();
let mut chunks = Vec::new();
for partition in partitions {
chunks.push(partition.execute()?.read_all().await?);
}
Ok((
partition_count,
ChunkedArray::try_new(chunks, dtype)?.into_array(),
))
}

/// Both of a file's executors are reachable through the Scan API and read the same rows.
#[rstest]
#[case::plan(false)]
#[case::layout_reader(true)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[cfg_attr(miri, ignore)]
async fn file_sources_scan_with_either_executor(#[case] layout_reader: bool) -> VortexResult<()> {
let array = StructArray::from_fields(&[("numbers", buffer![1u32, 2, 3, 4, 5].into_array())])?
.into_array();
let mut buf = ByteBufferMut::empty();
SESSION
.write_options()
.write(&mut buf, array.to_array_stream())
.await?;
let file = SESSION.open_options().open_buffer(buf)?;
let source = if layout_reader {
file.layout_reader_data_source()?
} else {
file.plan_data_source()
};

let (_, actual) = scan_source(
&source,
ScanRequest {
projection: get_item("numbers", root()),
filter: Some(gt(get_item("numbers", root()), lit(3u32))),
ordered: true,
..Default::default()
},
)
.await?;
assert_arrays_eq!(
actual,
buffer![4u32, 5].into_array(),
&mut SESSION.create_execution_ctx()
);
Ok(())
}

#[tokio::test]
async fn test_writer_with_statistics() -> VortexResult<()> {
let array = StructArray::from_fields(&[("numbers", buffer![1u32, 2, 3, 4, 5].into_array())])?
Expand Down
Loading
Loading