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(Extremum::Min) })
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(Extremum::Max) })
413    }
414
415    fn extremum<R: Value>(self, kind: Extremum) -> Result<Aggregate<Option<R>>, Error> {
416        let (plan, reducer) = self.extremum_plan::<R>(kind)?;
417
418        self.scalar_value(plan, reducer)
419    }
420
421    fn extremum_plan<R: Value>(&self, kind: Extremum) -> Result<(Plan<'a>, Reducer), Error> {
422        let plan = self.aggregate_plan(Some(R::definition()), false)?;
423        let reducer =
424            Reducer::extremum(E::SCHEMA, plan.projection.ok_or(Error::InvalidQuery)?, kind)?;
425
426        Ok((plan, reducer))
427    }
428
429    fn scalar_value<R: Value>(
430        self,
431        mut plan: Plan<'_>,
432        mut reducer: Reducer,
433    ) -> Result<Aggregate<Option<R>>, Error> {
434        super::order::select_unique_aggregate_path(E::SCHEMA, &self.request, &mut plan)?;
435        let page = self.scan_aggregate(&plan, Accumulator::Scalar(&mut reducer))?;
436        let (value, output_bytes) = scalar_output(reducer, self.request.bytes)?;
437
438        Ok(page.into_aggregate(value, output_bytes))
439    }
440
441    /// Minimum present operand per group. `K` is an exact grouping record; `R`
442    /// is an exact single-field operand record. They may overlap. All-absent
443    /// groups retain `None`; empty input yields no groups. No index is required.
444    /// Groups default to ascending canonical field-name tuple order;
445    /// `filter_groups` and `order_groups` select completed results. `limit` selects
446    /// completed groups, never input rows. Output bytes are the key record plus
447    /// the present winning record; transport option framing is excluded.
448    /// At most 32 groups and 128 KiB of retained keys, records and reducer payloads
449    /// are admitted. Every comparison key is bounded to 4096 bytes. Winner growth
450    /// is charged, and replacement releases the previous winner's charge.
451    /// # Errors
452    /// The projection, work and shape refusals of [`Self::min`] apply. Group or
453    /// retained-state exhaustion returns `Limit`. An oversized output group
454    /// returns `RowTooLarge`; combined output exhaustion returns `Limit`.
455    /// # Panics
456    /// Supplier corruption traps without repair.
457    pub fn group_min<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
458        observe!(query, { self.group_extrema(Extremum::Min) })
459    }
460
461    /// Maximum present operand per group, with the contract of [`Self::group_min`].
462    /// # Errors
463    /// The same projection, work, state, shape and output refusals as grouped minimum.
464    /// # Panics
465    /// Supplier corruption traps without repair.
466    pub fn group_max<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
467        observe!(query, { self.group_extrema(Extremum::Max) })
468    }
469
470    fn group_extrema<K: Value, R: Value>(
471        self,
472        kind: Extremum,
473    ) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
474        let (plan, initial) = self.group_extremum_plan::<K, R>(kind)?;
475
476        self.group_values(plan, initial)
477    }
478
479    fn group_extremum_plan<K: Value, R: Value>(
480        &self,
481        kind: Extremum,
482    ) -> Result<(Plan<'a>, Reducer), Error> {
483        let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
484        let operand = admit_projection(E::SCHEMA, R::definition())?;
485        let initial = Reducer::extremum(E::SCHEMA, operand, kind)?;
486        plan.selected |= operand;
487
488        Ok((plan, initial))
489    }
490
491    fn group_values<K: Value, R: Value>(
492        self,
493        mut plan: Plan<'_>,
494        initial: Reducer,
495    ) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
496        super::order::select_unique_aggregate_path(E::SCHEMA, &self.request, &mut plan)?;
497        group_output(
498            self.grouped(&plan, initial, None)?,
499            &self.request,
500            decode_group_value,
501        )
502    }
503
504    /// Whether at least one row matches, without materializing an entity.
505    /// Can seek a mandatory equality prefix and evaluate remaining filters on its owner rows.
506    /// A bounded list of complete keys can be probed in key order. Each hit is validated.
507    /// Stops after validating the first matching row; later rows are not inspected.
508    /// Returns false only after observing the end of the selected input.
509    /// `limit` does not truncate input. The boolean result occupies one byte.
510    /// # Errors
511    /// Refuses cursors, DISTINCT, explicit ordering and group modifiers, as for
512    /// `count`. If no examined row matches and another candidate remains
513    /// beyond `work_limit`, returns `Limit`.
514    /// Ordinary admission and examined-row integrity errors still apply.
515    /// # Panics
516    /// Supplier corruption traps without repair, as for ordinary query execution.
517    pub fn exists(self) -> Result<Aggregate<bool>, Error> {
518        observe!(query, { Ok(self.validated_count_until(1)?.at_least(1)) })
519    }
520
521    /// Count all matching rows in one synchronous execution. Empty input yields zero.
522    /// Uses maintained cardinality when all rows qualify. Physical index keys can
523    /// answer fully covered index ranges or primary-key comparison ranges. A partially covered
524    /// equality prefix narrows the owner rows checked by the remaining predicates.
525    /// Membership counts can probe distinct complete primary or secondary keys within
526    /// the work budget. A hit requires an owner read only when its filters need row values. Use
527    /// [`Self::count_validated`] to check each visited row and selected index owner.
528    /// `limit` does not limit input; the scalar output occupies eight bytes.
529    /// A scan completes when its last candidate uses the final unit of work. Use `start_count`/`resume_count` for retained work.
530    /// # Errors
531    /// Refuses cursors, DISTINCT, explicit ordering and the ordinary query failures.
532    /// Work exhaustion returns `Limit`, never a partial count. Too few output bytes
533    /// returns `RowTooLarge`.
534    /// # Panics
535    /// Supplier corruption traps without repair, as for ordinary query execution.
536    pub fn count(self) -> Result<Aggregate<u64>, Error> {
537        observe!(query, {
538            if self.request.bytes < 8 {
539                return Err(Error::RowTooLarge);
540            }
541            self.count_until(u64::MAX)
542        })
543    }
544
545    /// Test a minimum match count, stopping as soon as the requested number is proven.
546    /// Uses the same maintained counts and covered keys as `count`.
547    /// Zero is true after admission. The result occupies one byte.
548    /// # Errors
549    /// Returns ordinary count admission errors and `Limit` if work runs out before
550    /// either reaching the threshold or exhausting the input.
551    pub fn has_at_least(self, minimum: u64) -> Result<Aggregate<bool>, Error> {
552        observe!(query, { Ok(self.count_until(minimum)?.at_least(minimum)) })
553    }
554
555    fn count_until(self, stop: u64) -> Result<Aggregate<u64>, Error> {
556        if self.request.is_plain_count() {
557            return self.entity_count();
558        }
559        let mut plan = self.count_plan(None)?;
560        if stop == 0 {
561            return Ok(Aggregate {
562                value: 0,
563                examined: 0,
564                fetched: 0,
565                output_bytes: 8,
566            });
567        }
568        if self.request.index.is_none()
569            && self
570                .request
571                .clauses()
572                .zip(plan.clauses())
573                .all(|(clause, terms)| {
574                    clause.iter().zip(terms).any(|(p, term)| {
575                        p.constant_comparison(E::SCHEMA) == Some(true)
576                            || (term.tests_presence && E::SCHEMA.field_is_required(p.field))
577                    })
578                })
579        {
580            return self.entity_count();
581        }
582        if let Some(count) = probe_members(
583            &self.db,
584            E::SCHEMA,
585            &self.request,
586            &plan,
587            MemberProbe::CountKeys,
588            stop,
589        )? {
590            return Ok(count);
591        }
592        if super::order::select_filtered_path(
593            E::SCHEMA,
594            &self.request,
595            &mut plan,
596            Some(MemberProbe::CountWithRows),
597        )? {
598            return self.count_keys(&plan, stop);
599        }
600        self.count_matching_rows(&plan, MemberProbe::CountWithRows, stop)
601    }
602
603    fn validated_count_until(&self, stop: u64) -> Result<Aggregate<u64>, Error> {
604        let mut plan = self.count_plan(None)?;
605        self.select_aggregate_row_path(&mut plan, Some(MemberProbe::ValidateRows))?;
606
607        self.count_matching_rows(&plan, MemberProbe::ValidateRows, stop)
608    }
609
610    fn count_matching_rows(
611        &self,
612        plan: &Plan<'_>,
613        probe: MemberProbe,
614        stop: u64,
615    ) -> Result<Aggregate<u64>, Error> {
616        if let Some(count) = probe_members(&self.db, E::SCHEMA, &self.request, plan, probe, stop)? {
617            return Ok(count);
618        }
619        let mut remaining = stop;
620        let page = self.scan_aggregate(plan, Accumulator::Until(&mut remaining))?;
621        Ok(page.into_aggregate(stop - remaining, 8))
622    }
623
624    fn entity_count(&self) -> Result<Aggregate<u64>, Error> {
625        Ok(Aggregate {
626            value: self.db.read()?.cardinality::<E>()?,
627            examined: 0,
628            fetched: 0,
629            output_bytes: 8,
630        })
631    }
632
633    /// Count by validating each visited row, including its selected index entry.
634    /// For bounded exact-key lists, each distinct candidate costs one probe,
635    /// including misses. Every hit is checked before returning the count.
636    /// # Errors
637    /// Returns the same admission and resource errors as [`Self::count`], and
638    /// reports corruption encountered during traversal.
639    pub fn count_validated(self) -> Result<Aggregate<u64>, Error> {
640        observe!(query, {
641            if self.request.bytes < 8 {
642                return Err(Error::RowTooLarge);
643            }
644            self.validated_count_until(u64::MAX)
645        })
646    }
647
648    /// Count physical entries in the range selected by `using_index` and its
649    /// leading operands. This reads neither index values nor owner rows. A
650    /// dangling index entry counts as one. Use [`Self::count_validated`] to validate rows.
651    /// Like other scalar counts, the row limit does not truncate the input.
652    /// # Errors
653    /// Requires an explicit index. Row predicates, ordering, cursors, grouping
654    /// and DISTINCT refuse. A range with more entries than the work limit returns
655    /// `Limit`; fewer than eight output bytes returns `RowTooLarge`.
656    /// # Panics
657    /// Malformed supplier storage can trap during traversal.
658    pub fn count_index_entries(self) -> Result<Aggregate<u64>, Error> {
659        observe!(query, {
660            if self.request.index.is_none() || !self.request.predicates.is_empty() {
661                return Err(Error::InvalidQuery);
662            }
663            if self.request.bytes < 8 {
664                return Err(Error::RowTooLarge);
665            }
666            let plan = self.count_plan(None)?;
667
668            self.count_keys(&plan, u64::MAX)
669        })
670    }
671
672    fn count_keys(&self, plan: &Plan<'_>, stop: u64) -> Result<Aggregate<u64>, Error> {
673        let bounds = super::range::bounds(E::SCHEMA, &self.request, plan)?;
674        let mut examined = 0;
675        if let Some(range) = bounds {
676            let db = self.db.read()?;
677            if let Some(key) = super::range::exact_key(&range) {
678                examined = usize::from(db.map.contains_key(key));
679            } else {
680                let keys = db.map.keys_range((range.0.as_ref(), range.1.as_ref()));
681                for _ in keys {
682                    if examined == self.request.work {
683                        return Err(Error::Limit);
684                    }
685                    examined += 1;
686                    if examined as u64 == stop {
687                        break;
688                    }
689                }
690            }
691        }
692
693        Ok(Aggregate {
694            value: examined as u64,
695            examined,
696            fetched: 0,
697            output_bytes: 8,
698        })
699    }
700
701    /// Count present values of a top-level field, including non-scalar fields.
702    /// Empty input and all-absent input yield zero; present empty values count.
703    /// Limits, refusals and corruption traps are the same as [`Self::count`].
704    /// # Errors
705    /// Unknown fields refuse even for empty input. Ordinary count errors apply.
706    /// # Panics
707    /// Supplier corruption traps without repair.
708    pub fn count_field(self, field: &str) -> Result<Aggregate<u64>, Error> {
709        observe!(query, {
710            if self.request.bytes < 8 {
711                return Err(Error::RowTooLarge);
712            }
713            let mut plan = self.count_plan(None)?;
714            self.select_aggregate_row_path(&mut plan, None)?;
715            let reducer = self.count_reducer(Some(field))?;
716
717            self.scalar_count_value(&plan, reducer)
718        })
719    }
720
721    /// Count distinct projected tuples, including absent values. An indexed filter can narrow the input.
722    /// Retain at most 32 distinct comparison keys, each at most 4096 bytes, within
723    /// the shared 128-KiB state bound. No projected records are retained. `limit`
724    /// never truncates this count. The scalar result occupies eight bytes.
725    /// A mandatory literal equality or fixed index prefix excludes that field
726    /// from the comparison key. An empty input still counts zero tuples.
727    /// # Errors
728    /// Ordinary count/projection errors and distinct-state exhaustion refuse.
729    /// # Panics
730    /// Supplier corruption traps without repair.
731    pub fn count_distinct<K: Value>(self) -> Result<Aggregate<u64>, Error> {
732        observe!(query, {
733            if self.request.bytes < 8 {
734                return Err(Error::RowTooLarge);
735            }
736            let mut plan = self.count_plan(Some(K::definition()))?;
737            self.select_aggregate_row_path(&mut plan, None)?;
738            let projected = plan.projection.ok_or(Error::InvalidQuery)?;
739            let fixed = super::distinct::fixed_fields(E::SCHEMA, &self.request, &plan);
740
741            self.scalar_count_value(&plan, Reducer::distinct(projected & !fixed))
742        })
743    }
744
745    fn select_aggregate_row_path(
746        &self,
747        plan: &mut Plan<'a>,
748        probe: Option<MemberProbe>,
749    ) -> Result<(), Error> {
750        if plan.index.is_none() {
751            super::order::select_filtered_path(E::SCHEMA, &self.request, plan, probe)?;
752        }
753
754        Ok(())
755    }
756
757    fn scalar_count_value(
758        self,
759        plan: &Plan<'_>,
760        mut reducer: Reducer,
761    ) -> Result<Aggregate<u64>, Error> {
762        let page = self.scan_aggregate(plan, Accumulator::Scalar(&mut reducer))?;
763
764        Ok(page.into_aggregate(reducer.finish(false)?.into_count()?, 8))
765    }
766
767    /// Count matching rows grouped by an exact named-record projection.
768    /// Keys support ordered scalars/unit enums, including optional absence; no index
769    /// is required. Results default to ascending tuple order in canonical field-name order.
770    /// `filter_groups` and `order_groups` select completed results before output limits.
771    /// `limit` selects the first completed groups (1..=32), never input rows.
772    /// The engine output allowance bounds key-record bytes plus eight count bytes per group.
773    /// Empty input yields no groups. At most 32 groups and 128 KiB of key/output
774    /// state may be retained, independently of the requested output limit;
775    /// each comparison key is capped at 4096 bytes, independently of index-key limits.
776    /// # Errors
777    /// Refuses unsupported key types, cursors, DISTINCT and explicit ordering.
778    /// Work, group or retained-state exhaustion returns `Limit`, never partial groups.
779    /// Completion must be established within `work_limit`; a boundary scan can refuse.
780    /// Ordinary projection/query integrity and byte-limit errors also apply.
781    /// # Panics
782    /// Supplier corruption traps without repair, as for ordinary query execution.
783    pub fn group_count<K: Value>(self) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
784        observe!(query, { self.group_counts(CountInput::Rows) })
785    }
786
787    /// Count present operand values within each projected group. Groups whose
788    /// operands are all absent remain in the output with count zero. The operand
789    /// may be any top-level stored field and need not belong to the group key.
790    /// Bounds and ordering are the same as [`Self::group_count`].
791    /// # Errors
792    /// Unknown operands and ordinary grouped-count errors refuse.
793    /// # Panics
794    /// Supplier corruption traps without repair.
795    pub fn group_count_field<K: Value>(
796        self,
797        field: &str,
798    ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
799        observe!(query, { self.group_counts(CountInput::Field(field)) })
800    }
801
802    /// Count distinct projected `R` tuples within each projected `K` group.
803    /// Absence is a tuple component, as for [`Self::count_distinct`]; an all-absent
804    /// group has one distinct tuple, not zero. Projections may overlap. No index
805    /// is required. Complete input before group filtering/order and output limits.
806    /// Each group's set compares only operand fields that can vary within it.
807    /// Retain at most 32 groups and 32 distinct tuples per group, with one shared
808    /// 128-KiB state allowance and a 4096-byte cap per comparison key.
809    /// # Errors
810    /// Refuses unsupported projections, cursors, DISTINCT and explicit input order.
811    /// Work, cardinality or byte exhaustion returns `Limit`, never partial counts.
812    /// Ordinary grouped-count output and integrity errors apply.
813    /// # Panics
814    /// Supplier corruption traps without repair.
815    pub fn group_count_distinct<K: Value, R: Value>(
816        self,
817    ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
818        observe!(query, {
819            self.group_counts(CountInput::Distinct(R::definition()))
820        })
821    }
822
823    fn group_count_plan<K: Value>(
824        &self,
825        input: CountInput<'_>,
826    ) -> Result<(Plan<'a>, Reducer), Error> {
827        let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
828        let reducer = if let CountInput::Distinct(record) = input {
829            let operand = admit_projection(E::SCHEMA, record)?;
830            admit_ordered_fields(E::SCHEMA, operand)?;
831            plan.selected |= operand;
832            Reducer::distinct(operand)
833        } else {
834            self.count_reducer(input.field())?
835        };
836        Ok((plan, reducer))
837    }
838
839    fn group_counts<K: Value>(
840        self,
841        input: CountInput<'_>,
842    ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
843        let (mut plan, mut reducer) = self.group_count_plan::<K>(input)?;
844        self.select_aggregate_row_path(&mut plan, None)?;
845        if let Reducer::Distinct { mask, .. } = &mut reducer {
846            let grouped = plan.projection.ok_or(Error::InvalidQuery)?;
847            let fixed = super::distinct::fixed_fields(E::SCHEMA, &self.request, &plan);
848            *mask &= !(grouped | fixed);
849        }
850        group_output(
851            self.grouped(&plan, reducer, None)?,
852            &self.request,
853            decode_group_count,
854        )
855    }
856
857    fn count_reducer(&self, field: Option<&str>) -> Result<Reducer, Error> {
858        // Presence needs only the validated tag, not an ordered scalar slot.
859        let presence = field
860            .map(|name| E::SCHEMA.field_position(name).ok_or(Error::InvalidQuery))
861            .transpose()?
862            .filter(|&i| E::SCHEMA.fields[i].optional);
863
864        Ok(Reducer::Count { presence, total: 0 })
865    }
866
867    fn scan_aggregate(
868        &self,
869        plan: &Plan<'_>,
870        accumulator: Accumulator<'_>,
871    ) -> Result<QueryPage<Vec<u8>>, Error> {
872        execute(
873            &self.db.read()?.map,
874            E::SCHEMA,
875            &self.request,
876            plan,
877            Some(accumulator),
878        )
879    }
880
881    fn grouped(
882        &self,
883        plan: &Plan<'_>,
884        initial: Reducer,
885        summary_sum: Option<ValueSchema>,
886    ) -> Result<(Groups, QueryPage<Vec<u8>>), Error> {
887        self.request.groups.admit_start_page()?;
888        let mut groups = self
889            .request
890            .admit_groups(E::SCHEMA, plan, initial, summary_sum)?;
891        let page = self.scan_aggregate(plan, Accumulator::Groups(&mut groups))?;
892
893        Ok((groups, page))
894    }
895
896    fn count_plan(&self, output: Option<&TypeSchema>) -> Result<Plan<'a>, Error> {
897        self.request
898            .aggregate_plan(&self.db, E::SCHEMA, output, PlanOutput::ImmediateCount)
899    }
900
901    fn aggregate_plan(
902        &self,
903        output: Option<&TypeSchema>,
904        group_output: bool,
905    ) -> Result<Plan<'a>, Error> {
906        self.request.aggregate_plan(
907            &self.db,
908            E::SCHEMA,
909            output,
910            PlanOutput::Aggregate {
911                grouped: group_output,
912            },
913        )
914    }
915}
916
917impl<'a> super::Request<'a> {
918    // Only a plain, bounded request can use entity metadata before planning.
919    // Match every request field so new builder options require an explicit decision.
920    fn is_plain_count(&self) -> bool {
921        matches!(self, Self {
922            predicates,
923            groups,
924            index: None,
925            order: None,
926            descending: false,
927            distinct: false,
928            cursor: None,
929            single_result_probe: None,
930            rows: _, work: _, bytes: _, over_limit: _,
931        } if predicates.is_empty() && groups.is_empty() && self.within_limits())
932    }
933
934    fn admit_groups(
935        &self,
936        entity: &EntitySchema,
937        plan: &Plan<'_>,
938        initial: Reducer,
939        summary_sum: Option<ValueSchema>,
940    ) -> Result<Groups, Error> {
941        if summary_sum.is_none() && matches!(self.groups.order, Some(GroupOrder::Summary(..))) {
942            return Err(Error::InvalidQuery);
943        }
944        Ok(Groups {
945            selection: self.groups.admit(entity, &initial, summary_sum)?,
946            summary_sum,
947            mask: plan.projection.ok_or(Error::InvalidQuery)?,
948            initial,
949            rows: BTreeMap::new(),
950            state_bytes: 0,
951        })
952    }
953
954    fn aggregate_plan<M: Memory>(
955        &self,
956        source: &super::QuerySource<'_, M>,
957        entity: &'static EntitySchema,
958        output: Option<&TypeSchema>,
959        kind: PlanOutput,
960    ) -> Result<Plan<'a>, Error> {
961        if self.cursor.is_some()
962            || self.distinct
963            || ((self.order.is_some() || self.descending)
964                && self.groups.order != Some(GroupOrder::FirstOccurrence))
965        {
966            return Err(Error::InvalidQuery);
967        }
968        let db = source.read()?;
969        db.schema.admits(entity)?;
970        let mut plan = Plan::admit(
971            entity,
972            self,
973            db.schema.fingerprint(),
974            db.incarnation,
975            output.map(super::Projection::Record),
976            kind,
977        )?;
978        if let Some(mask) = plan.projection {
979            admit_ordered_fields(entity, mask)?;
980            plan.selected |= mask;
981        }
982
983        Ok(plan)
984    }
985}
986
987fn scalar_output<R: Value>(reducer: Reducer, limit: usize) -> Result<(Option<R>, usize), Error> {
988    let Some(bytes) = reducer.finish(false)?.into_value()? else {
989        return Ok((None, 0));
990    };
991    let mut used = 0;
992    admit_output(bytes.len(), limit, &mut used)?;
993
994    Ok((Some(decode_record(&bytes)?), used))
995}
996
997impl QueryPage<Vec<u8>> {
998    fn into_aggregate<T>(self, value: T, output_bytes: usize) -> Aggregate<T> {
999        Aggregate {
1000            value,
1001            examined: self.examined,
1002            fetched: self.fetched,
1003            output_bytes,
1004        }
1005    }
1006}
1007
1008fn group_output<T>(
1009    (groups, page): (Groups, QueryPage<Vec<u8>>),
1010    request: &super::Request<'_>,
1011    decode: fn(&[u8], Completed) -> Result<T, Error>,
1012) -> Result<Aggregate<Vec<T>>, Error> {
1013    let mut output_bytes = 0;
1014    let value = groups
1015        .into_output(request.rows)?
1016        .into_iter()
1017        .map(|(key, result)| {
1018            admit_output(
1019                key.len() + result.encoded_len(),
1020                request.bytes,
1021                &mut output_bytes,
1022            )?;
1023
1024            decode(&key, result)
1025        })
1026        .collect::<Result<_, Error>>()?;
1027
1028    Ok(page.into_aggregate(value, output_bytes))
1029}
1030
1031fn decode_group_count<K: Value>(key: &[u8], result: Completed) -> Result<GroupCount<K>, Error> {
1032    Ok(GroupCount {
1033        key: decode_record(key)?,
1034        count: result.into_count()?,
1035    })
1036}
1037
1038fn decode_group_value<K: Value, R: Value>(
1039    key: &[u8],
1040    result: Completed,
1041) -> Result<GroupValue<K, R>, Error> {
1042    let value = result.into_value()?;
1043
1044    Ok(GroupValue {
1045        key: decode_record(key)?,
1046        value: value.as_deref().map(decode_record).transpose()?,
1047    })
1048}
1049
1050// Closed choices over delivered reducers and one grouping table, not user extensions.
1051pub(super) enum Accumulator<'a> {
1052    // A synchronous threshold can finish on the last required matching row.
1053    Until(&'a mut u64),
1054    Scalar(&'a mut Reducer),
1055    Groups(&'a mut Groups),
1056}
1057impl Accumulator<'_> {
1058    pub(super) fn needs_spans(&self) -> bool {
1059        !matches!(
1060            self,
1061            Self::Until(_)
1062                | Self::Scalar(
1063                    Reducer::Numeric(_)
1064                        | Reducer::Count { presence: None, .. }
1065                        | Reducer::Distinct { .. }
1066                )
1067        )
1068    }
1069
1070    pub(super) fn push(
1071        &mut self,
1072        entity: &EntitySchema,
1073        values: &[IndexValue<'_>],
1074        bytes: &[u8],
1075        spans: &[(u16, u16)],
1076        scratch: &mut Vec<u8>,
1077    ) -> Result<(), Error> {
1078        match self {
1079            Self::Until(remaining) => {
1080                **remaining -= 1;
1081
1082                Ok(())
1083            }
1084            Self::Scalar(state) => {
1085                state.push(entity, values, bytes, spans, scratch, MAX_STATE_BYTES)
1086            }
1087            Self::Groups(state) => state.push(entity, values, bytes, spans, scratch),
1088        }
1089    }
1090}
1091
1092#[derive(Clone, Copy)]
1093pub(super) enum Extremum {
1094    Min,
1095    Max,
1096}
1097
1098type Winner = (Vec<u8>, Vec<u8>);
1099
1100#[derive(Clone)]
1101pub(super) enum Reducer {
1102    Keys(u8),
1103    Numeric(numeric::NumericAggregate),
1104    Distinct {
1105        mask: u32,
1106        seen: DistinctKeys,
1107        key_bytes: usize,
1108    },
1109    Count {
1110        presence: Option<usize>,
1111        total: u64,
1112    },
1113    Extremum {
1114        position: usize,
1115        kind: Extremum,
1116        selected: Option<Winner>,
1117    },
1118}
1119impl Reducer {
1120    fn distinct(mask: u32) -> Self {
1121        Self::Distinct {
1122            mask,
1123            seen: DistinctKeys::new(),
1124            key_bytes: 0,
1125        }
1126    }
1127
1128    fn extremum(entity: &EntitySchema, mask: u32, kind: Extremum) -> Result<Self, Error> {
1129        if mask.count_ones() != 1 {
1130            return Err(Error::InvalidQuery);
1131        }
1132        let position = mask.trailing_zeros() as usize;
1133        if !key::supports(entity.fields[position].value) {
1134            return Err(Error::InvalidQuery);
1135        }
1136
1137        Ok(Self::Extremum {
1138            position,
1139            kind,
1140            selected: None,
1141        })
1142    }
1143
1144    fn retained_bytes(&self) -> usize {
1145        match self {
1146            Self::Keys(_) => 0,
1147            Self::Numeric(state) => state.retained_bytes(),
1148            Self::Count { .. } => 8,
1149            Self::Distinct { key_bytes, .. } => 8 + key_bytes,
1150            Self::Extremum { selected, .. } => selected
1151                .as_ref()
1152                .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
1153        }
1154    }
1155
1156    fn finish(self, needs_numeric_key: bool) -> Result<Completed, Error> {
1157        match self {
1158            Self::Keys(_) => Ok(Completed::Key),
1159            Self::Count { total, .. } => Ok(Completed::Count(total)),
1160            Self::Distinct { seen, .. } => Ok(Completed::Count(seen.len() as u64)),
1161            Self::Extremum { selected, .. } => Ok(Completed::Value(selected)),
1162            Self::Numeric(state) => state.finish(needs_numeric_key),
1163        }
1164    }
1165
1166    fn push(
1167        &mut self,
1168        entity: &EntitySchema,
1169        values: &[IndexValue<'_>],
1170        bytes: &[u8],
1171        spans: &[(u16, u16)],
1172        scratch: &mut Vec<u8>,
1173        allowance: usize,
1174    ) -> Result<(), Error> {
1175        match self {
1176            Self::Keys(_) => {}
1177            Self::Numeric(state) => state.push(values)?,
1178            Self::Distinct {
1179                mask,
1180                seen,
1181                key_bytes,
1182            } => {
1183                comparison_key(entity, *mask, values, scratch)?;
1184                if let Err(position) =
1185                    seen.binary_search_by(|key| key.as_ref().cmp(scratch.as_slice()))
1186                {
1187                    let size = scratch.len();
1188                    if seen.len() == MAX_DISTINCT_VALUES || 8 + *key_bytes + size > allowance {
1189                        return Err(Error::Limit);
1190                    }
1191                    seen.insert(position, Box::from(scratch.as_slice()));
1192                    *key_bytes += size;
1193                }
1194            }
1195            Self::Count { presence, total } => {
1196                *total += u64::from(presence.is_none_or(|i| bytes[usize::from(spans[i].0)] != 0));
1197            }
1198            Self::Extremum {
1199                position,
1200                kind,
1201                selected,
1202            } => {
1203                let value = values[*position];
1204                if value == IndexValue::Absent {
1205                    return Ok(());
1206                }
1207                scratch.clear();
1208                value.append_component(entity.fields[*position].optional, scratch);
1209                if scratch.len() > MAX_COMPARISON_KEY {
1210                    return Err(Error::Limit);
1211                }
1212                if selected.as_ref().is_none_or(|(old, _)| {
1213                    if matches!(kind, Extremum::Max) {
1214                        scratch.as_slice() > old.as_slice()
1215                    } else {
1216                        scratch.as_slice() < old.as_slice()
1217                    }
1218                }) {
1219                    let (start, end) = spans[*position];
1220                    let output = &bytes[usize::from(start)..usize::from(end)];
1221                    if let Some((old_key, old_output)) = selected
1222                        && old_key.len() == scratch.len()
1223                        && old_output.len() == output.len()
1224                    {
1225                        // Equal-sized replacement uses the already charged buffers.
1226                        old_key.copy_from_slice(scratch);
1227                        old_output.copy_from_slice(output);
1228                        return Ok(());
1229                    }
1230                    if scratch.len() + output.len() > allowance {
1231                        return Err(Error::Limit);
1232                    }
1233                    // Copy only a winner, after admitting its replacement charge.
1234                    let key = scratch.as_slice().to_vec();
1235                    let output = output.to_vec();
1236                    if key.capacity() + output.capacity() > allowance {
1237                        return Err(Error::Limit);
1238                    }
1239                    *selected = Some((key, output));
1240                }
1241            }
1242        }
1243
1244        Ok(())
1245    }
1246}
1247
1248// Completed results cannot be advanced. All numeric range checks precede selection.
1249enum Completed {
1250    Summary {
1251        count: u64,
1252        sum: Option<Box<[u8]>>,
1253        average: Option<Box<[u8]>>,
1254        sort_key: Option<Box<[u8]>>,
1255    },
1256    Key,
1257    Count(u64),
1258    Value(Option<(Vec<u8>, Vec<u8>)>),
1259}
1260impl Completed {
1261    fn encoded_len(&self) -> usize {
1262        match self {
1263            Self::Summary { sum, average, .. } => {
1264                8 + sum.as_deref().map_or(0, <[u8]>::len)
1265                    + average.as_deref().map_or(0, <[u8]>::len)
1266            }
1267            Self::Key => 0,
1268            Self::Count(_) => 8,
1269            Self::Value(value) => value.as_ref().map_or(0, |(_, bytes)| bytes.len()),
1270        }
1271    }
1272    // Counts need only eight stack bytes; extrema borrow their retained ordered key.
1273    fn result_key<'a>(&'a self, scratch: &'a mut [u8; 8]) -> Option<&'a [u8]> {
1274        match self {
1275            Self::Summary { sort_key, .. } => sort_key.as_deref(),
1276            Self::Key => None,
1277            Self::Count(total) => {
1278                *scratch = total.to_be_bytes();
1279
1280                Some(scratch)
1281            }
1282            Self::Value(selected) => selected.as_ref().map(|(key, _)| key.as_slice()),
1283        }
1284    }
1285
1286    fn retained_bytes(&self) -> usize {
1287        match self {
1288            Self::Summary { sort_key, .. } => {
1289                self.encoded_len() + sort_key.as_deref().map_or(0, <[u8]>::len)
1290            }
1291            Self::Key => 0,
1292            Self::Count(_) => 8,
1293            Self::Value(value) => value
1294                .as_ref()
1295                .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
1296        }
1297    }
1298
1299    fn into_count(self) -> Result<u64, Error> {
1300        match self {
1301            Self::Count(count) => Ok(count),
1302            _ => Err(Error::Corrupt),
1303        }
1304    }
1305
1306    fn into_value(self) -> Result<Option<Vec<u8>>, Error> {
1307        match self {
1308            Self::Value(value) => Ok(value.map(|(_, bytes)| bytes)),
1309            _ => Err(Error::Corrupt),
1310        }
1311    }
1312}
1313
1314pub(super) struct Groups {
1315    summary_sum: Option<ValueSchema>,
1316    selection: Selection,
1317    mask: u32,
1318    // Never advanced: each new group receives its own empty reducer state.
1319    initial: Reducer,
1320    rows: BTreeMap<Box<[u8]>, (Vec<u8>, Reducer)>,
1321    state_bytes: usize,
1322}
1323impl Groups {
1324    fn max_keys(&self) -> usize {
1325        if matches!(self.initial, Reducer::Keys(_)) {
1326            usize::from(u8::MAX)
1327        } else {
1328            MAX_GROUPS
1329        }
1330    }
1331
1332    // Ordinals are assigned densely on first insertion or while restoring the checkpoint.
1333    fn first_occurrences(&self) -> Result<Vec<&[u8]>, Error> {
1334        let mut ordered = vec![&[][..]; self.rows.len()];
1335        for (bytes, reducer) in self.rows.values() {
1336            let Reducer::Keys(position) = reducer else {
1337                return Err(Error::Corrupt);
1338            };
1339            ordered[usize::from(*position)] = bytes;
1340        }
1341        Ok(ordered)
1342    }
1343
1344    fn into_output(self, limit: usize) -> Result<Vec<(Vec<u8>, Completed)>, Error> {
1345        // Accumulation has completed. Output filtering cannot relax input/state bounds.
1346        let mut state_bytes = self.state_bytes;
1347        let key_order = matches!(
1348            self.selection.order,
1349            GroupOrder::Key | GroupOrder::KeyDescending
1350        );
1351        let bounded_rank = !key_order && limit < self.rows.len();
1352        let compare = |a: &Completed, b: &Completed| {
1353            let (mut sa, mut sb) = ([0; 8], [0; 8]);
1354            let order = match (self.selection.order, a, b) {
1355                (
1356                    GroupOrder::Summary(SummaryMeasure::Count, _),
1357                    Completed::Summary { count: left, .. },
1358                    Completed::Summary { count: right, .. },
1359                ) => left.cmp(right),
1360                _ => a.result_key(&mut sa).cmp(&b.result_key(&mut sb)),
1361            };
1362            if matches!(
1363                self.selection.order,
1364                GroupOrder::AggregateDescending
1365                    | GroupOrder::Summary(_, super::SortDirection::Descending)
1366            ) {
1367                order.reverse()
1368            } else {
1369                order
1370            }
1371        };
1372        let retain = limit.min(self.rows.len());
1373        let mut rows = Vec::with_capacity(retain);
1374        let mut oldest = 0;
1375        let needs_value_key = !self.selection.predicates.is_empty()
1376            || matches!(
1377                self.selection.order,
1378                GroupOrder::AggregateAscending | GroupOrder::AggregateDescending
1379            );
1380        for (record, reducer) in self.rows.into_values() {
1381            let previous = reducer.retained_bytes();
1382            let (result, accepted) = if let Some(sum) = self.summary_sum {
1383                let Reducer::Numeric(state) = reducer else {
1384                    return Err(Error::Corrupt);
1385                };
1386                state.finish_summary(sum, &self.selection)?
1387            } else {
1388                let result = reducer.finish(needs_value_key)?;
1389                let mut scratch = [0; 8];
1390                let key = result.result_key(&mut scratch);
1391                let accepted = self.selection.accepts(|_| key);
1392                (result, accepted)
1393            };
1394            state_bytes = state_bytes - previous + result.retained_bytes();
1395            if state_bytes > MAX_STATE_BYTES {
1396                return Err(Error::Limit);
1397            }
1398            if accepted {
1399                if bounded_rank {
1400                    // Insert after equal values to keep canonical key order across ties.
1401                    let position =
1402                        rows.partition_point(|(_, value)| !compare(value, &result).is_gt());
1403                    if position < retain {
1404                        if rows.len() == retain {
1405                            rows.pop();
1406                        }
1407                        rows.insert(position, (record, result));
1408                    }
1409                } else if rows.len() < retain {
1410                    rows.push((record, result));
1411                } else if self.selection.order == GroupOrder::KeyDescending {
1412                    // The newest qualifying key displaces the smallest retained key.
1413                    rows[oldest] = (record, result);
1414                    oldest = (oldest + 1) % retain;
1415                }
1416            }
1417        }
1418        if self.selection.order == GroupOrder::KeyDescending {
1419            rows.rotate_left(oldest);
1420            rows.reverse();
1421        } else if !key_order && !bounded_rank {
1422            // Stable sorting preserves the map's ascending key order on equal results.
1423            rows.sort_by(|(_, a), (_, b)| compare(a, b));
1424        }
1425
1426        Ok(rows)
1427    }
1428
1429    fn push(
1430        &mut self,
1431        entity: &EntitySchema,
1432        values: &[IndexValue<'_>],
1433        bytes: &[u8],
1434        spans: &[(u16, u16)],
1435        scratch: &mut Vec<u8>,
1436    ) -> Result<(), Error> {
1437        comparison_key(entity, self.mask, values, scratch)?;
1438        let available = MAX_STATE_BYTES - self.state_bytes;
1439        if let Some((_, reducer)) = self.rows.get_mut(scratch.as_slice()) {
1440            let previous = reducer.retained_bytes();
1441            reducer.push(entity, values, bytes, spans, scratch, available + previous)?;
1442            self.state_bytes = self.state_bytes - previous + reducer.retained_bytes();
1443            return Ok(());
1444        }
1445
1446        let count = self.rows.len();
1447        let size = projection_size(spans, self.mask);
1448        let base = scratch.len() + size;
1449        if count == self.max_keys() || base + self.initial.retained_bytes() > available {
1450            return Err(Error::Limit);
1451        }
1452        // The reducer can reuse scratch as soon as the new group's key is owned.
1453        let key = Box::<[u8]>::from(scratch.as_slice());
1454        let mut reducer = self.initial.clone();
1455        if let Reducer::Keys(position) = &mut reducer {
1456            *position = count as u8;
1457        }
1458        reducer.push(entity, values, bytes, spans, scratch, available - base)?;
1459        let output = copy_projection(bytes, spans, self.mask, size);
1460        // Map/set nodes and fixed bookkeeping are independently bounded by the
1461        // group and per-group distinct cardinality caps.
1462        let retained = key.len() + output.capacity() + reducer.retained_bytes();
1463        if retained > available {
1464            return Err(Error::Limit);
1465        }
1466        self.state_bytes += retained;
1467        self.rows.insert(key, (output, reducer));
1468
1469        Ok(())
1470    }
1471}