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