Skip to main content

waratah_stats/
tick_histogram.rs

1//! Sparse dyadic histogram over the temporal tick axis (advisory-only).
2//!
3//! The temporal index's per-bucket row-count sketch: the same dyadic tree
4//! the `temporal_index` CF addresses with ([`waratah_storage::DyadicNode`])
5//! carries the counts. A **cut** — a set of pairwise non-nesting buckets —
6//! tiles the populated axis exactly once, so a window estimate is a sum over
7//! the cut (exact when finer buckets sit under the window), an ancestor
8//! proportional share (the one approximate case), or a uniform-density
9//! fallback. All outcomes are ADVISORY: they order plan alternatives and
10//! never prune (see `ARCH.md` §10).
11//!
12//! Adaptivity: a bucket observing [`SPLIT_THRESHOLD`] postings splits into
13//! its two halves, so dense recent time refines to fine buckets while sparse
14//! geological eras stay in one coarse bucket — no per-domain tuning. Fresh
15//! keys seed at the root: the first posting creates one full-axis bucket,
16//! and refinement descends only where postings concentrate. The cut is
17//! capped at [`MAX_BUCKETS`] buckets (coarsening of the smallest deepest
18//! sibling pair, applied wherever the cut grows: `observe` splits and
19//! merges alike) and [`MAX_REFINE_LEVEL`] (a bucket width floor near a
20//! quarter picosecond).
21//!
22//! Merging two cuts: union with addition, then resolve nesting by splitting
23//! any bucket that contains a finer one (counts halve per level — the
24//! uniform-share assumption only ever moves counts within the tree, so the
25//! total stays exact), then coarsen back under the cap. Deterministic: the
26//! same input set produces the same cut on every compute.
27
28use std::collections::BTreeMap;
29
30use waratah_storage::{DyadicNode, key_u128_to_tick, tick_to_key_u128};
31
32/// Postings observed in one bucket before it splits into its two halves.
33pub const SPLIT_THRESHOLD: u64 = 64;
34
35/// Maximum buckets in one cut (memory + wire budget).
36pub const MAX_BUCKETS: usize = 4096;
37
38/// Bucket width floor: finest allowed bucket level (width
39/// `2^(128-110) ≈ 2^18` ticks ≈ 0.26 picoseconds).
40pub const MAX_REFINE_LEVEL: u8 = 110;
41
42/// One cut bucket: a [`DyadicNode`] plus nothing — the map key IS the node.
43/// Ordering `(level, index)` is coarse-first, the deterministic merge and
44/// serialization order.
45type Cut = BTreeMap<DyadicNode, u64>;
46
47/// Sparse dyadic histogram over the tick axis.
48#[derive(Debug, Clone, Default, PartialEq, Eq)]
49pub struct TickHistogram {
50    /// The cut: pairwise non-nesting buckets tiling the observed axis.
51    cut: Cut,
52    /// Minimum observed posting key (tick order == key order).
53    min_key: Option<u128>,
54    /// Maximum observed posting key.
55    max_key: Option<u128>,
56    /// Total postings observed (Put-only, like `total_puts`; advisory).
57    total_postings: u64,
58}
59
60impl TickHistogram {
61    /// Observe one posting's node key (the flipped key-space `u128` the
62    /// temporal-index CF prefixes with; instants contribute their exact tick
63    /// key, so splits refine to true tick resolution under dense clusters).
64    pub fn observe(&mut self, node_key: u128) {
65        let bucket = self.locate(node_key);
66        let count = self.cut.entry(bucket).or_insert(0);
67        *count += 1;
68        let split = *count >= SPLIT_THRESHOLD && bucket.level < MAX_REFINE_LEVEL;
69        if split {
70            self.split_bucket(bucket);
71            // A split is the only way the cut can grow: once the root
72            // exists the cut tiles the whole key space, so every later key
73            // lands in a present bucket (see `locate`). Enforcing the cap
74            // exactly where growth happens keeps `observe` bounded — the
75            // pre-fix seeding at `MAX_REFINE_LEVEL` bypassed this and a
76            // rebuild of >`MAX_BUCKETS` distinct postings serialized a cut
77            // `decode_body` rejected as corrupt (audit B59).
78            self.coarsen_to_cap();
79        }
80        self.total_postings = self.total_postings.saturating_add(1);
81        self.min_key = Some(self.min_key.map_or(node_key, |m| m.min(node_key)));
82        self.max_key = Some(self.max_key.map_or(node_key, |m| m.max(node_key)));
83    }
84
85    /// The cut bucket holding `key`: the coarsest present node whose range
86    /// contains it (the cut is laminar, so at most one exists).
87    fn locate(&self, key: u128) -> DyadicNode {
88        for level in 0..=MAX_REFINE_LEVEL {
89            let index = match level {
90                0 => 0,
91                128 => key,
92                level => key >> (128 - u32::from(level)),
93            };
94            if let Some(&_) = self.cut.get(&DyadicNode { level, index }) {
95                return DyadicNode { level, index };
96            }
97        }
98        // Empty cut: seed the ROOT, not a finest-level leaf. Seeding at
99        // `MAX_REFINE_LEVEL` made the split guard (`level < MAX_REFINE_LEVEL`)
100        // always false for fresh buckets, so the documented adaptive
101        // refinement never ran (audit B59). Split and coarsen preserve
102        // coverage (a split replaces a node with its two same-range
103        // children), so this root seed is the only seeding the cut ever
104        // needs: afterwards every key finds a present containing bucket in
105        // the loop above.
106        DyadicNode { level: 0, index: 0 }
107    }
108
109    /// Replace one bucket with its two children (deterministic remainder:
110    /// first child takes the floor).
111    fn split_bucket(&mut self, bucket: DyadicNode) {
112        let Some(count) = self.cut.remove(&bucket) else {
113            return;
114        };
115        if bucket.level >= 128 {
116            // Cannot split a single-key leaf (defensive; observe guards).
117            self.cut.insert(bucket, count);
118            return;
119        }
120        let child_level = bucket.level + 1;
121        let left = DyadicNode {
122            level: child_level,
123            index: bucket.index << 1,
124        };
125        let right = DyadicNode {
126            level: child_level,
127            index: bucket.index << 1 | 1,
128        };
129        *self.cut.entry(left).or_insert(0) += count / 2;
130        *self.cut.entry(right).or_insert(0) += count - count / 2;
131    }
132
133    /// Algebraic merge: union with addition, nesting resolution (a bucket
134    /// containing finer ones splits until the cut is laminar again; counts
135    /// halve per level), then coarsening under [`MAX_BUCKETS`].
136    pub fn merge(&mut self, other: &Self) {
137        for (bucket, count) in &other.cut {
138            *self.cut.entry(*bucket).or_insert(0) += *count;
139        }
140        self.total_postings = self.total_postings.saturating_add(other.total_postings);
141        self.min_key = self.min_key.min(other.min_key);
142        self.max_key = self.max_key.max(other.max_key);
143        self.resolve_nesting();
144        self.coarsen_to_cap();
145    }
146
147    /// Split every bucket that strictly contains a finer present bucket,
148    /// until the cut is laminar again. A worklist, not a single pass: a
149    /// split's freshly created children are NEW cut members and may
150    /// themselves strictly contain finer buckets — a merge can nest finer
151    /// buckets into both halves of one coarse bucket — so every child owes
152    /// the same check its parent got. (The original single pass froze the
153    /// key vector before iterating; fresh children were never revisited and
154    /// the cut stayed non-laminar.) Children are strictly finer than the
155    /// bucket that produced them and levels end at 128, where
156    /// `split_bucket` refuses to split, so the loop terminates.
157    fn resolve_nesting(&mut self) {
158        let mut worklist: Vec<DyadicNode> = self.cut.keys().copied().collect();
159        while let Some(bucket) = worklist.pop() {
160            if self.cut.contains_key(&bucket) && self.has_finer_under(&bucket) {
161                self.split_bucket(bucket);
162                worklist.push(DyadicNode {
163                    level: bucket.level + 1,
164                    index: bucket.index << 1,
165                });
166                worklist.push(DyadicNode {
167                    level: bucket.level + 1,
168                    index: bucket.index << 1 | 1,
169                });
170            }
171        }
172    }
173
174    /// Whether any present bucket is strictly finer and inside `bucket`.
175    fn has_finer_under(&self, bucket: &DyadicNode) -> bool {
176        self.cut.iter().any(|(other, _)| {
177            other.level > bucket.level
178                && (other.min_key() >= bucket.min_key() && other.max_key() <= bucket.max_key())
179        })
180    }
181
182    /// Coarsen the smallest deepest sibling pair until the cut fits
183    /// [`MAX_BUCKETS`]. Deterministic: (max level, smallest sum, smaller
184    /// index) chooses one pair per step.
185    fn coarsen_to_cap(&mut self) {
186        while self.cut.len() > MAX_BUCKETS {
187            let Some(victim) = self.smallest_deepest_sibling_pair() else {
188                break;
189            };
190            let (left, right) = victim;
191            let sum = self.cut.get(&left).copied().unwrap_or(0)
192                + self.cut.get(&right).copied().unwrap_or(0);
193            self.cut.remove(&left);
194            self.cut.remove(&right);
195            if let Some(parent) = left.parent() {
196                *self.cut.entry(parent).or_insert(0) += sum;
197            }
198        }
199    }
200
201    /// The deepest level holding a complete sibling pair; among those pairs,
202    /// the one with the smallest total count (ties: smaller index).
203    fn smallest_deepest_sibling_pair(&self) -> Option<(DyadicNode, DyadicNode)> {
204        let mut best: Option<(u8, u64, DyadicNode)> = None;
205        for &level in self
206            .cut
207            .keys()
208            .map(|b| b.level)
209            .collect::<std::collections::BTreeSet<u8>>()
210            .iter()
211            .rev()
212        {
213            for bucket in self
214                .cut
215                .keys()
216                .filter(|b| b.level == level)
217                .copied()
218                .collect::<Vec<_>>()
219            {
220                if bucket.index & 1 == 1 {
221                    continue; // process pairs at the even sibling
222                }
223                let right = DyadicNode {
224                    level,
225                    index: bucket.index | 1,
226                };
227                if !self.cut.contains_key(&right) {
228                    continue;
229                }
230                let sum = self.cut[&bucket].saturating_add(self.cut[&right]);
231                let better = match best {
232                    None => true,
233                    Some((_, best_sum, best_left)) => {
234                        sum < best_sum || (sum == best_sum && bucket.index < best_left.index)
235                    }
236                };
237                if better {
238                    best = Some((level, sum, bucket));
239                }
240            }
241            if best.is_some() {
242                break; // deepest level with any pair wins
243            }
244        }
245        best.map(|(level, _, left)| {
246            (
247                left,
248                DyadicNode {
249                    level,
250                    index: left.index | 1,
251                },
252            )
253        })
254    }
255
256    /// Total postings observed (advisory; Put-only like `total_puts`).
257    pub fn total_postings(&self) -> u64 {
258        self.total_postings
259    }
260
261    /// Minimum observed tick.
262    pub fn min_tick(&self) -> Option<i128> {
263        self.min_key.map(key_u128_to_tick)
264    }
265
266    /// Maximum observed tick.
267    pub fn max_tick(&self) -> Option<i128> {
268        self.max_key.map(key_u128_to_tick)
269    }
270
271    /// Number of buckets in the cut (tests / diagnostics).
272    pub fn bucket_count(&self) -> usize {
273        self.cut.len()
274    }
275
276    /// The cut's buckets, coarse→fine (test visibility only).
277    #[cfg(test)]
278    pub fn cut_buckets(&self) -> Vec<DyadicNode> {
279        self.cut.keys().copied().collect()
280    }
281
282    /// Row-count estimate for the inclusive tick window `[begin, end]`.
283    ///
284    /// The window's exact canonical decomposition (the same walk the scan
285    /// uses) resolves per node: exact bucket → its count; finer buckets
286    /// under it → their sum; only a coarser ancestor → the ancestor's count
287    /// times the width share. No overlap evidence falls back to the uniform
288    /// density `total / observed_span × window_width`. Never zero: estimates
289    /// order plan alternatives, they never prune (§10), and the profile is
290    /// compaction-stale by construction, so a stats zero is not a proof of
291    /// zero.
292    pub fn estimate_window(&self, begin: i128, end: i128) -> u64 {
293        if end < begin {
294            return 0;
295        }
296        let begin_key = tick_to_key_u128(begin);
297        let end_key = tick_to_key_u128(end);
298        if self.cut.is_empty() {
299            return 1;
300        }
301        // Exact decomposition, uncapped (≤ 2 nodes per level).
302        let nodes = waratah_storage::cover_axis_range(
303            begin_key,
304            end_key,
305            &waratah_storage::DyadicCovererConfig {
306                max_nodes: usize::MAX,
307                ..waratah_storage::DyadicCovererConfig::default()
308            },
309        );
310        let window_width = (end.saturating_sub(begin)).saturating_add(1) as u128;
311        let mut estimate: u128 = 0;
312        for node in &nodes {
313            estimate = estimate.saturating_add(self.node_estimate(node, window_width));
314        }
315        (estimate as u64).max(1)
316    }
317
318    /// Estimate one decomposition node against the cut.
319    fn node_estimate(&self, node: &DyadicNode, window_width: u128) -> u128 {
320        if let Some(&count) = self.cut.get(node) {
321            return count as u128;
322        }
323        // Finer buckets under the node: exact sum (the cut tiles).
324        let finer: Vec<(DyadicNode, u64)> = self
325            .cut
326            .iter()
327            .filter(|(other, _)| {
328                other.level > node.level
329                    && other.min_key() >= node.min_key()
330                    && other.max_key() <= node.max_key()
331            })
332            .map(|(k, v)| (*k, *v))
333            .collect();
334        if !finer.is_empty() {
335            return finer.iter().map(|(_, v)| u128::from(*v)).sum();
336        }
337        // Nearest coarser present ancestor: proportional width share.
338        // Widths saturate: the root bucket spans the whole axis and
339        // `u128::MAX - 0 + 1` has no representable exact value — the
340        // pre-fix seeding could never produce a root bucket, so this
341        // overflow only became reachable with root seeding.
342        let mut parent = *node;
343        while let Some(up) = parent.parent() {
344            if let Some(&count) = self.cut.get(&up) {
345                let node_width = node
346                    .max_key()
347                    .saturating_sub(node.min_key())
348                    .saturating_add(1);
349                let up_width = up.max_key().saturating_sub(up.min_key()).saturating_add(1);
350                return (u128::from(count))
351                    .saturating_mul(node_width)
352                    .saturating_div(up_width.max(1))
353                    .max(1);
354            }
355            parent = up;
356        }
357        // Uniform-density fallback over the observed axis span.
358        match (self.min_key, self.max_key) {
359            (Some(min), Some(max)) => {
360                let span = max.saturating_sub(min).saturating_add(1).max(1);
361                let node_width = node
362                    .max_key()
363                    .saturating_sub(node.min_key())
364                    .saturating_add(1);
365                u128::from(self.total_postings.max(1))
366                    .saturating_mul(node_width.min(window_width).max(1))
367                    .saturating_div(span)
368                    .max(1)
369            }
370            _ => 1,
371        }
372    }
373
374    /// Serialize: buckets in `(level, index)` order, fixed-width fields.
375    pub fn encode_body(&self, out: &mut Vec<u8>) {
376        out.extend_from_slice(&SELF_VERSION.to_le_bytes());
377        out.extend_from_slice(&(self.cut.len() as u32).to_le_bytes());
378        for (bucket, count) in &self.cut {
379            out.push(bucket.level);
380            out.extend_from_slice(&bucket.index.to_be_bytes());
381            out.extend_from_slice(&count.to_le_bytes());
382        }
383        out.extend_from_slice(&self.min_key.map_or([0xFF; 16], |k| k.to_be_bytes()));
384        out.extend_from_slice(&self.max_key.map_or([0xFF; 16], |k| k.to_be_bytes()));
385        out.extend_from_slice(&self.total_postings.to_le_bytes());
386    }
387
388    /// Parse a body produced by [`Self::encode_body`]; trailing input is the
389    /// caller's (the profile continues after this section).
390    pub fn decode_body(buf: &mut &[u8]) -> Result<Self, crate::StatsError> {
391        let mut take = |n: usize| -> Result<&[u8], crate::StatsError> {
392            if buf.len() < n {
393                return Err(crate::StatsError::Corrupt(
394                    "tick histogram truncated".into(),
395                ));
396            }
397            let (head, tail) = buf.split_at(n);
398            *buf = tail;
399            Ok(head)
400        };
401        let version = u16::from_le_bytes(take(2)?.try_into().expect("2 bytes"));
402        if version != SELF_VERSION {
403            return Err(crate::StatsError::Corrupt(format!(
404                "unsupported tick-histogram version {version}"
405            )));
406        }
407        let len = u32::from_le_bytes(take(4)?.try_into().expect("4 bytes")) as usize;
408        // No `MAX_BUCKETS` rejection: a cut written before observe-side
409        // capping (or merged past the cap by an older build) decodes fine
410        // and is coarsened below — "corrupt" is the wrong diagnosis for
411        // "needs coarsening". Memory stays bounded by the body itself:
412        // every entry consumes 25 input bytes, so a bogus `len` dies in
413        // `take` as truncation before the map can outgrow the input.
414        let mut cut = Cut::new();
415        for _ in 0..len {
416            let level = take(1)?[0];
417            if level > 128 {
418                // Structural, not a cap matter: `DyadicNode` addressing has
419                // no level beyond the 128-level axis, and deeper bytes would
420                // shift-overflow the width math downstream.
421                return Err(crate::StatsError::Corrupt(format!(
422                    "tick histogram bucket level {level} exceeds the 128-level axis"
423                )));
424            }
425            let index = u128::from_be_bytes(take(16)?.try_into().expect("16 bytes"));
426            let count = u64::from_le_bytes(take(8)?.try_into().expect("8 bytes"));
427            cut.insert(DyadicNode { level, index }, count);
428        }
429        let min_raw = take(16)?.try_into().expect("16 bytes");
430        let max_raw = take(16)?.try_into().expect("16 bytes");
431        let total = u64::from_le_bytes(take(8)?.try_into().expect("8 bytes"));
432        let mut decoded = Self {
433            cut,
434            min_key: decode_optional_key(&min_raw),
435            max_key: decode_optional_key(&max_raw),
436            total_postings: total,
437        };
438        // Coarsen a legacy oversized cut under the cap (same deterministic
439        // smallest-deepest-sibling-pair choice as `merge`); a cut already at
440        // or under the cap passes through unchanged, so encode→decode is
441        // still identity for everything this build writes.
442        decoded.coarsen_to_cap();
443        Ok(decoded)
444    }
445}
446
447/// Section version for forward-compatible profile evolution.
448const SELF_VERSION: u16 = 1;
449
450/// `0xFF..FF` decodes as "absent" (a real key of all-ones is the axis
451/// maximum — indistinguishable, and irrelevant at advisory precision).
452fn decode_optional_key(raw: &[u8; 16]) -> Option<u128> {
453    if raw == &[0xFF; 16] {
454        None
455    } else {
456        Some(u128::from_be_bytes(*raw))
457    }
458}
459
460#[cfg(test)]
461mod tests {
462    use super::*;
463    use pretty_assertions::assert_eq;
464
465    fn key(tick: i128) -> u128 {
466        tick_to_key_u128(tick)
467    }
468
469    #[test]
470    fn observe_splits_dense_regions_and_keeps_sparse_ones_coarse() {
471        let mut histogram = TickHistogram::default();
472        // 128 postings one tick apart at +10^30: refines under the cluster.
473        for step in 0..128 {
474            histogram.observe(key(10_000_000_000_000_000_000_000_000_000_i128 + step));
475        }
476        // A handful far in the past: never reaches the split threshold.
477        for step in 0..10 {
478            histogram.observe(key(-4_000_000_000_000_000_000_000_000_000_000_i128 + step));
479        }
480        assert!(histogram.bucket_count() > 1, "dense cluster split");
481        assert_eq!(histogram.total_postings(), 138);
482        assert_eq!(
483            histogram.min_tick(),
484            Some(key_u128_to_tick(key(
485                -4_000_000_000_000_000_000_000_000_000_000_i128
486            )))
487        );
488        // Cut invariant: no bucket nests another.
489        let buckets = histogram.cut_buckets();
490        for (i, a) in buckets.iter().enumerate() {
491            for b in &buckets[i + 1..] {
492                let a_nests_b = a.min_key() <= b.min_key() && b.max_key() <= a.max_key();
493                let b_nests_a = b.min_key() <= a.min_key() && a.max_key() <= b.max_key();
494                assert!(!a_nests_b && !b_nests_a, "cut nests: {a:?} vs {b:?}");
495            }
496        }
497    }
498
499    #[test]
500    fn estimates_refine_with_density_and_never_hit_zero() {
501        let mut histogram = TickHistogram::default();
502        // Four postings, widely separated: the cut stays the coarse root
503        // bucket (below the split threshold), so a tiny window resolves by
504        // ancestor share — at least one row per decomposition node.
505        let ticks = [
506            -1_000_000_000_000_000_000_000_000_000_i128,
507            -500_000_000_000_000_000_000_000_000_i128,
508            500_000_000_000_000_000_000_000_000_i128,
509            1_000_000_000_000_000_000_000_000_000_i128,
510        ];
511        for &t in &ticks {
512            histogram.observe(key(t));
513        }
514        let tiny = histogram.estimate_window(ticks[2] - 1, ticks[2] + 1);
515        assert!(tiny >= 1);
516        // Empty histogram clamps to 1, never 0.
517        assert_eq!(TickHistogram::default().estimate_window(0, 100), 1);
518        // Out-of-range windows still estimate ≥ 1 (advisory, never prune).
519        assert!(
520            histogram.estimate_window(
521                9_000_000_000_000_000_000_000_000_000_i128 * 4,
522                9_000_000_000_000_000_000_000_000_000_i128 * 5
523            ) >= 1
524        );
525        // A dense run (5000 ticks one second apart — realistic sensor
526        // spacing) refines the cut deep enough that the whole-run window's
527        // interior nodes sum the fine buckets under them: right magnitude,
528        // and nested windows are monotone.
529        let mut dense = TickHistogram::default();
530        let run_start = 3_000_000_000_000_000_000_000_000_000_i128;
531        for step in 0..5_000 {
532            dense.observe(key(run_start + step * waratah_storage::ATTO_PER_SECOND));
533        }
534        let whole = dense.estimate_window(
535            run_start,
536            run_start + 4_999 * waratah_storage::ATTO_PER_SECOND,
537        );
538        assert!(
539            (1_000..=50_000).contains(&whole),
540            "whole-run estimate {whole} out of magnitude"
541        );
542        let half = dense.estimate_window(
543            run_start,
544            run_start + 2_499 * waratah_storage::ATTO_PER_SECOND,
545        );
546        assert!(
547            half < whole,
548            "nested window must not out-estimate its container: {half} vs {whole}"
549        );
550        assert!(half >= 1);
551        // A 3-second window inside the dense run resolves by fine-bucket
552        // proportion — small but never zero.
553        let sliver = dense.estimate_window(
554            run_start + 10 * waratah_storage::ATTO_PER_SECOND,
555            run_start + 12 * waratah_storage::ATTO_PER_SECOND,
556        );
557        assert!(sliver >= 1, "dense-run sliver must not prune: {sliver}");
558    }
559
560    #[test]
561    fn merge_resolves_nesting_into_both_halves_of_one_bucket() {
562        // The one-pass resolver's failure shape: the union holds one coarse
563        // bucket with a finer bucket under EACH of its halves. Splitting
564        // the coarse bucket creates two fresh children — one over each
565        // finer bucket — and a frozen pre-split key snapshot never
566        // revisits them, so the cut stayed non-laminar (C1 ⊃ F1 and
567        // C2 ⊃ F2). Hand-built cuts: the tests module can address the
568        // private field, which makes the failure shape exact instead of
569        // hoping two observed shards nest this way.
570        let mut a = TickHistogram::default();
571        a.cut.insert(
572            DyadicNode {
573                level: 120,
574                index: 4,
575            },
576            10,
577        ); // [1024, 1280)
578        let mut b = TickHistogram::default();
579        b.cut.insert(
580            DyadicNode {
581                level: 122,
582                index: 16,
583            },
584            5,
585        ); // [1024, 1088) ⊂ left half
586        b.cut.insert(
587            DyadicNode {
588                level: 122,
589                index: 18,
590            },
591            7,
592        ); // [1152, 1216) ⊂ right half
593
594        a.merge(&b);
595
596        // Laminar: no present bucket strictly contains another.
597        let buckets = a.cut_buckets();
598        assert!(
599            buckets.len() >= 4,
600            "both halves must have split: {buckets:?}"
601        );
602        for (i, x) in buckets.iter().enumerate() {
603            for y in &buckets[i + 1..] {
604                let x_nests_y = x.min_key() <= y.min_key() && y.max_key() <= x.max_key();
605                let y_nests_x = y.min_key() <= x.min_key() && x.max_key() <= y.max_key();
606                assert!(!x_nests_y && !y_nests_x, "cut nests: {x:?} over {y:?}");
607            }
608        }
609        // Resolution moves counts within the tree — nothing is lost.
610        let total: u64 = a.cut.values().sum();
611        assert_eq!(total, 22);
612    }
613
614    #[test]
615    fn merge_preserves_totals_and_restores_laminarity() {
616        // Shard A: 64 postings all inside the left half of +2^100.
617        // Shard B: 64 postings inside the left half's left quarter.
618        let base = 1_i128 << 100;
619        let mut shard_a = TickHistogram::default();
620        for step in 0..64 {
621            shard_a.observe(key(base + step));
622        }
623        let mut shard_b = TickHistogram::default();
624        for step in 0..64 {
625            shard_b.observe(key(base + 1_000_000 + step));
626        }
627        let total = shard_a.total_postings() + shard_b.total_postings();
628        shard_a.merge(&shard_b);
629        assert_eq!(shard_a.total_postings(), total);
630        assert_eq!(total, 128);
631        // The merged cut must not nest (splitting resolved the union). The
632        // window estimate is advisory over an adaptively coarse cut: with
633        // only 128 postings the buckets sit near the root, so the estimate
634        // is a proportional width share, not the fine-cut exact sum the
635        // pre-fix seeding implied. It must neither prune (≥ 1) nor inflate
636        // past clamp noise (≤ 2× total across the window's cover nodes).
637        let window = shard_a.estimate_window(base, base + 2_000_000);
638        assert!(
639            (1..=(2 * total)).contains(&window),
640            "advisory window in sketch bounds: {window}"
641        );
642        // Merge commutes for INDEPENDENT inputs (totals are additive, not
643        // idempotent — the same contract as `total_puts`).
644        let mut mirrored = shard_b.clone();
645        let fresh_a = {
646            let mut fresh = TickHistogram::default();
647            for step in 0..64 {
648                fresh.observe(key(base + step));
649            }
650            fresh
651        };
652        mirrored.merge(&fresh_a);
653        assert_eq!(mirrored.total_postings(), shard_a.total_postings());
654    }
655
656    #[test]
657    fn coarsen_caps_the_bucket_count() {
658        let mut histogram = TickHistogram::default();
659        // One posting per distinct coarse region: enough distinct regions
660        // to exceed MAX_BUCKETS via splitting chains is expensive; instead
661        // exercise the cap through merges of many shallow histograms.
662        for region in 0..64_i128 {
663            let mut shard = TickHistogram::default();
664            for step in 0..64 {
665                shard.observe(key(region * (1_i128 << 120) + step));
666            }
667            histogram.merge(&shard);
668        }
669        assert!(histogram.bucket_count() <= MAX_BUCKETS);
670        assert_eq!(histogram.total_postings(), 64 * 64);
671    }
672
673    #[test]
674    fn consecutive_keys_refine_by_splitting_not_scatter() {
675        // The audit-B59 probe shape: every posting inside ONE level-110
676        // cell. Seeding used to drop fresh keys at `MAX_REFINE_LEVEL`, where
677        // the split guard is always false — 300 such postings yielded
678        // exactly one bucket and the documented refinement never ran. Root
679        // seeding splits the containing chain instead: each 64 arrivals in
680        // the live bucket push it one level deeper (half the count is the
681        // phantom sibling), so the cut grows with density.
682        let base = 1_u128 << 100;
683        let mut histogram = TickHistogram::default();
684        for step in 0..600_u64 {
685            histogram.observe(base + u128::from(step));
686        }
687        let deepest = histogram
688            .cut_buckets()
689            .iter()
690            .map(|b| b.level)
691            .max()
692            .unwrap();
693        assert!(deepest >= 3, "chain must refine, deepest level {deepest}");
694        assert!(histogram.bucket_count() > 5);
695        assert_eq!(histogram.total_postings(), 600);
696        // The cut stays laminar through observe-side splits.
697        let buckets = histogram.cut_buckets();
698        for (i, a) in buckets.iter().enumerate() {
699            for b in &buckets[i + 1..] {
700                let a_nests_b = a.min_key() <= b.min_key() && b.max_key() <= a.max_key();
701                let b_nests_a = b.min_key() <= a.min_key() && a.max_key() <= b.max_key();
702                assert!(!a_nests_b && !b_nests_a, "cut nests: {a:?} vs {b:?}");
703            }
704        }
705    }
706
707    #[test]
708    fn splits_stop_at_max_refine_level() {
709        // Hammer one single key: the containing chain refines one level per
710        // threshold arrivals until the width floor, where the split guard
711        // blocks further refinement and the level-`MAX_REFINE_LEVEL`
712        // accumulator absorbs the rest. The cut is exactly the chain's
713        // frozen siblings plus that accumulator.
714        let mut histogram = TickHistogram::default();
715        for _ in 0..20_000_u64 {
716            histogram.observe(1_u128 << 100);
717        }
718        let deepest = histogram
719            .cut_buckets()
720            .iter()
721            .map(|b| b.level)
722            .max()
723            .unwrap();
724        assert_eq!(deepest, MAX_REFINE_LEVEL);
725        assert_eq!(
726            histogram.bucket_count(),
727            usize::from(MAX_REFINE_LEVEL) + 1,
728            "one frozen sibling per chain level + the accumulator"
729        );
730        assert_eq!(histogram.total_postings(), 20_000);
731    }
732
733    #[test]
734    fn observe_stays_bounded_and_round_trips_above_legacy_cap() {
735        // The B59 failure shape: more distinct postings than `MAX_BUCKETS`.
736        // A rebuild observing 6000 spread instants used to serialize a
737        // 6000-bucket cut that `decode_body` rejected as corrupt.
738        // Observe-side coarsening keeps the cut capped and the body
739        // decodable, and an already-capped cut round-trips unchanged.
740        let mut histogram = TickHistogram::default();
741        let day = 86_400_000_000_000_000_000_i128; // attoseconds per day
742        for step in 0..6_000_u64 {
743            histogram.observe(key(
744                1_000_000_000_000_000_000_000_000_000_i128 + i128::from(step) * day
745            ));
746        }
747        assert!(histogram.bucket_count() <= MAX_BUCKETS);
748        assert_eq!(histogram.total_postings(), 6_000);
749        let mut bytes = Vec::new();
750        histogram.encode_body(&mut bytes);
751        let mut rest = bytes.as_slice();
752        let decoded = TickHistogram::decode_body(&mut rest).unwrap();
753        assert_eq!(decoded, histogram, "capped cut round-trips unchanged");
754        assert!(rest.is_empty());
755    }
756
757    #[test]
758    fn decode_coarsens_a_legacy_oversized_body() {
759        // A body written before observe-side capping: `MAX_BUCKETS` + 104
760        // complete level-110 sibling pairs (splits always create both
761        // children, so every real oversized cut pairs up). Used to be
762        // rejected as corrupt; now it decodes and coarsens under the cap
763        // with the same deterministic pair choice as `merge`.
764        let pairs = MAX_BUCKETS + 104;
765        let mut bytes = Vec::new();
766        bytes.extend_from_slice(&1_u16.to_le_bytes()); // SELF_VERSION
767        bytes.extend_from_slice(&(2 * pairs as u32).to_le_bytes());
768        for i in 0..pairs {
769            for index in [(2 * i) as u128, (2 * i + 1) as u128] {
770                bytes.push(110_u8);
771                bytes.extend_from_slice(&index.to_be_bytes());
772                bytes.extend_from_slice(&1_u64.to_le_bytes());
773            }
774        }
775        bytes.extend_from_slice(&[0xFF; 16]); // min_key absent
776        bytes.extend_from_slice(&[0xFF; 16]); // max_key absent
777        bytes.extend_from_slice(&(2 * pairs as u64).to_le_bytes());
778        let mut rest = bytes.as_slice();
779        let decoded = TickHistogram::decode_body(&mut rest).unwrap();
780        assert!(rest.is_empty());
781        assert!(decoded.bucket_count() <= MAX_BUCKETS);
782        assert_eq!(decoded.total_postings(), 2 * pairs as u64);
783    }
784
785    #[test]
786    fn decode_rejects_structurally_impossible_levels() {
787        // Level 200 has no dyadic addressing on a 128-level axis; deeper
788        // bytes would shift-overflow the width math downstream. Structural
789        // garbage stays `Corrupt` — only oversIZE coarsens.
790        let mut bytes = Vec::new();
791        bytes.extend_from_slice(&1_u16.to_le_bytes()); // SELF_VERSION
792        bytes.extend_from_slice(&1_u32.to_le_bytes());
793        bytes.push(200_u8);
794        bytes.extend_from_slice(&0_u128.to_be_bytes());
795        bytes.extend_from_slice(&1_u64.to_le_bytes());
796        bytes.extend_from_slice(&[0xFF; 16]); // min_key absent
797        bytes.extend_from_slice(&[0xFF; 16]); // max_key absent
798        bytes.extend_from_slice(&1_u64.to_le_bytes());
799        assert!(TickHistogram::decode_body(&mut bytes.as_slice()).is_err());
800    }
801
802    #[test]
803    fn body_round_trips() {
804        let mut histogram = TickHistogram::default();
805        histogram.observe(key(-5));
806        histogram.observe(key(7));
807        histogram.observe(key(7));
808        let mut bytes = Vec::new();
809        histogram.encode_body(&mut bytes);
810        let mut rest = bytes.as_slice();
811        let decoded = TickHistogram::decode_body(&mut rest).unwrap();
812        assert_eq!(decoded, histogram);
813        assert!(rest.is_empty(), "no trailing bytes");
814        // Truncated body errors.
815        assert!(TickHistogram::decode_body(&mut &bytes[..bytes.len() - 1]).is_err());
816    }
817
818    #[test]
819    fn empty_histogram_has_no_extent() {
820        let histogram = TickHistogram::default();
821        assert_eq!(histogram.min_tick(), None);
822        assert_eq!(histogram.max_tick(), None);
823        assert_eq!(histogram.total_postings(), 0);
824        assert_eq!(histogram.estimate_window(0, 1), 1);
825    }
826}