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<'a, E: Entity, M: Memory> Query<'a, 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<'a>, 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<'a>, 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        if count == 0 && bytes.iter().any(|&b| b != 0) {
350            return Err(Error::Corrupt);
351        }
352        match &mut self.total {
353            Total::Signed(n) => {
354                *n = I256::from_be_bytes(bytes.try_into().map_err(|_| Error::Corrupt)?)
355            }
356            Total::Unsigned(n) => {
357                *n = U256::from_be_bytes(bytes.try_into().map_err(|_| Error::Corrupt)?)
358            }
359            Total::Float32(sum) => sum.restore(count, bytes)?,
360            Total::Float64(sum) => sum.restore(count, bytes)?,
361        }
362        self.count = count;
363        Ok(())
364    }
365
366    pub(super) fn total_bytes(&self) -> usize {
367        match self.total {
368            Total::Float32(_) => Binary32Sum::BYTES,
369            Total::Float64(_) => Binary64Sum::BYTES,
370            Total::Signed(_) | Total::Unsigned(_) => 32,
371        }
372    }
373
374    pub(super) fn retained_bytes(&self) -> usize {
375        self.total_bytes()
376            + if matches!(self.operation, Operation::Average) {
377                8
378            } else {
379                0
380            }
381    }
382
383    pub(super) fn output(&self) -> ValueSchema {
384        self.output
385    }
386
387    pub(super) fn finish_summary(
388        self,
389        output: ValueSchema,
390        selection: &super::Selection,
391    ) -> Result<(Completed, bool), Error> {
392        let (sum_key, sum) = self
393            .encode_result(
394                output,
395                Operation::Sum,
396                selection.needs_summary_key(SummaryMeasure::Sum),
397            )?
398            .unzip();
399        let (avg_key, average) = self
400            .encode_result(
401                self.output,
402                Operation::Average,
403                selection.needs_summary_key(SummaryMeasure::Average),
404            )?
405            .unzip();
406        let count_key = self.count.to_be_bytes();
407        let accepted = selection.accepts(|measure| match measure {
408            Some(SummaryMeasure::Count) => Some(&count_key),
409            Some(SummaryMeasure::Sum) => sum_key.as_deref(),
410            Some(SummaryMeasure::Average) => avg_key.as_deref(),
411            None => None,
412        });
413        let sort_key = match selection.order {
414            GroupOrder::Summary(SummaryMeasure::Sum, _) => sum_key,
415            GroupOrder::Summary(SummaryMeasure::Average, _) => avg_key,
416            _ => None,
417        };
418        Ok((
419            Completed::Summary {
420                count: self.count,
421                sum: sum.map(Vec::into_boxed_slice),
422                average: average.map(Vec::into_boxed_slice),
423                sort_key: sort_key.map(Vec::into_boxed_slice),
424            },
425            accepted,
426        ))
427    }
428
429    pub(super) fn finish(self, needs_key: bool) -> Result<Completed, Error> {
430        self.encode_result(self.output, self.operation, needs_key)
431            .map(Completed::Value)
432    }
433
434    fn encode_result(
435        &self,
436        schema: ValueSchema,
437        operation: Operation,
438        needs_key: bool,
439    ) -> Result<Option<EncodedValue>, Error> {
440        if self.count == 0 {
441            return Ok(None);
442        }
443        let result_type = crate::key::operand_type(schema.value);
444        let rounded;
445        let total =
446            if let (Operation::Average, FieldType::Decimal { scale }) = (operation, result_type) {
447                let numerator = match self.total {
448                    Total::Float32(_) | Total::Float64(_) => return Err(Error::Corrupt),
449                    Total::Signed(n) => n,
450                    // A nonnegative integer total this large cannot produce a Decimal
451                    // coefficient fitting i128 even after division by the retained
452                    // job's maximum one million inputs (synchronous scans use 512).
453                    Total::Unsigned(n) => n.try_into().map_err(|_| Error::ArithmeticOverflow)?,
454                };
455                rounded = Total::Signed(rounded_average(
456                    numerator,
457                    self.count,
458                    self.source_scale,
459                    scale,
460                )?);
461                &rounded
462            } else {
463                &self.total
464            };
465        let mut output = Encoder::new();
466        if schema.optional {
467            output.boolean(true)?;
468        }
469        // The ordinary owned codec supplies result bytes; checked conversion occurs
470        // only after complete accumulation, never once per input or work chunk.
471        macro_rules! encode {
472            ($method:ident, $variant:ident, $value:expr) => {{
473                let value = $value.try_into().map_err(|_| Error::ArithmeticOverflow)?;
474                output.$method(value)?;
475                IndexValue::$variant(value)
476            }};
477        }
478        let divisor = match operation {
479            Operation::Sum => 1,
480            Operation::Average => self.count,
481        };
482        let value = match (total, result_type) {
483            (Total::Float32(sum), FieldType::Float32) => {
484                let value = sum.finish(divisor)?;
485                output.float32(value)?;
486                IndexValue::Float32(value)
487            }
488            (Total::Float64(sum), FieldType::Float64) => {
489                let value = sum.finish(divisor)?;
490                output.float64(value)?;
491                IndexValue::Float64(value)
492            }
493            (Total::Signed(n), FieldType::Duration) => {
494                let millis = match operation {
495                    Operation::Sum => *n,
496                    Operation::Average => rounded_average(*n, self.count, 0, 0)?,
497                };
498                let value = crate::Duration::from_millis(
499                    millis.try_into().map_err(|_| Error::ArithmeticOverflow)?,
500                );
501                output.duration(value)?;
502                IndexValue::Duration(value)
503            }
504            (Total::Signed(n), FieldType::Int8) => encode!(int8, Int8, *n),
505            (Total::Signed(n), FieldType::Int16) => encode!(int16, Int16, *n),
506            (Total::Signed(n), FieldType::Int32) => encode!(int32, Int32, *n),
507            (Total::Signed(n), FieldType::Int64) => encode!(int64, Int64, *n),
508            (Total::Signed(n), FieldType::Int128) => encode!(int128, Int128, *n),
509            (Total::Signed(n), FieldType::Decimal { scale }) => {
510                let coefficient = (*n).try_into().map_err(|_| Error::ArithmeticOverflow)?;
511                let value = Decimal::try_new(coefficient, scale).ok_or(Error::Corrupt)?;
512                output.decimal(value, scale)?;
513                IndexValue::Decimal(value)
514            }
515            (Total::Unsigned(n), FieldType::Nat8) => encode!(nat8, Nat8, *n),
516            (Total::Unsigned(n), FieldType::Nat16) => encode!(nat16, Nat16, *n),
517            (Total::Unsigned(n), FieldType::Nat32) => encode!(nat32, Nat32, *n),
518            (Total::Unsigned(n), FieldType::Nat64) => encode!(nat64, Nat64, *n),
519            (Total::Unsigned(n), FieldType::Nat128) => encode!(nat128, Nat128, *n),
520            (Total::Unsigned(n), FieldType::U256) => {
521                let value = (*n).into();
522                output.u256(value)?;
523                IndexValue::U256(value)
524            }
525            _ => return Err(Error::Corrupt),
526        };
527        let mut key = Vec::new();
528        if needs_key {
529            value.append_component(schema.optional, &mut key);
530        }
531
532        Ok(Some((key, output.finish())))
533    }
534}
535
536fn rounded_average(
537    total: I256,
538    count: u64,
539    source_scale: u32,
540    result_scale: u32,
541) -> Result<I256, Error> {
542    // One million signed 128-bit inputs plus 28 decimal scale digits fit I256.
543    // For unsigned totals, a scale-up overflow cannot hide a fitting i128 result:
544    // division by at most one million cannot bring that magnitude into range.
545    // The scale-down denominator and twice-remainder also fit comfortably.
546    let factor = I256::from(10_i128.pow(source_scale.abs_diff(result_scale)));
547    let (numerator, denominator) = if result_scale >= source_scale {
548        (
549            total.checked_mul(factor).ok_or(Error::ArithmeticOverflow)?,
550            I256::from(count),
551        )
552    } else {
553        (total, I256::from(count) * factor)
554    };
555    let quotient = numerator / denominator;
556    let twice_remainder = (numerator % denominator).abs() * 2;
557    let round = twice_remainder > denominator
558        || (twice_remainder == denominator && quotient % 2 != I256::ZERO);
559
560    Ok(if round {
561        quotient
562            + if numerator < I256::ZERO {
563                I256::MINUS_ONE
564            } else {
565                I256::ONE
566            }
567    } else {
568        quotient
569    })
570}
571
572fn integer(value: FieldType) -> Option<(bool, u16)> {
573    Some(match value {
574        FieldType::Nat8 => (false, 8),
575        FieldType::Int8 => (true, 8),
576        FieldType::Nat16 => (false, 16),
577        FieldType::Int16 => (true, 16),
578        FieldType::Nat32 => (false, 32),
579        FieldType::Int32 => (true, 32),
580        FieldType::Nat64 => (false, 64),
581        FieldType::Int64 => (true, 64),
582        FieldType::Nat128 => (false, 128),
583        FieldType::Int128 => (true, 128),
584        FieldType::U256 => (false, 256),
585        _ => return None,
586    })
587}