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, Plan, PlanOutput, Query,
11 QueryPage, admit_ordered_fields, admit_output, admit_projection, comparison_key,
12 copy_projection, decode_record, execute, projection_size,
13};
14use crate::{
15 Entity, EntitySchema, Error, FieldType, IndexValue, TypeSchema, Value, ValueSchema, key,
16};
17use ic_storage::Memory;
18use std::collections::BTreeMap;
19
20const MAX_GROUPS: usize = 32;
21
22#[derive(Clone, Copy)]
23enum CountInput<'a> {
24 Rows,
25 Field(&'a str),
26 Distinct(&'static TypeSchema),
27}
28
29impl<'a> CountInput<'a> {
30 fn field(self) -> Option<&'a str> {
31 if let Self::Field(field) = self {
32 Some(field)
33 } else {
34 None
35 }
36 }
37
38 fn projection(self) -> Option<&'static TypeSchema> {
39 match self {
40 Self::Distinct(projection) => Some(projection),
41 _ => None,
42 }
43 }
44}
45
46#[derive(Clone, Copy, Debug, PartialEq, Eq)]
48#[repr(u8)]
49pub enum SummaryMeasure {
50 Count = 0,
52 Sum = 1,
54 Average = 2,
56}
57
58#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
60pub enum GroupOrder {
61 #[default]
63 Key,
64 AggregateAscending,
66 AggregateDescending,
68 KeyDescending,
70 FirstOccurrence,
72 Summary(SummaryMeasure, super::SortDirection),
74}
75
76struct GroupPredicate<T> {
77 measure: Option<SummaryMeasure>,
78 comparison: Comparison,
79 operand: T,
80 or_next: bool,
81}
82
83#[derive(Default)]
84pub(super) struct GroupRequest<'a> {
85 predicates: Vec<GroupPredicate<IndexValue<'a>>>,
86 order: Option<GroupOrder>,
87 page: Option<jobs::pages::PageRequest<'a>>,
88}
89impl GroupRequest<'_> {
90 fn admit_start_page(&self) -> Result<(), Error> {
91 if self.page.is_some() {
92 return Err(Error::InvalidQuery);
93 }
94 Ok(())
95 }
96
97 pub(super) fn is_empty(&self) -> bool {
98 self.predicates.is_empty() && self.order.is_none() && self.page.is_none()
99 }
100
101 fn admit(
102 &self,
103 entity: &EntitySchema,
104 reducer: &Reducer,
105 summary_sum: Option<ValueSchema>,
106 ) -> Result<Selection, Error> {
107 if self
108 .page
109 .is_some_and(|page| !(1..=MAX_GROUPS).contains(&page.size))
110 {
111 return Err(Error::Limit);
112 }
113 let field = match reducer {
114 Reducer::Keys(_) => {
115 let order = self.order.unwrap_or_default();
116 if !self.predicates.is_empty()
117 || !matches!(
118 order,
119 GroupOrder::Key | GroupOrder::KeyDescending | GroupOrder::FirstOccurrence
120 )
121 {
122 return Err(Error::InvalidQuery);
123 }
124
125 return Ok(Selection {
126 predicates: Vec::new(),
127 order,
128 optional: false,
129 });
130 }
131 Reducer::Count { .. } | Reducer::Distinct { .. } => ValueSchema {
132 value: FieldType::Nat64,
133 optional: false,
134 },
135 Reducer::Extremum { position, .. } => {
136 let field = &entity.fields[*position];
137
138 ValueSchema {
139 value: field.value,
140 optional: field.optional,
141 }
142 }
143 Reducer::Numeric(state) => state.output(),
144 };
145 if self.order == Some(GroupOrder::FirstOccurrence) {
146 return Err(Error::InvalidQuery);
147 }
148 let absent_result = !matches!(reducer, Reducer::Count { .. } | Reducer::Distinct { .. });
150 let predicates = self
151 .predicates
152 .iter()
153 .map(
154 |&GroupPredicate {
155 comparison,
156 operand: value,
157 or_next,
158 measure,
159 }| {
160 let (field, absent_result) = match (measure, summary_sum) {
161 (None, None) => (field, absent_result),
162 (Some(SummaryMeasure::Count), Some(_)) => (
163 ValueSchema {
164 value: FieldType::Nat64,
165 optional: false,
166 },
167 false,
168 ),
169 (Some(SummaryMeasure::Sum), Some(sum)) => (sum, true),
170 (Some(SummaryMeasure::Average), Some(_)) => (field, true),
171 _ => return Err(Error::InvalidQuery),
172 };
173 super::admit_literal_size(&value)?;
174 comparison.admit(field.value, absent_result, value)?;
175 let key = if value == IndexValue::Absent {
176 None
177 } else {
178 let key = value.component(field.optional);
179 if key.len() > MAX_COMPARISON_KEY {
180 return Err(Error::Limit);
181 }
182
183 Some(key)
184 };
185
186 Ok(GroupPredicate {
187 measure,
188 comparison,
189 operand: key,
190 or_next,
191 })
192 },
193 )
194 .collect::<Result<_, Error>>()?;
195
196 Ok(Selection {
197 predicates,
198 order: self.order.unwrap_or_default(),
199 optional: field.optional,
200 })
201 }
202}
203
204struct Selection {
205 predicates: Vec<GroupPredicate<Option<Vec<u8>>>>,
206 order: GroupOrder,
207 optional: bool,
209}
210
211impl Selection {
212 fn needs_summary_key(&self, measure: SummaryMeasure) -> bool {
213 matches!(self.order, GroupOrder::Summary(ordered, _) if ordered == measure)
214 || self
215 .predicates
216 .iter()
217 .any(|term| term.measure == Some(measure))
218 }
219
220 fn accepts<'a>(&self, key: impl Fn(Option<SummaryMeasure>) -> Option<&'a [u8]>) -> bool {
221 self.predicates
222 .split_inclusive(|term| !term.or_next)
223 .all(|clause| {
224 clause.iter().any(|term| {
225 term.comparison.accepts(
226 key(term.measure),
227 term.operand.as_deref(),
228 self.optional && term.measure != Some(SummaryMeasure::Count),
229 )
230 })
231 })
232 }
233}
234
235#[derive(Debug)]
237pub struct Aggregate<T> {
238 pub value: T,
240 pub examined: usize,
242 pub fetched: usize,
244 pub output_bytes: usize,
246}
247
248impl Aggregate<u64> {
249 fn at_least(self, minimum: u64) -> Aggregate<bool> {
250 Aggregate {
251 value: self.value >= minimum,
252 examined: self.examined,
253 fetched: self.fetched,
254 output_bytes: 1,
255 }
256 }
257}
258
259#[derive(Debug)]
261pub struct GroupCount<K> {
262 pub key: K,
264 pub count: u64,
266}
267
268pub type GroupSummaries<K, S, A> = Aggregate<Vec<GroupSummary<K, S, A>>>;
270
271pub type GroupSummaryPage<K, S, A> = jobs::GroupPage<GroupSummary<K, S, A>>;
273
274#[derive(Debug)]
276pub struct GroupSummary<K, S, A> {
277 pub key: K,
279 pub count: u64,
281 pub sum: Option<S>,
283 pub average: Option<A>,
285}
286
287#[derive(Debug)]
289pub struct GroupValue<K, R> {
290 pub key: K,
292 pub value: Option<R>,
294}
295
296impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
297 #[must_use]
302 pub fn group_page(mut self, size: usize, after: Option<&'a jobs::GroupCursor>) -> Self {
303 self.request.groups.page = Some(jobs::pages::PageRequest { size, after });
304
305 self
306 }
307
308 #[must_use]
315 pub fn filter_groups(self, comparison: Comparison, value: impl Into<IndexValue<'a>>) -> Self {
316 self.add_group_clause(std::iter::once((None, comparison, value.into())))
317 }
318
319 #[must_use]
322 pub fn filter_summary(
323 self,
324 measure: SummaryMeasure,
325 comparison: Comparison,
326 value: impl Into<IndexValue<'a>>,
327 ) -> Self {
328 self.add_group_clause(std::iter::once((Some(measure), comparison, value.into())))
329 }
330
331 #[must_use]
335 pub fn filter_summary_any(
336 self,
337 alternatives: &[(SummaryMeasure, Comparison, IndexValue<'a>)],
338 ) -> Self {
339 self.add_group_clause(
340 alternatives
341 .iter()
342 .map(|&(measure, comparison, value)| (Some(measure), comparison, value)),
343 )
344 }
345
346 #[must_use]
353 pub fn filter_groups_any(self, alternatives: &[(Comparison, IndexValue<'a>)]) -> Self {
354 self.add_group_clause(
355 alternatives
356 .iter()
357 .map(|&(comparison, value)| (None, comparison, value)),
358 )
359 }
360
361 fn add_group_clause(
362 mut self,
363 terms: impl ExactSizeIterator<Item = (Option<SummaryMeasure>, Comparison, IndexValue<'a>)>,
364 ) -> Self {
365 super::append_clause(
366 &mut self.request.groups.predicates,
367 &mut self.request.over_limit,
368 terms,
369 |(measure, comparison, operand), or_next| GroupPredicate {
370 measure,
371 comparison,
372 operand,
373 or_next,
374 },
375 );
376
377 self
378 }
379
380 #[must_use]
383 pub fn order_groups(mut self, order: GroupOrder) -> Self {
384 self.request.groups.order = Some(order);
385
386 self
387 }
388
389 pub fn min<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
402 observe!(query, { self.extremum(Extremum::Min) })
403 }
404
405 pub fn max<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
412 observe!(query, { self.extremum(Extremum::Max) })
413 }
414
415 fn extremum<R: Value>(self, kind: Extremum) -> Result<Aggregate<Option<R>>, Error> {
416 let (plan, reducer) = self.extremum_plan::<R>(kind)?;
417
418 self.scalar_value(plan, reducer)
419 }
420
421 fn extremum_plan<R: Value>(&self, kind: Extremum) -> Result<(Plan<'a>, Reducer), Error> {
422 let plan = self.aggregate_plan(Some(R::definition()), false)?;
423 let reducer =
424 Reducer::extremum(E::SCHEMA, plan.projection.ok_or(Error::InvalidQuery)?, kind)?;
425
426 Ok((plan, reducer))
427 }
428
429 fn scalar_value<R: Value>(
430 self,
431 mut plan: Plan<'_>,
432 mut reducer: Reducer,
433 ) -> Result<Aggregate<Option<R>>, Error> {
434 super::order::select_unique_aggregate_path(E::SCHEMA, &self.request, &mut plan)?;
435 let page = self.scan_aggregate(&plan, Accumulator::Scalar(&mut reducer))?;
436 let (value, output_bytes) = scalar_output(reducer, self.request.bytes)?;
437
438 Ok(page.into_aggregate(value, output_bytes))
439 }
440
441 pub fn group_min<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
458 observe!(query, { self.group_extrema(Extremum::Min) })
459 }
460
461 pub fn group_max<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
467 observe!(query, { self.group_extrema(Extremum::Max) })
468 }
469
470 fn group_extrema<K: Value, R: Value>(
471 self,
472 kind: Extremum,
473 ) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
474 let (plan, initial) = self.group_extremum_plan::<K, R>(kind)?;
475
476 self.group_values(plan, initial)
477 }
478
479 fn group_extremum_plan<K: Value, R: Value>(
480 &self,
481 kind: Extremum,
482 ) -> Result<(Plan<'a>, Reducer), Error> {
483 let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
484 let operand = admit_projection(E::SCHEMA, R::definition())?;
485 let initial = Reducer::extremum(E::SCHEMA, operand, kind)?;
486 plan.selected |= operand;
487
488 Ok((plan, initial))
489 }
490
491 fn group_values<K: Value, R: Value>(
492 self,
493 mut plan: Plan<'_>,
494 initial: Reducer,
495 ) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
496 super::order::select_unique_aggregate_path(E::SCHEMA, &self.request, &mut plan)?;
497 group_output(
498 self.grouped(&plan, initial, None)?,
499 &self.request,
500 decode_group_value,
501 )
502 }
503
504 pub fn exists(self) -> Result<Aggregate<bool>, Error> {
518 observe!(query, { Ok(self.validated_count_until(1)?.at_least(1)) })
519 }
520
521 pub fn count(self) -> Result<Aggregate<u64>, Error> {
537 observe!(query, {
538 if self.request.bytes < 8 {
539 return Err(Error::RowTooLarge);
540 }
541 self.count_until(u64::MAX)
542 })
543 }
544
545 pub fn has_at_least(self, minimum: u64) -> Result<Aggregate<bool>, Error> {
552 observe!(query, { Ok(self.count_until(minimum)?.at_least(minimum)) })
553 }
554
555 fn count_until(self, stop: u64) -> Result<Aggregate<u64>, Error> {
556 if self.request.is_plain_count() {
557 return self.entity_count();
558 }
559 let mut plan = self.count_plan(None)?;
560 if stop == 0 {
561 return Ok(Aggregate {
562 value: 0,
563 examined: 0,
564 fetched: 0,
565 output_bytes: 8,
566 });
567 }
568 if self.request.index.is_none()
569 && self
570 .request
571 .clauses()
572 .zip(plan.clauses())
573 .all(|(clause, terms)| {
574 clause.iter().zip(terms).any(|(p, term)| {
575 p.constant_comparison(E::SCHEMA) == Some(true)
576 || (term.tests_presence && E::SCHEMA.field_is_required(p.field))
577 })
578 })
579 {
580 return self.entity_count();
581 }
582 if let Some(count) = probe_members(
583 &self.db,
584 E::SCHEMA,
585 &self.request,
586 &plan,
587 MemberProbe::CountKeys,
588 stop,
589 )? {
590 return Ok(count);
591 }
592 if super::order::select_filtered_path(
593 E::SCHEMA,
594 &self.request,
595 &mut plan,
596 Some(MemberProbe::CountWithRows),
597 )? {
598 return self.count_keys(&plan, stop);
599 }
600 self.count_matching_rows(&plan, MemberProbe::CountWithRows, stop)
601 }
602
603 fn validated_count_until(&self, stop: u64) -> Result<Aggregate<u64>, Error> {
604 let mut plan = self.count_plan(None)?;
605 self.select_aggregate_row_path(&mut plan, Some(MemberProbe::ValidateRows))?;
606
607 self.count_matching_rows(&plan, MemberProbe::ValidateRows, stop)
608 }
609
610 fn count_matching_rows(
611 &self,
612 plan: &Plan<'_>,
613 probe: MemberProbe,
614 stop: u64,
615 ) -> Result<Aggregate<u64>, Error> {
616 if let Some(count) = probe_members(&self.db, E::SCHEMA, &self.request, plan, probe, stop)? {
617 return Ok(count);
618 }
619 let mut remaining = stop;
620 let page = self.scan_aggregate(plan, Accumulator::Until(&mut remaining))?;
621 Ok(page.into_aggregate(stop - remaining, 8))
622 }
623
624 fn entity_count(&self) -> Result<Aggregate<u64>, Error> {
625 Ok(Aggregate {
626 value: self.db.read()?.cardinality::<E>()?,
627 examined: 0,
628 fetched: 0,
629 output_bytes: 8,
630 })
631 }
632
633 pub fn count_validated(self) -> Result<Aggregate<u64>, Error> {
640 observe!(query, {
641 if self.request.bytes < 8 {
642 return Err(Error::RowTooLarge);
643 }
644 self.validated_count_until(u64::MAX)
645 })
646 }
647
648 pub fn count_index_entries(self) -> Result<Aggregate<u64>, Error> {
659 observe!(query, {
660 if self.request.index.is_none() || !self.request.predicates.is_empty() {
661 return Err(Error::InvalidQuery);
662 }
663 if self.request.bytes < 8 {
664 return Err(Error::RowTooLarge);
665 }
666 let plan = self.count_plan(None)?;
667
668 self.count_keys(&plan, u64::MAX)
669 })
670 }
671
672 fn count_keys(&self, plan: &Plan<'_>, stop: u64) -> Result<Aggregate<u64>, Error> {
673 let bounds = super::range::bounds(E::SCHEMA, &self.request, plan)?;
674 let mut examined = 0;
675 if let Some(range) = bounds {
676 let db = self.db.read()?;
677 if let Some(key) = super::range::exact_key(&range) {
678 examined = usize::from(db.map.contains_key(key));
679 } else {
680 let keys = db.map.keys_range((range.0.as_ref(), range.1.as_ref()));
681 for _ in keys {
682 if examined == self.request.work {
683 return Err(Error::Limit);
684 }
685 examined += 1;
686 if examined as u64 == stop {
687 break;
688 }
689 }
690 }
691 }
692
693 Ok(Aggregate {
694 value: examined as u64,
695 examined,
696 fetched: 0,
697 output_bytes: 8,
698 })
699 }
700
701 pub fn count_field(self, field: &str) -> Result<Aggregate<u64>, Error> {
709 observe!(query, {
710 if self.request.bytes < 8 {
711 return Err(Error::RowTooLarge);
712 }
713 let mut plan = self.count_plan(None)?;
714 self.select_aggregate_row_path(&mut plan, None)?;
715 let reducer = self.count_reducer(Some(field))?;
716
717 self.scalar_count_value(&plan, reducer)
718 })
719 }
720
721 pub fn count_distinct<K: Value>(self) -> Result<Aggregate<u64>, Error> {
732 observe!(query, {
733 if self.request.bytes < 8 {
734 return Err(Error::RowTooLarge);
735 }
736 let mut plan = self.count_plan(Some(K::definition()))?;
737 self.select_aggregate_row_path(&mut plan, None)?;
738 let projected = plan.projection.ok_or(Error::InvalidQuery)?;
739 let fixed = super::distinct::fixed_fields(E::SCHEMA, &self.request, &plan);
740
741 self.scalar_count_value(&plan, Reducer::distinct(projected & !fixed))
742 })
743 }
744
745 fn select_aggregate_row_path(
746 &self,
747 plan: &mut Plan<'static>,
748 probe: Option<MemberProbe>,
749 ) -> Result<(), Error> {
750 if plan.index.is_none() {
751 super::order::select_filtered_path(E::SCHEMA, &self.request, plan, probe)?;
752 }
753
754 Ok(())
755 }
756
757 fn scalar_count_value(
758 self,
759 plan: &Plan<'_>,
760 mut reducer: Reducer,
761 ) -> Result<Aggregate<u64>, Error> {
762 let page = self.scan_aggregate(plan, Accumulator::Scalar(&mut reducer))?;
763
764 Ok(page.into_aggregate(reducer.finish(false)?.into_count()?, 8))
765 }
766
767 pub fn group_count<K: Value>(self) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
784 observe!(query, { self.group_counts(CountInput::Rows) })
785 }
786
787 pub fn group_count_field<K: Value>(
796 self,
797 field: &str,
798 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
799 observe!(query, { self.group_counts(CountInput::Field(field)) })
800 }
801
802 pub fn group_count_distinct<K: Value, R: Value>(
816 self,
817 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
818 observe!(query, {
819 self.group_counts(CountInput::Distinct(R::definition()))
820 })
821 }
822
823 fn group_count_plan<K: Value>(
824 &self,
825 input: CountInput<'_>,
826 ) -> Result<(Plan<'static>, Reducer), Error> {
827 let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
828 let reducer = if let CountInput::Distinct(record) = input {
829 let operand = admit_projection(E::SCHEMA, record)?;
830 admit_ordered_fields(E::SCHEMA, operand)?;
831 plan.selected |= operand;
832 Reducer::distinct(operand)
833 } else {
834 self.count_reducer(input.field())?
835 };
836 Ok((plan, reducer))
837 }
838
839 fn group_counts<K: Value>(
840 self,
841 input: CountInput<'_>,
842 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
843 let (mut plan, mut reducer) = self.group_count_plan::<K>(input)?;
844 self.select_aggregate_row_path(&mut plan, None)?;
845 if let Reducer::Distinct { mask, .. } = &mut reducer {
846 let grouped = plan.projection.ok_or(Error::InvalidQuery)?;
847 let fixed = super::distinct::fixed_fields(E::SCHEMA, &self.request, &plan);
848 *mask &= !(grouped | fixed);
849 }
850 group_output(
851 self.grouped(&plan, reducer, None)?,
852 &self.request,
853 decode_group_count,
854 )
855 }
856
857 fn count_reducer(&self, field: Option<&str>) -> Result<Reducer, Error> {
858 let presence = field
860 .map(|name| E::SCHEMA.field_position(name).ok_or(Error::InvalidQuery))
861 .transpose()?
862 .filter(|&i| E::SCHEMA.fields[i].optional);
863
864 Ok(Reducer::Count { presence, total: 0 })
865 }
866
867 fn scan_aggregate(
868 &self,
869 plan: &Plan<'_>,
870 accumulator: Accumulator<'_>,
871 ) -> Result<QueryPage<Vec<u8>>, Error> {
872 execute(
873 &self.db.read()?.map,
874 E::SCHEMA,
875 &self.request,
876 plan,
877 Some(accumulator),
878 )
879 }
880
881 fn grouped(
882 &self,
883 plan: &Plan<'_>,
884 initial: Reducer,
885 summary_sum: Option<ValueSchema>,
886 ) -> Result<(Groups, QueryPage<Vec<u8>>), Error> {
887 self.request.groups.admit_start_page()?;
888 let mut groups = self
889 .request
890 .admit_groups(E::SCHEMA, plan, initial, summary_sum)?;
891 let page = self.scan_aggregate(plan, Accumulator::Groups(&mut groups))?;
892
893 Ok((groups, page))
894 }
895
896 fn count_plan(&self, output: Option<&TypeSchema>) -> Result<Plan<'static>, Error> {
897 self.request
898 .aggregate_plan(&self.db, E::SCHEMA, output, PlanOutput::ImmediateCount)
899 }
900
901 fn aggregate_plan(
902 &self,
903 output: Option<&TypeSchema>,
904 group_output: bool,
905 ) -> Result<Plan<'static>, Error> {
906 self.request.aggregate_plan(
907 &self.db,
908 E::SCHEMA,
909 output,
910 PlanOutput::Aggregate {
911 grouped: group_output,
912 },
913 )
914 }
915}
916
917impl super::Request<'_> {
918 fn is_plain_count(&self) -> bool {
921 matches!(self, Self {
922 predicates,
923 groups,
924 index: None,
925 order: None,
926 descending: false,
927 distinct: false,
928 cursor: None,
929 single_result_probe: None,
930 rows: _, work: _, bytes: _, over_limit: _,
931 } if predicates.is_empty() && groups.is_empty() && self.within_limits())
932 }
933
934 fn admit_groups(
935 &self,
936 entity: &EntitySchema,
937 plan: &Plan<'_>,
938 initial: Reducer,
939 summary_sum: Option<ValueSchema>,
940 ) -> Result<Groups, Error> {
941 if summary_sum.is_none() && matches!(self.groups.order, Some(GroupOrder::Summary(..))) {
942 return Err(Error::InvalidQuery);
943 }
944 Ok(Groups {
945 selection: self.groups.admit(entity, &initial, summary_sum)?,
946 summary_sum,
947 mask: plan.projection.ok_or(Error::InvalidQuery)?,
948 initial,
949 rows: BTreeMap::new(),
950 state_bytes: 0,
951 })
952 }
953
954 fn aggregate_plan<M: Memory>(
955 &self,
956 source: &super::QuerySource<'_, M>,
957 entity: &'static EntitySchema,
958 output: Option<&TypeSchema>,
959 kind: PlanOutput,
960 ) -> Result<Plan<'static>, Error> {
961 if self.cursor.is_some()
962 || self.distinct
963 || ((self.order.is_some() || self.descending)
964 && self.groups.order != Some(GroupOrder::FirstOccurrence))
965 {
966 return Err(Error::InvalidQuery);
967 }
968 let db = source.read()?;
969 db.schema.admits(entity)?;
970 let mut plan = Plan::admit(
971 entity,
972 self,
973 db.schema.fingerprint(),
974 db.incarnation,
975 output.map(super::Projection::Record),
976 kind,
977 )?;
978 if let Some(mask) = plan.projection {
979 admit_ordered_fields(entity, mask)?;
980 plan.selected |= mask;
981 }
982
983 Ok(plan)
984 }
985}
986
987fn scalar_output<R: Value>(reducer: Reducer, limit: usize) -> Result<(Option<R>, usize), Error> {
988 let Some(bytes) = reducer.finish(false)?.into_value()? else {
989 return Ok((None, 0));
990 };
991 let mut used = 0;
992 admit_output(bytes.len(), limit, &mut used)?;
993
994 Ok((Some(decode_record(&bytes)?), used))
995}
996
997impl QueryPage<Vec<u8>> {
998 fn into_aggregate<T>(self, value: T, output_bytes: usize) -> Aggregate<T> {
999 Aggregate {
1000 value,
1001 examined: self.examined,
1002 fetched: self.fetched,
1003 output_bytes,
1004 }
1005 }
1006}
1007
1008fn group_output<T>(
1009 (groups, page): (Groups, QueryPage<Vec<u8>>),
1010 request: &super::Request<'_>,
1011 decode: fn(&[u8], Completed) -> Result<T, Error>,
1012) -> Result<Aggregate<Vec<T>>, Error> {
1013 let mut output_bytes = 0;
1014 let value = groups
1015 .into_output(request.rows)?
1016 .into_iter()
1017 .map(|(key, result)| {
1018 admit_output(
1019 key.len() + result.encoded_len(),
1020 request.bytes,
1021 &mut output_bytes,
1022 )?;
1023
1024 decode(&key, result)
1025 })
1026 .collect::<Result<_, Error>>()?;
1027
1028 Ok(page.into_aggregate(value, output_bytes))
1029}
1030
1031fn decode_group_count<K: Value>(key: &[u8], result: Completed) -> Result<GroupCount<K>, Error> {
1032 Ok(GroupCount {
1033 key: decode_record(key)?,
1034 count: result.into_count()?,
1035 })
1036}
1037
1038fn decode_group_value<K: Value, R: Value>(
1039 key: &[u8],
1040 result: Completed,
1041) -> Result<GroupValue<K, R>, Error> {
1042 let value = result.into_value()?;
1043
1044 Ok(GroupValue {
1045 key: decode_record(key)?,
1046 value: value.as_deref().map(decode_record).transpose()?,
1047 })
1048}
1049
1050pub(super) enum Accumulator<'a> {
1052 Until(&'a mut u64),
1054 Scalar(&'a mut Reducer),
1055 Groups(&'a mut Groups),
1056}
1057impl Accumulator<'_> {
1058 pub(super) fn needs_spans(&self) -> bool {
1059 !matches!(
1060 self,
1061 Self::Until(_)
1062 | Self::Scalar(
1063 Reducer::Numeric(_)
1064 | Reducer::Count { presence: None, .. }
1065 | Reducer::Distinct { .. }
1066 )
1067 )
1068 }
1069
1070 pub(super) fn push(
1071 &mut self,
1072 entity: &EntitySchema,
1073 values: &[IndexValue<'_>],
1074 bytes: &[u8],
1075 spans: &[(u16, u16)],
1076 scratch: &mut Vec<u8>,
1077 ) -> Result<(), Error> {
1078 match self {
1079 Self::Until(remaining) => {
1080 **remaining -= 1;
1081
1082 Ok(())
1083 }
1084 Self::Scalar(state) => {
1085 state.push(entity, values, bytes, spans, scratch, MAX_STATE_BYTES)
1086 }
1087 Self::Groups(state) => state.push(entity, values, bytes, spans, scratch),
1088 }
1089 }
1090}
1091
1092#[derive(Clone, Copy)]
1093pub(super) enum Extremum {
1094 Min,
1095 Max,
1096}
1097
1098#[derive(Clone)]
1099pub(super) enum Reducer {
1100 Keys(u8),
1101 Numeric(numeric::NumericAggregate),
1102 Distinct {
1103 mask: u32,
1104 seen: DistinctKeys,
1105 key_bytes: usize,
1106 },
1107 Count {
1108 presence: Option<usize>,
1109 total: u64,
1110 },
1111 Extremum {
1112 position: usize,
1113 kind: Extremum,
1114 selected: Option<(Vec<u8>, Vec<u8>)>,
1115 },
1116}
1117impl Reducer {
1118 fn distinct(mask: u32) -> Self {
1119 Self::Distinct {
1120 mask,
1121 seen: DistinctKeys::new(),
1122 key_bytes: 0,
1123 }
1124 }
1125
1126 fn extremum(entity: &EntitySchema, mask: u32, kind: Extremum) -> Result<Self, Error> {
1127 if mask.count_ones() != 1 {
1128 return Err(Error::InvalidQuery);
1129 }
1130 let position = mask.trailing_zeros() as usize;
1131 if !key::supports(entity.fields[position].value) {
1132 return Err(Error::InvalidQuery);
1133 }
1134
1135 Ok(Self::Extremum {
1136 position,
1137 kind,
1138 selected: None,
1139 })
1140 }
1141
1142 fn retained_bytes(&self) -> usize {
1143 match self {
1144 Self::Keys(_) => 0,
1145 Self::Numeric(state) => state.retained_bytes(),
1146 Self::Count { .. } => 8,
1147 Self::Distinct { key_bytes, .. } => 8 + key_bytes,
1148 Self::Extremum { selected, .. } => selected
1149 .as_ref()
1150 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
1151 }
1152 }
1153
1154 fn finish(self, needs_numeric_key: bool) -> Result<Completed, Error> {
1155 match self {
1156 Self::Keys(_) => Ok(Completed::Key),
1157 Self::Count { total, .. } => Ok(Completed::Count(total)),
1158 Self::Distinct { seen, .. } => Ok(Completed::Count(seen.len() as u64)),
1159 Self::Extremum { selected, .. } => Ok(Completed::Value(selected)),
1160 Self::Numeric(state) => state.finish(needs_numeric_key),
1161 }
1162 }
1163
1164 fn push(
1165 &mut self,
1166 entity: &EntitySchema,
1167 values: &[IndexValue<'_>],
1168 bytes: &[u8],
1169 spans: &[(u16, u16)],
1170 scratch: &mut Vec<u8>,
1171 allowance: usize,
1172 ) -> Result<(), Error> {
1173 match self {
1174 Self::Keys(_) => {}
1175 Self::Numeric(state) => state.push(values)?,
1176 Self::Distinct {
1177 mask,
1178 seen,
1179 key_bytes,
1180 } => {
1181 comparison_key(entity, *mask, values, scratch)?;
1182 if let Err(position) =
1183 seen.binary_search_by(|key| key.as_ref().cmp(scratch.as_slice()))
1184 {
1185 let size = scratch.len();
1186 if seen.len() == MAX_DISTINCT_VALUES || 8 + *key_bytes + size > allowance {
1187 return Err(Error::Limit);
1188 }
1189 seen.insert(position, Box::from(scratch.as_slice()));
1190 *key_bytes += size;
1191 }
1192 }
1193 Self::Count { presence, total } => {
1194 *total += u64::from(presence.is_none_or(|i| bytes[usize::from(spans[i].0)] != 0));
1195 }
1196 Self::Extremum {
1197 position,
1198 kind,
1199 selected,
1200 } => {
1201 let value = values[*position];
1202 if value == IndexValue::Absent {
1203 return Ok(());
1204 }
1205 scratch.clear();
1206 value.append_component(entity.fields[*position].optional, scratch);
1207 if scratch.len() > MAX_COMPARISON_KEY {
1208 return Err(Error::Limit);
1209 }
1210 if selected.as_ref().is_none_or(|(old, _)| {
1211 if matches!(kind, Extremum::Max) {
1212 scratch.as_slice() > old.as_slice()
1213 } else {
1214 scratch.as_slice() < old.as_slice()
1215 }
1216 }) {
1217 let (start, end) = spans[*position];
1218 let output = &bytes[usize::from(start)..usize::from(end)];
1219 if let Some((old_key, old_output)) = selected
1220 && old_key.len() == scratch.len()
1221 && old_output.len() == output.len()
1222 {
1223 old_key.copy_from_slice(scratch);
1225 old_output.copy_from_slice(output);
1226 return Ok(());
1227 }
1228 if scratch.len() + output.len() > allowance {
1229 return Err(Error::Limit);
1230 }
1231 let key = scratch.as_slice().to_vec();
1233 let output = output.to_vec();
1234 if key.capacity() + output.capacity() > allowance {
1235 return Err(Error::Limit);
1236 }
1237 *selected = Some((key, output));
1238 }
1239 }
1240 }
1241
1242 Ok(())
1243 }
1244}
1245
1246enum Completed {
1248 Summary {
1249 count: u64,
1250 sum: Option<Box<[u8]>>,
1251 average: Option<Box<[u8]>>,
1252 sort_key: Option<Box<[u8]>>,
1253 },
1254 Key,
1255 Count(u64),
1256 Value(Option<(Vec<u8>, Vec<u8>)>),
1257}
1258impl Completed {
1259 fn encoded_len(&self) -> usize {
1260 match self {
1261 Self::Summary { sum, average, .. } => {
1262 8 + sum.as_deref().map_or(0, <[u8]>::len)
1263 + average.as_deref().map_or(0, <[u8]>::len)
1264 }
1265 Self::Key => 0,
1266 Self::Count(_) => 8,
1267 Self::Value(value) => value.as_ref().map_or(0, |(_, bytes)| bytes.len()),
1268 }
1269 }
1270 fn result_key<'a>(&'a self, scratch: &'a mut [u8; 8]) -> Option<&'a [u8]> {
1272 match self {
1273 Self::Summary { sort_key, .. } => sort_key.as_deref(),
1274 Self::Key => None,
1275 Self::Count(total) => {
1276 *scratch = total.to_be_bytes();
1277
1278 Some(scratch)
1279 }
1280 Self::Value(selected) => selected.as_ref().map(|(key, _)| key.as_slice()),
1281 }
1282 }
1283
1284 fn retained_bytes(&self) -> usize {
1285 match self {
1286 Self::Summary { sort_key, .. } => {
1287 self.encoded_len() + sort_key.as_deref().map_or(0, <[u8]>::len)
1288 }
1289 Self::Key => 0,
1290 Self::Count(_) => 8,
1291 Self::Value(value) => value
1292 .as_ref()
1293 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
1294 }
1295 }
1296
1297 fn into_count(self) -> Result<u64, Error> {
1298 match self {
1299 Self::Count(count) => Ok(count),
1300 _ => Err(Error::Corrupt),
1301 }
1302 }
1303
1304 fn into_value(self) -> Result<Option<Vec<u8>>, Error> {
1305 match self {
1306 Self::Value(value) => Ok(value.map(|(_, bytes)| bytes)),
1307 _ => Err(Error::Corrupt),
1308 }
1309 }
1310}
1311
1312pub(super) struct Groups {
1313 summary_sum: Option<ValueSchema>,
1314 selection: Selection,
1315 mask: u32,
1316 initial: Reducer,
1318 rows: BTreeMap<Box<[u8]>, (Vec<u8>, Reducer)>,
1319 state_bytes: usize,
1320}
1321impl Groups {
1322 fn max_keys(&self) -> usize {
1323 if matches!(self.initial, Reducer::Keys(_)) {
1324 usize::from(u8::MAX)
1325 } else {
1326 MAX_GROUPS
1327 }
1328 }
1329
1330 fn first_occurrences(&self) -> Result<Vec<&[u8]>, Error> {
1332 let mut ordered = vec![&[][..]; self.rows.len()];
1333 for (bytes, reducer) in self.rows.values() {
1334 let Reducer::Keys(position) = reducer else {
1335 return Err(Error::Corrupt);
1336 };
1337 ordered[usize::from(*position)] = bytes;
1338 }
1339 Ok(ordered)
1340 }
1341
1342 fn into_output(self, limit: usize) -> Result<Vec<(Vec<u8>, Completed)>, Error> {
1343 let mut state_bytes = self.state_bytes;
1345 let key_order = matches!(
1346 self.selection.order,
1347 GroupOrder::Key | GroupOrder::KeyDescending
1348 );
1349 let bounded_rank = !key_order && limit < self.rows.len();
1350 let compare = |a: &Completed, b: &Completed| {
1351 let (mut sa, mut sb) = ([0; 8], [0; 8]);
1352 let order = match (self.selection.order, a, b) {
1353 (
1354 GroupOrder::Summary(SummaryMeasure::Count, _),
1355 Completed::Summary { count: left, .. },
1356 Completed::Summary { count: right, .. },
1357 ) => left.cmp(right),
1358 _ => a.result_key(&mut sa).cmp(&b.result_key(&mut sb)),
1359 };
1360 if matches!(
1361 self.selection.order,
1362 GroupOrder::AggregateDescending
1363 | GroupOrder::Summary(_, super::SortDirection::Descending)
1364 ) {
1365 order.reverse()
1366 } else {
1367 order
1368 }
1369 };
1370 let retain = limit.min(self.rows.len());
1371 let mut rows = Vec::with_capacity(retain);
1372 let mut oldest = 0;
1373 let needs_value_key = !self.selection.predicates.is_empty()
1374 || matches!(
1375 self.selection.order,
1376 GroupOrder::AggregateAscending | GroupOrder::AggregateDescending
1377 );
1378 for (record, reducer) in self.rows.into_values() {
1379 let previous = reducer.retained_bytes();
1380 let (result, accepted) = if let Some(sum) = self.summary_sum {
1381 let Reducer::Numeric(state) = reducer else {
1382 return Err(Error::Corrupt);
1383 };
1384 state.finish_summary(sum, &self.selection)?
1385 } else {
1386 let result = reducer.finish(needs_value_key)?;
1387 let mut scratch = [0; 8];
1388 let key = result.result_key(&mut scratch);
1389 let accepted = self.selection.accepts(|_| key);
1390 (result, accepted)
1391 };
1392 state_bytes = state_bytes - previous + result.retained_bytes();
1393 if state_bytes > MAX_STATE_BYTES {
1394 return Err(Error::Limit);
1395 }
1396 if accepted {
1397 if bounded_rank {
1398 let position =
1400 rows.partition_point(|(_, value)| !compare(value, &result).is_gt());
1401 if position < retain {
1402 if rows.len() == retain {
1403 rows.pop();
1404 }
1405 rows.insert(position, (record, result));
1406 }
1407 } else if rows.len() < retain {
1408 rows.push((record, result));
1409 } else if self.selection.order == GroupOrder::KeyDescending {
1410 rows[oldest] = (record, result);
1412 oldest = (oldest + 1) % retain;
1413 }
1414 }
1415 }
1416 if self.selection.order == GroupOrder::KeyDescending {
1417 rows.rotate_left(oldest);
1418 rows.reverse();
1419 } else if !key_order && !bounded_rank {
1420 rows.sort_by(|(_, a), (_, b)| compare(a, b));
1422 }
1423
1424 Ok(rows)
1425 }
1426
1427 fn push(
1428 &mut self,
1429 entity: &EntitySchema,
1430 values: &[IndexValue<'_>],
1431 bytes: &[u8],
1432 spans: &[(u16, u16)],
1433 scratch: &mut Vec<u8>,
1434 ) -> Result<(), Error> {
1435 comparison_key(entity, self.mask, values, scratch)?;
1436 let available = MAX_STATE_BYTES - self.state_bytes;
1437 if let Some((_, reducer)) = self.rows.get_mut(scratch.as_slice()) {
1438 let previous = reducer.retained_bytes();
1439 reducer.push(entity, values, bytes, spans, scratch, available + previous)?;
1440 self.state_bytes = self.state_bytes - previous + reducer.retained_bytes();
1441 return Ok(());
1442 }
1443
1444 let count = self.rows.len();
1445 let size = projection_size(spans, self.mask);
1446 let base = scratch.len() + size;
1447 if count == self.max_keys() || base + self.initial.retained_bytes() > available {
1448 return Err(Error::Limit);
1449 }
1450 let key = Box::<[u8]>::from(scratch.as_slice());
1452 let mut reducer = self.initial.clone();
1453 if let Reducer::Keys(position) = &mut reducer {
1454 *position = count as u8;
1455 }
1456 reducer.push(entity, values, bytes, spans, scratch, available - base)?;
1457 let output = copy_projection(bytes, spans, self.mask, size);
1458 let retained = key.len() + output.capacity() + reducer.retained_bytes();
1461 if retained > available {
1462 return Err(Error::Limit);
1463 }
1464 self.state_bytes += retained;
1465 self.rows.insert(key, (output, reducer));
1466
1467 Ok(())
1468 }
1469}