Skip to main content

ic_db/store/query/aggregate/
numeric.rs

1//! Exact integer, decimal, duration and finite float totals, with rounding at completion.
2
3use super::float_sum::{Binary32Sum, Binary64Sum};
4use super::{
5    super::Plan, Aggregate, Completed, GroupOrder, GroupSummaries, GroupSummary, GroupValue, Query,
6    Reducer, SummaryMeasure,
7};
8use crate::{
9    Decimal, Entity, EntitySchema, Error, FieldType, IndexValue, TypeBody, TypeSchema, Value,
10    ValueSchema, codec::Encoder,
11};
12use ethnum::{I256, U256};
13use ic_storage::Memory;
14
15impl<E: Entity, M: Memory> Query<'_, E, M> {
16    /// Sum one integer, Decimal, Duration or finite float field into a single-field result record with the same field
17    /// name and optionality. Scalar newtype inputs use their declared primitive.
18    /// The result may preserve the exact input newtype. A primitive integer result may widen within
19    /// the same signed/unsigned family. Unsigned results may widen to U256.
20    /// Decimal results preserve the source's declared scale; coefficients accumulate
21    /// exactly in I256 and must fit i128 at completion. No rescaling or rounding.
22    /// Duration totals must fit the unsigned 64-bit millisecond result.
23    /// Float32 and Float64 sum finite values exactly, rounding once to nearest with ties to even.
24    /// Empty/all-absent input returns `None`; present zero returns a record.
25    /// Signed accumulation uses I256, so cancelling prefixes do not cause narrow
26    /// overflow. Unsigned accumulation uses checked U256. The final total must fit
27    /// the declared result width. Integer and Decimal sums retain their exact result types.
28    /// # Errors
29    /// Refuses unsupported/narrower/cross-signedness result shapes, cursors, DISTINCT,
30    /// input ordering and group modifiers. Work exhaustion returns `Limit` without
31    /// a prefix total; numeric overflow returns `ArithmeticOverflow`. Output bytes
32    /// count the completed result record, with `RowTooLarge` on overflow of that budget.
33    /// # Panics
34    /// Supplier corruption traps without repair.
35    pub fn sum<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
36        observe!(query, {
37            let (plan, reducer) = self.numeric_plan::<R>(None, Operation::Sum)?;
38
39            self.scalar_value(plan, reducer)
40        })
41    }
42
43    /// Sum one integer, Decimal, Duration or finite float operand per exact grouping record, retaining absent keys
44    /// and all-absent groups. R selects the same explicit result widening as sum.
45    /// Group predicates use R's result type; e.g. Nat128 totals require u128 operands.
46    /// Complete every group before filtering, ordering and output limits.
47    /// # Errors
48    /// Scalar sum shape/range errors and grouped query work/state/output bounds apply.
49    /// Overflow in any group refuses the whole query, even if that group would be
50    /// filtered out or fall beyond the output limit. Finalization is bounded to
51    /// 32 groups and charged to the retained-state byte cap.
52    /// # Panics
53    /// Supplier corruption traps without repair.
54    pub fn group_sum<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
55        observe!(query, {
56            let (plan, reducer) = self.numeric_plan::<R>(Some(K::definition()), Operation::Sum)?;
57
58            self.group_values(plan, reducer)
59        })
60    }
61
62    /// Average present values into a single-field record with matching name and optionality.
63    /// Duration inputs produce Duration rounded to the nearest millisecond.
64    /// Float inputs preserve their width. Integer and Decimal inputs produce Decimal at the
65    /// declared result scale (0–28). A named result preserves the source newtype.
66    /// Divide the exact total by the present count and round once, nearest with
67    /// ties to even. Empty and all-absent inputs return `None`.
68    /// # Errors
69    /// Refuses unsupported input/result pairs, changed optionality, cursors,
70    /// DISTINCT, input ordering and group modifiers. Work exhaustion returns `Limit`;
71    /// an unrepresentable rounded coefficient returns `ArithmeticOverflow`.
72    /// Output-byte bounds match [`Self::sum`]. No partial average is returned.
73    /// # Panics
74    /// Supplier corruption traps without repair.
75    pub fn avg<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
76        observe!(query, {
77            let (plan, reducer) = self.numeric_plan::<R>(None, Operation::Average)?;
78
79            self.scalar_value(plan, reducer)
80        })
81    }
82
83    /// Average per group using [`Self::avg`]'s result type and rounding contract.
84    /// Finalize all groups before filtering, ordering and output limits; these
85    /// operations compare the rounded results. Retain all-absent groups.
86    /// # Errors
87    /// Scalar average admission/range errors and grouped work/state/output bounds
88    /// apply. Overflow in an excluded group still refuses the whole query.
89    /// # Panics
90    /// Supplier corruption traps without repair.
91    pub fn group_avg<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
92        observe!(query, {
93            let (plan, reducer) =
94                self.numeric_plan::<R>(Some(K::definition()), Operation::Average)?;
95
96            self.group_values(plan, reducer)
97        })
98    }
99
100    /// Compute present count, sum and average for one numeric field in one scan.
101    /// S and A name the same operand and follow the result rules of sum and avg.
102    /// All-absent groups have count zero and two absent results. Supports key order or an explicit summary measure
103    /// in either direction. The row limit applies after every group is checked.
104    /// # Errors
105    /// Refuses unnamed group predicates, unspecified aggregate-value ordering and paging. Ordinary
106    /// grouped numeric type, overflow, work, state and output bounds apply.
107    /// # Panics
108    /// Supplier corruption traps without repair.
109    pub fn group_summary<K: Value, S: Value, A: Value>(
110        self,
111    ) -> Result<GroupSummaries<K, S, A>, Error> {
112        observe!(query, {
113            let (mut plan, initial, sum) = self.summary_plan::<K, S, A>()?;
114            super::super::order::select_unique_aggregate_path(E::SCHEMA, &self.request, &mut plan)?;
115            super::group_output(
116                self.grouped(&plan, initial, Some(sum))?,
117                &self.request,
118                decode_summary,
119            )
120        })
121    }
122
123    pub(super) fn summary_plan<K: Value, S: Value, A: Value>(
124        &self,
125    ) -> Result<(Plan<'static>, Reducer, ValueSchema), Error> {
126        let request = &self.request.groups;
127        let order = request.order.unwrap_or_default();
128        if !matches!(
129            order,
130            GroupOrder::Key | GroupOrder::KeyDescending | GroupOrder::Summary(..)
131        ) {
132            return Err(Error::InvalidQuery);
133        }
134        let (plan, initial) = self.numeric_plan::<A>(Some(K::definition()), Operation::Average)?;
135        let sum = NumericAggregate::admit(E::SCHEMA, S::definition(), Operation::Sum)?;
136        let Reducer::Numeric(average) = &initial else {
137            return Err(Error::Corrupt);
138        };
139        if sum.position != average.position {
140            return Err(Error::InvalidQuery);
141        }
142        Ok((plan, initial, sum.output))
143    }
144
145    // One admission path for synchronous, grouped and retained numeric terminals.
146    pub(super) fn numeric_plan<R: Value>(
147        &self,
148        group: Option<&TypeSchema>,
149        operation: Operation,
150    ) -> Result<(Plan<'static>, Reducer), Error> {
151        let mut plan = self.aggregate_plan(group, group.is_some())?;
152        let state = NumericAggregate::admit(E::SCHEMA, R::definition(), operation)?;
153        plan.selected |= 1 << state.position;
154
155        Ok((plan, Reducer::Numeric(state)))
156    }
157}
158
159pub(super) fn decode_summary<K: Value, S: Value, A: Value>(
160    key: &[u8],
161    result: Completed,
162) -> Result<GroupSummary<K, S, A>, Error> {
163    let Completed::Summary {
164        count,
165        sum,
166        average,
167        ..
168    } = result
169    else {
170        return Err(Error::Corrupt);
171    };
172    Ok(GroupSummary {
173        key: super::decode_record(key)?,
174        count,
175        sum: sum.as_deref().map(super::decode_record).transpose()?,
176        average: average.as_deref().map(super::decode_record).transpose()?,
177    })
178}
179
180#[derive(Clone, Copy)]
181#[repr(u8)]
182pub(super) enum Operation {
183    // Stable job-binding tags; preserve the original sum identity.
184    Sum = 1,
185    Average = 2,
186}
187
188#[derive(Clone)]
189pub(in crate::store::query) struct NumericAggregate {
190    pub(super) position: usize,
191    source_scale: u32,
192    output: ValueSchema,
193    total: Total,
194    count: u64,
195    pub(super) operation: Operation,
196}
197#[derive(Clone)]
198enum Total {
199    Float32(Box<Binary32Sum>),
200    Float64(Box<Binary64Sum>),
201    Signed(I256),
202    Unsigned(U256),
203}
204impl Total {
205    fn integer_zero(signed: bool) -> Self {
206        if signed {
207            Self::Signed(I256::ZERO)
208        } else {
209            Self::Unsigned(U256::ZERO)
210        }
211    }
212}
213
214type EncodedValue = (Vec<u8>, Vec<u8>);
215
216impl NumericAggregate {
217    fn admit(
218        entity: &EntitySchema,
219        output: &TypeSchema,
220        operation: Operation,
221    ) -> Result<Self, Error> {
222        let TypeBody::Record([result]) = output.body else {
223            return Err(Error::InvalidQuery);
224        };
225        let position = entity
226            .field_position(result.name)
227            .ok_or(Error::InvalidQuery)?;
228        let source = &entity.fields[position];
229        if source.optional != result.optional {
230            return Err(Error::InvalidQuery);
231        }
232        let input = crate::key::operand_type(source.value);
233        // A named result keeps the exact stored field contract, as in a projection.
234        if matches!(result.value, FieldType::Named(_)) {
235            super::admit_projection(entity, output)?;
236        }
237        let result_type = crate::key::operand_type(result.value);
238        let source_scale = match input {
239            FieldType::Decimal { scale } => scale,
240            _ => 0,
241        };
242        let total = match (operation, input, result_type) {
243            (_, FieldType::Duration, FieldType::Duration) => Total::Signed(I256::ZERO),
244            (_, FieldType::Float32, FieldType::Float32) => Total::Float32(Box::default()),
245            (_, FieldType::Float64, FieldType::Float64) => Total::Float64(Box::default()),
246            (
247                Operation::Sum,
248                FieldType::Decimal { scale: from },
249                FieldType::Decimal { scale: to },
250            ) if from == to => Total::Signed(I256::ZERO),
251            (
252                Operation::Average,
253                FieldType::Decimal { .. },
254                FieldType::Decimal { scale: 0..=28 },
255            ) => Total::Signed(I256::ZERO),
256            (Operation::Average, source, FieldType::Decimal { scale: 0..=28 }) => {
257                Total::integer_zero(integer(source).ok_or(Error::InvalidQuery)?.0)
258            }
259            (Operation::Average, _, _) => return Err(Error::InvalidQuery),
260            (Operation::Sum, source, result) => {
261                let (signed, bits) = integer(source).ok_or(Error::InvalidQuery)?;
262                let (result_signed, result_bits) = integer(result).ok_or(Error::InvalidQuery)?;
263                if signed != result_signed || bits > result_bits {
264                    return Err(Error::InvalidQuery);
265                }
266                Total::integer_zero(signed)
267            }
268        };
269        Ok(Self {
270            position,
271            source_scale,
272            output: ValueSchema {
273                value: result.value,
274                optional: result.optional,
275            },
276            total,
277            count: 0,
278            operation,
279        })
280    }
281
282    pub(super) fn push(&mut self, values: &[IndexValue<'_>]) -> Result<(), Error> {
283        let value = values[self.position];
284        if value == IndexValue::Absent {
285            return Ok(());
286        }
287        match &mut self.total {
288            Total::Float32(total) => {
289                let IndexValue::Float32(value) = value else {
290                    return Err(Error::Corrupt);
291                };
292                total.add(value);
293            }
294            Total::Float64(total) => {
295                let IndexValue::Float64(value) = value else {
296                    return Err(Error::Corrupt);
297                };
298                total.add(value);
299            }
300            Total::Signed(total) => {
301                let value = match value {
302                    IndexValue::Duration(d) => i128::from(d.as_millis()),
303                    IndexValue::Int8(n) => i128::from(n),
304                    IndexValue::Int16(n) => i128::from(n),
305                    IndexValue::Int32(n) => i128::from(n),
306                    IndexValue::Int64(n) => i128::from(n),
307                    IndexValue::Int128(n) => n,
308                    IndexValue::Decimal(n) => n
309                        .coefficient_at_scale(self.source_scale)
310                        .ok_or(Error::Corrupt)?,
311                    _ => return Err(Error::Corrupt),
312                };
313                // Both synchronous and retained scans bound input counts; sums
314                // remain checked independently of that resource proof.
315                *total = total
316                    .checked_add(I256::from(value))
317                    .ok_or(Error::ArithmeticOverflow)?;
318            }
319            Total::Unsigned(total) => {
320                let value = match value {
321                    IndexValue::Nat8(n) => U256::from(n),
322                    IndexValue::Nat16(n) => U256::from(n),
323                    IndexValue::Nat32(n) => U256::from(n),
324                    IndexValue::Nat64(n) => U256::from(n),
325                    IndexValue::Nat128(n) => U256::from(n),
326                    IndexValue::U256(n) => n.into(),
327                    _ => return Err(Error::Corrupt),
328                };
329                *total = total.checked_add(value).ok_or(Error::ArithmeticOverflow)?;
330            }
331        }
332        self.count = self.count.checked_add(1).ok_or(Error::ArithmeticOverflow)?;
333
334        Ok(())
335    }
336
337    // The job binding supplies admitted type/scale/operation metadata. Store only
338    // the exact accumulator and presence count, never a second schema or value AST.
339    pub(super) fn with_checkpoint<T>(&self, write: impl FnOnce(u64, &[u8]) -> T) -> T {
340        match &self.total {
341            Total::Signed(n) => write(self.count, &n.to_be_bytes()),
342            Total::Unsigned(n) => write(self.count, &n.to_be_bytes()),
343            Total::Float32(sum) => write(self.count, sum.checkpoint().as_flattened()),
344            Total::Float64(sum) => write(self.count, sum.checkpoint().as_flattened()),
345        }
346    }
347
348    pub(super) fn restore(&mut self, count: u64, bytes: &[u8]) -> Result<(), Error> {
349        match &mut self.total {
350            Total::Signed(n) => {
351                *n = I256::from_be_bytes(bytes.try_into().map_err(|_| Error::Corrupt)?)
352            }
353            Total::Unsigned(n) => {
354                *n = U256::from_be_bytes(bytes.try_into().map_err(|_| Error::Corrupt)?)
355            }
356            Total::Float32(sum) => sum.restore(count, bytes)?,
357            Total::Float64(sum) => sum.restore(count, bytes)?,
358        }
359        self.count = count;
360        Ok(())
361    }
362
363    pub(super) fn total_bytes(&self) -> usize {
364        match self.total {
365            Total::Float32(_) => Binary32Sum::BYTES,
366            Total::Float64(_) => Binary64Sum::BYTES,
367            Total::Signed(_) | Total::Unsigned(_) => 32,
368        }
369    }
370
371    pub(super) fn retained_bytes(&self) -> usize {
372        self.total_bytes()
373            + if matches!(self.operation, Operation::Average) {
374                8
375            } else {
376                0
377            }
378    }
379
380    pub(super) fn output(&self) -> ValueSchema {
381        self.output
382    }
383
384    pub(super) fn finish_summary(
385        self,
386        output: ValueSchema,
387        selection: &super::Selection,
388    ) -> Result<(Completed, bool), Error> {
389        let (sum_key, sum) = self
390            .encode_result(
391                output,
392                Operation::Sum,
393                selection.needs_summary_key(SummaryMeasure::Sum),
394            )?
395            .unzip();
396        let (avg_key, average) = self
397            .encode_result(
398                self.output,
399                Operation::Average,
400                selection.needs_summary_key(SummaryMeasure::Average),
401            )?
402            .unzip();
403        let count_key = self.count.to_be_bytes();
404        let accepted = selection.accepts(|measure| match measure {
405            Some(SummaryMeasure::Count) => Some(&count_key),
406            Some(SummaryMeasure::Sum) => sum_key.as_deref(),
407            Some(SummaryMeasure::Average) => avg_key.as_deref(),
408            None => None,
409        });
410        let sort_key = match selection.order {
411            GroupOrder::Summary(SummaryMeasure::Sum, _) => sum_key,
412            GroupOrder::Summary(SummaryMeasure::Average, _) => avg_key,
413            _ => None,
414        };
415        Ok((
416            Completed::Summary {
417                count: self.count,
418                sum: sum.map(Vec::into_boxed_slice),
419                average: average.map(Vec::into_boxed_slice),
420                sort_key: sort_key.map(Vec::into_boxed_slice),
421            },
422            accepted,
423        ))
424    }
425
426    pub(super) fn finish(self, needs_key: bool) -> Result<Completed, Error> {
427        self.encode_result(self.output, self.operation, needs_key)
428            .map(Completed::Value)
429    }
430
431    fn encode_result(
432        &self,
433        schema: ValueSchema,
434        operation: Operation,
435        needs_key: bool,
436    ) -> Result<Option<EncodedValue>, Error> {
437        if self.count == 0 {
438            return Ok(None);
439        }
440        let result_type = crate::key::operand_type(schema.value);
441        let rounded;
442        let total =
443            if let (Operation::Average, FieldType::Decimal { scale }) = (operation, result_type) {
444                let numerator = match self.total {
445                    Total::Float32(_) | Total::Float64(_) => return Err(Error::Corrupt),
446                    Total::Signed(n) => n,
447                    // A nonnegative integer total this large cannot produce a Decimal
448                    // coefficient fitting i128 even after division by the retained
449                    // job's maximum one million inputs (synchronous scans use 512).
450                    Total::Unsigned(n) => n.try_into().map_err(|_| Error::ArithmeticOverflow)?,
451                };
452                rounded = Total::Signed(rounded_average(
453                    numerator,
454                    self.count,
455                    self.source_scale,
456                    scale,
457                )?);
458                &rounded
459            } else {
460                &self.total
461            };
462        let mut output = Encoder::new();
463        if schema.optional {
464            output.boolean(true)?;
465        }
466        // The ordinary owned codec supplies result bytes; checked conversion occurs
467        // only after complete accumulation, never once per input or work chunk.
468        macro_rules! encode {
469            ($method:ident, $variant:ident, $value:expr) => {{
470                let value = $value.try_into().map_err(|_| Error::ArithmeticOverflow)?;
471                output.$method(value)?;
472                IndexValue::$variant(value)
473            }};
474        }
475        let divisor = match operation {
476            Operation::Sum => 1,
477            Operation::Average => self.count,
478        };
479        let value = match (total, result_type) {
480            (Total::Float32(sum), FieldType::Float32) => {
481                let value = sum.finish(divisor)?;
482                output.float32(value)?;
483                IndexValue::Float32(value)
484            }
485            (Total::Float64(sum), FieldType::Float64) => {
486                let value = sum.finish(divisor)?;
487                output.float64(value)?;
488                IndexValue::Float64(value)
489            }
490            (Total::Signed(n), FieldType::Duration) => {
491                let millis = match operation {
492                    Operation::Sum => *n,
493                    Operation::Average => rounded_average(*n, self.count, 0, 0)?,
494                };
495                let value = crate::Duration::from_millis(
496                    millis.try_into().map_err(|_| Error::ArithmeticOverflow)?,
497                );
498                output.duration(value)?;
499                IndexValue::Duration(value)
500            }
501            (Total::Signed(n), FieldType::Int8) => encode!(int8, Int8, *n),
502            (Total::Signed(n), FieldType::Int16) => encode!(int16, Int16, *n),
503            (Total::Signed(n), FieldType::Int32) => encode!(int32, Int32, *n),
504            (Total::Signed(n), FieldType::Int64) => encode!(int64, Int64, *n),
505            (Total::Signed(n), FieldType::Int128) => encode!(int128, Int128, *n),
506            (Total::Signed(n), FieldType::Decimal { scale }) => {
507                let coefficient = (*n).try_into().map_err(|_| Error::ArithmeticOverflow)?;
508                let value = Decimal::try_new(coefficient, scale).ok_or(Error::Corrupt)?;
509                output.decimal(value, scale)?;
510                IndexValue::Decimal(value)
511            }
512            (Total::Unsigned(n), FieldType::Nat8) => encode!(nat8, Nat8, *n),
513            (Total::Unsigned(n), FieldType::Nat16) => encode!(nat16, Nat16, *n),
514            (Total::Unsigned(n), FieldType::Nat32) => encode!(nat32, Nat32, *n),
515            (Total::Unsigned(n), FieldType::Nat64) => encode!(nat64, Nat64, *n),
516            (Total::Unsigned(n), FieldType::Nat128) => encode!(nat128, Nat128, *n),
517            (Total::Unsigned(n), FieldType::U256) => {
518                let value = (*n).into();
519                output.u256(value)?;
520                IndexValue::U256(value)
521            }
522            _ => return Err(Error::Corrupt),
523        };
524        let mut key = Vec::new();
525        if needs_key {
526            value.append_component(schema.optional, &mut key);
527        }
528
529        Ok(Some((key, output.finish())))
530    }
531}
532
533fn rounded_average(
534    total: I256,
535    count: u64,
536    source_scale: u32,
537    result_scale: u32,
538) -> Result<I256, Error> {
539    // One million signed 128-bit inputs plus 28 decimal scale digits fit I256.
540    // For unsigned totals, a scale-up overflow cannot hide a fitting i128 result:
541    // division by at most one million cannot bring that magnitude into range.
542    // The scale-down denominator and twice-remainder also fit comfortably.
543    let factor = I256::from(10_i128.pow(source_scale.abs_diff(result_scale)));
544    let (numerator, denominator) = if result_scale >= source_scale {
545        (
546            total.checked_mul(factor).ok_or(Error::ArithmeticOverflow)?,
547            I256::from(count),
548        )
549    } else {
550        (total, I256::from(count) * factor)
551    };
552    let quotient = numerator / denominator;
553    let twice_remainder = (numerator % denominator).abs() * 2;
554    let round = twice_remainder > denominator
555        || (twice_remainder == denominator && quotient % 2 != I256::ZERO);
556
557    Ok(if round {
558        quotient
559            + if numerator < I256::ZERO {
560                I256::MINUS_ONE
561            } else {
562                I256::ONE
563            }
564    } else {
565        quotient
566    })
567}
568
569fn integer(value: FieldType) -> Option<(bool, u16)> {
570    Some(match value {
571        FieldType::Nat8 => (false, 8),
572        FieldType::Int8 => (true, 8),
573        FieldType::Nat16 => (false, 16),
574        FieldType::Int16 => (true, 16),
575        FieldType::Nat32 => (false, 32),
576        FieldType::Int32 => (true, 32),
577        FieldType::Nat64 => (false, 64),
578        FieldType::Int64 => (true, 64),
579        FieldType::Nat128 => (false, 128),
580        FieldType::Int128 => (true, 128),
581        FieldType::U256 => (false, 256),
582        _ => return None,
583    })
584}