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            let (groups, page) = self.grouped(&plan, initial, Some(sum))?;
114            let (value, output_bytes) = super::group_output(
115                groups,
116                self.request.rows,
117                self.request.bytes,
118                decode_summary,
119            )?;
120            Ok(Aggregate {
121                value,
122                output_bytes,
123                examined: page.examined,
124                fetched: page.fetched,
125            })
126        })
127    }
128
129    pub(super) fn summary_plan<K: Value, S: Value, A: Value>(
130        &self,
131    ) -> Result<(Plan<'static>, Reducer, ValueSchema), Error> {
132        let request = &self.request.groups;
133        let order = request.order.unwrap_or_default();
134        if !matches!(
135            order,
136            GroupOrder::Key | GroupOrder::KeyDescending | GroupOrder::Summary(..)
137        ) {
138            return Err(Error::InvalidQuery);
139        }
140        let (plan, initial) = self.numeric_plan::<A>(Some(K::definition()), Operation::Average)?;
141        let sum = NumericAggregate::admit(E::SCHEMA, S::definition(), Operation::Sum)?;
142        let Reducer::Numeric(average) = &initial else {
143            return Err(Error::Corrupt);
144        };
145        if sum.position != average.position {
146            return Err(Error::InvalidQuery);
147        }
148        Ok((plan, initial, sum.output))
149    }
150
151    // One admission path for synchronous, grouped and retained numeric terminals.
152    pub(super) fn numeric_plan<R: Value>(
153        &self,
154        group: Option<&TypeSchema>,
155        operation: Operation,
156    ) -> Result<(Plan<'static>, Reducer), Error> {
157        let mut plan = self.aggregate_plan(group, group.is_some())?;
158        let state = NumericAggregate::admit(E::SCHEMA, R::definition(), operation)?;
159        plan.selected |= 1 << state.position;
160
161        Ok((plan, Reducer::Numeric(state)))
162    }
163}
164
165pub(super) fn decode_summary<K: Value, S: Value, A: Value>(
166    key: &[u8],
167    result: Completed,
168) -> Result<GroupSummary<K, S, A>, Error> {
169    let Completed::Summary {
170        count,
171        sum,
172        average,
173        ..
174    } = result
175    else {
176        return Err(Error::Corrupt);
177    };
178    Ok(GroupSummary {
179        key: super::decode_record(key)?,
180        count,
181        sum: sum.as_deref().map(super::decode_record).transpose()?,
182        average: average.as_deref().map(super::decode_record).transpose()?,
183    })
184}
185
186#[derive(Clone, Copy)]
187#[repr(u8)]
188pub(super) enum Operation {
189    // Stable job-binding tags; preserve the original sum identity.
190    Sum = 1,
191    Average = 2,
192}
193
194#[derive(Clone)]
195pub(in crate::store::query) struct NumericAggregate {
196    pub(super) position: usize,
197    source_scale: u32,
198    output: ValueSchema,
199    total: Total,
200    count: u64,
201    pub(super) operation: Operation,
202}
203#[derive(Clone)]
204enum Total {
205    Float32(Box<Binary32Sum>),
206    Float64(Box<Binary64Sum>),
207    Signed(I256),
208    Unsigned(U256),
209}
210impl Total {
211    fn integer_zero(signed: bool) -> Self {
212        if signed {
213            Self::Signed(I256::ZERO)
214        } else {
215            Self::Unsigned(U256::ZERO)
216        }
217    }
218}
219
220type EncodedValue = (Vec<u8>, Vec<u8>);
221
222impl NumericAggregate {
223    fn admit(
224        entity: &EntitySchema,
225        output: &TypeSchema,
226        operation: Operation,
227    ) -> Result<Self, Error> {
228        let TypeBody::Record([result]) = output.body else {
229            return Err(Error::InvalidQuery);
230        };
231        let position = entity
232            .field_position(result.name)
233            .ok_or(Error::InvalidQuery)?;
234        let source = &entity.fields[position];
235        if source.optional != result.optional {
236            return Err(Error::InvalidQuery);
237        }
238        let input = crate::key::operand_type(source.value);
239        // A named result keeps the exact stored field contract, as in a projection.
240        if matches!(result.value, FieldType::Named(_)) {
241            super::admit_projection(entity, output)?;
242        }
243        let result_type = crate::key::operand_type(result.value);
244        let source_scale = match input {
245            FieldType::Decimal { scale } => scale,
246            _ => 0,
247        };
248        let total = match (operation, input, result_type) {
249            (_, FieldType::Float32, FieldType::Float32) => Total::Float32(Box::default()),
250            (_, FieldType::Float64, FieldType::Float64) => Total::Float64(Box::default()),
251            (
252                Operation::Sum,
253                FieldType::Decimal { scale: from },
254                FieldType::Decimal { scale: to },
255            ) if from == to => Total::Signed(I256::ZERO),
256            (
257                Operation::Average,
258                FieldType::Decimal { .. },
259                FieldType::Decimal { scale: 0..=28 },
260            ) => Total::Signed(I256::ZERO),
261            (Operation::Average, source, FieldType::Decimal { scale: 0..=28 }) => {
262                Total::integer_zero(integer(source).ok_or(Error::InvalidQuery)?.0)
263            }
264            (Operation::Average, _, _) => return Err(Error::InvalidQuery),
265            (Operation::Sum, source, result) => {
266                let (signed, bits) = integer(source).ok_or(Error::InvalidQuery)?;
267                let (result_signed, result_bits) = integer(result).ok_or(Error::InvalidQuery)?;
268                if signed != result_signed || bits > result_bits {
269                    return Err(Error::InvalidQuery);
270                }
271                Total::integer_zero(signed)
272            }
273        };
274        Ok(Self {
275            position,
276            source_scale,
277            output: ValueSchema {
278                value: result.value,
279                optional: result.optional,
280            },
281            total,
282            count: 0,
283            operation,
284        })
285    }
286
287    pub(super) fn push(&mut self, values: &[IndexValue<'_>]) -> Result<(), Error> {
288        let value = values[self.position];
289        if value == IndexValue::Absent {
290            return Ok(());
291        }
292        match &mut self.total {
293            Total::Float32(total) => {
294                let IndexValue::Float32(value) = value else {
295                    return Err(Error::Corrupt);
296                };
297                total.add(value);
298            }
299            Total::Float64(total) => {
300                let IndexValue::Float64(value) = value else {
301                    return Err(Error::Corrupt);
302                };
303                total.add(value);
304            }
305            Total::Signed(total) => {
306                let value = match value {
307                    IndexValue::Int8(n) => i128::from(n),
308                    IndexValue::Int16(n) => i128::from(n),
309                    IndexValue::Int32(n) => i128::from(n),
310                    IndexValue::Int64(n) => i128::from(n),
311                    IndexValue::Int128(n) => n,
312                    IndexValue::Decimal(n) => n
313                        .coefficient_at_scale(self.source_scale)
314                        .ok_or(Error::Corrupt)?,
315                    _ => return Err(Error::Corrupt),
316                };
317                // Both synchronous and retained scans bound input counts; sums
318                // remain checked independently of that resource proof.
319                *total = total
320                    .checked_add(I256::from(value))
321                    .ok_or(Error::ArithmeticOverflow)?;
322            }
323            Total::Unsigned(total) => {
324                let value = match value {
325                    IndexValue::Nat8(n) => U256::from(n),
326                    IndexValue::Nat16(n) => U256::from(n),
327                    IndexValue::Nat32(n) => U256::from(n),
328                    IndexValue::Nat64(n) => U256::from(n),
329                    IndexValue::Nat128(n) => U256::from(n),
330                    IndexValue::U256(n) => n.into(),
331                    _ => return Err(Error::Corrupt),
332                };
333                *total = total.checked_add(value).ok_or(Error::ArithmeticOverflow)?;
334            }
335        }
336        self.count = self.count.checked_add(1).ok_or(Error::ArithmeticOverflow)?;
337
338        Ok(())
339    }
340
341    // The job binding supplies admitted type/scale/operation metadata. Store only
342    // the exact accumulator and presence count, never a second schema or value AST.
343    pub(super) fn with_checkpoint<T>(&self, write: impl FnOnce(u64, &[u8]) -> T) -> T {
344        match &self.total {
345            Total::Signed(n) => write(self.count, &n.to_be_bytes()),
346            Total::Unsigned(n) => write(self.count, &n.to_be_bytes()),
347            Total::Float32(sum) => write(self.count, sum.checkpoint().as_flattened()),
348            Total::Float64(sum) => write(self.count, sum.checkpoint().as_flattened()),
349        }
350    }
351
352    pub(super) fn restore(&mut self, count: u64, bytes: &[u8]) -> Result<(), Error> {
353        match &mut self.total {
354            Total::Signed(n) => {
355                *n = I256::from_be_bytes(bytes.try_into().map_err(|_| Error::Corrupt)?)
356            }
357            Total::Unsigned(n) => {
358                *n = U256::from_be_bytes(bytes.try_into().map_err(|_| Error::Corrupt)?)
359            }
360            Total::Float32(sum) => sum.restore(count, bytes)?,
361            Total::Float64(sum) => sum.restore(count, bytes)?,
362        }
363        self.count = count;
364        Ok(())
365    }
366
367    pub(super) fn total_bytes(&self) -> usize {
368        match self.total {
369            Total::Float32(_) => Binary32Sum::BYTES,
370            Total::Float64(_) => Binary64Sum::BYTES,
371            Total::Signed(_) | Total::Unsigned(_) => 32,
372        }
373    }
374
375    pub(super) fn retained_bytes(&self) -> usize {
376        self.total_bytes()
377            + if matches!(self.operation, Operation::Average) {
378                8
379            } else {
380                0
381            }
382    }
383
384    pub(super) fn output(&self) -> ValueSchema {
385        self.output
386    }
387
388    pub(super) fn finish_summary(
389        self,
390        output: ValueSchema,
391        selection: &super::Selection,
392    ) -> Result<(Completed, bool), Error> {
393        let (sum_key, sum) = self
394            .encode_result(
395                output,
396                Operation::Sum,
397                selection.needs_summary_key(SummaryMeasure::Sum),
398            )?
399            .unzip();
400        let (avg_key, average) = self
401            .encode_result(
402                self.output,
403                Operation::Average,
404                selection.needs_summary_key(SummaryMeasure::Average),
405            )?
406            .unzip();
407        let count_key = self.count.to_be_bytes();
408        let accepted = selection.accepts(|measure| match measure {
409            Some(SummaryMeasure::Count) => Some(&count_key),
410            Some(SummaryMeasure::Sum) => sum_key.as_deref(),
411            Some(SummaryMeasure::Average) => avg_key.as_deref(),
412            None => None,
413        });
414        let sort_key = match selection.order {
415            GroupOrder::Summary(SummaryMeasure::Sum, _) => sum_key,
416            GroupOrder::Summary(SummaryMeasure::Average, _) => avg_key,
417            _ => None,
418        };
419        Ok((
420            Completed::Summary {
421                count: self.count,
422                sum: sum.map(Vec::into_boxed_slice),
423                average: average.map(Vec::into_boxed_slice),
424                sort_key: sort_key.map(Vec::into_boxed_slice),
425            },
426            accepted,
427        ))
428    }
429
430    pub(super) fn finish(self, needs_key: bool) -> Result<Completed, Error> {
431        self.encode_result(self.output, self.operation, needs_key)
432            .map(Completed::Value)
433    }
434
435    fn encode_result(
436        &self,
437        schema: ValueSchema,
438        operation: Operation,
439        needs_key: bool,
440    ) -> Result<Option<EncodedValue>, Error> {
441        if self.count == 0 {
442            return Ok(None);
443        }
444        let result_type = crate::key::operand_type(schema.value);
445        let rounded;
446        let total =
447            if let (Operation::Average, FieldType::Decimal { scale }) = (operation, result_type) {
448                let numerator = match self.total {
449                    Total::Float32(_) | Total::Float64(_) => return Err(Error::Corrupt),
450                    Total::Signed(n) => n,
451                    // A nonnegative integer total this large cannot produce a Decimal
452                    // coefficient fitting i128 even after division by the retained
453                    // job's maximum one million inputs (synchronous scans use 512).
454                    Total::Unsigned(n) => n.try_into().map_err(|_| Error::ArithmeticOverflow)?,
455                };
456                rounded = Total::Signed(rounded_average(
457                    numerator,
458                    self.count,
459                    self.source_scale,
460                    scale,
461                )?);
462                &rounded
463            } else {
464                &self.total
465            };
466        let mut output = Encoder::new();
467        if schema.optional {
468            output.boolean(true)?;
469        }
470        // The ordinary owned codec supplies result bytes; checked conversion occurs
471        // only after complete accumulation, never once per input or work chunk.
472        macro_rules! encode {
473            ($method:ident, $variant:ident, $value:expr) => {{
474                let value = $value.try_into().map_err(|_| Error::ArithmeticOverflow)?;
475                output.$method(value)?;
476                IndexValue::$variant(value)
477            }};
478        }
479        let divisor = match operation {
480            Operation::Sum => 1,
481            Operation::Average => self.count,
482        };
483        let value = match (total, result_type) {
484            (Total::Float32(sum), FieldType::Float32) => {
485                let value = sum.finish(divisor)?;
486                output.float32(value)?;
487                IndexValue::Float32(value)
488            }
489            (Total::Float64(sum), FieldType::Float64) => {
490                let value = sum.finish(divisor)?;
491                output.float64(value)?;
492                IndexValue::Float64(value)
493            }
494            (Total::Signed(n), FieldType::Int8) => encode!(int8, Int8, *n),
495            (Total::Signed(n), FieldType::Int16) => encode!(int16, Int16, *n),
496            (Total::Signed(n), FieldType::Int32) => encode!(int32, Int32, *n),
497            (Total::Signed(n), FieldType::Int64) => encode!(int64, Int64, *n),
498            (Total::Signed(n), FieldType::Int128) => encode!(int128, Int128, *n),
499            (Total::Signed(n), FieldType::Decimal { scale }) => {
500                let coefficient = (*n).try_into().map_err(|_| Error::ArithmeticOverflow)?;
501                let value = Decimal::try_new(coefficient, scale).ok_or(Error::Corrupt)?;
502                output.decimal(value, scale)?;
503                IndexValue::Decimal(value)
504            }
505            (Total::Unsigned(n), FieldType::Nat8) => encode!(nat8, Nat8, *n),
506            (Total::Unsigned(n), FieldType::Nat16) => encode!(nat16, Nat16, *n),
507            (Total::Unsigned(n), FieldType::Nat32) => encode!(nat32, Nat32, *n),
508            (Total::Unsigned(n), FieldType::Nat64) => encode!(nat64, Nat64, *n),
509            (Total::Unsigned(n), FieldType::Nat128) => encode!(nat128, Nat128, *n),
510            (Total::Unsigned(n), FieldType::U256) => {
511                let value = (*n).into();
512                output.u256(value)?;
513                IndexValue::U256(value)
514            }
515            _ => return Err(Error::Corrupt),
516        };
517        let mut key = Vec::new();
518        if needs_key {
519            value.append_component(schema.optional, &mut key);
520        }
521
522        Ok(Some((key, output.finish())))
523    }
524}
525
526fn rounded_average(
527    total: I256,
528    count: u64,
529    source_scale: u32,
530    result_scale: u32,
531) -> Result<I256, Error> {
532    // One million signed 128-bit inputs plus 28 decimal scale digits fit I256.
533    // For unsigned totals, a scale-up overflow cannot hide a fitting i128 result:
534    // division by at most one million cannot bring that magnitude into range.
535    // The scale-down denominator and twice-remainder also fit comfortably.
536    let factor = I256::from(10_i128.pow(source_scale.abs_diff(result_scale)));
537    let (numerator, denominator) = if result_scale >= source_scale {
538        (
539            total.checked_mul(factor).ok_or(Error::ArithmeticOverflow)?,
540            I256::from(count),
541        )
542    } else {
543        (total, I256::from(count) * factor)
544    };
545    let quotient = numerator / denominator;
546    let twice_remainder = (numerator % denominator).abs() * 2;
547    let round = twice_remainder > denominator
548        || (twice_remainder == denominator && quotient % 2 != I256::ZERO);
549
550    Ok(if round {
551        quotient
552            + if numerator < I256::ZERO {
553                I256::MINUS_ONE
554            } else {
555                I256::ONE
556            }
557    } else {
558        quotient
559    })
560}
561
562fn integer(value: FieldType) -> Option<(bool, u16)> {
563    Some(match value {
564        FieldType::Nat8 => (false, 8),
565        FieldType::Int8 => (true, 8),
566        FieldType::Nat16 => (false, 16),
567        FieldType::Int16 => (true, 16),
568        FieldType::Nat32 => (false, 32),
569        FieldType::Int32 => (true, 32),
570        FieldType::Nat64 => (false, 64),
571        FieldType::Int64 => (true, 64),
572        FieldType::Nat128 => (false, 128),
573        FieldType::Int128 => (true, 128),
574        FieldType::U256 => (false, 256),
575        _ => return None,
576    })
577}