-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathaccumulator.rs
More file actions
2096 lines (1810 loc) · 74.9 KB
/
Copy pathaccumulator.rs
File metadata and controls
2096 lines (1810 loc) · 74.9 KB
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
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Accumulator logic for time-sliced metric capture
//!
//! This module solves an important problem for lading. We need metrics-rs
//! metrics to reach our capture file, prometheus export depending on how users
//! configure it. This has worked well since the beginning of the
//! project. However, we need also to support "historical" or "delayed"
//! metrics. Consider a generator that mimics the Datadog Intake API. Metrics
//! sent to this intake are batched in 10 second intervals, meaning the
//! metrics-rs understanding of all metrics arriving 'now' no longer serves all
//! needed cases.
//!
//! To that end this module supports a Counter and Gauge metric in a 60-tick
//! rolling accumulation. The core structure is [`Accumulator`]. Calling code is
//! responsible for defining the real-clock duration of a 'tick'. Conceptually,
//! every tick the [`Accumulator`] creates a new 0th interval where 'now' writes
//! are stored. The previous 0th interval becomes the 1st, the 1st the 2nd and
//! so forth. This is called a 'roll'. After 60 ticks the 60th tick becomes
//! 'flushable', that is, the metrics stored in that interval will be returned
//! to the caller should they be requested. Tick time advances independently of
//! flushes and metrics are _not_ stored to the 61st interval. [`Accumulator`]
//! supports a `drain` operation that consumes the structure, allowing for
//! metrics to be exfiltrated on shutdown without delay.
//
//! # Semantics
//!
//! The [`Accumulator`] accepts writes to any absolute tick `T` such that:
//!
//! * `T <= current_tick` (not in the future)
//! * `current_tick - T < 60` (within the 60-interval window)
//!
//! Writes do not expire. When a tick time advances data in the previous
//! interval is copied forward into the new interval.
//!
//! ## Counters
//!
//! A `Counter` write may be either `Increment(k, T, i)` or `Absolute(k, T, i)`,
//! where `T` is the absolute logical tick when the event occurred, `k` is the
//! identifying key of the metric, and `i` is the counter value (`i >= 0`).
//!
//! The operation `Increment(k, T, i)` sums `i` to the value of `k` in each
//! interval Ti such that T <= Ti <= `current_tick`, or sets the value to `i` if
//! there is no value in the interval for `k`. The operation `Absolute(k, T, i)`
//! sets `i` as the value of `k` in each interval Ti such that T <= Ti <=
//! `current_tick`.
//!
//! As a matter of state notation let's adopt a notation for discussing the
//! evolution of Accumulator state. In what follows we'll describe two
//! increments to `k` in the same tick `0` with no tick advancement:
//!
//! ```
//! [Increment(k, 0, 10), Increment(k, 0, 100)]
//! -> 0:[-] => []
//! -> 0:[Increment(k, 0, 10)] => [(k, 10)]
//! -> 0:[Increment(k, 0, 100)] => [(k, 110)]
//! ```
//!
//! In the above we begin with empty state -- signaled by `0:[-] => []` -- and
//! have two increments at time 0 to k, first of 10 and then
//! 100. `0:[Increment(k, 0, 10)]` denotes the operation `Increment(k, 0, 10)`
//! being applied to the state at tick 0, resulting in state `[(k, 10)]`. We
//! allow a further operation `TICK` which advances the tick interval.
//!
//! ```
//! [Increment(k, 0, 10), TICK, Increment(k, 0, 100)]
//! -> 0:[-] => []
//! -> 0:[Increment(k, 0, 10)] => [(k, 10)]
//! -> 0:[TICK] => [(k, 10), (k, 10)]
//! -> 1:[Increment(k, 0, 100)] => [(k, 110), (k, 110)]]
//! ```
//!
//! Let's examine the mixture of absolute and increment writes. For instance, an
//! increment and absolute write to the same `k`:
//!
//! ```
//! [Increment(k, 0, 10), Absolute(k, 2, 100)]
//! -> 2:[-] => []
//! -> 2:[Increment(k, 0, 10)] => [(k, 10), (k, 10), (k, 10)]
//! -> 2:[Absolute(k, 2, 100)] => [(k, 10), (k, 10), (k, 100)]
//! ```
//!
//! Absolute writes overwrite any value previously set to `k` in an
//! interval. But, what if the order of writes were different?
//!
//! ```
//! [Absolute(k, 2, 100), Increment(k, 0, 10)]
//! -> 2:[-] => []
//! -> 2:[Absolute(k, 2, 100)] => [∅, ∅, (k, 100)]
//! -> 2:[Increment(k, 0, 10)] => [(k, 10), (k, 10), (k, 110)]
//! ```
//!
//! Two separate outcomes! The `Accumulator` does not admit concurrent writes
//! and so we analyze writes in serial. The order of writes therefore matters
//! very much in the determination of state. Stated logically:
//!
//! * `Increment` is associative and commutative.
//! * `Absolute` is idempotent.
//! * `Absolute` does not commute with `Increment`.
//!
//! ## Gauges
//!
//! A `Gauge` write may be either `Increment(k, T, i)` or `Decrement(k, T, i)`
//! or `Set(k, T, i)`. The semantic considerations of `Counter` discussed above
//! largely apply to `Gauge`. Loss of associativity compared to `Counter` is a
//! result of the interior f64. Logically:
//!
//! * `Increment` is commutative.
//! * `Decrement` is commutative.
//! * `Increment` and `Decrement` commute.
//! * `Set` is idempotent.
//! * `Set` does not commute with `Increment` nor `Decrement`.
//!
//! ## Histograms
//!
//! A `Histogram` write is `Record(k, T, v)` where `T` is the absolute logical
//! tick when the sample was recorded, `k` is the identifying key of the metric,
//! and `v` is a finite sample value. The operation `Record(k, T, v)` adds sample
//! `v` to the `DDSketch` distribution at key `k` in each interval Ti such that
//! T <= Ti <= `current_tick`. Infinity and NaN values are rejected.
//!
//! Histograms do not copy forward on tick advance. Each interval stores only
//! samples recorded during that tick.
//!
//! ```
//! [Record(k, 0, 10.0), Record(k, 0, 20.0), TICK]
//! -> 0:[-] => []
//! -> 0:[Record(k, 0, 10.0)] => [(k, DDSketch{10.0})]
//! -> 0:[Record(k, 0, 20.0)] => [(k, DDSketch{10.0, 20.0})]
//! -> 0:[TICK] => [(k, DDSketch{10.0, 20.0}), (k, DDSketch{})]
//! ```
//!
//! On TICK, the new interval receives an empty sketch. This contrasts with
//! Counters and Gauges which copy forward. Historical writes populate multiple
//! intervals:
//!
//! ```
//! [TICK, Record(k, 0, 5.0)]
//! -> 0:[-] => []
//! -> 0:[TICK] => [∅, ∅]
//! -> 1:[Record(k, 0, 5.0)] => [(k, DDSketch{5.0}), (k, DDSketch{5.0})]
//! ```
//!
//! Flush extracts the sketch from the flushable interval and replaces it with
//! an empty sketch.
//!
//! Stated logically:
//!
//! * `Record` is not commutative.
//! * `Record` is not idempotent.
//! * Historical writes populate all intervals from T to `current_tick`.
//! * Empty sketches are not flushed.
//! * Infinity and NaN are filtered with warning.
use datadog_protos::metrics::Dogsketch;
use ddsketch_agent::DDSketch;
use metrics::Key;
use protobuf::Message;
use rustc_hash::FxHashMap;
use tracing::warn;
use crate::metric::{Counter, CounterValue, Gauge, GaugeValue, Histogram};
pub(crate) const INTERVALS: usize = 60;
// The actual buffer size is INTERVALS + 1 to prevent accidental overwrite when
// we have exactly INTERVALS unflushed ticks. This extra slot acts as a guard to
// prevent the write-advance-flush pattern from overwriting unflushed data.
const BUFFER_SIZE: usize = INTERVALS + 1;
#[inline]
#[expect(clippy::cast_possible_truncation)]
fn interval_idx(tick: u64) -> usize {
// Use BUFFER_SIZE for modulo to utilize the extra guard slot
(tick % (BUFFER_SIZE as u64)) as usize
}
/// Errors produced by [`Accumulator`]
#[derive(thiserror::Error, Debug, Copy, Clone)]
pub enum Error {
/// Metric tick is too old
#[error("Tick for metric too old: {tick}")]
TickTooOld { tick: u64 },
/// Metric tick is from the future
#[error("Tick for metric from future: {tick}")]
FutureTick { tick: u64 },
}
/// Iterator that drains all accumulated metrics during shutdown.
///
/// Each iteration flushes metrics from a single interval until no intervals
/// remain.
pub(crate) struct DrainIter {
accumulator: Accumulator,
remaining: usize,
}
impl Iterator for DrainIter {
type Item = Vec<(Key, MetricValue, u64)>;
fn next(&mut self) -> Option<Self::Item> {
if self.remaining == 0 {
return None;
}
self.remaining -= 1;
// Calculate which tick to flush based on what's already been flushed
let tick_to_flush = if let Some(last) = self.accumulator.last_flushed_tick {
last + 1
} else {
0
};
// Directly gather metrics from the tick's interval without going
// through flush(). flush/advance_tick are intended as a pair of
// operations and one should not be used without the other.
let mut metrics = Vec::new();
let interval = interval_idx(tick_to_flush);
for (key, values) in &self.accumulator.counters {
let value = values[interval];
metrics.push((key.clone(), MetricValue::Counter(value), tick_to_flush));
}
for (key, values) in &self.accumulator.gauges {
let value = values[interval];
metrics.push((key.clone(), MetricValue::Gauge(value), tick_to_flush));
}
for (key, sketches) in &mut self.accumulator.histograms {
let sketch = std::mem::take(&mut sketches[interval]);
if sketch.count() > 0 {
let mut dogsketch = Dogsketch::new();
sketch.merge_to_dogsketch(&mut dogsketch);
let sketch_bytes = dogsketch.write_to_bytes().unwrap_or_else(|_| {
unreachable!(
"prost::Message::write_to_bytes on an in-memory Dogsketch cannot fail"
)
});
metrics.push((
key.clone(),
MetricValue::Histogram(sketch_bytes),
tick_to_flush,
));
}
}
self.accumulator.last_flushed_tick = Some(tick_to_flush);
Some(metrics)
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.remaining, Some(self.remaining))
}
}
impl ExactSizeIterator for DrainIter {}
/// Represents a metric value (counter, gauge, or histogram)
#[derive(Clone)]
pub(crate) enum MetricValue {
/// Counter value
Counter(u64),
/// Gauge value
Gauge(f64),
/// Histogram distribution (protobuf-serialized `DDSketch`)
Histogram(Vec<u8>),
}
impl std::fmt::Debug for MetricValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
MetricValue::Counter(v) => f.debug_tuple("Counter").field(v).finish(),
MetricValue::Gauge(v) => f.debug_tuple("Gauge").field(v).finish(),
MetricValue::Histogram(bytes) => {
let count = Dogsketch::parse_from_bytes(bytes)
.ok()
.and_then(|ds| ddsketch_agent::DDSketch::try_from(ds).ok())
.map_or(0, |sketch| sketch.count());
f.debug_tuple("Histogram")
.field(&format!("count={count}"))
.finish()
}
}
}
}
/// Accumulator with 60-interval rolling window for metrics
///
/// # Critical Design Constraints
///
/// This accumulator uses a circular buffer with `BUFFER_SIZE` (61) slots to
/// store INTERVALS (60) ticks worth of data. The extra slot prevents overwrite
/// when exactly INTERVALS ticks are unflushed.
///
/// This means:
/// - Only the most recent 60 ticks of data can be stored at any time.
/// - When tick N is written, it goes to slot N % 61.
/// - The extra slot ensures the write-advance-flush pattern doesn't overwrite
/// data.
pub(crate) struct Accumulator {
counters: FxHashMap<Key, [u64; BUFFER_SIZE]>,
gauges: FxHashMap<Key, [f64; BUFFER_SIZE]>,
histograms: FxHashMap<Key, [DDSketch; BUFFER_SIZE]>,
pub(crate) current_tick: u64,
last_flushed_tick: Option<u64>,
}
impl std::fmt::Debug for Accumulator {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Accumulator")
.field("counters", &self.counters)
.field("gauges", &self.gauges)
.field(
"histograms",
&format!("<{len} histogram keys>", len = self.histograms.len()),
)
.field("current_tick", &self.current_tick)
.field("last_flushed_tick", &self.last_flushed_tick)
.finish()
}
}
impl Accumulator {
pub(crate) fn new() -> Self {
Self {
counters: FxHashMap::default(),
gauges: FxHashMap::default(),
histograms: FxHashMap::default(),
current_tick: 0,
last_flushed_tick: None,
}
}
pub(crate) fn counter(&mut self, c: Counter, tick: u64) -> Result<(), Error> {
if tick > self.current_tick {
warn!(
metric_tick = tick,
current_tick = self.current_tick,
delta = tick - self.current_tick,
timestamp = ?c.timestamp,
key = %c.key.name(),
"Counter metric tick is from future"
);
return Err(Error::FutureTick { tick });
}
let tick_offset = self.current_tick.saturating_sub(tick);
if tick_offset >= INTERVALS as u64 {
warn!(
metric_tick = tick,
current_tick = self.current_tick,
tick_offset = tick_offset,
timestamp = ?c.timestamp,
key = %c.key.name(),
"Counter metric tick too old"
);
return Err(Error::TickTooOld { tick });
}
let values = self.counters.entry(c.key).or_insert([0; BUFFER_SIZE]);
for offset in 0..=tick_offset {
let target_tick = self.current_tick - offset; // always lands within u64 range
let interval = interval_idx(target_tick);
match c.value {
CounterValue::Absolute(v) => values[interval] = v,
CounterValue::Increment(v) => values[interval] += v,
}
}
Ok(())
}
pub(crate) fn gauge(&mut self, g: Gauge, tick: u64) -> Result<(), Error> {
if tick > self.current_tick {
warn!(
metric_tick = tick,
current_tick = self.current_tick,
delta = tick - self.current_tick,
timestamp = ?g.timestamp,
key = %g.key.name(),
"Gauge metric tick is from future"
);
return Err(Error::FutureTick { tick });
}
let tick_offset = self.current_tick.saturating_sub(tick);
if tick_offset >= INTERVALS as u64 {
warn!(
metric_tick = tick,
current_tick = self.current_tick,
tick_offset = tick_offset,
timestamp = ?g.timestamp,
key = %g.key.name(),
"Gauge metric tick too old"
);
return Err(Error::TickTooOld { tick });
}
let values = self.gauges.entry(g.key).or_insert([0.0; BUFFER_SIZE]);
for offset in 0..=tick_offset {
let target_tick = self.current_tick - offset; // always lands within u64 range
let interval = interval_idx(target_tick);
match g.value {
GaugeValue::Set(v) => values[interval] = v,
GaugeValue::Increment(v) => values[interval] += v,
GaugeValue::Decrement(v) => values[interval] -= v,
}
}
Ok(())
}
pub(crate) fn histogram(&mut self, h: Histogram, tick: u64) -> Result<(), Error> {
if tick > self.current_tick {
warn!(
metric_tick = tick,
current_tick = self.current_tick,
delta = tick - self.current_tick,
timestamp = ?h.timestamp,
key = %h.key.name(),
"Histogram metric tick is from future"
);
return Err(Error::FutureTick { tick });
}
let tick_offset = self.current_tick.saturating_sub(tick);
if tick_offset >= INTERVALS as u64 {
warn!(
metric_tick = tick,
current_tick = self.current_tick,
tick_offset = tick_offset,
timestamp = ?h.timestamp,
key = %h.key.name(),
"Histogram metric tick too old"
);
return Err(Error::TickTooOld { tick });
}
// Filter infinity and NaN. DDSketch panics on infinite values.
if !h.value.is_finite() {
warn!(
key = %h.key.name(),
value = h.value,
tick = tick,
"Histogram sample rejected - infinity or NaN not supported by DDSketch"
);
return Ok(());
}
let sketches = self
.histograms
.entry(h.key)
.or_insert_with(|| std::array::from_fn(|_| DDSketch::default()));
for offset in 0..=tick_offset {
let target_tick = self.current_tick - offset;
let interval = interval_idx(target_tick);
sketches[interval].insert(h.value);
}
Ok(())
}
/// Advance tick and copy forward values
///
/// This function is intended to be paired with calls to `flush`. It WILL
/// overwrite data if data is not flushed in a timely fashion.
pub(crate) fn advance_tick(&mut self) {
let old_interval = interval_idx(self.current_tick);
// WARNING: When we hit u64::MAX whether this wrapping_add is correct or
// not depends on the value of INTERVALS. For instance, u64::MAX % 61 ==
// 15 so when we wrap to 0 we'll index into the wrong spot. However if
// an interval is 1 nanosecond we're looking at a continuous runtime of
// ~500 years before this becomes a problem.
self.current_tick = self.current_tick.wrapping_add(1);
let new_interval = interval_idx(self.current_tick);
for values in self.counters.values_mut() {
values[new_interval] = values[old_interval];
}
for values in self.gauges.values_mut() {
values[new_interval] = values[old_interval];
}
}
/// Flush T-INTERVALS data, returning an iterator of (Key, `MetricValue`, tick)
/// tuples.
///
/// Returns metrics from the interval that is INTERVALS ticks old. If the
/// current tick has not yet reached INTERVALS, returns an empty iterator.
pub(crate) fn flush(&mut self) -> impl Iterator<Item = (Key, MetricValue, u64)> + use<> {
let mut metrics =
Vec::with_capacity(self.counters.len() + self.gauges.len() + self.histograms.len());
if self.current_tick < INTERVALS as u64 {
return metrics.into_iter();
}
let flush_tick = self.current_tick - INTERVALS as u64;
// Debug check to catch misuse during development
debug_assert!(
self.last_flushed_tick.is_none_or(|last| flush_tick > last),
"flush_tick {flush_tick} should be > last_flushed {:?}",
self.last_flushed_tick
);
let flush_interval = interval_idx(flush_tick);
for (key, values) in &self.counters {
let value = values[flush_interval];
metrics.push((key.clone(), MetricValue::Counter(value), flush_tick));
}
for (key, values) in &self.gauges {
let value = values[flush_interval];
metrics.push((key.clone(), MetricValue::Gauge(value), flush_tick));
}
for (key, sketches) in &mut self.histograms {
let sketch = std::mem::take(&mut sketches[flush_interval]);
// Only include histograms with samples. Empty sketches represent
// "no data" which is different from counters/gauges where 0 is
// meaningful.
if sketch.count() > 0 {
let mut dogsketch = Dogsketch::new();
sketch.merge_to_dogsketch(&mut dogsketch);
let sketch_bytes = dogsketch.write_to_bytes().unwrap_or_else(|_| {
unreachable!(
"prost::Message::write_to_bytes on an in-memory Dogsketch cannot fail"
)
});
metrics.push((
key.clone(),
MetricValue::Histogram(sketch_bytes),
flush_tick,
));
}
}
self.last_flushed_tick = Some(flush_tick);
metrics.into_iter()
}
/// Returns an iterator that drains all accumulated metrics.
///
/// Only flushes ticks that haven't been flushed yet. If the most recent
/// `flush()` call already wrote tick N, drain will start from tick N+1.
pub(crate) fn drain(self) -> DrainIter {
// Calculate how many unflushed ticks remain.
//
// After normal operation, current_tick points to the next tick that would
// be written to. All ticks from 0 to (current_tick - 1) have data.
let remaining = if let Some(last_flushed) = self.last_flushed_tick {
// We need to flush from (last_flushed + 1) to (current_tick - 1)
let next_to_flush = last_flushed + 1;
let last_with_data = self.current_tick.saturating_sub(1);
if next_to_flush > last_with_data {
// All ticks have been flushed
0
} else {
// Number of ticks to flush
let to_flush = last_with_data - next_to_flush + 1;
#[expect(clippy::cast_possible_truncation)]
{
to_flush.min(INTERVALS as u64) as usize
}
}
} else {
// No flushes yet. We can flush all ticks that have data (0 to current_tick-1)
// Capped at INTERVALS since that's all we can store
#[expect(clippy::cast_possible_truncation)]
{
self.current_tick.min(INTERVALS as u64) as usize
}
};
DrainIter {
accumulator: self,
remaining,
}
}
#[cfg(test)]
fn get_counter_value(&self, key: &Key, tick: u64) -> u64 {
self.counters
.get(key)
.map_or(0, |intervals| intervals[interval_idx(tick)])
}
#[cfg(test)]
fn get_gauge_value(&self, key: &Key, tick: u64) -> f64 {
self.gauges
.get(key)
.map_or(0.0, |intervals| intervals[interval_idx(tick)])
}
}
#[cfg(test)]
#[expect(
clippy::float_cmp,
reason = "stored values must round-trip exactly; any deviation is a bug"
)]
mod tests {
use super::*;
use crate::metric::{Counter, CounterValue, Gauge, GaugeValue, Histogram};
use proptest::prelude::*;
use std::time::Instant;
fn deserialize_histogram(bytes: &[u8]) -> DDSketch {
let dogsketch = Dogsketch::parse_from_bytes(bytes).expect("parse protobuf");
DDSketch::try_from(dogsketch).expect("convert")
}
// Test helpers that handle the full counter/gauge operation
fn counter_increment(
acc: &mut Accumulator,
key: Key,
tick: u64,
value: u64,
) -> Result<(), Error> {
let counter = Counter {
key,
timestamp: Instant::now(),
value: CounterValue::Increment(value),
};
acc.counter(counter, tick)
}
fn counter_absolute(
acc: &mut Accumulator,
key: Key,
tick: u64,
value: u64,
) -> Result<(), Error> {
let counter = Counter {
key,
timestamp: Instant::now(),
value: CounterValue::Absolute(value),
};
acc.counter(counter, tick)
}
fn gauge_set(acc: &mut Accumulator, key: Key, tick: u64, value: f64) -> Result<(), Error> {
let gauge = Gauge {
key,
timestamp: Instant::now(),
value: GaugeValue::Set(value),
};
acc.gauge(gauge, tick)
}
fn gauge_increment(
acc: &mut Accumulator,
key: Key,
tick: u64,
value: f64,
) -> Result<(), Error> {
let gauge = Gauge {
key,
timestamp: Instant::now(),
value: GaugeValue::Increment(value),
};
acc.gauge(gauge, tick)
}
fn gauge_decrement(
acc: &mut Accumulator,
key: Key,
tick: u64,
value: f64,
) -> Result<(), Error> {
let gauge = Gauge {
key,
timestamp: Instant::now(),
value: GaugeValue::Decrement(value),
};
acc.gauge(gauge, tick)
}
fn histogram_sample(
acc: &mut Accumulator,
key: Key,
tick: u64,
value: f64,
) -> Result<(), Error> {
let histogram = Histogram {
key,
timestamp: Instant::now(),
value,
};
acc.histogram(histogram, tick)
}
#[derive(Debug, Clone)]
enum Op {
CounterIncrement(u64),
CounterAbsolute(u64),
GaugeIncrement(f64),
GaugeDecrement(f64),
GaugeSet(f64),
HistogramRecord(f64),
AdvanceTick,
}
impl Arbitrary for Op {
type Parameters = ();
type Strategy = BoxedStrategy<Self>;
fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
prop_oneof![
(1u64..100u64).prop_map(Op::CounterIncrement),
(1u64..100u64).prop_map(Op::CounterAbsolute),
(0.0f64..100.0f64).prop_map(Op::GaugeIncrement),
(0.0f64..100.0f64).prop_map(Op::GaugeDecrement),
(0.0f64..100.0f64).prop_map(Op::GaugeSet),
(-100.0f64..100.0f64)
.prop_filter("must be finite", |f| f.is_finite())
.prop_map(Op::HistogramRecord),
Just(Op::AdvanceTick),
]
.boxed()
}
}
// NOTE generally speaking in lading project we have a complicated System
// under Test (SUT) and then a simple, 'obviously correct' model that we do
// model checking against. The SuT here is already very simple and so I have
// elected to leave the stub of what a model check might be while leaning
// more into unit tests. My hope is that as the SuT evolves into something
// more complex we can pursue the more common project test approach.
proptest! {
#[test]
fn random_operations_maintain_invariants(ops in prop::collection::vec(any::<Op>(), 0..50)) {
let key = Key::from_name("test");
let mut acc = Accumulator::new();
let initial_tick = acc.current_tick;
for op in ops {
let old_tick = acc.current_tick;
match op {
Op::CounterIncrement(v) => {
let _ = counter_increment(&mut acc, key.clone(), 0, v);
}
Op::CounterAbsolute(v) => {
let _ = counter_absolute(&mut acc, key.clone(), 0, v);
}
Op::GaugeIncrement(v) => {
let _ = gauge_increment(&mut acc, key.clone(), 0, v);
}
Op::GaugeDecrement(v) => {
let _ = gauge_decrement(&mut acc, key.clone(), 0, v);
}
Op::GaugeSet(v) => {
let _ = gauge_set(&mut acc, key.clone(), 0, v);
}
Op::HistogramRecord(v) => {
let _ = histogram_sample(&mut acc, key.clone(), 0, v);
}
Op::AdvanceTick => {
acc.advance_tick();
}
}
// Invariants
assert!(acc.current_tick >= old_tick, "tick must not decrease");
assert!(
acc.current_tick <= old_tick + 1,
"tick can only advance by 1 at a time"
);
assert!(
acc.current_tick >= initial_tick,
"tick must be >= initial tick"
);
}
}
}
// Counter: Increment is associative and commutative
#[test]
fn counter_increment_commutative() {
let key = Key::from_name("test");
// [Increment(5), Increment(3)]
let mut acc1 = Accumulator::new();
counter_increment(&mut acc1, key.clone(), 0, 5).unwrap();
counter_increment(&mut acc1, key.clone(), 0, 3).unwrap();
// [Increment(3), Increment(5)]
let mut acc2 = Accumulator::new();
counter_increment(&mut acc2, key.clone(), 0, 3).unwrap();
counter_increment(&mut acc2, key.clone(), 0, 5).unwrap();
assert_eq!(
acc1.get_counter_value(&key, acc1.current_tick),
acc2.get_counter_value(&key, acc2.current_tick)
);
assert_eq!(acc1.get_counter_value(&key, acc1.current_tick), 8);
}
// Counter: Absolute is idempotent
#[test]
fn counter_absolute_idempotent() {
let key = Key::from_name("test");
// [Absolute(100)]
let mut acc1 = Accumulator::new();
counter_absolute(&mut acc1, key.clone(), 0, 100).unwrap();
// [Absolute(100), Absolute(100)]
let mut acc2 = Accumulator::new();
counter_absolute(&mut acc2, key.clone(), 0, 100).unwrap();
counter_absolute(&mut acc2, key.clone(), 0, 100).unwrap();
assert_eq!(
acc1.get_counter_value(&key, acc1.current_tick),
acc2.get_counter_value(&key, acc2.current_tick)
);
assert_eq!(acc1.get_counter_value(&key, acc1.current_tick), 100);
}
// Counter: Absolute does NOT commute with Increment
#[test]
fn counter_absolute_noncommutative_with_increment() {
let key = Key::from_name("test");
// [Increment(10), Absolute(50)]
let mut acc1 = Accumulator::new();
counter_increment(&mut acc1, key.clone(), 0, 10).unwrap();
counter_absolute(&mut acc1, key.clone(), 0, 50).unwrap();
// [Absolute(50), Increment(10)]
let mut acc2 = Accumulator::new();
counter_absolute(&mut acc2, key.clone(), 0, 50).unwrap();
counter_increment(&mut acc2, key.clone(), 0, 10).unwrap();
// Should differ: acc1 is 50, acc2 is 60
assert_eq!(acc1.get_counter_value(&key, acc1.current_tick), 50);
assert_eq!(acc2.get_counter_value(&key, acc2.current_tick), 60);
assert_ne!(
acc1.get_counter_value(&key, acc1.current_tick),
acc2.get_counter_value(&key, acc2.current_tick)
);
}
// Gauge: Increment and Decrement commute
#[test]
fn gauge_increment_decrement_commute() {
let key = Key::from_name("test");
// [Increment(10.0), Decrement(3.0)]
let mut acc1 = Accumulator::new();
gauge_increment(&mut acc1, key.clone(), 0, 10.0).unwrap();
gauge_decrement(&mut acc1, key.clone(), 0, 3.0).unwrap();
// [Decrement(3.0), Increment(10.0)]
let mut acc2 = Accumulator::new();
gauge_decrement(&mut acc2, key.clone(), 0, 3.0).unwrap();
gauge_increment(&mut acc2, key.clone(), 0, 10.0).unwrap();
assert_eq!(
acc1.get_gauge_value(&key, acc1.current_tick),
acc2.get_gauge_value(&key, acc2.current_tick)
);
assert!((acc1.get_gauge_value(&key, acc1.current_tick) - 7.0).abs() < 1e-10);
}
// Gauge: Set is idempotent
#[test]
fn gauge_set_idempotent() {
let key = Key::from_name("test");
// [Set(50.0)]
let mut acc1 = Accumulator::new();
gauge_set(&mut acc1, key.clone(), 0, 50.0).unwrap();
// [Set(50.0), Set(50.0)]
let mut acc2 = Accumulator::new();
gauge_set(&mut acc2, key.clone(), 0, 50.0).unwrap();
gauge_set(&mut acc2, key.clone(), 0, 50.0).unwrap();
assert!(
(acc1.get_gauge_value(&key, acc1.current_tick)
- acc2.get_gauge_value(&key, acc2.current_tick))
.abs()
< 1e-10
);
assert!((acc1.get_gauge_value(&key, acc1.current_tick) - 50.0).abs() < 1e-10);
}
// Gauge: Set does NOT commute with Increment/Decrement
#[test]
fn gauge_set_noncommutative_with_increment() {
let key = Key::from_name("test");
// [Increment(10.0), Set(25.0)]
let mut acc1 = Accumulator::new();
gauge_increment(&mut acc1, key.clone(), 0, 10.0).unwrap();
gauge_set(&mut acc1, key.clone(), 0, 25.0).unwrap();
// [Set(25.0), Increment(10.0)]
let mut acc2 = Accumulator::new();
gauge_set(&mut acc2, key.clone(), 0, 25.0).unwrap();
gauge_increment(&mut acc2, key.clone(), 0, 10.0).unwrap();
let v1 = acc1.get_gauge_value(&key, acc1.current_tick);
let v2 = acc2.get_gauge_value(&key, acc2.current_tick);
// Should differ: acc1 is 25.0, acc2 is 35.0
assert!((v1 - 25.0).abs() < 1e-10);
assert!((v2 - 35.0).abs() < 1e-10);
assert!((v1 - v2).abs() > 1e-10);
}
// Tick advancement: values copy forward, no expiration
#[test]
fn tick_advancement_copies_forward() {
let key = Key::from_name("test");
let mut acc = Accumulator::new();
counter_increment(&mut acc, key.clone(), 0, 42).unwrap();
let value_before_advance = acc.get_counter_value(&key, acc.current_tick);
acc.advance_tick();
let value_after_advance = acc.get_counter_value(&key, acc.current_tick);
assert_eq!(value_before_advance, 42);
assert_eq!(value_after_advance, 42);
}
// Test that the Accumulator is not flushable until INTERVAL ticks have
// passed.
#[test]
fn advancing_to_tick_intervals_makes_data_flushable() {
let key1 = Key::from_name("counter");
let key2 = Key::from_name("gauge");
let mut acc = Accumulator::new();
counter_increment(&mut acc, key1.clone(), 0, 42).unwrap();
gauge_set(&mut acc, key2.clone(), 0, 3.15).unwrap();
assert!(
acc.flush().count() == 0,
"flush should return no data before INTERVALS ticks"
);
while acc.current_tick < (INTERVALS as u64 - 1) {
acc.advance_tick();
}
assert!(
acc.flush().count() == 0,
"flush should return no data at INTERVALS-1 ticks"
);
// Advance one more tick to reach INTERVALS, accumulator is now
// flushable
acc.advance_tick();
assert_eq!(acc.current_tick, INTERVALS as u64);
let results: Vec<_> = acc.flush().collect();
assert_eq!(results.len(), 2, "flush should return both metrics");
// Verify the returned data
for (key, value, tick) in results {
assert_eq!(tick, 0, "flushed data should be from tick 0");
match key.name() {
"counter" => {
assert!(matches!(value, MetricValue::Counter(42)));
}
"gauge" => {
if let MetricValue::Gauge(v) = value {
assert!((v - 3.15).abs() < 1e-10);
} else {
panic!("Expected gauge value");
}
}
_ => panic!("Unexpected key"),
}
}
}
// Test that the shutdown pattern (advance + flush loop) drains all data
// without loss or duplication
#[test]
fn shutdown_pattern_drains_all_data() {
let key = Key::from_name("test");
let mut acc = Accumulator::new();
// Add data at various ticks
counter_increment(&mut acc, key.clone(), 0, 10).unwrap();
for _i in 0..5 {
acc.advance_tick();
}
counter_increment(&mut acc, key.clone(), 0, 20).unwrap();
for _i in 0..10 {
acc.advance_tick();