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