wedb_embed 0.1.1

Embedded database engine providing Redis-like APIs, built on fjall / 嵌入式数据库引擎,提供类似 Redis 的接口,底层基于 fjall 开发
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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
use std::collections::BTreeSet;
use std::fmt::{self, Display};
use std::str::FromStr;

use rapidhash::RapidHashSet;

pub use super::meta::{ChunkType, DuplicatePolicy, TimeSeriesMeta};

/// 聚合计算类型(对标 Apache Kvrocks TSAggregatorType + RedisTimeSeries)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, bitcode::Encode, bitcode::Decode)]
#[repr(u8)]
pub enum AggregationType {
    #[default]
    None = 0,
    Sum = 1,
    Min = 2,
    Max = 3,
    Count = 4,
    First = 5,
    Last = 6,
    Avg = 7,
    Range = 8,
    StdP = 9,
    StdS = 10,
    VarP = 11,
    VarS = 12,
    Twa = 13,
}

impl FromStr for AggregationType {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_ascii_uppercase().as_str() {
            "NONE" => Ok(Self::None),
            "SUM" => Ok(Self::Sum),
            "MIN" => Ok(Self::Min),
            "MAX" => Ok(Self::Max),
            "COUNT" => Ok(Self::Count),
            "FIRST" => Ok(Self::First),
            "LAST" => Ok(Self::Last),
            "AVG" => Ok(Self::Avg),
            "RANGE" => Ok(Self::Range),
            "STD.P" | "STDP" => Ok(Self::StdP),
            "STD.S" | "STDS" => Ok(Self::StdS),
            "VAR.P" | "VARP" => Ok(Self::VarP),
            "VAR.S" | "VARS" => Ok(Self::VarS),
            "TWA" => Ok(Self::Twa),
            _ => Err(()),
        }
    }
}

impl Display for AggregationType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl AggregationType {
    pub fn parse(s: &str) -> Option<Self> {
        s.parse().ok()
    }

    #[inline]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Sum => "sum",
            Self::Min => "min",
            Self::Max => "max",
            Self::Count => "count",
            Self::First => "first",
            Self::Last => "last",
            Self::Avg => "avg",
            Self::Range => "range",
            Self::StdP => "std.p",
            Self::StdS => "std.s",
            Self::VarP => "var.p",
            Self::VarS => "var.s",
            Self::Twa => "twa",
        }
    }

    /// 是否支持增量累加计算(对标 Kvrocks IsIncrementalAggregatorType)
    #[inline]
    pub const fn is_incremental(&self) -> bool {
        matches!(self, Self::Sum | Self::Min | Self::Max | Self::Count)
    }
}

/// 降采样桶时间戳类型(对标 Apache Kvrocks BucketTimestampType)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, bitcode::Encode, bitcode::Decode)]
#[repr(u8)]
pub enum BucketTimestampType {
    #[default]
    Start = 0,
    End = 1,
    Mid = 2,
}

impl FromStr for BucketTimestampType {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_ascii_uppercase().as_str() {
            "START" | "-" => Ok(Self::Start),
            "END" | "+" => Ok(Self::End),
            "MID" | "~" => Ok(Self::Mid),
            _ => Err(()),
        }
    }
}

impl Display for BucketTimestampType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl BucketTimestampType {
    pub fn parse(s: &str) -> Option<Self> {
        s.parse().ok()
    }

    #[inline]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Start => "start",
            Self::End => "end",
            Self::Mid => "mid",
        }
    }
}

/// 时序聚合计算器(对标 Apache Kvrocks TSAggregator)
#[derive(Debug, Clone, PartialEq, Default, bitcode::Encode, bitcode::Decode)]
pub struct Aggregator {
    pub agg_type: AggregationType,
    pub bucket_duration: u64,
    pub alignment: u64,
}

impl Aggregator {
    #[inline]
    pub fn new(agg_type: AggregationType, bucket_duration: u64, alignment: u64) -> Self {
        Self {
            agg_type,
            bucket_duration: bucket_duration.max(1),
            alignment,
        }
    }

    /// 计算对齐时间桶左边界(对标 Kvrocks CalculateAlignedBucketLeft)
    #[inline]
    pub fn calculate_aligned_bucket_left(&self, ts: u64) -> u64 {
        if self.bucket_duration == 0 {
            return ts;
        }
        if ts >= self.alignment {
            let diff = ts - self.alignment;
            let k = diff / self.bucket_duration;
            self.alignment + k * self.bucket_duration
        } else {
            let diff = self.alignment - ts;
            let m0 = diff / self.bucket_duration
                + if diff.is_multiple_of(self.bucket_duration) {
                    0
                } else {
                    1
                };
            if m0 <= self.alignment / self.bucket_duration {
                self.alignment - m0 * self.bucket_duration
            } else {
                0
            }
        }
    }

    /// 计算对齐时间桶右边界(对标 Kvrocks CalculateAlignedBucketRight)
    #[inline]
    pub fn calculate_aligned_bucket_right(&self, ts: u64) -> u64 {
        if self.bucket_duration == 0 {
            return ts;
        }
        if ts < self.alignment {
            let diff = self.alignment - ts;
            let k = diff / self.bucket_duration;
            self.alignment.saturating_sub(k * self.bucket_duration)
        } else {
            let diff = ts - self.alignment;
            let m0 = diff / self.bucket_duration + 1;
            self.alignment
                .saturating_add(m0.saturating_mul(self.bucket_duration))
        }
    }

    /// 将采样点零拷贝切分到对齐时间桶切片列表(基于边界跳跃,避免每点重复计算除法)
    pub fn split_samples_to_buckets<'a>(
        &self,
        samples: &'a [(u64, f64)],
    ) -> Vec<(u64, &'a [(u64, f64)])> {
        if samples.is_empty() {
            return Vec::new();
        }

        let mut buckets = Vec::new();
        let mut start_idx = 0;
        let mut current_left = self.calculate_aligned_bucket_left(samples[0].0);
        let mut current_right = self.calculate_aligned_bucket_right(current_left);

        for (i, &(ts, _)) in samples.iter().enumerate() {
            if ts >= current_right {
                buckets.push((current_left, &samples[start_idx..i]));
                start_idx = i;
                current_left = self.calculate_aligned_bucket_left(ts);
                current_right = self.calculate_aligned_bucket_right(current_left);
            }
        }

        if start_idx < samples.len() {
            buckets.push((current_left, &samples[start_idx..]));
        }

        buckets
    }

    /// 聚合计算单个时间桶内采样点值(专用单次遍历极速路径,对标 Kvrocks Reducer)
    pub fn aggregate_samples(&self, samples: &[(u64, f64)]) -> f64 {
        if samples.is_empty() {
            return match self.agg_type {
                AggregationType::Sum | AggregationType::Count => 0.0,
                _ => f64::NAN,
            };
        }

        let count = samples.len();
        match self.agg_type {
            AggregationType::None => samples[count - 1].1,
            AggregationType::Count => count as f64,
            AggregationType::First => samples[0].1,
            AggregationType::Last => samples[count - 1].1,
            AggregationType::Sum => samples.iter().map(|s| s.1).sum(),
            AggregationType::Avg => samples.iter().map(|s| s.1).sum::<f64>() / (count as f64),
            AggregationType::Min => samples.iter().map(|s| s.1).fold(f64::INFINITY, f64::min),
            AggregationType::Max => samples
                .iter()
                .map(|s| s.1)
                .fold(f64::NEG_INFINITY, f64::max),
            AggregationType::Range => {
                let mut min_v = f64::INFINITY;
                let mut max_v = f64::NEG_INFINITY;
                for &(_, val) in samples {
                    if val < min_v {
                        min_v = val;
                    }
                    if val > max_v {
                        max_v = val;
                    }
                }
                max_v - min_v
            }
            AggregationType::VarP
            | AggregationType::StdP
            | AggregationType::VarS
            | AggregationType::StdS => {
                let n = count as f64;
                let mut sum = 0.0;
                let mut sq_sum = 0.0;
                for &(_, val) in samples {
                    sum += val;
                    sq_sum += val * val;
                }
                let var_p = ((sq_sum - (sum * sum) / n) / n).max(0.0);
                match self.agg_type {
                    AggregationType::VarP => var_p,
                    AggregationType::StdP => var_p.sqrt(),
                    AggregationType::VarS => {
                        if count <= 1 {
                            0.0
                        } else {
                            var_p * n / (n - 1.0)
                        }
                    }
                    AggregationType::StdS => {
                        if count <= 1 {
                            0.0
                        } else {
                            (var_p * n / (n - 1.0)).max(0.0).sqrt()
                        }
                    }
                    _ => 0.0,
                }
            }
            AggregationType::Twa => {
                if count == 1 {
                    samples[0].1
                } else {
                    let total_time_span = samples[count - 1].0 - samples[0].0;
                    if total_time_span == 0 {
                        samples.iter().map(|s| s.1).sum::<f64>() / (count as f64)
                    } else {
                        let mut weighted_sum = 0.0;
                        for i in 0..count - 1 {
                            let dt = (samples[i + 1].0 - samples[i].0) as f64;
                            let avg_v = (samples[i].1 + samples[i + 1].1) * 0.5;
                            weighted_sum += avg_v * dt;
                        }
                        weighted_sum / (total_time_span as f64)
                    }
                }
            }
        }
    }

    /// 切分并聚合采样序列(默认 Start 对齐,不填充空桶)
    #[inline]
    pub fn split_and_aggregate(
        &self,
        samples: &[(u64, f64)],
        limit: Option<usize>,
    ) -> Vec<(u64, f64)> {
        self.split_and_aggregate_opt(samples, limit, false, BucketTimestampType::Start)
    }

    /// 切分并聚合采样序列(支持 limit、empty 桶填充以及时间戳对齐选项)
    pub fn split_and_aggregate_opt(
        &self,
        samples: &[(u64, f64)],
        limit: Option<usize>,
        is_return_empty: bool,
        ts_type: BucketTimestampType,
    ) -> Vec<(u64, f64)> {
        if samples.is_empty() {
            return Vec::new();
        }

        let get_bucket_ts = |left: u64| -> u64 {
            match ts_type {
                BucketTimestampType::Start => left,
                BucketTimestampType::End => left + self.bucket_duration,
                BucketTimestampType::Mid => left + self.bucket_duration / 2,
            }
        };

        let buckets = self.split_samples_to_buckets(samples);
        if buckets.is_empty() {
            return Vec::new();
        }

        if !is_return_empty {
            let cap = if let Some(l) = limit {
                l.min(buckets.len())
            } else {
                buckets.len()
            };
            let mut results = Vec::with_capacity(cap);
            for (bucket_left, bucket_samples) in buckets {
                let agg_val = self.aggregate_samples(bucket_samples);
                results.push((get_bucket_ts(bucket_left), agg_val));
                if let Some(l) = limit
                    && results.len() >= l
                {
                    break;
                }
            }
            return results;
        }

        // 处理 EMPTY 模式:双指针顺序填充空桶,避免哈希开销
        let mut results = Vec::new();
        let last_left = buckets[buckets.len() - 1].0;
        let mut curr_left = buckets[0].0;
        let mut bucket_idx = 0;
        let mut last_known_val = f64::NAN;

        while curr_left <= last_left {
            let out_ts = get_bucket_ts(curr_left);
            if bucket_idx < buckets.len() && buckets[bucket_idx].0 == curr_left {
                let b_samples = buckets[bucket_idx].1;
                let agg_val = self.aggregate_samples(b_samples);
                if let Some(last_s) = b_samples.last() {
                    last_known_val = last_s.1;
                }
                results.push((out_ts, agg_val));
                bucket_idx += 1;
            } else {
                let empty_val = match self.agg_type {
                    AggregationType::Sum | AggregationType::Count => 0.0,
                    AggregationType::Last => last_known_val,
                    _ => f64::NAN,
                };
                results.push((out_ts, empty_val));
            }

            if let Some(l) = limit
                && results.len() >= l
            {
                break;
            }

            curr_left = self.calculate_aligned_bucket_right(curr_left);
        }

        results
    }
}

/// 创建 TS 选项(对标 Apache Kvrocks TSCreateOption)
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct TSCreateOption {
    pub retention_time: u64,
    pub chunk_size: u64,
    pub chunk_type: ChunkType,
    pub duplicate_policy: DuplicatePolicy,
    pub source_key: String,
    pub labels: Vec<(String, String)>,
}

/// TS.RANGE 检索选项(对标 Apache Kvrocks TSRangeOption)
#[derive(Debug, Clone, PartialEq, Default)]
pub struct TSRangeOption {
    pub start_ts: u64,
    pub end_ts: u64,
    pub count_limit: Option<usize>,
    pub filter_by_ts: BTreeSet<u64>,
    pub filter_by_value: Option<(f64, f64)>,
    pub aggregator: Option<Aggregator>,
    pub is_return_latest: bool,
    pub is_return_empty: bool,
    pub bucket_timestamp_type: BucketTimestampType,
}

/// 多序列聚合组 Reducer 类型(对标 Apache Kvrocks GroupReducerType)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, bitcode::Encode, bitcode::Decode)]
#[repr(u8)]
pub enum GroupReducerType {
    #[default]
    None = 0,
    Avg = 1,
    Sum = 2,
    Min = 3,
    Max = 4,
    Range = 5,
    Count = 6,
    StdP = 7,
    StdS = 8,
    VarP = 9,
    VarS = 10,
    Twa = 11,
    First = 12,
    Last = 13,
}

impl FromStr for GroupReducerType {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_ascii_uppercase().as_str() {
            "NONE" => Ok(Self::None),
            "AVG" => Ok(Self::Avg),
            "SUM" => Ok(Self::Sum),
            "MIN" => Ok(Self::Min),
            "MAX" => Ok(Self::Max),
            "RANGE" => Ok(Self::Range),
            "COUNT" => Ok(Self::Count),
            "STD.P" | "STDP" => Ok(Self::StdP),
            "STD.S" | "STDS" => Ok(Self::StdS),
            "VAR.P" | "VARP" => Ok(Self::VarP),
            "VAR.S" | "VARS" => Ok(Self::VarS),
            "TWA" => Ok(Self::Twa),
            "FIRST" => Ok(Self::First),
            "LAST" => Ok(Self::Last),
            _ => Err(()),
        }
    }
}

impl Display for GroupReducerType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl GroupReducerType {
    pub fn parse(s: &str) -> Option<Self> {
        s.parse().ok()
    }

    #[inline]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Avg => "avg",
            Self::Sum => "sum",
            Self::Min => "min",
            Self::Max => "max",
            Self::Range => "range",
            Self::Count => "count",
            Self::StdP => "std.p",
            Self::StdS => "std.s",
            Self::VarP => "var.p",
            Self::VarS => "var.s",
            Self::Twa => "twa",
            Self::First => "first",
            Self::Last => "last",
        }
    }
}

/// TS.MGET 选项
#[derive(Debug, Clone, Default)]
pub struct TSMGetOption {
    pub with_labels: bool,
    pub selected_labels: RapidHashSet<String>,
    pub filters: Vec<String>,
}

/// TS.MGET 结果
#[derive(Debug, Clone, PartialEq)]
pub struct TSMGetResult {
    pub name: String,
    pub labels: Vec<(String, String)>,
    pub sample: Option<(u64, f64)>,
}

/// TS.MRANGE 选项
#[derive(Debug, Clone, Default)]
pub struct TSMRangeOption {
    pub mget: TSMGetOption,
    pub range: TSRangeOption,
    pub reducer: GroupReducerType,
    pub group_by_label: Option<String>,
}

/// TS.MRANGE 结果
#[derive(Debug, Clone, PartialEq)]
pub struct TSMRangeResult {
    pub name: String,
    pub labels: Vec<(String, String)>,
    pub samples: Vec<(u64, f64)>,
    pub source_keys: Vec<String>,
}

/// 下游降采样元数据(对标 Apache Kvrocks TSDownStreamMeta)
#[derive(Debug, Clone, PartialEq, Default, bitcode::Encode, bitcode::Decode)]
pub struct TSDownStreamMeta {
    pub aggregator: Aggregator,
    pub latest_bucket_idx: u64,
    pub u64_auxs: Vec<u64>,
    pub f64_auxs: Vec<f64>,
}

impl TSDownStreamMeta {
    #[inline]
    pub fn new(aggregator: Aggregator) -> Self {
        let mut meta = Self {
            aggregator,
            latest_bucket_idx: 0,
            u64_auxs: Vec::new(),
            f64_auxs: Vec::new(),
        };
        meta.reset_auxs();
        meta
    }

    pub fn reset_auxs(&mut self) {
        match self.aggregator.agg_type {
            AggregationType::Sum | AggregationType::Count => {
                self.f64_auxs = vec![0.0];
                self.u64_auxs.clear();
            }
            AggregationType::Min | AggregationType::Max => {
                self.f64_auxs = vec![f64::NAN];
                self.u64_auxs.clear();
            }
            AggregationType::First => {
                self.u64_auxs = vec![u64::MAX];
                self.f64_auxs = vec![f64::NAN];
            }
            AggregationType::Last => {
                self.u64_auxs = vec![0];
                self.f64_auxs = vec![f64::NAN];
            }
            AggregationType::Avg => {
                self.u64_auxs = vec![0];
                self.f64_auxs = vec![0.0];
            }
            AggregationType::StdP
            | AggregationType::StdS
            | AggregationType::VarP
            | AggregationType::VarS => {
                self.u64_auxs = vec![0];
                self.f64_auxs = vec![0.0, 0.0];
            }
            AggregationType::Range => {
                self.f64_auxs = vec![f64::NAN, f64::NAN];
                self.u64_auxs.clear();
            }
            _ => {
                self.u64_auxs.clear();
                self.f64_auxs.clear();
            }
        }
    }

    /// 向最新桶聚合新样本并更新辅助状态(对标 Kvrocks AggregateLatestBucket)
    pub fn aggregate_latest_bucket(&mut self, samples: &[(u64, f64)]) {
        if samples.is_empty() {
            return;
        }
        match self.aggregator.agg_type {
            AggregationType::Sum => {
                if self.f64_auxs.is_empty() {
                    self.f64_auxs = vec![0.0];
                }
                self.f64_auxs[0] += samples.iter().map(|s| s.1).sum::<f64>();
            }
            AggregationType::Min => {
                if self.f64_auxs.is_empty() {
                    self.f64_auxs = vec![f64::NAN];
                }
                let min_v = samples.iter().map(|s| s.1).fold(f64::INFINITY, f64::min);
                self.f64_auxs[0] = if self.f64_auxs[0].is_nan() {
                    min_v
                } else {
                    self.f64_auxs[0].min(min_v)
                };
            }
            AggregationType::Max => {
                if self.f64_auxs.is_empty() {
                    self.f64_auxs = vec![f64::NAN];
                }
                let max_v = samples
                    .iter()
                    .map(|s| s.1)
                    .fold(f64::NEG_INFINITY, f64::max);
                self.f64_auxs[0] = if self.f64_auxs[0].is_nan() {
                    max_v
                } else {
                    self.f64_auxs[0].max(max_v)
                };
            }
            AggregationType::Count => {
                if self.f64_auxs.is_empty() {
                    self.f64_auxs = vec![0.0];
                }
                self.f64_auxs[0] += samples.len() as f64;
            }
            AggregationType::First => {
                if self.u64_auxs.is_empty() {
                    self.u64_auxs = vec![u64::MAX];
                    self.f64_auxs = vec![f64::NAN];
                }
                if self.f64_auxs[0].is_nan() || samples[0].0 < self.u64_auxs[0] {
                    self.f64_auxs[0] = samples[0].1;
                    self.u64_auxs[0] = samples[0].0;
                }
            }
            AggregationType::Last => {
                if self.u64_auxs.is_empty() {
                    self.u64_auxs = vec![0];
                    self.f64_auxs = vec![f64::NAN];
                }
                let last_s = samples[samples.len() - 1];
                if self.f64_auxs[0].is_nan() || last_s.0 >= self.u64_auxs[0] {
                    self.f64_auxs[0] = last_s.1;
                    self.u64_auxs[0] = last_s.0;
                }
            }
            AggregationType::Avg => {
                if self.u64_auxs.is_empty() {
                    self.u64_auxs = vec![0];
                    self.f64_auxs = vec![0.0];
                }
                self.u64_auxs[0] += samples.len() as u64;
                self.f64_auxs[0] += samples.iter().map(|s| s.1).sum::<f64>();
            }
            AggregationType::StdP
            | AggregationType::StdS
            | AggregationType::VarP
            | AggregationType::VarS => {
                if self.u64_auxs.is_empty() {
                    self.u64_auxs = vec![0];
                    self.f64_auxs = vec![0.0, 0.0];
                }
                self.u64_auxs[0] += samples.len() as u64;
                self.f64_auxs[0] += samples.iter().map(|s| s.1).sum::<f64>();
                self.f64_auxs[1] += samples.iter().map(|s| s.1 * s.1).sum::<f64>();
            }
            AggregationType::Range => {
                if self.f64_auxs.len() < 2 {
                    self.f64_auxs = vec![f64::NAN, f64::NAN];
                }
                let min_v = samples.iter().map(|s| s.1).fold(f64::INFINITY, f64::min);
                let max_v = samples
                    .iter()
                    .map(|s| s.1)
                    .fold(f64::NEG_INFINITY, f64::max);
                if self.f64_auxs[0].is_nan() {
                    self.f64_auxs[0] = min_v;
                    self.f64_auxs[1] = max_v;
                } else {
                    self.f64_auxs[0] = self.f64_auxs[0].min(min_v);
                    self.f64_auxs[1] = self.f64_auxs[1].max(max_v);
                }
            }
            AggregationType::Twa | AggregationType::None => {}
        }
    }

    /// 跨多桶聚合样本,生成已封口时间桶样本并维护当前最新桶辅助信息(对标 Kvrocks AggregateMultiBuckets)
    pub fn aggregate_multi_buckets(
        &mut self,
        bucket_spans: &[(u64, &[(u64, f64)])],
        skip_last_bucket: bool,
    ) -> Vec<(u64, f64)> {
        let mut res = Vec::new();
        for (i, &(bucket_left, span)) in bucket_spans.iter().enumerate() {
            if span.is_empty() {
                continue;
            }
            if bucket_left < self.latest_bucket_idx {
                continue;
            }
            if bucket_left > self.latest_bucket_idx && !self.f64_auxs.is_empty() {
                let finalized_v = match self.aggregator.agg_type {
                    AggregationType::Sum
                    | AggregationType::Min
                    | AggregationType::Max
                    | AggregationType::Count
                    | AggregationType::First
                    | AggregationType::Last => self.f64_auxs[0],
                    AggregationType::Avg => {
                        let count = self.u64_auxs.first().copied().unwrap_or(1) as f64;
                        if count > 0.0 {
                            self.f64_auxs[0] / count
                        } else {
                            0.0
                        }
                    }
                    AggregationType::StdP
                    | AggregationType::StdS
                    | AggregationType::VarP
                    | AggregationType::VarS => {
                        let count = self.u64_auxs.first().copied().unwrap_or(1) as f64;
                        if count > 0.0 {
                            let sum = self.f64_auxs[0];
                            let sq_sum = self.f64_auxs.get(1).copied().unwrap_or(0.0);
                            let var_p = ((sq_sum - (sum * sum) / count) / count).max(0.0);
                            match self.aggregator.agg_type {
                                AggregationType::VarP => var_p,
                                AggregationType::StdP => var_p.sqrt(),
                                AggregationType::VarS => {
                                    if count <= 1.0 {
                                        0.0
                                    } else {
                                        var_p * count / (count - 1.0)
                                    }
                                }
                                AggregationType::StdS => {
                                    if count <= 1.0 {
                                        0.0
                                    } else {
                                        (var_p * count / (count - 1.0)).max(0.0).sqrt()
                                    }
                                }
                                _ => 0.0,
                            }
                        } else {
                            0.0
                        }
                    }
                    AggregationType::Range if self.f64_auxs.len() >= 2 => {
                        self.f64_auxs[1] - self.f64_auxs[0]
                    }
                    _ => 0.0,
                };
                res.push((self.latest_bucket_idx, finalized_v));
                self.reset_auxs();
                self.latest_bucket_idx = bucket_left;
            }

            if skip_last_bucket && i == bucket_spans.len() - 1 {
                break;
            }
            self.aggregate_latest_bucket(span);
        }
        res
    }

    pub fn encode(&self) -> Vec<u8> {
        let cap = 1 + 8 + 8 + 8 + 4 + self.u64_auxs.len() * 8 + 4 + self.f64_auxs.len() * 8;
        let mut buf = Vec::with_capacity(cap);
        buf.push(self.aggregator.agg_type as u8);
        buf.extend_from_slice(&self.aggregator.bucket_duration.to_be_bytes());
        buf.extend_from_slice(&self.aggregator.alignment.to_be_bytes());
        buf.extend_from_slice(&self.latest_bucket_idx.to_be_bytes());
        buf.extend_from_slice(&(self.u64_auxs.len() as u32).to_be_bytes());
        for &u in &self.u64_auxs {
            buf.extend_from_slice(&u.to_be_bytes());
        }
        buf.extend_from_slice(&(self.f64_auxs.len() as u32).to_be_bytes());
        for &f in &self.f64_auxs {
            buf.extend_from_slice(&f.to_be_bytes());
        }
        buf
    }

    pub fn decode(bytes: &[u8]) -> Option<Self> {
        if bytes.len() < 1 + 8 + 8 + 8 + 4 {
            return None;
        }
        let agg_type = match bytes[0] {
            1 => AggregationType::Sum,
            2 => AggregationType::Min,
            3 => AggregationType::Max,
            4 => AggregationType::Count,
            5 => AggregationType::First,
            6 => AggregationType::Last,
            7 => AggregationType::Avg,
            8 => AggregationType::Range,
            9 => AggregationType::StdP,
            10 => AggregationType::StdS,
            11 => AggregationType::VarP,
            12 => AggregationType::VarS,
            13 => AggregationType::Twa,
            _ => AggregationType::None,
        };
        let mut offset = 1;
        let bucket_duration = u64::from_be_bytes(bytes[offset..offset + 8].try_into().ok()?);
        offset += 8;

        let alignment = u64::from_be_bytes(bytes[offset..offset + 8].try_into().ok()?);
        offset += 8;

        let latest_bucket_idx = u64::from_be_bytes(bytes[offset..offset + 8].try_into().ok()?);
        offset += 8;

        let u64_len = u32::from_be_bytes(bytes[offset..offset + 4].try_into().ok()?) as usize;
        offset += 4;

        let mut u64_auxs = Vec::with_capacity(u64_len);
        for _ in 0..u64_len {
            if offset + 8 > bytes.len() {
                break;
            }
            u64_auxs.push(u64::from_be_bytes(
                bytes[offset..offset + 8].try_into().ok()?,
            ));
            offset += 8;
        }

        let mut f64_auxs = Vec::new();
        if offset + 4 <= bytes.len() {
            let f64_len = u32::from_be_bytes(bytes[offset..offset + 4].try_into().ok()?) as usize;
            offset += 4;

            f64_auxs.reserve(f64_len);
            for _ in 0..f64_len {
                if offset + 8 > bytes.len() {
                    break;
                }
                f64_auxs.push(f64::from_be_bytes(
                    bytes[offset..offset + 8].try_into().ok()?,
                ));
                offset += 8;
            }
        }

        Some(Self {
            aggregator: Aggregator::new(agg_type, bucket_duration, alignment),
            latest_bucket_idx,
            u64_auxs,
            f64_auxs,
        })
    }
}

/// TS.INFO 响应结果(对标 Apache Kvrocks TSInfoResult)
#[derive(Debug, Clone, PartialEq)]
pub struct TSInfoResult {
    pub total_samples: u64,
    pub memory_usage: u64,
    pub first_timestamp: u64,
    pub last_timestamp: u64,
    pub retention_time: u64,
    pub chunk_size: u64,
    pub chunk_type: ChunkType,
    pub duplicate_policy: DuplicatePolicy,
    pub labels: Vec<(String, String)>,
    pub source_key: String,
    pub downstream_rules: Vec<(String, Aggregator)>,
}