Skip to content
Open
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
45 changes: 45 additions & 0 deletions vortex-file/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -2454,6 +2457,48 @@ async fn write_read_roundtrip(array: ArrayRef) -> VortexResult<ArrayRef> {
.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::<Flat>());
}
let actual = file.scan()?.into_array_stream()?.read_all().await?;
assert_arrays_eq!(actual, input, &mut SESSION.create_execution_ctx());
Ok(())
}

/// A `list<list<i32>>` column round-trips through the `TableStrategy` dispatcher, exercising list
/// decomposition recursing into itself (the outer list's `elements` are themselves lists).
#[tokio::test]
Expand Down
1 change: 1 addition & 0 deletions vortex-layout/src/layouts/struct_/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion vortex-layout/src/layouts/struct_/normalize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
3 changes: 3 additions & 0 deletions vortex-layout/src/layouts/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)
Expand Down
153 changes: 153 additions & 0 deletions vortex-layout/src/layouts/table/null_runs.rs
Original file line number Diff line number Diff line change
@@ -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::<Struct>()
.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<ArrayRef> {
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::<VortexResult<Vec<_>>>()?;
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_::<Struct>(), 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::<Vec<_>>()
.now_or_never()
.expect("a full run must not wait for another batch")?;
assert_eq!(lengths, [limit - 1, limit]);
Ok(())
}
}
Loading
Loading