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