chronix-query 0.7.0

Query engine for the Chronix time-series database
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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
//! Time-bucket downsampling engine.
//!
//! Groups data points into fixed-width time buckets and applies an
//! aggregation function per bucket. This enables efficient data reduction
//! for dashboards, alerting queries, and long-term storage.
//!
//! # Two entry points
//!
//! [`downsample`] takes a whole `RecordBatch` and returns every bucket in it.
//! It is correct only when the batch contains *all* the rows for the buckets
//! it covers.
//!
//! [`StreamingDownsampler`] is the one to use over a chunked scan. Bucket
//! boundaries do not line up with batch boundaries, so downsampling each
//! batch independently emits the straddling interval twice — once per side —
//! which a caller then sums, averages or plots as two points. The
//! streaming form keeps one open bucket across batches and closes it only
//! when a row from a later bucket arrives, so a bucket is emitted exactly
//! once no matter how the input was chunked. Peak memory is one bucket's
//! accumulator, not one batch's worth of rows.

use std::sync::Arc;

use fnv::FnvHashMap;

use arrow::array::{Array, ArrayRef, Float64Array, Int64Array};
use arrow::datatypes::{DataType, Field, Schema};
use arrow::record_batch::RecordBatch;

use crate::aggregate::AggFn;
use crate::error::{QueryError, Result};

/// Extract the value at `index` from a numeric column as `f64`.
///
/// Returns `None` if the value is null.
#[allow(clippy::cast_precision_loss)]
fn extract_f64(col: &dyn Array, index: usize) -> Option<f64> {
    crate::extract_f64(col, index)
}

/// Downsample a `RecordBatch` into time buckets.
///
/// For each bucket `[bucket.start_of(ts), bucket.next(start))`, the
/// aggregation function is applied to the values in the `value_column`.
/// The bucket may be a fixed span or a calendar one — it is the same type
/// SQL's `time_bucket()` and a rollup tier use, so the three agree.
///
/// Returns a new `RecordBatch` with two columns: `_time` (bucket start)
/// and the aggregated value column.
///
/// # Arguments
///
/// * `batch` – input data (must have a `_time` Int64 column)
/// * `value_column` – name of the column to aggregate
/// * `bucket` – the bucket width and the calendar it is read against
/// * `function` – aggregation function to apply per bucket
///
/// # Errors
///
/// Returns an error if columns are missing or have unexpected types.
#[allow(clippy::cast_precision_loss)]
pub fn downsample(
    batch: &RecordBatch,
    value_column: &str,
    bucket: &chronix_core::TimeBucket,
    function: &AggFn,
    memory_tracker: Option<&crate::memory::MemoryTracker>,
) -> Result<RecordBatch> {
    let schema = batch.schema();

    let time_idx = schema
        .index_of(chronix_core::TIME_COLUMN)
        .map_err(|_| QueryError::Validation("'timestamp' column not found".into()))?;
    let val_idx = schema
        .index_of(value_column)
        .map_err(|_| QueryError::FieldNotFound {
            measurement: String::new(),
            field: value_column.to_string(),
        })?;

    let timestamps = batch
        .column(time_idx)
        .as_any()
        .downcast_ref::<Int64Array>()
        .ok_or_else(|| QueryError::Validation("'timestamp' column is not Int64".into()))?;

    let value_col = batch.column(val_idx).as_ref();

    // Validate the value column is a supported numeric type
    match value_col.data_type() {
        DataType::Float64 | DataType::Int64 | DataType::UInt64 | DataType::Decimal128(_, _) => {}
        dt => {
            return Err(QueryError::Validation(format!(
                "'{value_column}' column has unsupported type {dt} \
                 (expected Float64, Int64, UInt64, or Decimal128)"
            )));
        }
    }

    // Group indices by bucket – use a hash map for O(1) inserts,
    // then sort the keys once at the end to restore time order.
    let mut buckets: FnvHashMap<i64, Vec<usize>> = FnvHashMap::default();
    for i in 0..timestamps.len() {
        if timestamps.is_null(i) {
            continue;
        }
        let ts = timestamps.value(i);
        // The bucket knows its own calendar: a fixed width aligns on the
        // epoch, a `1d` in a zone on local midnight, a `1mo` on the first of
        // the month. Doing the arithmetic here is what made this surface
        // disagree with SQL's `time_bucket()`.
        let bucket_start = bucket.start_of(ts);
        buckets.entry(bucket_start).or_default().push(i);
    }

    // Sort bucket keys so the output is ordered by time.
    let mut sorted_keys: Vec<i64> = buckets.keys().copied().collect();
    sorted_keys.sort_unstable();

    // Compute aggregate per bucket
    let mut out_times = Vec::with_capacity(buckets.len());
    let mut out_values = Vec::with_capacity(buckets.len());

    for bucket_start in &sorted_keys {
        let indices = &buckets[bucket_start];
        // Collect (timestamp, value) pairs for this bucket.
        // Timestamps are needed for First/Last semantics.
        let raw_pairs: Vec<(i64, f64)> = indices
            .iter()
            .filter_map(|&i| {
                let val = extract_f64(value_col, i)?;
                Some((timestamps.value(i), val))
            })
            .collect();

        if raw_pairs.is_empty() {
            continue;
        }

        let agg_value = match function {
            // Count counts all non-null, non-NaN rows for consistency
            // with the other aggregation functions.
            AggFn::Count => raw_pairs.iter().filter(|(_, v)| !v.is_nan()).count() as f64,
            _ => {
                // For numeric aggregations, filter out NaN
                let clean: Vec<(i64, f64)> =
                    raw_pairs.into_iter().filter(|(_, v)| !v.is_nan()).collect();
                if clean.is_empty() {
                    continue;
                }
                match function {
                    AggFn::Sum => clean.iter().map(|(_, v)| v).sum(),
                    AggFn::Min => clean.iter().map(|(_, v)| *v).fold(f64::INFINITY, f64::min),
                    AggFn::Max => clean
                        .iter()
                        .map(|(_, v)| *v)
                        .fold(f64::NEG_INFINITY, f64::max),
                    AggFn::Avg => {
                        let sum: f64 = clean.iter().map(|(_, v)| v).sum();
                        sum / clean.len() as f64
                    }
                    // First: value with the smallest timestamp in the bucket
                    AggFn::First => clean
                        .iter()
                        .min_by_key(|(ts, _)| *ts)
                        .map(|(_, v)| *v)
                        .expect("clean is non-empty"),
                    // Last: value with the largest timestamp in the bucket
                    AggFn::Last => clean
                        .iter()
                        .max_by_key(|(ts, _)| *ts)
                        .map(|(_, v)| *v)
                        .expect("clean is non-empty"),
                    AggFn::Count => {
                        // Count is handled in the outer branch; defensive error.
                        return Err(QueryError::Validation(
                            "Count aggregation reached inner branch unexpectedly".into(),
                        ));
                    }
                }
            }
        };

        out_times.push(*bucket_start);
        out_values.push(agg_value);
    }

    let out_schema = Arc::new(Schema::new(vec![
        Field::new(chronix_core::TIME_COLUMN, DataType::Int64, false),
        Field::new(value_column, DataType::Float64, false),
    ]));

    let result = RecordBatch::try_new(
        out_schema,
        vec![
            Arc::new(Int64Array::from(out_times)) as ArrayRef,
            Arc::new(Float64Array::from(out_values)) as ArrayRef,
        ],
    )?;

    if let Some(tracker) = memory_tracker {
        tracker.try_allocate(result.get_array_memory_size())?;
    }

    Ok(result)
}

/// Boundary-safe downsampling over a sequence of time-ordered batches.
///
/// Rows must arrive ascending by timestamp — which is what the query engine's
/// merge guarantees — so a bucket is complete as soon as a row belonging to a
/// later bucket is seen. Buckets are emitted in order and exactly once.
///
/// # Example
///
/// ```no_run
/// # use chronix_query::downsample::StreamingDownsampler;
/// # use chronix_query::aggregate::AggFn;
/// # use arrow::record_batch::RecordBatch;
/// # use chronix_core::TimeBucket;
/// # use std::time::Duration;
/// # fn batches() -> Vec<RecordBatch> { vec![] }
/// // A fixed minute. `TimeBucket::parse("1d", Some("Europe/Berlin"))` for a
/// // calendar bucket — the same type SQL's `time_bucket()` uses.
/// let bucket = TimeBucket::fixed(Duration::from_secs(60));
/// let mut ds = StreamingDownsampler::new("value", bucket, AggFn::Avg)?;
/// let mut out = Vec::new();
/// for batch in batches() {
///     out.extend(ds.push(&batch)?);
/// }
/// out.extend(ds.finish()?);
/// # Ok::<(), chronix_query::QueryError>(())
/// ```
pub struct StreamingDownsampler {
    value_column: String,
    bucket: chronix_core::TimeBucket,
    function: AggFn,
    /// Start timestamp of the bucket currently being accumulated.
    open_bucket: Option<i64>,
    /// Accumulated state for the open bucket.
    acc: BucketAcc,
    /// Completed buckets not yet drained into an output batch.
    pending: Vec<(i64, f64)>,
    /// Rows per emitted batch.
    chunk_rows: usize,
}

/// Running state for one time bucket.
#[derive(Default)]
struct BucketAcc {
    count: u64,
    sum: f64,
    min: f64,
    max: f64,
    first_ts: i64,
    first_val: f64,
    last_ts: i64,
    last_val: f64,
}

impl BucketAcc {
    fn reset(&mut self) {
        self.count = 0;
        self.sum = 0.0;
        self.min = f64::INFINITY;
        self.max = f64::NEG_INFINITY;
        self.first_ts = i64::MAX;
        self.first_val = 0.0;
        self.last_ts = i64::MIN;
        self.last_val = 0.0;
    }

    fn update(&mut self, ts: i64, v: f64) {
        // NaN is excluded, matching `downsample`'s per-bucket filtering.
        if v.is_nan() {
            return;
        }
        self.count += 1;
        self.sum += v;
        if v < self.min {
            self.min = v;
        }
        if v > self.max {
            self.max = v;
        }
        if ts < self.first_ts {
            self.first_ts = ts;
            self.first_val = v;
        }
        // `>=` so the last-encountered value wins on ties.
        if ts >= self.last_ts {
            self.last_ts = ts;
            self.last_val = v;
        }
    }

    #[allow(clippy::cast_precision_loss)]
    fn finalize(&self, function: AggFn) -> Option<f64> {
        if self.count == 0 {
            // `Count` still reports a bucket that had only NaN rows as absent,
            // matching `downsample`, which skips such buckets entirely.
            return None;
        }
        Some(match function {
            AggFn::Count => self.count as f64,
            AggFn::Sum => self.sum,
            AggFn::Min => self.min,
            AggFn::Max => self.max,
            AggFn::Avg => self.sum / self.count as f64,
            AggFn::First => self.first_val,
            AggFn::Last => self.last_val,
        })
    }
}

impl StreamingDownsampler {
    /// Rows per emitted batch.
    const DEFAULT_CHUNK_ROWS: usize = 65_536;

    /// Create a downsampler for `value_column` over `bucket`-wide buckets.
    ///
    /// # Errors
    ///
    /// Never fails today; the signature is fallible because `push` is, and
    /// callers already handle a `Result` here.
    pub fn new(
        value_column: &str,
        bucket: chronix_core::TimeBucket,
        function: AggFn,
    ) -> Result<Self> {
        let mut acc = BucketAcc::default();
        acc.reset();
        Ok(Self {
            value_column: value_column.to_string(),
            bucket,
            function,
            open_bucket: None,
            acc,
            pending: Vec::new(),
            chunk_rows: Self::DEFAULT_CHUNK_ROWS,
        })
    }

    /// Fold one batch in, returning any batches of completed buckets.
    ///
    /// # Errors
    ///
    /// Returns an error if the timestamp or value column is missing or has an
    /// unsupported type, or if a row arrives out of timestamp order.
    pub fn push(&mut self, batch: &RecordBatch) -> Result<Vec<RecordBatch>> {
        if batch.num_rows() == 0 {
            return Ok(Vec::new());
        }
        let schema = batch.schema();
        let time_idx = schema
            .index_of(chronix_core::TIME_COLUMN)
            .map_err(|_| QueryError::Validation("'timestamp' column not found".into()))?;
        let val_idx =
            schema
                .index_of(&self.value_column)
                .map_err(|_| QueryError::FieldNotFound {
                    measurement: String::new(),
                    field: self.value_column.clone(),
                })?;

        let timestamps = batch
            .column(time_idx)
            .as_any()
            .downcast_ref::<Int64Array>()
            .ok_or_else(|| QueryError::Validation("'timestamp' column is not Int64".into()))?;
        let value_col = batch.column(val_idx).as_ref();
        match value_col.data_type() {
            DataType::Float64 | DataType::Int64 | DataType::UInt64 | DataType::Decimal128(_, _) => {
            }
            dt => {
                return Err(QueryError::Validation(format!(
                    "'{}' column has unsupported type {dt} \
                     (expected Float64, Int64, UInt64, or Decimal128)",
                    self.value_column
                )));
            }
        }

        for i in 0..timestamps.len() {
            if timestamps.is_null(i) {
                continue;
            }
            let ts = timestamps.value(i);
            // See `downsample` above: the bucket owns its own calendar.
            let bucket = self.bucket.start_of(ts);

            match self.open_bucket {
                Some(open) if bucket == open => {}
                Some(open) if bucket < open => {
                    // Out-of-order input would silently corrupt a closed
                    // bucket, so say so instead of producing a wrong number.
                    return Err(QueryError::Validation(format!(
                        "downsample input is not ascending by timestamp: bucket {bucket} \
                         arrived after {open} was closed"
                    )));
                }
                Some(_) => self.close_open_bucket(),
                None => {}
            }
            self.open_bucket = Some(bucket);

            if let Some(v) = extract_f64(value_col, i) {
                self.acc.update(ts, v);
            }
        }

        self.drain(false)
    }

    /// Close the final bucket and return any remaining output.
    ///
    /// # Errors
    ///
    /// Returns an error if the output batch cannot be built.
    pub fn finish(mut self) -> Result<Vec<RecordBatch>> {
        if self.open_bucket.is_some() {
            self.close_open_bucket();
        }
        self.drain(true)
    }

    fn close_open_bucket(&mut self) {
        if let (Some(start), Some(v)) = (self.open_bucket, self.acc.finalize(self.function)) {
            self.pending.push((start, v));
        }
        self.acc.reset();
        self.open_bucket = None;
    }

    /// Turn completed buckets into output batches. Unless `flush`, a partial
    /// chunk is kept back so emitted batches stay a uniform size.
    fn drain(&mut self, flush: bool) -> Result<Vec<RecordBatch>> {
        let mut out = Vec::new();
        while self.pending.len() >= self.chunk_rows || (flush && !self.pending.is_empty()) {
            let take = self.chunk_rows.min(self.pending.len());
            let rows: Vec<(i64, f64)> = self.pending.drain(..take).collect();
            // Propagate rather than skip: dropping a failed batch here would
            // silently lose completed buckets.
            out.push(build_batch(&self.value_column, &rows)?);
        }
        Ok(out)
    }
}

/// Build the two-column output batch for a run of completed buckets.
fn build_batch(value_column: &str, rows: &[(i64, f64)]) -> Result<RecordBatch> {
    let schema = Arc::new(Schema::new(vec![
        Field::new(chronix_core::TIME_COLUMN, DataType::Int64, false),
        Field::new(value_column, DataType::Float64, false),
    ]));
    let times: Vec<i64> = rows.iter().map(|(t, _)| *t).collect();
    let values: Vec<f64> = rows.iter().map(|(_, v)| *v).collect();
    RecordBatch::try_new(
        schema,
        vec![
            Arc::new(Int64Array::from(times)) as ArrayRef,
            Arc::new(Float64Array::from(values)) as ArrayRef,
        ],
    )
    .map_err(Into::into)
}

#[cfg(test)]
mod tests {
    use super::*;
    use arrow::array::UInt64Array;
    use chronix_core::TimeBucket;

    fn make_batch(times: Vec<i64>, values: Vec<f64>) -> RecordBatch {
        let schema = Arc::new(Schema::new(vec![
            Field::new(chronix_core::TIME_COLUMN, DataType::Int64, false),
            Field::new("value", DataType::Float64, false),
        ]));

        RecordBatch::try_new(
            schema,
            vec![
                Arc::new(Int64Array::from(times)),
                Arc::new(Float64Array::from(values)),
            ],
        )
        .unwrap()
    }

    #[test]
    fn downsample_avg_10s_buckets() {
        let batch = make_batch(
            vec![0, 5, 10, 15, 20, 25],
            vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
        );

        let result = downsample(
            &batch,
            "value",
            &TimeBucket::fixed_ns(10),
            &AggFn::Avg,
            None,
        )
        .unwrap();
        assert_eq!(result.num_rows(), 3);

        let times = result
            .column(0)
            .as_any()
            .downcast_ref::<Int64Array>()
            .unwrap();
        let values = result
            .column(1)
            .as_any()
            .downcast_ref::<Float64Array>()
            .unwrap();

        // Bucket [0, 10): ts=0, 5 → avg 1.5
        assert_eq!(times.value(0), 0);
        assert!((values.value(0) - 1.5).abs() < f64::EPSILON);

        // Bucket [10, 20): ts=10, 15 → avg 3.5
        assert_eq!(times.value(1), 10);
        assert!((values.value(1) - 3.5).abs() < f64::EPSILON);

        // Bucket [20, 30): ts=20, 25 → avg 5.5
        assert_eq!(times.value(2), 20);
        assert!((values.value(2) - 5.5).abs() < f64::EPSILON);
    }

    #[test]
    fn downsample_sum() {
        let batch = make_batch(vec![0, 5, 10, 15], vec![10.0, 20.0, 30.0, 40.0]);

        let result = downsample(
            &batch,
            "value",
            &TimeBucket::fixed_ns(10),
            &AggFn::Sum,
            None,
        )
        .unwrap();
        assert_eq!(result.num_rows(), 2);

        let values = result
            .column(1)
            .as_any()
            .downcast_ref::<Float64Array>()
            .unwrap();

        assert!((values.value(0) - 30.0).abs() < f64::EPSILON);
        assert!((values.value(1) - 70.0).abs() < f64::EPSILON);
    }

    #[test]
    fn downsample_count() {
        let batch = make_batch(vec![0, 1, 2, 10, 20, 21, 22, 23], vec![1.0; 8]);

        let result = downsample(
            &batch,
            "value",
            &TimeBucket::fixed_ns(10),
            &AggFn::Count,
            None,
        )
        .unwrap();
        assert_eq!(result.num_rows(), 3);

        let values = result
            .column(1)
            .as_any()
            .downcast_ref::<Float64Array>()
            .unwrap();

        assert!((values.value(0) - 3.0).abs() < f64::EPSILON); // [0,10): 3 points
        assert!((values.value(1) - 1.0).abs() < f64::EPSILON); // [10,20): 1 point
        assert!((values.value(2) - 4.0).abs() < f64::EPSILON); // [20,30): 4 points
    }

    #[test]
    fn downsample_min_max() {
        let batch = make_batch(vec![0, 5, 10, 15], vec![3.0, 1.0, 4.0, 2.0]);

        let min_result = downsample(
            &batch,
            "value",
            &TimeBucket::fixed_ns(10),
            &AggFn::Min,
            None,
        )
        .unwrap();
        let max_result = downsample(
            &batch,
            "value",
            &TimeBucket::fixed_ns(10),
            &AggFn::Max,
            None,
        )
        .unwrap();

        let min_vals = min_result
            .column(1)
            .as_any()
            .downcast_ref::<Float64Array>()
            .unwrap();
        let max_vals = max_result
            .column(1)
            .as_any()
            .downcast_ref::<Float64Array>()
            .unwrap();

        assert!((min_vals.value(0) - 1.0).abs() < f64::EPSILON); // min(3, 1)
        assert!((min_vals.value(1) - 2.0).abs() < f64::EPSILON); // min(4, 2)
        assert!((max_vals.value(0) - 3.0).abs() < f64::EPSILON); // max(3, 1)
        assert!((max_vals.value(1) - 4.0).abs() < f64::EPSILON); // max(4, 2)
    }

    #[test]
    fn downsample_first_last() {
        let batch = make_batch(vec![0, 5, 10, 15], vec![10.0, 20.0, 30.0, 40.0]);

        let first = downsample(
            &batch,
            "value",
            &TimeBucket::fixed_ns(10),
            &AggFn::First,
            None,
        )
        .unwrap();
        let last = downsample(
            &batch,
            "value",
            &TimeBucket::fixed_ns(10),
            &AggFn::Last,
            None,
        )
        .unwrap();

        let first_vals = first
            .column(1)
            .as_any()
            .downcast_ref::<Float64Array>()
            .unwrap();
        let last_vals = last
            .column(1)
            .as_any()
            .downcast_ref::<Float64Array>()
            .unwrap();

        assert!((first_vals.value(0) - 10.0).abs() < f64::EPSILON);
        assert!((first_vals.value(1) - 30.0).abs() < f64::EPSILON);
        assert!((last_vals.value(0) - 20.0).abs() < f64::EPSILON);
        assert!((last_vals.value(1) - 40.0).abs() < f64::EPSILON);
    }

    #[test]
    fn empty_batch() {
        let batch = make_batch(vec![], vec![]);
        let result = downsample(
            &batch,
            "value",
            &TimeBucket::fixed_ns(10),
            &AggFn::Avg,
            None,
        )
        .unwrap();
        assert_eq!(result.num_rows(), 0);
    }

    #[test]
    fn downsample_i64_column() {
        let schema = Arc::new(Schema::new(vec![
            Field::new(chronix_core::TIME_COLUMN, DataType::Int64, false),
            Field::new("value", DataType::Int64, false),
        ]));
        let batch = RecordBatch::try_new(
            schema,
            vec![
                Arc::new(Int64Array::from(vec![0, 5, 10, 15])) as ArrayRef,
                Arc::new(Int64Array::from(vec![10, 20, 30, 40])) as ArrayRef,
            ],
        )
        .unwrap();

        let result = downsample(
            &batch,
            "value",
            &TimeBucket::fixed_ns(10),
            &AggFn::Sum,
            None,
        )
        .unwrap();
        assert_eq!(result.num_rows(), 2);

        let values = result
            .column(1)
            .as_any()
            .downcast_ref::<Float64Array>()
            .unwrap();
        assert!((values.value(0) - 30.0).abs() < f64::EPSILON);
        assert!((values.value(1) - 70.0).abs() < f64::EPSILON);
    }

    #[test]
    fn downsample_u64_column() {
        let schema = Arc::new(Schema::new(vec![
            Field::new(chronix_core::TIME_COLUMN, DataType::Int64, false),
            Field::new("value", DataType::UInt64, false),
        ]));
        let batch = RecordBatch::try_new(
            schema,
            vec![
                Arc::new(Int64Array::from(vec![0, 5, 10, 15])) as ArrayRef,
                Arc::new(UInt64Array::from(vec![100u64, 200, 300, 400])) as ArrayRef,
            ],
        )
        .unwrap();

        let result = downsample(
            &batch,
            "value",
            &TimeBucket::fixed_ns(10),
            &AggFn::Avg,
            None,
        )
        .unwrap();
        assert_eq!(result.num_rows(), 2);

        let values = result
            .column(1)
            .as_any()
            .downcast_ref::<Float64Array>()
            .unwrap();
        assert!((values.value(0) - 150.0).abs() < f64::EPSILON);
        assert!((values.value(1) - 350.0).abs() < f64::EPSILON);
    }

    #[test]
    fn downsample_unsupported_type_fails() {
        let schema = Arc::new(Schema::new(vec![
            Field::new(chronix_core::TIME_COLUMN, DataType::Int64, false),
            Field::new("value", DataType::Boolean, false),
        ]));
        let batch = RecordBatch::try_new(
            schema,
            vec![
                Arc::new(Int64Array::from(vec![0i64])) as ArrayRef,
                Arc::new(arrow::array::BooleanArray::from(vec![true])) as ArrayRef,
            ],
        )
        .unwrap();

        let err = downsample(
            &batch,
            "value",
            &TimeBucket::fixed_ns(10),
            &AggFn::Avg,
            None,
        )
        .unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains("unsupported"),
            "expected unsupported type error, got: {msg}"
        );
    }

    #[test]
    fn downsample_respects_memory_tracker() {
        let batch = make_batch(vec![0, 5, 10, 15], vec![1.0, 2.0, 3.0, 4.0]);
        let tracker = crate::memory::MemoryTracker::new(1_000_000);
        let result = downsample(
            &batch,
            "value",
            &TimeBucket::fixed_ns(10),
            &AggFn::Avg,
            Some(&tracker),
        )
        .unwrap();
        assert!(tracker.allocated() > 0);
        assert_eq!(result.num_rows(), 2);
    }

    #[test]
    fn downsample_exceeds_memory_budget() {
        let batch = make_batch(vec![0, 5, 10, 15], vec![1.0, 2.0, 3.0, 4.0]);
        let tracker = crate::memory::MemoryTracker::new(1);
        let err = downsample(
            &batch,
            "value",
            &TimeBucket::fixed_ns(10),
            &AggFn::Avg,
            Some(&tracker),
        )
        .unwrap_err();
        assert!(matches!(
            err,
            crate::error::QueryError::QueryMemoryExceeded { .. }
        ));
    }
}