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