1use 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, U256, Value,
10 ValueSchema, codec::Encoder,
11};
12use ethnum::I256;
13use ic_storage::Memory;
14
15impl<E: Entity, M: Memory> Query<'_, E, M> {
16 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 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 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 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 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 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 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 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 *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,
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 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::Count, _) => {
416 Some(self.count.to_be_bytes().to_vec())
417 }
418 GroupOrder::Summary(SummaryMeasure::Sum, _) => sum_key,
419 GroupOrder::Summary(SummaryMeasure::Average, _) => avg_key,
420 _ => None,
421 };
422 Ok((
423 Completed::Summary {
424 count: self.count,
425 sum: sum.map(Vec::into_boxed_slice),
426 average: average.map(Vec::into_boxed_slice),
427 sort_key: sort_key.map(Vec::into_boxed_slice),
428 },
429 accepted,
430 ))
431 }
432
433 pub(super) fn finish(self, needs_key: bool) -> Result<Completed, Error> {
434 self.encode_result(self.output, self.operation, needs_key)
435 .map(Completed::Value)
436 }
437
438 fn encode_result(
439 &self,
440 schema: ValueSchema,
441 operation: Operation,
442 needs_key: bool,
443 ) -> Result<Option<EncodedValue>, Error> {
444 if self.count == 0 {
445 return Ok(None);
446 }
447 let result_type = crate::key::operand_type(schema.value);
448 let rounded;
449 let total =
450 if let (Operation::Average, FieldType::Decimal { scale }) = (operation, result_type) {
451 let numerator = match self.total {
452 Total::Float32(_) | Total::Float64(_) => return Err(Error::Corrupt),
453 Total::Signed(n) => n,
454 Total::Unsigned(n) => n.try_into().map_err(|_| Error::ArithmeticOverflow)?,
458 };
459 rounded = Total::Signed(rounded_average(
460 numerator,
461 self.count,
462 self.source_scale,
463 scale,
464 )?);
465 &rounded
466 } else {
467 &self.total
468 };
469 let mut output = Encoder::new();
470 if schema.optional {
471 output.boolean(true)?;
472 }
473 macro_rules! encode {
476 ($method:ident, $variant:ident, $value:expr) => {{
477 let value = $value.try_into().map_err(|_| Error::ArithmeticOverflow)?;
478 output.$method(value)?;
479 IndexValue::$variant(value)
480 }};
481 }
482 let divisor = match operation {
483 Operation::Sum => 1,
484 Operation::Average => self.count,
485 };
486 let value = match (total, result_type) {
487 (Total::Float32(sum), FieldType::Float32) => {
488 let value = sum.finish(divisor)?;
489 output.float32(value)?;
490 IndexValue::Float32(value)
491 }
492 (Total::Float64(sum), FieldType::Float64) => {
493 let value = sum.finish(divisor)?;
494 output.float64(value)?;
495 IndexValue::Float64(value)
496 }
497 (Total::Signed(n), FieldType::Int8) => encode!(int8, Int8, *n),
498 (Total::Signed(n), FieldType::Int16) => encode!(int16, Int16, *n),
499 (Total::Signed(n), FieldType::Int32) => encode!(int32, Int32, *n),
500 (Total::Signed(n), FieldType::Int64) => encode!(int64, Int64, *n),
501 (Total::Signed(n), FieldType::Int128) => encode!(int128, Int128, *n),
502 (Total::Signed(n), FieldType::Decimal { scale }) => {
503 let coefficient = (*n).try_into().map_err(|_| Error::ArithmeticOverflow)?;
504 let value = Decimal::try_new(coefficient, scale).ok_or(Error::Corrupt)?;
505 output.decimal(value, scale)?;
506 IndexValue::Decimal(value)
507 }
508 (Total::Unsigned(n), FieldType::Nat8) => encode!(nat8, Nat8, *n),
509 (Total::Unsigned(n), FieldType::Nat16) => encode!(nat16, Nat16, *n),
510 (Total::Unsigned(n), FieldType::Nat32) => encode!(nat32, Nat32, *n),
511 (Total::Unsigned(n), FieldType::Nat64) => encode!(nat64, Nat64, *n),
512 (Total::Unsigned(n), FieldType::Nat128) => encode!(nat128, Nat128, *n),
513 (Total::Unsigned(n), FieldType::U256) => {
514 output.u256(*n)?;
515 IndexValue::U256(*n)
516 }
517 _ => return Err(Error::Corrupt),
518 };
519 let mut key = Vec::new();
520 if needs_key {
521 value.append_component(schema.optional, &mut key);
522 }
523
524 Ok(Some((key, output.finish())))
525 }
526}
527
528fn rounded_average(
529 total: I256,
530 count: u64,
531 source_scale: u32,
532 result_scale: u32,
533) -> Result<I256, Error> {
534 let factor = I256::from(10_i128.pow(source_scale.abs_diff(result_scale)));
539 let (numerator, denominator) = if result_scale >= source_scale {
540 (
541 total.checked_mul(factor).ok_or(Error::ArithmeticOverflow)?,
542 I256::from(count),
543 )
544 } else {
545 (total, I256::from(count) * factor)
546 };
547 let quotient = numerator / denominator;
548 let twice_remainder = (numerator % denominator).abs() * 2;
549 let round = twice_remainder > denominator
550 || (twice_remainder == denominator && quotient % 2 != I256::ZERO);
551
552 Ok(if round {
553 quotient
554 + if numerator < I256::ZERO {
555 I256::MINUS_ONE
556 } else {
557 I256::ONE
558 }
559 } else {
560 quotient
561 })
562}
563
564fn integer(value: FieldType) -> Option<(bool, u16)> {
565 Some(match value {
566 FieldType::Nat8 => (false, 8),
567 FieldType::Int8 => (true, 8),
568 FieldType::Nat16 => (false, 16),
569 FieldType::Int16 => (true, 16),
570 FieldType::Nat32 => (false, 32),
571 FieldType::Int32 => (true, 32),
572 FieldType::Nat64 => (false, 64),
573 FieldType::Int64 => (true, 64),
574 FieldType::Nat128 => (false, 128),
575 FieldType::Int128 => (true, 128),
576 FieldType::U256 => (false, 256),
577 _ => return None,
578 })
579}