1use std::collections::{BTreeMap, HashMap};
9
10use crate::IndexValue;
11
12#[derive(Debug, Clone, PartialEq)]
14pub struct GroupStats {
15 pub count: u64,
17 pub sum: f64,
20 pub min: Option<IndexValue>,
22 pub max: Option<IndexValue>,
24}
25
26impl GroupStats {
27 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 values: BTreeMap<IndexValue, u32>,
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
42pub enum AggBy {
43 #[default]
45 Count,
46 Sum,
48 Min,
50 Max,
52}
53
54impl AggBy {
55 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
73pub struct AggStats {
74 pub groups: u64,
76 pub rows: u64,
78 pub excluded: u64,
80 pub approx_bytes: u64,
83}
84
85#[derive(Default)]
87pub struct AggSegment {
88 groups: HashMap<Vec<u8>, Group>,
89 rows: HashMap<Vec<u8>, (Vec<u8>, IndexValue)>,
91 excluded: u64,
92 distinct_total: u64,
97 gkey_bytes: u64,
98 row_key_bytes: u64,
99}
100
101impl AggSegment {
102 pub fn new() -> Self {
104 Self::default()
105 }
106
107 #[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 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; }
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 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 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 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 #[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 pub fn all_groups(&self) -> Vec<(Vec<u8>, GroupStats)> {
259 self.groups.keys().map(|k| (k.clone(), self.group(k))).collect()
260 }
261
262 pub fn contains(&self, key: &[u8]) -> bool {
264 self.rows.contains_key(key)
265 }
266
267 pub fn rows(&self) -> u64 {
272 self.rows.len() as u64
273 }
274
275 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 #[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
309pub 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
336pub 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 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 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 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 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 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 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 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 #[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), _ => {
469 let g = groups[(next() % 3) as usize].to_vec();
470 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}