1mod float_sum;
4pub(super) mod jobs;
5mod numeric;
6
7use super::distinct::DistinctKeys;
8use super::{
9 Comparison, MAX_COMPARISON_KEY, MAX_DISTINCT_VALUES, MAX_STATE_BYTES, MAX_TERMS, Plan, Query,
10 QueryPage, admit_ordered_fields, admit_output, admit_projection, comparison_key,
11 copy_projection, execute, projection_size,
12};
13use crate::{
14 Entity, EntitySchema, Error, FieldType, IndexValue, TypeSchema, Value, ValueSchema,
15 codec::Decoder, key,
16};
17use ic_storage::Memory;
18use std::collections::BTreeMap;
19
20const MAX_GROUPS: usize = 32;
21
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24#[repr(u8)]
25pub enum SummaryMeasure {
26 Count = 0,
28 Sum = 1,
30 Average = 2,
32}
33
34#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
36pub enum GroupOrder {
37 #[default]
39 Key,
40 AggregateAscending,
42 AggregateDescending,
44 KeyDescending,
46 FirstOccurrence,
48 Summary(SummaryMeasure, super::SortDirection),
50}
51
52struct GroupPredicate<T> {
53 measure: Option<SummaryMeasure>,
54 comparison: Comparison,
55 operand: T,
56 or_next: bool,
57}
58
59#[derive(Default)]
60pub(super) struct GroupRequest<'a> {
61 predicates: Vec<GroupPredicate<IndexValue<'a>>>,
62 order: Option<GroupOrder>,
63 page: Option<jobs::pages::PageRequest<'a>>,
64}
65impl GroupRequest<'_> {
66 pub(super) fn is_empty(&self) -> bool {
67 self.predicates.is_empty() && self.order.is_none() && self.page.is_none()
68 }
69
70 fn admit(
71 &self,
72 entity: &EntitySchema,
73 reducer: &Reducer,
74 summary_sum: Option<ValueSchema>,
75 ) -> Result<Selection, Error> {
76 if self
77 .page
78 .is_some_and(|page| !(1..=MAX_GROUPS).contains(&page.size))
79 {
80 return Err(Error::Limit);
81 }
82 let field = match reducer {
83 Reducer::Keys(_) => {
84 let order = self.order.unwrap_or_default();
85 if !self.predicates.is_empty()
86 || !matches!(
87 order,
88 GroupOrder::Key | GroupOrder::KeyDescending | GroupOrder::FirstOccurrence
89 )
90 {
91 return Err(Error::InvalidQuery);
92 }
93
94 return Ok(Selection {
95 predicates: Vec::new(),
96 order,
97 optional: false,
98 });
99 }
100 Reducer::Count { .. } | Reducer::Distinct { .. } => ValueSchema {
101 value: FieldType::Nat64,
102 optional: false,
103 },
104 Reducer::Extremum { position, .. } => {
105 let field = &entity.fields[*position];
106
107 ValueSchema {
108 value: field.value,
109 optional: field.optional,
110 }
111 }
112 Reducer::Numeric(state) => state.output(),
113 };
114 if self.order == Some(GroupOrder::FirstOccurrence) {
115 return Err(Error::InvalidQuery);
116 }
117 let absent_result = !matches!(reducer, Reducer::Count { .. } | Reducer::Distinct { .. });
119 let predicates = self
120 .predicates
121 .iter()
122 .map(
123 |&GroupPredicate {
124 comparison,
125 operand: value,
126 or_next,
127 measure,
128 }| {
129 let (field, absent_result) = match (measure, summary_sum) {
130 (None, None) => (field, absent_result),
131 (Some(SummaryMeasure::Count), Some(_)) => (
132 ValueSchema {
133 value: FieldType::Nat64,
134 optional: false,
135 },
136 false,
137 ),
138 (Some(SummaryMeasure::Sum), Some(sum)) => (sum, true),
139 (Some(SummaryMeasure::Average), Some(_)) => (field, true),
140 _ => return Err(Error::InvalidQuery),
141 };
142 if match value {
143 IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
144 IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
145 _ => false,
146 } {
147 return Err(Error::Limit);
148 }
149 comparison.admit(field.value, absent_result, value)?;
150 let key = if value == IndexValue::Absent {
151 None
152 } else {
153 let mut key = Vec::new();
154 value.append_component(field.optional, &mut key);
155 if key.len() > MAX_COMPARISON_KEY {
156 return Err(Error::Limit);
157 }
158
159 Some(key)
160 };
161
162 Ok(GroupPredicate {
163 measure,
164 comparison,
165 operand: key,
166 or_next,
167 })
168 },
169 )
170 .collect::<Result<_, Error>>()?;
171
172 Ok(Selection {
173 predicates,
174 order: self.order.unwrap_or_default(),
175 optional: field.optional,
176 })
177 }
178}
179
180struct Selection {
181 predicates: Vec<GroupPredicate<Option<Vec<u8>>>>,
182 order: GroupOrder,
183 optional: bool,
185}
186
187impl Selection {
188 fn accepts<'a>(&self, key: impl Fn(Option<SummaryMeasure>) -> Option<&'a [u8]>) -> bool {
189 self.predicates
190 .split_inclusive(|term| !term.or_next)
191 .all(|clause| {
192 clause.iter().any(|term| {
193 term.comparison.accepts(
194 key(term.measure),
195 term.operand.as_deref(),
196 self.optional && term.measure != Some(SummaryMeasure::Count),
197 )
198 })
199 })
200 }
201}
202
203#[derive(Debug)]
205pub struct Aggregate<T> {
206 pub value: T,
208 pub examined: usize,
210 pub fetched: usize,
212 pub output_bytes: usize,
214}
215
216#[derive(Debug)]
218pub struct GroupCount<K> {
219 pub key: K,
221 pub count: u64,
223}
224
225pub type GroupSummaries<K, S, A> = Aggregate<Vec<GroupSummary<K, S, A>>>;
227
228pub type GroupSummaryPage<K, S, A> = jobs::GroupPage<GroupSummary<K, S, A>>;
230
231#[derive(Debug)]
233pub struct GroupSummary<K, S, A> {
234 pub key: K,
236 pub count: u64,
238 pub sum: Option<S>,
240 pub average: Option<A>,
242}
243
244#[derive(Debug)]
246pub struct GroupValue<K, R> {
247 pub key: K,
249 pub value: Option<R>,
251}
252
253impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
254 #[must_use]
259 pub fn group_page(mut self, size: usize, after: Option<&'a jobs::GroupCursor>) -> Self {
260 self.request.groups.page = Some(jobs::pages::PageRequest { size, after });
261
262 self
263 }
264
265 #[must_use]
272 pub fn filter_groups(self, comparison: Comparison, value: impl Into<IndexValue<'a>>) -> Self {
273 self.add_group_clause(std::iter::once((None, comparison, value.into())))
274 }
275
276 #[must_use]
279 pub fn filter_summary(
280 self,
281 measure: SummaryMeasure,
282 comparison: Comparison,
283 value: impl Into<IndexValue<'a>>,
284 ) -> Self {
285 self.add_group_clause(std::iter::once((Some(measure), comparison, value.into())))
286 }
287
288 #[must_use]
292 pub fn filter_summary_any(
293 self,
294 alternatives: &[(SummaryMeasure, Comparison, IndexValue<'a>)],
295 ) -> Self {
296 self.add_group_clause(
297 alternatives
298 .iter()
299 .map(|&(measure, comparison, value)| (Some(measure), comparison, value)),
300 )
301 }
302
303 #[must_use]
310 pub fn filter_groups_any(self, alternatives: &[(Comparison, IndexValue<'a>)]) -> Self {
311 self.add_group_clause(
312 alternatives
313 .iter()
314 .map(|&(comparison, value)| (None, comparison, value)),
315 )
316 }
317
318 fn add_group_clause(
319 mut self,
320 terms: impl ExactSizeIterator<Item = (Option<SummaryMeasure>, Comparison, IndexValue<'a>)>,
321 ) -> Self {
322 let count = terms.len();
323 if count == 0 || count > MAX_TERMS - self.request.groups.predicates.len() {
324 self.request.over_limit = true;
325 } else {
326 self.request.groups.predicates.extend(terms.enumerate().map(
327 |(i, (measure, comparison, operand))| GroupPredicate {
328 measure,
329 comparison,
330 operand,
331 or_next: i + 1 != count,
332 },
333 ));
334 }
335
336 self
337 }
338
339 #[must_use]
342 pub fn order_groups(mut self, order: GroupOrder) -> Self {
343 self.request.groups.order = Some(order);
344
345 self
346 }
347
348 pub fn min<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
361 observe!(query, { self.extremum(false) })
362 }
363
364 pub fn max<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
371 observe!(query, { self.extremum(true) })
372 }
373
374 fn extremum<R: Value>(self, maximum: bool) -> Result<Aggregate<Option<R>>, Error> {
375 let (plan, reducer) = self.extremum_plan::<R>(maximum)?;
376
377 self.scalar_value(plan, reducer)
378 }
379
380 fn extremum_plan<R: Value>(&self, maximum: bool) -> Result<(Plan<'a>, Reducer), Error> {
381 let plan = self.aggregate_plan(Some(R::definition()), false)?;
382 let reducer = Reducer::extremum(
383 E::SCHEMA,
384 plan.projection.ok_or(Error::InvalidQuery)?,
385 maximum,
386 )?;
387
388 Ok((plan, reducer))
389 }
390
391 fn scalar_value<R: Value>(
392 self,
393 mut plan: Plan<'_>,
394 mut reducer: Reducer,
395 ) -> Result<Aggregate<Option<R>>, Error> {
396 super::order::select_unique_aggregate_path(E::SCHEMA, &self.request, &mut plan)?;
397 let page = execute(
398 &self.db.read()?.map,
399 E::SCHEMA,
400 &self.request,
401 &plan,
402 Some(Accumulator::Scalar(&mut reducer)),
403 )?;
404 let mut output_bytes = 0;
405 let value = reducer
406 .finish()?
407 .into_value()?
408 .map(|bytes| {
409 admit_output(bytes.len(), self.request.bytes, &mut output_bytes)?;
410
411 decode_record(&bytes)
412 })
413 .transpose()?;
414
415 Ok(Aggregate {
416 value,
417 examined: page.examined,
418 fetched: page.fetched,
419 output_bytes,
420 })
421 }
422
423 pub fn group_min<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
440 observe!(query, { self.group_extrema(false) })
441 }
442
443 pub fn group_max<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
449 observe!(query, { self.group_extrema(true) })
450 }
451
452 fn group_extrema<K: Value, R: Value>(
453 self,
454 maximum: bool,
455 ) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
456 let (plan, initial) = self.group_extremum_plan::<K, R>(maximum)?;
457
458 self.group_values(plan, initial)
459 }
460
461 fn group_extremum_plan<K: Value, R: Value>(
462 &self,
463 maximum: bool,
464 ) -> Result<(Plan<'a>, Reducer), Error> {
465 let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
466 let operand = admit_projection(E::SCHEMA, R::definition())?;
467 let initial = Reducer::extremum(E::SCHEMA, operand, maximum)?;
468 plan.selected |= operand;
469
470 Ok((plan, initial))
471 }
472
473 fn group_values<K: Value, R: Value>(
474 self,
475 mut plan: Plan<'_>,
476 initial: Reducer,
477 ) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
478 super::order::select_unique_aggregate_path(E::SCHEMA, &self.request, &mut plan)?;
479 let (groups, page) = self.grouped(&plan, initial, None)?;
480 let (value, output_bytes) = group_output(
481 groups,
482 self.request.rows,
483 self.request.bytes,
484 decode_group_value,
485 )?;
486
487 Ok(Aggregate {
488 value,
489 examined: page.examined,
490 fetched: page.fetched,
491 output_bytes,
492 })
493 }
494
495 pub fn exists(self) -> Result<Aggregate<bool>, Error> {
508 observe!(query, {
509 let mut plan = self.aggregate_plan(None, false)?;
510 self.select_aggregate_row_path(&mut plan)?;
511 let mut found = false;
512 let page = execute(
513 &self.db.read()?.map,
514 E::SCHEMA,
515 &self.request,
516 &plan,
517 Some(Accumulator::Exists(&mut found)),
518 )?;
519
520 Ok(Aggregate {
521 value: found,
522 examined: page.examined,
523 fetched: page.fetched,
524 output_bytes: 1,
525 })
526 })
527 }
528
529 pub fn count(self) -> Result<Aggregate<u64>, Error> {
546 observe!(query, {
547 if self.request.bytes < 8 {
548 return Err(Error::RowTooLarge);
549 }
550 let mut plan = self.aggregate_plan(None, false)?;
551 if self.request.predicates.is_empty() && self.request.index.is_none() {
552 return Ok(Aggregate {
553 value: self.db.read()?.cardinality::<E>()?,
554 examined: 0,
555 fetched: 0,
556 output_bytes: 8,
557 });
558 }
559 if plan.index.is_none()
560 && let Some(count) = self.count_members(&plan)?
561 {
562 return Ok(count);
563 }
564 if super::order::select_aggregate_path(E::SCHEMA, &self.request, &mut plan, true)? {
565 return self.count_keys(&plan);
566 }
567 if plan.index.is_some()
568 && let Some(count) = self.count_members(&plan)?
569 {
570 return Ok(count);
571 }
572 let reducer = self.count_reducer(None)?;
573
574 self.scalar_count_value(&plan, reducer)
575 })
576 }
577
578 pub fn count_validated(self) -> Result<Aggregate<u64>, Error> {
583 observe!(query, { self.scalar_count(None) })
584 }
585
586 pub fn count_index_entries(self) -> Result<Aggregate<u64>, Error> {
598 observe!(query, {
599 if self.request.index.is_none() || !self.request.predicates.is_empty() {
600 return Err(Error::InvalidQuery);
601 }
602 if self.request.bytes < 8 {
603 return Err(Error::RowTooLarge);
604 }
605 let plan = self.aggregate_plan(None, false)?;
606
607 self.count_keys(&plan)
608 })
609 }
610
611 fn count_members(&self, plan: &Plan<'_>) -> Result<Option<Aggregate<u64>>, Error> {
612 let Some(members) = super::range::point_count_members(E::SCHEMA, plan, &self.request)
613 else {
614 return Ok(None);
615 };
616 let db = self.db.read()?;
617 let mut count = 0;
618 for member in &members {
619 let key = crate::store_key::StoreKey::new([plan.prefix.as_slice(), *member].concat())?;
620 count += u64::from(db.map.contains_key(&key));
621 }
622
623 Ok(Some(Aggregate {
624 value: count,
625 examined: members.len(),
626 fetched: 0,
627 output_bytes: 8,
628 }))
629 }
630
631 fn count_keys(&self, plan: &Plan<'_>) -> Result<Aggregate<u64>, Error> {
632 let bounds = super::range::bounds(E::SCHEMA, &self.request, plan)?;
633 let mut examined = 0;
634 if let Some(range) = bounds {
635 let terminal = super::range::terminal_key(&range, false);
636 let db = self.db.read()?;
637 let entries = db.map.range((range.0.as_ref(), range.1.as_ref()));
638 for entry in entries.take(self.request.work) {
639 examined += 1;
640 if examined == self.request.work && terminal.is_none_or(|end| end != entry.key()) {
641 return Err(Error::Limit);
642 }
643 }
644 }
645
646 Ok(Aggregate {
647 value: examined as u64,
648 examined,
649 fetched: 0,
650 output_bytes: 8,
651 })
652 }
653
654 pub fn count_field(self, field: &str) -> Result<Aggregate<u64>, Error> {
662 observe!(query, { self.scalar_count(Some(field)) })
663 }
664
665 pub fn count_distinct<K: Value>(self) -> Result<Aggregate<u64>, Error> {
674 observe!(query, {
675 if self.request.bytes < 8 {
676 return Err(Error::RowTooLarge);
677 }
678 let (mut plan, reducer) = self.distinct_plan::<K>()?;
679 self.select_aggregate_row_path(&mut plan)?;
680
681 self.scalar_count_value(&plan, reducer)
682 })
683 }
684
685 fn distinct_plan<K: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
686 let plan = self.aggregate_plan(Some(K::definition()), false)?;
687 let reducer = Reducer::distinct(plan.projection.ok_or(Error::InvalidQuery)?);
688
689 Ok((plan, reducer))
690 }
691
692 fn select_aggregate_row_path(&self, plan: &mut Plan<'static>) -> Result<(), Error> {
693 if plan.index.is_none() {
694 super::order::select_aggregate_path(E::SCHEMA, &self.request, plan, false)?;
695 }
696
697 Ok(())
698 }
699
700 fn scalar_count(self, field: Option<&str>) -> Result<Aggregate<u64>, Error> {
701 if self.request.bytes < 8 {
702 return Err(Error::RowTooLarge);
703 }
704 let mut plan = self.aggregate_plan(None, false)?;
705 self.select_aggregate_row_path(&mut plan)?;
706 let reducer = self.count_reducer(field)?;
707
708 self.scalar_count_value(&plan, reducer)
709 }
710
711 fn scalar_count_value(
712 self,
713 plan: &Plan<'_>,
714 mut reducer: Reducer,
715 ) -> Result<Aggregate<u64>, Error> {
716 let page = execute(
717 &self.db.read()?.map,
718 E::SCHEMA,
719 &self.request,
720 plan,
721 Some(Accumulator::Scalar(&mut reducer)),
722 )?;
723
724 Ok(Aggregate {
725 value: reducer.finish()?.into_count()?,
726 examined: page.examined,
727 fetched: page.fetched,
728 output_bytes: 8,
729 })
730 }
731
732 pub fn group_count<K: Value>(self) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
749 observe!(query, { self.group_counts(None) })
750 }
751
752 pub fn group_count_field<K: Value>(
761 self,
762 field: &str,
763 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
764 observe!(query, { self.group_counts(Some(field)) })
765 }
766
767 pub fn group_count_distinct<K: Value, R: Value>(
780 self,
781 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
782 observe!(query, {
783 let (plan, reducer) = self.group_distinct_plan::<K, R>()?;
784
785 self.group_count_values(plan, reducer)
786 })
787 }
788
789 fn group_distinct_plan<K: Value, R: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
790 let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
791 let operand = admit_projection(E::SCHEMA, R::definition())?;
792 admit_ordered_fields(E::SCHEMA, operand)?;
793 plan.selected |= operand;
794
795 Ok((plan, Reducer::distinct(operand)))
796 }
797
798 fn group_counts<K: Value>(
799 self,
800 field: Option<&str>,
801 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
802 let plan = self.aggregate_plan(Some(K::definition()), true)?;
803 let reducer = self.count_reducer(field)?;
804
805 self.group_count_values(plan, reducer)
806 }
807
808 fn group_count_values<K: Value>(
809 self,
810 mut plan: Plan<'static>,
811 reducer: Reducer,
812 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
813 self.select_aggregate_row_path(&mut plan)?;
814 let (groups, page) = self.grouped(&plan, reducer, None)?;
815 let (value, output_bytes) = group_output(
816 groups,
817 self.request.rows,
818 self.request.bytes,
819 decode_group_count,
820 )?;
821
822 Ok(Aggregate {
823 value,
824 examined: page.examined,
825 fetched: page.fetched,
826 output_bytes,
827 })
828 }
829
830 fn count_reducer(&self, field: Option<&str>) -> Result<Reducer, Error> {
831 let presence = field
833 .map(|name| E::SCHEMA.field_position(name).ok_or(Error::InvalidQuery))
834 .transpose()?
835 .filter(|&i| E::SCHEMA.fields[i].optional);
836
837 Ok(Reducer::Count { presence, total: 0 })
838 }
839
840 fn grouped(
841 &self,
842 plan: &Plan<'_>,
843 initial: Reducer,
844 summary_sum: Option<ValueSchema>,
845 ) -> Result<(Groups, QueryPage<Vec<u8>>), Error> {
846 if self.request.groups.page.is_some() {
847 return Err(Error::InvalidQuery);
848 }
849 let mut groups = self.admit_groups(plan, initial, summary_sum)?;
850 let page = execute(
851 &self.db.read()?.map,
852 E::SCHEMA,
853 &self.request,
854 plan,
855 Some(Accumulator::Groups(&mut groups)),
856 )?;
857
858 Ok((groups, page))
859 }
860
861 fn admit_groups(
862 &self,
863 plan: &Plan<'_>,
864 initial: Reducer,
865 summary_sum: Option<ValueSchema>,
866 ) -> Result<Groups, Error> {
867 if summary_sum.is_none()
868 && matches!(self.request.groups.order, Some(GroupOrder::Summary(..)))
869 {
870 return Err(Error::InvalidQuery);
871 }
872 Ok(Groups {
873 selection: self
874 .request
875 .groups
876 .admit(E::SCHEMA, &initial, summary_sum)?,
877 summary_sum,
878 mask: plan.projection.ok_or(Error::InvalidQuery)?,
879 initial,
880 rows: BTreeMap::new(),
881 state_bytes: 0,
882 })
883 }
884
885 fn aggregate_plan(
886 &self,
887 output: Option<&TypeSchema>,
888 group_output: bool,
889 ) -> Result<Plan<'static>, Error> {
890 if self.request.cursor.is_some()
891 || self.request.distinct
892 || ((self.request.order.is_some() || self.request.descending)
893 && self.request.groups.order != Some(GroupOrder::FirstOccurrence))
894 {
895 return Err(Error::InvalidQuery);
896 }
897 let db = self.db.read()?;
898 db.schema.admits(E::SCHEMA)?;
899 let mut plan = Plan::admit(
900 E::SCHEMA,
901 &self.request,
902 db.schema.fingerprint(),
903 db.incarnation,
904 output,
905 super::PlanOutput::Aggregate {
906 grouped: group_output,
907 },
908 )?;
909 if let Some(mask) = plan.projection {
910 admit_ordered_fields(E::SCHEMA, mask)?;
911 plan.selected |= mask;
912 }
913
914 Ok(plan)
915 }
916}
917
918fn group_output<T>(
919 groups: Groups,
920 rows: usize,
921 bytes: usize,
922 decode: fn(&[u8], Completed) -> Result<T, Error>,
923) -> Result<(Vec<T>, usize), Error> {
924 let mut output_bytes = 0;
925 let value = groups
926 .into_output()?
927 .into_iter()
928 .take(rows)
929 .map(|(key, result)| {
930 admit_output(key.len() + result.encoded_len(), bytes, &mut output_bytes)?;
931
932 decode(&key, result)
933 })
934 .collect::<Result<_, Error>>()?;
935
936 Ok((value, output_bytes))
937}
938
939fn decode_group_count<K: Value>(key: &[u8], result: Completed) -> Result<GroupCount<K>, Error> {
940 Ok(GroupCount {
941 key: decode_record(key)?,
942 count: result.into_count()?,
943 })
944}
945
946fn decode_group_value<K: Value, R: Value>(
947 key: &[u8],
948 result: Completed,
949) -> Result<GroupValue<K, R>, Error> {
950 let value = result.into_value()?;
951
952 Ok(GroupValue {
953 key: decode_record(key)?,
954 value: value.as_deref().map(decode_record).transpose()?,
955 })
956}
957
958fn decode_record<R: Value>(bytes: &[u8]) -> Result<R, Error> {
959 let mut reader = Decoder::new(bytes)?;
960 let value = R::decode_from(&mut reader)?;
961 reader.finish()?;
962
963 Ok(value)
964}
965
966pub(super) enum Accumulator<'a> {
968 Exists(&'a mut bool),
970 Scalar(&'a mut Reducer),
971 Groups(&'a mut Groups),
972}
973impl Accumulator<'_> {
974 pub(super) fn needs_spans(&self) -> bool {
975 !matches!(
976 self,
977 Self::Exists(_)
978 | Self::Scalar(
979 Reducer::Numeric(_)
980 | Reducer::Count { presence: None, .. }
981 | Reducer::Distinct { .. }
982 )
983 )
984 }
985
986 pub(super) fn push(
987 &mut self,
988 entity: &EntitySchema,
989 values: &[IndexValue<'_>],
990 bytes: &[u8],
991 spans: &[(u16, u16)],
992 scratch: &mut Vec<u8>,
993 ) -> Result<(), Error> {
994 match self {
995 Self::Exists(found) => {
996 **found = true;
997
998 Ok(())
999 }
1000 Self::Scalar(state) => {
1001 state.push(entity, values, bytes, spans, scratch, MAX_STATE_BYTES)
1002 }
1003 Self::Groups(state) => state.push(entity, values, bytes, spans, scratch),
1004 }
1005 }
1006}
1007
1008#[derive(Clone)]
1009pub(super) enum Reducer {
1010 Keys(u8),
1011 Numeric(numeric::NumericAggregate),
1012 Distinct {
1013 mask: u16,
1014 seen: DistinctKeys,
1015 key_bytes: usize,
1016 },
1017 Count {
1018 presence: Option<usize>,
1019 total: u64,
1020 },
1021 Extremum {
1022 position: usize,
1023 maximum: bool,
1024 selected: Option<(Vec<u8>, Vec<u8>)>,
1025 },
1026}
1027impl Reducer {
1028 fn distinct(mask: u16) -> Self {
1029 Self::Distinct {
1030 mask,
1031 seen: DistinctKeys::new(),
1032 key_bytes: 0,
1033 }
1034 }
1035
1036 fn extremum(entity: &EntitySchema, mask: u16, maximum: bool) -> Result<Self, Error> {
1037 if mask.count_ones() != 1 {
1038 return Err(Error::InvalidQuery);
1039 }
1040 let position = mask.trailing_zeros() as usize;
1041 if !key::supports(entity.fields[position].value) {
1042 return Err(Error::InvalidQuery);
1043 }
1044
1045 Ok(Self::Extremum {
1046 position,
1047 maximum,
1048 selected: None,
1049 })
1050 }
1051
1052 fn retained_bytes(&self) -> usize {
1053 match self {
1054 Self::Keys(_) => 0,
1055 Self::Numeric(state) => state.retained_bytes(),
1056 Self::Count { .. } => 8,
1057 Self::Distinct { key_bytes, .. } => 8 + key_bytes,
1058 Self::Extremum { selected, .. } => selected
1059 .as_ref()
1060 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
1061 }
1062 }
1063
1064 fn finish(self) -> Result<Completed, Error> {
1065 match self {
1066 Self::Keys(_) => Ok(Completed::Key),
1067 Self::Count { total, .. } => Ok(Completed::Count(total)),
1068 Self::Distinct { seen, .. } => Ok(Completed::Count(seen.len() as u64)),
1069 Self::Extremum { selected, .. } => Ok(Completed::Value(selected)),
1070 Self::Numeric(state) => state.finish(),
1071 }
1072 }
1073
1074 fn push(
1075 &mut self,
1076 entity: &EntitySchema,
1077 values: &[IndexValue<'_>],
1078 bytes: &[u8],
1079 spans: &[(u16, u16)],
1080 scratch: &mut Vec<u8>,
1081 allowance: usize,
1082 ) -> Result<(), Error> {
1083 match self {
1084 Self::Keys(_) => {}
1085 Self::Numeric(state) => state.push(values)?,
1086 Self::Distinct {
1087 mask,
1088 seen,
1089 key_bytes,
1090 } => {
1091 comparison_key(entity, *mask, values, scratch)?;
1092 if let Err(position) =
1093 seen.binary_search_by(|key| key.as_ref().cmp(scratch.as_slice()))
1094 {
1095 let size = scratch.len();
1096 if seen.len() == MAX_DISTINCT_VALUES || 8 + *key_bytes + size > allowance {
1097 return Err(Error::Limit);
1098 }
1099 seen.insert(position, Box::from(scratch.as_slice()));
1100 *key_bytes += size;
1101 }
1102 }
1103 Self::Count { presence, total } => {
1104 *total += u64::from(presence.is_none_or(|i| bytes[usize::from(spans[i].0)] != 0));
1105 }
1106 Self::Extremum {
1107 position,
1108 maximum,
1109 selected,
1110 } => {
1111 let value = values[*position];
1112 if value == IndexValue::Absent {
1113 return Ok(());
1114 }
1115 scratch.clear();
1116 value.append_component(entity.fields[*position].optional, scratch);
1117 if scratch.len() > MAX_COMPARISON_KEY {
1118 return Err(Error::Limit);
1119 }
1120 if selected.as_ref().is_none_or(|(old, _)| {
1121 if *maximum {
1122 scratch.as_slice() > old.as_slice()
1123 } else {
1124 scratch.as_slice() < old.as_slice()
1125 }
1126 }) {
1127 let (start, end) = spans[*position];
1128 let output = &bytes[usize::from(start)..usize::from(end)];
1129 if let Some((old_key, old_output)) = selected
1130 && old_key.len() == scratch.len()
1131 && old_output.len() == output.len()
1132 {
1133 old_key.copy_from_slice(scratch);
1135 old_output.copy_from_slice(output);
1136 return Ok(());
1137 }
1138 if scratch.len() + output.len() > allowance {
1139 return Err(Error::Limit);
1140 }
1141 let key = scratch.as_slice().to_vec();
1143 let output = output.to_vec();
1144 if key.capacity() + output.capacity() > allowance {
1145 return Err(Error::Limit);
1146 }
1147 *selected = Some((key, output));
1148 }
1149 }
1150 }
1151
1152 Ok(())
1153 }
1154}
1155
1156enum Completed {
1158 Summary {
1159 count: u64,
1160 sum: Option<Box<[u8]>>,
1161 average: Option<Box<[u8]>>,
1162 sort_key: Option<Box<[u8]>>,
1163 },
1164 Key,
1165 Count(u64),
1166 Value(Option<(Vec<u8>, Vec<u8>)>),
1167}
1168impl Completed {
1169 fn encoded_len(&self) -> usize {
1170 match self {
1171 Self::Summary { sum, average, .. } => {
1172 8 + sum.as_deref().map_or(0, <[u8]>::len)
1173 + average.as_deref().map_or(0, <[u8]>::len)
1174 }
1175 Self::Key => 0,
1176 Self::Count(_) => 8,
1177 Self::Value(value) => value.as_ref().map_or(0, |(_, bytes)| bytes.len()),
1178 }
1179 }
1180 fn result_key<'a>(&'a self, scratch: &'a mut [u8; 8]) -> Option<&'a [u8]> {
1182 match self {
1183 Self::Summary { sort_key, .. } => sort_key.as_deref(),
1184 Self::Key => None,
1185 Self::Count(total) => {
1186 *scratch = total.to_be_bytes();
1187
1188 Some(scratch)
1189 }
1190 Self::Value(selected) => selected.as_ref().map(|(key, _)| key.as_slice()),
1191 }
1192 }
1193
1194 fn retained_bytes(&self) -> usize {
1195 match self {
1196 Self::Summary { sort_key, .. } => {
1197 self.encoded_len() + sort_key.as_deref().map_or(0, <[u8]>::len)
1198 }
1199 Self::Key => 0,
1200 Self::Count(_) => 8,
1201 Self::Value(value) => value
1202 .as_ref()
1203 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
1204 }
1205 }
1206
1207 fn into_count(self) -> Result<u64, Error> {
1208 match self {
1209 Self::Count(count) => Ok(count),
1210 _ => Err(Error::Corrupt),
1211 }
1212 }
1213
1214 fn into_value(self) -> Result<Option<Vec<u8>>, Error> {
1215 match self {
1216 Self::Value(value) => Ok(value.map(|(_, bytes)| bytes)),
1217 _ => Err(Error::Corrupt),
1218 }
1219 }
1220}
1221
1222pub(super) struct Groups {
1223 summary_sum: Option<ValueSchema>,
1224 selection: Selection,
1225 mask: u16,
1226 initial: Reducer,
1228 rows: BTreeMap<Box<[u8]>, (Vec<u8>, Reducer)>,
1229 state_bytes: usize,
1230}
1231impl Groups {
1232 fn max_keys(&self) -> usize {
1233 if matches!(self.initial, Reducer::Keys(_)) {
1234 usize::from(u8::MAX)
1235 } else {
1236 MAX_GROUPS
1237 }
1238 }
1239
1240 fn first_occurrences(&self) -> Result<Vec<&[u8]>, Error> {
1242 let mut ordered = vec![&[][..]; self.rows.len()];
1243 for (bytes, reducer) in self.rows.values() {
1244 let Reducer::Keys(position) = reducer else {
1245 return Err(Error::Corrupt);
1246 };
1247 ordered[usize::from(*position)] = bytes;
1248 }
1249 Ok(ordered)
1250 }
1251
1252 fn into_output(self) -> Result<Vec<(Vec<u8>, Completed)>, Error> {
1253 let mut state_bytes = self.state_bytes;
1255 let mut rows = Vec::with_capacity(self.rows.len());
1256 for (record, reducer) in self.rows.into_values() {
1257 let previous = reducer.retained_bytes();
1258 let (result, accepted) = if let Some(sum) = self.summary_sum {
1259 let Reducer::Numeric(state) = reducer else {
1260 return Err(Error::Corrupt);
1261 };
1262 state.finish_summary(sum, &self.selection)?
1263 } else {
1264 let result = reducer.finish()?;
1265 let mut scratch = [0; 8];
1266 let key = result.result_key(&mut scratch);
1267 let accepted = self.selection.accepts(|_| key);
1268 (result, accepted)
1269 };
1270 state_bytes = state_bytes - previous + result.retained_bytes();
1271 if state_bytes > MAX_STATE_BYTES {
1272 return Err(Error::Limit);
1273 }
1274 if accepted {
1275 rows.push((record, result));
1276 }
1277 }
1278 if self.selection.order == GroupOrder::KeyDescending {
1279 rows.reverse();
1282 } else if self.selection.order != GroupOrder::Key {
1283 rows.sort_by(|(_, a), (_, b)| {
1285 let (mut sa, mut sb) = ([0; 8], [0; 8]);
1286 let order = a.result_key(&mut sa).cmp(&b.result_key(&mut sb));
1287 if matches!(
1288 self.selection.order,
1289 GroupOrder::AggregateDescending
1290 | GroupOrder::Summary(_, super::SortDirection::Descending)
1291 ) {
1292 order.reverse()
1293 } else {
1294 order
1295 }
1296 });
1297 }
1298
1299 Ok(rows)
1300 }
1301
1302 fn push(
1303 &mut self,
1304 entity: &EntitySchema,
1305 values: &[IndexValue<'_>],
1306 bytes: &[u8],
1307 spans: &[(u16, u16)],
1308 scratch: &mut Vec<u8>,
1309 ) -> Result<(), Error> {
1310 comparison_key(entity, self.mask, values, scratch)?;
1311 let available = MAX_STATE_BYTES - self.state_bytes;
1312 if let Some((_, reducer)) = self.rows.get_mut(scratch.as_slice()) {
1313 let previous = reducer.retained_bytes();
1314 reducer.push(entity, values, bytes, spans, scratch, available + previous)?;
1315 self.state_bytes = self.state_bytes - previous + reducer.retained_bytes();
1316 return Ok(());
1317 }
1318
1319 let count = self.rows.len();
1320 let size = projection_size(spans, self.mask);
1321 let base = scratch.len() + size;
1322 if count == self.max_keys() || base + self.initial.retained_bytes() > available {
1323 return Err(Error::Limit);
1324 }
1325 let key = Box::<[u8]>::from(scratch.as_slice());
1327 let mut reducer = self.initial.clone();
1328 if let Reducer::Keys(position) = &mut reducer {
1329 *position = count as u8;
1330 }
1331 reducer.push(entity, values, bytes, spans, scratch, available - base)?;
1332 let output = copy_projection(bytes, spans, self.mask, size);
1333 let retained = key.len() + output.capacity() + reducer.retained_bytes();
1336 if retained > available {
1337 return Err(Error::Limit);
1338 }
1339 self.state_bytes += retained;
1340 self.rows.insert(key, (output, reducer));
1341
1342 Ok(())
1343 }
1344}