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
225impl Aggregate<u64> {
226 fn at_least(self, minimum: u64) -> Aggregate<bool> {
227 Aggregate {
228 value: self.value >= minimum,
229 examined: self.examined,
230 fetched: self.fetched,
231 output_bytes: 1,
232 }
233 }
234}
235
236#[derive(Debug)]
238pub struct GroupCount<K> {
239 pub key: K,
241 pub count: u64,
243}
244
245pub type GroupSummaries<K, S, A> = Aggregate<Vec<GroupSummary<K, S, A>>>;
247
248pub type GroupSummaryPage<K, S, A> = jobs::GroupPage<GroupSummary<K, S, A>>;
250
251#[derive(Debug)]
253pub struct GroupSummary<K, S, A> {
254 pub key: K,
256 pub count: u64,
258 pub sum: Option<S>,
260 pub average: Option<A>,
262}
263
264#[derive(Debug)]
266pub struct GroupValue<K, R> {
267 pub key: K,
269 pub value: Option<R>,
271}
272
273impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
274 #[must_use]
279 pub fn group_page(mut self, size: usize, after: Option<&'a jobs::GroupCursor>) -> Self {
280 self.request.groups.page = Some(jobs::pages::PageRequest { size, after });
281
282 self
283 }
284
285 #[must_use]
292 pub fn filter_groups(self, comparison: Comparison, value: impl Into<IndexValue<'a>>) -> Self {
293 self.add_group_clause(std::iter::once((None, comparison, value.into())))
294 }
295
296 #[must_use]
299 pub fn filter_summary(
300 self,
301 measure: SummaryMeasure,
302 comparison: Comparison,
303 value: impl Into<IndexValue<'a>>,
304 ) -> Self {
305 self.add_group_clause(std::iter::once((Some(measure), comparison, value.into())))
306 }
307
308 #[must_use]
312 pub fn filter_summary_any(
313 self,
314 alternatives: &[(SummaryMeasure, Comparison, IndexValue<'a>)],
315 ) -> Self {
316 self.add_group_clause(
317 alternatives
318 .iter()
319 .map(|&(measure, comparison, value)| (Some(measure), comparison, value)),
320 )
321 }
322
323 #[must_use]
330 pub fn filter_groups_any(self, alternatives: &[(Comparison, IndexValue<'a>)]) -> Self {
331 self.add_group_clause(
332 alternatives
333 .iter()
334 .map(|&(comparison, value)| (None, comparison, value)),
335 )
336 }
337
338 fn add_group_clause(
339 mut self,
340 terms: impl ExactSizeIterator<Item = (Option<SummaryMeasure>, Comparison, IndexValue<'a>)>,
341 ) -> Self {
342 let count = terms.len();
343 if count == 0 || count > MAX_TERMS - self.request.groups.predicates.len() {
344 self.request.over_limit = true;
345 } else {
346 self.request.groups.predicates.extend(terms.enumerate().map(
347 |(i, (measure, comparison, operand))| GroupPredicate {
348 measure,
349 comparison,
350 operand,
351 or_next: i + 1 != count,
352 },
353 ));
354 }
355
356 self
357 }
358
359 #[must_use]
362 pub fn order_groups(mut self, order: GroupOrder) -> Self {
363 self.request.groups.order = Some(order);
364
365 self
366 }
367
368 pub fn min<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
381 observe!(query, { self.extremum(false) })
382 }
383
384 pub fn max<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
391 observe!(query, { self.extremum(true) })
392 }
393
394 fn extremum<R: Value>(self, maximum: bool) -> Result<Aggregate<Option<R>>, Error> {
395 let (plan, reducer) = self.extremum_plan::<R>(maximum)?;
396
397 self.scalar_value(plan, reducer)
398 }
399
400 fn extremum_plan<R: Value>(&self, maximum: bool) -> Result<(Plan<'a>, Reducer), Error> {
401 let plan = self.aggregate_plan(Some(R::definition()), false)?;
402 let reducer = Reducer::extremum(
403 E::SCHEMA,
404 plan.projection.ok_or(Error::InvalidQuery)?,
405 maximum,
406 )?;
407
408 Ok((plan, reducer))
409 }
410
411 fn scalar_value<R: Value>(
412 self,
413 mut plan: Plan<'_>,
414 mut reducer: Reducer,
415 ) -> Result<Aggregate<Option<R>>, Error> {
416 super::order::select_unique_aggregate_path(E::SCHEMA, &self.request, &mut plan)?;
417 let page = execute(
418 &self.db.read()?.map,
419 E::SCHEMA,
420 &self.request,
421 &plan,
422 Some(Accumulator::Scalar(&mut reducer)),
423 )?;
424 let (value, output_bytes) = scalar_output(reducer, self.request.bytes)?;
425
426 Ok(Aggregate {
427 value,
428 examined: page.examined,
429 fetched: page.fetched,
430 output_bytes,
431 })
432 }
433
434 pub fn group_min<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
451 observe!(query, { self.group_extrema(false) })
452 }
453
454 pub fn group_max<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
460 observe!(query, { self.group_extrema(true) })
461 }
462
463 fn group_extrema<K: Value, R: Value>(
464 self,
465 maximum: bool,
466 ) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
467 let (plan, initial) = self.group_extremum_plan::<K, R>(maximum)?;
468
469 self.group_values(plan, initial)
470 }
471
472 fn group_extremum_plan<K: Value, R: Value>(
473 &self,
474 maximum: bool,
475 ) -> Result<(Plan<'a>, Reducer), Error> {
476 let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
477 let operand = admit_projection(E::SCHEMA, R::definition())?;
478 let initial = Reducer::extremum(E::SCHEMA, operand, maximum)?;
479 plan.selected |= operand;
480
481 Ok((plan, initial))
482 }
483
484 fn group_values<K: Value, R: Value>(
485 self,
486 mut plan: Plan<'_>,
487 initial: Reducer,
488 ) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
489 super::order::select_unique_aggregate_path(E::SCHEMA, &self.request, &mut plan)?;
490 group_output(
491 self.grouped(&plan, initial, None)?,
492 &self.request,
493 decode_group_value,
494 )
495 }
496
497 pub fn exists(self) -> Result<Aggregate<bool>, Error> {
511 observe!(query, {
512 let mut plan = self.count_plan(None)?;
513 self.select_aggregate_row_path(&mut plan, Some(MemberProbe::Exists))?;
514 Ok(self
515 .count_matching_rows(&plan, MemberProbe::Exists, 1)?
516 .at_least(1))
517 })
518 }
519
520 pub fn count(self) -> Result<Aggregate<u64>, Error> {
536 observe!(query, {
537 if self.request.bytes < 8 {
538 return Err(Error::RowTooLarge);
539 }
540 self.count_until(u64::MAX)
541 })
542 }
543
544 pub fn has_at_least(self, minimum: u64) -> Result<Aggregate<bool>, Error> {
551 observe!(query, { Ok(self.count_until(minimum)?.at_least(minimum)) })
552 }
553
554 fn count_until(self, stop: u64) -> Result<Aggregate<u64>, Error> {
555 if self.request.is_plain_count() {
556 return self.entity_count();
557 }
558 let mut plan = self.count_plan(None)?;
559 if stop == 0 {
560 return Ok(Aggregate {
561 value: 0,
562 examined: 0,
563 fetched: 0,
564 output_bytes: 8,
565 });
566 }
567 if self.request.index.is_none()
568 && self
569 .request
570 .clauses()
571 .zip(plan.clauses())
572 .all(|(clause, terms)| {
573 clause.iter().zip(terms).any(|(p, term)| {
574 p.constant_comparison(E::SCHEMA) == Some(true)
575 || (term.tests_presence && E::SCHEMA.field_is_required(p.field))
576 })
577 })
578 {
579 return self.entity_count();
580 }
581 if let Some(count) = probe_members(
582 &self.db,
583 E::SCHEMA,
584 &self.request,
585 &plan,
586 MemberProbe::CountKeys,
587 stop,
588 )? {
589 return Ok(count);
590 }
591 if super::order::select_filtered_path(
592 E::SCHEMA,
593 &self.request,
594 &mut plan,
595 Some(MemberProbe::CountWithRows),
596 )? {
597 return self.count_keys(&plan, stop);
598 }
599 self.count_matching_rows(&plan, MemberProbe::CountWithRows, stop)
600 }
601
602 fn count_matching_rows(
603 &self,
604 plan: &Plan<'_>,
605 probe: MemberProbe,
606 stop: u64,
607 ) -> Result<Aggregate<u64>, Error> {
608 if let Some(count) = probe_members(&self.db, E::SCHEMA, &self.request, plan, probe, stop)? {
609 return Ok(count);
610 }
611 let mut remaining = stop;
612 let page = execute(
613 &self.db.read()?.map,
614 E::SCHEMA,
615 &self.request,
616 plan,
617 Some(Accumulator::Until(&mut remaining)),
618 )?;
619 Ok(Aggregate {
620 value: stop - remaining,
621 examined: page.examined,
622 fetched: page.fetched,
623 output_bytes: 8,
624 })
625 }
626
627 fn entity_count(&self) -> Result<Aggregate<u64>, Error> {
628 Ok(Aggregate {
629 value: self.db.read()?.cardinality::<E>()?,
630 examined: 0,
631 fetched: 0,
632 output_bytes: 8,
633 })
634 }
635
636 pub fn count_validated(self) -> Result<Aggregate<u64>, Error> {
643 observe!(query, { self.scalar_count(None) })
644 }
645
646 pub fn count_index_entries(self) -> Result<Aggregate<u64>, Error> {
657 observe!(query, {
658 if self.request.index.is_none() || !self.request.predicates.is_empty() {
659 return Err(Error::InvalidQuery);
660 }
661 if self.request.bytes < 8 {
662 return Err(Error::RowTooLarge);
663 }
664 let plan = self.count_plan(None)?;
665
666 self.count_keys(&plan, u64::MAX)
667 })
668 }
669
670 fn count_keys(&self, plan: &Plan<'_>, stop: u64) -> Result<Aggregate<u64>, Error> {
671 let bounds = super::range::bounds(E::SCHEMA, &self.request, plan)?;
672 let mut examined = 0;
673 if let Some(range) = bounds {
674 let db = self.db.read()?;
675 if let Some(key) = super::range::exact_key(&range) {
676 examined = usize::from(db.map.contains_key(key));
677 } else {
678 let keys = db.map.keys_range((range.0.as_ref(), range.1.as_ref()));
679 for _ in keys {
680 if examined == self.request.work {
681 return Err(Error::Limit);
682 }
683 examined += 1;
684 if examined as u64 == stop {
685 break;
686 }
687 }
688 }
689 }
690
691 Ok(Aggregate {
692 value: examined as u64,
693 examined,
694 fetched: 0,
695 output_bytes: 8,
696 })
697 }
698
699 pub fn count_field(self, field: &str) -> Result<Aggregate<u64>, Error> {
707 observe!(query, { self.scalar_count(Some(field)) })
708 }
709
710 pub fn count_distinct<K: Value>(self) -> Result<Aggregate<u64>, Error> {
721 observe!(query, {
722 if self.request.bytes < 8 {
723 return Err(Error::RowTooLarge);
724 }
725 let mut plan = self.count_plan(Some(K::definition()))?;
726 self.select_aggregate_row_path(&mut plan, None)?;
727 let projected = plan.projection.ok_or(Error::InvalidQuery)?;
728 let fixed = super::distinct::fixed_fields(E::SCHEMA, &self.request, &plan);
729
730 self.scalar_count_value(&plan, Reducer::distinct(projected & !fixed))
731 })
732 }
733
734 fn select_aggregate_row_path(
735 &self,
736 plan: &mut Plan<'static>,
737 probe: Option<MemberProbe>,
738 ) -> Result<(), Error> {
739 if plan.index.is_none() {
740 super::order::select_filtered_path(E::SCHEMA, &self.request, plan, probe)?;
741 }
742
743 Ok(())
744 }
745
746 fn scalar_count(self, field: Option<&str>) -> Result<Aggregate<u64>, Error> {
747 if self.request.bytes < 8 {
748 return Err(Error::RowTooLarge);
749 }
750 let mut plan = self.count_plan(None)?;
751 let probe = field.is_none().then_some(MemberProbe::CountValidated);
752 self.select_aggregate_row_path(&mut plan, probe)?;
753 if let Some(probe) = probe
754 && let Some(count) =
755 probe_members(&self.db, E::SCHEMA, &self.request, &plan, probe, u64::MAX)?
756 {
757 return Ok(count);
758 }
759 let reducer = self.count_reducer(field)?;
760
761 self.scalar_count_value(&plan, reducer)
762 }
763
764 fn scalar_count_value(
765 self,
766 plan: &Plan<'_>,
767 mut reducer: Reducer,
768 ) -> Result<Aggregate<u64>, Error> {
769 let page = execute(
770 &self.db.read()?.map,
771 E::SCHEMA,
772 &self.request,
773 plan,
774 Some(Accumulator::Scalar(&mut reducer)),
775 )?;
776
777 Ok(Aggregate {
778 value: reducer.finish(false)?.into_count()?,
779 examined: page.examined,
780 fetched: page.fetched,
781 output_bytes: 8,
782 })
783 }
784
785 pub fn group_count<K: Value>(self) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
802 observe!(query, { self.group_counts(None) })
803 }
804
805 pub fn group_count_field<K: Value>(
814 self,
815 field: &str,
816 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
817 observe!(query, { self.group_counts(Some(field)) })
818 }
819
820 pub fn group_count_distinct<K: Value, R: Value>(
834 self,
835 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
836 observe!(query, {
837 let (plan, reducer) = self.group_distinct_plan::<K, R>()?;
838
839 self.group_count_values(plan, reducer)
840 })
841 }
842
843 fn group_distinct_plan<K: Value, R: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
844 let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
845 let operand = admit_projection(E::SCHEMA, R::definition())?;
846 admit_ordered_fields(E::SCHEMA, operand)?;
847 plan.selected |= operand;
848
849 Ok((plan, Reducer::distinct(operand)))
850 }
851
852 fn group_counts<K: Value>(
853 self,
854 field: Option<&str>,
855 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
856 let plan = self.aggregate_plan(Some(K::definition()), true)?;
857 let reducer = self.count_reducer(field)?;
858
859 self.group_count_values(plan, reducer)
860 }
861
862 fn group_count_values<K: Value>(
863 self,
864 mut plan: Plan<'static>,
865 mut reducer: Reducer,
866 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
867 self.select_aggregate_row_path(&mut plan, None)?;
868 if let Reducer::Distinct { mask, .. } = &mut reducer {
869 let grouped = plan.projection.ok_or(Error::InvalidQuery)?;
870 let fixed = super::distinct::fixed_fields(E::SCHEMA, &self.request, &plan);
871 *mask &= !(grouped | fixed);
872 }
873 group_output(
874 self.grouped(&plan, reducer, None)?,
875 &self.request,
876 decode_group_count,
877 )
878 }
879
880 fn count_reducer(&self, field: Option<&str>) -> Result<Reducer, Error> {
881 let presence = field
883 .map(|name| E::SCHEMA.field_position(name).ok_or(Error::InvalidQuery))
884 .transpose()?
885 .filter(|&i| E::SCHEMA.fields[i].optional);
886
887 Ok(Reducer::Count { presence, total: 0 })
888 }
889
890 fn grouped(
891 &self,
892 plan: &Plan<'_>,
893 initial: Reducer,
894 summary_sum: Option<ValueSchema>,
895 ) -> Result<(Groups, QueryPage<Vec<u8>>), Error> {
896 if self.request.groups.page.is_some() {
897 return Err(Error::InvalidQuery);
898 }
899 let mut groups = self
900 .request
901 .admit_groups(E::SCHEMA, plan, initial, summary_sum)?;
902 let page = execute(
903 &self.db.read()?.map,
904 E::SCHEMA,
905 &self.request,
906 plan,
907 Some(Accumulator::Groups(&mut groups)),
908 )?;
909
910 Ok((groups, page))
911 }
912
913 fn count_plan(&self, output: Option<&TypeSchema>) -> Result<Plan<'static>, Error> {
914 self.request
915 .aggregate_plan(&self.db, E::SCHEMA, output, PlanOutput::ImmediateCount)
916 }
917
918 fn aggregate_plan(
919 &self,
920 output: Option<&TypeSchema>,
921 group_output: bool,
922 ) -> Result<Plan<'static>, Error> {
923 self.request.aggregate_plan(
924 &self.db,
925 E::SCHEMA,
926 output,
927 PlanOutput::Aggregate {
928 grouped: group_output,
929 },
930 )
931 }
932}
933
934impl super::Request<'_> {
935 fn is_plain_count(&self) -> bool {
938 matches!(self, Self {
939 predicates,
940 groups,
941 index: None,
942 order: None,
943 order_descending: 0,
944 descending: false,
945 distinct: false,
946 cursor: None,
947 single_result_probe: None,
948 rows: _, work: _, bytes: _, over_limit: _,
949 } if predicates.is_empty() && groups.is_empty() && self.within_limits())
950 }
951
952 fn admit_groups(
953 &self,
954 entity: &EntitySchema,
955 plan: &Plan<'_>,
956 initial: Reducer,
957 summary_sum: Option<ValueSchema>,
958 ) -> Result<Groups, Error> {
959 if summary_sum.is_none() && matches!(self.groups.order, Some(GroupOrder::Summary(..))) {
960 return Err(Error::InvalidQuery);
961 }
962 Ok(Groups {
963 selection: self.groups.admit(entity, &initial, summary_sum)?,
964 summary_sum,
965 mask: plan.projection.ok_or(Error::InvalidQuery)?,
966 initial,
967 rows: BTreeMap::new(),
968 state_bytes: 0,
969 })
970 }
971
972 fn aggregate_plan<M: Memory>(
973 &self,
974 source: &super::QuerySource<'_, M>,
975 entity: &'static EntitySchema,
976 output: Option<&TypeSchema>,
977 kind: PlanOutput,
978 ) -> Result<Plan<'static>, Error> {
979 if self.cursor.is_some()
980 || self.distinct
981 || ((self.order.is_some() || self.descending)
982 && self.groups.order != Some(GroupOrder::FirstOccurrence))
983 {
984 return Err(Error::InvalidQuery);
985 }
986 let db = source.read()?;
987 db.schema.admits(entity)?;
988 let mut plan = Plan::admit(
989 entity,
990 self,
991 db.schema.fingerprint(),
992 db.incarnation,
993 output.map(super::Projection::Record),
994 kind,
995 )?;
996 if let Some(mask) = plan.projection {
997 admit_ordered_fields(entity, mask)?;
998 plan.selected |= mask;
999 }
1000
1001 Ok(plan)
1002 }
1003}
1004
1005fn scalar_output<R: Value>(reducer: Reducer, limit: usize) -> Result<(Option<R>, usize), Error> {
1006 let Some(bytes) = reducer.finish(false)?.into_value()? else {
1007 return Ok((None, 0));
1008 };
1009 let mut used = 0;
1010 admit_output(bytes.len(), limit, &mut used)?;
1011
1012 Ok((Some(decode_record(&bytes)?), used))
1013}
1014
1015fn group_output<T>(
1016 (groups, page): (Groups, QueryPage<Vec<u8>>),
1017 request: &super::Request<'_>,
1018 decode: fn(&[u8], Completed) -> Result<T, Error>,
1019) -> Result<Aggregate<Vec<T>>, Error> {
1020 let mut output_bytes = 0;
1021 let value = groups
1022 .into_output(request.rows)?
1023 .into_iter()
1024 .map(|(key, result)| {
1025 admit_output(
1026 key.len() + result.encoded_len(),
1027 request.bytes,
1028 &mut output_bytes,
1029 )?;
1030
1031 decode(&key, result)
1032 })
1033 .collect::<Result<_, Error>>()?;
1034
1035 Ok(Aggregate {
1036 value,
1037 examined: page.examined,
1038 fetched: page.fetched,
1039 output_bytes,
1040 })
1041}
1042
1043fn decode_group_count<K: Value>(key: &[u8], result: Completed) -> Result<GroupCount<K>, Error> {
1044 Ok(GroupCount {
1045 key: decode_record(key)?,
1046 count: result.into_count()?,
1047 })
1048}
1049
1050fn decode_group_value<K: Value, R: Value>(
1051 key: &[u8],
1052 result: Completed,
1053) -> Result<GroupValue<K, R>, Error> {
1054 let value = result.into_value()?;
1055
1056 Ok(GroupValue {
1057 key: decode_record(key)?,
1058 value: value.as_deref().map(decode_record).transpose()?,
1059 })
1060}
1061
1062fn decode_record<R: Value>(bytes: &[u8]) -> Result<R, Error> {
1063 let mut reader = Decoder::new(bytes)?;
1064 let value = R::decode_from(&mut reader)?;
1065 reader.finish()?;
1066
1067 Ok(value)
1068}
1069
1070pub(super) enum Accumulator<'a> {
1072 Until(&'a mut u64),
1074 Scalar(&'a mut Reducer),
1075 Groups(&'a mut Groups),
1076}
1077impl Accumulator<'_> {
1078 pub(super) fn needs_spans(&self) -> bool {
1079 !matches!(
1080 self,
1081 Self::Until(_)
1082 | Self::Scalar(
1083 Reducer::Numeric(_)
1084 | Reducer::Count { presence: None, .. }
1085 | Reducer::Distinct { .. }
1086 )
1087 )
1088 }
1089
1090 pub(super) fn push(
1091 &mut self,
1092 entity: &EntitySchema,
1093 values: &[IndexValue<'_>],
1094 bytes: &[u8],
1095 spans: &[(u16, u16)],
1096 scratch: &mut Vec<u8>,
1097 ) -> Result<(), Error> {
1098 match self {
1099 Self::Until(remaining) => {
1100 **remaining -= 1;
1101
1102 Ok(())
1103 }
1104 Self::Scalar(state) => {
1105 state.push(entity, values, bytes, spans, scratch, MAX_STATE_BYTES)
1106 }
1107 Self::Groups(state) => state.push(entity, values, bytes, spans, scratch),
1108 }
1109 }
1110}
1111
1112#[derive(Clone)]
1113pub(super) enum Reducer {
1114 Keys(u8),
1115 Numeric(numeric::NumericAggregate),
1116 Distinct {
1117 mask: u32,
1118 seen: DistinctKeys,
1119 key_bytes: usize,
1120 },
1121 Count {
1122 presence: Option<usize>,
1123 total: u64,
1124 },
1125 Extremum {
1126 position: usize,
1127 maximum: bool,
1128 selected: Option<(Vec<u8>, Vec<u8>)>,
1129 },
1130}
1131impl Reducer {
1132 fn distinct(mask: u32) -> Self {
1133 Self::Distinct {
1134 mask,
1135 seen: DistinctKeys::new(),
1136 key_bytes: 0,
1137 }
1138 }
1139
1140 fn extremum(entity: &EntitySchema, mask: u32, maximum: bool) -> Result<Self, Error> {
1141 if mask.count_ones() != 1 {
1142 return Err(Error::InvalidQuery);
1143 }
1144 let position = mask.trailing_zeros() as usize;
1145 if !key::supports(entity.fields[position].value) {
1146 return Err(Error::InvalidQuery);
1147 }
1148
1149 Ok(Self::Extremum {
1150 position,
1151 maximum,
1152 selected: None,
1153 })
1154 }
1155
1156 fn retained_bytes(&self) -> usize {
1157 match self {
1158 Self::Keys(_) => 0,
1159 Self::Numeric(state) => state.retained_bytes(),
1160 Self::Count { .. } => 8,
1161 Self::Distinct { key_bytes, .. } => 8 + key_bytes,
1162 Self::Extremum { selected, .. } => selected
1163 .as_ref()
1164 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
1165 }
1166 }
1167
1168 fn finish(self, needs_numeric_key: bool) -> Result<Completed, Error> {
1169 match self {
1170 Self::Keys(_) => Ok(Completed::Key),
1171 Self::Count { total, .. } => Ok(Completed::Count(total)),
1172 Self::Distinct { seen, .. } => Ok(Completed::Count(seen.len() as u64)),
1173 Self::Extremum { selected, .. } => Ok(Completed::Value(selected)),
1174 Self::Numeric(state) => state.finish(needs_numeric_key),
1175 }
1176 }
1177
1178 fn push(
1179 &mut self,
1180 entity: &EntitySchema,
1181 values: &[IndexValue<'_>],
1182 bytes: &[u8],
1183 spans: &[(u16, u16)],
1184 scratch: &mut Vec<u8>,
1185 allowance: usize,
1186 ) -> Result<(), Error> {
1187 match self {
1188 Self::Keys(_) => {}
1189 Self::Numeric(state) => state.push(values)?,
1190 Self::Distinct {
1191 mask,
1192 seen,
1193 key_bytes,
1194 } => {
1195 comparison_key(entity, *mask, values, scratch)?;
1196 if let Err(position) =
1197 seen.binary_search_by(|key| key.as_ref().cmp(scratch.as_slice()))
1198 {
1199 let size = scratch.len();
1200 if seen.len() == MAX_DISTINCT_VALUES || 8 + *key_bytes + size > allowance {
1201 return Err(Error::Limit);
1202 }
1203 seen.insert(position, Box::from(scratch.as_slice()));
1204 *key_bytes += size;
1205 }
1206 }
1207 Self::Count { presence, total } => {
1208 *total += u64::from(presence.is_none_or(|i| bytes[usize::from(spans[i].0)] != 0));
1209 }
1210 Self::Extremum {
1211 position,
1212 maximum,
1213 selected,
1214 } => {
1215 let value = values[*position];
1216 if value == IndexValue::Absent {
1217 return Ok(());
1218 }
1219 scratch.clear();
1220 value.append_component(entity.fields[*position].optional, scratch);
1221 if scratch.len() > MAX_COMPARISON_KEY {
1222 return Err(Error::Limit);
1223 }
1224 if selected.as_ref().is_none_or(|(old, _)| {
1225 if *maximum {
1226 scratch.as_slice() > old.as_slice()
1227 } else {
1228 scratch.as_slice() < old.as_slice()
1229 }
1230 }) {
1231 let (start, end) = spans[*position];
1232 let output = &bytes[usize::from(start)..usize::from(end)];
1233 if let Some((old_key, old_output)) = selected
1234 && old_key.len() == scratch.len()
1235 && old_output.len() == output.len()
1236 {
1237 old_key.copy_from_slice(scratch);
1239 old_output.copy_from_slice(output);
1240 return Ok(());
1241 }
1242 if scratch.len() + output.len() > allowance {
1243 return Err(Error::Limit);
1244 }
1245 let key = scratch.as_slice().to_vec();
1247 let output = output.to_vec();
1248 if key.capacity() + output.capacity() > allowance {
1249 return Err(Error::Limit);
1250 }
1251 *selected = Some((key, output));
1252 }
1253 }
1254 }
1255
1256 Ok(())
1257 }
1258}
1259
1260enum Completed {
1262 Summary {
1263 count: u64,
1264 sum: Option<Box<[u8]>>,
1265 average: Option<Box<[u8]>>,
1266 sort_key: Option<Box<[u8]>>,
1267 },
1268 Key,
1269 Count(u64),
1270 Value(Option<(Vec<u8>, Vec<u8>)>),
1271}
1272impl Completed {
1273 fn encoded_len(&self) -> usize {
1274 match self {
1275 Self::Summary { sum, average, .. } => {
1276 8 + sum.as_deref().map_or(0, <[u8]>::len)
1277 + average.as_deref().map_or(0, <[u8]>::len)
1278 }
1279 Self::Key => 0,
1280 Self::Count(_) => 8,
1281 Self::Value(value) => value.as_ref().map_or(0, |(_, bytes)| bytes.len()),
1282 }
1283 }
1284 fn result_key<'a>(&'a self, scratch: &'a mut [u8; 8]) -> Option<&'a [u8]> {
1286 match self {
1287 Self::Summary { sort_key, .. } => sort_key.as_deref(),
1288 Self::Key => None,
1289 Self::Count(total) => {
1290 *scratch = total.to_be_bytes();
1291
1292 Some(scratch)
1293 }
1294 Self::Value(selected) => selected.as_ref().map(|(key, _)| key.as_slice()),
1295 }
1296 }
1297
1298 fn retained_bytes(&self) -> usize {
1299 match self {
1300 Self::Summary { sort_key, .. } => {
1301 self.encoded_len() + sort_key.as_deref().map_or(0, <[u8]>::len)
1302 }
1303 Self::Key => 0,
1304 Self::Count(_) => 8,
1305 Self::Value(value) => value
1306 .as_ref()
1307 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
1308 }
1309 }
1310
1311 fn into_count(self) -> Result<u64, Error> {
1312 match self {
1313 Self::Count(count) => Ok(count),
1314 _ => Err(Error::Corrupt),
1315 }
1316 }
1317
1318 fn into_value(self) -> Result<Option<Vec<u8>>, Error> {
1319 match self {
1320 Self::Value(value) => Ok(value.map(|(_, bytes)| bytes)),
1321 _ => Err(Error::Corrupt),
1322 }
1323 }
1324}
1325
1326pub(super) struct Groups {
1327 summary_sum: Option<ValueSchema>,
1328 selection: Selection,
1329 mask: u32,
1330 initial: Reducer,
1332 rows: BTreeMap<Box<[u8]>, (Vec<u8>, Reducer)>,
1333 state_bytes: usize,
1334}
1335impl Groups {
1336 fn max_keys(&self) -> usize {
1337 if matches!(self.initial, Reducer::Keys(_)) {
1338 usize::from(u8::MAX)
1339 } else {
1340 MAX_GROUPS
1341 }
1342 }
1343
1344 fn first_occurrences(&self) -> Result<Vec<&[u8]>, Error> {
1346 let mut ordered = vec![&[][..]; self.rows.len()];
1347 for (bytes, reducer) in self.rows.values() {
1348 let Reducer::Keys(position) = reducer else {
1349 return Err(Error::Corrupt);
1350 };
1351 ordered[usize::from(*position)] = bytes;
1352 }
1353 Ok(ordered)
1354 }
1355
1356 fn into_output(self, limit: usize) -> Result<Vec<(Vec<u8>, Completed)>, Error> {
1357 let mut state_bytes = self.state_bytes;
1359 let key_order = matches!(
1360 self.selection.order,
1361 GroupOrder::Key | GroupOrder::KeyDescending
1362 );
1363 let bounded_rank = !key_order && limit < self.rows.len();
1364 let compare = |a: &Completed, b: &Completed| {
1365 let (mut sa, mut sb) = ([0; 8], [0; 8]);
1366 let order = match (self.selection.order, a, b) {
1367 (
1368 GroupOrder::Summary(SummaryMeasure::Count, _),
1369 Completed::Summary { count: left, .. },
1370 Completed::Summary { count: right, .. },
1371 ) => left.cmp(right),
1372 _ => a.result_key(&mut sa).cmp(&b.result_key(&mut sb)),
1373 };
1374 if matches!(
1375 self.selection.order,
1376 GroupOrder::AggregateDescending
1377 | GroupOrder::Summary(_, super::SortDirection::Descending)
1378 ) {
1379 order.reverse()
1380 } else {
1381 order
1382 }
1383 };
1384 let retain = limit.min(self.rows.len());
1385 let mut rows = Vec::with_capacity(retain);
1386 let mut oldest = 0;
1387 let needs_value_key = !self.selection.predicates.is_empty()
1388 || matches!(
1389 self.selection.order,
1390 GroupOrder::AggregateAscending | GroupOrder::AggregateDescending
1391 );
1392 for (record, reducer) in self.rows.into_values() {
1393 let previous = reducer.retained_bytes();
1394 let (result, accepted) = if let Some(sum) = self.summary_sum {
1395 let Reducer::Numeric(state) = reducer else {
1396 return Err(Error::Corrupt);
1397 };
1398 state.finish_summary(sum, &self.selection)?
1399 } else {
1400 let result = reducer.finish(needs_value_key)?;
1401 let mut scratch = [0; 8];
1402 let key = result.result_key(&mut scratch);
1403 let accepted = self.selection.accepts(|_| key);
1404 (result, accepted)
1405 };
1406 state_bytes = state_bytes - previous + result.retained_bytes();
1407 if state_bytes > MAX_STATE_BYTES {
1408 return Err(Error::Limit);
1409 }
1410 if accepted {
1411 if bounded_rank {
1412 let position =
1414 rows.partition_point(|(_, value)| !compare(value, &result).is_gt());
1415 if position < retain {
1416 if rows.len() == retain {
1417 rows.pop();
1418 }
1419 rows.insert(position, (record, result));
1420 }
1421 } else if rows.len() < retain {
1422 rows.push((record, result));
1423 } else if self.selection.order == GroupOrder::KeyDescending {
1424 rows[oldest] = (record, result);
1426 oldest = (oldest + 1) % retain;
1427 }
1428 }
1429 }
1430 if self.selection.order == GroupOrder::KeyDescending {
1431 rows.rotate_left(oldest);
1432 rows.reverse();
1433 } else if !key_order && !bounded_rank {
1434 rows.sort_by(|(_, a), (_, b)| compare(a, b));
1436 }
1437
1438 Ok(rows)
1439 }
1440
1441 fn push(
1442 &mut self,
1443 entity: &EntitySchema,
1444 values: &[IndexValue<'_>],
1445 bytes: &[u8],
1446 spans: &[(u16, u16)],
1447 scratch: &mut Vec<u8>,
1448 ) -> Result<(), Error> {
1449 comparison_key(entity, self.mask, values, scratch)?;
1450 let available = MAX_STATE_BYTES - self.state_bytes;
1451 if let Some((_, reducer)) = self.rows.get_mut(scratch.as_slice()) {
1452 let previous = reducer.retained_bytes();
1453 reducer.push(entity, values, bytes, spans, scratch, available + previous)?;
1454 self.state_bytes = self.state_bytes - previous + reducer.retained_bytes();
1455 return Ok(());
1456 }
1457
1458 let count = self.rows.len();
1459 let size = projection_size(spans, self.mask);
1460 let base = scratch.len() + size;
1461 if count == self.max_keys() || base + self.initial.retained_bytes() > available {
1462 return Err(Error::Limit);
1463 }
1464 let key = Box::<[u8]>::from(scratch.as_slice());
1466 let mut reducer = self.initial.clone();
1467 if let Reducer::Keys(position) = &mut reducer {
1468 *position = count as u8;
1469 }
1470 reducer.push(entity, values, bytes, spans, scratch, available - base)?;
1471 let output = copy_projection(bytes, spans, self.mask, size);
1472 let retained = key.len() + output.capacity() + reducer.retained_bytes();
1475 if retained > available {
1476 return Err(Error::Limit);
1477 }
1478 self.state_bytes += retained;
1479 self.rows.insert(key, (output, reducer));
1480
1481 Ok(())
1482 }
1483}