Skip to main content

ic_db/store/query/aggregate/
numeric.rs

1//! Integer/decimal sums and averages over one exact total, without numeric coercion.
2
3use super::{super::Plan, Aggregate, Completed, GroupValue, Query, Reducer};
4use crate::{
5    Decimal, Entity, EntitySchema, Error, FieldType, IndexValue, TypeBody, TypeSchema, U256, Value,
6    ValueSchema, codec::Encoder,
7};
8use ethnum::I256;
9use ic_storage::Memory;
10
11impl<E: Entity, M: Memory> Query<'_, E, M> {
12    /// Sum one integer or Decimal field into a single-field result record with the same field
13    /// name and optionality. Scalar newtype inputs use their declared primitive.
14    /// The result may preserve the exact input newtype. A primitive integer result may widen within
15    /// the same signed/unsigned family. Unsigned results may widen to U256.
16    /// Decimal results preserve the source's declared scale; coefficients accumulate
17    /// exactly in I256 and must fit i128 at completion. No rescaling or rounding.
18    /// Empty/all-absent input returns `None`; present zero returns a record.
19    /// Signed accumulation uses I256, so cancelling prefixes do not cause narrow
20    /// overflow. Unsigned accumulation uses checked U256. The final total must fit
21    /// the declared result width. No decimal/float conversion or rounding occurs.
22    /// # Errors
23    /// Refuses unsupported/narrower/cross-signedness result shapes, cursors, DISTINCT,
24    /// input ordering and group modifiers. Work exhaustion returns `Limit` without
25    /// a prefix total; numeric overflow returns `ArithmeticOverflow`. Output bytes
26    /// count the completed result record, with `RowTooLarge` on overflow of that budget.
27    /// # Panics
28    /// Supplier corruption traps without repair.
29    pub fn sum<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
30        let (plan, reducer) = self.numeric_plan::<R>(None, Operation::Sum)?;
31
32        self.scalar_value(&plan, reducer)
33    }
34
35    /// Sum one integer or Decimal operand per exact grouping record, retaining absent keys
36    /// and all-absent groups. R selects the same explicit result widening as sum.
37    /// Group predicates use R's result type; e.g. Nat128 totals require u128 operands.
38    /// Complete every group before filtering, ordering and output limits.
39    /// # Errors
40    /// Scalar sum shape/range errors and grouped query work/state/output bounds apply.
41    /// Overflow in any group refuses the whole query, even if that group would be
42    /// filtered out or fall beyond the output limit. Finalization is bounded to
43    /// 32 groups and charged to the retained-state byte cap.
44    /// # Panics
45    /// Supplier corruption traps without repair.
46    pub fn group_sum<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
47        let (plan, reducer) = self.numeric_plan::<R>(Some(K::definition()), Operation::Sum)?;
48
49        self.group_values(&plan, reducer)
50    }
51
52    /// Average an integer or Decimal field (including a scalar newtype) into a single-field Decimal record.
53    /// Preserve the field name and optionality. A primitive Decimal selects scale 0–28;
54    /// a Decimal newtype result preserves the exact input newtype and its scale.
55    /// Ignore absent operands, returning `None` for empty/all-absent input.
56    /// Divide the exact total by the present count once, rounding to nearest with
57    /// ties to even at the result scale. No floating-point conversion or scale fallback.
58    /// # Errors
59    /// Refuses nonnumeric inputs, non-Decimal results, changed optionality, cursors,
60    /// DISTINCT, input ordering and group modifiers. Work exhaustion returns `Limit`;
61    /// an unrepresentable rounded coefficient returns `ArithmeticOverflow`.
62    /// Output-byte bounds match [`Self::sum`]. No partial average is returned.
63    /// # Panics
64    /// Supplier corruption traps without repair.
65    pub fn avg<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
66        let (plan, reducer) = self.numeric_plan::<R>(None, Operation::Average)?;
67
68        self.scalar_value(&plan, reducer)
69    }
70
71    /// Average per group using [`Self::avg`]'s Decimal scale and rounding contract.
72    /// Finalize all groups before filtering, ordering and output limits; these
73    /// operations compare the rounded Decimal results. Retain all-absent groups.
74    /// # Errors
75    /// Scalar average admission/range errors and grouped work/state/output bounds
76    /// apply. Overflow in an excluded group still refuses the whole query.
77    /// # Panics
78    /// Supplier corruption traps without repair.
79    pub fn group_avg<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
80        let (plan, reducer) = self.numeric_plan::<R>(Some(K::definition()), Operation::Average)?;
81
82        self.group_values(&plan, reducer)
83    }
84
85    // One admission path for synchronous, grouped and retained numeric terminals.
86    pub(super) fn numeric_plan<R: Value>(
87        &self,
88        group: Option<&TypeSchema>,
89        operation: Operation,
90    ) -> Result<(Plan<'static>, Reducer), Error> {
91        let mut plan = self.aggregate_plan(group, group.is_some())?;
92        let state = NumericAggregate::admit(E::SCHEMA, R::definition(), operation)?;
93        plan.selected |= 1 << state.position;
94
95        Ok((plan, Reducer::Numeric(state)))
96    }
97}
98
99#[derive(Clone, Copy)]
100#[repr(u8)]
101pub(super) enum Operation {
102    // Stable job-binding tags; preserve the original sum identity.
103    Sum = 1,
104    Average = 2,
105}
106
107#[derive(Clone)]
108pub(in crate::store::query) struct NumericAggregate {
109    pub(super) position: usize,
110    source_scale: u32,
111    output: ValueSchema,
112    total: Total,
113    count: u64,
114    pub(super) operation: Operation,
115}
116#[derive(Clone)]
117enum Total {
118    Signed(I256),
119    Unsigned(U256),
120}
121impl NumericAggregate {
122    fn admit(
123        entity: &EntitySchema,
124        output: &TypeSchema,
125        operation: Operation,
126    ) -> Result<Self, Error> {
127        let TypeBody::Record([result]) = output.body else {
128            return Err(Error::InvalidQuery);
129        };
130        let position = entity
131            .field_position(result.name)
132            .ok_or(Error::InvalidQuery)?;
133        let source = &entity.fields[position];
134        if source.optional != result.optional {
135            return Err(Error::InvalidQuery);
136        }
137        let input = crate::key::operand_type(source.value);
138        // A named result keeps the exact stored field contract, as in a projection.
139        if matches!(result.value, FieldType::Named(_)) {
140            super::admit_projection(entity, output)?;
141        }
142        let result_type = crate::key::operand_type(result.value);
143        let source_scale = match input {
144            FieldType::Decimal { scale } => scale,
145            _ => 0,
146        };
147        let signed = if matches!(operation, Operation::Average) {
148            if !matches!(result_type, FieldType::Decimal { scale: 0..=28 }) {
149                return Err(Error::InvalidQuery);
150            }
151
152            match input {
153                FieldType::Decimal { .. } => true,
154                value => integer(value).ok_or(Error::InvalidQuery)?.0,
155            }
156        } else {
157            match (input, result_type) {
158                (FieldType::Decimal { scale: source }, FieldType::Decimal { scale: result })
159                    if source == result =>
160                {
161                    true
162                }
163                (source, result) => {
164                    let (signed, bits) = integer(source).ok_or(Error::InvalidQuery)?;
165                    let (result_signed, result_bits) =
166                        integer(result).ok_or(Error::InvalidQuery)?;
167                    if signed != result_signed || bits > result_bits {
168                        return Err(Error::InvalidQuery);
169                    }
170
171                    signed
172                }
173            }
174        };
175
176        Ok(Self {
177            position,
178            source_scale,
179            output: ValueSchema {
180                value: result.value,
181                optional: result.optional,
182            },
183            total: if signed {
184                Total::Signed(I256::ZERO)
185            } else {
186                Total::Unsigned(U256::ZERO)
187            },
188            count: 0,
189            operation,
190        })
191    }
192
193    pub(super) fn push(&mut self, values: &[IndexValue<'_>]) -> Result<(), Error> {
194        let value = values[self.position];
195        if value == IndexValue::Absent {
196            return Ok(());
197        }
198        match &mut self.total {
199            Total::Signed(total) => {
200                let value = match value {
201                    IndexValue::Int8(n) => i128::from(n),
202                    IndexValue::Int16(n) => i128::from(n),
203                    IndexValue::Int32(n) => i128::from(n),
204                    IndexValue::Int64(n) => i128::from(n),
205                    IndexValue::Int128(n) => n,
206                    IndexValue::Decimal(n) => n
207                        .coefficient_at_scale(self.source_scale)
208                        .ok_or(Error::Corrupt)?,
209                    _ => return Err(Error::Corrupt),
210                };
211                // Both synchronous and retained scans bound input counts; sums
212                // remain checked independently of that resource proof.
213                *total = total
214                    .checked_add(I256::from(value))
215                    .ok_or(Error::ArithmeticOverflow)?;
216            }
217            Total::Unsigned(total) => {
218                let value = match value {
219                    IndexValue::Nat8(n) => U256::from(n),
220                    IndexValue::Nat16(n) => U256::from(n),
221                    IndexValue::Nat32(n) => U256::from(n),
222                    IndexValue::Nat64(n) => U256::from(n),
223                    IndexValue::Nat128(n) => U256::from(n),
224                    IndexValue::U256(n) => n,
225                    _ => return Err(Error::Corrupt),
226                };
227                *total = total.checked_add(value).ok_or(Error::ArithmeticOverflow)?;
228            }
229        }
230        self.count = self.count.checked_add(1).ok_or(Error::ArithmeticOverflow)?;
231
232        Ok(())
233    }
234
235    // The job binding supplies admitted type/scale/operation metadata. Store only
236    // the exact accumulator and presence count, never a second schema or value AST.
237    pub(super) fn checkpoint(&self) -> (u64, [u8; 32]) {
238        (
239            self.count,
240            match self.total {
241                Total::Signed(n) => n.to_be_bytes(),
242                Total::Unsigned(n) => n.to_be_bytes(),
243            },
244        )
245    }
246
247    pub(super) fn restore(&mut self, count: u64, total: [u8; 32]) {
248        self.count = count;
249        self.total = match self.total {
250            Total::Signed(_) => Total::Signed(I256::from_be_bytes(total)),
251            Total::Unsigned(_) => Total::Unsigned(U256::from_be_bytes(total)),
252        };
253    }
254
255    pub(super) fn retained_bytes(&self) -> usize {
256        // Total payload plus the average's denominator. Fixed metadata remains
257        // bounded by the group cap, as for count/extrema reducers.
258        32 + if matches!(self.operation, Operation::Average) {
259            8
260        } else {
261            0
262        }
263    }
264
265    pub(super) fn output(&self) -> ValueSchema {
266        self.output
267    }
268
269    pub(super) fn finish(mut self) -> Result<Completed, Error> {
270        if self.count == 0 {
271            return Ok(Completed::Value(None));
272        }
273        let result_type = crate::key::operand_type(self.output.value);
274        if matches!(self.operation, Operation::Average) {
275            let FieldType::Decimal { scale } = result_type else {
276                return Err(Error::Corrupt);
277            };
278            let numerator = match self.total {
279                Total::Signed(n) => n,
280                // A nonnegative integer total this large cannot produce a Decimal
281                // coefficient fitting i128 even after division by the retained
282                // job's maximum one million inputs (synchronous scans use 512).
283                Total::Unsigned(n) => n.try_into().map_err(|_| Error::ArithmeticOverflow)?,
284            };
285            self.total = Total::Signed(rounded_average(
286                numerator,
287                self.count,
288                self.source_scale,
289                scale,
290            )?);
291        }
292        let mut output = Encoder::new();
293        let mut key = Vec::new();
294        if self.output.optional {
295            output.boolean(true)?;
296        }
297        // The ordinary owned codec supplies result bytes; checked conversion occurs
298        // only after complete accumulation, never once per input or work chunk.
299        macro_rules! encode {
300            ($method:ident, $variant:ident, $value:expr) => {{
301                let value = $value.try_into().map_err(|_| Error::ArithmeticOverflow)?;
302                output.$method(value)?;
303                IndexValue::$variant(value).append_component(self.output.optional, &mut key);
304            }};
305        }
306        match (self.total, result_type) {
307            (Total::Signed(n), FieldType::Int8) => encode!(int8, Int8, n),
308            (Total::Signed(n), FieldType::Int16) => encode!(int16, Int16, n),
309            (Total::Signed(n), FieldType::Int32) => encode!(int32, Int32, n),
310            (Total::Signed(n), FieldType::Int64) => encode!(int64, Int64, n),
311            (Total::Signed(n), FieldType::Int128) => encode!(int128, Int128, n),
312            (Total::Signed(n), FieldType::Decimal { scale }) => {
313                let coefficient = n.try_into().map_err(|_| Error::ArithmeticOverflow)?;
314                let value = Decimal::try_new(coefficient, scale).ok_or(Error::Corrupt)?;
315                output.decimal(value, scale)?;
316                IndexValue::Decimal(value).append_component(self.output.optional, &mut key);
317            }
318            (Total::Unsigned(n), FieldType::Nat8) => encode!(nat8, Nat8, n),
319            (Total::Unsigned(n), FieldType::Nat16) => encode!(nat16, Nat16, n),
320            (Total::Unsigned(n), FieldType::Nat32) => encode!(nat32, Nat32, n),
321            (Total::Unsigned(n), FieldType::Nat64) => encode!(nat64, Nat64, n),
322            (Total::Unsigned(n), FieldType::Nat128) => encode!(nat128, Nat128, n),
323            (Total::Unsigned(n), FieldType::U256) => {
324                output.u256(n)?;
325                IndexValue::U256(n).append_component(self.output.optional, &mut key);
326            }
327            _ => return Err(Error::Corrupt),
328        }
329
330        Ok(Completed::Value(Some((key, output.finish()))))
331    }
332}
333
334fn rounded_average(
335    total: I256,
336    count: u64,
337    source_scale: u32,
338    result_scale: u32,
339) -> Result<I256, Error> {
340    // One million signed 128-bit inputs plus 28 decimal scale digits fit I256.
341    // For unsigned totals, a scale-up overflow cannot hide a fitting i128 result:
342    // division by at most one million cannot bring that magnitude into range.
343    // The scale-down denominator and twice-remainder also fit comfortably.
344    let factor = I256::from(10_i128.pow(source_scale.abs_diff(result_scale)));
345    let (numerator, denominator) = if result_scale >= source_scale {
346        (
347            total.checked_mul(factor).ok_or(Error::ArithmeticOverflow)?,
348            I256::from(count),
349        )
350    } else {
351        (total, I256::from(count) * factor)
352    };
353    let quotient = numerator / denominator;
354    let twice_remainder = (numerator % denominator).abs() * 2;
355    let round = twice_remainder > denominator
356        || (twice_remainder == denominator && quotient % 2 != I256::ZERO);
357
358    Ok(if round {
359        quotient
360            + if numerator < I256::ZERO {
361                I256::MINUS_ONE
362            } else {
363                I256::ONE
364            }
365    } else {
366        quotient
367    })
368}
369
370fn integer(value: FieldType) -> Option<(bool, u16)> {
371    Some(match value {
372        FieldType::Nat8 => (false, 8),
373        FieldType::Int8 => (true, 8),
374        FieldType::Nat16 => (false, 16),
375        FieldType::Int16 => (true, 16),
376        FieldType::Nat32 => (false, 32),
377        FieldType::Int32 => (true, 32),
378        FieldType::Nat64 => (false, 64),
379        FieldType::Int64 => (true, 64),
380        FieldType::Nat128 => (false, 128),
381        FieldType::Int128 => (true, 128),
382        FieldType::U256 => (false, 256),
383        _ => return None,
384    })
385}