Skip to main content

ic_db/store/query/aggregate/
mod.rs

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