Skip to main content

ic_db/store/query/aggregate/
mod.rs

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