diff --git a/vortex-btrblocks/src/schemes/boolean.rs b/vortex-btrblocks/src/schemes/boolean.rs index eeea7f02e7ae0fae74767f7450ecd8169b33deba..c190ebbe1f1d27143af913ec39cd725fdae975cc 100644 --- a/vortex-btrblocks/src/schemes/boolean.rs +++ b/vortex-btrblocks/src/schemes/boolean.rs @@ -15,18 +15,21 @@ use vortex_array::arrays::ConstantArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::RunEnd; use vortex_array::arrays::bool::BoolArrayExt; -use vortex_array::arrays::primitive::PrimitiveArrayExt; use vortex_array::arrays::runend::compress::bool_run_count; use vortex_array::arrays::runend::compress::runend_encode_bool; use vortex_array::dtype::DType; +use vortex_array::dtype::NativePType; use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; use vortex_array::scalar::Scalar; +use vortex_array::validity::Validity; +use vortex_buffer::BitBuffer; +use vortex_buffer::BufferMut; use vortex_compressor::scheme::CompressionEstimate; use vortex_compressor::scheme::EstimateVerdict; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_sparse::Sparse; -use vortex_sparse::SparseExt; use crate::ArrayAndStats; use crate::CascadingCompressor; @@ -153,21 +156,35 @@ impl Scheme for BoolSparseScheme { ) -> VortexResult { let stats = data.bool_stats(exec_ctx); let fill = stats.true_count() > stats.value_count() / 2; - let encoded = Sparse::encode(data.array(), Some(Scalar::from(fill)), exec_ctx)?; - let Some(sparse) = encoded.as_opt::() else { - return Ok(Encoded::leaf(encoded)); + let num_patches = stats + .true_count() + .min(stats.value_count() - stats.true_count()) as usize; + let len = data.array().len(); + if num_patches == 0 { + return Ok(Encoded::leaf(ConstantArray::new(fill, len).into_array())); + } + let bits = data + .array() + .as_opt::() + .vortex_expect("boolean input") + .to_bit_buffer(); + // Narrow from the last exception, not the array length: a long fill tail costs no indices. + let last_index = if fill { + bits.select_unset(num_patches - 1) + } else { + bits.last_set_index() + } + .vortex_expect("non-empty exceptions"); + let indices = match PType::min_unsigned_ptype_for_value(last_index as u64) { + PType::U8 => sparse_indices::(&bits, fill, num_patches), + PType::U16 => sparse_indices::(&bits, fill, num_patches), + PType::U32 => sparse_indices::(&bits, fill, num_patches), + PType::U64 => sparse_indices::(&bits, fill, num_patches), + _ => unreachable!("unsigned index type"), }; - let indices = sparse - .patches() - .indices() - .clone() - .execute::(exec_ctx)? - .narrow(exec_ctx)?; - let num_patches = sparse.patches().values().len(); - let len = sparse.len(); - let fill_scalar = sparse.fill_scalar().clone(); + let fill_scalar = Scalar::from(fill); Ok(Encoded::new( - vec![Child::new(self, 0, indices.into_array())], + vec![Child::new(self, 0, indices)], Vec::new(), move |children, exec_ctx| { let [indices] = children.compressed()?; @@ -194,3 +211,14 @@ impl Scheme for BoolSparseScheme { unimplemented!("{} compresses through Scheme::encode", self.scheme_name()) } } + +fn sparse_indices(bits: &BitBuffer, fill: bool, count: usize) -> ArrayRef { + let mut indices = BufferMut::::with_capacity(count); + let mut push = |index| indices.push(T::from(index).vortex_expect("index fits selected width")); + if fill { + bits.for_each_unset_index(&mut push); + } else { + bits.for_each_set_index(&mut push); + } + PrimitiveArray::new(indices.freeze(), Validity::NonNullable).into_array() +} diff --git a/vortex-btrblocks/tests/bool_sparse_alloc_check.rs b/vortex-btrblocks/tests/bool_sparse_alloc_check.rs new file mode 100644 index 0000000000000000000000000000000000000000..f3ae93d4426725137410e81975f7531fffb44ec4 --- /dev/null +++ b/vortex-btrblocks/tests/bool_sparse_alloc_check.rs @@ -0,0 +1,115 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +#![allow(clippy::tests_outside_test_module)] + +use std::sync::Arc; + +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::BoolArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::primitive::PrimitiveArrayExt; +use vortex_array::assert_arrays_eq; +use vortex_array::dtype::PType; +use vortex_array::validity::Validity; +use vortex_btrblocks::BtrBlocksCompressorBuilder; +use vortex_btrblocks::ChildDecision; +use vortex_btrblocks::ChildPolicy; +use vortex_btrblocks::ChildRequest; +use vortex_btrblocks::CompressionSession; +use vortex_btrblocks::schemes::boolean::BoolSparseScheme; +use vortex_buffer::BitBuffer; +use vortex_edition::EDITION_DECLARATIONS; +use vortex_edition::EDITION_FAMILIES; +use vortex_edition::EditionSession; +use vortex_edition::EditionSessionExt; +use vortex_edition::declarations::core::CORE_2026_08_3; +use vortex_error::VortexResult; +use vortex_session::VortexSession; +use vortex_sparse::Sparse; +use vortex_sparse::SparseExt; + +#[derive(Debug)] +struct KeepChildren; +impl ChildPolicy for KeepChildren { + fn decide(&self, _request: &ChildRequest<'_>) -> ChildDecision { + ChildDecision::Keep + } +} + +fn core_write_session() -> VortexResult { + let session = VortexSession::empty() + .with::() + .with::(); + vortex_fastlanes::initialize(&session); + vortex_sequence::initialize(&session); + vortex_sparse::initialize(&session); + vortex_zigzag::initialize(&session); + for family in EDITION_FAMILIES { + session.editions().declare_family(family)?; + } + for declaration in EDITION_DECLARATIONS { + session.register_edition(declaration)?; + } + session.enable_edition(CORE_2026_08_3)?; + Ok(session) +} + +#[test] +fn sparse_boolean_index_widths_and_slices() -> VortexResult<()> { + let session = core_write_session()?; + let compressor = BtrBlocksCompressorBuilder::empty() + .with_new_scheme(&BoolSparseScheme) + .with_child_policy(Arc::new(KeepChildren)) + .build(); + let mut ctx = session.create_execution_ctx(); + // All four boundaries, both fills and both alignments: 16 cases. A long fill tail + // also checks that width depends on the last exception rather than the length. + for (last, expected) in [ + (255, PType::U8), + (256, PType::U16), + (65_535, PType::U16), + (65_536, PType::U32), + ] { + for fill in [false, true] { + for offset in [0, 5] { + let len = 65_539; + let bits = BitBuffer::from_iter((0..len + offset + 8).map(|i| { + if i < offset || i >= offset + len { + !fill + } else { + fill ^ (i == offset + || (64..128).contains(&(i - offset)) + || i - offset == last) + } + })) + .slice(offset..offset + len); + let input = BoolArray::new(bits, Validity::NonNullable).into_array(); + let compressed = compressor.compress(&input, &mut ctx)?; + assert_arrays_eq!(&compressed, &input, &mut ctx); + let indices = compressed + .as_::() + .patches() + .indices() + .clone() + .execute::(&mut ctx)?; + assert_eq!(indices.ptype(), expected); + } + } + } + Ok(()) +} + +#[test] +fn sparse_boolean_constants_without_builtin_detection() -> VortexResult<()> { + let session = core_write_session()?; + let compressor = vortex_btrblocks::CascadingCompressor::new(vec![&BoolSparseScheme]) + .with_allow_constant(false); + let mut ctx = session.create_execution_ctx(); + for fill in [false, true] { + let input = BoolArray::from_iter(std::iter::repeat_n(fill, 65)).into_array(); + assert_arrays_eq!(compressor.compress(&input, &mut ctx)?, input, &mut ctx); + } + Ok(()) +}