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