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