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
105 changes: 86 additions & 19 deletions encodings/sparse/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -479,11 +479,13 @@ impl SparseData {

/// Encode given array as a SparseArray.
///
/// Optionally provided fill value will be respected if the array is less than 90% null.
/// Without one, the fill is the valid value that fills more than half of the valid positions if
/// there is one, and some valid value otherwise. That requires a boolean, primitive, decimal,
/// UTF-8 or binary array. A string array whose dominant value is too long to inline in a view
/// is returned as it is.
/// An explicit null fill always uses the null-fill layout (storing only valid rows as patches)
/// when the array has at least one null. Any other explicit fill value is respected when the
/// array is at most 90% null; arrays that are more than 90% null always use a null fill.
/// Without an explicit fill, the fill is the valid value that fills more than half of the
/// valid positions if there is one, and some valid value otherwise. That requires a boolean,
/// primitive, decimal, UTF-8 or binary array. A string array whose dominant value is too long
/// to inline in a view is returned as it is.
pub fn encode(
array: &ArrayRef,
fill_value: Option<Scalar>,
Expand All @@ -505,8 +507,10 @@ impl SparseData {
return Ok(
ConstantArray::new(Scalar::null(array.dtype().clone()), array.len()).into_array(),
);
} else if mask.false_count() as f64 > (0.9 * mask.len() as f64) {
// Array is dominated by NULL but has non-NULL values
} else if (fill_value.as_ref().is_some_and(Scalar::is_null) && !mask.all_true())
|| mask.false_count() as f64 > (0.9 * mask.len() as f64)
{
// Array uses a null fill and has both nulls and non-null values.
// The values are stored as they are, so their validity must not stay a lazy filter
// over the input's bitmap, which may itself be compressed.
let non_null_values = array
Expand All @@ -516,21 +520,14 @@ impl SparseData {
.into_array();
let non_null_indices = match mask.indices() {
AllOr::All => {
// We already know that the mask is 90%+ false
unreachable!("Mask is mostly null")
// We already checked that the mask has at least one null.
unreachable!("Mask has at least one null")
}
AllOr::None => {
// we know there are some non-NULL values
unreachable!("Mask is mostly null but not all null")
}
AllOr::Some(values) => {
let buffer: Buffer<u32> = values
.iter()
.map(|&v| v.try_into().vortex_expect("indices must fit in u32"))
.collect();

buffer.into_array()
// We already checked that the mask is not all null.
unreachable!("Mask has at least one valid value")
}
AllOr::Some(values) => collect_null_fill_indices(values),
};

return Sparse::try_new(
Expand Down Expand Up @@ -592,6 +589,25 @@ impl SparseData {
}
}

fn collect_null_fill_indices(indices: &[usize]) -> ArrayRef {
if indices
.last()
.is_some_and(|&last| u32::try_from(last).is_err())
{
indices
.iter()
.map(|&v| v as u64)
.collect::<Buffer<u64>>()
.into_array()
} else {
indices
.iter()
.map(|&v| u32::try_from(v).vortex_expect("sorted indices fit in u32"))
.collect::<Buffer<u32>>()
.into_array()
}
}

/// Extension trait for accessing patches on [`SparseArray`] and [`ArrayView<'_, Sparse>`].
///
/// Patches are reconstructed from the array's slots and stored metadata on each call.
Expand Down Expand Up @@ -978,4 +994,55 @@ mod test {

assert_eq!(actual, expected);
}

#[test]
fn encode_null_fill_all_valid() -> VortexResult<()> {
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
let mut ctx = SESSION.create_execution_ctx();
let original =
PrimitiveArray::new(buffer![1.0f64, 2.0, 3.0, 4.0], Validity::AllValid).into_array();
let encoded = Sparse::encode(
&original,
Some(Scalar::null(original.dtype().clone())),
&mut ctx,
)?;
assert_arrays_eq!(&encoded, &original, &mut ctx);
Ok(())
}

#[test]
fn encode_null_fill_below_threshold() -> VortexResult<()> {
let mut ctx = SESSION.create_execution_ctx();
let original = PrimitiveArray::from_option_iter([Some(10i32), None, Some(20), None, None])
.into_array();
let encoded = Sparse::encode(
&original,
Some(Scalar::null(original.dtype().clone())),
&mut ctx,
)?;
let sparse = encoded.as_opt::<Sparse>().expect("expected Sparse");
assert!(sparse.fill_scalar().is_null());
assert_eq!(sparse.patches().num_patches(), 2);
assert_arrays_eq!(&encoded, &original, &mut ctx);
Ok(())
}

#[test]
fn null_fill_indices_width_at_u32_boundary() {
let mut ctx = SESSION.create_execution_ctx();
let u32_indices = collect_null_fill_indices(&[0, u32::MAX as usize]);
assert_eq!(u32_indices.dtype().as_ptype(), PType::U32);
assert_arrays_eq!(&u32_indices, buffer![0u32, u32::MAX].into_array(), &mut ctx);

#[cfg(target_pointer_width = "64")]
{
let above_u32 = u32::MAX as usize + 1;
let u64_indices = collect_null_fill_indices(&[0, above_u32]);
assert_eq!(u64_indices.dtype().as_ptype(), PType::U64);
assert_arrays_eq!(
&u64_indices,
buffer![0u64, above_u32 as u64].into_array(),
&mut ctx
);
}
}
}
Loading
Loading