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