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