alopex-core 0.5.0

Core storage engine for Alopex DB - LSM-tree, columnar storage, and vector index
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
//! Column statistics computation for segment metadata.
//!
//! Provides statistics (min, max, null_count, distinct_count) for columns
//! to enable predicate pushdown and query optimization.

use serde::{Deserialize, Serialize};
use std::collections::HashSet;

use crate::columnar::encoding::Column;
use crate::columnar::encoding_v2::Bitmap;
use crate::columnar::error::{ColumnarError, Result};

/// A scalar value that can represent min/max statistics for any column type.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ScalarValue {
    /// Null value.
    Null,
    /// Boolean value.
    Bool(bool),
    /// 32-bit floating point.
    Float32(f32),
    /// 64-bit signed integer.
    Int64(i64),
    /// 64-bit floating point.
    Float64(f64),
    /// Variable-length binary data (also used for strings).
    Binary(Vec<u8>),
}

impl ScalarValue {
    /// Check if this value is null.
    pub fn is_null(&self) -> bool {
        matches!(self, ScalarValue::Null)
    }
}

/// Statistics for a single column.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct ColumnStatistics {
    /// Minimum value in the column (None if all values are null).
    pub min: Option<ScalarValue>,
    /// Maximum value in the column (None if all values are null).
    pub max: Option<ScalarValue>,
    /// Number of null values.
    pub null_count: u64,
    /// Estimated number of distinct values (None if not computed).
    pub distinct_count: Option<u64>,
}

/// Statistics for an entire segment.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SegmentStatistics {
    /// Total number of rows in the segment.
    pub num_rows: u64,
    /// Statistics for each column.
    pub column_stats: Vec<ColumnStatistics>,
}

impl SegmentStatistics {
    /// Create new segment statistics with the given row count.
    pub fn new(num_rows: u64) -> Self {
        Self {
            num_rows,
            column_stats: Vec::new(),
        }
    }

    /// Add column statistics to the segment.
    pub fn add_column_stats(&mut self, stats: ColumnStatistics) {
        self.column_stats.push(stats);
    }
}

/// ベクトルセグメント向けの統計情報。
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VectorSegmentStatistics {
    /// 全行数。
    pub row_count: u64,
    /// NULL 行数。
    pub null_count: u64,
    /// アクティブ(有効)行数。
    pub active_count: u64,
    /// 論理削除行数。
    pub deleted_count: u64,
    /// 削除率(0-1)。
    pub deletion_ratio: f32,
    /// ベクトルノルムの最小値。
    pub norm_min: f32,
    /// ベクトルノルムの最大値。
    pub norm_max: f32,
    /// フィルタ列の最小値。
    pub min_values: Vec<ScalarValue>,
    /// フィルタ列の最大値。
    pub max_values: Vec<ScalarValue>,
    /// 作成時刻(epoch millis)。
    pub created_at: u64,
}

impl VectorSegmentStatistics {
    /// シリアライズ(KVS 永続化用)。
    pub fn to_bytes(&self) -> Result<Vec<u8>> {
        bincode::serialize(self).map_err(|e| ColumnarError::InvalidFormat(e.to_string()))
    }

    /// バイト列から復元する。
    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
        bincode::deserialize(bytes).map_err(|e| ColumnarError::InvalidFormat(e.to_string()))
    }
}

/// Compute statistics for a column.
///
/// # Arguments
/// * `column` - The column data
/// * `null_bitmap` - Optional null bitmap (1 = valid, 0 = null)
/// * `compute_distinct` - Whether to compute distinct count (can be expensive)
pub fn compute_column_statistics(
    column: &Column,
    null_bitmap: Option<&Bitmap>,
    compute_distinct: bool,
) -> ColumnStatistics {
    match column {
        Column::Int64(values) => compute_int64_statistics(values, null_bitmap, compute_distinct),
        Column::Float32(values) => {
            compute_float32_statistics(values, null_bitmap, compute_distinct)
        }
        Column::Float64(values) => {
            compute_float64_statistics(values, null_bitmap, compute_distinct)
        }
        Column::Bool(values) => compute_bool_statistics(values, null_bitmap, compute_distinct),
        Column::Binary(values) => compute_binary_statistics(values, null_bitmap, compute_distinct),
        Column::Fixed { values, len: _ } => {
            compute_binary_statistics(values, null_bitmap, compute_distinct)
        }
    }
}

/// Compute statistics for Int64 column.
fn compute_int64_statistics(
    values: &[i64],
    null_bitmap: Option<&Bitmap>,
    compute_distinct: bool,
) -> ColumnStatistics {
    if values.is_empty() {
        return ColumnStatistics::default();
    }

    let mut min_val: Option<i64> = None;
    let mut max_val: Option<i64> = None;
    let mut null_count = 0u64;
    let mut distinct_set: Option<HashSet<i64>> = if compute_distinct {
        Some(HashSet::new())
    } else {
        None
    };

    for (i, &value) in values.iter().enumerate() {
        if let Some(bitmap) = null_bitmap {
            if !bitmap.get(i) {
                null_count += 1;
                continue;
            }
        }

        min_val = Some(min_val.map_or(value, |m| m.min(value)));
        max_val = Some(max_val.map_or(value, |m| m.max(value)));

        if let Some(ref mut set) = distinct_set {
            set.insert(value);
        }
    }

    ColumnStatistics {
        min: min_val.map(ScalarValue::Int64),
        max: max_val.map(ScalarValue::Int64),
        null_count,
        distinct_count: distinct_set.map(|s| s.len() as u64),
    }
}

/// Compute statistics for Float64 column.
fn compute_float64_statistics(
    values: &[f64],
    null_bitmap: Option<&Bitmap>,
    compute_distinct: bool,
) -> ColumnStatistics {
    if values.is_empty() {
        return ColumnStatistics::default();
    }

    let mut min_val: Option<f64> = None;
    let mut max_val: Option<f64> = None;
    let mut null_count = 0u64;
    let mut distinct_set: Option<HashSet<u64>> = if compute_distinct {
        Some(HashSet::new())
    } else {
        None
    };

    for (i, &value) in values.iter().enumerate() {
        if let Some(bitmap) = null_bitmap {
            if !bitmap.get(i) {
                null_count += 1;
                continue;
            }
        }

        // Skip NaN for min/max computation
        if value.is_nan() {
            if let Some(ref mut set) = distinct_set {
                // Use canonical NaN representation for distinct count
                set.insert(f64::NAN.to_bits());
            }
            continue;
        }

        min_val = Some(min_val.map_or(value, |m| m.min(value)));
        max_val = Some(max_val.map_or(value, |m| m.max(value)));

        if let Some(ref mut set) = distinct_set {
            set.insert(value.to_bits());
        }
    }

    ColumnStatistics {
        min: min_val.map(ScalarValue::Float64),
        max: max_val.map(ScalarValue::Float64),
        null_count,
        distinct_count: distinct_set.map(|s| s.len() as u64),
    }
}

/// Compute statistics for Float32 column.
fn compute_float32_statistics(
    values: &[f32],
    null_bitmap: Option<&Bitmap>,
    compute_distinct: bool,
) -> ColumnStatistics {
    if values.is_empty() {
        return ColumnStatistics::default();
    }

    let mut min_val: Option<f32> = None;
    let mut max_val: Option<f32> = None;
    let mut null_count = 0u64;
    let mut distinct_set: Option<HashSet<u32>> = if compute_distinct {
        Some(HashSet::new())
    } else {
        None
    };

    for (i, &value) in values.iter().enumerate() {
        if let Some(bitmap) = null_bitmap {
            if !bitmap.get(i) {
                null_count += 1;
                continue;
            }
        }

        if value.is_nan() {
            if let Some(ref mut set) = distinct_set {
                set.insert(f32::NAN.to_bits());
            }
            continue;
        }

        min_val = Some(min_val.map_or(value, |m| m.min(value)));
        max_val = Some(max_val.map_or(value, |m| m.max(value)));

        if let Some(ref mut set) = distinct_set {
            set.insert(value.to_bits());
        }
    }

    ColumnStatistics {
        min: min_val.map(ScalarValue::Float32),
        max: max_val.map(ScalarValue::Float32),
        null_count,
        distinct_count: distinct_set.map(|s| s.len() as u64),
    }
}

/// Compute statistics for Bool column.
fn compute_bool_statistics(
    values: &[bool],
    null_bitmap: Option<&Bitmap>,
    compute_distinct: bool,
) -> ColumnStatistics {
    if values.is_empty() {
        return ColumnStatistics::default();
    }

    let mut has_true = false;
    let mut has_false = false;
    let mut null_count = 0u64;

    for (i, &value) in values.iter().enumerate() {
        if let Some(bitmap) = null_bitmap {
            if !bitmap.get(i) {
                null_count += 1;
                continue;
            }
        }

        if value {
            has_true = true;
        } else {
            has_false = true;
        }
    }

    let (min, max) = match (has_false, has_true) {
        (false, false) => (None, None),
        (true, false) => (
            Some(ScalarValue::Bool(false)),
            Some(ScalarValue::Bool(false)),
        ),
        (false, true) => (Some(ScalarValue::Bool(true)), Some(ScalarValue::Bool(true))),
        (true, true) => (
            Some(ScalarValue::Bool(false)),
            Some(ScalarValue::Bool(true)),
        ),
    };

    let distinct_count = if compute_distinct {
        let count = match (has_false, has_true) {
            (false, false) => 0,
            (true, false) | (false, true) => 1,
            (true, true) => 2,
        };
        Some(count)
    } else {
        None
    };

    ColumnStatistics {
        min,
        max,
        null_count,
        distinct_count,
    }
}

/// Compute statistics for Binary column (lexicographic ordering).
fn compute_binary_statistics(
    values: &[Vec<u8>],
    null_bitmap: Option<&Bitmap>,
    compute_distinct: bool,
) -> ColumnStatistics {
    if values.is_empty() {
        return ColumnStatistics::default();
    }

    let mut min_val: Option<&[u8]> = None;
    let mut max_val: Option<&[u8]> = None;
    let mut null_count = 0u64;
    let mut distinct_set: Option<HashSet<&[u8]>> = if compute_distinct {
        Some(HashSet::new())
    } else {
        None
    };

    for (i, value) in values.iter().enumerate() {
        if let Some(bitmap) = null_bitmap {
            if !bitmap.get(i) {
                null_count += 1;
                continue;
            }
        }

        let slice: &[u8] = value.as_slice();
        min_val = Some(min_val.map_or(slice, |m| if slice < m { slice } else { m }));
        max_val = Some(max_val.map_or(slice, |m| if slice > m { slice } else { m }));

        if let Some(ref mut set) = distinct_set {
            set.insert(slice);
        }
    }

    ColumnStatistics {
        min: min_val.map(|v| ScalarValue::Binary(v.to_vec())),
        max: max_val.map(|v| ScalarValue::Binary(v.to_vec())),
        null_count,
        distinct_count: distinct_set.map(|s| s.len() as u64),
    }
}

/// Merge two column statistics.
///
/// This is useful when combining statistics from multiple row groups.
pub fn merge_column_statistics(a: &ColumnStatistics, b: &ColumnStatistics) -> ColumnStatistics {
    let min = merge_min(&a.min, &b.min);
    let max = merge_max(&a.max, &b.max);

    ColumnStatistics {
        min,
        max,
        null_count: a.null_count + b.null_count,
        // Cannot accurately merge distinct counts without full data
        distinct_count: None,
    }
}

fn merge_min(a: &Option<ScalarValue>, b: &Option<ScalarValue>) -> Option<ScalarValue> {
    match (a, b) {
        (None, None) => None,
        (Some(v), None) | (None, Some(v)) => Some(v.clone()),
        (Some(a_val), Some(b_val)) => Some(scalar_min(a_val, b_val)),
    }
}

fn merge_max(a: &Option<ScalarValue>, b: &Option<ScalarValue>) -> Option<ScalarValue> {
    match (a, b) {
        (None, None) => None,
        (Some(v), None) | (None, Some(v)) => Some(v.clone()),
        (Some(a_val), Some(b_val)) => Some(scalar_max(a_val, b_val)),
    }
}

fn scalar_min(a: &ScalarValue, b: &ScalarValue) -> ScalarValue {
    match (a, b) {
        (ScalarValue::Int64(a), ScalarValue::Int64(b)) => ScalarValue::Int64(*a.min(b)),
        (ScalarValue::Float32(a), ScalarValue::Float32(b)) => ScalarValue::Float32(a.min(*b)),
        (ScalarValue::Float64(a), ScalarValue::Float64(b)) => ScalarValue::Float64(a.min(*b)),
        (ScalarValue::Bool(a), ScalarValue::Bool(b)) => ScalarValue::Bool(*a && *b),
        (ScalarValue::Binary(a), ScalarValue::Binary(b)) => {
            ScalarValue::Binary(if a < b { a.clone() } else { b.clone() })
        }
        _ => a.clone(), // Type mismatch, return first
    }
}

fn scalar_max(a: &ScalarValue, b: &ScalarValue) -> ScalarValue {
    match (a, b) {
        (ScalarValue::Int64(a), ScalarValue::Int64(b)) => ScalarValue::Int64(*a.max(b)),
        (ScalarValue::Float32(a), ScalarValue::Float32(b)) => ScalarValue::Float32(a.max(*b)),
        (ScalarValue::Float64(a), ScalarValue::Float64(b)) => ScalarValue::Float64(a.max(*b)),
        (ScalarValue::Bool(a), ScalarValue::Bool(b)) => ScalarValue::Bool(*a || *b),
        (ScalarValue::Binary(a), ScalarValue::Binary(b)) => {
            ScalarValue::Binary(if a > b { a.clone() } else { b.clone() })
        }
        _ => a.clone(), // Type mismatch, return first
    }
}

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use super::*;

    #[test]
    fn test_min_max_int64() {
        let values = vec![5i64, 2, 8, 1, 9, 3];
        let column = Column::Int64(values);
        let stats = compute_column_statistics(&column, None, true);

        assert_eq!(stats.min, Some(ScalarValue::Int64(1)));
        assert_eq!(stats.max, Some(ScalarValue::Int64(9)));
        assert_eq!(stats.null_count, 0);
        assert_eq!(stats.distinct_count, Some(6));
    }

    #[test]
    fn test_min_max_int64_with_duplicates() {
        let values = vec![5i64, 2, 5, 2, 5, 2];
        let column = Column::Int64(values);
        let stats = compute_column_statistics(&column, None, true);

        assert_eq!(stats.min, Some(ScalarValue::Int64(2)));
        assert_eq!(stats.max, Some(ScalarValue::Int64(5)));
        assert_eq!(stats.distinct_count, Some(2));
    }

    #[test]
    fn test_null_count() {
        let values = vec![1i64, 2, 3, 4, 5];
        let column = Column::Int64(values);

        // Create bitmap where indices 1 and 3 are null (0)
        let mut bitmap = Bitmap::new(5);
        bitmap.set(0, true);
        bitmap.set(1, false); // null
        bitmap.set(2, true);
        bitmap.set(3, false); // null
        bitmap.set(4, true);

        let stats = compute_column_statistics(&column, Some(&bitmap), true);

        assert_eq!(stats.null_count, 2);
        assert_eq!(stats.min, Some(ScalarValue::Int64(1))); // indices 0, 2, 4
        assert_eq!(stats.max, Some(ScalarValue::Int64(5)));
        assert_eq!(stats.distinct_count, Some(3)); // 1, 3, 5
    }

    #[test]
    fn test_distinct_count_estimation() {
        // Test with many values
        let values: Vec<i64> = (0..1000).collect();
        let column = Column::Int64(values);
        let stats = compute_column_statistics(&column, None, true);

        assert_eq!(stats.distinct_count, Some(1000));
    }

    #[test]
    fn test_min_max_float64() {
        let values = vec![1.5f64, 2.5, 0.5, 3.5, -1.5];
        let column = Column::Float64(values);
        let stats = compute_column_statistics(&column, None, true);

        assert_eq!(stats.min, Some(ScalarValue::Float64(-1.5)));
        assert_eq!(stats.max, Some(ScalarValue::Float64(3.5)));
        assert_eq!(stats.null_count, 0);
        assert_eq!(stats.distinct_count, Some(5));
    }

    #[test]
    fn test_min_max_float32() {
        let values = vec![1.5f32, 2.5, 0.5, 3.5, -1.5];
        let column = Column::Float32(values);
        let stats = compute_column_statistics(&column, None, true);

        assert_eq!(stats.min, Some(ScalarValue::Float32(-1.5)));
        assert_eq!(stats.max, Some(ScalarValue::Float32(3.5)));
        assert_eq!(stats.null_count, 0);
        assert_eq!(stats.distinct_count, Some(5));
    }

    #[test]
    fn test_float64_with_nan() {
        let values = vec![1.0f64, f64::NAN, 2.0, f64::NAN, 3.0];
        let column = Column::Float64(values);
        let stats = compute_column_statistics(&column, None, true);

        // NaN should be excluded from min/max
        assert_eq!(stats.min, Some(ScalarValue::Float64(1.0)));
        assert_eq!(stats.max, Some(ScalarValue::Float64(3.0)));
        // NaN counts as one distinct value
        assert_eq!(stats.distinct_count, Some(4)); // 1.0, 2.0, 3.0, NaN
    }

    #[test]
    fn test_min_max_binary_lexicographic() {
        let values = vec![
            b"banana".to_vec(),
            b"apple".to_vec(),
            b"cherry".to_vec(),
            b"apricot".to_vec(),
        ];
        let column = Column::Binary(values);
        let stats = compute_column_statistics(&column, None, true);

        assert_eq!(stats.min, Some(ScalarValue::Binary(b"apple".to_vec())));
        assert_eq!(stats.max, Some(ScalarValue::Binary(b"cherry".to_vec())));
        assert_eq!(stats.distinct_count, Some(4));
    }

    #[test]
    fn test_bool_statistics() {
        let values = vec![true, false, true, true, false];
        let column = Column::Bool(values);
        let stats = compute_column_statistics(&column, None, true);

        assert_eq!(stats.min, Some(ScalarValue::Bool(false)));
        assert_eq!(stats.max, Some(ScalarValue::Bool(true)));
        assert_eq!(stats.distinct_count, Some(2));
    }

    #[test]
    fn test_bool_all_true() {
        let values = vec![true, true, true];
        let column = Column::Bool(values);
        let stats = compute_column_statistics(&column, None, true);

        assert_eq!(stats.min, Some(ScalarValue::Bool(true)));
        assert_eq!(stats.max, Some(ScalarValue::Bool(true)));
        assert_eq!(stats.distinct_count, Some(1));
    }

    #[test]
    fn test_empty_column() {
        let values: Vec<i64> = vec![];
        let column = Column::Int64(values);
        let stats = compute_column_statistics(&column, None, true);

        assert_eq!(stats.min, None);
        assert_eq!(stats.max, None);
        assert_eq!(stats.null_count, 0);
        assert_eq!(stats.distinct_count, None);
    }

    #[test]
    fn test_all_nulls() {
        let values = vec![1i64, 2, 3];
        let column = Column::Int64(values);

        // All values are null
        let mut bitmap = Bitmap::new(3);
        bitmap.set(0, false);
        bitmap.set(1, false);
        bitmap.set(2, false);

        let stats = compute_column_statistics(&column, Some(&bitmap), true);

        assert_eq!(stats.min, None);
        assert_eq!(stats.max, None);
        assert_eq!(stats.null_count, 3);
        assert_eq!(stats.distinct_count, Some(0));
    }

    #[test]
    fn test_merge_statistics() {
        let stats1 = ColumnStatistics {
            min: Some(ScalarValue::Int64(5)),
            max: Some(ScalarValue::Int64(15)),
            null_count: 2,
            distinct_count: Some(10),
        };

        let stats2 = ColumnStatistics {
            min: Some(ScalarValue::Int64(3)),
            max: Some(ScalarValue::Int64(20)),
            null_count: 3,
            distinct_count: Some(8),
        };

        let merged = merge_column_statistics(&stats1, &stats2);

        assert_eq!(merged.min, Some(ScalarValue::Int64(3)));
        assert_eq!(merged.max, Some(ScalarValue::Int64(20)));
        assert_eq!(merged.null_count, 5);
        // Distinct count cannot be merged accurately
        assert_eq!(merged.distinct_count, None);
    }

    #[test]
    fn test_segment_statistics() {
        let mut seg_stats = SegmentStatistics::new(1000);

        seg_stats.add_column_stats(ColumnStatistics {
            min: Some(ScalarValue::Int64(1)),
            max: Some(ScalarValue::Int64(100)),
            null_count: 5,
            distinct_count: Some(95),
        });

        seg_stats.add_column_stats(ColumnStatistics {
            min: Some(ScalarValue::Binary(b"a".to_vec())),
            max: Some(ScalarValue::Binary(b"z".to_vec())),
            null_count: 10,
            distinct_count: Some(26),
        });

        assert_eq!(seg_stats.num_rows, 1000);
        assert_eq!(seg_stats.column_stats.len(), 2);
    }

    #[test]
    fn test_scalar_value_is_null() {
        assert!(ScalarValue::Null.is_null());
        assert!(!ScalarValue::Int64(42).is_null());
        assert!(!ScalarValue::Float64(std::f64::consts::PI).is_null());
        assert!(!ScalarValue::Bool(true).is_null());
        assert!(!ScalarValue::Binary(vec![1, 2, 3]).is_null());
    }

    #[test]
    fn test_fixed_column_statistics() {
        let values = vec![
            vec![0x01, 0x02, 0x03, 0x04],
            vec![0x00, 0x00, 0x00, 0x01],
            vec![0xFF, 0xFF, 0xFF, 0xFF],
        ];
        let column = Column::Fixed { len: 4, values };
        let stats = compute_column_statistics(&column, None, true);

        assert_eq!(
            stats.min,
            Some(ScalarValue::Binary(vec![0x00, 0x00, 0x00, 0x01]))
        );
        assert_eq!(
            stats.max,
            Some(ScalarValue::Binary(vec![0xFF, 0xFF, 0xFF, 0xFF]))
        );
        assert_eq!(stats.distinct_count, Some(3));
    }

    #[test]
    fn test_vector_segment_statistics_roundtrip() {
        let stats = VectorSegmentStatistics {
            row_count: 10_000,
            null_count: 5,
            active_count: 9_900,
            deleted_count: 95,
            deletion_ratio: 0.0095,
            norm_min: 0.1,
            norm_max: 3.2,
            min_values: vec![ScalarValue::Int64(1)],
            max_values: vec![ScalarValue::Int64(100)],
            created_at: 1_735_000_000,
        };

        let bytes = stats.to_bytes().unwrap();
        let decoded = VectorSegmentStatistics::from_bytes(&bytes).unwrap();

        assert_eq!(decoded, stats);
    }
}