Skip to main content

ic_db/store/query/aggregate/
numeric.rs

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