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