Skip to main content

ic_db/store/query/aggregate/
mod.rs

1//! Bounded aggregates over the shared scanner and exact reducers, without row history.
2
3mod float_sum;
4pub(super) mod jobs;
5mod numeric;
6
7use super::distinct::DistinctKeys;
8use super::probe::{MemberProbe, probe_members};
9use super::{
10    Comparison, MAX_COMPARISON_KEY, MAX_DISTINCT_VALUES, MAX_STATE_BYTES, MAX_TERMS, Plan,
11    PlanOutput, Query, QueryPage, admit_ordered_fields, admit_output, admit_projection,
12    comparison_key, copy_projection, execute, projection_size,
13};
14use crate::{
15    Entity, EntitySchema, Error, FieldType, IndexValue, TypeSchema, Value, ValueSchema,
16    codec::Decoder, key,
17};
18use ic_storage::Memory;
19use std::collections::BTreeMap;
20
21const MAX_GROUPS: usize = 32;
22
23/// Numeric result used to order completed summary groups.
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25#[repr(u8)]
26pub enum SummaryMeasure {
27    /// Number of present operands.
28    Count = 0,
29    /// Completed sum.
30    Sum = 1,
31    /// Average after rounding to the declared result type.
32    Average = 2,
33}
34
35/// Completed-group ordering. Aggregate ties always use ascending canonical keys.
36#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
37pub enum GroupOrder {
38    /// Ascending group-key tuple, in canonical field-name order (the default).
39    #[default]
40    Key,
41    /// Ascending aggregate value; absent values precede present values.
42    AggregateAscending,
43    /// Descending aggregate value; absent values follow present values.
44    AggregateDescending,
45    /// Descending group-key tuple, in canonical field-name order; absence sorts last.
46    KeyDescending,
47    /// Retained DISTINCT keys in first matching input order.
48    FirstOccurrence,
49    /// Order a grouped numeric summary by one completed measure.
50    Summary(SummaryMeasure, super::SortDirection),
51}
52
53struct GroupPredicate<T> {
54    measure: Option<SummaryMeasure>,
55    comparison: Comparison,
56    operand: T,
57    or_next: bool,
58}
59
60#[derive(Default)]
61pub(super) struct GroupRequest<'a> {
62    predicates: Vec<GroupPredicate<IndexValue<'a>>>,
63    order: Option<GroupOrder>,
64    page: Option<jobs::pages::PageRequest<'a>>,
65}
66impl GroupRequest<'_> {
67    pub(super) fn is_empty(&self) -> bool {
68        self.predicates.is_empty() && self.order.is_none() && self.page.is_none()
69    }
70
71    fn admit(
72        &self,
73        entity: &EntitySchema,
74        reducer: &Reducer,
75        summary_sum: Option<ValueSchema>,
76    ) -> Result<Selection, Error> {
77        if self
78            .page
79            .is_some_and(|page| !(1..=MAX_GROUPS).contains(&page.size))
80        {
81            return Err(Error::Limit);
82        }
83        let field = match reducer {
84            Reducer::Keys(_) => {
85                let order = self.order.unwrap_or_default();
86                if !self.predicates.is_empty()
87                    || !matches!(
88                        order,
89                        GroupOrder::Key | GroupOrder::KeyDescending | GroupOrder::FirstOccurrence
90                    )
91                {
92                    return Err(Error::InvalidQuery);
93                }
94
95                return Ok(Selection {
96                    predicates: Vec::new(),
97                    order,
98                    optional: false,
99                });
100            }
101            Reducer::Count { .. } | Reducer::Distinct { .. } => ValueSchema {
102                value: FieldType::Nat64,
103                optional: false,
104            },
105            Reducer::Extremum { position, .. } => {
106                let field = &entity.fields[*position];
107
108                ValueSchema {
109                    value: field.value,
110                    optional: field.optional,
111                }
112            }
113            Reducer::Numeric(state) => state.output(),
114        };
115        if self.order == Some(GroupOrder::FirstOccurrence) {
116            return Err(Error::InvalidQuery);
117        }
118        // Extrema/numeric results may be absent even with required input fields.
119        let absent_result = !matches!(reducer, Reducer::Count { .. } | Reducer::Distinct { .. });
120        let predicates = self
121            .predicates
122            .iter()
123            .map(
124                |&GroupPredicate {
125                     comparison,
126                     operand: value,
127                     or_next,
128                     measure,
129                 }| {
130                    let (field, absent_result) = match (measure, summary_sum) {
131                        (None, None) => (field, absent_result),
132                        (Some(SummaryMeasure::Count), Some(_)) => (
133                            ValueSchema {
134                                value: FieldType::Nat64,
135                                optional: false,
136                            },
137                            false,
138                        ),
139                        (Some(SummaryMeasure::Sum), Some(sum)) => (sum, true),
140                        (Some(SummaryMeasure::Average), Some(_)) => (field, true),
141                        _ => return Err(Error::InvalidQuery),
142                    };
143                    if match value {
144                        IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
145                        IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
146                        _ => false,
147                    } {
148                        return Err(Error::Limit);
149                    }
150                    comparison.admit(field.value, absent_result, value)?;
151                    let key = if value == IndexValue::Absent {
152                        None
153                    } else {
154                        let mut key = Vec::new();
155                        value.append_component(field.optional, &mut key);
156                        if key.len() > MAX_COMPARISON_KEY {
157                            return Err(Error::Limit);
158                        }
159
160                        Some(key)
161                    };
162
163                    Ok(GroupPredicate {
164                        measure,
165                        comparison,
166                        operand: key,
167                        or_next,
168                    })
169                },
170            )
171            .collect::<Result<_, Error>>()?;
172
173        Ok(Selection {
174            predicates,
175            order: self.order.unwrap_or_default(),
176            optional: field.optional,
177        })
178    }
179}
180
181struct Selection {
182    predicates: Vec<GroupPredicate<Option<Vec<u8>>>>,
183    order: GroupOrder,
184    // Physical comparison-key framing, distinct from an absent aggregate result.
185    optional: bool,
186}
187
188impl Selection {
189    fn needs_summary_key(&self, measure: SummaryMeasure) -> bool {
190        matches!(self.order, GroupOrder::Summary(ordered, _) if ordered == measure)
191            || self
192                .predicates
193                .iter()
194                .any(|term| term.measure == Some(measure))
195    }
196
197    fn accepts<'a>(&self, key: impl Fn(Option<SummaryMeasure>) -> Option<&'a [u8]>) -> bool {
198        self.predicates
199            .split_inclusive(|term| !term.or_next)
200            .all(|clause| {
201                clause.iter().any(|term| {
202                    term.comparison.accepts(
203                        key(term.measure),
204                        term.operand.as_deref(),
205                        self.optional && term.measure != Some(SummaryMeasure::Count),
206                    )
207                })
208            })
209    }
210}
211
212/// A completed aggregate and its execution costs. No partial result or cursor.
213#[derive(Debug)]
214pub struct Aggregate<T> {
215    /// Completed value over all matching input rows.
216    pub value: T,
217    /// Examined primary/index candidates, including residual nonmatches and missing point probes.
218    pub examined: usize,
219    /// Fetched and validated source rows.
220    pub fetched: usize,
221    /// Encoded result bytes, excluding transport framing.
222    pub output_bytes: usize,
223}
224
225/// One complete group. Absent optional key values belong to a group too.
226#[derive(Debug)]
227pub struct GroupCount<K> {
228    /// Projected grouping tuple in an ordinary named record.
229    pub key: K,
230    /// Matching rows, or present operand values for `group_count_field`.
231    pub count: u64,
232}
233
234/// Completed numeric summaries and the work of their shared scan.
235pub type GroupSummaries<K, S, A> = Aggregate<Vec<GroupSummary<K, S, A>>>;
236
237/// A page of completed retained numeric summaries.
238pub type GroupSummaryPage<K, S, A> = jobs::GroupPage<GroupSummary<K, S, A>>;
239
240/// Count, sum and average of one numeric operand in a completed group.
241#[derive(Debug)]
242pub struct GroupSummary<K, S, A> {
243    /// Grouping record.
244    pub key: K,
245    /// Number of present operands (the average denominator).
246    pub count: u64,
247    /// Exact sum converted to the declared sum result.
248    pub sum: Option<S>,
249    /// Average rounded once to the declared average result.
250    pub average: Option<A>,
251}
252
253/// One complete group's aggregate value, preserving all-absent groups.
254#[derive(Debug)]
255pub struct GroupValue<K, R> {
256    /// Projected grouping tuple, including optional absent keys.
257    pub key: K,
258    /// Single-field result record, or `None` when the group has no present operand.
259    pub value: Option<R>,
260}
261
262impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
263    /// Page completed retained groups, returning at most 1..=32 rows per response.
264    /// `limit` still caps the complete selected result and binds the job. Page size
265    /// and byte allowance may change. Supply None for the first page; continuation
266    /// is valid only for a completed job. Only grouped resume terminals accept this.
267    #[must_use]
268    pub fn group_page(mut self, size: usize, after: Option<&'a jobs::GroupCursor>) -> Self {
269        self.request.groups.page = Some(jobs::pages::PageRequest { size, after });
270
271        self
272    }
273
274    /// Add an AND predicate on the completed aggregate value, before group ordering
275    /// and output limits. At most eight terms. Counts require Nat64 operands;
276    /// extrema require the source type; sums require the declared result type.
277    /// Absent values support Eq/Ne only. Text and Blob extrema also accept StartsWith,
278    /// EndsWith and Contains.
279    /// Only grouped terminals accept this modifier, even for empty input.
280    #[must_use]
281    pub fn filter_groups(self, comparison: Comparison, value: impl Into<IndexValue<'a>>) -> Self {
282        self.add_group_clause(std::iter::once((None, comparison, value.into())))
283    }
284
285    /// Require a completed summary measure to satisfy the comparison before ordering or limiting.
286    /// Calls are ANDed. Count uses Nat64; sum and average use their declared result types.
287    #[must_use]
288    pub fn filter_summary(
289        self,
290        measure: SummaryMeasure,
291        comparison: Comparison,
292        value: impl Into<IndexValue<'a>>,
293    ) -> Self {
294        self.add_group_clause(std::iter::once((Some(measure), comparison, value.into())))
295    }
296
297    /// Require at least one comparison on a completed count, sum or rounded average.
298    /// Alternatives can name different measures. Separate clauses are ANDed.
299    /// A clause must be nonempty and all group predicates share the eight-term limit.
300    #[must_use]
301    pub fn filter_summary_any(
302        self,
303        alternatives: &[(SummaryMeasure, Comparison, IndexValue<'a>)],
304    ) -> Self {
305        self.add_group_clause(
306            alternatives
307                .iter()
308                .map(|&(measure, comparison, value)| (Some(measure), comparison, value)),
309        )
310    }
311
312    /// Add an OR clause on completed aggregate values, ANDed with other group
313    /// filters. The clause must be nonempty; all group filters together permit
314    /// eight comparisons. Every operand is admitted before reading any rows.
315    /// Uses `filter_groups`' exact type and absence rules. All groups must finish
316    /// and validate before selection, ordering and output limits. Clause boundaries
317    /// bind retained jobs; a singleton clause is equivalent to `filter_groups`.
318    #[must_use]
319    pub fn filter_groups_any(self, alternatives: &[(Comparison, IndexValue<'a>)]) -> Self {
320        self.add_group_clause(
321            alternatives
322                .iter()
323                .map(|&(comparison, value)| (None, comparison, value)),
324        )
325    }
326
327    fn add_group_clause(
328        mut self,
329        terms: impl ExactSizeIterator<Item = (Option<SummaryMeasure>, Comparison, IndexValue<'a>)>,
330    ) -> Self {
331        let count = terms.len();
332        if count == 0 || count > MAX_TERMS - self.request.groups.predicates.len() {
333            self.request.over_limit = true;
334        } else {
335            self.request.groups.predicates.extend(terms.enumerate().map(
336                |(i, (measure, comparison, operand))| GroupPredicate {
337                    measure,
338                    comparison,
339                    operand,
340                    or_next: i + 1 != count,
341                },
342            ));
343        }
344
345        self
346    }
347
348    /// Order completed groups before applying output limits. Retained DISTINCT
349    /// also accepts key order and first-occurrence order. The last call selects the order.
350    #[must_use]
351    pub fn order_groups(mut self, order: GroupOrder) -> Self {
352        self.request.groups.order = Some(order);
353
354        self
355    }
356
357    /// Minimum present value of an exact single-field record projection.
358    /// Supports ordered scalars/unit enums without requiring an index. The result
359    /// preserves the declared type and optionality; empty/all-absent input returns
360    /// `None`. `limit` never truncates input. Only the winning record's bytes count
361    /// toward the engine output bound; an absent result occupies zero payload bytes.
362    /// # Errors
363    /// Refuses multi-field projections, unsupported types, cursors, DISTINCT and
364    /// explicit ordering. Work exhaustion or a comparison key beyond 4096 bytes
365    /// returns `Limit`; an oversized winning result returns `RowTooLarge`.
366    /// Ordinary projection/query errors apply. Completion must precede `work_limit`.
367    /// # Panics
368    /// Supplier corruption traps without repair.
369    pub fn min<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
370        observe!(query, { self.extremum(false) })
371    }
372
373    /// Maximum present value, with the same types, bounds and empty-input behavior
374    /// as [`Self::min`]. Equal operands retain the first encountered value.
375    /// # Errors
376    /// The same projection, resource and query errors as [`Self::min`].
377    /// # Panics
378    /// Supplier corruption traps without repair.
379    pub fn max<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
380        observe!(query, { self.extremum(true) })
381    }
382
383    fn extremum<R: Value>(self, maximum: bool) -> Result<Aggregate<Option<R>>, Error> {
384        let (plan, reducer) = self.extremum_plan::<R>(maximum)?;
385
386        self.scalar_value(plan, reducer)
387    }
388
389    fn extremum_plan<R: Value>(&self, maximum: bool) -> Result<(Plan<'a>, Reducer), Error> {
390        let plan = self.aggregate_plan(Some(R::definition()), false)?;
391        let reducer = Reducer::extremum(
392            E::SCHEMA,
393            plan.projection.ok_or(Error::InvalidQuery)?,
394            maximum,
395        )?;
396
397        Ok((plan, reducer))
398    }
399
400    fn scalar_value<R: Value>(
401        self,
402        mut plan: Plan<'_>,
403        mut reducer: Reducer,
404    ) -> Result<Aggregate<Option<R>>, Error> {
405        super::order::select_unique_aggregate_path(E::SCHEMA, &self.request, &mut plan)?;
406        let page = execute(
407            &self.db.read()?.map,
408            E::SCHEMA,
409            &self.request,
410            &plan,
411            Some(Accumulator::Scalar(&mut reducer)),
412        )?;
413        let (value, output_bytes) = scalar_output(reducer, self.request.bytes)?;
414
415        Ok(Aggregate {
416            value,
417            examined: page.examined,
418            fetched: page.fetched,
419            output_bytes,
420        })
421    }
422
423    /// Minimum present operand per group. `K` is an exact grouping record; `R`
424    /// is an exact single-field operand record. They may overlap. All-absent
425    /// groups retain `None`; empty input yields no groups. No index is required.
426    /// Groups default to ascending canonical field-name tuple order;
427    /// `filter_groups` and `order_groups` select completed results. `limit` selects
428    /// completed groups, never input rows. Output bytes are the key record plus
429    /// the present winning record; transport option framing is excluded.
430    /// At most 32 groups and 128 KiB of retained keys, records and reducer payloads
431    /// are admitted. Every comparison key is bounded to 4096 bytes. Winner growth
432    /// is charged, and replacement releases the previous winner's charge.
433    /// # Errors
434    /// The projection, work and shape refusals of [`Self::min`] apply. Group or
435    /// retained-state exhaustion returns `Limit`. An oversized output group
436    /// returns `RowTooLarge`; combined output exhaustion returns `Limit`.
437    /// # Panics
438    /// Supplier corruption traps without repair.
439    pub fn group_min<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
440        observe!(query, { self.group_extrema(false) })
441    }
442
443    /// Maximum present operand per group, with the contract of [`Self::group_min`].
444    /// # Errors
445    /// The same projection, work, state, shape and output refusals as grouped minimum.
446    /// # Panics
447    /// Supplier corruption traps without repair.
448    pub fn group_max<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
449        observe!(query, { self.group_extrema(true) })
450    }
451
452    fn group_extrema<K: Value, R: Value>(
453        self,
454        maximum: bool,
455    ) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
456        let (plan, initial) = self.group_extremum_plan::<K, R>(maximum)?;
457
458        self.group_values(plan, initial)
459    }
460
461    fn group_extremum_plan<K: Value, R: Value>(
462        &self,
463        maximum: bool,
464    ) -> Result<(Plan<'a>, Reducer), Error> {
465        let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
466        let operand = admit_projection(E::SCHEMA, R::definition())?;
467        let initial = Reducer::extremum(E::SCHEMA, operand, maximum)?;
468        plan.selected |= operand;
469
470        Ok((plan, initial))
471    }
472
473    fn group_values<K: Value, R: Value>(
474        self,
475        mut plan: Plan<'_>,
476        initial: Reducer,
477    ) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
478        super::order::select_unique_aggregate_path(E::SCHEMA, &self.request, &mut plan)?;
479        group_output(
480            self.grouped(&plan, initial, None)?,
481            &self.request,
482            decode_group_value,
483        )
484    }
485
486    /// Whether at least one row matches, without materializing an entity.
487    /// Can seek a mandatory equality prefix and evaluate remaining filters on its owner rows.
488    /// A bounded list of complete keys can be probed in key order. Each hit is validated.
489    /// Stops after validating the first matching row; later rows are not inspected.
490    /// Returns false only after observing the end of the selected input.
491    /// `limit` does not truncate input. The boolean result occupies one byte.
492    /// # Errors
493    /// Refuses cursors, DISTINCT, explicit ordering and group modifiers, as for
494    /// `count`. If no examined row matches and another candidate remains
495    /// beyond `work_limit`, returns `Limit`.
496    /// Ordinary admission and examined-row integrity errors still apply.
497    /// # Panics
498    /// Supplier corruption traps without repair, as for ordinary query execution.
499    pub fn exists(self) -> Result<Aggregate<bool>, Error> {
500        observe!(query, {
501            let mut plan = self.count_plan(None)?;
502            self.select_aggregate_row_path(&mut plan, Some(MemberProbe::Exists))?;
503            if let Some(result) = probe_members(
504                &self.db,
505                E::SCHEMA,
506                &self.request,
507                &plan,
508                MemberProbe::Exists,
509                1,
510            )? {
511                return Ok(Aggregate {
512                    value: result.value != 0,
513                    examined: result.examined,
514                    fetched: result.fetched,
515                    output_bytes: 1,
516                });
517            }
518            let mut remaining = 1;
519            let page = execute(
520                &self.db.read()?.map,
521                E::SCHEMA,
522                &self.request,
523                &plan,
524                Some(Accumulator::Until(&mut remaining)),
525            )?;
526
527            Ok(Aggregate {
528                value: remaining == 0,
529                examined: page.examined,
530                fetched: page.fetched,
531                output_bytes: 1,
532            })
533        })
534    }
535
536    /// Count all matching rows in one synchronous execution. Empty input yields zero.
537    /// Uses maintained cardinality when all rows qualify. Physical index keys can
538    /// answer fully covered index ranges or primary-key comparison ranges. A partially covered
539    /// equality prefix narrows the owner rows checked by the remaining predicates.
540    /// Membership counts can probe distinct complete primary or secondary keys within
541    /// the work budget. A hit requires an owner read only when its filters need row values. Use
542    /// [`Self::count_validated`] to check each visited row and selected index owner.
543    /// `limit` does not limit input; the scalar output occupies eight bytes.
544    /// A scan completes when its last candidate uses the final unit of work. Use `start_count`/`resume_count` for retained work.
545    /// # Errors
546    /// Refuses cursors, DISTINCT, explicit ordering and the ordinary query failures.
547    /// Work exhaustion returns `Limit`, never a partial count. Too few output bytes
548    /// returns `RowTooLarge`.
549    /// # Panics
550    /// Supplier corruption traps without repair, as for ordinary query execution.
551    pub fn count(self) -> Result<Aggregate<u64>, Error> {
552        observe!(query, {
553            if self.request.bytes < 8 {
554                return Err(Error::RowTooLarge);
555            }
556            self.count_until(u64::MAX)
557        })
558    }
559
560    /// Test a minimum match count, stopping as soon as the requested number is proven.
561    /// Uses the same maintained counts and covered keys as `count`.
562    /// Zero is true after admission. The result occupies one byte.
563    /// # Errors
564    /// Returns ordinary count admission errors and `Limit` if work runs out before
565    /// either reaching the threshold or exhausting the input.
566    pub fn has_at_least(self, minimum: u64) -> Result<Aggregate<bool>, Error> {
567        observe!(query, {
568            let result = self.count_until(minimum)?;
569            Ok(Aggregate {
570                value: result.value >= minimum,
571                examined: result.examined,
572                fetched: result.fetched,
573                output_bytes: 1,
574            })
575        })
576    }
577
578    fn count_until(self, stop: u64) -> Result<Aggregate<u64>, Error> {
579        if self.request.is_plain_count() {
580            return self.entity_count();
581        }
582        let mut plan = self.count_plan(None)?;
583        if stop == 0 {
584            return Ok(Aggregate {
585                value: 0,
586                examined: 0,
587                fetched: 0,
588                output_bytes: 8,
589            });
590        }
591        if self.request.index.is_none()
592            && self
593                .request
594                .clauses()
595                .zip(plan.clauses())
596                .all(|(clause, terms)| {
597                    clause.iter().zip(terms).any(|(p, term)| {
598                        p.constant_comparison(E::SCHEMA) == Some(true)
599                            || (term.tests_presence && E::SCHEMA.field_is_required(p.field))
600                    })
601                })
602        {
603            return self.entity_count();
604        }
605        if let Some(count) = probe_members(
606            &self.db,
607            E::SCHEMA,
608            &self.request,
609            &plan,
610            MemberProbe::CountKeys,
611            stop,
612        )? {
613            return Ok(count);
614        }
615        if super::order::select_filtered_path(
616            E::SCHEMA,
617            &self.request,
618            &mut plan,
619            Some(MemberProbe::CountWithRows),
620        )? {
621            return self.count_keys(&plan, stop);
622        }
623        if let Some(count) = probe_members(
624            &self.db,
625            E::SCHEMA,
626            &self.request,
627            &plan,
628            MemberProbe::CountWithRows,
629            stop,
630        )? {
631            return Ok(count);
632        }
633        let mut remaining = stop;
634        let page = execute(
635            &self.db.read()?.map,
636            E::SCHEMA,
637            &self.request,
638            &plan,
639            Some(Accumulator::Until(&mut remaining)),
640        )?;
641        Ok(Aggregate {
642            value: stop - remaining,
643            examined: page.examined,
644            fetched: page.fetched,
645            output_bytes: 8,
646        })
647    }
648
649    fn entity_count(&self) -> Result<Aggregate<u64>, Error> {
650        Ok(Aggregate {
651            value: self.db.read()?.cardinality::<E>()?,
652            examined: 0,
653            fetched: 0,
654            output_bytes: 8,
655        })
656    }
657
658    /// Count by validating each visited row, including its selected index entry.
659    /// For bounded exact-key lists, each distinct candidate costs one probe,
660    /// including misses. Every hit is checked before returning the count.
661    /// # Errors
662    /// Returns the same admission and resource errors as [`Self::count`], and
663    /// reports corruption encountered during traversal.
664    pub fn count_validated(self) -> Result<Aggregate<u64>, Error> {
665        observe!(query, { self.scalar_count(None) })
666    }
667
668    /// Count physical entries in the range selected by `using_index` and its
669    /// leading operands. This reads neither index values nor owner rows. A
670    /// dangling index entry counts as one. Use [`Self::count_validated`] to validate rows.
671    /// Like other scalar counts, the row limit does not truncate the input.
672    /// # Errors
673    /// Requires an explicit index. Row predicates, ordering, cursors, grouping
674    /// and DISTINCT refuse. A range with more entries than the work limit returns
675    /// `Limit`; fewer than eight output bytes returns `RowTooLarge`.
676    /// # Panics
677    /// Malformed supplier storage can trap during traversal.
678    pub fn count_index_entries(self) -> Result<Aggregate<u64>, Error> {
679        observe!(query, {
680            if self.request.index.is_none() || !self.request.predicates.is_empty() {
681                return Err(Error::InvalidQuery);
682            }
683            if self.request.bytes < 8 {
684                return Err(Error::RowTooLarge);
685            }
686            let plan = self.count_plan(None)?;
687
688            self.count_keys(&plan, u64::MAX)
689        })
690    }
691
692    fn count_keys(&self, plan: &Plan<'_>, stop: u64) -> Result<Aggregate<u64>, Error> {
693        let bounds = super::range::bounds(E::SCHEMA, &self.request, plan)?;
694        let mut examined = 0;
695        if let Some(range) = bounds {
696            let db = self.db.read()?;
697            if let Some(key) = super::range::exact_key(&range) {
698                examined = usize::from(db.map.contains_key(key));
699            } else {
700                let keys = db.map.keys_range((range.0.as_ref(), range.1.as_ref()));
701                for _ in keys {
702                    if examined == self.request.work {
703                        return Err(Error::Limit);
704                    }
705                    examined += 1;
706                    if examined as u64 == stop {
707                        break;
708                    }
709                }
710            }
711        }
712
713        Ok(Aggregate {
714            value: examined as u64,
715            examined,
716            fetched: 0,
717            output_bytes: 8,
718        })
719    }
720
721    /// Count present values of a top-level field, including non-scalar fields.
722    /// Empty input and all-absent input yield zero; present empty values count.
723    /// Limits, refusals and corruption traps are the same as [`Self::count`].
724    /// # Errors
725    /// Unknown fields refuse even for empty input. Ordinary count errors apply.
726    /// # Panics
727    /// Supplier corruption traps without repair.
728    pub fn count_field(self, field: &str) -> Result<Aggregate<u64>, Error> {
729        observe!(query, { self.scalar_count(Some(field)) })
730    }
731
732    /// Count distinct projected tuples, including absent values. An indexed filter can narrow the input.
733    /// Retain at most 32 distinct comparison keys, each at most 4096 bytes, within
734    /// the shared 128-KiB state bound. No projected records are retained. `limit`
735    /// never truncates this count. The scalar result occupies eight bytes.
736    /// A mandatory literal equality or fixed index prefix excludes that field
737    /// from the comparison key. An empty input still counts zero tuples.
738    /// # Errors
739    /// Ordinary count/projection errors and distinct-state exhaustion refuse.
740    /// # Panics
741    /// Supplier corruption traps without repair.
742    pub fn count_distinct<K: Value>(self) -> Result<Aggregate<u64>, Error> {
743        observe!(query, {
744            if self.request.bytes < 8 {
745                return Err(Error::RowTooLarge);
746            }
747            let mut plan = self.count_plan(Some(K::definition()))?;
748            self.select_aggregate_row_path(&mut plan, None)?;
749            let projected = plan.projection.ok_or(Error::InvalidQuery)?;
750            let fixed = super::distinct::fixed_fields(E::SCHEMA, &self.request, &plan);
751
752            self.scalar_count_value(&plan, Reducer::distinct(projected & !fixed))
753        })
754    }
755
756    fn select_aggregate_row_path(
757        &self,
758        plan: &mut Plan<'static>,
759        probe: Option<MemberProbe>,
760    ) -> Result<(), Error> {
761        if plan.index.is_none() {
762            super::order::select_filtered_path(E::SCHEMA, &self.request, plan, probe)?;
763        }
764
765        Ok(())
766    }
767
768    fn scalar_count(self, field: Option<&str>) -> Result<Aggregate<u64>, Error> {
769        if self.request.bytes < 8 {
770            return Err(Error::RowTooLarge);
771        }
772        let mut plan = self.count_plan(None)?;
773        let probe = field.is_none().then_some(MemberProbe::CountValidated);
774        self.select_aggregate_row_path(&mut plan, probe)?;
775        if let Some(probe) = probe
776            && let Some(count) =
777                probe_members(&self.db, E::SCHEMA, &self.request, &plan, probe, u64::MAX)?
778        {
779            return Ok(count);
780        }
781        let reducer = self.count_reducer(field)?;
782
783        self.scalar_count_value(&plan, reducer)
784    }
785
786    fn scalar_count_value(
787        self,
788        plan: &Plan<'_>,
789        mut reducer: Reducer,
790    ) -> Result<Aggregate<u64>, Error> {
791        let page = execute(
792            &self.db.read()?.map,
793            E::SCHEMA,
794            &self.request,
795            plan,
796            Some(Accumulator::Scalar(&mut reducer)),
797        )?;
798
799        Ok(Aggregate {
800            value: reducer.finish(false)?.into_count()?,
801            examined: page.examined,
802            fetched: page.fetched,
803            output_bytes: 8,
804        })
805    }
806
807    /// Count matching rows grouped by an exact named-record projection.
808    /// Keys support ordered scalars/unit enums, including optional absence; no index
809    /// is required. Results default to ascending tuple order in canonical field-name order.
810    /// `filter_groups` and `order_groups` select completed results before output limits.
811    /// `limit` selects the first completed groups (1..=32), never input rows.
812    /// The engine output allowance bounds key-record bytes plus eight count bytes per group.
813    /// Empty input yields no groups. At most 32 groups and 128 KiB of key/output
814    /// state may be retained, independently of the requested output limit;
815    /// each comparison key is capped at 4096 bytes, independently of index-key limits.
816    /// # Errors
817    /// Refuses unsupported key types, cursors, DISTINCT and explicit ordering.
818    /// Work, group or retained-state exhaustion returns `Limit`, never partial groups.
819    /// Completion must be established within `work_limit`; a boundary scan can refuse.
820    /// Ordinary projection/query integrity and byte-limit errors also apply.
821    /// # Panics
822    /// Supplier corruption traps without repair, as for ordinary query execution.
823    pub fn group_count<K: Value>(self) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
824        observe!(query, { self.group_counts(None) })
825    }
826
827    /// Count present operand values within each projected group. Groups whose
828    /// operands are all absent remain in the output with count zero. The operand
829    /// may be any top-level stored field and need not belong to the group key.
830    /// Bounds and ordering are the same as [`Self::group_count`].
831    /// # Errors
832    /// Unknown operands and ordinary grouped-count errors refuse.
833    /// # Panics
834    /// Supplier corruption traps without repair.
835    pub fn group_count_field<K: Value>(
836        self,
837        field: &str,
838    ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
839        observe!(query, { self.group_counts(Some(field)) })
840    }
841
842    /// Count distinct projected `R` tuples within each projected `K` group.
843    /// Absence is a tuple component, as for [`Self::count_distinct`]; an all-absent
844    /// group has one distinct tuple, not zero. Projections may overlap. No index
845    /// is required. Complete input before group filtering/order and output limits.
846    /// Each group's set compares only operand fields that can vary within it.
847    /// Retain at most 32 groups and 32 distinct tuples per group, with one shared
848    /// 128-KiB state allowance and a 4096-byte cap per comparison key.
849    /// # Errors
850    /// Refuses unsupported projections, cursors, DISTINCT and explicit input order.
851    /// Work, cardinality or byte exhaustion returns `Limit`, never partial counts.
852    /// Ordinary grouped-count output and integrity errors apply.
853    /// # Panics
854    /// Supplier corruption traps without repair.
855    pub fn group_count_distinct<K: Value, R: Value>(
856        self,
857    ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
858        observe!(query, {
859            let (plan, reducer) = self.group_distinct_plan::<K, R>()?;
860
861            self.group_count_values(plan, reducer)
862        })
863    }
864
865    fn group_distinct_plan<K: Value, R: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
866        let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
867        let operand = admit_projection(E::SCHEMA, R::definition())?;
868        admit_ordered_fields(E::SCHEMA, operand)?;
869        plan.selected |= operand;
870
871        Ok((plan, Reducer::distinct(operand)))
872    }
873
874    fn group_counts<K: Value>(
875        self,
876        field: Option<&str>,
877    ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
878        let plan = self.aggregate_plan(Some(K::definition()), true)?;
879        let reducer = self.count_reducer(field)?;
880
881        self.group_count_values(plan, reducer)
882    }
883
884    fn group_count_values<K: Value>(
885        self,
886        mut plan: Plan<'static>,
887        mut reducer: Reducer,
888    ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
889        self.select_aggregate_row_path(&mut plan, None)?;
890        if let Reducer::Distinct { mask, .. } = &mut reducer {
891            let grouped = plan.projection.ok_or(Error::InvalidQuery)?;
892            let fixed = super::distinct::fixed_fields(E::SCHEMA, &self.request, &plan);
893            *mask &= !(grouped | fixed);
894        }
895        group_output(
896            self.grouped(&plan, reducer, None)?,
897            &self.request,
898            decode_group_count,
899        )
900    }
901
902    fn count_reducer(&self, field: Option<&str>) -> Result<Reducer, Error> {
903        // Presence needs only the validated tag, not an ordered scalar slot.
904        let presence = field
905            .map(|name| E::SCHEMA.field_position(name).ok_or(Error::InvalidQuery))
906            .transpose()?
907            .filter(|&i| E::SCHEMA.fields[i].optional);
908
909        Ok(Reducer::Count { presence, total: 0 })
910    }
911
912    fn grouped(
913        &self,
914        plan: &Plan<'_>,
915        initial: Reducer,
916        summary_sum: Option<ValueSchema>,
917    ) -> Result<(Groups, QueryPage<Vec<u8>>), Error> {
918        if self.request.groups.page.is_some() {
919            return Err(Error::InvalidQuery);
920        }
921        let mut groups = self
922            .request
923            .admit_groups(E::SCHEMA, plan, initial, summary_sum)?;
924        let page = execute(
925            &self.db.read()?.map,
926            E::SCHEMA,
927            &self.request,
928            plan,
929            Some(Accumulator::Groups(&mut groups)),
930        )?;
931
932        Ok((groups, page))
933    }
934
935    fn count_plan(&self, output: Option<&TypeSchema>) -> Result<Plan<'static>, Error> {
936        self.request
937            .aggregate_plan(&self.db, E::SCHEMA, output, PlanOutput::ImmediateCount)
938    }
939
940    fn aggregate_plan(
941        &self,
942        output: Option<&TypeSchema>,
943        group_output: bool,
944    ) -> Result<Plan<'static>, Error> {
945        self.request.aggregate_plan(
946            &self.db,
947            E::SCHEMA,
948            output,
949            PlanOutput::Aggregate {
950                grouped: group_output,
951            },
952        )
953    }
954}
955
956impl super::Request<'_> {
957    // Only a plain, bounded request can use entity metadata before planning.
958    // Match every request field so new builder options require an explicit decision.
959    fn is_plain_count(&self) -> bool {
960        matches!(self, Self {
961            predicates,
962            groups,
963            index: None,
964            order: None,
965            order_descending: 0,
966            descending: false,
967            distinct: false,
968            cursor: None,
969            single_result_probe: None,
970            rows: _, work: _, bytes: _, over_limit: _,
971        } if predicates.is_empty() && groups.is_empty() && self.within_limits())
972    }
973
974    fn admit_groups(
975        &self,
976        entity: &EntitySchema,
977        plan: &Plan<'_>,
978        initial: Reducer,
979        summary_sum: Option<ValueSchema>,
980    ) -> Result<Groups, Error> {
981        if summary_sum.is_none() && matches!(self.groups.order, Some(GroupOrder::Summary(..))) {
982            return Err(Error::InvalidQuery);
983        }
984        Ok(Groups {
985            selection: self.groups.admit(entity, &initial, summary_sum)?,
986            summary_sum,
987            mask: plan.projection.ok_or(Error::InvalidQuery)?,
988            initial,
989            rows: BTreeMap::new(),
990            state_bytes: 0,
991        })
992    }
993
994    fn aggregate_plan<M: Memory>(
995        &self,
996        source: &super::QuerySource<'_, M>,
997        entity: &'static EntitySchema,
998        output: Option<&TypeSchema>,
999        kind: PlanOutput,
1000    ) -> Result<Plan<'static>, Error> {
1001        if self.cursor.is_some()
1002            || self.distinct
1003            || ((self.order.is_some() || self.descending)
1004                && self.groups.order != Some(GroupOrder::FirstOccurrence))
1005        {
1006            return Err(Error::InvalidQuery);
1007        }
1008        let db = source.read()?;
1009        db.schema.admits(entity)?;
1010        let mut plan = Plan::admit(
1011            entity,
1012            self,
1013            db.schema.fingerprint(),
1014            db.incarnation,
1015            output.map(super::Projection::Record),
1016            kind,
1017        )?;
1018        if let Some(mask) = plan.projection {
1019            admit_ordered_fields(entity, mask)?;
1020            plan.selected |= mask;
1021        }
1022
1023        Ok(plan)
1024    }
1025}
1026
1027fn scalar_output<R: Value>(reducer: Reducer, limit: usize) -> Result<(Option<R>, usize), Error> {
1028    let Some(bytes) = reducer.finish(false)?.into_value()? else {
1029        return Ok((None, 0));
1030    };
1031    let mut used = 0;
1032    admit_output(bytes.len(), limit, &mut used)?;
1033
1034    Ok((Some(decode_record(&bytes)?), used))
1035}
1036
1037fn group_output<T>(
1038    (groups, page): (Groups, QueryPage<Vec<u8>>),
1039    request: &super::Request<'_>,
1040    decode: fn(&[u8], Completed) -> Result<T, Error>,
1041) -> Result<Aggregate<Vec<T>>, Error> {
1042    let mut output_bytes = 0;
1043    let value = groups
1044        .into_output(request.rows)?
1045        .into_iter()
1046        .map(|(key, result)| {
1047            admit_output(
1048                key.len() + result.encoded_len(),
1049                request.bytes,
1050                &mut output_bytes,
1051            )?;
1052
1053            decode(&key, result)
1054        })
1055        .collect::<Result<_, Error>>()?;
1056
1057    Ok(Aggregate {
1058        value,
1059        examined: page.examined,
1060        fetched: page.fetched,
1061        output_bytes,
1062    })
1063}
1064
1065fn decode_group_count<K: Value>(key: &[u8], result: Completed) -> Result<GroupCount<K>, Error> {
1066    Ok(GroupCount {
1067        key: decode_record(key)?,
1068        count: result.into_count()?,
1069    })
1070}
1071
1072fn decode_group_value<K: Value, R: Value>(
1073    key: &[u8],
1074    result: Completed,
1075) -> Result<GroupValue<K, R>, Error> {
1076    let value = result.into_value()?;
1077
1078    Ok(GroupValue {
1079        key: decode_record(key)?,
1080        value: value.as_deref().map(decode_record).transpose()?,
1081    })
1082}
1083
1084fn decode_record<R: Value>(bytes: &[u8]) -> Result<R, Error> {
1085    let mut reader = Decoder::new(bytes)?;
1086    let value = R::decode_from(&mut reader)?;
1087    reader.finish()?;
1088
1089    Ok(value)
1090}
1091
1092// Closed choices over delivered reducers and one grouping table, not user extensions.
1093pub(super) enum Accumulator<'a> {
1094    // A synchronous threshold can finish on the last required matching row.
1095    Until(&'a mut u64),
1096    Scalar(&'a mut Reducer),
1097    Groups(&'a mut Groups),
1098}
1099impl Accumulator<'_> {
1100    pub(super) fn needs_spans(&self) -> bool {
1101        !matches!(
1102            self,
1103            Self::Until(_)
1104                | Self::Scalar(
1105                    Reducer::Numeric(_)
1106                        | Reducer::Count { presence: None, .. }
1107                        | Reducer::Distinct { .. }
1108                )
1109        )
1110    }
1111
1112    pub(super) fn push(
1113        &mut self,
1114        entity: &EntitySchema,
1115        values: &[IndexValue<'_>],
1116        bytes: &[u8],
1117        spans: &[(u16, u16)],
1118        scratch: &mut Vec<u8>,
1119    ) -> Result<(), Error> {
1120        match self {
1121            Self::Until(remaining) => {
1122                **remaining -= 1;
1123
1124                Ok(())
1125            }
1126            Self::Scalar(state) => {
1127                state.push(entity, values, bytes, spans, scratch, MAX_STATE_BYTES)
1128            }
1129            Self::Groups(state) => state.push(entity, values, bytes, spans, scratch),
1130        }
1131    }
1132}
1133
1134#[derive(Clone)]
1135pub(super) enum Reducer {
1136    Keys(u8),
1137    Numeric(numeric::NumericAggregate),
1138    Distinct {
1139        mask: u32,
1140        seen: DistinctKeys,
1141        key_bytes: usize,
1142    },
1143    Count {
1144        presence: Option<usize>,
1145        total: u64,
1146    },
1147    Extremum {
1148        position: usize,
1149        maximum: bool,
1150        selected: Option<(Vec<u8>, Vec<u8>)>,
1151    },
1152}
1153impl Reducer {
1154    fn distinct(mask: u32) -> Self {
1155        Self::Distinct {
1156            mask,
1157            seen: DistinctKeys::new(),
1158            key_bytes: 0,
1159        }
1160    }
1161
1162    fn extremum(entity: &EntitySchema, mask: u32, maximum: bool) -> Result<Self, Error> {
1163        if mask.count_ones() != 1 {
1164            return Err(Error::InvalidQuery);
1165        }
1166        let position = mask.trailing_zeros() as usize;
1167        if !key::supports(entity.fields[position].value) {
1168            return Err(Error::InvalidQuery);
1169        }
1170
1171        Ok(Self::Extremum {
1172            position,
1173            maximum,
1174            selected: None,
1175        })
1176    }
1177
1178    fn retained_bytes(&self) -> usize {
1179        match self {
1180            Self::Keys(_) => 0,
1181            Self::Numeric(state) => state.retained_bytes(),
1182            Self::Count { .. } => 8,
1183            Self::Distinct { key_bytes, .. } => 8 + key_bytes,
1184            Self::Extremum { selected, .. } => selected
1185                .as_ref()
1186                .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
1187        }
1188    }
1189
1190    fn finish(self, needs_numeric_key: bool) -> Result<Completed, Error> {
1191        match self {
1192            Self::Keys(_) => Ok(Completed::Key),
1193            Self::Count { total, .. } => Ok(Completed::Count(total)),
1194            Self::Distinct { seen, .. } => Ok(Completed::Count(seen.len() as u64)),
1195            Self::Extremum { selected, .. } => Ok(Completed::Value(selected)),
1196            Self::Numeric(state) => state.finish(needs_numeric_key),
1197        }
1198    }
1199
1200    fn push(
1201        &mut self,
1202        entity: &EntitySchema,
1203        values: &[IndexValue<'_>],
1204        bytes: &[u8],
1205        spans: &[(u16, u16)],
1206        scratch: &mut Vec<u8>,
1207        allowance: usize,
1208    ) -> Result<(), Error> {
1209        match self {
1210            Self::Keys(_) => {}
1211            Self::Numeric(state) => state.push(values)?,
1212            Self::Distinct {
1213                mask,
1214                seen,
1215                key_bytes,
1216            } => {
1217                comparison_key(entity, *mask, values, scratch)?;
1218                if let Err(position) =
1219                    seen.binary_search_by(|key| key.as_ref().cmp(scratch.as_slice()))
1220                {
1221                    let size = scratch.len();
1222                    if seen.len() == MAX_DISTINCT_VALUES || 8 + *key_bytes + size > allowance {
1223                        return Err(Error::Limit);
1224                    }
1225                    seen.insert(position, Box::from(scratch.as_slice()));
1226                    *key_bytes += size;
1227                }
1228            }
1229            Self::Count { presence, total } => {
1230                *total += u64::from(presence.is_none_or(|i| bytes[usize::from(spans[i].0)] != 0));
1231            }
1232            Self::Extremum {
1233                position,
1234                maximum,
1235                selected,
1236            } => {
1237                let value = values[*position];
1238                if value == IndexValue::Absent {
1239                    return Ok(());
1240                }
1241                scratch.clear();
1242                value.append_component(entity.fields[*position].optional, scratch);
1243                if scratch.len() > MAX_COMPARISON_KEY {
1244                    return Err(Error::Limit);
1245                }
1246                if selected.as_ref().is_none_or(|(old, _)| {
1247                    if *maximum {
1248                        scratch.as_slice() > old.as_slice()
1249                    } else {
1250                        scratch.as_slice() < old.as_slice()
1251                    }
1252                }) {
1253                    let (start, end) = spans[*position];
1254                    let output = &bytes[usize::from(start)..usize::from(end)];
1255                    if let Some((old_key, old_output)) = selected
1256                        && old_key.len() == scratch.len()
1257                        && old_output.len() == output.len()
1258                    {
1259                        // Equal-sized replacement uses the already charged buffers.
1260                        old_key.copy_from_slice(scratch);
1261                        old_output.copy_from_slice(output);
1262                        return Ok(());
1263                    }
1264                    if scratch.len() + output.len() > allowance {
1265                        return Err(Error::Limit);
1266                    }
1267                    // Copy only a winner, after admitting its replacement charge.
1268                    let key = scratch.as_slice().to_vec();
1269                    let output = output.to_vec();
1270                    if key.capacity() + output.capacity() > allowance {
1271                        return Err(Error::Limit);
1272                    }
1273                    *selected = Some((key, output));
1274                }
1275            }
1276        }
1277
1278        Ok(())
1279    }
1280}
1281
1282// Completed results cannot be advanced. All numeric range checks precede selection.
1283enum Completed {
1284    Summary {
1285        count: u64,
1286        sum: Option<Box<[u8]>>,
1287        average: Option<Box<[u8]>>,
1288        sort_key: Option<Box<[u8]>>,
1289    },
1290    Key,
1291    Count(u64),
1292    Value(Option<(Vec<u8>, Vec<u8>)>),
1293}
1294impl Completed {
1295    fn encoded_len(&self) -> usize {
1296        match self {
1297            Self::Summary { sum, average, .. } => {
1298                8 + sum.as_deref().map_or(0, <[u8]>::len)
1299                    + average.as_deref().map_or(0, <[u8]>::len)
1300            }
1301            Self::Key => 0,
1302            Self::Count(_) => 8,
1303            Self::Value(value) => value.as_ref().map_or(0, |(_, bytes)| bytes.len()),
1304        }
1305    }
1306    // Counts need only eight stack bytes; extrema borrow their retained ordered key.
1307    fn result_key<'a>(&'a self, scratch: &'a mut [u8; 8]) -> Option<&'a [u8]> {
1308        match self {
1309            Self::Summary { sort_key, .. } => sort_key.as_deref(),
1310            Self::Key => None,
1311            Self::Count(total) => {
1312                *scratch = total.to_be_bytes();
1313
1314                Some(scratch)
1315            }
1316            Self::Value(selected) => selected.as_ref().map(|(key, _)| key.as_slice()),
1317        }
1318    }
1319
1320    fn retained_bytes(&self) -> usize {
1321        match self {
1322            Self::Summary { sort_key, .. } => {
1323                self.encoded_len() + sort_key.as_deref().map_or(0, <[u8]>::len)
1324            }
1325            Self::Key => 0,
1326            Self::Count(_) => 8,
1327            Self::Value(value) => value
1328                .as_ref()
1329                .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
1330        }
1331    }
1332
1333    fn into_count(self) -> Result<u64, Error> {
1334        match self {
1335            Self::Count(count) => Ok(count),
1336            _ => Err(Error::Corrupt),
1337        }
1338    }
1339
1340    fn into_value(self) -> Result<Option<Vec<u8>>, Error> {
1341        match self {
1342            Self::Value(value) => Ok(value.map(|(_, bytes)| bytes)),
1343            _ => Err(Error::Corrupt),
1344        }
1345    }
1346}
1347
1348pub(super) struct Groups {
1349    summary_sum: Option<ValueSchema>,
1350    selection: Selection,
1351    mask: u32,
1352    // Never advanced: each new group receives its own empty reducer state.
1353    initial: Reducer,
1354    rows: BTreeMap<Box<[u8]>, (Vec<u8>, Reducer)>,
1355    state_bytes: usize,
1356}
1357impl Groups {
1358    fn max_keys(&self) -> usize {
1359        if matches!(self.initial, Reducer::Keys(_)) {
1360            usize::from(u8::MAX)
1361        } else {
1362            MAX_GROUPS
1363        }
1364    }
1365
1366    // Ordinals are assigned densely on first insertion or while restoring the checkpoint.
1367    fn first_occurrences(&self) -> Result<Vec<&[u8]>, Error> {
1368        let mut ordered = vec![&[][..]; self.rows.len()];
1369        for (bytes, reducer) in self.rows.values() {
1370            let Reducer::Keys(position) = reducer else {
1371                return Err(Error::Corrupt);
1372            };
1373            ordered[usize::from(*position)] = bytes;
1374        }
1375        Ok(ordered)
1376    }
1377
1378    fn into_output(self, limit: usize) -> Result<Vec<(Vec<u8>, Completed)>, Error> {
1379        // Accumulation has completed. Output filtering cannot relax input/state bounds.
1380        let mut state_bytes = self.state_bytes;
1381        let key_order = matches!(
1382            self.selection.order,
1383            GroupOrder::Key | GroupOrder::KeyDescending
1384        );
1385        let bounded_rank = !key_order && limit < self.rows.len();
1386        let compare = |a: &Completed, b: &Completed| {
1387            let (mut sa, mut sb) = ([0; 8], [0; 8]);
1388            let order = match (self.selection.order, a, b) {
1389                (
1390                    GroupOrder::Summary(SummaryMeasure::Count, _),
1391                    Completed::Summary { count: left, .. },
1392                    Completed::Summary { count: right, .. },
1393                ) => left.cmp(right),
1394                _ => a.result_key(&mut sa).cmp(&b.result_key(&mut sb)),
1395            };
1396            if matches!(
1397                self.selection.order,
1398                GroupOrder::AggregateDescending
1399                    | GroupOrder::Summary(_, super::SortDirection::Descending)
1400            ) {
1401                order.reverse()
1402            } else {
1403                order
1404            }
1405        };
1406        let retain = limit.min(self.rows.len());
1407        let mut rows = Vec::with_capacity(retain);
1408        let mut oldest = 0;
1409        let needs_value_key = !self.selection.predicates.is_empty()
1410            || matches!(
1411                self.selection.order,
1412                GroupOrder::AggregateAscending | GroupOrder::AggregateDescending
1413            );
1414        for (record, reducer) in self.rows.into_values() {
1415            let previous = reducer.retained_bytes();
1416            let (result, accepted) = if let Some(sum) = self.summary_sum {
1417                let Reducer::Numeric(state) = reducer else {
1418                    return Err(Error::Corrupt);
1419                };
1420                state.finish_summary(sum, &self.selection)?
1421            } else {
1422                let result = reducer.finish(needs_value_key)?;
1423                let mut scratch = [0; 8];
1424                let key = result.result_key(&mut scratch);
1425                let accepted = self.selection.accepts(|_| key);
1426                (result, accepted)
1427            };
1428            state_bytes = state_bytes - previous + result.retained_bytes();
1429            if state_bytes > MAX_STATE_BYTES {
1430                return Err(Error::Limit);
1431            }
1432            if accepted {
1433                if bounded_rank {
1434                    // Insert after equal values to keep canonical key order across ties.
1435                    let position =
1436                        rows.partition_point(|(_, value)| !compare(value, &result).is_gt());
1437                    if position < retain {
1438                        if rows.len() == retain {
1439                            rows.pop();
1440                        }
1441                        rows.insert(position, (record, result));
1442                    }
1443                } else if rows.len() < retain {
1444                    rows.push((record, result));
1445                } else if self.selection.order == GroupOrder::KeyDescending {
1446                    // The newest qualifying key displaces the smallest retained key.
1447                    rows[oldest] = (record, result);
1448                    oldest = (oldest + 1) % retain;
1449                }
1450            }
1451        }
1452        if self.selection.order == GroupOrder::KeyDescending {
1453            rows.rotate_left(oldest);
1454            rows.reverse();
1455        } else if !key_order && !bounded_rank {
1456            // Stable sorting preserves the map's ascending key order on equal results.
1457            rows.sort_by(|(_, a), (_, b)| compare(a, b));
1458        }
1459
1460        Ok(rows)
1461    }
1462
1463    fn push(
1464        &mut self,
1465        entity: &EntitySchema,
1466        values: &[IndexValue<'_>],
1467        bytes: &[u8],
1468        spans: &[(u16, u16)],
1469        scratch: &mut Vec<u8>,
1470    ) -> Result<(), Error> {
1471        comparison_key(entity, self.mask, values, scratch)?;
1472        let available = MAX_STATE_BYTES - self.state_bytes;
1473        if let Some((_, reducer)) = self.rows.get_mut(scratch.as_slice()) {
1474            let previous = reducer.retained_bytes();
1475            reducer.push(entity, values, bytes, spans, scratch, available + previous)?;
1476            self.state_bytes = self.state_bytes - previous + reducer.retained_bytes();
1477            return Ok(());
1478        }
1479
1480        let count = self.rows.len();
1481        let size = projection_size(spans, self.mask);
1482        let base = scratch.len() + size;
1483        if count == self.max_keys() || base + self.initial.retained_bytes() > available {
1484            return Err(Error::Limit);
1485        }
1486        // The reducer can reuse scratch as soon as the new group's key is owned.
1487        let key = Box::<[u8]>::from(scratch.as_slice());
1488        let mut reducer = self.initial.clone();
1489        if let Reducer::Keys(position) = &mut reducer {
1490            *position = count as u8;
1491        }
1492        reducer.push(entity, values, bytes, spans, scratch, available - base)?;
1493        let output = copy_projection(bytes, spans, self.mask, size);
1494        // Map/set nodes and fixed bookkeeping are independently bounded by the
1495        // group and per-group distinct cardinality caps.
1496        let retained = key.len() + output.capacity() + reducer.retained_bytes();
1497        if retained > available {
1498            return Err(Error::Limit);
1499        }
1500        self.state_bytes += retained;
1501        self.rows.insert(key, (output, reducer));
1502
1503        Ok(())
1504    }
1505}