diff --git a/vortex-file/src/tests.rs b/vortex-file/src/tests.rs index db3fc73048a..9baf5642728 100644 --- a/vortex-file/src/tests.rs +++ b/vortex-file/src/tests.rs @@ -124,8 +124,11 @@ use vortex_io::std_file::FileWrite; use vortex_layout::DynLayout; use vortex_layout::LayoutStrategy; use vortex_layout::layouts::chunked::writer::ChunkedLayoutStrategy; +use vortex_layout::layouts::constant::ConstantStrategy; use vortex_layout::layouts::file_stats::AggregateStats; +use vortex_layout::layouts::flat::Flat; use vortex_layout::layouts::flat::writer::FlatLayoutStrategy; +use vortex_layout::layouts::table::TableStrategy; use vortex_layout::layouts::zoned::LegacyStats; use vortex_layout::layouts::zoned::Zoned; use vortex_layout::scan::scan_builder::ScanBuilder; @@ -2454,6 +2457,48 @@ async fn write_read_roundtrip(array: ArrayRef) -> VortexResult { .await } +#[tokio::test] +async fn sparse_nested_struct_runs_preserve_constant_fields() -> VortexResult<()> { + let batch = |float, validity| { + let float = PrimitiveArray::from_option_iter([float; 2]); + let inner = StructArray::try_from_iter_with_validity( + [ + ("float", float.into_array()), + ("required", ConstantArray::new(7i32, 2).into_array()), + ], + Validity::from_iter([true, false]), + )?; + StructArray::try_from_iter_with_validity([("inner", inner)], validity) + .map(IntoArray::into_array) + }; + let present = batch(Some(0.0f64), Validity::AllValid)?; + let absent = batch(None, Validity::AllInvalid)?; + let input = + ChunkedArray::from_iter([absent.clone(), present, absent.clone(), absent]).into_array(); + + // Validity records one chunk per batch. A constant leaf gets one flat layout for all batches. + let chunked = ChunkedLayoutStrategy::new(FlatLayoutStrategy::default()); + let constant = ConstantStrategy::new(chunked.clone(), FlatLayoutStrategy::default()); + let strategy = TableStrategy::new(Arc::new(chunked), Arc::new(constant)); + let mut buf = ByteBufferMut::empty(); + SESSION + .write_options() + .with_strategy(Arc::new(strategy)) + .write(&mut buf, input.to_array_stream()) + .await?; + + let file = SESSION.open_options().open_buffer(buf)?; + let root = file.footer().layout(); + assert_eq!(root.slot(0)?.expect("validity").children()?.len(), 3); + let inner = root.slot(1)?.expect("inner"); + for slot in [1, 2] { + assert!(inner.slot(slot)?.expect("field").is::()); + } + let actual = file.scan()?.into_array_stream()?.read_all().await?; + assert_arrays_eq!(actual, input, &mut SESSION.create_execution_ctx()); + Ok(()) +} + /// A `list>` column round-trips through the `TableStrategy` dispatcher, exercising list /// decomposition recursing into itself (the outer list's `elements` are themselves lists). #[tokio::test] diff --git a/vortex-layout/src/layouts/struct_/mod.rs b/vortex-layout/src/layouts/struct_/mod.rs index 27c218b30d4..09ea0854f49 100644 --- a/vortex-layout/src/layouts/struct_/mod.rs +++ b/vortex-layout/src/layouts/struct_/mod.rs @@ -7,6 +7,7 @@ pub mod writer; use std::sync::Arc; +pub(super) use normalize::normalize_field; use reader::StructReader; use vortex_array::EmptyMetadata; use vortex_array::dtype::DType; diff --git a/vortex-layout/src/layouts/struct_/normalize.rs b/vortex-layout/src/layouts/struct_/normalize.rs index 158c0b6bdbf..40092a5d3ae 100644 --- a/vortex-layout/src/layouts/struct_/normalize.rs +++ b/vortex-layout/src/layouts/struct_/normalize.rs @@ -17,7 +17,7 @@ use vortex_functions::builtins::ArrayFunctions; use vortex_mask::Mask; /// Removes redundant validity beneath null struct rows before writing a field on its own. -pub(super) fn normalize_field( +pub(in crate::layouts) fn normalize_field( array: ArrayRef, visible: &Mask, ctx: &mut ExecutionCtx, diff --git a/vortex-layout/src/layouts/table.rs b/vortex-layout/src/layouts/table.rs index 08575a80515..9b669d20ccd 100644 --- a/vortex-layout/src/layouts/table.rs +++ b/vortex-layout/src/layouts/table.rs @@ -12,6 +12,8 @@ //! The dispatcher also owns field-path overrides, letting callers force a specific leaf field — //! at any depth — onto a custom strategy. +mod null_runs; + use std::sync::Arc; use async_trait::async_trait; @@ -291,6 +293,7 @@ impl LayoutStrategy for TableStrategy { let dtype = stream.dtype().clone(); if dtype.is_struct() { + let stream = null_runs::coalesce_null_structs(stream, session); return self .struct_strategy() .write_stream(ctx, segment_sink, stream, eof, session) diff --git a/vortex-layout/src/layouts/table/null_runs.rs b/vortex-layout/src/layouts/table/null_runs.rs new file mode 100644 index 00000000000..7108393b786 --- /dev/null +++ b/vortex-layout/src/layouts/table/null_runs.rs @@ -0,0 +1,153 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use async_stream::try_stream; +use futures::StreamExt; +use futures::pin_mut; +use vortex_array::ArrayRef; +use vortex_array::ArrayView; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::Struct; +use vortex_array::arrays::StructArray; +use vortex_array::arrays::struct_::StructArrayExt; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::validity::Validity; +use vortex_error::VortexResult; +use vortex_mask::Mask; +use vortex_session::VortexSession; + +use crate::layouts::struct_::normalize_field; +use crate::sequence::SendableSequentialStream; +use crate::sequence::SequentialStreamAdapter; +use crate::sequence::SequentialStreamExt; + +// Bound the rows a downstream writer might materialize at once, even for an all-null stream. +const MAX_NULL_RUN_ROWS: usize = 1024 * 1024; + +fn supports_null_runs(dtype: &DType) -> bool { + match dtype { + DType::Struct(fields, _) => fields.fields().all(|field| supports_null_runs(&field)), + DType::Null + | DType::Bool(_) + | DType::Primitive(..) + | DType::Decimal(..) + | DType::Utf8(_) + | DType::Binary(_) => true, + _ => false, + } +} + +fn is_absent(chunk: &ArrayRef) -> bool { + // Merging needs the physical struct fields, including values hidden by the parent validity. + !chunk.is_empty() + && chunk + .as_opt::() + .is_some_and(|array| array.struct_validity().definitely_all_null()) +} + +// Every row is hidden. Repeat a representative row after applying the same field normalization +// as the struct writer, so its choices for sparse integers, constants and nested validity survive. +fn merged_run( + chunk: ArrayView<'_, Struct>, + len: usize, + ctx: &mut ExecutionCtx, +) -> VortexResult { + let hidden = Mask::new_false(chunk.len()); + let children = chunk + .iter_unmasked_fields() + .map(|field| { + let field = normalize_field(field.clone(), &hidden, ctx)?; + let scalar = field.execute_scalar(0, ctx)?; + Ok(ConstantArray::new(scalar, len).into_array()) + }) + .collect::>>()?; + StructArray::try_new_with_dtype( + children, + chunk.struct_fields().clone(), + len, + Validity::AllInvalid, + ) + .map(IntoArray::into_array) +} + +/// Combine consecutive absent batches before they are fanned out to the struct's descendants. +/// The most recent sequence orders the whole run, so earlier batches can release their positions. +pub(super) fn coalesce_null_structs( + stream: SendableSequentialStream, + session: &VortexSession, +) -> SendableSequentialStream { + let dtype = stream.dtype(); + if !matches!(dtype, DType::Struct(_, Nullability::Nullable)) || !supports_null_runs(dtype) { + return stream; + } + let dtype = dtype.clone(); + let session = session.clone(); + let chunks = try_stream! { + let stream = stream.peekable(); + pin_mut!(stream); + while let Some(item) = stream.next().await { + let (mut id, mut chunk) = item?; + let mut len = chunk.len(); + if is_absent(&chunk) { + while len < MAX_NULL_RUN_ROWS + && let Some(next) = stream.as_mut().next_if(|item| { + item.as_ref().is_ok_and(|(_, next)| { + next.len() <= MAX_NULL_RUN_ROWS - len && is_absent(next) + }) + }).await + { + (id, chunk) = next?; + len += chunk.len(); + } + if len > chunk.len() { + chunk = merged_run(chunk.as_::(), len, &mut session.create_execution_ctx())?; + } + } + yield (id, chunk); + } + }; + SequentialStreamAdapter::new(dtype, chunks).sendable() +} + +#[cfg(test)] +mod tests { + use futures::FutureExt; + use futures::StreamExt; + use futures::TryStreamExt; + use futures::stream; + use vortex_array::IntoArray; + use vortex_array::arrays::StructArray; + use vortex_array::validity::Validity; + use vortex_error::VortexResult; + + use super::MAX_NULL_RUN_ROWS; + use super::coalesce_null_structs; + use crate::sequence::SequenceId; + use crate::sequence::SequentialStreamAdapter; + use crate::sequence::SequentialStreamExt; + use crate::test::SESSION; + + #[test] + fn null_runs_flush_at_the_row_limit_while_input_is_pending() -> VortexResult<()> { + let limit = MAX_NULL_RUN_ROWS; + let batches = [limit - 1, 2, limit - 2].map(|len| { + StructArray::new(Default::default(), [], len, Validity::AllInvalid).into_array() + }); + let dtype = batches[0].dtype().clone(); + let mut ptr = SequenceId::root(); + let input = stream::iter(batches.map(|batch| Ok((ptr.advance(), batch)))); + let input = SequentialStreamAdapter::new(dtype, input.chain(stream::pending())).sendable(); + let lengths = coalesce_null_structs(input, &SESSION) + .map_ok(|(_, batch)| batch.len()) + .take(2) + .try_collect::>() + .now_or_never() + .expect("a full run must not wait for another batch")?; + assert_eq!(lengths, [limit - 1, limit]); + Ok(()) + } +} diff --git a/vortex-layout/src/sequence.rs b/vortex-layout/src/sequence.rs index bd531ba6612..e8089d48d75 100644 --- a/vortex-layout/src/sequence.rs +++ b/vortex-layout/src/sequence.rs @@ -2,13 +2,13 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors use std::cmp::Ordering; -use std::collections::BTreeSet; use std::fmt; use std::hash::Hash; use std::hash::Hasher; use std::mem; use std::pin::Pin; use std::sync::Arc; +use std::sync::Weak; use std::task::Context; use std::task::Poll; use std::task::Waker; @@ -22,7 +22,6 @@ use vortex_array::dtype::DType; use vortex_array::stream::ArrayStream; use vortex_error::VortexExpect; use vortex_error::VortexResult; -use vortex_utils::aliases::hash_map::HashMap; /// A hierarchical sequence identifier that exists within a shared universe. /// @@ -44,7 +43,7 @@ use vortex_utils::aliases::hash_map::HashMap; /// recursively created sequence IDs. pub struct SequenceId { id: Vec, - universe: Arc>, + position: Arc>, } impl PartialEq for SequenceId { @@ -86,7 +85,10 @@ impl SequenceId { /// guarantees between separate root instances. Within a single universe, /// all IDs are strictly ordered. pub fn root() -> SequencePointer { - SequencePointer(SequenceId::new(vec![0], Default::default())) + SequencePointer(SequenceId { + id: vec![0], + position: Default::default(), + }) } /// Creates a child sequence by descending one level in the hierarchy. @@ -100,28 +102,9 @@ impl SequenceId { /// This method consumes `self`, as the parent ID is no longer needed once /// we've descended to work with its children. pub fn descend(mut self) -> SequencePointer { - // Take the parent's id, so that dropping `self` does not touch the universe. The child - // replaces the parent under one lock acquisition, as every writer task contends on it. - let parent = mem::take(&mut self.id); - let mut id = parent.clone(); - id.push(0); - let key = id.clone(); - - let (removed, waker) = { - let mut universe = self.universe.lock(); - universe.active.insert(key); - universe.remove(&parent) - }; - - drop(removed); - if let Some(w) = waker { - w.wake(); - } - - SequencePointer(SequenceId { - id, - universe: Arc::clone(&self.universe), - }) + // Replacing the parent with its first child cannot cross another live ID. + self.id.push(0); + SequencePointer(self) } /// Waits until all SequenceIds with IDs lexicographically smaller than this one are dropped. @@ -152,33 +135,43 @@ impl SequenceId { pub async fn collapse(&mut self) { WaitSequenceFuture(self).await; } - - /// This is intentionally not pub. [SequencePointer::advance] is the only allowed way to create - /// [SequenceId] instances - fn new(id: Vec, universe: Arc>) -> Self { - // NOTE: Apart from `descend`, this is the only place we construct a SequenceId, and - // we immediately add it to the universe. Clone the key before taking the lock, as every - // writer task contends on it. - let key = id.clone(); - universe.lock().active.insert(key); - Self { id, universe } - } } impl Drop for SequenceId { fn drop(&mut self) { - // An empty id was taken by `descend`, which already removed it from the universe. - if self.id.is_empty() { + // Take locks in sequence order. If a predecessor finishes before its lock is acquired, + // retry with the new predecessor. A waiter can proceed only when it becomes the head. + loop { + let mut current = self.position.lock(); + let Some(previous) = current.previous.as_ref().and_then(Weak::upgrade) else { + let wake = current.next.take().and_then(|next| { + let mut next = next.lock(); + next.previous = None; + next.waiter.take() + }); + drop(current); + if let Some(waker) = wake { + waker.wake(); + } + return; + }; + drop(current); + + let mut links = previous.lock(); + if links + .next + .as_ref() + .is_none_or(|next| !Arc::ptr_eq(next, &self.position)) + { + continue; + } + let mut current = self.position.lock(); + if let Some(next) = ¤t.next { + next.lock().previous = current.previous.clone(); + } + links.next = current.next.take(); return; } - - let (removed, waker) = self.universe.lock().remove(&self.id); - - // Free the removed key outside the lock. - drop(removed); - if let Some(w) = waker { - w.wake(); - } } } @@ -216,7 +209,22 @@ impl SequencePointer { let last = next_id.last_mut(); let last = last.vortex_expect("must have at least one element"); *last += 1; - let next_sibling = SequenceId::new(next_id, Arc::clone(&self.0.universe)); + let position = { + let mut current = self.0.position.lock(); + let position = Arc::new(Mutex::new(Position { + previous: Some(Arc::downgrade(&self.0.position)), + next: current.next.clone(), + waiter: None, + })); + if let Some(next) = current.next.replace(Arc::clone(&position)) { + next.lock().previous = Some(Arc::downgrade(&position)); + } + position + }; + let next_sibling = SequenceId { + id: next_id, + position, + }; mem::replace(&mut self.0, next_sibling) } @@ -230,30 +238,13 @@ impl SequencePointer { } } +// Advancing inserts a successor immediately after this position. Descending preserves the +// position. Independent branches can therefore update their disjoint neighbours concurrently. #[derive(Default)] -struct SequenceUniverse { - active: BTreeSet>, - wakers: HashMap, Waker>, -} - -impl SequenceUniverse { - /// Removes `id` from the active set, returning the removed key and the waker of the new first - /// active sequence, if one is waiting. - fn remove(&mut self, id: &[usize]) -> (Option>, Option) { - let removed = self.active.take(id); - - // Most sequences are never collapsed, so usually no waker is registered. - if self.wakers.is_empty() { - return (removed, None); - } - - let Some(first) = self.active.first() else { - // last sequence finished, we must have no pending futures - unreachable!("all wakers must have been removed"); - }; - let waker = self.wakers.remove(first); - (removed, waker) - } +struct Position { + previous: Option>>, + next: Option>>, + waiter: Option, } struct WaitSequenceFuture<'a>(&'a mut SequenceId); @@ -262,18 +253,11 @@ impl Future for WaitSequenceFuture<'_> { type Output = (); fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { - let mut guard = self.0.universe.lock(); - let current_first = guard - .active - .first() - .cloned() - .vortex_expect("if we have a future, we must have at least one active sequence"); - if self.0.id == current_first { - guard.wakers.remove(&self.0.id); + let mut position = self.0.position.lock(); + if position.previous.is_none() { return Poll::Ready(()); } - - guard.wakers.insert(self.0.id.clone(), cx.waker().clone()); + position.waiter = Some(cx.waker().clone()); Poll::Pending } } @@ -281,7 +265,7 @@ impl Future for WaitSequenceFuture<'_> { /// If the future itself is dropped, we don't want to orphan the waker impl Drop for WaitSequenceFuture<'_> { fn drop(&mut self) { - self.0.universe.lock().wakers.remove(&self.0.id); + self.0.position.lock().waiter = None; } } @@ -375,3 +359,50 @@ pub trait SequentialArrayStreamExt: ArrayStream { } impl SequentialArrayStreamExt for S {} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::time::Duration; + + use futures::FutureExt; + use parking_lot::Mutex; + + use super::SequenceId; + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn collapse_orders_concurrent_descendants_after_cancelled_waits() { + let mut root = SequenceId::root(); + let granted = Arc::new(Mutex::new(Vec::new())); + let mut tasks = Vec::new(); + // Keep the first position live until the branches have been assigned. + let first = root.advance(); + for branch in 0..64 { + let mut pointer = root.advance().descend(); + let granted = Arc::clone(&granted); + tasks.push(tokio::spawn(async move { + let mut left = pointer.advance(); + let unused = pointer.advance(); + let mut right = pointer.downgrade(); + // Cancelling this wait must leave the position usable with a different waker. + assert!(right.collapse().now_or_never().is_none()); + drop(unused); + left.collapse().await; + granted.lock().push((branch, 0)); + drop(left); + right.collapse().await; + granted.lock().push((branch, 1)); + })); + } + drop(first); + let mut end = root.downgrade(); + tokio::time::timeout(Duration::from_secs(30), end.collapse()) + .await + .expect("all descendants must release the final position"); + for task in tasks { + task.await.expect("branch task must complete"); + } + let expected: Vec<_> = (0..64).flat_map(|i| [(i, 0), (i, 1)]).collect(); + assert_eq!(*granted.lock(), expected); + } +}