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
205 changes: 78 additions & 127 deletions vortex-duckdb/src/file_reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,16 @@ use vortex::file::multi::MultiFileSession;
use vortex::file::multi::open_cached;
use vortex::file::multi::parse_uri_or_path;
use vortex::file::v2::FileStatsLayoutReader;
use vortex::functions::dynamic::DynamicExprUpdates;
use vortex::io::compat::Compat;
use vortex::io::filesystem::FileSystemRef;
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::DataSourceRef;
use vortex::scan::ScanRequest;
use vortex::scan::stream::Claims;
use vortex::scan::stream::ScanExec;
Expand All @@ -56,7 +53,6 @@ use crate::exporter::ArrayExporter;
use crate::exporter::ConversionCache;
use crate::projection::Filter;
use crate::projection::extract_schema_from_dtype;
use crate::scan_v2::FileScan;
use crate::table_function::BindState;
use crate::table_function::GlobalState;
use crate::table_function::LocalState;
Expand Down Expand Up @@ -132,45 +128,47 @@ pub struct OpenFileReader {
/// The state of an open file that the threads scanning it share.
pub struct FileScanState {
reader: LayoutReaderRef,
/// The file as the V2 executor reads it.
scan_file: ScanFile,
/// 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>,
/// The file as a source whose scans run on the V2 executor.
plan_source: DataSourceRef,
/// The opened scan of the file, which each thread scanning the file reads a stream of. Set
/// when the file is initialized.
scan: OnceLock<FileExec>,
cache: ConversionCache,
}

/// The opened scan of a file.
struct FileExec {
exec: ScanExec,
/// Whether a batch can join chunks of several layout chunks, as a V2 batch can.
joins_chunks: bool,
}

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))
// A thread joins the file until its last unit of work, a V1 split or a V2 part, is taken,
// then moves on to the next file while the threads holding the last work finish it: 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 scan = self.scan.get()?;
(!scan.exec.is_exhausted()).then_some(Split(None))
}
}

impl OpenFileReader {
async fn open(path: String) -> VortexResult<Self> {
let (fs, fs_path) = resolve_filesystem(&parse_uri_or_path(&path)?)?;
let source = fs.open_read(&fs_path).await?;
let file = open_cached(&SESSION, Some(&path), source, None, &|options| options).await?;
let mut scan_file = file.scan_file();
scan_file.cache.get_or_insert_default();
// Caching lets the V2 source cut its parts on the layout reader built here, and gives
// every V2 scan of the file one plan cache.
let file = open_cached(&SESSION, Some(&path), source, None, &|options| options)
.await?
.with_caching();
Ok(OpenFileReader {
scan_state: Some(Arc::new(FileScanState {
reader: file.layout_reader()?,
scan_file,
v2: OnceLock::new(),
exec: OnceLock::new(),
plan_source: file.plan_data_source(),
scan: OnceLock::new(),
cache: ConversionCache::default(),
})),
})
Expand Down Expand Up @@ -241,27 +239,8 @@ pub fn reader_initialize(file: &mut OpenFileReader, global: &GlobalState) -> Vor
return Ok(true);
}

// 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 {
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);
}

// Opening 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.
let state = file.scan_state();
let filter = &global.filter;
let request = ScanRequest {
Expand All @@ -271,16 +250,25 @@ pub fn reader_initialize(file: &mut OpenFileReader, global: &GlobalState) -> Vor
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.
// one split at a time, polling it itself. A stream with room for more would claim splits
// other threads could have run, leaving them nothing on a file with few splits. A V2
// stream always runs one part at a time.
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() {
// An unordered scan without a limit opens onto a queue of the file's work, V1 splits or V2
// parts, whose streams each take the next once they have finished their last.
let exec = if global.scan_v2 {
RUNTIME.block_on(state.plan_source.scan(request))?.open()?
} else {
let source = LayoutReaderDataSource::new(Arc::clone(&state.reader), SESSION.clone());
RUNTIME.block_on(source.scan(request))?.open()?
};
let scan = FileExec {
exec,
joins_chunks: global.scan_v2,
};
if state.scan.set(scan).is_err() {
vortex_panic!("file initialized twice");
}
Ok(false)
Expand All @@ -296,17 +284,6 @@ fn file_rows(state: &FileScanState, filter: &Filter) -> Range<u64> {
})
}

/// 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 rows = file_rows(state, filter);
V2ScanBuilder::new(SESSION.clone(), state.scan_file.clone())
.with_projection(global.projection.clone())
.with_some_filter(filter.filter.clone())
.with_selection(filter.row_selection.clone())
.with_row_range(rows)
}

/// What a thread's split yields next.
enum SplitItem {
/// The split has no more rows.
Expand All @@ -318,65 +295,42 @@ enum SplitItem {

/// Takes the next array of the thread's split, keeping the split while it has more to yield.
fn next_split_item(local: &mut LocalState) -> VortexResult<SplitItem> {
match local.split.take() {
None => Ok(SplitItem::Done),
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)));
let array = match local.pending.pop() {
Some(array) => array,
None => {
let Some(Split(stream)) = local.split.take() else {
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
.v2
.scan
.get()
.vortex_expect("V2 split of a file without a V2 scan");
let array = match local.pending.pop() {
Some(array) => array,
None => {
let Some(array) = scan.next_array(&mut local.run)? else {
return Ok(SplitItem::Done);
};
// A V2 batch can join chunks of several layout chunks. Canonicalizing it
// would decode their dictionaries, so export each chunk on its own, as a V1
// scan yields them.
match array.as_opt::<Chunked>() {
Some(chunked) => {
local.pending.extend(chunked.chunks().into_iter().rev());
local.pending.pop().unwrap_or(array)
}
None => array,
}
}
.vortex_expect("split of a file without an opened scan");
let mut stream = stream.unwrap_or_else(|| scan.exec.stream());
let Some(array) = RUNTIME.block_on(stream.next()).transpose()? else {
// Dropping the last stream drops the file's queue of work; do that outside
// DuckDB's locks.
local.retired_splits.push(Split(Some(stream)));
return Ok(SplitItem::Done);
};
local.split = Some(Split::V2);
Ok(if array.is_empty() {
SplitItem::Empty
} else {
SplitItem::Array(array)
})
local.split = Some(Split(Some(stream)));
let joins_chunks = scan.joins_chunks;
// A V2 batch can join chunks of several layout chunks. Canonicalizing it would decode
// their dictionaries, so export each chunk on its own, as a V1 scan yields them.
match array.as_opt::<Chunked>().filter(|_| joins_chunks) {
Some(chunked) => {
local.pending.extend(chunked.chunks().into_iter().rev());
local.pending.pop().unwrap_or(array)
}
None => array,
}
}
}
};
Ok(if array.is_empty() {
SplitItem::Empty
} else {
SplitItem::Array(array)
})
}

/// Called by all threads under global lock. If this function returns true,
Expand All @@ -388,9 +342,9 @@ 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 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.
// A thread joins a file while its scan has work left to take. The 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()
Expand Down Expand Up @@ -513,13 +467,10 @@ pub fn reader_get_progress_in_file(file: &OpenFileReader) -> f64 {
let Some(state) = file.scan_state.as_ref() else {
return 100.0;
};
if let Some(scan) = state.v2.get() {
return scan.progress();
}
state
.exec
.scan
.get()
.and_then(ScanExec::progress)
.and_then(|scan| scan.exec.progress())
.map_or(0.0, |Claims { claimed, total }| {
if total == 0 {
100.0
Expand Down
1 change: 0 additions & 1 deletion vortex-duckdb/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ mod exporter;
mod ffi;
mod file_reader;
mod projection;
mod scan_v2;
mod table_function;

#[rustfmt::skip]
Expand Down
Loading