1mod float_sum;
4pub(super) mod jobs;
5mod numeric;
6
7use super::distinct::DistinctKeys;
8use super::probe::{MemberProbe, probe_members};
9use super::{
10 Comparison, MAX_COMPARISON_KEY, MAX_DISTINCT_VALUES, MAX_STATE_BYTES, MAX_TERMS, Plan,
11 PlanOutput, Query, QueryPage, admit_ordered_fields, admit_output, admit_projection,
12 comparison_key, copy_projection, execute, projection_size,
13};
14use crate::{
15 Entity, EntitySchema, Error, FieldType, IndexValue, TypeSchema, Value, ValueSchema,
16 codec::Decoder, key,
17};
18use ic_storage::Memory;
19use std::collections::BTreeMap;
20
21const MAX_GROUPS: usize = 32;
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25#[repr(u8)]
26pub enum SummaryMeasure {
27 Count = 0,
29 Sum = 1,
31 Average = 2,
33}
34
35#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
37pub enum GroupOrder {
38 #[default]
40 Key,
41 AggregateAscending,
43 AggregateDescending,
45 KeyDescending,
47 FirstOccurrence,
49 Summary(SummaryMeasure, super::SortDirection),
51}
52
53struct GroupPredicate<T> {
54 measure: Option<SummaryMeasure>,
55 comparison: Comparison,
56 operand: T,
57 or_next: bool,
58}
59
60#[derive(Default)]
61pub(super) struct GroupRequest<'a> {
62 predicates: Vec<GroupPredicate<IndexValue<'a>>>,
63 order: Option<GroupOrder>,
64 page: Option<jobs::pages::PageRequest<'a>>,
65}
66impl GroupRequest<'_> {
67 pub(super) fn is_empty(&self) -> bool {
68 self.predicates.is_empty() && self.order.is_none() && self.page.is_none()
69 }
70
71 fn admit(
72 &self,
73 entity: &EntitySchema,
74 reducer: &Reducer,
75 summary_sum: Option<ValueSchema>,
76 ) -> Result<Selection, Error> {
77 if self
78 .page
79 .is_some_and(|page| !(1..=MAX_GROUPS).contains(&page.size))
80 {
81 return Err(Error::Limit);
82 }
83 let field = match reducer {
84 Reducer::Keys(_) => {
85 let order = self.order.unwrap_or_default();
86 if !self.predicates.is_empty()
87 || !matches!(
88 order,
89 GroupOrder::Key | GroupOrder::KeyDescending | GroupOrder::FirstOccurrence
90 )
91 {
92 return Err(Error::InvalidQuery);
93 }
94
95 return Ok(Selection {
96 predicates: Vec::new(),
97 order,
98 optional: false,
99 });
100 }
101 Reducer::Count { .. } | Reducer::Distinct { .. } => ValueSchema {
102 value: FieldType::Nat64,
103 optional: false,
104 },
105 Reducer::Extremum { position, .. } => {
106 let field = &entity.fields[*position];
107
108 ValueSchema {
109 value: field.value,
110 optional: field.optional,
111 }
112 }
113 Reducer::Numeric(state) => state.output(),
114 };
115 if self.order == Some(GroupOrder::FirstOccurrence) {
116 return Err(Error::InvalidQuery);
117 }
118 let absent_result = !matches!(reducer, Reducer::Count { .. } | Reducer::Distinct { .. });
120 let predicates = self
121 .predicates
122 .iter()
123 .map(
124 |&GroupPredicate {
125 comparison,
126 operand: value,
127 or_next,
128 measure,
129 }| {
130 let (field, absent_result) = match (measure, summary_sum) {
131 (None, None) => (field, absent_result),
132 (Some(SummaryMeasure::Count), Some(_)) => (
133 ValueSchema {
134 value: FieldType::Nat64,
135 optional: false,
136 },
137 false,
138 ),
139 (Some(SummaryMeasure::Sum), Some(sum)) => (sum, true),
140 (Some(SummaryMeasure::Average), Some(_)) => (field, true),
141 _ => return Err(Error::InvalidQuery),
142 };
143 if match value {
144 IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
145 IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
146 _ => false,
147 } {
148 return Err(Error::Limit);
149 }
150 comparison.admit(field.value, absent_result, value)?;
151 let key = if value == IndexValue::Absent {
152 None
153 } else {
154 let mut key = Vec::new();
155 value.append_component(field.optional, &mut key);
156 if key.len() > MAX_COMPARISON_KEY {
157 return Err(Error::Limit);
158 }
159
160 Some(key)
161 };
162
163 Ok(GroupPredicate {
164 measure,
165 comparison,
166 operand: key,
167 or_next,
168 })
169 },
170 )
171 .collect::<Result<_, Error>>()?;
172
173 Ok(Selection {
174 predicates,
175 order: self.order.unwrap_or_default(),
176 optional: field.optional,
177 })
178 }
179}
180
181struct Selection {
182 predicates: Vec<GroupPredicate<Option<Vec<u8>>>>,
183 order: GroupOrder,
184 optional: bool,
186}
187
188impl Selection {
189 fn needs_summary_key(&self, measure: SummaryMeasure) -> bool {
190 matches!(self.order, GroupOrder::Summary(ordered, _) if ordered == measure)
191 || self
192 .predicates
193 .iter()
194 .any(|term| term.measure == Some(measure))
195 }
196
197 fn accepts<'a>(&self, key: impl Fn(Option<SummaryMeasure>) -> Option<&'a [u8]>) -> bool {
198 self.predicates
199 .split_inclusive(|term| !term.or_next)
200 .all(|clause| {
201 clause.iter().any(|term| {
202 term.comparison.accepts(
203 key(term.measure),
204 term.operand.as_deref(),
205 self.optional && term.measure != Some(SummaryMeasure::Count),
206 )
207 })
208 })
209 }
210}
211
212#[derive(Debug)]
214pub struct Aggregate<T> {
215 pub value: T,
217 pub examined: usize,
219 pub fetched: usize,
221 pub output_bytes: usize,
223}
224
225#[derive(Debug)]
227pub struct GroupCount<K> {
228 pub key: K,
230 pub count: u64,
232}
233
234pub type GroupSummaries<K, S, A> = Aggregate<Vec<GroupSummary<K, S, A>>>;
236
237pub type GroupSummaryPage<K, S, A> = jobs::GroupPage<GroupSummary<K, S, A>>;
239
240#[derive(Debug)]
242pub struct GroupSummary<K, S, A> {
243 pub key: K,
245 pub count: u64,
247 pub sum: Option<S>,
249 pub average: Option<A>,
251}
252
253#[derive(Debug)]
255pub struct GroupValue<K, R> {
256 pub key: K,
258 pub value: Option<R>,
260}
261
262impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
263 #[must_use]
268 pub fn group_page(mut self, size: usize, after: Option<&'a jobs::GroupCursor>) -> Self {
269 self.request.groups.page = Some(jobs::pages::PageRequest { size, after });
270
271 self
272 }
273
274 #[must_use]
281 pub fn filter_groups(self, comparison: Comparison, value: impl Into<IndexValue<'a>>) -> Self {
282 self.add_group_clause(std::iter::once((None, comparison, value.into())))
283 }
284
285 #[must_use]
288 pub fn filter_summary(
289 self,
290 measure: SummaryMeasure,
291 comparison: Comparison,
292 value: impl Into<IndexValue<'a>>,
293 ) -> Self {
294 self.add_group_clause(std::iter::once((Some(measure), comparison, value.into())))
295 }
296
297 #[must_use]
301 pub fn filter_summary_any(
302 self,
303 alternatives: &[(SummaryMeasure, Comparison, IndexValue<'a>)],
304 ) -> Self {
305 self.add_group_clause(
306 alternatives
307 .iter()
308 .map(|&(measure, comparison, value)| (Some(measure), comparison, value)),
309 )
310 }
311
312 #[must_use]
319 pub fn filter_groups_any(self, alternatives: &[(Comparison, IndexValue<'a>)]) -> Self {
320 self.add_group_clause(
321 alternatives
322 .iter()
323 .map(|&(comparison, value)| (None, comparison, value)),
324 )
325 }
326
327 fn add_group_clause(
328 mut self,
329 terms: impl ExactSizeIterator<Item = (Option<SummaryMeasure>, Comparison, IndexValue<'a>)>,
330 ) -> Self {
331 let count = terms.len();
332 if count == 0 || count > MAX_TERMS - self.request.groups.predicates.len() {
333 self.request.over_limit = true;
334 } else {
335 self.request.groups.predicates.extend(terms.enumerate().map(
336 |(i, (measure, comparison, operand))| GroupPredicate {
337 measure,
338 comparison,
339 operand,
340 or_next: i + 1 != count,
341 },
342 ));
343 }
344
345 self
346 }
347
348 #[must_use]
351 pub fn order_groups(mut self, order: GroupOrder) -> Self {
352 self.request.groups.order = Some(order);
353
354 self
355 }
356
357 pub fn min<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
370 observe!(query, { self.extremum(false) })
371 }
372
373 pub fn max<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
380 observe!(query, { self.extremum(true) })
381 }
382
383 fn extremum<R: Value>(self, maximum: bool) -> Result<Aggregate<Option<R>>, Error> {
384 let (plan, reducer) = self.extremum_plan::<R>(maximum)?;
385
386 self.scalar_value(plan, reducer)
387 }
388
389 fn extremum_plan<R: Value>(&self, maximum: bool) -> Result<(Plan<'a>, Reducer), Error> {
390 let plan = self.aggregate_plan(Some(R::definition()), false)?;
391 let reducer = Reducer::extremum(
392 E::SCHEMA,
393 plan.projection.ok_or(Error::InvalidQuery)?,
394 maximum,
395 )?;
396
397 Ok((plan, reducer))
398 }
399
400 fn scalar_value<R: Value>(
401 self,
402 mut plan: Plan<'_>,
403 mut reducer: Reducer,
404 ) -> Result<Aggregate<Option<R>>, Error> {
405 super::order::select_unique_aggregate_path(E::SCHEMA, &self.request, &mut plan)?;
406 let page = execute(
407 &self.db.read()?.map,
408 E::SCHEMA,
409 &self.request,
410 &plan,
411 Some(Accumulator::Scalar(&mut reducer)),
412 )?;
413 let (value, output_bytes) = scalar_output(reducer, self.request.bytes)?;
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 group_output(
480 self.grouped(&plan, initial, None)?,
481 &self.request,
482 decode_group_value,
483 )
484 }
485
486 pub fn exists(self) -> Result<Aggregate<bool>, Error> {
500 observe!(query, {
501 let mut plan = self.count_plan(None)?;
502 self.select_aggregate_row_path(&mut plan, Some(MemberProbe::Exists))?;
503 if let Some(result) = probe_members(
504 &self.db,
505 E::SCHEMA,
506 &self.request,
507 &plan,
508 MemberProbe::Exists,
509 1,
510 )? {
511 return Ok(Aggregate {
512 value: result.value != 0,
513 examined: result.examined,
514 fetched: result.fetched,
515 output_bytes: 1,
516 });
517 }
518 let mut remaining = 1;
519 let page = execute(
520 &self.db.read()?.map,
521 E::SCHEMA,
522 &self.request,
523 &plan,
524 Some(Accumulator::Until(&mut remaining)),
525 )?;
526
527 Ok(Aggregate {
528 value: remaining == 0,
529 examined: page.examined,
530 fetched: page.fetched,
531 output_bytes: 1,
532 })
533 })
534 }
535
536 pub fn count(self) -> Result<Aggregate<u64>, Error> {
552 observe!(query, {
553 if self.request.bytes < 8 {
554 return Err(Error::RowTooLarge);
555 }
556 self.count_until(u64::MAX)
557 })
558 }
559
560 pub fn has_at_least(self, minimum: u64) -> Result<Aggregate<bool>, Error> {
567 observe!(query, {
568 let result = self.count_until(minimum)?;
569 Ok(Aggregate {
570 value: result.value >= minimum,
571 examined: result.examined,
572 fetched: result.fetched,
573 output_bytes: 1,
574 })
575 })
576 }
577
578 fn count_until(self, stop: u64) -> Result<Aggregate<u64>, Error> {
579 if self.request.is_plain_count() {
580 return self.entity_count();
581 }
582 let mut plan = self.count_plan(None)?;
583 if stop == 0 {
584 return Ok(Aggregate {
585 value: 0,
586 examined: 0,
587 fetched: 0,
588 output_bytes: 8,
589 });
590 }
591 if self.request.index.is_none()
592 && self
593 .request
594 .clauses()
595 .zip(plan.clauses())
596 .all(|(clause, terms)| {
597 clause.iter().zip(terms).any(|(p, term)| {
598 p.constant_comparison(E::SCHEMA) == Some(true)
599 || (term.tests_presence && E::SCHEMA.field_is_required(p.field))
600 })
601 })
602 {
603 return self.entity_count();
604 }
605 if let Some(count) = probe_members(
606 &self.db,
607 E::SCHEMA,
608 &self.request,
609 &plan,
610 MemberProbe::CountKeys,
611 stop,
612 )? {
613 return Ok(count);
614 }
615 if super::order::select_filtered_path(
616 E::SCHEMA,
617 &self.request,
618 &mut plan,
619 Some(MemberProbe::CountWithRows),
620 )? {
621 return self.count_keys(&plan, stop);
622 }
623 if let Some(count) = probe_members(
624 &self.db,
625 E::SCHEMA,
626 &self.request,
627 &plan,
628 MemberProbe::CountWithRows,
629 stop,
630 )? {
631 return Ok(count);
632 }
633 let mut remaining = stop;
634 let page = execute(
635 &self.db.read()?.map,
636 E::SCHEMA,
637 &self.request,
638 &plan,
639 Some(Accumulator::Until(&mut remaining)),
640 )?;
641 Ok(Aggregate {
642 value: stop - remaining,
643 examined: page.examined,
644 fetched: page.fetched,
645 output_bytes: 8,
646 })
647 }
648
649 fn entity_count(&self) -> Result<Aggregate<u64>, Error> {
650 Ok(Aggregate {
651 value: self.db.read()?.cardinality::<E>()?,
652 examined: 0,
653 fetched: 0,
654 output_bytes: 8,
655 })
656 }
657
658 pub fn count_validated(self) -> Result<Aggregate<u64>, Error> {
665 observe!(query, { self.scalar_count(None) })
666 }
667
668 pub fn count_index_entries(self) -> Result<Aggregate<u64>, Error> {
679 observe!(query, {
680 if self.request.index.is_none() || !self.request.predicates.is_empty() {
681 return Err(Error::InvalidQuery);
682 }
683 if self.request.bytes < 8 {
684 return Err(Error::RowTooLarge);
685 }
686 let plan = self.count_plan(None)?;
687
688 self.count_keys(&plan, u64::MAX)
689 })
690 }
691
692 fn count_keys(&self, plan: &Plan<'_>, stop: u64) -> Result<Aggregate<u64>, Error> {
693 let bounds = super::range::bounds(E::SCHEMA, &self.request, plan)?;
694 let mut examined = 0;
695 if let Some(range) = bounds {
696 let db = self.db.read()?;
697 if let Some(key) = super::range::exact_key(&range) {
698 examined = usize::from(db.map.contains_key(key));
699 } else {
700 let keys = db.map.keys_range((range.0.as_ref(), range.1.as_ref()));
701 for _ in keys {
702 if examined == self.request.work {
703 return Err(Error::Limit);
704 }
705 examined += 1;
706 if examined as u64 == stop {
707 break;
708 }
709 }
710 }
711 }
712
713 Ok(Aggregate {
714 value: examined as u64,
715 examined,
716 fetched: 0,
717 output_bytes: 8,
718 })
719 }
720
721 pub fn count_field(self, field: &str) -> Result<Aggregate<u64>, Error> {
729 observe!(query, { self.scalar_count(Some(field)) })
730 }
731
732 pub fn count_distinct<K: Value>(self) -> Result<Aggregate<u64>, Error> {
743 observe!(query, {
744 if self.request.bytes < 8 {
745 return Err(Error::RowTooLarge);
746 }
747 let mut plan = self.count_plan(Some(K::definition()))?;
748 self.select_aggregate_row_path(&mut plan, None)?;
749 let projected = plan.projection.ok_or(Error::InvalidQuery)?;
750 let fixed = super::distinct::fixed_fields(E::SCHEMA, &self.request, &plan);
751
752 self.scalar_count_value(&plan, Reducer::distinct(projected & !fixed))
753 })
754 }
755
756 fn select_aggregate_row_path(
757 &self,
758 plan: &mut Plan<'static>,
759 probe: Option<MemberProbe>,
760 ) -> Result<(), Error> {
761 if plan.index.is_none() {
762 super::order::select_filtered_path(E::SCHEMA, &self.request, plan, probe)?;
763 }
764
765 Ok(())
766 }
767
768 fn scalar_count(self, field: Option<&str>) -> Result<Aggregate<u64>, Error> {
769 if self.request.bytes < 8 {
770 return Err(Error::RowTooLarge);
771 }
772 let mut plan = self.count_plan(None)?;
773 let probe = field.is_none().then_some(MemberProbe::CountValidated);
774 self.select_aggregate_row_path(&mut plan, probe)?;
775 if let Some(probe) = probe
776 && let Some(count) =
777 probe_members(&self.db, E::SCHEMA, &self.request, &plan, probe, u64::MAX)?
778 {
779 return Ok(count);
780 }
781 let reducer = self.count_reducer(field)?;
782
783 self.scalar_count_value(&plan, reducer)
784 }
785
786 fn scalar_count_value(
787 self,
788 plan: &Plan<'_>,
789 mut reducer: Reducer,
790 ) -> Result<Aggregate<u64>, Error> {
791 let page = execute(
792 &self.db.read()?.map,
793 E::SCHEMA,
794 &self.request,
795 plan,
796 Some(Accumulator::Scalar(&mut reducer)),
797 )?;
798
799 Ok(Aggregate {
800 value: reducer.finish(false)?.into_count()?,
801 examined: page.examined,
802 fetched: page.fetched,
803 output_bytes: 8,
804 })
805 }
806
807 pub fn group_count<K: Value>(self) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
824 observe!(query, { self.group_counts(None) })
825 }
826
827 pub fn group_count_field<K: Value>(
836 self,
837 field: &str,
838 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
839 observe!(query, { self.group_counts(Some(field)) })
840 }
841
842 pub fn group_count_distinct<K: Value, R: Value>(
856 self,
857 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
858 observe!(query, {
859 let (plan, reducer) = self.group_distinct_plan::<K, R>()?;
860
861 self.group_count_values(plan, reducer)
862 })
863 }
864
865 fn group_distinct_plan<K: Value, R: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
866 let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
867 let operand = admit_projection(E::SCHEMA, R::definition())?;
868 admit_ordered_fields(E::SCHEMA, operand)?;
869 plan.selected |= operand;
870
871 Ok((plan, Reducer::distinct(operand)))
872 }
873
874 fn group_counts<K: Value>(
875 self,
876 field: Option<&str>,
877 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
878 let plan = self.aggregate_plan(Some(K::definition()), true)?;
879 let reducer = self.count_reducer(field)?;
880
881 self.group_count_values(plan, reducer)
882 }
883
884 fn group_count_values<K: Value>(
885 self,
886 mut plan: Plan<'static>,
887 mut reducer: Reducer,
888 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
889 self.select_aggregate_row_path(&mut plan, None)?;
890 if let Reducer::Distinct { mask, .. } = &mut reducer {
891 let grouped = plan.projection.ok_or(Error::InvalidQuery)?;
892 let fixed = super::distinct::fixed_fields(E::SCHEMA, &self.request, &plan);
893 *mask &= !(grouped | fixed);
894 }
895 group_output(
896 self.grouped(&plan, reducer, None)?,
897 &self.request,
898 decode_group_count,
899 )
900 }
901
902 fn count_reducer(&self, field: Option<&str>) -> Result<Reducer, Error> {
903 let presence = field
905 .map(|name| E::SCHEMA.field_position(name).ok_or(Error::InvalidQuery))
906 .transpose()?
907 .filter(|&i| E::SCHEMA.fields[i].optional);
908
909 Ok(Reducer::Count { presence, total: 0 })
910 }
911
912 fn grouped(
913 &self,
914 plan: &Plan<'_>,
915 initial: Reducer,
916 summary_sum: Option<ValueSchema>,
917 ) -> Result<(Groups, QueryPage<Vec<u8>>), Error> {
918 if self.request.groups.page.is_some() {
919 return Err(Error::InvalidQuery);
920 }
921 let mut groups = self
922 .request
923 .admit_groups(E::SCHEMA, plan, initial, summary_sum)?;
924 let page = execute(
925 &self.db.read()?.map,
926 E::SCHEMA,
927 &self.request,
928 plan,
929 Some(Accumulator::Groups(&mut groups)),
930 )?;
931
932 Ok((groups, page))
933 }
934
935 fn count_plan(&self, output: Option<&TypeSchema>) -> Result<Plan<'static>, Error> {
936 self.request
937 .aggregate_plan(&self.db, E::SCHEMA, output, PlanOutput::ImmediateCount)
938 }
939
940 fn aggregate_plan(
941 &self,
942 output: Option<&TypeSchema>,
943 group_output: bool,
944 ) -> Result<Plan<'static>, Error> {
945 self.request.aggregate_plan(
946 &self.db,
947 E::SCHEMA,
948 output,
949 PlanOutput::Aggregate {
950 grouped: group_output,
951 },
952 )
953 }
954}
955
956impl super::Request<'_> {
957 fn is_plain_count(&self) -> bool {
960 matches!(self, Self {
961 predicates,
962 groups,
963 index: None,
964 order: None,
965 order_descending: 0,
966 descending: false,
967 distinct: false,
968 cursor: None,
969 single_result_probe: None,
970 rows: _, work: _, bytes: _, over_limit: _,
971 } if predicates.is_empty() && groups.is_empty() && self.within_limits())
972 }
973
974 fn admit_groups(
975 &self,
976 entity: &EntitySchema,
977 plan: &Plan<'_>,
978 initial: Reducer,
979 summary_sum: Option<ValueSchema>,
980 ) -> Result<Groups, Error> {
981 if summary_sum.is_none() && matches!(self.groups.order, Some(GroupOrder::Summary(..))) {
982 return Err(Error::InvalidQuery);
983 }
984 Ok(Groups {
985 selection: self.groups.admit(entity, &initial, summary_sum)?,
986 summary_sum,
987 mask: plan.projection.ok_or(Error::InvalidQuery)?,
988 initial,
989 rows: BTreeMap::new(),
990 state_bytes: 0,
991 })
992 }
993
994 fn aggregate_plan<M: Memory>(
995 &self,
996 source: &super::QuerySource<'_, M>,
997 entity: &'static EntitySchema,
998 output: Option<&TypeSchema>,
999 kind: PlanOutput,
1000 ) -> Result<Plan<'static>, Error> {
1001 if self.cursor.is_some()
1002 || self.distinct
1003 || ((self.order.is_some() || self.descending)
1004 && self.groups.order != Some(GroupOrder::FirstOccurrence))
1005 {
1006 return Err(Error::InvalidQuery);
1007 }
1008 let db = source.read()?;
1009 db.schema.admits(entity)?;
1010 let mut plan = Plan::admit(
1011 entity,
1012 self,
1013 db.schema.fingerprint(),
1014 db.incarnation,
1015 output.map(super::Projection::Record),
1016 kind,
1017 )?;
1018 if let Some(mask) = plan.projection {
1019 admit_ordered_fields(entity, mask)?;
1020 plan.selected |= mask;
1021 }
1022
1023 Ok(plan)
1024 }
1025}
1026
1027fn scalar_output<R: Value>(reducer: Reducer, limit: usize) -> Result<(Option<R>, usize), Error> {
1028 let Some(bytes) = reducer.finish(false)?.into_value()? else {
1029 return Ok((None, 0));
1030 };
1031 let mut used = 0;
1032 admit_output(bytes.len(), limit, &mut used)?;
1033
1034 Ok((Some(decode_record(&bytes)?), used))
1035}
1036
1037fn group_output<T>(
1038 (groups, page): (Groups, QueryPage<Vec<u8>>),
1039 request: &super::Request<'_>,
1040 decode: fn(&[u8], Completed) -> Result<T, Error>,
1041) -> Result<Aggregate<Vec<T>>, Error> {
1042 let mut output_bytes = 0;
1043 let value = groups
1044 .into_output(request.rows)?
1045 .into_iter()
1046 .map(|(key, result)| {
1047 admit_output(
1048 key.len() + result.encoded_len(),
1049 request.bytes,
1050 &mut output_bytes,
1051 )?;
1052
1053 decode(&key, result)
1054 })
1055 .collect::<Result<_, Error>>()?;
1056
1057 Ok(Aggregate {
1058 value,
1059 examined: page.examined,
1060 fetched: page.fetched,
1061 output_bytes,
1062 })
1063}
1064
1065fn decode_group_count<K: Value>(key: &[u8], result: Completed) -> Result<GroupCount<K>, Error> {
1066 Ok(GroupCount {
1067 key: decode_record(key)?,
1068 count: result.into_count()?,
1069 })
1070}
1071
1072fn decode_group_value<K: Value, R: Value>(
1073 key: &[u8],
1074 result: Completed,
1075) -> Result<GroupValue<K, R>, Error> {
1076 let value = result.into_value()?;
1077
1078 Ok(GroupValue {
1079 key: decode_record(key)?,
1080 value: value.as_deref().map(decode_record).transpose()?,
1081 })
1082}
1083
1084fn decode_record<R: Value>(bytes: &[u8]) -> Result<R, Error> {
1085 let mut reader = Decoder::new(bytes)?;
1086 let value = R::decode_from(&mut reader)?;
1087 reader.finish()?;
1088
1089 Ok(value)
1090}
1091
1092pub(super) enum Accumulator<'a> {
1094 Until(&'a mut u64),
1096 Scalar(&'a mut Reducer),
1097 Groups(&'a mut Groups),
1098}
1099impl Accumulator<'_> {
1100 pub(super) fn needs_spans(&self) -> bool {
1101 !matches!(
1102 self,
1103 Self::Until(_)
1104 | Self::Scalar(
1105 Reducer::Numeric(_)
1106 | Reducer::Count { presence: None, .. }
1107 | Reducer::Distinct { .. }
1108 )
1109 )
1110 }
1111
1112 pub(super) fn push(
1113 &mut self,
1114 entity: &EntitySchema,
1115 values: &[IndexValue<'_>],
1116 bytes: &[u8],
1117 spans: &[(u16, u16)],
1118 scratch: &mut Vec<u8>,
1119 ) -> Result<(), Error> {
1120 match self {
1121 Self::Until(remaining) => {
1122 **remaining -= 1;
1123
1124 Ok(())
1125 }
1126 Self::Scalar(state) => {
1127 state.push(entity, values, bytes, spans, scratch, MAX_STATE_BYTES)
1128 }
1129 Self::Groups(state) => state.push(entity, values, bytes, spans, scratch),
1130 }
1131 }
1132}
1133
1134#[derive(Clone)]
1135pub(super) enum Reducer {
1136 Keys(u8),
1137 Numeric(numeric::NumericAggregate),
1138 Distinct {
1139 mask: u32,
1140 seen: DistinctKeys,
1141 key_bytes: usize,
1142 },
1143 Count {
1144 presence: Option<usize>,
1145 total: u64,
1146 },
1147 Extremum {
1148 position: usize,
1149 maximum: bool,
1150 selected: Option<(Vec<u8>, Vec<u8>)>,
1151 },
1152}
1153impl Reducer {
1154 fn distinct(mask: u32) -> Self {
1155 Self::Distinct {
1156 mask,
1157 seen: DistinctKeys::new(),
1158 key_bytes: 0,
1159 }
1160 }
1161
1162 fn extremum(entity: &EntitySchema, mask: u32, maximum: bool) -> Result<Self, Error> {
1163 if mask.count_ones() != 1 {
1164 return Err(Error::InvalidQuery);
1165 }
1166 let position = mask.trailing_zeros() as usize;
1167 if !key::supports(entity.fields[position].value) {
1168 return Err(Error::InvalidQuery);
1169 }
1170
1171 Ok(Self::Extremum {
1172 position,
1173 maximum,
1174 selected: None,
1175 })
1176 }
1177
1178 fn retained_bytes(&self) -> usize {
1179 match self {
1180 Self::Keys(_) => 0,
1181 Self::Numeric(state) => state.retained_bytes(),
1182 Self::Count { .. } => 8,
1183 Self::Distinct { key_bytes, .. } => 8 + key_bytes,
1184 Self::Extremum { selected, .. } => selected
1185 .as_ref()
1186 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
1187 }
1188 }
1189
1190 fn finish(self, needs_numeric_key: bool) -> Result<Completed, Error> {
1191 match self {
1192 Self::Keys(_) => Ok(Completed::Key),
1193 Self::Count { total, .. } => Ok(Completed::Count(total)),
1194 Self::Distinct { seen, .. } => Ok(Completed::Count(seen.len() as u64)),
1195 Self::Extremum { selected, .. } => Ok(Completed::Value(selected)),
1196 Self::Numeric(state) => state.finish(needs_numeric_key),
1197 }
1198 }
1199
1200 fn push(
1201 &mut self,
1202 entity: &EntitySchema,
1203 values: &[IndexValue<'_>],
1204 bytes: &[u8],
1205 spans: &[(u16, u16)],
1206 scratch: &mut Vec<u8>,
1207 allowance: usize,
1208 ) -> Result<(), Error> {
1209 match self {
1210 Self::Keys(_) => {}
1211 Self::Numeric(state) => state.push(values)?,
1212 Self::Distinct {
1213 mask,
1214 seen,
1215 key_bytes,
1216 } => {
1217 comparison_key(entity, *mask, values, scratch)?;
1218 if let Err(position) =
1219 seen.binary_search_by(|key| key.as_ref().cmp(scratch.as_slice()))
1220 {
1221 let size = scratch.len();
1222 if seen.len() == MAX_DISTINCT_VALUES || 8 + *key_bytes + size > allowance {
1223 return Err(Error::Limit);
1224 }
1225 seen.insert(position, Box::from(scratch.as_slice()));
1226 *key_bytes += size;
1227 }
1228 }
1229 Self::Count { presence, total } => {
1230 *total += u64::from(presence.is_none_or(|i| bytes[usize::from(spans[i].0)] != 0));
1231 }
1232 Self::Extremum {
1233 position,
1234 maximum,
1235 selected,
1236 } => {
1237 let value = values[*position];
1238 if value == IndexValue::Absent {
1239 return Ok(());
1240 }
1241 scratch.clear();
1242 value.append_component(entity.fields[*position].optional, scratch);
1243 if scratch.len() > MAX_COMPARISON_KEY {
1244 return Err(Error::Limit);
1245 }
1246 if selected.as_ref().is_none_or(|(old, _)| {
1247 if *maximum {
1248 scratch.as_slice() > old.as_slice()
1249 } else {
1250 scratch.as_slice() < old.as_slice()
1251 }
1252 }) {
1253 let (start, end) = spans[*position];
1254 let output = &bytes[usize::from(start)..usize::from(end)];
1255 if let Some((old_key, old_output)) = selected
1256 && old_key.len() == scratch.len()
1257 && old_output.len() == output.len()
1258 {
1259 old_key.copy_from_slice(scratch);
1261 old_output.copy_from_slice(output);
1262 return Ok(());
1263 }
1264 if scratch.len() + output.len() > allowance {
1265 return Err(Error::Limit);
1266 }
1267 let key = scratch.as_slice().to_vec();
1269 let output = output.to_vec();
1270 if key.capacity() + output.capacity() > allowance {
1271 return Err(Error::Limit);
1272 }
1273 *selected = Some((key, output));
1274 }
1275 }
1276 }
1277
1278 Ok(())
1279 }
1280}
1281
1282enum Completed {
1284 Summary {
1285 count: u64,
1286 sum: Option<Box<[u8]>>,
1287 average: Option<Box<[u8]>>,
1288 sort_key: Option<Box<[u8]>>,
1289 },
1290 Key,
1291 Count(u64),
1292 Value(Option<(Vec<u8>, Vec<u8>)>),
1293}
1294impl Completed {
1295 fn encoded_len(&self) -> usize {
1296 match self {
1297 Self::Summary { sum, average, .. } => {
1298 8 + sum.as_deref().map_or(0, <[u8]>::len)
1299 + average.as_deref().map_or(0, <[u8]>::len)
1300 }
1301 Self::Key => 0,
1302 Self::Count(_) => 8,
1303 Self::Value(value) => value.as_ref().map_or(0, |(_, bytes)| bytes.len()),
1304 }
1305 }
1306 fn result_key<'a>(&'a self, scratch: &'a mut [u8; 8]) -> Option<&'a [u8]> {
1308 match self {
1309 Self::Summary { sort_key, .. } => sort_key.as_deref(),
1310 Self::Key => None,
1311 Self::Count(total) => {
1312 *scratch = total.to_be_bytes();
1313
1314 Some(scratch)
1315 }
1316 Self::Value(selected) => selected.as_ref().map(|(key, _)| key.as_slice()),
1317 }
1318 }
1319
1320 fn retained_bytes(&self) -> usize {
1321 match self {
1322 Self::Summary { sort_key, .. } => {
1323 self.encoded_len() + sort_key.as_deref().map_or(0, <[u8]>::len)
1324 }
1325 Self::Key => 0,
1326 Self::Count(_) => 8,
1327 Self::Value(value) => value
1328 .as_ref()
1329 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
1330 }
1331 }
1332
1333 fn into_count(self) -> Result<u64, Error> {
1334 match self {
1335 Self::Count(count) => Ok(count),
1336 _ => Err(Error::Corrupt),
1337 }
1338 }
1339
1340 fn into_value(self) -> Result<Option<Vec<u8>>, Error> {
1341 match self {
1342 Self::Value(value) => Ok(value.map(|(_, bytes)| bytes)),
1343 _ => Err(Error::Corrupt),
1344 }
1345 }
1346}
1347
1348pub(super) struct Groups {
1349 summary_sum: Option<ValueSchema>,
1350 selection: Selection,
1351 mask: u32,
1352 initial: Reducer,
1354 rows: BTreeMap<Box<[u8]>, (Vec<u8>, Reducer)>,
1355 state_bytes: usize,
1356}
1357impl Groups {
1358 fn max_keys(&self) -> usize {
1359 if matches!(self.initial, Reducer::Keys(_)) {
1360 usize::from(u8::MAX)
1361 } else {
1362 MAX_GROUPS
1363 }
1364 }
1365
1366 fn first_occurrences(&self) -> Result<Vec<&[u8]>, Error> {
1368 let mut ordered = vec![&[][..]; self.rows.len()];
1369 for (bytes, reducer) in self.rows.values() {
1370 let Reducer::Keys(position) = reducer else {
1371 return Err(Error::Corrupt);
1372 };
1373 ordered[usize::from(*position)] = bytes;
1374 }
1375 Ok(ordered)
1376 }
1377
1378 fn into_output(self, limit: usize) -> Result<Vec<(Vec<u8>, Completed)>, Error> {
1379 let mut state_bytes = self.state_bytes;
1381 let key_order = matches!(
1382 self.selection.order,
1383 GroupOrder::Key | GroupOrder::KeyDescending
1384 );
1385 let bounded_rank = !key_order && limit < self.rows.len();
1386 let compare = |a: &Completed, b: &Completed| {
1387 let (mut sa, mut sb) = ([0; 8], [0; 8]);
1388 let order = match (self.selection.order, a, b) {
1389 (
1390 GroupOrder::Summary(SummaryMeasure::Count, _),
1391 Completed::Summary { count: left, .. },
1392 Completed::Summary { count: right, .. },
1393 ) => left.cmp(right),
1394 _ => a.result_key(&mut sa).cmp(&b.result_key(&mut sb)),
1395 };
1396 if matches!(
1397 self.selection.order,
1398 GroupOrder::AggregateDescending
1399 | GroupOrder::Summary(_, super::SortDirection::Descending)
1400 ) {
1401 order.reverse()
1402 } else {
1403 order
1404 }
1405 };
1406 let retain = limit.min(self.rows.len());
1407 let mut rows = Vec::with_capacity(retain);
1408 let mut oldest = 0;
1409 let needs_value_key = !self.selection.predicates.is_empty()
1410 || matches!(
1411 self.selection.order,
1412 GroupOrder::AggregateAscending | GroupOrder::AggregateDescending
1413 );
1414 for (record, reducer) in self.rows.into_values() {
1415 let previous = reducer.retained_bytes();
1416 let (result, accepted) = if let Some(sum) = self.summary_sum {
1417 let Reducer::Numeric(state) = reducer else {
1418 return Err(Error::Corrupt);
1419 };
1420 state.finish_summary(sum, &self.selection)?
1421 } else {
1422 let result = reducer.finish(needs_value_key)?;
1423 let mut scratch = [0; 8];
1424 let key = result.result_key(&mut scratch);
1425 let accepted = self.selection.accepts(|_| key);
1426 (result, accepted)
1427 };
1428 state_bytes = state_bytes - previous + result.retained_bytes();
1429 if state_bytes > MAX_STATE_BYTES {
1430 return Err(Error::Limit);
1431 }
1432 if accepted {
1433 if bounded_rank {
1434 let position =
1436 rows.partition_point(|(_, value)| !compare(value, &result).is_gt());
1437 if position < retain {
1438 if rows.len() == retain {
1439 rows.pop();
1440 }
1441 rows.insert(position, (record, result));
1442 }
1443 } else if rows.len() < retain {
1444 rows.push((record, result));
1445 } else if self.selection.order == GroupOrder::KeyDescending {
1446 rows[oldest] = (record, result);
1448 oldest = (oldest + 1) % retain;
1449 }
1450 }
1451 }
1452 if self.selection.order == GroupOrder::KeyDescending {
1453 rows.rotate_left(oldest);
1454 rows.reverse();
1455 } else if !key_order && !bounded_rank {
1456 rows.sort_by(|(_, a), (_, b)| compare(a, b));
1458 }
1459
1460 Ok(rows)
1461 }
1462
1463 fn push(
1464 &mut self,
1465 entity: &EntitySchema,
1466 values: &[IndexValue<'_>],
1467 bytes: &[u8],
1468 spans: &[(u16, u16)],
1469 scratch: &mut Vec<u8>,
1470 ) -> Result<(), Error> {
1471 comparison_key(entity, self.mask, values, scratch)?;
1472 let available = MAX_STATE_BYTES - self.state_bytes;
1473 if let Some((_, reducer)) = self.rows.get_mut(scratch.as_slice()) {
1474 let previous = reducer.retained_bytes();
1475 reducer.push(entity, values, bytes, spans, scratch, available + previous)?;
1476 self.state_bytes = self.state_bytes - previous + reducer.retained_bytes();
1477 return Ok(());
1478 }
1479
1480 let count = self.rows.len();
1481 let size = projection_size(spans, self.mask);
1482 let base = scratch.len() + size;
1483 if count == self.max_keys() || base + self.initial.retained_bytes() > available {
1484 return Err(Error::Limit);
1485 }
1486 let key = Box::<[u8]>::from(scratch.as_slice());
1488 let mut reducer = self.initial.clone();
1489 if let Reducer::Keys(position) = &mut reducer {
1490 *position = count as u8;
1491 }
1492 reducer.push(entity, values, bytes, spans, scratch, available - base)?;
1493 let output = copy_projection(bytes, spans, self.mask, size);
1494 let retained = key.len() + output.capacity() + reducer.retained_bytes();
1497 if retained > available {
1498 return Err(Error::Limit);
1499 }
1500 self.state_bytes += retained;
1501 self.rows.insert(key, (output, reducer));
1502
1503 Ok(())
1504 }
1505}