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