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, Query,
11 QueryPage, admit_ordered_fields, admit_output, admit_projection, comparison_key,
12 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.aggregate_plan(None, false)?;
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.aggregate_plan(None, false)?;
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.aggregate_plan(None, false)?;
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 let entries = db.map.range((range.0.as_ref(), range.1.as_ref()));
698 for _ in entries {
699 if examined == self.request.work {
700 return Err(Error::Limit);
701 }
702 examined += 1;
703 if examined as u64 == stop {
704 break;
705 }
706 }
707 }
708
709 Ok(Aggregate {
710 value: examined as u64,
711 examined,
712 fetched: 0,
713 output_bytes: 8,
714 })
715 }
716
717 pub fn count_field(self, field: &str) -> Result<Aggregate<u64>, Error> {
725 observe!(query, { self.scalar_count(Some(field)) })
726 }
727
728 pub fn count_distinct<K: Value>(self) -> Result<Aggregate<u64>, Error> {
739 observe!(query, {
740 if self.request.bytes < 8 {
741 return Err(Error::RowTooLarge);
742 }
743 let mut plan = self.aggregate_plan(Some(K::definition()), false)?;
744 self.select_aggregate_row_path(&mut plan, None)?;
745 let projected = plan.projection.ok_or(Error::InvalidQuery)?;
746 let fixed = super::distinct::fixed_fields(E::SCHEMA, &self.request, &plan);
747
748 self.scalar_count_value(&plan, Reducer::distinct(projected & !fixed))
749 })
750 }
751
752 fn select_aggregate_row_path(
753 &self,
754 plan: &mut Plan<'static>,
755 probe: Option<MemberProbe>,
756 ) -> Result<(), Error> {
757 if plan.index.is_none() {
758 super::order::select_filtered_path(E::SCHEMA, &self.request, plan, probe)?;
759 }
760
761 Ok(())
762 }
763
764 fn scalar_count(self, field: Option<&str>) -> Result<Aggregate<u64>, Error> {
765 if self.request.bytes < 8 {
766 return Err(Error::RowTooLarge);
767 }
768 let mut plan = self.aggregate_plan(None, false)?;
769 let probe = field.is_none().then_some(MemberProbe::CountValidated);
770 self.select_aggregate_row_path(&mut plan, probe)?;
771 if let Some(probe) = probe
772 && let Some(count) =
773 probe_members(&self.db, E::SCHEMA, &self.request, &plan, probe, u64::MAX)?
774 {
775 return Ok(count);
776 }
777 let reducer = self.count_reducer(field)?;
778
779 self.scalar_count_value(&plan, reducer)
780 }
781
782 fn scalar_count_value(
783 self,
784 plan: &Plan<'_>,
785 mut reducer: Reducer,
786 ) -> Result<Aggregate<u64>, Error> {
787 let page = execute(
788 &self.db.read()?.map,
789 E::SCHEMA,
790 &self.request,
791 plan,
792 Some(Accumulator::Scalar(&mut reducer)),
793 )?;
794
795 Ok(Aggregate {
796 value: reducer.finish(false)?.into_count()?,
797 examined: page.examined,
798 fetched: page.fetched,
799 output_bytes: 8,
800 })
801 }
802
803 pub fn group_count<K: Value>(self) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
820 observe!(query, { self.group_counts(None) })
821 }
822
823 pub fn group_count_field<K: Value>(
832 self,
833 field: &str,
834 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
835 observe!(query, { self.group_counts(Some(field)) })
836 }
837
838 pub fn group_count_distinct<K: Value, R: Value>(
852 self,
853 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
854 observe!(query, {
855 let (plan, reducer) = self.group_distinct_plan::<K, R>()?;
856
857 self.group_count_values(plan, reducer)
858 })
859 }
860
861 fn group_distinct_plan<K: Value, R: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
862 let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
863 let operand = admit_projection(E::SCHEMA, R::definition())?;
864 admit_ordered_fields(E::SCHEMA, operand)?;
865 plan.selected |= operand;
866
867 Ok((plan, Reducer::distinct(operand)))
868 }
869
870 fn group_counts<K: Value>(
871 self,
872 field: Option<&str>,
873 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
874 let plan = self.aggregate_plan(Some(K::definition()), true)?;
875 let reducer = self.count_reducer(field)?;
876
877 self.group_count_values(plan, reducer)
878 }
879
880 fn group_count_values<K: Value>(
881 self,
882 mut plan: Plan<'static>,
883 mut reducer: Reducer,
884 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
885 self.select_aggregate_row_path(&mut plan, None)?;
886 if let Reducer::Distinct { mask, .. } = &mut reducer {
887 let grouped = plan.projection.ok_or(Error::InvalidQuery)?;
888 let fixed = super::distinct::fixed_fields(E::SCHEMA, &self.request, &plan);
889 *mask &= !(grouped | fixed);
890 }
891 group_output(
892 self.grouped(&plan, reducer, None)?,
893 &self.request,
894 decode_group_count,
895 )
896 }
897
898 fn count_reducer(&self, field: Option<&str>) -> Result<Reducer, Error> {
899 let presence = field
901 .map(|name| E::SCHEMA.field_position(name).ok_or(Error::InvalidQuery))
902 .transpose()?
903 .filter(|&i| E::SCHEMA.fields[i].optional);
904
905 Ok(Reducer::Count { presence, total: 0 })
906 }
907
908 fn grouped(
909 &self,
910 plan: &Plan<'_>,
911 initial: Reducer,
912 summary_sum: Option<ValueSchema>,
913 ) -> Result<(Groups, QueryPage<Vec<u8>>), Error> {
914 if self.request.groups.page.is_some() {
915 return Err(Error::InvalidQuery);
916 }
917 let mut groups = self
918 .request
919 .admit_groups(E::SCHEMA, plan, initial, summary_sum)?;
920 let page = execute(
921 &self.db.read()?.map,
922 E::SCHEMA,
923 &self.request,
924 plan,
925 Some(Accumulator::Groups(&mut groups)),
926 )?;
927
928 Ok((groups, page))
929 }
930
931 fn aggregate_plan(
932 &self,
933 output: Option<&TypeSchema>,
934 group_output: bool,
935 ) -> Result<Plan<'static>, Error> {
936 self.request
937 .aggregate_plan(&self.db, E::SCHEMA, output, group_output)
938 }
939}
940
941impl super::Request<'_> {
942 fn is_plain_count(&self) -> bool {
945 matches!(self, Self {
946 predicates,
947 groups,
948 index: None,
949 order: None,
950 order_descending: 0,
951 descending: false,
952 distinct: false,
953 cursor: None,
954 single_result_probe: None,
955 rows: _, work: _, bytes: _, over_limit: _,
956 } if predicates.is_empty() && groups.is_empty() && self.within_limits())
957 }
958
959 fn admit_groups(
960 &self,
961 entity: &EntitySchema,
962 plan: &Plan<'_>,
963 initial: Reducer,
964 summary_sum: Option<ValueSchema>,
965 ) -> Result<Groups, Error> {
966 if summary_sum.is_none() && matches!(self.groups.order, Some(GroupOrder::Summary(..))) {
967 return Err(Error::InvalidQuery);
968 }
969 Ok(Groups {
970 selection: self.groups.admit(entity, &initial, summary_sum)?,
971 summary_sum,
972 mask: plan.projection.ok_or(Error::InvalidQuery)?,
973 initial,
974 rows: BTreeMap::new(),
975 state_bytes: 0,
976 })
977 }
978
979 fn aggregate_plan<M: Memory>(
980 &self,
981 source: &super::QuerySource<'_, M>,
982 entity: &'static EntitySchema,
983 output: Option<&TypeSchema>,
984 group_output: bool,
985 ) -> Result<Plan<'static>, Error> {
986 if self.cursor.is_some()
987 || self.distinct
988 || ((self.order.is_some() || self.descending)
989 && self.groups.order != Some(GroupOrder::FirstOccurrence))
990 {
991 return Err(Error::InvalidQuery);
992 }
993 let db = source.read()?;
994 db.schema.admits(entity)?;
995 let mut plan = Plan::admit(
996 entity,
997 self,
998 db.schema.fingerprint(),
999 db.incarnation,
1000 output.map(super::Projection::Record),
1001 super::PlanOutput::Aggregate {
1002 grouped: group_output,
1003 },
1004 )?;
1005 if let Some(mask) = plan.projection {
1006 admit_ordered_fields(entity, mask)?;
1007 plan.selected |= mask;
1008 }
1009
1010 Ok(plan)
1011 }
1012}
1013
1014fn scalar_output<R: Value>(reducer: Reducer, limit: usize) -> Result<(Option<R>, usize), Error> {
1015 let Some(bytes) = reducer.finish(false)?.into_value()? else {
1016 return Ok((None, 0));
1017 };
1018 let mut used = 0;
1019 admit_output(bytes.len(), limit, &mut used)?;
1020
1021 Ok((Some(decode_record(&bytes)?), used))
1022}
1023
1024fn group_output<T>(
1025 (groups, page): (Groups, QueryPage<Vec<u8>>),
1026 request: &super::Request<'_>,
1027 decode: fn(&[u8], Completed) -> Result<T, Error>,
1028) -> Result<Aggregate<Vec<T>>, Error> {
1029 let mut output_bytes = 0;
1030 let value = groups
1031 .into_output(request.rows)?
1032 .into_iter()
1033 .map(|(key, result)| {
1034 admit_output(
1035 key.len() + result.encoded_len(),
1036 request.bytes,
1037 &mut output_bytes,
1038 )?;
1039
1040 decode(&key, result)
1041 })
1042 .collect::<Result<_, Error>>()?;
1043
1044 Ok(Aggregate {
1045 value,
1046 examined: page.examined,
1047 fetched: page.fetched,
1048 output_bytes,
1049 })
1050}
1051
1052fn decode_group_count<K: Value>(key: &[u8], result: Completed) -> Result<GroupCount<K>, Error> {
1053 Ok(GroupCount {
1054 key: decode_record(key)?,
1055 count: result.into_count()?,
1056 })
1057}
1058
1059fn decode_group_value<K: Value, R: Value>(
1060 key: &[u8],
1061 result: Completed,
1062) -> Result<GroupValue<K, R>, Error> {
1063 let value = result.into_value()?;
1064
1065 Ok(GroupValue {
1066 key: decode_record(key)?,
1067 value: value.as_deref().map(decode_record).transpose()?,
1068 })
1069}
1070
1071fn decode_record<R: Value>(bytes: &[u8]) -> Result<R, Error> {
1072 let mut reader = Decoder::new(bytes)?;
1073 let value = R::decode_from(&mut reader)?;
1074 reader.finish()?;
1075
1076 Ok(value)
1077}
1078
1079pub(super) enum Accumulator<'a> {
1081 Until(&'a mut u64),
1083 Scalar(&'a mut Reducer),
1084 Groups(&'a mut Groups),
1085}
1086impl Accumulator<'_> {
1087 pub(super) fn needs_spans(&self) -> bool {
1088 !matches!(
1089 self,
1090 Self::Until(_)
1091 | Self::Scalar(
1092 Reducer::Numeric(_)
1093 | Reducer::Count { presence: None, .. }
1094 | Reducer::Distinct { .. }
1095 )
1096 )
1097 }
1098
1099 pub(super) fn push(
1100 &mut self,
1101 entity: &EntitySchema,
1102 values: &[IndexValue<'_>],
1103 bytes: &[u8],
1104 spans: &[(u16, u16)],
1105 scratch: &mut Vec<u8>,
1106 ) -> Result<(), Error> {
1107 match self {
1108 Self::Until(remaining) => {
1109 **remaining -= 1;
1110
1111 Ok(())
1112 }
1113 Self::Scalar(state) => {
1114 state.push(entity, values, bytes, spans, scratch, MAX_STATE_BYTES)
1115 }
1116 Self::Groups(state) => state.push(entity, values, bytes, spans, scratch),
1117 }
1118 }
1119}
1120
1121#[derive(Clone)]
1122pub(super) enum Reducer {
1123 Keys(u8),
1124 Numeric(numeric::NumericAggregate),
1125 Distinct {
1126 mask: u32,
1127 seen: DistinctKeys,
1128 key_bytes: usize,
1129 },
1130 Count {
1131 presence: Option<usize>,
1132 total: u64,
1133 },
1134 Extremum {
1135 position: usize,
1136 maximum: bool,
1137 selected: Option<(Vec<u8>, Vec<u8>)>,
1138 },
1139}
1140impl Reducer {
1141 fn distinct(mask: u32) -> Self {
1142 Self::Distinct {
1143 mask,
1144 seen: DistinctKeys::new(),
1145 key_bytes: 0,
1146 }
1147 }
1148
1149 fn extremum(entity: &EntitySchema, mask: u32, maximum: bool) -> Result<Self, Error> {
1150 if mask.count_ones() != 1 {
1151 return Err(Error::InvalidQuery);
1152 }
1153 let position = mask.trailing_zeros() as usize;
1154 if !key::supports(entity.fields[position].value) {
1155 return Err(Error::InvalidQuery);
1156 }
1157
1158 Ok(Self::Extremum {
1159 position,
1160 maximum,
1161 selected: None,
1162 })
1163 }
1164
1165 fn retained_bytes(&self) -> usize {
1166 match self {
1167 Self::Keys(_) => 0,
1168 Self::Numeric(state) => state.retained_bytes(),
1169 Self::Count { .. } => 8,
1170 Self::Distinct { key_bytes, .. } => 8 + key_bytes,
1171 Self::Extremum { selected, .. } => selected
1172 .as_ref()
1173 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
1174 }
1175 }
1176
1177 fn finish(self, needs_numeric_key: bool) -> Result<Completed, Error> {
1178 match self {
1179 Self::Keys(_) => Ok(Completed::Key),
1180 Self::Count { total, .. } => Ok(Completed::Count(total)),
1181 Self::Distinct { seen, .. } => Ok(Completed::Count(seen.len() as u64)),
1182 Self::Extremum { selected, .. } => Ok(Completed::Value(selected)),
1183 Self::Numeric(state) => state.finish(needs_numeric_key),
1184 }
1185 }
1186
1187 fn push(
1188 &mut self,
1189 entity: &EntitySchema,
1190 values: &[IndexValue<'_>],
1191 bytes: &[u8],
1192 spans: &[(u16, u16)],
1193 scratch: &mut Vec<u8>,
1194 allowance: usize,
1195 ) -> Result<(), Error> {
1196 match self {
1197 Self::Keys(_) => {}
1198 Self::Numeric(state) => state.push(values)?,
1199 Self::Distinct {
1200 mask,
1201 seen,
1202 key_bytes,
1203 } => {
1204 comparison_key(entity, *mask, values, scratch)?;
1205 if let Err(position) =
1206 seen.binary_search_by(|key| key.as_ref().cmp(scratch.as_slice()))
1207 {
1208 let size = scratch.len();
1209 if seen.len() == MAX_DISTINCT_VALUES || 8 + *key_bytes + size > allowance {
1210 return Err(Error::Limit);
1211 }
1212 seen.insert(position, Box::from(scratch.as_slice()));
1213 *key_bytes += size;
1214 }
1215 }
1216 Self::Count { presence, total } => {
1217 *total += u64::from(presence.is_none_or(|i| bytes[usize::from(spans[i].0)] != 0));
1218 }
1219 Self::Extremum {
1220 position,
1221 maximum,
1222 selected,
1223 } => {
1224 let value = values[*position];
1225 if value == IndexValue::Absent {
1226 return Ok(());
1227 }
1228 scratch.clear();
1229 value.append_component(entity.fields[*position].optional, scratch);
1230 if scratch.len() > MAX_COMPARISON_KEY {
1231 return Err(Error::Limit);
1232 }
1233 if selected.as_ref().is_none_or(|(old, _)| {
1234 if *maximum {
1235 scratch.as_slice() > old.as_slice()
1236 } else {
1237 scratch.as_slice() < old.as_slice()
1238 }
1239 }) {
1240 let (start, end) = spans[*position];
1241 let output = &bytes[usize::from(start)..usize::from(end)];
1242 if let Some((old_key, old_output)) = selected
1243 && old_key.len() == scratch.len()
1244 && old_output.len() == output.len()
1245 {
1246 old_key.copy_from_slice(scratch);
1248 old_output.copy_from_slice(output);
1249 return Ok(());
1250 }
1251 if scratch.len() + output.len() > allowance {
1252 return Err(Error::Limit);
1253 }
1254 let key = scratch.as_slice().to_vec();
1256 let output = output.to_vec();
1257 if key.capacity() + output.capacity() > allowance {
1258 return Err(Error::Limit);
1259 }
1260 *selected = Some((key, output));
1261 }
1262 }
1263 }
1264
1265 Ok(())
1266 }
1267}
1268
1269enum Completed {
1271 Summary {
1272 count: u64,
1273 sum: Option<Box<[u8]>>,
1274 average: Option<Box<[u8]>>,
1275 sort_key: Option<Box<[u8]>>,
1276 },
1277 Key,
1278 Count(u64),
1279 Value(Option<(Vec<u8>, Vec<u8>)>),
1280}
1281impl Completed {
1282 fn encoded_len(&self) -> usize {
1283 match self {
1284 Self::Summary { sum, average, .. } => {
1285 8 + sum.as_deref().map_or(0, <[u8]>::len)
1286 + average.as_deref().map_or(0, <[u8]>::len)
1287 }
1288 Self::Key => 0,
1289 Self::Count(_) => 8,
1290 Self::Value(value) => value.as_ref().map_or(0, |(_, bytes)| bytes.len()),
1291 }
1292 }
1293 fn result_key<'a>(&'a self, scratch: &'a mut [u8; 8]) -> Option<&'a [u8]> {
1295 match self {
1296 Self::Summary { sort_key, .. } => sort_key.as_deref(),
1297 Self::Key => None,
1298 Self::Count(total) => {
1299 *scratch = total.to_be_bytes();
1300
1301 Some(scratch)
1302 }
1303 Self::Value(selected) => selected.as_ref().map(|(key, _)| key.as_slice()),
1304 }
1305 }
1306
1307 fn retained_bytes(&self) -> usize {
1308 match self {
1309 Self::Summary { sort_key, .. } => {
1310 self.encoded_len() + sort_key.as_deref().map_or(0, <[u8]>::len)
1311 }
1312 Self::Key => 0,
1313 Self::Count(_) => 8,
1314 Self::Value(value) => value
1315 .as_ref()
1316 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
1317 }
1318 }
1319
1320 fn into_count(self) -> Result<u64, Error> {
1321 match self {
1322 Self::Count(count) => Ok(count),
1323 _ => Err(Error::Corrupt),
1324 }
1325 }
1326
1327 fn into_value(self) -> Result<Option<Vec<u8>>, Error> {
1328 match self {
1329 Self::Value(value) => Ok(value.map(|(_, bytes)| bytes)),
1330 _ => Err(Error::Corrupt),
1331 }
1332 }
1333}
1334
1335pub(super) struct Groups {
1336 summary_sum: Option<ValueSchema>,
1337 selection: Selection,
1338 mask: u32,
1339 initial: Reducer,
1341 rows: BTreeMap<Box<[u8]>, (Vec<u8>, Reducer)>,
1342 state_bytes: usize,
1343}
1344impl Groups {
1345 fn max_keys(&self) -> usize {
1346 if matches!(self.initial, Reducer::Keys(_)) {
1347 usize::from(u8::MAX)
1348 } else {
1349 MAX_GROUPS
1350 }
1351 }
1352
1353 fn first_occurrences(&self) -> Result<Vec<&[u8]>, Error> {
1355 let mut ordered = vec![&[][..]; self.rows.len()];
1356 for (bytes, reducer) in self.rows.values() {
1357 let Reducer::Keys(position) = reducer else {
1358 return Err(Error::Corrupt);
1359 };
1360 ordered[usize::from(*position)] = bytes;
1361 }
1362 Ok(ordered)
1363 }
1364
1365 fn into_output(self, limit: usize) -> Result<Vec<(Vec<u8>, Completed)>, Error> {
1366 let mut state_bytes = self.state_bytes;
1368 let key_order = matches!(
1369 self.selection.order,
1370 GroupOrder::Key | GroupOrder::KeyDescending
1371 );
1372 let bounded_rank = !key_order && limit < self.rows.len();
1373 let compare = |a: &Completed, b: &Completed| {
1374 let (mut sa, mut sb) = ([0; 8], [0; 8]);
1375 let order = match (self.selection.order, a, b) {
1376 (
1377 GroupOrder::Summary(SummaryMeasure::Count, _),
1378 Completed::Summary { count: left, .. },
1379 Completed::Summary { count: right, .. },
1380 ) => left.cmp(right),
1381 _ => a.result_key(&mut sa).cmp(&b.result_key(&mut sb)),
1382 };
1383 if matches!(
1384 self.selection.order,
1385 GroupOrder::AggregateDescending
1386 | GroupOrder::Summary(_, super::SortDirection::Descending)
1387 ) {
1388 order.reverse()
1389 } else {
1390 order
1391 }
1392 };
1393 let retain = limit.min(self.rows.len());
1394 let mut rows = Vec::with_capacity(retain);
1395 let mut oldest = 0;
1396 let needs_value_key = !self.selection.predicates.is_empty()
1397 || matches!(
1398 self.selection.order,
1399 GroupOrder::AggregateAscending | GroupOrder::AggregateDescending
1400 );
1401 for (record, reducer) in self.rows.into_values() {
1402 let previous = reducer.retained_bytes();
1403 let (result, accepted) = if let Some(sum) = self.summary_sum {
1404 let Reducer::Numeric(state) = reducer else {
1405 return Err(Error::Corrupt);
1406 };
1407 state.finish_summary(sum, &self.selection)?
1408 } else {
1409 let result = reducer.finish(needs_value_key)?;
1410 let mut scratch = [0; 8];
1411 let key = result.result_key(&mut scratch);
1412 let accepted = self.selection.accepts(|_| key);
1413 (result, accepted)
1414 };
1415 state_bytes = state_bytes - previous + result.retained_bytes();
1416 if state_bytes > MAX_STATE_BYTES {
1417 return Err(Error::Limit);
1418 }
1419 if accepted {
1420 if bounded_rank {
1421 let position =
1423 rows.partition_point(|(_, value)| !compare(value, &result).is_gt());
1424 if position < retain {
1425 if rows.len() == retain {
1426 rows.pop();
1427 }
1428 rows.insert(position, (record, result));
1429 }
1430 } else if rows.len() < retain {
1431 rows.push((record, result));
1432 } else if self.selection.order == GroupOrder::KeyDescending {
1433 rows[oldest] = (record, result);
1435 oldest = (oldest + 1) % retain;
1436 }
1437 }
1438 }
1439 if self.selection.order == GroupOrder::KeyDescending {
1440 rows.rotate_left(oldest);
1441 rows.reverse();
1442 } else if !key_order && !bounded_rank {
1443 rows.sort_by(|(_, a), (_, b)| compare(a, b));
1445 }
1446
1447 Ok(rows)
1448 }
1449
1450 fn push(
1451 &mut self,
1452 entity: &EntitySchema,
1453 values: &[IndexValue<'_>],
1454 bytes: &[u8],
1455 spans: &[(u16, u16)],
1456 scratch: &mut Vec<u8>,
1457 ) -> Result<(), Error> {
1458 comparison_key(entity, self.mask, values, scratch)?;
1459 let available = MAX_STATE_BYTES - self.state_bytes;
1460 if let Some((_, reducer)) = self.rows.get_mut(scratch.as_slice()) {
1461 let previous = reducer.retained_bytes();
1462 reducer.push(entity, values, bytes, spans, scratch, available + previous)?;
1463 self.state_bytes = self.state_bytes - previous + reducer.retained_bytes();
1464 return Ok(());
1465 }
1466
1467 let count = self.rows.len();
1468 let size = projection_size(spans, self.mask);
1469 let base = scratch.len() + size;
1470 if count == self.max_keys() || base + self.initial.retained_bytes() > available {
1471 return Err(Error::Limit);
1472 }
1473 let key = Box::<[u8]>::from(scratch.as_slice());
1475 let mut reducer = self.initial.clone();
1476 if let Reducer::Keys(position) = &mut reducer {
1477 *position = count as u8;
1478 }
1479 reducer.push(entity, values, bytes, spans, scratch, available - base)?;
1480 let output = copy_projection(bytes, spans, self.mask, size);
1481 let retained = key.len() + output.capacity() + reducer.retained_bytes();
1484 if retained > available {
1485 return Err(Error::Limit);
1486 }
1487 self.state_bytes += retained;
1488 self.rows.insert(key, (output, reducer));
1489
1490 Ok(())
1491 }
1492}