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