Skip to main content

liquid_cache_storage/liquid_array/
ipc.rs

1//! IPC for liquid array.
2
3use std::sync::Arc;
4use std::{any::TypeId, mem::size_of};
5
6use arrow::array::ArrowPrimitiveType;
7use arrow::datatypes::{
8    Date32Type, Date64Type, Float32Type, Float64Type, Int8Type, Int16Type, Int32Type, Int64Type,
9    UInt8Type, UInt16Type, UInt32Type, UInt64Type,
10};
11use bytes::Bytes;
12use fsst::Compressor;
13
14use crate::liquid_array::LiquidByteViewArray;
15use crate::liquid_array::LiquidPrimitiveArray;
16use crate::liquid_array::byte_view_array::MemoryBuffer;
17
18use super::linear_integer_array::LiquidLinearArray;
19use super::{
20    LiquidArrayRef, LiquidByteArray, LiquidDataType, LiquidFixedLenByteArray, LiquidFloatArray,
21};
22
23const MAGIC: u32 = 0x4C51_4441; // "LQDA" for LiQuid Data Array
24const VERSION: u16 = 1;
25
26/*
27    +--------------------------------------------------+
28    | LiquidIPCHeader (16 bytes)                       |
29    +--------------------------------------------------+
30    | MAGIC (4 bytes)                                  |  // Offset  0..3: "LQDA" magic number (0x4C51_4441)
31    +--------------------------------------------------+
32    | VERSION (2 bytes)                                |  // Offset  4..5: Version (currently 1)
33    +--------------------------------------------------+
34    | logical_type_id (2 bytes)                        |  // Offset  6..7: Logical type identifier (e.g. Integer)
35    +--------------------------------------------------+
36    | physical_type_id (2 bytes)                       |  // Offset  8..9: Physical type identifier for T
37    +--------------------------------------------------+
38    | __padding (6 bytes)                              |  // Offset 10..15: Padding to ensure 16 byte header
39    +--------------------------------------------------+
40*/
41#[repr(C)]
42pub(super) struct LiquidIPCHeader {
43    pub(super) magic: [u8; 4],
44    pub(super) version: u16,
45    pub(super) logical_type_id: u16,
46    pub(super) physical_type_id: u16,
47    pub(super) __padding: [u8; 6],
48}
49
50const _: () = assert!(size_of::<LiquidIPCHeader>() == LiquidIPCHeader::size());
51
52impl LiquidIPCHeader {
53    pub(super) const fn size() -> usize {
54        16
55    }
56
57    pub(super) fn new(logical_type_id: u16, physical_type_id: u16) -> Self {
58        Self {
59            magic: MAGIC.to_le_bytes(),
60            version: VERSION,
61            logical_type_id,
62            physical_type_id,
63            __padding: [0; 6],
64        }
65    }
66
67    pub(super) fn to_bytes(&self) -> [u8; Self::size()] {
68        let mut bytes = [0; Self::size()];
69        bytes[0..4].copy_from_slice(&self.magic);
70        bytes[4..6].copy_from_slice(&self.version.to_le_bytes());
71        bytes[6..8].copy_from_slice(&self.logical_type_id.to_le_bytes());
72        bytes[8..10].copy_from_slice(&self.physical_type_id.to_le_bytes());
73        bytes
74    }
75
76    pub(super) fn from_bytes(bytes: &[u8]) -> Self {
77        if bytes.len() < Self::size() {
78            panic!(
79                "value too small for LiquidIPCHeader, expected at least {} bytes, got {}",
80                Self::size(),
81                bytes.len()
82            );
83        }
84        let magic = bytes[0..4].try_into().unwrap();
85        let version = u16::from_le_bytes(bytes[4..6].try_into().unwrap());
86        let logical_type_id = u16::from_le_bytes(bytes[6..8].try_into().unwrap());
87        let physical_type_id = u16::from_le_bytes(bytes[8..10].try_into().unwrap());
88
89        if magic != MAGIC.to_le_bytes() {
90            panic!("Invalid magic number");
91        }
92        if version != VERSION {
93            panic!("Unsupported version");
94        }
95
96        Self {
97            magic,
98            version,
99            logical_type_id,
100            physical_type_id,
101            __padding: [0; 6],
102        }
103    }
104}
105
106/// Context for liquid IPC.
107pub struct LiquidIPCContext {
108    compressor: Option<Arc<Compressor>>,
109}
110
111impl LiquidIPCContext {
112    /// Create a new instance of LiquidIPCContext.
113    pub fn new(compressor: Option<Arc<Compressor>>) -> Self {
114        Self { compressor }
115    }
116}
117
118/// Read a liquid array from bytes.
119pub fn read_from_bytes(bytes: Bytes, context: &LiquidIPCContext) -> LiquidArrayRef {
120    let header = LiquidIPCHeader::from_bytes(&bytes);
121    let logical_type = LiquidDataType::from(header.logical_type_id);
122    match logical_type {
123        LiquidDataType::Integer => match header.physical_type_id {
124            0 => Arc::new(LiquidPrimitiveArray::<Int8Type>::from_bytes(bytes)),
125            1 => Arc::new(LiquidPrimitiveArray::<Int16Type>::from_bytes(bytes)),
126            2 => Arc::new(LiquidPrimitiveArray::<Int32Type>::from_bytes(bytes)),
127            3 => Arc::new(LiquidPrimitiveArray::<Int64Type>::from_bytes(bytes)),
128            4 => Arc::new(LiquidPrimitiveArray::<UInt8Type>::from_bytes(bytes)),
129            5 => Arc::new(LiquidPrimitiveArray::<UInt16Type>::from_bytes(bytes)),
130            6 => Arc::new(LiquidPrimitiveArray::<UInt32Type>::from_bytes(bytes)),
131            7 => Arc::new(LiquidPrimitiveArray::<UInt64Type>::from_bytes(bytes)),
132            10 => Arc::new(LiquidPrimitiveArray::<Date32Type>::from_bytes(bytes)),
133            11 => Arc::new(LiquidPrimitiveArray::<Date64Type>::from_bytes(bytes)),
134            v => panic!("Unsupported integer physical type: {v}"),
135        },
136        LiquidDataType::ByteArray => {
137            let compressor = context.compressor.as_ref().expect("Expected a compressor");
138            Arc::new(LiquidByteArray::from_bytes(bytes, compressor.clone()))
139        }
140        LiquidDataType::ByteViewArray => {
141            let compressor = context.compressor.as_ref().expect("Expected a compressor");
142            Arc::new(LiquidByteViewArray::<MemoryBuffer>::from_bytes(
143                bytes,
144                compressor.clone(),
145            ))
146        }
147        LiquidDataType::Float => match header.physical_type_id {
148            8 => Arc::new(LiquidFloatArray::<Float32Type>::from_bytes(bytes)),
149            9 => Arc::new(LiquidFloatArray::<Float64Type>::from_bytes(bytes)),
150            v => panic!("Unsupported float physical type: {v}"),
151        },
152        LiquidDataType::FixedLenByteArray => {
153            let compressor = context.compressor.as_ref().expect("Expected a compressor");
154            Arc::new(LiquidFixedLenByteArray::from_bytes(
155                bytes,
156                compressor.clone(),
157            ))
158        }
159        LiquidDataType::LinearInteger => match header.physical_type_id {
160            0 => Arc::new(LiquidLinearArray::<Int8Type>::from_bytes(bytes)),
161            1 => Arc::new(LiquidLinearArray::<Int16Type>::from_bytes(bytes)),
162            2 => Arc::new(LiquidLinearArray::<Int32Type>::from_bytes(bytes)),
163            3 => Arc::new(LiquidLinearArray::<Int64Type>::from_bytes(bytes)),
164            4 => Arc::new(LiquidLinearArray::<UInt8Type>::from_bytes(bytes)),
165            5 => Arc::new(LiquidLinearArray::<UInt16Type>::from_bytes(bytes)),
166            6 => Arc::new(LiquidLinearArray::<UInt32Type>::from_bytes(bytes)),
167            7 => Arc::new(LiquidLinearArray::<UInt64Type>::from_bytes(bytes)),
168            10 => Arc::new(LiquidLinearArray::<Date32Type>::from_bytes(bytes)),
169            11 => Arc::new(LiquidLinearArray::<Date64Type>::from_bytes(bytes)),
170            v => panic!("Unsupported linear-integer physical type: {v}"),
171        },
172    }
173}
174
175pub(super) fn get_physical_type_id<T: ArrowPrimitiveType>() -> u16 {
176    match TypeId::of::<T>() {
177        id if id == TypeId::of::<arrow::datatypes::Int8Type>() => 0,
178        id if id == TypeId::of::<arrow::datatypes::Int16Type>() => 1,
179        id if id == TypeId::of::<arrow::datatypes::Int32Type>() => 2,
180        id if id == TypeId::of::<arrow::datatypes::Int64Type>() => 3,
181        id if id == TypeId::of::<arrow::datatypes::UInt8Type>() => 4,
182        id if id == TypeId::of::<arrow::datatypes::UInt16Type>() => 5,
183        id if id == TypeId::of::<arrow::datatypes::UInt32Type>() => 6,
184        id if id == TypeId::of::<arrow::datatypes::UInt64Type>() => 7,
185        id if id == TypeId::of::<arrow::datatypes::Float32Type>() => 8,
186        id if id == TypeId::of::<arrow::datatypes::Float64Type>() => 9,
187        id if id == TypeId::of::<arrow::datatypes::Date32Type>() => 10,
188        id if id == TypeId::of::<arrow::datatypes::Date64Type>() => 11,
189        _ => panic!("Unsupported primitive type: {}", T::DATA_TYPE),
190    }
191}
192
193#[cfg(test)]
194mod tests {
195    use arrow::{
196        array::{AsArray, BinaryViewArray, PrimitiveArray, StringArray},
197        datatypes::{Decimal128Type, Decimal256Type, DecimalType, Int32Type, i256},
198    };
199    use arrow_schema::DataType;
200
201    use crate::liquid_array::raw::FsstArray;
202    use crate::liquid_array::{LiquidArray, utils::gen_test_decimal_array};
203
204    use super::*;
205
206    #[test]
207    fn test_to_bytes() {
208        // Create a simple array
209        let original: Vec<Option<i32>> = vec![Some(10), Some(20), Some(30), None, Some(50)];
210        let array = PrimitiveArray::<Int32Type>::from(original.clone());
211        let liquid_array = LiquidPrimitiveArray::<Int32Type>::from_arrow_array(array);
212
213        // Serialize to bytes
214        let bytes = liquid_array.to_bytes_inner();
215
216        // Basic validation
217        let header = LiquidIPCHeader::from_bytes(&bytes);
218        assert_eq!(
219            header.magic,
220            MAGIC.to_le_bytes(),
221            "Magic number should be LQDA"
222        );
223        assert_eq!(header.version, VERSION, "Version should be 1");
224        assert_eq!(
225            header.physical_type_id, 2,
226            "Type ID for Int32Type should be 2"
227        );
228        assert_eq!(
229            header.logical_type_id,
230            LiquidDataType::Integer as u16,
231            "Logical type ID should be 1"
232        );
233
234        // Check that the total size makes sense (we can't predict the exact size without knowing bit_width)
235        assert!(
236            bytes.len() > 100,
237            "Serialized data should have a reasonable size"
238        );
239    }
240
241    #[test]
242    fn test_roundtrip_bytes() {
243        let original: Vec<Option<i32>> = vec![Some(10), Some(20), Some(30), None, Some(50)];
244        let array = PrimitiveArray::<Int32Type>::from(original.clone());
245        let liquid_array = LiquidPrimitiveArray::<Int32Type>::from_arrow_array(array.clone());
246
247        let bytes = liquid_array.to_bytes_inner();
248        let bytes = Bytes::from(bytes);
249
250        let deserialized_array = LiquidPrimitiveArray::<Int32Type>::from_bytes(bytes);
251
252        let result_array = deserialized_array.to_arrow_array();
253
254        assert_eq!(result_array.as_ref(), &array);
255    }
256
257    #[test]
258    fn test_roundtrip_edge_cases() {
259        // Test various edge cases
260
261        // 1. All nulls array
262        let all_nulls: Vec<Option<i32>> = vec![None; 1000];
263        let array = PrimitiveArray::<Int32Type>::from(all_nulls);
264        let liquid_array = LiquidPrimitiveArray::<Int32Type>::from_arrow_array(array.clone());
265        let bytes = liquid_array.to_bytes_inner();
266        let bytes = Bytes::from(bytes);
267        let deserialized = LiquidPrimitiveArray::<Int32Type>::from_bytes(bytes);
268        let result = deserialized.to_arrow_array();
269        assert_eq!(result.as_ref(), &array);
270
271        // 2. No nulls array
272        let no_nulls: Vec<Option<i32>> = (0..1000).map(Some).collect();
273        let array = PrimitiveArray::<Int32Type>::from(no_nulls);
274        let liquid_array = LiquidPrimitiveArray::<Int32Type>::from_arrow_array(array.clone());
275        let bytes = liquid_array.to_bytes_inner();
276        let bytes = Bytes::from(bytes);
277        let deserialized = LiquidPrimitiveArray::<Int32Type>::from_bytes(bytes);
278        let result = deserialized.to_arrow_array();
279        assert_eq!(result.as_ref(), &array);
280
281        // 3. Single value array
282        let single_value: Vec<Option<i32>> = vec![Some(42)];
283        let array = PrimitiveArray::<Int32Type>::from(single_value);
284        let liquid_array = LiquidPrimitiveArray::<Int32Type>::from_arrow_array(array.clone());
285        let bytes = liquid_array.to_bytes_inner();
286        let bytes = Bytes::from(bytes);
287        let deserialized = LiquidPrimitiveArray::<Int32Type>::from_bytes(bytes);
288        let result = deserialized.to_arrow_array();
289        assert_eq!(result.as_ref(), &array);
290
291        // 4. Empty array
292        let empty: Vec<Option<i32>> = vec![];
293        let array = PrimitiveArray::<Int32Type>::from(empty);
294        let liquid_array = LiquidPrimitiveArray::<Int32Type>::from_arrow_array(array.clone());
295        let bytes = liquid_array.to_bytes_inner();
296        let bytes = Bytes::from(bytes);
297        let deserialized = LiquidPrimitiveArray::<Int32Type>::from_bytes(bytes);
298        let result = deserialized.to_arrow_array();
299        assert_eq!(result.as_ref(), &array);
300
301        // 5. Large array with very sparse nulls
302        let sparse_nulls: Vec<Option<i32>> = (0..10_000)
303            .map(|i| {
304                if i == 1000 || i == 5000 || i == 9000 {
305                    None
306                } else {
307                    Some(i)
308                }
309            })
310            .collect();
311        let array = PrimitiveArray::<Int32Type>::from(sparse_nulls);
312        let liquid_array = LiquidPrimitiveArray::<Int32Type>::from_arrow_array(array.clone());
313        let bytes = liquid_array.to_bytes_inner();
314        let bytes = Bytes::from(bytes);
315        let deserialized = LiquidPrimitiveArray::<Int32Type>::from_bytes(bytes);
316        let result = deserialized.to_arrow_array();
317        assert_eq!(result.as_ref(), &array);
318    }
319
320    #[test]
321    fn test_roundtrip_multiple_data_types() {
322        use arrow::datatypes::{Int16Type, UInt32Type, UInt64Type};
323
324        // Test with Int16Type
325        let i16_values: Vec<Option<i16>> = (0..2000)
326            .map(|i| {
327                if i % 11 == 0 {
328                    None
329                } else {
330                    Some((i % 300 - 150) as i16)
331                }
332            })
333            .collect();
334        let array = PrimitiveArray::<Int16Type>::from(i16_values);
335        let liquid_array = LiquidPrimitiveArray::<Int16Type>::from_arrow_array(array.clone());
336        let bytes = liquid_array.to_bytes_inner();
337        let bytes = Bytes::from(bytes);
338        let deserialized = LiquidPrimitiveArray::<Int16Type>::from_bytes(bytes);
339        let result = deserialized.to_arrow_array();
340        assert_eq!(result.as_ref(), &array);
341
342        // Test with UInt32Type
343        let u32_values: Vec<Option<u32>> = (0..2000)
344            .map(|i| {
345                if i % 13 == 0 {
346                    None
347                } else {
348                    Some(i as u32 * 10000)
349                }
350            })
351            .collect();
352        let array = PrimitiveArray::<UInt32Type>::from(u32_values);
353        let liquid_array = LiquidPrimitiveArray::<UInt32Type>::from_arrow_array(array.clone());
354        let bytes = liquid_array.to_bytes_inner();
355        let bytes = Bytes::from(bytes);
356        let deserialized = LiquidPrimitiveArray::<UInt32Type>::from_bytes(bytes);
357        let result = deserialized.to_arrow_array();
358        assert_eq!(result.as_ref(), &array);
359
360        // Test with UInt64Type
361        let u64_values: Vec<Option<u64>> = (0..2000)
362            .map(|i| {
363                if i % 17 == 0 {
364                    None
365                } else {
366                    Some(u64::MAX - (i as u64 * 1000000))
367                }
368            })
369            .collect();
370        let array = PrimitiveArray::<UInt64Type>::from(u64_values);
371        let liquid_array = LiquidPrimitiveArray::<UInt64Type>::from_arrow_array(array.clone());
372        let bytes = liquid_array.to_bytes_inner();
373        let bytes = Bytes::from(bytes);
374        let deserialized = LiquidPrimitiveArray::<UInt64Type>::from_bytes(bytes);
375        let result = deserialized.to_arrow_array();
376        assert_eq!(result.as_ref(), &array);
377    }
378
379    #[test]
380    fn test_date_types_ipc_roundtrip() {
381        // Test Date32Type
382        let date32_array = PrimitiveArray::<Date32Type>::from(vec![Some(18628), None, Some(0)]);
383        let liquid_array =
384            LiquidPrimitiveArray::<Date32Type>::from_arrow_array(date32_array.clone());
385        let bytes = Bytes::from(liquid_array.to_bytes());
386        let context = LiquidIPCContext::new(None);
387        let deserialized = read_from_bytes(bytes, &context);
388        assert_eq!(deserialized.to_arrow_array().as_ref(), &date32_array);
389
390        // Test Date64Type
391        let date64_array =
392            PrimitiveArray::<Date64Type>::from(vec![Some(1609459200000), None, Some(0)]);
393        let liquid_array =
394            LiquidPrimitiveArray::<Date64Type>::from_arrow_array(date64_array.clone());
395        let bytes = Bytes::from(liquid_array.to_bytes());
396        let context = LiquidIPCContext::new(None);
397        let deserialized = read_from_bytes(bytes, &context);
398        assert_eq!(deserialized.to_arrow_array().as_ref(), &date64_array);
399    }
400
401    #[test]
402    fn test_byte_array_roundtrip() {
403        let string_array = StringArray::from(vec![
404            Some("hello"),
405            Some("world"),
406            None,
407            Some("liquid"),
408            Some("byte"),
409            Some("array"),
410        ]);
411
412        // Create a compressor and LiquidByteArray
413        let compressor =
414            FsstArray::train_compressor(string_array.iter().flat_map(|s| s.map(|s| s.as_bytes())));
415        let compressor_arc = Arc::new(compressor);
416
417        let original = LiquidByteArray::from_string_array(&string_array, compressor_arc.clone());
418
419        let bytes = original.to_bytes_inner();
420        let bytes = Bytes::from(bytes);
421        let deserialized = LiquidByteArray::from_bytes(bytes, compressor_arc);
422
423        let original_arrow = original.to_arrow_array();
424        let deserialized_arrow = deserialized.to_arrow_array();
425
426        assert_eq!(original_arrow.as_ref(), deserialized_arrow.as_ref());
427
428        // Verify the original arrow type is preserved via Arrow array types
429        assert_eq!(
430            original.to_arrow_array().data_type(),
431            deserialized.to_arrow_array().data_type()
432        );
433    }
434
435    #[test]
436    fn test_ipc_roundtrip_utf8_for_both_byte_and_view() {
437        let input = StringArray::from(vec![
438            Some("hello"),
439            Some("world"),
440            None,
441            Some("liquid"),
442            Some("byte"),
443            Some("array"),
444            Some("hello"),
445        ]);
446
447        // LiquidByteArray
448        let compressor_ba = LiquidByteArray::train_compressor(input.iter());
449        let original_ba = LiquidByteArray::from_string_array(&input, compressor_ba.clone());
450        let bytes_ba = Bytes::from(original_ba.to_bytes());
451        let deserialized_ba = LiquidByteArray::from_bytes(bytes_ba, compressor_ba);
452        let output_ba = deserialized_ba.to_arrow_array();
453        assert_eq!(output_ba.as_string::<i32>(), &input);
454
455        // LiquidByteViewArray
456        let compressor_bv = LiquidByteViewArray::<MemoryBuffer>::train_compressor(input.iter());
457        let original_bv =
458            LiquidByteViewArray::<MemoryBuffer>::from_string_array(&input, compressor_bv.clone());
459        let bytes_bv = Bytes::from(original_bv.to_bytes());
460        let deserialized_bv =
461            LiquidByteViewArray::<MemoryBuffer>::from_bytes(bytes_bv, compressor_bv);
462        let output_bv = deserialized_bv.to_arrow_array().unwrap();
463        assert_eq!(output_bv.as_string::<i32>(), &input);
464    }
465
466    #[test]
467    fn test_ipc_roundtrip_binaryview_for_both_byte_and_view() {
468        let input = BinaryViewArray::from(vec![
469            Some(b"hello".as_slice()),
470            Some(b"world".as_slice()),
471            Some(b"hello".as_slice()),
472            Some(b"rust\x00".as_slice()),
473            None,
474            Some(b"This is a very long string that should be compressed well"),
475            Some(b""),
476            Some(b"This is a very long string that should be compressed well"),
477        ]);
478
479        // LiquidByteArray via BinaryView
480        let (compressor_ba, original_ba) = LiquidByteArray::train_from_binary_view(&input);
481        let bytes_ba = Bytes::from(original_ba.to_bytes());
482        let deserialized_ba = LiquidByteArray::from_bytes(bytes_ba, compressor_ba);
483        let output_ba = deserialized_ba.to_arrow_array();
484        assert_eq!(output_ba.as_binary_view(), &input);
485
486        // LiquidByteViewArray via BinaryView
487        let (compressor_bv, original_bv) =
488            LiquidByteViewArray::<MemoryBuffer>::train_from_binary_view(&input);
489        let bytes_bv = Bytes::from(original_bv.to_bytes());
490        let deserialized_bv =
491            LiquidByteViewArray::<MemoryBuffer>::from_bytes(bytes_bv, compressor_bv);
492        let output_bv = deserialized_bv.to_arrow_array().unwrap();
493        assert_eq!(output_bv.as_binary_view(), &input);
494    }
495
496    #[test]
497    fn test_float32_array_roundtrip() {
498        let arr = PrimitiveArray::<Float32Type>::from(vec![
499            Some(-1.3e7),
500            Some(1.9),
501            Some(6.6e4),
502            None,
503            Some(9.1e-5),
504        ]);
505        let original = LiquidFloatArray::<Float32Type>::from_arrow_array(arr.clone());
506        let serialized = Bytes::from(original.to_bytes_inner());
507        let deserialized = LiquidFloatArray::<Float32Type>::from_bytes(serialized).to_arrow_array();
508        assert_eq!(deserialized.as_ref(), &arr);
509    }
510
511    #[test]
512    fn test_float64_array_roundtrip() {
513        let arr = PrimitiveArray::<Float64Type>::from(vec![
514            Some(-1.3e7),
515            Some(1.9),
516            Some(6.6e4),
517            None,
518            Some(9.1e-5),
519        ]);
520        let original = LiquidFloatArray::<Float64Type>::from_arrow_array(arr.clone());
521        let serialized = Bytes::from(original.to_bytes_inner());
522        let deserialized = LiquidFloatArray::<Float64Type>::from_bytes(serialized).to_arrow_array();
523        assert_eq!(deserialized.as_ref(), &arr);
524    }
525
526    fn test_decimal_roundtrip<T: DecimalType>(data_type: DataType) {
527        let original_array = gen_test_decimal_array::<T>(data_type);
528        let (compressor, liquid_array) =
529            LiquidFixedLenByteArray::train_from_decimal_array(&original_array);
530
531        let bytes = liquid_array.to_bytes_inner();
532        let bytes = Bytes::from(bytes);
533        let deserialized = LiquidFixedLenByteArray::from_bytes(bytes, compressor);
534        let deserialized_arrow = deserialized.to_arrow_array();
535        assert_eq!(deserialized_arrow.as_ref(), &original_array);
536    }
537
538    #[test]
539    fn test_decimal128_array_roundtrip() {
540        test_decimal_roundtrip::<Decimal128Type>(DataType::Decimal128(10, 2));
541    }
542
543    #[test]
544    fn test_decimal256_array_roundtrip() {
545        test_decimal_roundtrip::<Decimal256Type>(DataType::Decimal256(38, 6));
546    }
547
548    #[test]
549    fn test_fixed_len_byte_array_ipc_roundtrip() {
550        // Test both Decimal128 and Decimal256 through the full IPC pipeline
551
552        let decimal128_array =
553            gen_test_decimal_array::<Decimal128Type>(DataType::Decimal128(15, 3));
554        let (compressor, liquid_array) =
555            LiquidFixedLenByteArray::train_from_decimal_array(&decimal128_array);
556
557        let bytes = liquid_array.to_bytes();
558        let bytes = Bytes::from(bytes);
559
560        let context = LiquidIPCContext::new(Some(compressor.clone()));
561        let deserialized_ref = read_from_bytes(bytes, &context);
562        assert!(matches!(
563            deserialized_ref.data_type(),
564            LiquidDataType::FixedLenByteArray
565        ));
566        let result_arrow = deserialized_ref.to_arrow_array();
567        assert_eq!(result_arrow.as_ref(), &decimal128_array);
568
569        // Test Decimal256
570        let decimal256_array =
571            gen_test_decimal_array::<Decimal256Type>(DataType::Decimal256(38, 6));
572        let (compressor, liquid_array) =
573            LiquidFixedLenByteArray::train_from_decimal_array(&decimal256_array);
574
575        let bytes = liquid_array.to_bytes();
576        let bytes = Bytes::from(bytes);
577
578        let context = LiquidIPCContext::new(Some(compressor.clone()));
579        let deserialized_ref = read_from_bytes(bytes, &context);
580
581        assert!(matches!(
582            deserialized_ref.data_type(),
583            LiquidDataType::FixedLenByteArray
584        ));
585
586        let result_arrow = deserialized_ref.to_arrow_array();
587        assert_eq!(result_arrow.as_ref(), &decimal256_array);
588    }
589
590    #[test]
591    fn test_fixed_len_byte_array_ipc_edge_cases() {
592        // Test edge cases with FixedLenByteArray IPC
593
594        let mut builder = arrow::array::Decimal128Builder::new();
595        builder.append_value(123456789_i128);
596        builder.append_null();
597        builder.append_value(-987654321_i128);
598        builder.append_null();
599        builder.append_value(0_i128);
600        let array_with_nulls = builder.finish().with_precision_and_scale(15, 3).unwrap();
601
602        let (compressor, liquid_array) =
603            LiquidFixedLenByteArray::train_from_decimal_array(&array_with_nulls);
604
605        let bytes = liquid_array.to_bytes();
606        let bytes = Bytes::from(bytes);
607
608        let context = LiquidIPCContext::new(Some(compressor));
609        let deserialized_ref = read_from_bytes(bytes, &context);
610        let result_arrow = deserialized_ref.to_arrow_array();
611
612        assert_eq!(result_arrow.as_ref(), &array_with_nulls);
613
614        // Test with single value
615        let mut builder = arrow::array::Decimal256Builder::new();
616        builder.append_value(i256::from_i128(42_i128));
617        let single_value_array = builder.finish().with_precision_and_scale(38, 6).unwrap();
618
619        let (compressor, liquid_array) =
620            LiquidFixedLenByteArray::train_from_decimal_array(&single_value_array);
621
622        let bytes = liquid_array.to_bytes();
623        let bytes = Bytes::from(bytes);
624
625        let context = LiquidIPCContext::new(Some(compressor));
626        let deserialized_ref = read_from_bytes(bytes, &context);
627        let result_arrow = deserialized_ref.to_arrow_array();
628
629        assert_eq!(result_arrow.as_ref(), &single_value_array);
630    }
631}