Skip to main content

kevy_index/
agg.rs

1//! [`AggSegment`] — one shard's slice of one aggregate index (KIND
2//! agg): per-group count / sum / min / max maintained
3//! synchronously with writes. min/max stay EXACT under deletion via a
4//! per-group value multiset (BTreeMap value → multiplicity); a
5//! row → (group, value) reverse map supports O(log) updates — the
6//! same derived-by-construction discipline as [`crate::Segment`].
7
8use std::collections::{BTreeMap, HashMap};
9
10use crate::IndexValue;
11
12/// One group's live statistics.
13#[derive(Debug, Clone, PartialEq)]
14pub struct GroupStats {
15    /// Rows in the group.
16    pub count: u64,
17    /// Sum of the aggregated field (f64 accumulation — the i64
18    /// overflow guard; precision bounds documented).
19    pub sum: f64,
20    /// Exact minimum (None only when count == 0).
21    pub min: Option<IndexValue>,
22    /// Exact maximum.
23    pub max: Option<IndexValue>,
24}
25
26impl GroupStats {
27    /// Derived average.
28    pub fn avg(&self) -> Option<f64> {
29        (self.count > 0).then(|| self.sum / self.count as f64)
30    }
31}
32
33struct Group {
34    count: u64,
35    sum: f64,
36    /// value → multiplicity; min/max = first/last key.
37    values: BTreeMap<IndexValue, u32>,
38}
39
40/// Ranking metric for [`AggSegment::top_groups`].
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
42pub enum AggBy {
43    /// By row count (default).
44    #[default]
45    Count,
46    /// By sum.
47    Sum,
48    /// By minimum (ascending — smallest mins first).
49    Min,
50    /// By maximum (descending — largest maxes first).
51    Max,
52}
53
54impl AggBy {
55    /// Wire tag.
56    pub fn parse(raw: &[u8]) -> Option<AggBy> {
57        if raw.eq_ignore_ascii_case(b"count") {
58            Some(AggBy::Count)
59        } else if raw.eq_ignore_ascii_case(b"sum") {
60            Some(AggBy::Sum)
61        } else if raw.eq_ignore_ascii_case(b"min") {
62            Some(AggBy::Min)
63        } else if raw.eq_ignore_ascii_case(b"max") {
64            Some(AggBy::Max)
65        } else {
66            None
67        }
68    }
69}
70
71/// Sizing counters (memory formula / IDX.LIST).
72#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
73pub struct AggStats {
74    /// Live groups.
75    pub groups: u64,
76    /// Rows participating.
77    pub rows: u64,
78    /// Rows excluded (coerce failure / missing group field).
79    pub excluded: u64,
80    /// Approximate heap bytes (the measured side of the documented
81    /// memory formula).
82    pub approx_bytes: u64,
83}
84
85/// One shard's aggregate segment.
86#[derive(Default)]
87pub struct AggSegment {
88    groups: HashMap<Vec<u8>, Group>,
89    /// row key → (group, value) for O(log) update/remove.
90    rows: HashMap<Vec<u8>, (Vec<u8>, IndexValue)>,
91    excluded: u64,
92    /// Running counters, so `stats()` never walks the maps
93    /// (the walk ran on every tiering tick). Each mirrors one walking
94    /// term of the byte formula; `recompute_stats` is the reference
95    /// the tests hold them to.
96    distinct_total: u64,
97    gkey_bytes: u64,
98    row_key_bytes: u64,
99}
100
101impl AggSegment {
102    /// Empty segment.
103    pub fn new() -> Self {
104        Self::default()
105    }
106
107    /// (Re-)register one row: `Some((group, value))` = row
108    /// participates; `None` = removed or excluded. `excluded_row`
109    /// marks the None case as a coercion/missing-field exclusion
110    /// (counted) rather than a plain delete.
111    // missing_panics_doc: the only panic is the "group of live row" expect —
112    // an internal rows↔groups invariant, never reachable from caller input.
113    #[allow(clippy::missing_panics_doc)]
114    pub fn apply(&mut self, key: &[u8], entry: Option<(Vec<u8>, IndexValue)>, excluded_row: bool) {
115        if let Some((group, val)) = &entry
116            && self.fast_path_same_group(key, group, val)
117        {
118            return;
119        }
120        self.retract_row(key);
121        match entry {
122            Some((group, val)) => {
123                let g = self.groups.entry(group.clone()).or_insert(Group {
124                    count: 0,
125                    sum: 0.0,
126                    values: BTreeMap::new(),
127                });
128                if g.count == 0 {
129                    self.gkey_bytes += group.len() as u64;
130                }
131                g.count += 1;
132                g.sum += val.as_f64();
133                let slot = g.values.entry(val.clone()).or_insert(0);
134                *slot += 1;
135                if *slot == 1 {
136                    self.distinct_total += 1;
137                }
138                self.row_key_bytes += key.len() as u64 + 10;
139                self.rows.insert(key.to_vec(), (group, val));
140            }
141            None if excluded_row => self.excluded += 1,
142            None => {}
143        }
144    }
145
146    /// Fast path: same-group value update (the dominant serving write
147    /// shape — measured 16.8% write tax on a Zipf corpus with the
148    /// retract+register path; hot groups make every full retract pay
149    /// two map round-trips and two clones). `true` = handled.
150    fn fast_path_same_group(&mut self, key: &[u8], group: &[u8], val: &IndexValue) -> bool {
151        let Some((old_group, old_val)) = self.rows.get_mut(key) else { return false };
152        if old_group != group {
153            return false;
154        }
155        if old_val == val {
156            return true; // nothing changed
157        }
158        let g = self.groups.get_mut(group).expect("group of live row");
159        g.sum += val.as_f64() - old_val.as_f64();
160        match g.values.get_mut(old_val) {
161            Some(m) if *m > 1 => *m -= 1,
162            _ => {
163                g.values.remove(old_val);
164                self.distinct_total -= 1;
165            }
166        }
167        let slot = g.values.entry(val.clone()).or_insert(0);
168        *slot += 1;
169        if *slot == 1 {
170            self.distinct_total += 1;
171        }
172        *old_val = val.clone();
173        true
174    }
175
176    /// Retract one row's current contribution (no-op for an unknown
177    /// key); drops the group when its last row leaves.
178    fn retract_row(&mut self, key: &[u8]) {
179        if let Some((old_group, old_val)) = self.rows.remove(key) {
180            self.row_key_bytes -= key.len() as u64 + 10;
181            let empty = {
182                let g = self.groups.get_mut(&old_group).expect("group of live row");
183                g.count -= 1;
184                g.sum -= old_val.as_f64();
185                match g.values.get_mut(&old_val) {
186                    Some(m) if *m > 1 => *m -= 1,
187                    _ => {
188                        g.values.remove(&old_val);
189                        self.distinct_total -= 1;
190                    }
191                }
192                g.count == 0
193            };
194            if empty {
195                self.groups.remove(&old_group);
196                self.gkey_bytes -= old_group.len() as u64;
197            }
198        }
199    }
200
201    /// One group's stats (`count == 0` shape for an unknown group).
202    pub fn group(&self, group: &[u8]) -> GroupStats {
203        match self.groups.get(group) {
204            Some(g) => GroupStats {
205                count: g.count,
206                sum: g.sum,
207                min: g.values.keys().next().cloned(),
208                max: g.values.keys().next_back().cloned(),
209            },
210            None => GroupStats { count: 0, sum: 0.0, min: None, max: None },
211        }
212    }
213
214    /// Top `limit` groups ranked by `by` (count/sum/max descending,
215    /// min ascending), ties broken by group key ascending.
216    ///
217    /// Bounded selection over BORROWED keys — the first cut cloned
218    /// and sorted every group per query (measured as the dominant
219    /// per-shard cost at 10k groups); only the winners materialize.
220    pub fn top_groups(&self, by: AggBy, limit: usize) -> Vec<(Vec<u8>, GroupStats)> {
221        let score_of = |g: &Group| -> f64 {
222            match by {
223                AggBy::Count => g.count as f64,
224                AggBy::Sum => g.sum,
225                AggBy::Max => g.values.keys().next_back().map_or(f64::NEG_INFINITY, IndexValue::as_f64),
226                AggBy::Min => g.values.keys().next().map_or(f64::NEG_INFINITY, |v| -v.as_f64()),
227            }
228        };
229        // float_cmp: exact equality is the tiebreak trigger — an epsilon would
230        // make the top-K selection non-deterministic for equal scores.
231        #[allow(clippy::float_cmp)]
232        let better = |a: (f64, &[u8]), b: (f64, &[u8])| a.0 > b.0 || (a.0 == b.0 && a.1 < b.1);
233        let mut top: Vec<(f64, &Vec<u8>)> = Vec::with_capacity(limit.min(1024) + 1);
234        for (k, g) in &self.groups {
235            let cand = (score_of(g), k);
236            if top.len() < limit {
237                top.push(cand);
238                if top.len() == limit {
239                    top.sort_by(|a, b| b.0.total_cmp(&a.0).then_with(|| a.1.cmp(b.1)));
240                }
241            } else if let Some(last) = top.last()
242                && better((cand.0, cand.1), (last.0, last.1))
243            {
244                let pos = top.partition_point(|e| better((e.0, e.1), (cand.0, cand.1)));
245                top.insert(pos, cand);
246                top.pop();
247            }
248        }
249        if top.len() < limit {
250            top.sort_by(|a, b| b.0.total_cmp(&a.0).then_with(|| a.1.cmp(b.1)));
251        }
252        top.into_iter().map(|(_, k)| (k.clone(), self.group(k))).collect()
253    }
254
255    /// Every group, UNRANKED — the fan-out chunk shape (ranking
256    /// happens once, at the reduce, after cross-shard merge; sorting
257    /// per shard would be wasted work).
258    pub fn all_groups(&self) -> Vec<(Vec<u8>, GroupStats)> {
259        self.groups.keys().map(|k| (k.clone(), self.group(k))).collect()
260    }
261
262    /// Membership probe (verify hook).
263    pub fn contains(&self, key: &[u8]) -> bool {
264        self.rows.contains_key(key)
265    }
266
267    /// This segment's live row count — the one field of [`Self::stats`]
268    /// that is a `len()`. Its own accessor because `stats` also sums every
269    /// group's values, every group key and every row key to estimate bytes,
270    /// and a caller asking "how many rows" should not pay for that.
271    pub fn rows(&self) -> u64 {
272        self.rows.len() as u64
273    }
274
275    /// Live counters — O(1): every term is a running
276    /// counter maintained at the mutation sites. Byte constants
277    /// calibrated against measured RSS growth at 1M rows / 10k Zipf
278    /// groups (the first-cut 40/24 constants overestimated 2× —
279    /// BTreeMap packs ~11 entries per node and the reverse map's vecs
280    /// are small-alloc pooled).
281    pub fn stats(&self) -> AggStats {
282        AggStats {
283            groups: self.groups.len() as u64,
284            rows: self.rows.len() as u64,
285            excluded: self.excluded,
286            approx_bytes: self.gkey_bytes
287                + self.groups.len() as u64 * 64
288                + self.distinct_total * 18
289                + self.row_key_bytes,
290        }
291    }
292
293    /// The walking reference — recomputes every byte term from the
294    /// live maps. Test-only: production reads the running counters.
295    #[cfg(test)]
296    pub(crate) fn recompute_stats(&self) -> AggStats {
297        let distinct: u64 = self.groups.values().map(|g| g.values.len() as u64).sum();
298        let gkey: u64 = self.groups.keys().map(|k| k.len() as u64).sum();
299        let rowbytes: u64 = self.rows.keys().map(|k| (k.len() + 10) as u64).sum();
300        AggStats {
301            groups: self.groups.len() as u64,
302            rows: self.rows.len() as u64,
303            excluded: self.excluded,
304            approx_bytes: gkey + self.groups.len() as u64 * 64 + distinct * 18 + rowbytes,
305        }
306    }
307}
308
309/// Shared ranking order (per-shard AND at the reduce after merging
310/// shard partials — one definition, no drift).
311pub fn sort_groups(all: &mut [(Vec<u8>, GroupStats)], by: AggBy) {
312    match by {
313        AggBy::Count => all.sort_by(|a, b| b.1.count.cmp(&a.1.count).then_with(|| a.0.cmp(&b.0))),
314        AggBy::Sum => all.sort_by(|a, b| b.1.sum.total_cmp(&a.1.sum).then_with(|| a.0.cmp(&b.0))),
315        AggBy::Min => all.sort_by(|a, b| {
316            match (&a.1.min, &b.1.min) {
317                (Some(x), Some(y)) => x.cmp(y),
318                (Some(_), None) => std::cmp::Ordering::Less,
319                (None, Some(_)) => std::cmp::Ordering::Greater,
320                (None, None) => std::cmp::Ordering::Equal,
321            }
322            .then_with(|| a.0.cmp(&b.0))
323        }),
324        AggBy::Max => all.sort_by(|a, b| {
325            match (&b.1.max, &a.1.max) {
326                (Some(x), Some(y)) => x.cmp(y),
327                (Some(_), None) => std::cmp::Ordering::Less,
328                (None, Some(_)) => std::cmp::Ordering::Greater,
329                (None, None) => std::cmp::Ordering::Equal,
330            }
331            .then_with(|| a.0.cmp(&b.0))
332        }),
333    }
334}
335
336/// Merge shard partials for one group (reduce side): counts/sums add,
337/// min/max take extremes.
338pub fn merge_group(into: &mut GroupStats, part: &GroupStats) {
339    into.count += part.count;
340    into.sum += part.sum;
341    into.min = match (into.min.take(), part.min.clone()) {
342        (Some(a), Some(b)) => Some(if b < a { b } else { a }),
343        (a, b) => a.or(b),
344    };
345    into.max = match (into.max.take(), part.max.clone()) {
346        (Some(a), Some(b)) => Some(if b > a { b } else { a }),
347        (a, b) => a.or(b),
348    };
349}
350
351#[cfg(test)]
352mod tests {
353    use super::*;
354
355    fn seg() -> AggSegment {
356        let mut s = AggSegment::new();
357        // orders: group = status, value = amount
358        for (k, g, v) in [
359            ("o1", "paid", 100),
360            ("o2", "paid", 250),
361            ("o3", "open", 40),
362            ("o4", "paid", 100),
363            ("o5", "open", 999),
364        ] {
365            s.apply(k.as_bytes(), Some((g.as_bytes().to_vec(), IndexValue::I64(v))), false);
366        }
367        s
368    }
369
370    #[test]
371    fn group_stats_exact() {
372        let s = seg();
373        let g = s.group(b"paid");
374        assert_eq!((g.count, g.sum), (3, 450.0));
375        assert_eq!(g.min, Some(IndexValue::I64(100)));
376        assert_eq!(g.max, Some(IndexValue::I64(250)));
377        assert_eq!(g.avg(), Some(150.0));
378        let none = s.group(b"nope");
379        assert_eq!(none.count, 0);
380        assert!(none.min.is_none() && none.avg().is_none());
381    }
382
383    #[test]
384    fn min_max_exact_under_delete_and_update() {
385        let mut s = seg();
386        // delete the paid max (o2=250): max must fall back to 100
387        s.apply(b"o2", None, false);
388        let g = s.group(b"paid");
389        assert_eq!((g.count, g.max.clone()), (2, Some(IndexValue::I64(100))));
390        // duplicate values: removing ONE 100 keeps the other
391        s.apply(b"o1", None, false);
392        let g = s.group(b"paid");
393        assert_eq!((g.count, g.min.clone()), (1, Some(IndexValue::I64(100))));
394        // update moves a row across groups
395        s.apply(b"o3", Some((b"paid".to_vec(), IndexValue::I64(40))), false);
396        assert_eq!(s.group(b"paid").count, 2);
397        assert_eq!(s.group(b"open").count, 1);
398        assert_eq!(s.group(b"paid").min, Some(IndexValue::I64(40)));
399        // last row leaving a group drops the group
400        s.apply(b"o5", None, false);
401        assert_eq!(s.group(b"open").count, 0);
402        assert_eq!(s.stats().groups, 1);
403    }
404
405    #[test]
406    fn top_groups_all_metrics() {
407        let s = seg();
408        let top = s.top_groups(AggBy::Count, 10);
409        assert_eq!(top[0].0, b"paid".to_vec());
410        let top = s.top_groups(AggBy::Sum, 10);
411        assert_eq!(top[0].0, b"open".to_vec(), "open sum 1039 > paid 450");
412        let top = s.top_groups(AggBy::Min, 10);
413        assert_eq!(top[0].0, b"open".to_vec(), "min ascending: 40 first");
414        let top = s.top_groups(AggBy::Max, 1);
415        assert_eq!(top.len(), 1);
416        assert_eq!(top[0].0, b"open".to_vec(), "max 999");
417    }
418
419    #[test]
420    fn excluded_counted_and_merge() {
421        let mut s = seg();
422        s.apply(b"bad1", None, true);
423        s.apply(b"bad2", None, true);
424        assert_eq!(s.stats().excluded, 2);
425        assert!(s.contains(b"o1") && !s.contains(b"bad1"));
426        // cross-shard merge semantics
427        let mut a = s.group(b"paid");
428        let b = seg().group(b"paid");
429        merge_group(&mut a, &b);
430        assert_eq!((a.count, a.sum), (6, 900.0));
431        assert_eq!(a.min, Some(IndexValue::I64(100)));
432        assert_eq!(a.max, Some(IndexValue::I64(250)));
433        // merge with an empty partial keeps extremes
434        let mut e = GroupStats { count: 0, sum: 0.0, min: None, max: None };
435        merge_group(&mut e, &a);
436        assert_eq!(e.max, Some(IndexValue::I64(250)));
437    }
438
439    #[test]
440    fn stats_bytes_nonzero() {
441        let s = seg();
442        let st = s.stats();
443        assert_eq!((st.groups, st.rows), (2, 5));
444        assert!(st.approx_bytes > 0);
445    }
446
447    /// `stats()` reads running counters instead of walking the
448    /// maps. A mixed workload — inserts, the same-group fast path,
449    /// group moves, removals down to empty — holds them to the walking
450    /// reference after every step.
451    #[test]
452    fn running_stats_never_drift_from_the_walking_reference() {
453        let mut s = AggSegment::new();
454        let check = |s: &AggSegment, at: &str| {
455            assert_eq!(s.stats(), s.recompute_stats(), "counter drift after {at}");
456        };
457        let mut x = 0x2545F491u64;
458        let mut next = move || {
459            x = x.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
460            (x >> 33) as u32
461        };
462        let groups = [b"eng".as_slice(), b"sales", b"ops"];
463        for round in 0..300u32 {
464            let key = format!("r:{}", next() % 30);
465            match next() % 6 {
466                0 => s.apply(key.as_bytes(), None, false),
467                1 => s.apply(key.as_bytes(), None, true), // excluded
468                _ => {
469                    let g = groups[(next() % 3) as usize].to_vec();
470                    // Small value domain forces shared distinct entries.
471                    let v = IndexValue::I64(i64::from(next() % 7));
472                    s.apply(key.as_bytes(), Some((g, v)), false);
473                }
474            }
475            check(&s, &format!("round {round}"));
476        }
477        for i in 0..30u32 {
478            s.apply(format!("r:{i}").as_bytes(), None, false);
479        }
480        check(&s, "full drain");
481        let end = s.stats();
482        assert_eq!((end.groups, end.rows), (0, 0));
483    }
484}