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