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
//! Per-group statistics and the one ranking order every face shares.
use crate::IndexValue;
/// One group's live statistics.
///
/// ```
/// use kevy_index::{GroupStats, IndexValue};
/// let mut total = GroupStats::default();
/// let mut part = GroupStats::default();
/// (part.count, part.sum, part.min, part.max) = (2, 10.0, Some(IndexValue::I64(3)), Some(IndexValue::I64(7)));
/// total.merge(&part);
/// assert_eq!(total.avg(), Some(5.0));
/// ```
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct GroupStats {
/// Rows in the group.
///
/// ```
/// # use kevy_index::{AggRow, AggSegment, IndexValue};
/// # let mut s = AggSegment::new();
/// # let row = |g: &[u8], v| AggRow::Member { group: g.to_vec(), value: IndexValue::I64(v) };
/// s.apply(b"o:1", row(b"eu", 30));
/// s.apply(b"o:2", row(b"eu", 12));
/// assert_eq!(s.group(b"eu").count, 2);
/// s.apply(b"o:2", AggRow::Removed);
/// assert_eq!(s.group(b"eu").count, 1);
/// ```
pub count: u64,
/// Sum of the aggregated field (f64 accumulation — the i64
/// overflow guard; precision bounds documented).
///
/// ```
/// # use kevy_index::{AggRow, AggSegment, IndexValue};
/// # let mut s = AggSegment::new();
/// # let row = |g: &[u8], v| AggRow::Member { group: g.to_vec(), value: IndexValue::I64(v) };
/// s.apply(b"o:1", row(b"eu", 30));
/// s.apply(b"o:2", row(b"eu", 12));
/// assert_eq!(s.group(b"eu").sum, 42.0);
/// ```
pub sum: f64,
/// Exact minimum (None only when count == 0).
///
/// ```
/// # use kevy_index::{AggRow, AggSegment, IndexValue};
/// # let mut s = AggSegment::new();
/// # let row = |g: &[u8], v| AggRow::Member { group: g.to_vec(), value: IndexValue::I64(v) };
/// s.apply(b"o:1", row(b"eu", 30));
/// s.apply(b"o:2", row(b"eu", 12));
/// assert_eq!(s.group(b"eu").min, Some(IndexValue::I64(12)));
/// // exact under deletion: the next-smallest value takes over
/// s.apply(b"o:2", AggRow::Removed);
/// assert_eq!(s.group(b"eu").min, Some(IndexValue::I64(30)));
/// assert_eq!(s.group(b"us").min, None, "an unknown group has no rows");
/// ```
pub min: Option<IndexValue>,
/// Exact maximum.
///
/// ```
/// # use kevy_index::{AggRow, AggSegment, IndexValue};
/// # let mut s = AggSegment::new();
/// # let row = |g: &[u8], v| AggRow::Member { group: g.to_vec(), value: IndexValue::I64(v) };
/// s.apply(b"o:1", row(b"eu", 30));
/// s.apply(b"o:2", row(b"eu", 12));
/// assert_eq!(s.group(b"eu").max, Some(IndexValue::I64(30)));
/// s.apply(b"o:1", row(b"eu", 5));
/// assert_eq!(s.group(b"eu").max, Some(IndexValue::I64(12)));
/// ```
pub max: Option<IndexValue>,
}
impl GroupStats {
/// Derived average.
///
/// ```
/// assert_eq!(kevy_index::GroupStats::default().avg(), None);
/// ```
pub fn avg(&self) -> Option<f64> {
(self.count > 0).then(|| self.sum / self.count as f64)
}
/// This group's standing under `by`, oriented so a larger score ranks
/// higher for every metric — the order [`sort_groups`] puts groups in
/// (a smaller minimum ranks higher; a group without one ranks last).
///
/// ```
/// use kevy_index::{AggBy, GroupStats, IndexValue};
/// let mut g = GroupStats::default();
/// (g.count, g.min) = (3, Some(IndexValue::I64(2)));
/// assert_eq!((g.rank_score(AggBy::Count), g.rank_score(AggBy::Min)), (3.0, -2.0));
/// assert_eq!(g.rank_score(AggBy::Max), f64::NEG_INFINITY);
/// ```
pub fn rank_score(&self, by: AggBy) -> f64 {
match by {
AggBy::Count => self.count as f64,
AggBy::Sum => self.sum,
AggBy::Max => self.max.as_ref().map_or(f64::NEG_INFINITY, IndexValue::as_f64),
AggBy::Min => self.min.as_ref().map_or(f64::NEG_INFINITY, |v| -v.as_f64()),
}
}
/// Fold one shard's partial for the same group into this one (reduce
/// side): counts and sums add, min and max take the extremes.
///
/// ```
/// use kevy_index::{GroupStats, IndexValue};
/// let mut a = GroupStats::default();
/// a.count = 1;
/// a.min = Some(IndexValue::I64(5));
/// let mut b = GroupStats::default();
/// b.count = 1;
/// b.min = Some(IndexValue::I64(2));
/// a.merge(&b);
/// assert_eq!((a.count, a.min), (2, Some(IndexValue::I64(2))));
/// ```
pub fn merge(&mut self, part: &GroupStats) {
self.count += part.count;
self.sum += part.sum;
self.min = match (self.min.take(), part.min.clone()) {
(Some(a), Some(b)) => Some(if b < a { b } else { a }),
(a, b) => a.or(b),
};
self.max = match (self.max.take(), part.max.clone()) {
(Some(a), Some(b)) => Some(if b > a { b } else { a }),
(a, b) => a.or(b),
};
}
}
/// Ranking metric for [`AggSegment::top_groups`](crate::AggSegment::top_groups).
///
/// ```
/// use kevy_index::AggBy;
/// assert_eq!(AggBy::default(), AggBy::Count);
/// assert_eq!(AggBy::parse(b"MAX"), Some(AggBy::Max), "tags are case-insensitive");
/// assert_eq!(AggBy::parse(b"avg"), None);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum AggBy {
/// By row count (default).
///
/// ```
/// # use kevy_index::{AggRow, AggSegment, IndexValue};
/// # let mut s = AggSegment::new();
/// # let row = |g: &[u8], v| AggRow::Member { group: g.to_vec(), value: IndexValue::I64(v) };
/// s.apply(b"o:1", row(b"eu", 30));
/// s.apply(b"o:2", row(b"eu", 12));
/// s.apply(b"o:3", row(b"us", 99));
/// let top = s.top_groups(kevy_index::AggBy::Count, 1);
/// assert_eq!((top[0].0.as_slice(), top[0].1.count), (&b"eu"[..], 2));
/// ```
#[default]
Count,
/// By sum.
///
/// ```
/// # use kevy_index::{AggRow, AggSegment, IndexValue};
/// # let mut s = AggSegment::new();
/// # let row = |g: &[u8], v| AggRow::Member { group: g.to_vec(), value: IndexValue::I64(v) };
/// s.apply(b"o:1", row(b"eu", 30));
/// s.apply(b"o:2", row(b"eu", 12));
/// s.apply(b"o:3", row(b"us", 99));
/// let top = s.top_groups(kevy_index::AggBy::Sum, 1);
/// assert_eq!((top[0].0.as_slice(), top[0].1.sum), (&b"us"[..], 99.0));
/// ```
Sum,
/// By minimum (ascending — smallest mins first).
///
/// ```
/// # use kevy_index::{AggRow, AggSegment, IndexValue};
/// # let mut s = AggSegment::new();
/// # let row = |g: &[u8], v| AggRow::Member { group: g.to_vec(), value: IndexValue::I64(v) };
/// s.apply(b"o:1", row(b"eu", 30));
/// s.apply(b"o:2", row(b"eu", 12));
/// s.apply(b"o:3", row(b"us", 99));
/// let top = s.top_groups(kevy_index::AggBy::Min, 2);
/// assert_eq!(top[0].0, b"eu", "12 < 99");
/// ```
Min,
/// By maximum (descending — largest maxes first).
///
/// ```
/// # use kevy_index::{AggRow, AggSegment, IndexValue};
/// # let mut s = AggSegment::new();
/// # let row = |g: &[u8], v| AggRow::Member { group: g.to_vec(), value: IndexValue::I64(v) };
/// s.apply(b"o:1", row(b"eu", 30));
/// s.apply(b"o:2", row(b"eu", 12));
/// s.apply(b"o:3", row(b"us", 99));
/// let top = s.top_groups(kevy_index::AggBy::Max, 2);
/// assert_eq!(top[0].0, b"us", "99 > 30");
/// ```
Max,
}
impl AggBy {
/// The wire tag, as [`AggBy::parse`] reads it.
///
/// ```
/// use kevy_index::AggBy;
/// assert_eq!(AggBy::parse(AggBy::Sum.tag().as_bytes()), Some(AggBy::Sum));
/// ```
pub fn tag(self) -> &'static str {
match self {
AggBy::Count => "count",
AggBy::Sum => "sum",
AggBy::Min => "min",
AggBy::Max => "max",
}
}
/// Wire tag.
pub fn parse(raw: &[u8]) -> Option<AggBy> {
if raw.eq_ignore_ascii_case(b"count") {
Some(AggBy::Count)
} else if raw.eq_ignore_ascii_case(b"sum") {
Some(AggBy::Sum)
} else if raw.eq_ignore_ascii_case(b"min") {
Some(AggBy::Min)
} else if raw.eq_ignore_ascii_case(b"max") {
Some(AggBy::Max)
} else {
None
}
}
}
/// Shared ranking order (per-shard AND at the reduce after merging
/// shard partials — one definition, no drift).
///
/// ```
/// use kevy_index::{AggBy, AggRow, AggSegment, IndexValue, sort_groups};
/// let row = |g: &[u8], v| AggRow::Member { group: g.to_vec(), value: IndexValue::I64(v) };
/// let (mut a, mut b) = (AggSegment::new(), AggSegment::new());
/// a.apply(b"o:1", row(b"eu", 5));
/// b.apply(b"o:2", row(b"us", 9));
/// b.apply(b"o:3", row(b"us", 1));
/// // reduce: concatenate the shards' unranked chunks, then rank once
/// let mut all = a.all_groups();
/// all.extend(b.all_groups());
/// sort_groups(&mut all, AggBy::Sum);
/// assert_eq!(all[0].0, b"us");
/// sort_groups(&mut all, AggBy::Min);
/// assert_eq!(all[0].0, b"us", "1 is the smallest minimum");
/// ```
pub fn sort_groups(all: &mut [(Vec<u8>, GroupStats)], by: AggBy) {
match by {
AggBy::Count => all.sort_by(|a, b| b.1.count.cmp(&a.1.count).then_with(|| a.0.cmp(&b.0))),
AggBy::Sum => all.sort_by(|a, b| b.1.sum.total_cmp(&a.1.sum).then_with(|| a.0.cmp(&b.0))),
AggBy::Min => all.sort_by(|a, b| {
match (&a.1.min, &b.1.min) {
(Some(x), Some(y)) => x.cmp(y),
(Some(_), None) => std::cmp::Ordering::Less,
(None, Some(_)) => std::cmp::Ordering::Greater,
(None, None) => std::cmp::Ordering::Equal,
}
.then_with(|| a.0.cmp(&b.0))
}),
AggBy::Max => all.sort_by(|a, b| {
match (&a.1.max, &b.1.max) {
(Some(x), Some(y)) => y.cmp(x),
(Some(_), None) => std::cmp::Ordering::Less,
(None, Some(_)) => std::cmp::Ordering::Greater,
(None, None) => std::cmp::Ordering::Equal,
}
.then_with(|| a.0.cmp(&b.0))
}),
}
}