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