Skip to main content

ic_db/store/query/aggregate/
numeric.rs

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