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)]
262enum 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)?;
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(E::SCHEMA, &self.request, &mut plan, true)? {
656                return self.count_keys(&plan);
657            }
658            if let Some(count) = probe_members(
659                &self.db,
660                E::SCHEMA,
661                &self.request,
662                &plan,
663                MemberProbe::CountWithRows,
664            )? {
665                return Ok(count);
666            }
667            let reducer = self.count_reducer(None)?;
668
669            self.scalar_count_value(&plan, reducer)
670        })
671    }
672
673    /// Count by validating each visited row, including its selected index entry.
674    /// For bounded exact-key lists, each distinct candidate costs one probe,
675    /// including misses. Every hit is checked before returning the count.
676    /// # Errors
677    /// Returns the same admission and resource errors as [`Self::count`], and
678    /// reports corruption encountered during traversal.
679    pub fn count_validated(self) -> Result<Aggregate<u64>, Error> {
680        observe!(query, { self.scalar_count(None) })
681    }
682
683    /// Count physical entries in the range selected by `using_index` and its
684    /// leading operands. This reads neither index values nor owner rows. A
685    /// dangling index entry counts as one. Use [`Self::count_validated`] to validate rows.
686    /// Like other scalar counts, the row limit does not truncate the input.
687    /// # Errors
688    /// Requires an explicit index. Row predicates, ordering, cursors, grouping
689    /// and DISTINCT refuse. Visiting the inclusive terminal key proves completion,
690    /// even on the last allowed visit. Exhausting the work budget earlier returns
691    /// `Limit`; fewer than eight output bytes returns `RowTooLarge`.
692    /// # Panics
693    /// Malformed supplier storage can trap during traversal.
694    pub fn count_index_entries(self) -> Result<Aggregate<u64>, Error> {
695        observe!(query, {
696            if self.request.index.is_none() || !self.request.predicates.is_empty() {
697                return Err(Error::InvalidQuery);
698            }
699            if self.request.bytes < 8 {
700                return Err(Error::RowTooLarge);
701            }
702            let plan = self.aggregate_plan(None, false)?;
703
704            self.count_keys(&plan)
705        })
706    }
707
708    fn count_keys(&self, plan: &Plan<'_>) -> Result<Aggregate<u64>, Error> {
709        let bounds = super::range::bounds(E::SCHEMA, &self.request, plan)?;
710        let mut examined = 0;
711        if let Some(range) = bounds {
712            let terminal = super::range::terminal_key(&range, false);
713            let db = self.db.read()?;
714            let entries = db.map.range((range.0.as_ref(), range.1.as_ref()));
715            for entry in entries.take(self.request.work) {
716                examined += 1;
717                if examined == self.request.work && terminal.is_none_or(|end| end != entry.key()) {
718                    return Err(Error::Limit);
719                }
720            }
721        }
722
723        Ok(Aggregate {
724            value: examined as u64,
725            examined,
726            fetched: 0,
727            output_bytes: 8,
728        })
729    }
730
731    /// Count present values of a top-level field, including non-scalar fields.
732    /// Empty input and all-absent input yield zero; present empty values count.
733    /// Limits, refusals and corruption traps are the same as [`Self::count`].
734    /// # Errors
735    /// Unknown fields refuse even for empty input. Ordinary count errors apply.
736    /// # Panics
737    /// Supplier corruption traps without repair.
738    pub fn count_field(self, field: &str) -> Result<Aggregate<u64>, Error> {
739        observe!(query, { self.scalar_count(Some(field)) })
740    }
741
742    /// Count distinct projected tuples, including absent values. An indexed filter can narrow the input.
743    /// Retain at most 32 distinct comparison keys, each at most 4096 bytes, within
744    /// the shared 128-KiB state bound. No projected records are retained. `limit`
745    /// never truncates this count. The scalar result occupies eight bytes.
746    /// A mandatory literal equality or fixed index prefix excludes that field
747    /// from the comparison key. An empty input still counts zero tuples.
748    /// # Errors
749    /// Ordinary count/projection errors and distinct-state exhaustion refuse.
750    /// # Panics
751    /// Supplier corruption traps without repair.
752    pub fn count_distinct<K: Value>(self) -> Result<Aggregate<u64>, Error> {
753        observe!(query, {
754            if self.request.bytes < 8 {
755                return Err(Error::RowTooLarge);
756            }
757            let mut plan = self.aggregate_plan(Some(K::definition()), false)?;
758            self.select_aggregate_row_path(&mut plan)?;
759            let projected = plan.projection.ok_or(Error::InvalidQuery)?;
760            let fixed = super::distinct::fixed_fields(E::SCHEMA, &self.request, &plan);
761
762            self.scalar_count_value(&plan, Reducer::distinct(projected & !fixed))
763        })
764    }
765
766    fn select_aggregate_row_path(&self, plan: &mut Plan<'static>) -> Result<(), Error> {
767        if plan.index.is_none() {
768            super::order::select_filtered_path(E::SCHEMA, &self.request, plan, false)?;
769        }
770
771        Ok(())
772    }
773
774    fn scalar_count(self, field: Option<&str>) -> Result<Aggregate<u64>, Error> {
775        if self.request.bytes < 8 {
776            return Err(Error::RowTooLarge);
777        }
778        let mut plan = self.aggregate_plan(None, false)?;
779        self.select_aggregate_row_path(&mut plan)?;
780        if field.is_none()
781            && let Some(count) = probe_members(
782                &self.db,
783                E::SCHEMA,
784                &self.request,
785                &plan,
786                MemberProbe::CountValidated,
787            )?
788        {
789            return Ok(count);
790        }
791        let reducer = self.count_reducer(field)?;
792
793        self.scalar_count_value(&plan, reducer)
794    }
795
796    fn scalar_count_value(
797        self,
798        plan: &Plan<'_>,
799        mut reducer: Reducer,
800    ) -> Result<Aggregate<u64>, Error> {
801        let page = execute(
802            &self.db.read()?.map,
803            E::SCHEMA,
804            &self.request,
805            plan,
806            Some(Accumulator::Scalar(&mut reducer)),
807        )?;
808
809        Ok(Aggregate {
810            value: reducer.finish(false)?.into_count()?,
811            examined: page.examined,
812            fetched: page.fetched,
813            output_bytes: 8,
814        })
815    }
816
817    /// Count matching rows grouped by an exact named-record projection.
818    /// Keys support ordered scalars/unit enums, including optional absence; no index
819    /// is required. Results default to ascending tuple order in canonical field-name order.
820    /// `filter_groups` and `order_groups` select completed results before output limits.
821    /// `limit` selects the first completed groups (1..=32), never input rows.
822    /// The engine output allowance bounds key-record bytes plus eight count bytes per group.
823    /// Empty input yields no groups. At most 32 groups and 128 KiB of key/output
824    /// state may be retained, independently of the requested output limit;
825    /// each comparison key is capped at 4096 bytes, independently of index-key limits.
826    /// # Errors
827    /// Refuses unsupported key types, cursors, DISTINCT and explicit ordering.
828    /// Work, group or retained-state exhaustion returns `Limit`, never partial groups.
829    /// Completion must be established within `work_limit`; a boundary scan can refuse.
830    /// Ordinary projection/query integrity and byte-limit errors also apply.
831    /// # Panics
832    /// Supplier corruption traps without repair, as for ordinary query execution.
833    pub fn group_count<K: Value>(self) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
834        observe!(query, { self.group_counts(None) })
835    }
836
837    /// Count present operand values within each projected group. Groups whose
838    /// operands are all absent remain in the output with count zero. The operand
839    /// may be any top-level stored field and need not belong to the group key.
840    /// Bounds and ordering are the same as [`Self::group_count`].
841    /// # Errors
842    /// Unknown operands and ordinary grouped-count errors refuse.
843    /// # Panics
844    /// Supplier corruption traps without repair.
845    pub fn group_count_field<K: Value>(
846        self,
847        field: &str,
848    ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
849        observe!(query, { self.group_counts(Some(field)) })
850    }
851
852    /// Count distinct projected `R` tuples within each projected `K` group.
853    /// Absence is a tuple component, as for [`Self::count_distinct`]; an all-absent
854    /// group has one distinct tuple, not zero. Projections may overlap. No index
855    /// is required. Complete input before group filtering/order and output limits.
856    /// Each group's set compares only operand fields that can vary within it.
857    /// Retain at most 32 groups and 32 distinct tuples per group, with one shared
858    /// 128-KiB state allowance and a 4096-byte cap per comparison key.
859    /// # Errors
860    /// Refuses unsupported projections, cursors, DISTINCT and explicit input order.
861    /// Work, cardinality or byte exhaustion returns `Limit`, never partial counts.
862    /// Ordinary grouped-count output and integrity errors apply.
863    /// # Panics
864    /// Supplier corruption traps without repair.
865    pub fn group_count_distinct<K: Value, R: Value>(
866        self,
867    ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
868        observe!(query, {
869            let (plan, reducer) = self.group_distinct_plan::<K, R>()?;
870
871            self.group_count_values(plan, reducer)
872        })
873    }
874
875    fn group_distinct_plan<K: Value, R: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
876        let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
877        let operand = admit_projection(E::SCHEMA, R::definition())?;
878        admit_ordered_fields(E::SCHEMA, operand)?;
879        plan.selected |= operand;
880
881        Ok((plan, Reducer::distinct(operand)))
882    }
883
884    fn group_counts<K: Value>(
885        self,
886        field: Option<&str>,
887    ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
888        let plan = self.aggregate_plan(Some(K::definition()), true)?;
889        let reducer = self.count_reducer(field)?;
890
891        self.group_count_values(plan, reducer)
892    }
893
894    fn group_count_values<K: Value>(
895        self,
896        mut plan: Plan<'static>,
897        mut reducer: Reducer,
898    ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
899        self.select_aggregate_row_path(&mut plan)?;
900        if let Reducer::Distinct { mask, .. } = &mut reducer {
901            let grouped = plan.projection.ok_or(Error::InvalidQuery)?;
902            let fixed = super::distinct::fixed_fields(E::SCHEMA, &self.request, &plan);
903            *mask &= !(grouped | fixed);
904        }
905        let (groups, page) = self.grouped(&plan, reducer, None)?;
906        let (value, output_bytes) = group_output(
907            groups,
908            self.request.rows,
909            self.request.bytes,
910            decode_group_count,
911        )?;
912
913        Ok(Aggregate {
914            value,
915            examined: page.examined,
916            fetched: page.fetched,
917            output_bytes,
918        })
919    }
920
921    fn count_reducer(&self, field: Option<&str>) -> Result<Reducer, Error> {
922        // Presence needs only the validated tag, not an ordered scalar slot.
923        let presence = field
924            .map(|name| E::SCHEMA.field_position(name).ok_or(Error::InvalidQuery))
925            .transpose()?
926            .filter(|&i| E::SCHEMA.fields[i].optional);
927
928        Ok(Reducer::Count { presence, total: 0 })
929    }
930
931    fn grouped(
932        &self,
933        plan: &Plan<'_>,
934        initial: Reducer,
935        summary_sum: Option<ValueSchema>,
936    ) -> Result<(Groups, QueryPage<Vec<u8>>), Error> {
937        if self.request.groups.page.is_some() {
938            return Err(Error::InvalidQuery);
939        }
940        let mut groups = self.admit_groups(plan, initial, summary_sum)?;
941        let page = execute(
942            &self.db.read()?.map,
943            E::SCHEMA,
944            &self.request,
945            plan,
946            Some(Accumulator::Groups(&mut groups)),
947        )?;
948
949        Ok((groups, page))
950    }
951
952    fn admit_groups(
953        &self,
954        plan: &Plan<'_>,
955        initial: Reducer,
956        summary_sum: Option<ValueSchema>,
957    ) -> Result<Groups, Error> {
958        if summary_sum.is_none()
959            && matches!(self.request.groups.order, Some(GroupOrder::Summary(..)))
960        {
961            return Err(Error::InvalidQuery);
962        }
963        Ok(Groups {
964            selection: self
965                .request
966                .groups
967                .admit(E::SCHEMA, &initial, summary_sum)?,
968            summary_sum,
969            mask: plan.projection.ok_or(Error::InvalidQuery)?,
970            initial,
971            rows: BTreeMap::new(),
972            state_bytes: 0,
973        })
974    }
975
976    fn aggregate_plan(
977        &self,
978        output: Option<&TypeSchema>,
979        group_output: bool,
980    ) -> Result<Plan<'static>, Error> {
981        if self.request.cursor.is_some()
982            || self.request.distinct
983            || ((self.request.order.is_some() || self.request.descending)
984                && self.request.groups.order != Some(GroupOrder::FirstOccurrence))
985        {
986            return Err(Error::InvalidQuery);
987        }
988        let db = self.db.read()?;
989        db.schema.admits(E::SCHEMA)?;
990        let mut plan = Plan::admit(
991            E::SCHEMA,
992            &self.request,
993            db.schema.fingerprint(),
994            db.incarnation,
995            output,
996            super::PlanOutput::Aggregate {
997                grouped: group_output,
998            },
999        )?;
1000        if let Some(mask) = plan.projection {
1001            admit_ordered_fields(E::SCHEMA, mask)?;
1002            plan.selected |= mask;
1003        }
1004
1005        Ok(plan)
1006    }
1007}
1008
1009fn scalar_output<R: Value>(reducer: Reducer, limit: usize) -> Result<(Option<R>, usize), Error> {
1010    let Some(bytes) = reducer.finish(false)?.into_value()? else {
1011        return Ok((None, 0));
1012    };
1013    let mut used = 0;
1014    admit_output(bytes.len(), limit, &mut used)?;
1015
1016    Ok((Some(decode_record(&bytes)?), used))
1017}
1018
1019fn group_output<T>(
1020    groups: Groups,
1021    rows: usize,
1022    bytes: usize,
1023    decode: fn(&[u8], Completed) -> Result<T, Error>,
1024) -> Result<(Vec<T>, usize), Error> {
1025    let mut output_bytes = 0;
1026    let value = groups
1027        .into_output(rows)?
1028        .into_iter()
1029        .map(|(key, result)| {
1030            admit_output(key.len() + result.encoded_len(), bytes, &mut output_bytes)?;
1031
1032            decode(&key, result)
1033        })
1034        .collect::<Result<_, Error>>()?;
1035
1036    Ok((value, output_bytes))
1037}
1038
1039fn decode_group_count<K: Value>(key: &[u8], result: Completed) -> Result<GroupCount<K>, Error> {
1040    Ok(GroupCount {
1041        key: decode_record(key)?,
1042        count: result.into_count()?,
1043    })
1044}
1045
1046fn decode_group_value<K: Value, R: Value>(
1047    key: &[u8],
1048    result: Completed,
1049) -> Result<GroupValue<K, R>, Error> {
1050    let value = result.into_value()?;
1051
1052    Ok(GroupValue {
1053        key: decode_record(key)?,
1054        value: value.as_deref().map(decode_record).transpose()?,
1055    })
1056}
1057
1058fn decode_record<R: Value>(bytes: &[u8]) -> Result<R, Error> {
1059    let mut reader = Decoder::new(bytes)?;
1060    let value = R::decode_from(&mut reader)?;
1061    reader.finish()?;
1062
1063    Ok(value)
1064}
1065
1066// Closed choices over delivered reducers and one grouping table, not user extensions.
1067pub(super) enum Accumulator<'a> {
1068    // Synchronous existence can complete on the first matching row; no job state.
1069    Exists(&'a mut bool),
1070    Scalar(&'a mut Reducer),
1071    Groups(&'a mut Groups),
1072}
1073impl Accumulator<'_> {
1074    pub(super) fn needs_spans(&self) -> bool {
1075        !matches!(
1076            self,
1077            Self::Exists(_)
1078                | Self::Scalar(
1079                    Reducer::Numeric(_)
1080                        | Reducer::Count { presence: None, .. }
1081                        | Reducer::Distinct { .. }
1082                )
1083        )
1084    }
1085
1086    pub(super) fn push(
1087        &mut self,
1088        entity: &EntitySchema,
1089        values: &[IndexValue<'_>],
1090        bytes: &[u8],
1091        spans: &[(u16, u16)],
1092        scratch: &mut Vec<u8>,
1093    ) -> Result<(), Error> {
1094        match self {
1095            Self::Exists(found) => {
1096                **found = true;
1097
1098                Ok(())
1099            }
1100            Self::Scalar(state) => {
1101                state.push(entity, values, bytes, spans, scratch, MAX_STATE_BYTES)
1102            }
1103            Self::Groups(state) => state.push(entity, values, bytes, spans, scratch),
1104        }
1105    }
1106}
1107
1108#[derive(Clone)]
1109pub(super) enum Reducer {
1110    Keys(u8),
1111    Numeric(numeric::NumericAggregate),
1112    Distinct {
1113        mask: u16,
1114        seen: DistinctKeys,
1115        key_bytes: usize,
1116    },
1117    Count {
1118        presence: Option<usize>,
1119        total: u64,
1120    },
1121    Extremum {
1122        position: usize,
1123        maximum: bool,
1124        selected: Option<(Vec<u8>, Vec<u8>)>,
1125    },
1126}
1127impl Reducer {
1128    fn distinct(mask: u16) -> Self {
1129        Self::Distinct {
1130            mask,
1131            seen: DistinctKeys::new(),
1132            key_bytes: 0,
1133        }
1134    }
1135
1136    fn extremum(entity: &EntitySchema, mask: u16, maximum: bool) -> Result<Self, Error> {
1137        if mask.count_ones() != 1 {
1138            return Err(Error::InvalidQuery);
1139        }
1140        let position = mask.trailing_zeros() as usize;
1141        if !key::supports(entity.fields[position].value) {
1142            return Err(Error::InvalidQuery);
1143        }
1144
1145        Ok(Self::Extremum {
1146            position,
1147            maximum,
1148            selected: None,
1149        })
1150    }
1151
1152    fn retained_bytes(&self) -> usize {
1153        match self {
1154            Self::Keys(_) => 0,
1155            Self::Numeric(state) => state.retained_bytes(),
1156            Self::Count { .. } => 8,
1157            Self::Distinct { key_bytes, .. } => 8 + key_bytes,
1158            Self::Extremum { selected, .. } => selected
1159                .as_ref()
1160                .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
1161        }
1162    }
1163
1164    fn finish(self, needs_numeric_key: bool) -> Result<Completed, Error> {
1165        match self {
1166            Self::Keys(_) => Ok(Completed::Key),
1167            Self::Count { total, .. } => Ok(Completed::Count(total)),
1168            Self::Distinct { seen, .. } => Ok(Completed::Count(seen.len() as u64)),
1169            Self::Extremum { selected, .. } => Ok(Completed::Value(selected)),
1170            Self::Numeric(state) => state.finish(needs_numeric_key),
1171        }
1172    }
1173
1174    fn push(
1175        &mut self,
1176        entity: &EntitySchema,
1177        values: &[IndexValue<'_>],
1178        bytes: &[u8],
1179        spans: &[(u16, u16)],
1180        scratch: &mut Vec<u8>,
1181        allowance: usize,
1182    ) -> Result<(), Error> {
1183        match self {
1184            Self::Keys(_) => {}
1185            Self::Numeric(state) => state.push(values)?,
1186            Self::Distinct {
1187                mask,
1188                seen,
1189                key_bytes,
1190            } => {
1191                comparison_key(entity, *mask, values, scratch)?;
1192                if let Err(position) =
1193                    seen.binary_search_by(|key| key.as_ref().cmp(scratch.as_slice()))
1194                {
1195                    let size = scratch.len();
1196                    if seen.len() == MAX_DISTINCT_VALUES || 8 + *key_bytes + size > allowance {
1197                        return Err(Error::Limit);
1198                    }
1199                    seen.insert(position, Box::from(scratch.as_slice()));
1200                    *key_bytes += size;
1201                }
1202            }
1203            Self::Count { presence, total } => {
1204                *total += u64::from(presence.is_none_or(|i| bytes[usize::from(spans[i].0)] != 0));
1205            }
1206            Self::Extremum {
1207                position,
1208                maximum,
1209                selected,
1210            } => {
1211                let value = values[*position];
1212                if value == IndexValue::Absent {
1213                    return Ok(());
1214                }
1215                scratch.clear();
1216                value.append_component(entity.fields[*position].optional, scratch);
1217                if scratch.len() > MAX_COMPARISON_KEY {
1218                    return Err(Error::Limit);
1219                }
1220                if selected.as_ref().is_none_or(|(old, _)| {
1221                    if *maximum {
1222                        scratch.as_slice() > old.as_slice()
1223                    } else {
1224                        scratch.as_slice() < old.as_slice()
1225                    }
1226                }) {
1227                    let (start, end) = spans[*position];
1228                    let output = &bytes[usize::from(start)..usize::from(end)];
1229                    if let Some((old_key, old_output)) = selected
1230                        && old_key.len() == scratch.len()
1231                        && old_output.len() == output.len()
1232                    {
1233                        // Equal-sized replacement uses the already charged buffers.
1234                        old_key.copy_from_slice(scratch);
1235                        old_output.copy_from_slice(output);
1236                        return Ok(());
1237                    }
1238                    if scratch.len() + output.len() > allowance {
1239                        return Err(Error::Limit);
1240                    }
1241                    // Copy only a winner, after admitting its replacement charge.
1242                    let key = scratch.as_slice().to_vec();
1243                    let output = output.to_vec();
1244                    if key.capacity() + output.capacity() > allowance {
1245                        return Err(Error::Limit);
1246                    }
1247                    *selected = Some((key, output));
1248                }
1249            }
1250        }
1251
1252        Ok(())
1253    }
1254}
1255
1256// Completed results cannot be advanced. All numeric range checks precede selection.
1257enum Completed {
1258    Summary {
1259        count: u64,
1260        sum: Option<Box<[u8]>>,
1261        average: Option<Box<[u8]>>,
1262        sort_key: Option<Box<[u8]>>,
1263    },
1264    Key,
1265    Count(u64),
1266    Value(Option<(Vec<u8>, Vec<u8>)>),
1267}
1268impl Completed {
1269    fn encoded_len(&self) -> usize {
1270        match self {
1271            Self::Summary { sum, average, .. } => {
1272                8 + sum.as_deref().map_or(0, <[u8]>::len)
1273                    + average.as_deref().map_or(0, <[u8]>::len)
1274            }
1275            Self::Key => 0,
1276            Self::Count(_) => 8,
1277            Self::Value(value) => value.as_ref().map_or(0, |(_, bytes)| bytes.len()),
1278        }
1279    }
1280    // Counts need only eight stack bytes; extrema borrow their retained ordered key.
1281    fn result_key<'a>(&'a self, scratch: &'a mut [u8; 8]) -> Option<&'a [u8]> {
1282        match self {
1283            Self::Summary { sort_key, .. } => sort_key.as_deref(),
1284            Self::Key => None,
1285            Self::Count(total) => {
1286                *scratch = total.to_be_bytes();
1287
1288                Some(scratch)
1289            }
1290            Self::Value(selected) => selected.as_ref().map(|(key, _)| key.as_slice()),
1291        }
1292    }
1293
1294    fn retained_bytes(&self) -> usize {
1295        match self {
1296            Self::Summary { sort_key, .. } => {
1297                self.encoded_len() + sort_key.as_deref().map_or(0, <[u8]>::len)
1298            }
1299            Self::Key => 0,
1300            Self::Count(_) => 8,
1301            Self::Value(value) => value
1302                .as_ref()
1303                .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
1304        }
1305    }
1306
1307    fn into_count(self) -> Result<u64, Error> {
1308        match self {
1309            Self::Count(count) => Ok(count),
1310            _ => Err(Error::Corrupt),
1311        }
1312    }
1313
1314    fn into_value(self) -> Result<Option<Vec<u8>>, Error> {
1315        match self {
1316            Self::Value(value) => Ok(value.map(|(_, bytes)| bytes)),
1317            _ => Err(Error::Corrupt),
1318        }
1319    }
1320}
1321
1322pub(super) struct Groups {
1323    summary_sum: Option<ValueSchema>,
1324    selection: Selection,
1325    mask: u16,
1326    // Never advanced: each new group receives its own empty reducer state.
1327    initial: Reducer,
1328    rows: BTreeMap<Box<[u8]>, (Vec<u8>, Reducer)>,
1329    state_bytes: usize,
1330}
1331impl Groups {
1332    fn max_keys(&self) -> usize {
1333        if matches!(self.initial, Reducer::Keys(_)) {
1334            usize::from(u8::MAX)
1335        } else {
1336            MAX_GROUPS
1337        }
1338    }
1339
1340    // Ordinals are assigned densely on first insertion or while restoring the checkpoint.
1341    fn first_occurrences(&self) -> Result<Vec<&[u8]>, Error> {
1342        let mut ordered = vec![&[][..]; self.rows.len()];
1343        for (bytes, reducer) in self.rows.values() {
1344            let Reducer::Keys(position) = reducer else {
1345                return Err(Error::Corrupt);
1346            };
1347            ordered[usize::from(*position)] = bytes;
1348        }
1349        Ok(ordered)
1350    }
1351
1352    fn into_output(self, limit: usize) -> Result<Vec<(Vec<u8>, Completed)>, Error> {
1353        // Accumulation has completed. Output filtering cannot relax input/state bounds.
1354        let mut state_bytes = self.state_bytes;
1355        let key_order = matches!(
1356            self.selection.order,
1357            GroupOrder::Key | GroupOrder::KeyDescending
1358        );
1359        let bounded_rank = !key_order && limit < self.rows.len();
1360        let compare = |a: &Completed, b: &Completed| {
1361            let (mut sa, mut sb) = ([0; 8], [0; 8]);
1362            let order = match (self.selection.order, a, b) {
1363                (
1364                    GroupOrder::Summary(SummaryMeasure::Count, _),
1365                    Completed::Summary { count: left, .. },
1366                    Completed::Summary { count: right, .. },
1367                ) => left.cmp(right),
1368                _ => a.result_key(&mut sa).cmp(&b.result_key(&mut sb)),
1369            };
1370            if matches!(
1371                self.selection.order,
1372                GroupOrder::AggregateDescending
1373                    | GroupOrder::Summary(_, super::SortDirection::Descending)
1374            ) {
1375                order.reverse()
1376            } else {
1377                order
1378            }
1379        };
1380        let retain = limit.min(self.rows.len());
1381        let mut rows = Vec::with_capacity(retain);
1382        let mut oldest = 0;
1383        let needs_value_key = !self.selection.predicates.is_empty()
1384            || matches!(
1385                self.selection.order,
1386                GroupOrder::AggregateAscending | GroupOrder::AggregateDescending
1387            );
1388        for (record, reducer) in self.rows.into_values() {
1389            let previous = reducer.retained_bytes();
1390            let (result, accepted) = if let Some(sum) = self.summary_sum {
1391                let Reducer::Numeric(state) = reducer else {
1392                    return Err(Error::Corrupt);
1393                };
1394                state.finish_summary(sum, &self.selection)?
1395            } else {
1396                let result = reducer.finish(needs_value_key)?;
1397                let mut scratch = [0; 8];
1398                let key = result.result_key(&mut scratch);
1399                let accepted = self.selection.accepts(|_| key);
1400                (result, accepted)
1401            };
1402            state_bytes = state_bytes - previous + result.retained_bytes();
1403            if state_bytes > MAX_STATE_BYTES {
1404                return Err(Error::Limit);
1405            }
1406            if accepted {
1407                if bounded_rank {
1408                    // Insert after equal values to keep canonical key order across ties.
1409                    let position =
1410                        rows.partition_point(|(_, value)| !compare(value, &result).is_gt());
1411                    if position < retain {
1412                        if rows.len() == retain {
1413                            rows.pop();
1414                        }
1415                        rows.insert(position, (record, result));
1416                    }
1417                } else if rows.len() < retain {
1418                    rows.push((record, result));
1419                } else if self.selection.order == GroupOrder::KeyDescending {
1420                    // The newest qualifying key displaces the smallest retained key.
1421                    rows[oldest] = (record, result);
1422                    oldest = (oldest + 1) % retain;
1423                }
1424            }
1425        }
1426        if self.selection.order == GroupOrder::KeyDescending {
1427            rows.rotate_left(oldest);
1428            rows.reverse();
1429        } else if !key_order && !bounded_rank {
1430            // Stable sorting preserves the map's ascending key order on equal results.
1431            rows.sort_by(|(_, a), (_, b)| compare(a, b));
1432        }
1433
1434        Ok(rows)
1435    }
1436
1437    fn push(
1438        &mut self,
1439        entity: &EntitySchema,
1440        values: &[IndexValue<'_>],
1441        bytes: &[u8],
1442        spans: &[(u16, u16)],
1443        scratch: &mut Vec<u8>,
1444    ) -> Result<(), Error> {
1445        comparison_key(entity, self.mask, values, scratch)?;
1446        let available = MAX_STATE_BYTES - self.state_bytes;
1447        if let Some((_, reducer)) = self.rows.get_mut(scratch.as_slice()) {
1448            let previous = reducer.retained_bytes();
1449            reducer.push(entity, values, bytes, spans, scratch, available + previous)?;
1450            self.state_bytes = self.state_bytes - previous + reducer.retained_bytes();
1451            return Ok(());
1452        }
1453
1454        let count = self.rows.len();
1455        let size = projection_size(spans, self.mask);
1456        let base = scratch.len() + size;
1457        if count == self.max_keys() || base + self.initial.retained_bytes() > available {
1458            return Err(Error::Limit);
1459        }
1460        // The reducer can reuse scratch as soon as the new group's key is owned.
1461        let key = Box::<[u8]>::from(scratch.as_slice());
1462        let mut reducer = self.initial.clone();
1463        if let Reducer::Keys(position) = &mut reducer {
1464            *position = count as u8;
1465        }
1466        reducer.push(entity, values, bytes, spans, scratch, available - base)?;
1467        let output = copy_projection(bytes, spans, self.mask, size);
1468        // Map/set nodes and fixed bookkeeping are independently bounded by the
1469        // group and per-group distinct cardinality caps.
1470        let retained = key.len() + output.capacity() + reducer.retained_bytes();
1471        if retained > available {
1472            return Err(Error::Limit);
1473        }
1474        self.state_bytes += retained;
1475        self.rows.insert(key, (output, reducer));
1476
1477        Ok(())
1478    }
1479}