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