Skip to main content

liquid_cache_storage/liquid_array/
float_array.rs

1///
2/// Acknowledgement:
3/// The ALP compression implemented in this file is based on the Rust implementation available at https://github.com/spiraldb/alp
4///
5use std::{
6    any::Any,
7    fmt::Debug,
8    num::NonZero,
9    ops::{Mul, Shl, Shr},
10    sync::Arc,
11};
12
13use arrow::{
14    array::{
15        Array, ArrayRef, ArrowNativeTypeOp, ArrowPrimitiveType, AsArray, BooleanArray,
16        PrimitiveArray,
17    },
18    buffer::{BooleanBuffer, ScalarBuffer},
19    datatypes::{
20        ArrowNativeType, Float32Type, Float64Type, Int32Type, Int64Type, UInt32Type, UInt64Type,
21    },
22};
23use arrow_schema::DataType;
24use datafusion::{
25    physical_plan::{
26        PhysicalExpr,
27        expressions::{BinaryExpr, Literal},
28    },
29    scalar::ScalarValue,
30};
31use fastlanes::BitPacking;
32use num_traits::{AsPrimitive, Float, FromPrimitive};
33
34use super::LiquidDataType;
35use crate::liquid_array::ipc::get_physical_type_id;
36use crate::liquid_array::raw::BitPackedArray;
37use crate::liquid_array::{
38    IoRange, LiquidHybridArray, LiquidHybridArrayRef, Operator, ipc::LiquidIPCHeader,
39};
40use crate::liquid_array::{LiquidArray, LiquidArrayRef};
41use crate::utils::get_bit_width;
42use bytes::Bytes;
43
44mod private {
45    use arrow::{
46        array::ArrowNumericType,
47        datatypes::{Float32Type, Float64Type},
48    };
49    use num_traits::AsPrimitive;
50
51    pub trait Sealed: ArrowNumericType<Native: AsPrimitive<f64> + AsPrimitive<f32>> {}
52
53    impl Sealed for Float32Type {}
54    impl Sealed for Float64Type {}
55}
56
57const NUM_SAMPLES: usize = 1024; // we use FASTLANES to encode array, the sample size needs to be at least 1024 to get a good estimate of the best exponents
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
60pub enum FloatSqueezePolicy {
61    /// Quantize values into buckets (good for coarse filtering; requires disk to recover values).
62    #[default]
63    Quantize = 0,
64}
65
66/// LiquidFloatType is a sealed trait that represents all the float types supported by Liquid.
67/// Implementors are Float32Type and Float64Type. TODO(): What about Float16Type, decimal types?
68pub trait LiquidFloatType:
69        ArrowPrimitiveType<
70            Native: AsPrimitive<
71                <Self::UnsignedIntType as ArrowPrimitiveType>::Native // Native must be convertible to the Native type of Self::UnSignedType
72            >
73            + AsPrimitive<<Self::SignedIntType as ArrowPrimitiveType>::Native>
74            + FromPrimitive
75            + AsPrimitive<<Self as ArrowPrimitiveType>::Native>
76            + Mul<<Self as ArrowPrimitiveType>::Native>
77            + Float // required for decode_single and encode_single_unchecked
78        >
79        + private::Sealed + Debug {
80    type UnsignedIntType:
81        ArrowPrimitiveType<
82            Native: BitPacking +
83                AsPrimitive<<Self as ArrowPrimitiveType>::Native>
84                + AsPrimitive<<Self::SignedIntType as ArrowPrimitiveType>::Native>
85                + AsPrimitive<u64>
86        >
87        + Debug;
88    type SignedIntType:
89        ArrowPrimitiveType<
90            Native: AsPrimitive<<Self as ArrowPrimitiveType>::Native>
91                + AsPrimitive<<Self::UnsignedIntType as ArrowPrimitiveType>::Native>
92                + Ord
93                + Shr<u8, Output = <Self::SignedIntType as ArrowPrimitiveType>::Native>
94                + Shl<u8, Output = <Self::SignedIntType as ArrowPrimitiveType>::Native>
95                + From<i32>
96        >
97        + Debug + Sync + Send;
98
99    const SWEET: <Self as ArrowPrimitiveType>::Native;
100    const MAX_EXPONENT: u8;
101    const FRACTIONAL_BITS: u8;
102    const F10: &'static [<Self as ArrowPrimitiveType>::Native];
103    const IF10: &'static [<Self as ArrowPrimitiveType>::Native];
104
105    #[inline]
106    fn fast_round(val: <Self as ArrowPrimitiveType>::Native) -> <Self::SignedIntType as ArrowPrimitiveType>::Native {
107        ((val + Self::SWEET) - Self::SWEET).as_()
108    }
109
110    #[inline]
111    fn encode_single_unchecked(val: &<Self as ArrowPrimitiveType>::Native, exp: &Exponents) -> <Self::SignedIntType as ArrowPrimitiveType>::Native {
112        Self::fast_round(*val * Self::F10[exp.e as usize] * Self::IF10[exp.f as usize])
113    }
114
115    #[inline]
116    fn decode_single(val: &<Self::SignedIntType as ArrowPrimitiveType>::Native, exp: &Exponents) -> <Self as ArrowPrimitiveType>::Native {
117        let decoded_float: <Self as ArrowPrimitiveType>::Native = (*val).as_();
118        decoded_float * Self::F10[exp.f as usize] * Self::IF10[exp.e as usize]
119    }
120
121}
122
123impl LiquidFloatType for Float32Type {
124    type UnsignedIntType = UInt32Type;
125    type SignedIntType = Int32Type;
126    const FRACTIONAL_BITS: u8 = 23;
127    const MAX_EXPONENT: u8 = 10;
128    const SWEET: <Self as ArrowPrimitiveType>::Native = (1 << Self::FRACTIONAL_BITS)
129        as <Self as ArrowPrimitiveType>::Native
130        + (1 << (Self::FRACTIONAL_BITS - 1)) as <Self as ArrowPrimitiveType>::Native;
131    const F10: &'static [<Self as ArrowPrimitiveType>::Native] = &[
132        1.0,
133        10.0,
134        100.0,
135        1000.0,
136        10000.0,
137        100000.0,
138        1000000.0,
139        10000000.0,
140        100000000.0,
141        1000000000.0,
142        10000000000.0, // 10^10
143    ];
144    const IF10: &'static [<Self as ArrowPrimitiveType>::Native] = &[
145        1.0,
146        0.1,
147        0.01,
148        0.001,
149        0.0001,
150        0.00001,
151        0.000001,
152        0.0000001,
153        0.00000001,
154        0.000000001,
155        0.0000000001, // 10^-10
156    ];
157}
158
159impl LiquidFloatType for Float64Type {
160    type UnsignedIntType = UInt64Type;
161    type SignedIntType = Int64Type;
162    const FRACTIONAL_BITS: u8 = 52;
163    const MAX_EXPONENT: u8 = 18;
164    const SWEET: <Self as ArrowPrimitiveType>::Native = (1u64 << Self::FRACTIONAL_BITS)
165        as <Self as ArrowPrimitiveType>::Native
166        + (1u64 << (Self::FRACTIONAL_BITS - 1)) as <Self as ArrowPrimitiveType>::Native;
167    const F10: &'static [<Self as ArrowPrimitiveType>::Native] = &[
168        1.0,
169        10.0,
170        100.0,
171        1000.0,
172        10000.0,
173        100000.0,
174        1000000.0,
175        10000000.0,
176        100000000.0,
177        1000000000.0,
178        10000000000.0,
179        100000000000.0,
180        1000000000000.0,
181        10000000000000.0,
182        100000000000000.0,
183        1000000000000000.0,
184        10000000000000000.0,
185        100000000000000000.0,
186        1000000000000000000.0,
187        10000000000000000000.0,
188        100000000000000000000.0,
189        1000000000000000000000.0,
190        10000000000000000000000.0,
191        100000000000000000000000.0, // 10^23
192    ];
193
194    const IF10: &'static [<Self as ArrowPrimitiveType>::Native] = &[
195        1.0,
196        0.1,
197        0.01,
198        0.001,
199        0.0001,
200        0.00001,
201        0.000001,
202        0.0000001,
203        0.00000001,
204        0.000000001,
205        0.0000000001,
206        0.00000000001,
207        0.000000000001,
208        0.0000000000001,
209        0.00000000000001,
210        0.000000000000001,
211        0.0000000000000001,
212        0.00000000000000001,
213        0.000000000000000001,
214        0.0000000000000000001,
215        0.00000000000000000001,
216        0.000000000000000000001,
217        0.0000000000000000000001,
218        0.00000000000000000000001, // 10^-23
219    ];
220}
221
222/// Liquid's single-precision floating point array
223pub type LiquidFloat32Array = LiquidFloatArray<Float32Type>;
224/// Liquid's double precision floating point array
225pub type LiquidFloat64Array = LiquidFloatArray<Float64Type>;
226
227/// An array that stores floats in ALP
228#[derive(Debug, Clone)]
229pub struct LiquidFloatArray<T: LiquidFloatType> {
230    exponent: Exponents,
231    bit_packed: BitPackedArray<T::UnsignedIntType>,
232    patch_indices: Vec<u64>,
233    patch_values: Vec<T::Native>,
234    reference_value: <T::SignedIntType as ArrowPrimitiveType>::Native,
235    squeeze_policy: FloatSqueezePolicy,
236}
237
238impl<T> LiquidFloatArray<T>
239where
240    T: LiquidFloatType,
241{
242    /// Check if the Liquid float array is empty.
243    pub fn is_empty(&self) -> bool {
244        self.len() == 0
245    }
246
247    /// Get the length of the Liquid float array.
248    pub fn len(&self) -> usize {
249        self.bit_packed.len()
250    }
251
252    /// Get the memory size of the Liquid primitive array.
253    pub fn get_array_memory_size(&self) -> usize {
254        self.bit_packed.get_array_memory_size()
255            + size_of::<Exponents>()
256            + self.patch_indices.capacity() * size_of::<u64>()
257            + self.patch_values.capacity() * size_of::<T::Native>()
258            + size_of::<<T::SignedIntType as ArrowPrimitiveType>::Native>()
259    }
260
261    /// Create a Liquid primitive array from an Arrow float array.
262    pub fn from_arrow_array(arrow_array: arrow::array::PrimitiveArray<T>) -> LiquidFloatArray<T> {
263        let best_exponents = get_best_exponents::<T>(&arrow_array);
264        encode_arrow_array(&arrow_array, &best_exponents)
265    }
266
267    /// Get current squeeze policy for this array
268    pub fn squeeze_policy(&self) -> FloatSqueezePolicy {
269        self.squeeze_policy
270    }
271}
272
273impl<T> LiquidArray for LiquidFloatArray<T>
274where
275    T: LiquidFloatType,
276{
277    fn as_any(&self) -> &dyn Any {
278        self
279    }
280
281    fn get_array_memory_size(&self) -> usize {
282        self.get_array_memory_size()
283    }
284
285    fn len(&self) -> usize {
286        self.len()
287    }
288
289    #[inline]
290    fn to_arrow_array(&self) -> ArrayRef {
291        let unsigned_array = self.bit_packed.to_primitive();
292        let (_data_type, values, _nulls) = unsigned_array.into_parts();
293        let nulls = self.bit_packed.nulls();
294        // TODO(): Check if we should align vectors to cache line boundary
295        let mut decoded_values = Vec::from_iter(values.iter().map(|v| {
296            let mut val: <T::SignedIntType as ArrowPrimitiveType>::Native = (*v).as_();
297            val = val.add_wrapping(self.reference_value);
298            T::decode_single(&val, &self.exponent)
299        }));
300
301        // Patch values
302        if !self.patch_indices.is_empty() {
303            for i in 0..self.patch_indices.len() {
304                decoded_values[self.patch_indices[i].as_usize()] = self.patch_values[i];
305            }
306        }
307
308        Arc::new(PrimitiveArray::<T>::new(
309            ScalarBuffer::<<T as ArrowPrimitiveType>::Native>::from(decoded_values),
310            nulls.cloned(),
311        ))
312    }
313
314    fn original_arrow_data_type(&self) -> DataType {
315        T::DATA_TYPE.clone()
316    }
317
318    fn data_type(&self) -> LiquidDataType {
319        LiquidDataType::Float
320    }
321
322    fn to_bytes(&self) -> Vec<u8> {
323        self.to_bytes_inner()
324    }
325
326    fn filter(&self, selection: &BooleanBuffer) -> LiquidArrayRef {
327        let values = self.to_arrow_array();
328        let selection = BooleanArray::new(selection.clone(), None);
329        let filtered_values = arrow::compute::kernels::filter::filter(&values, &selection).unwrap();
330        let primitive_values = filtered_values.as_primitive::<T>().clone();
331        let bit_packed = Self::from_arrow_array(primitive_values);
332        Arc::new(bit_packed)
333    }
334
335    fn is_empty(&self) -> bool {
336        self.len() == 0
337    }
338
339    fn to_best_arrow_array(&self) -> ArrayRef {
340        self.to_arrow_array()
341    }
342
343    fn squeeze(&self) -> Option<(super::LiquidHybridArrayRef, bytes::Bytes)> {
344        let orig_bw = self.bit_packed.bit_width()?;
345        if orig_bw.get() < 8 {
346            return None;
347        }
348
349        // New squeezed bit width is half of the original
350        let new_bw = orig_bw.get() / 2;
351
352        let full_bytes = Bytes::from(self.to_bytes_inner());
353        let disk_range = 0u64..(full_bytes.len() as u64);
354
355        let (_dt, values, nulls) = self.bit_packed.to_primitive().into_parts();
356
357        match self.squeeze_policy {
358            FloatSqueezePolicy::Quantize => {
359                let shift = orig_bw.get() - new_bw;
360                let quantized_min = self.reference_value.shr(shift);
361                // let quantized_max = values
362                let quantized_values: ScalarBuffer<
363                    <T::UnsignedIntType as ArrowPrimitiveType>::Native,
364                > = ScalarBuffer::from_iter(values.iter().map(|&v| {
365                    let signed_val: <T::SignedIntType as ArrowPrimitiveType>::Native = v.as_();
366                    let v_signed = self.reference_value.add_wrapping(signed_val);
367                    let v_quantized: <T::SignedIntType as ArrowPrimitiveType>::Native =
368                        v_signed.shr(shift);
369                    v_quantized.sub_wrapping(quantized_min).as_()
370                }));
371                let quantized_array =
372                    PrimitiveArray::<<T as LiquidFloatType>::UnsignedIntType>::new(
373                        quantized_values,
374                        nulls.clone(),
375                    );
376                let quantized_bitpacked =
377                    BitPackedArray::from_primitive(quantized_array, NonZero::new(new_bw).unwrap());
378                let hybrid = LiquidFloatQuantizedArray::<T> {
379                    exponent: self.exponent,
380                    quantized: quantized_bitpacked,
381                    reference_value: self.reference_value,
382                    bucket_width: shift,
383                    disk_range,
384                    patch_indices: self.patch_indices.clone(),
385                    patch_values: self.patch_values.clone(),
386                };
387                Some((Arc::new(hybrid) as LiquidHybridArrayRef, full_bytes))
388            }
389        }
390    }
391}
392
393impl<T> LiquidFloatArray<T>
394where
395    T: LiquidFloatType,
396{
397    /*
398    Serialized LiquidFloatArray Memory Layout:
399    +--------------------------------------------------+
400    | LiquidIPCHeader (16 bytes)                       |
401    +--------------------------------------------------+
402
403    +--------------------------------------------------+
404    | reference_value                                  |
405    | (size_of::<T::SignedIntType::Native> bytes)      |  // The reference value (e.g. minimum value)
406    +--------------------------------------------------+
407    | Padding (to 8-byte alignment)                    |  // Padding to ensure 8-byte alignment
408    +--------------------------------------------------+
409
410    +--------------------------------------------------+
411    | Exponents                                        |
412    +--------------------------------------------------+
413    | e (1 byte)                                       |
414    +--------------------------------------------------+
415    | f (1 byte)                                       |
416    +--------------------------------------------------+
417    | Padding (6 bytes)                                |
418    +--------------------------------------------------+
419
420    +--------------------------------------------------+
421    | Patch Data                                       |
422    +--------------------------------------------------+
423    | patch_length (8 bytes)                           |
424    +--------------------------------------------------+
425    | patch_indices (8 * patch_length btyes)           |
426    +--------------------------------------------------+
427    | patch_values (length *size_of::<T::Native> btyes;|
428    |               8-byte aligned)                    |
429    +--------------------------------------------------+
430
431    +--------------------------------------------------+
432    | BitPackedArray Data                              |
433    +--------------------------------------------------+
434    | [BitPackedArray Header & Bit-Packed Values]      |  // Written by self.bit_packed.to_bytes()
435    +--------------------------------------------------+
436    */
437    pub(crate) fn to_bytes_inner(&self) -> Vec<u8> {
438        // Determine type ID based on the type
439        let physical_type_id = get_physical_type_id::<T>();
440        let logical_type_id = LiquidDataType::Float as u16;
441        let header = LiquidIPCHeader::new(logical_type_id, physical_type_id);
442
443        let mut result = Vec::with_capacity(256); // Pre-allocate a reasonable size
444
445        // Write header
446        result.extend_from_slice(&header.to_bytes());
447
448        // Write reference value
449        let ref_value_bytes = unsafe {
450            std::slice::from_raw_parts(
451                &self.reference_value as *const <T::SignedIntType as ArrowPrimitiveType>::Native
452                    as *const u8,
453                std::mem::size_of::<<T::SignedIntType as ArrowPrimitiveType>::Native>(),
454            )
455        };
456        result.extend_from_slice(ref_value_bytes);
457
458        let exponents_starting_loc = (result.len() + 7) & !7;
459        // Insert padding before exponents start
460        while result.len() < exponents_starting_loc {
461            result.push(0);
462        }
463
464        let exponent_e_bytes =
465            unsafe { std::slice::from_raw_parts(&self.exponent.e as *const u8, 1) };
466        let exponent_f_bytes =
467            unsafe { std::slice::from_raw_parts(&self.exponent.f as *const u8, 1) };
468        // Write exponents and padding
469        result.extend_from_slice(exponent_e_bytes);
470        result.extend_from_slice(exponent_f_bytes);
471        for _i in 0..6 {
472            result.push(0);
473        }
474
475        // Number of bytes occupied by usize is target-dependent; use u64 instead
476        let patch_length = self.patch_indices.len() as u64;
477
478        let patch_length_bytes = unsafe {
479            std::slice::from_raw_parts(
480                &patch_length as *const u64 as *const u8,
481                std::mem::size_of::<u64>(),
482            )
483        };
484
485        // Write the patch length
486        result.extend_from_slice(patch_length_bytes);
487
488        if !self.patch_indices.is_empty() {
489            let patch_indices_bytes = unsafe {
490                std::slice::from_raw_parts(
491                    self.patch_indices.as_ptr() as *const u8,
492                    std::mem::size_of::<u64>() * self.patch_indices.len(),
493                )
494            };
495
496            // Write the patch indices
497            result.extend_from_slice(patch_indices_bytes);
498
499            // Write the patch values
500            let patch_values_bytes = unsafe {
501                std::slice::from_raw_parts(
502                    self.patch_values.as_ptr() as *const u8,
503                    std::mem::size_of::<T::Native>() * self.patch_indices.len(),
504                )
505            };
506            result.extend_from_slice(patch_values_bytes);
507        }
508        let padding = ((result.len() + 7) & !7) - result.len();
509
510        // Add padding before writing bit-packed array
511        for _i in 0..padding {
512            result.push(0);
513        }
514
515        // Serialize bit-packed values
516        self.bit_packed.to_bytes(&mut result);
517
518        result
519    }
520
521    /// Deserialize a LiquidFloatArray from bytes, using zero-copy where possible.
522    pub fn from_bytes(bytes: Bytes) -> Self {
523        let header = LiquidIPCHeader::from_bytes(&bytes);
524
525        // Verify the type id
526        let physical_id = header.physical_type_id;
527        assert_eq!(physical_id, get_physical_type_id::<T>());
528        let logical_id = header.logical_type_id;
529        assert_eq!(logical_id, LiquidDataType::Float as u16);
530
531        // Get the reference value
532        let ref_value_ptr = &bytes[LiquidIPCHeader::size()];
533        let reference_value = unsafe {
534            (ref_value_ptr as *const u8 as *const <T::SignedIntType as ArrowPrimitiveType>::Native)
535                .read_unaligned()
536        };
537
538        // Read exponents (e, f) & skip padding
539        let mut next = ((LiquidIPCHeader::size()
540            + std::mem::size_of::<<T::SignedIntType as ArrowPrimitiveType>::Native>())
541            + 7)
542            & !7;
543
544        // Read exponent fields (1 byte each) and skip 6 padding bytes
545        let exponent_e = bytes[next];
546        let exponent_f = bytes[next + 1];
547        next += 8;
548
549        // Read patch length (8 bytes)
550        let mut patch_length = 0u64;
551        patch_length |= bytes[next] as u64;
552        patch_length |= (bytes[next + 1] as u64) << 8;
553        patch_length |= (bytes[next + 2] as u64) << 16;
554        patch_length |= (bytes[next + 3] as u64) << 24;
555        patch_length |= (bytes[next + 4] as u64) << 32;
556        patch_length |= (bytes[next + 5] as u64) << 40;
557        patch_length |= (bytes[next + 6] as u64) << 48;
558        patch_length |= (bytes[next + 7] as u64) << 56;
559        next += 8;
560
561        // Read patch indices
562        let mut patch_indices = Vec::new();
563        let mut patch_values = Vec::new();
564        if patch_length > 0 {
565            let count = patch_length as usize;
566            let idx_bytes = count * std::mem::size_of::<u64>();
567            let val_bytes = count * std::mem::size_of::<T::Native>();
568
569            let indices_slice = bytes.slice(next..next + idx_bytes);
570            next += idx_bytes;
571            patch_indices = unsafe {
572                let ptr = indices_slice.as_ptr() as *const u64;
573                std::slice::from_raw_parts(ptr, count).to_vec()
574            };
575
576            let values_slice = bytes.slice(next..next + val_bytes);
577            next += val_bytes;
578            patch_values = unsafe {
579                let ptr = values_slice.as_ptr() as *const T::Native;
580                std::slice::from_raw_parts(ptr, count).to_vec()
581            };
582        }
583
584        // Align up to 8 bytes for bit-packed array
585        next = (next + 7) & !7;
586
587        let bit_packed = BitPackedArray::<T::UnsignedIntType>::from_bytes(bytes.slice(next..));
588
589        Self {
590            exponent: Exponents {
591                e: exponent_e,
592                f: exponent_f,
593            },
594            bit_packed,
595            patch_indices,
596            patch_values,
597            reference_value,
598            squeeze_policy: FloatSqueezePolicy::Quantize,
599        }
600    }
601}
602
603#[derive(Debug, Copy, Clone, PartialEq, Eq)]
604pub struct Exponents {
605    pub(crate) e: u8,
606    pub(crate) f: u8,
607}
608
609fn encode_arrow_array<T: LiquidFloatType>(
610    arrow_array: &PrimitiveArray<T>,
611    exp: &Exponents, // fill_value: &mut Option<<T::UnsignedIntType as ArrowPrimitiveType>::Native>
612) -> LiquidFloatArray<T> {
613    let mut patch_indices: Vec<u64> = Vec::new();
614    let mut patch_values: Vec<T::Native> = Vec::new();
615    let mut patch_count: usize = 0;
616    let mut fill_value: Option<<T::SignedIntType as ArrowPrimitiveType>::Native> = None;
617    let values = arrow_array.values();
618    let nulls = arrow_array.nulls();
619
620    // All values are null
621    if arrow_array.null_count() == arrow_array.len() {
622        return LiquidFloatArray::<T> {
623            bit_packed: BitPackedArray::new_null_array(arrow_array.len()),
624            exponent: Exponents { e: 0, f: 0 },
625            patch_indices: Vec::new(),
626            patch_values: Vec::new(),
627            reference_value: <T::SignedIntType as ArrowPrimitiveType>::Native::ZERO,
628            squeeze_policy: FloatSqueezePolicy::Quantize,
629        };
630    }
631
632    let mut encoded_values = Vec::with_capacity(arrow_array.len());
633    for v in values.iter() {
634        let encoded = T::encode_single_unchecked(&v.as_(), exp);
635        let decoded = T::decode_single(&encoded, exp);
636        // TODO(): Check if this is a bitwise comparison
637        let neq = !decoded.eq(&v.as_()) as usize;
638        patch_count += neq;
639        encoded_values.push(encoded);
640    }
641
642    if patch_count > 0 {
643        patch_indices.resize_with(patch_count + 1, Default::default);
644        patch_values.resize_with(patch_count + 1, Default::default);
645        let mut patch_index: usize = 0;
646
647        for i in 0..encoded_values.len() {
648            let decoded = T::decode_single(&encoded_values[i], exp);
649            patch_indices[patch_index] = i.as_();
650            patch_values[patch_index] = arrow_array.value(i).as_();
651            patch_index += !(decoded.eq(&values[i].as_())) as usize;
652        }
653        assert_eq!(patch_index, patch_count);
654        unsafe {
655            patch_indices.set_len(patch_count);
656            patch_values.set_len(patch_count);
657        }
658    }
659
660    // find the first successfully encoded value (i.e., not patched)
661    // this is our fill value for missing values
662    if patch_count > 0 && patch_count < arrow_array.len() {
663        for i in 0..encoded_values.len() {
664            if i >= patch_indices.len() || patch_indices[i] != i as u64 {
665                fill_value = encoded_values.get(i).copied();
666                break;
667            }
668        }
669    }
670
671    // replace the patched values in the encoded array with the fill value
672    // for better downstream compression
673    if let Some(fill_value) = fill_value {
674        // handle the edge case where the first N >= 1 chunks are all patches
675        for patch_idx in &patch_indices {
676            encoded_values[*patch_idx as usize] = fill_value;
677        }
678    }
679
680    let min = *encoded_values
681        .iter()
682        .min()
683        .expect("`encoded_values` shouldn't be all nulls");
684    let max = *encoded_values
685        .iter()
686        .max()
687        .expect("`encoded_values` shouldn't be all nulls");
688    let sub: <T::UnsignedIntType as ArrowPrimitiveType>::Native = max.sub_wrapping(min).as_();
689
690    let unsigned_encoded_values = encoded_values
691        .iter()
692        .map(|v| {
693            let k: <T::UnsignedIntType as ArrowPrimitiveType>::Native = v.sub_wrapping(min).as_();
694            k
695        })
696        .collect::<Vec<_>>();
697    let encoded_output = PrimitiveArray::<<T as LiquidFloatType>::UnsignedIntType>::new(
698        ScalarBuffer::from(unsigned_encoded_values),
699        nulls.cloned(),
700    );
701
702    let bit_width = get_bit_width(sub.as_());
703    let bit_packed_array = BitPackedArray::from_primitive(encoded_output, bit_width);
704
705    LiquidFloatArray::<T> {
706        bit_packed: bit_packed_array,
707        exponent: *exp,
708        patch_indices,
709        patch_values,
710        reference_value: min,
711        squeeze_policy: FloatSqueezePolicy::Quantize,
712    }
713}
714
715fn get_best_exponents<T: LiquidFloatType>(arrow_array: &PrimitiveArray<T>) -> Exponents {
716    let mut best_exponents = Exponents { e: 0, f: 0 };
717    let mut min_encoded_size: usize = usize::MAX;
718
719    let sample_arrow_array: Option<PrimitiveArray<T>> =
720        (arrow_array.len() > NUM_SAMPLES).then(|| {
721            arrow_array
722                .iter()
723                .step_by(arrow_array.len() / NUM_SAMPLES)
724                .filter(|s| s.is_some())
725                .collect()
726        });
727
728    for e in 0..T::MAX_EXPONENT {
729        for f in 0..e {
730            let exp = Exponents { e, f };
731            let liquid_array =
732                encode_arrow_array(sample_arrow_array.as_ref().unwrap_or(arrow_array), &exp);
733            if liquid_array.get_array_memory_size() < min_encoded_size {
734                best_exponents = exp;
735                min_encoded_size = liquid_array.get_array_memory_size();
736            }
737        }
738    }
739    best_exponents
740}
741
742#[derive(Debug)]
743struct LiquidFloatQuantizedArray<T: LiquidFloatType> {
744    exponent: Exponents,
745    quantized: BitPackedArray<T::UnsignedIntType>,
746    reference_value: <T::SignedIntType as ArrowPrimitiveType>::Native,
747    bucket_width: u8, // Width of each bucket (in bits)
748    disk_range: std::ops::Range<u64>,
749    patch_indices: Vec<u64>,
750    patch_values: Vec<T::Native>,
751}
752
753impl<T> LiquidFloatQuantizedArray<T>
754where
755    T: LiquidFloatType,
756{
757    #[allow(dead_code)]
758    fn as_any(&self) -> &dyn Any {
759        self
760    }
761
762    #[inline]
763    fn len(&self) -> usize {
764        self.quantized.len()
765    }
766
767    fn new_from_filtered(
768        &self,
769        filtered: PrimitiveArray<<T as LiquidFloatType>::UnsignedIntType>,
770    ) -> Self {
771        let bit_width = self
772            .quantized
773            .bit_width()
774            .expect("quantized bit width must exist");
775        let quantized = BitPackedArray::from_primitive(filtered, bit_width);
776        Self {
777            exponent: self.exponent,
778            quantized,
779            reference_value: self.reference_value,
780            bucket_width: self.bucket_width,
781            patch_indices: self.patch_indices.clone(),
782            patch_values: self.patch_values.clone(),
783            disk_range: self.disk_range.clone(),
784        }
785    }
786
787    fn filter_inner(&self, selection: &BooleanBuffer) -> Self {
788        let q_prim: PrimitiveArray<T::UnsignedIntType> = self.quantized.to_primitive();
789        let selection = BooleanArray::new(selection.clone(), None);
790        let filtered = arrow::compute::kernels::filter::filter(&q_prim, &selection).unwrap();
791        let filtered = filtered.as_primitive::<T::UnsignedIntType>().clone();
792        self.new_from_filtered(filtered)
793    }
794
795    #[inline]
796    fn handle_eq(lo: T::Native, hi: T::Native, k: T::Native) -> Option<bool> {
797        if k < lo || k > hi { Some(false) } else { None }
798    }
799
800    #[inline]
801    fn handle_neq(lo: T::Native, hi: T::Native, k: T::Native) -> Option<bool> {
802        if k < lo || k > hi { Some(true) } else { None }
803    }
804
805    #[inline]
806    fn handle_lt(lo: T::Native, hi: T::Native, k: T::Native) -> Option<bool> {
807        if k <= lo {
808            Some(false)
809        } else if hi < k {
810            Some(true)
811        } else {
812            None
813        }
814    }
815
816    #[inline]
817    fn handle_lteq(lo: T::Native, hi: T::Native, k: T::Native) -> Option<bool> {
818        if k < lo {
819            Some(false)
820        } else if hi <= k {
821            Some(true)
822        } else {
823            None
824        }
825    }
826
827    #[inline]
828    fn handle_gt(lo: T::Native, hi: T::Native, k: T::Native) -> Option<bool> {
829        if k < lo {
830            Some(true)
831        } else if hi <= k {
832            Some(false)
833        } else {
834            None
835        }
836    }
837
838    #[inline]
839    fn handle_gteq(lo: T::Native, hi: T::Native, k: T::Native) -> Option<bool> {
840        if k <= lo {
841            Some(true)
842        } else if hi < k {
843            Some(false)
844        } else {
845            None
846        }
847    }
848
849    fn try_eval_predicate_inner(
850        &self,
851        op: &Operator,
852        literal: &Literal,
853    ) -> Result<Option<BooleanArray>, IoRange> {
854        // Extract scalar value as T::Native
855        let k_opt: Option<T::Native> = match literal.value() {
856            ScalarValue::Int8(Some(v)) => T::Native::from_i8(*v),
857            ScalarValue::Int16(Some(v)) => T::Native::from_i16(*v),
858            ScalarValue::Int32(Some(v)) => T::Native::from_i32(*v),
859            ScalarValue::Int64(Some(v)) => T::Native::from_i64(*v),
860            ScalarValue::UInt8(Some(v)) => T::Native::from_u8(*v),
861            ScalarValue::UInt16(Some(v)) => T::Native::from_u16(*v),
862            ScalarValue::UInt32(Some(v)) => T::Native::from_u32(*v),
863            ScalarValue::UInt64(Some(v)) => T::Native::from_u64(*v),
864            ScalarValue::Date32(Some(v)) => T::Native::from_i32(*v),
865            ScalarValue::Date64(Some(v)) => T::Native::from_i64(*v),
866            ScalarValue::Float32(Some(v)) => T::Native::from_f32(*v),
867            ScalarValue::Float64(Some(v)) => T::Native::from_f64(*v),
868            _ => None,
869        };
870        let Some(k) = k_opt else { return Ok(None) };
871        let q_prim = self.quantized.to_primitive();
872        let (_dt, values, _nulls) = q_prim.into_parts();
873
874        let mut out_vals: Vec<bool> = Vec::with_capacity(values.len());
875        let mut next_patch_index = 0;
876        let mut ignore_patches = false;
877        if self.patch_indices.is_empty() {
878            ignore_patches = true;
879        }
880        let comp_fn = match op {
881            Operator::Eq => Self::handle_eq,
882            Operator::NotEq => Self::handle_neq,
883            Operator::Lt => Self::handle_lt,
884            Operator::LtEq => Self::handle_lteq,
885            Operator::Gt => Self::handle_gt,
886            Operator::GtEq => Self::handle_gteq,
887        };
888        // TODO(): This might not be very vectorization-friendly right now. Figure out optimizations
889        for (i, &b) in values.iter().enumerate() {
890            if let Some(nulls) = self.quantized.nulls()
891                && !nulls.is_valid(i)
892            {
893                out_vals.push(false);
894                continue;
895            }
896            if !ignore_patches && i as u64 == self.patch_indices[next_patch_index] {
897                next_patch_index += 1;
898                if next_patch_index == self.patch_indices.len() {
899                    ignore_patches = true;
900                }
901                out_vals.push(false);
902                continue;
903            }
904
905            let val: <T::SignedIntType as ArrowPrimitiveType>::Native = b.as_();
906            let lo = (val << self.bucket_width).add_wrapping(self.reference_value);
907            let hi = ((val.add_wrapping(1i32.into())) << self.bucket_width)
908                .add_wrapping(self.reference_value);
909            let val_lower = T::decode_single(&lo, &self.exponent);
910            let val_higher = T::decode_single(&hi, &self.exponent);
911
912            let decided = comp_fn(val_lower, val_higher, k);
913            if let Some(v) = decided {
914                out_vals.push(v);
915            } else {
916                return Err(IoRange {
917                    range: self.disk_range.clone(),
918                });
919            }
920        }
921
922        // Handle patches separately
923        // TODO(): Vectorize this
924        for (idx, patch_idx) in self.patch_indices.iter().enumerate() {
925            let patch_value = self.patch_values[idx];
926            out_vals[*patch_idx as usize] = match op {
927                Operator::Eq => patch_value == k,
928                Operator::NotEq => patch_value != k,
929                Operator::Lt => patch_value < k,
930                Operator::LtEq => patch_value <= k,
931                Operator::Gt => patch_value > k,
932                Operator::GtEq => patch_value >= k,
933            }
934        }
935
936        let bool_buf = arrow::buffer::BooleanBuffer::from_iter(out_vals);
937        let out = BooleanArray::new(bool_buf, self.quantized.nulls().cloned());
938        Ok(Some(out))
939    }
940}
941
942impl<T> LiquidHybridArray for LiquidFloatQuantizedArray<T>
943where
944    T: LiquidFloatType,
945{
946    fn as_any(&self) -> &dyn Any {
947        self
948    }
949
950    fn get_array_memory_size(&self) -> usize {
951        self.quantized.get_array_memory_size()
952            + size_of::<Exponents>()
953            + self.patch_indices.capacity() * size_of::<u64>()
954            + self.patch_values.capacity() * size_of::<T::Native>()
955            + size_of::<<T::SignedIntType as ArrowPrimitiveType>::Native>()
956    }
957
958    fn len(&self) -> usize {
959        LiquidFloatQuantizedArray::<T>::len(self)
960    }
961
962    fn to_arrow_array(&self) -> Result<ArrayRef, super::IoRange> {
963        Err(IoRange {
964            range: self.disk_range.clone(),
965        })
966    }
967
968    fn data_type(&self) -> LiquidDataType {
969        LiquidDataType::Float
970    }
971
972    fn original_arrow_data_type(&self) -> DataType {
973        T::DATA_TYPE.clone()
974    }
975
976    fn to_bytes(&self) -> Result<Vec<u8>, super::IoRange> {
977        Err(IoRange {
978            range: self.disk_range.clone(),
979        })
980    }
981
982    fn filter(&self, selection: &BooleanBuffer) -> Result<LiquidHybridArrayRef, super::IoRange> {
983        let filtered = self.filter_inner(selection);
984        Ok(Arc::new(filtered) as LiquidHybridArrayRef)
985    }
986
987    fn soak(&self, data: bytes::Bytes) -> LiquidArrayRef {
988        // `data` is the full IPC payload for primitive array
989        let arr = LiquidFloatArray::<T>::from_bytes(data);
990        Arc::new(arr)
991    }
992
993    fn to_liquid(&self) -> super::IoRange {
994        IoRange {
995            range: self.disk_range.clone(),
996        }
997    }
998
999    fn try_eval_predicate(
1000        &self,
1001        expr: &Arc<dyn PhysicalExpr>,
1002        filter: &BooleanBuffer,
1003    ) -> Result<Option<BooleanArray>, IoRange> {
1004        // Apply selection first to reduce input rows
1005        let filtered = self.filter_inner(filter);
1006
1007        if let Some(binary_expr) = expr.as_any().downcast_ref::<BinaryExpr>()
1008            && let Some(literal) = binary_expr.right().as_any().downcast_ref::<Literal>()
1009        {
1010            let op = binary_expr.op();
1011            let supported_op = Operator::from_datafusion(op);
1012            if let Some(supported_op) = supported_op {
1013                return filtered.try_eval_predicate_inner(&supported_op, literal);
1014            }
1015        }
1016        Ok(None)
1017    }
1018}
1019
1020#[cfg(test)]
1021mod tests {
1022    use datafusion::logical_expr::Operator;
1023    use rand::{Rng as _, SeedableRng as _, distr::uniform::SampleUniform, rngs::StdRng};
1024
1025    use super::*;
1026    macro_rules! test_roundtrip {
1027        ($test_name: ident, $type:ty, $values: expr) => {
1028            #[test]
1029            fn $test_name() {
1030                let original: Vec<Option<<$type as ArrowPrimitiveType>::Native>> = $values;
1031                let array = PrimitiveArray::<$type>::from(original.clone());
1032
1033                // Convert to Liquid array and back
1034                let liquid_array = LiquidFloatArray::<$type>::from_arrow_array(array.clone());
1035                let result_array = liquid_array.to_arrow_array();
1036                let bytes_array =
1037                    LiquidFloatArray::<$type>::from_bytes(liquid_array.to_bytes().into());
1038
1039                assert_eq!(result_array.as_ref(), &array);
1040                assert_eq!(bytes_array.to_arrow_array().as_ref(), &array);
1041            }
1042        };
1043    }
1044
1045    // Test cases for Float32
1046    test_roundtrip!(
1047        test_float32_roundtrip_basic,
1048        Float32Type,
1049        vec![Some(-1.0), Some(1.0), Some(0.0)]
1050    );
1051
1052    test_roundtrip!(
1053        test_float32_roundtrip_with_nones,
1054        Float32Type,
1055        vec![Some(-1.0), Some(1.0), Some(0.0), None]
1056    );
1057
1058    test_roundtrip!(
1059        test_float32_roundtrip_all_nones,
1060        Float32Type,
1061        vec![None, None, None, None]
1062    );
1063
1064    test_roundtrip!(test_float32_roundtrip_empty, Float32Type, vec![]);
1065
1066    // Test cases for Float64
1067    test_roundtrip!(
1068        test_float64_roundtrip_basic,
1069        Float64Type,
1070        vec![Some(-1.0), Some(1.0), Some(0.0)]
1071    );
1072
1073    test_roundtrip!(
1074        test_float64_roundtrip_with_nones,
1075        Float64Type,
1076        vec![Some(-1.0), Some(1.0), Some(0.0), None]
1077    );
1078
1079    test_roundtrip!(
1080        test_float64_roundtrip_all_nones,
1081        Float64Type,
1082        vec![None, None, None, None]
1083    );
1084
1085    test_roundtrip!(test_float64_roundtrip_empty, Float64Type, vec![]);
1086
1087    // Tests with ilters
1088    #[test]
1089    fn test_filter_basic() {
1090        // Create original array with some values
1091        let original = vec![Some(1.0), Some(2.1), Some(3.2), None, Some(5.5)];
1092        let array = PrimitiveArray::<Float32Type>::from(original);
1093        let liquid_array = LiquidFloatArray::<Float32Type>::from_arrow_array(array);
1094
1095        // Create selection mask: keep indices 0, 2, and 4
1096        let selection = BooleanBuffer::from(vec![true, false, true, false, true]);
1097
1098        // Apply filter
1099        let filtered = liquid_array.filter(&selection);
1100        let result_array = filtered.to_arrow_array();
1101
1102        // Expected result after filtering
1103        let expected = PrimitiveArray::<Float32Type>::from(vec![Some(1.0), Some(3.2), Some(5.5)]);
1104
1105        assert_eq!(result_array.as_ref(), &expected);
1106    }
1107
1108    #[test]
1109    fn test_original_arrow_data_type_returns_float32() {
1110        let array = PrimitiveArray::<Float32Type>::from(vec![Some(1.0), Some(2.5)]);
1111        let liquid = LiquidFloatArray::<Float32Type>::from_arrow_array(array);
1112        assert_eq!(liquid.original_arrow_data_type(), DataType::Float32);
1113    }
1114
1115    #[test]
1116    fn test_filter_all_nulls() {
1117        // Create array with all nulls
1118        let original = vec![None, None, None, None];
1119        let array = PrimitiveArray::<Float32Type>::from(original);
1120        let liquid_array = LiquidFloatArray::<Float32Type>::from_arrow_array(array);
1121
1122        // Keep first and last elements
1123        let selection = BooleanBuffer::from(vec![true, false, false, true]);
1124
1125        let filtered = liquid_array.filter(&selection);
1126        let result_array = filtered.to_arrow_array();
1127
1128        let expected = PrimitiveArray::<Float32Type>::from(vec![None, None]);
1129
1130        assert_eq!(result_array.as_ref(), &expected);
1131    }
1132
1133    #[test]
1134    fn test_filter_empty_result() {
1135        let original = vec![Some(1.0), Some(2.1), Some(3.3)];
1136        let array = PrimitiveArray::<Float32Type>::from(original);
1137        let liquid_array = LiquidFloatArray::<Float32Type>::from_arrow_array(array);
1138
1139        // Filter out all elements
1140        let selection = BooleanBuffer::from(vec![false, false, false]);
1141
1142        let filtered = liquid_array.filter(&selection);
1143        let result_array = filtered.to_arrow_array();
1144
1145        assert_eq!(result_array.len(), 0);
1146    }
1147
1148    #[test]
1149    fn test_compression_f32_f64() {
1150        fn run_compression_test<T: LiquidFloatType>(
1151            type_name: &str,
1152            data_fn: impl Fn(usize) -> T::Native,
1153        ) {
1154            let original: Vec<T::Native> = (0..2000).map(data_fn).collect();
1155            let array = PrimitiveArray::<T>::from_iter_values(original);
1156            let uncompressed_size = array.get_array_memory_size();
1157
1158            let liquid_array = LiquidFloatArray::<T>::from_arrow_array(array);
1159            let compressed_size = liquid_array.get_array_memory_size();
1160
1161            println!(
1162                "Type: {type_name}, uncompressed_size: {uncompressed_size}, compressed_size: {compressed_size}"
1163            );
1164            // Assert that compression actually reduced the size
1165            assert!(
1166                compressed_size < uncompressed_size,
1167                "{type_name} compression failed to reduce size"
1168            );
1169        }
1170
1171        // Run for f32
1172        run_compression_test::<Float32Type>("f32", |i| i as f32);
1173
1174        // Run for f64
1175        run_compression_test::<Float64Type>("f64", |i| i as f64);
1176    }
1177
1178    //  --------- Hybrid (squeeze) tests ----------
1179    fn make_f_array_with_range<T>(
1180        len: usize,
1181        base_min: T::Native,
1182        range: T::Native,
1183        null_prob: f32,
1184        rng: &mut StdRng,
1185    ) -> PrimitiveArray<T>
1186    where
1187        T: LiquidFloatType,
1188        <T as arrow::array::ArrowPrimitiveType>::Native: SampleUniform,
1189        PrimitiveArray<T>: From<Vec<Option<<T as ArrowPrimitiveType>::Native>>>,
1190    {
1191        let mut vals: Vec<Option<T::Native>> = Vec::with_capacity(len);
1192        for _ in 0..len {
1193            if rng.random_bool(null_prob as f64) {
1194                vals.push(None);
1195            } else {
1196                vals.push(Some(rng.random_range(base_min..(base_min + range))));
1197            }
1198        }
1199        PrimitiveArray::<T>::from(vals)
1200    }
1201
1202    #[test]
1203    fn hybrid_squeeze_unsqueezable_small_range() {
1204        let mut rng = StdRng::seed_from_u64(0x51_71);
1205        let arr = make_f_array_with_range::<Float32Type>(64, 10_000.0, 100.0, 0.1, &mut rng);
1206        let liquid = LiquidFloatArray::<Float32Type>::from_arrow_array(arr);
1207        assert!(liquid.squeeze().is_none());
1208    }
1209
1210    #[test]
1211    fn hybrid_squeeze_and_soak_roundtrip_f32() {
1212        let mut rng = StdRng::seed_from_u64(0x51_72);
1213        let arr = make_f_array_with_range::<Float32Type>(
1214            2000,
1215            -50_000.0,
1216            (1 << 16) as f32,
1217            0.1,
1218            &mut rng,
1219        );
1220        let liq = LiquidFloatArray::<Float32Type>::from_arrow_array(arr.clone());
1221        let bytes_baseline = liq.to_bytes();
1222        let (hybrid, bytes) = liq.squeeze().expect("squeezable");
1223        // ensure we can recover the original using soak
1224        let recovered = hybrid.soak(bytes.clone());
1225        assert_eq!(
1226            recovered.to_arrow_array().as_primitive::<Float32Type>(),
1227            &arr
1228        );
1229        assert_eq!(bytes_baseline, recovered.to_bytes());
1230
1231        let min = arrow::compute::kernels::aggregate::min(&arr).unwrap();
1232        let mask = BooleanBuffer::from(vec![true; arr.len()]);
1233        let build_expr =
1234            |op: Operator, k: f32| -> Arc<dyn datafusion::physical_plan::PhysicalExpr> {
1235                let lit = Arc::new(Literal::new(ScalarValue::Float32(Some(k))));
1236                Arc::new(BinaryExpr::new(lit.clone(), op, lit))
1237            };
1238
1239        // Expect resolvable results without IO
1240        let resolvable_cases: Vec<(Operator, f32, bool)> = vec![
1241            (Operator::Eq, min - 1.0, false),   // eq false everywhere
1242            (Operator::NotEq, min - 1.0, true), // neq true everywhere
1243            (Operator::Lt, min, false),         // lt false everywhere
1244            (Operator::LtEq, min - 1.0, false), // lte false everywhere
1245            (Operator::Gt, min - 1.0, true),    // gt true everywhere
1246            (Operator::GtEq, min, true),        // gte true everywhere
1247        ];
1248
1249        for (op, k, expected_const) in resolvable_cases {
1250            let expr = build_expr(op, k);
1251            let got = hybrid.try_eval_predicate(&expr, &mask).expect("no IO");
1252            let expected = {
1253                let vals: Vec<Option<bool>> = (0..arr.len())
1254                    .map(|i| {
1255                        if arr.is_null(i) {
1256                            None
1257                        } else {
1258                            Some(expected_const)
1259                        }
1260                    })
1261                    .collect();
1262                BooleanArray::from(vals)
1263            };
1264            assert_eq!(got.unwrap(), expected);
1265        }
1266
1267        // Unresolvable for Eq: pick a present value (ensures ambiguous bucket)
1268        let k_present = (0..arr.len())
1269            .find_map(|i| {
1270                if arr.is_null(i) {
1271                    None
1272                } else {
1273                    Some(arr.value(i))
1274                }
1275            })
1276            .unwrap();
1277        let expr_eq_present = build_expr(Operator::Eq, k_present);
1278        let err = hybrid
1279            .try_eval_predicate(&expr_eq_present, &mask)
1280            .expect_err("quantized should request IO on ambiguous eq bucket");
1281        assert_eq!(err.range(), hybrid.to_liquid().range());
1282    }
1283
1284    #[test]
1285    fn hybrid_squeeze_and_soak_roundtrip_f64() {
1286        let mut rng = StdRng::seed_from_u64(0x51_72);
1287        let arr = make_f_array_with_range::<Float64Type>(
1288            2000,
1289            -50_000.0f64,
1290            (1 << 16) as f64,
1291            0.1,
1292            &mut rng,
1293        );
1294        let liq = LiquidFloatArray::<Float64Type>::from_arrow_array(arr.clone());
1295        let bytes_baseline = liq.to_bytes();
1296        let (hybrid, bytes) = liq.squeeze().expect("squeezable");
1297        // ensure we can recover the original using soak
1298        let recovered = hybrid.soak(bytes.clone());
1299        assert_eq!(
1300            recovered.to_arrow_array().as_primitive::<Float64Type>(),
1301            &arr
1302        );
1303        assert_eq!(bytes_baseline, recovered.to_bytes());
1304
1305        let min = arrow::compute::kernels::aggregate::min(&arr).unwrap();
1306        let mask = BooleanBuffer::from(vec![true; arr.len()]);
1307        let build_expr =
1308            |op: Operator, k: f64| -> Arc<dyn datafusion::physical_plan::PhysicalExpr> {
1309                let lit = Arc::new(Literal::new(ScalarValue::Float64(Some(k))));
1310                Arc::new(BinaryExpr::new(lit.clone(), op, lit))
1311            };
1312
1313        // Expect resolvable results without IO
1314        let resolvable_cases: Vec<(Operator, f64, bool)> = vec![
1315            (Operator::Eq, min - 1.0, false),   // eq false everywhere
1316            (Operator::NotEq, min - 1.0, true), // neq true everywhere
1317            (Operator::Lt, min, false),         // lt false everywhere
1318            (Operator::LtEq, min - 1.0, false), // lte false everywhere
1319            (Operator::Gt, min - 1.0, true),    // gt true everywhere
1320            (Operator::GtEq, min, true),        // gte true everywhere
1321        ];
1322
1323        for (op, k, expected_const) in resolvable_cases {
1324            let expr = build_expr(op, k);
1325            let got = hybrid.try_eval_predicate(&expr, &mask).expect("no IO");
1326            let expected = {
1327                let vals: Vec<Option<bool>> = (0..arr.len())
1328                    .map(|i| {
1329                        if arr.is_null(i) {
1330                            None
1331                        } else {
1332                            Some(expected_const)
1333                        }
1334                    })
1335                    .collect();
1336                BooleanArray::from(vals)
1337            };
1338            assert_eq!(got.unwrap(), expected);
1339        }
1340
1341        // Unresolvable for Eq: pick a present value (ensures ambiguous bucket)
1342        let k_present = (0..arr.len())
1343            .find_map(|i| {
1344                if arr.is_null(i) {
1345                    None
1346                } else {
1347                    Some(arr.value(i))
1348                }
1349            })
1350            .unwrap();
1351        let expr_eq_present = build_expr(Operator::Eq, k_present);
1352        let err = hybrid
1353            .try_eval_predicate(&expr_eq_present, &mask)
1354            .expect_err("quantized should request IO on ambiguous eq bucket");
1355        assert_eq!(err.range(), hybrid.to_liquid().range());
1356    }
1357}