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 )? {
510 return Ok(Aggregate {
511 value: result.value != 0,
512 examined: result.examined,
513 fetched: result.fetched,
514 output_bytes: 1,
515 });
516 }
517 let mut found = false;
518 let page = execute(
519 &self.db.read()?.map,
520 E::SCHEMA,
521 &self.request,
522 &plan,
523 Some(Accumulator::Exists(&mut found)),
524 )?;
525
526 Ok(Aggregate {
527 value: found,
528 examined: page.examined,
529 fetched: page.fetched,
530 output_bytes: 1,
531 })
532 })
533 }
534
535 pub fn count(self) -> Result<Aggregate<u64>, Error> {
551 observe!(query, {
552 if self.request.bytes < 8 {
553 return Err(Error::RowTooLarge);
554 }
555 let mut plan = self.aggregate_plan(None, false)?;
556 if self.request.index.is_none()
557 && self
558 .request
559 .clauses()
560 .zip(plan.clauses())
561 .all(|(clause, terms)| {
562 clause.iter().zip(terms).any(|(p, term)| {
563 p.constant_comparison(E::SCHEMA) == Some(true)
564 || (term.tests_presence && E::SCHEMA.field_is_required(p.field))
565 })
566 })
567 {
568 return Ok(Aggregate {
569 value: self.db.read()?.cardinality::<E>()?,
570 examined: 0,
571 fetched: 0,
572 output_bytes: 8,
573 });
574 }
575 if let Some(count) = probe_members(
576 &self.db,
577 E::SCHEMA,
578 &self.request,
579 &plan,
580 MemberProbe::CountKeys,
581 )? {
582 return Ok(count);
583 }
584 if super::order::select_filtered_path(
585 E::SCHEMA,
586 &self.request,
587 &mut plan,
588 Some(MemberProbe::CountWithRows),
589 )? {
590 return self.count_keys(&plan);
591 }
592 if let Some(count) = probe_members(
593 &self.db,
594 E::SCHEMA,
595 &self.request,
596 &plan,
597 MemberProbe::CountWithRows,
598 )? {
599 return Ok(count);
600 }
601 let reducer = self.count_reducer(None)?;
602
603 self.scalar_count_value(&plan, reducer)
604 })
605 }
606
607 pub fn count_validated(self) -> Result<Aggregate<u64>, Error> {
614 observe!(query, { self.scalar_count(None) })
615 }
616
617 pub fn count_index_entries(self) -> Result<Aggregate<u64>, Error> {
628 observe!(query, {
629 if self.request.index.is_none() || !self.request.predicates.is_empty() {
630 return Err(Error::InvalidQuery);
631 }
632 if self.request.bytes < 8 {
633 return Err(Error::RowTooLarge);
634 }
635 let plan = self.aggregate_plan(None, false)?;
636
637 self.count_keys(&plan)
638 })
639 }
640
641 fn count_keys(&self, plan: &Plan<'_>) -> Result<Aggregate<u64>, Error> {
642 let bounds = super::range::bounds(E::SCHEMA, &self.request, plan)?;
643 let mut examined = 0;
644 if let Some(range) = bounds {
645 let db = self.db.read()?;
646 let entries = db.map.range((range.0.as_ref(), range.1.as_ref()));
647 for _ in entries {
648 if examined == self.request.work {
649 return Err(Error::Limit);
650 }
651 examined += 1;
652 }
653 }
654
655 Ok(Aggregate {
656 value: examined as u64,
657 examined,
658 fetched: 0,
659 output_bytes: 8,
660 })
661 }
662
663 pub fn count_field(self, field: &str) -> Result<Aggregate<u64>, Error> {
671 observe!(query, { self.scalar_count(Some(field)) })
672 }
673
674 pub fn count_distinct<K: Value>(self) -> Result<Aggregate<u64>, Error> {
685 observe!(query, {
686 if self.request.bytes < 8 {
687 return Err(Error::RowTooLarge);
688 }
689 let mut plan = self.aggregate_plan(Some(K::definition()), false)?;
690 self.select_aggregate_row_path(&mut plan, None)?;
691 let projected = plan.projection.ok_or(Error::InvalidQuery)?;
692 let fixed = super::distinct::fixed_fields(E::SCHEMA, &self.request, &plan);
693
694 self.scalar_count_value(&plan, Reducer::distinct(projected & !fixed))
695 })
696 }
697
698 fn select_aggregate_row_path(
699 &self,
700 plan: &mut Plan<'static>,
701 probe: Option<MemberProbe>,
702 ) -> Result<(), Error> {
703 if plan.index.is_none() {
704 super::order::select_filtered_path(E::SCHEMA, &self.request, plan, probe)?;
705 }
706
707 Ok(())
708 }
709
710 fn scalar_count(self, field: Option<&str>) -> Result<Aggregate<u64>, Error> {
711 if self.request.bytes < 8 {
712 return Err(Error::RowTooLarge);
713 }
714 let mut plan = self.aggregate_plan(None, false)?;
715 let probe = field.is_none().then_some(MemberProbe::CountValidated);
716 self.select_aggregate_row_path(&mut plan, probe)?;
717 if let Some(probe) = probe
718 && let Some(count) = probe_members(&self.db, E::SCHEMA, &self.request, &plan, probe)?
719 {
720 return Ok(count);
721 }
722 let reducer = self.count_reducer(field)?;
723
724 self.scalar_count_value(&plan, reducer)
725 }
726
727 fn scalar_count_value(
728 self,
729 plan: &Plan<'_>,
730 mut reducer: Reducer,
731 ) -> Result<Aggregate<u64>, Error> {
732 let page = execute(
733 &self.db.read()?.map,
734 E::SCHEMA,
735 &self.request,
736 plan,
737 Some(Accumulator::Scalar(&mut reducer)),
738 )?;
739
740 Ok(Aggregate {
741 value: reducer.finish(false)?.into_count()?,
742 examined: page.examined,
743 fetched: page.fetched,
744 output_bytes: 8,
745 })
746 }
747
748 pub fn group_count<K: Value>(self) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
765 observe!(query, { self.group_counts(None) })
766 }
767
768 pub fn group_count_field<K: Value>(
777 self,
778 field: &str,
779 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
780 observe!(query, { self.group_counts(Some(field)) })
781 }
782
783 pub fn group_count_distinct<K: Value, R: Value>(
797 self,
798 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
799 observe!(query, {
800 let (plan, reducer) = self.group_distinct_plan::<K, R>()?;
801
802 self.group_count_values(plan, reducer)
803 })
804 }
805
806 fn group_distinct_plan<K: Value, R: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
807 let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
808 let operand = admit_projection(E::SCHEMA, R::definition())?;
809 admit_ordered_fields(E::SCHEMA, operand)?;
810 plan.selected |= operand;
811
812 Ok((plan, Reducer::distinct(operand)))
813 }
814
815 fn group_counts<K: Value>(
816 self,
817 field: Option<&str>,
818 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
819 let plan = self.aggregate_plan(Some(K::definition()), true)?;
820 let reducer = self.count_reducer(field)?;
821
822 self.group_count_values(plan, reducer)
823 }
824
825 fn group_count_values<K: Value>(
826 self,
827 mut plan: Plan<'static>,
828 mut reducer: Reducer,
829 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
830 self.select_aggregate_row_path(&mut plan, None)?;
831 if let Reducer::Distinct { mask, .. } = &mut reducer {
832 let grouped = plan.projection.ok_or(Error::InvalidQuery)?;
833 let fixed = super::distinct::fixed_fields(E::SCHEMA, &self.request, &plan);
834 *mask &= !(grouped | fixed);
835 }
836 group_output(
837 self.grouped(&plan, reducer, None)?,
838 &self.request,
839 decode_group_count,
840 )
841 }
842
843 fn count_reducer(&self, field: Option<&str>) -> Result<Reducer, Error> {
844 let presence = field
846 .map(|name| E::SCHEMA.field_position(name).ok_or(Error::InvalidQuery))
847 .transpose()?
848 .filter(|&i| E::SCHEMA.fields[i].optional);
849
850 Ok(Reducer::Count { presence, total: 0 })
851 }
852
853 fn grouped(
854 &self,
855 plan: &Plan<'_>,
856 initial: Reducer,
857 summary_sum: Option<ValueSchema>,
858 ) -> Result<(Groups, QueryPage<Vec<u8>>), Error> {
859 if self.request.groups.page.is_some() {
860 return Err(Error::InvalidQuery);
861 }
862 let mut groups = self.admit_groups(plan, initial, summary_sum)?;
863 let page = execute(
864 &self.db.read()?.map,
865 E::SCHEMA,
866 &self.request,
867 plan,
868 Some(Accumulator::Groups(&mut groups)),
869 )?;
870
871 Ok((groups, page))
872 }
873
874 fn admit_groups(
875 &self,
876 plan: &Plan<'_>,
877 initial: Reducer,
878 summary_sum: Option<ValueSchema>,
879 ) -> Result<Groups, Error> {
880 if summary_sum.is_none()
881 && matches!(self.request.groups.order, Some(GroupOrder::Summary(..)))
882 {
883 return Err(Error::InvalidQuery);
884 }
885 Ok(Groups {
886 selection: self
887 .request
888 .groups
889 .admit(E::SCHEMA, &initial, summary_sum)?,
890 summary_sum,
891 mask: plan.projection.ok_or(Error::InvalidQuery)?,
892 initial,
893 rows: BTreeMap::new(),
894 state_bytes: 0,
895 })
896 }
897
898 fn aggregate_plan(
899 &self,
900 output: Option<&TypeSchema>,
901 group_output: bool,
902 ) -> Result<Plan<'static>, Error> {
903 if self.request.cursor.is_some()
904 || self.request.distinct
905 || ((self.request.order.is_some() || self.request.descending)
906 && self.request.groups.order != Some(GroupOrder::FirstOccurrence))
907 {
908 return Err(Error::InvalidQuery);
909 }
910 let db = self.db.read()?;
911 db.schema.admits(E::SCHEMA)?;
912 let mut plan = Plan::admit(
913 E::SCHEMA,
914 &self.request,
915 db.schema.fingerprint(),
916 db.incarnation,
917 output.map(super::Projection::Record),
918 super::PlanOutput::Aggregate {
919 grouped: group_output,
920 },
921 )?;
922 if let Some(mask) = plan.projection {
923 admit_ordered_fields(E::SCHEMA, mask)?;
924 plan.selected |= mask;
925 }
926
927 Ok(plan)
928 }
929}
930
931fn scalar_output<R: Value>(reducer: Reducer, limit: usize) -> Result<(Option<R>, usize), Error> {
932 let Some(bytes) = reducer.finish(false)?.into_value()? else {
933 return Ok((None, 0));
934 };
935 let mut used = 0;
936 admit_output(bytes.len(), limit, &mut used)?;
937
938 Ok((Some(decode_record(&bytes)?), used))
939}
940
941fn group_output<T>(
942 (groups, page): (Groups, QueryPage<Vec<u8>>),
943 request: &super::Request<'_>,
944 decode: fn(&[u8], Completed) -> Result<T, Error>,
945) -> Result<Aggregate<Vec<T>>, Error> {
946 let mut output_bytes = 0;
947 let value = groups
948 .into_output(request.rows)?
949 .into_iter()
950 .map(|(key, result)| {
951 admit_output(
952 key.len() + result.encoded_len(),
953 request.bytes,
954 &mut output_bytes,
955 )?;
956
957 decode(&key, result)
958 })
959 .collect::<Result<_, Error>>()?;
960
961 Ok(Aggregate {
962 value,
963 examined: page.examined,
964 fetched: page.fetched,
965 output_bytes,
966 })
967}
968
969fn decode_group_count<K: Value>(key: &[u8], result: Completed) -> Result<GroupCount<K>, Error> {
970 Ok(GroupCount {
971 key: decode_record(key)?,
972 count: result.into_count()?,
973 })
974}
975
976fn decode_group_value<K: Value, R: Value>(
977 key: &[u8],
978 result: Completed,
979) -> Result<GroupValue<K, R>, Error> {
980 let value = result.into_value()?;
981
982 Ok(GroupValue {
983 key: decode_record(key)?,
984 value: value.as_deref().map(decode_record).transpose()?,
985 })
986}
987
988fn decode_record<R: Value>(bytes: &[u8]) -> Result<R, Error> {
989 let mut reader = Decoder::new(bytes)?;
990 let value = R::decode_from(&mut reader)?;
991 reader.finish()?;
992
993 Ok(value)
994}
995
996pub(super) enum Accumulator<'a> {
998 Exists(&'a mut bool),
1000 Scalar(&'a mut Reducer),
1001 Groups(&'a mut Groups),
1002}
1003impl Accumulator<'_> {
1004 pub(super) fn needs_spans(&self) -> bool {
1005 !matches!(
1006 self,
1007 Self::Exists(_)
1008 | Self::Scalar(
1009 Reducer::Numeric(_)
1010 | Reducer::Count { presence: None, .. }
1011 | Reducer::Distinct { .. }
1012 )
1013 )
1014 }
1015
1016 pub(super) fn push(
1017 &mut self,
1018 entity: &EntitySchema,
1019 values: &[IndexValue<'_>],
1020 bytes: &[u8],
1021 spans: &[(u16, u16)],
1022 scratch: &mut Vec<u8>,
1023 ) -> Result<(), Error> {
1024 match self {
1025 Self::Exists(found) => {
1026 **found = true;
1027
1028 Ok(())
1029 }
1030 Self::Scalar(state) => {
1031 state.push(entity, values, bytes, spans, scratch, MAX_STATE_BYTES)
1032 }
1033 Self::Groups(state) => state.push(entity, values, bytes, spans, scratch),
1034 }
1035 }
1036}
1037
1038#[derive(Clone)]
1039pub(super) enum Reducer {
1040 Keys(u8),
1041 Numeric(numeric::NumericAggregate),
1042 Distinct {
1043 mask: u32,
1044 seen: DistinctKeys,
1045 key_bytes: usize,
1046 },
1047 Count {
1048 presence: Option<usize>,
1049 total: u64,
1050 },
1051 Extremum {
1052 position: usize,
1053 maximum: bool,
1054 selected: Option<(Vec<u8>, Vec<u8>)>,
1055 },
1056}
1057impl Reducer {
1058 fn distinct(mask: u32) -> Self {
1059 Self::Distinct {
1060 mask,
1061 seen: DistinctKeys::new(),
1062 key_bytes: 0,
1063 }
1064 }
1065
1066 fn extremum(entity: &EntitySchema, mask: u32, maximum: bool) -> Result<Self, Error> {
1067 if mask.count_ones() != 1 {
1068 return Err(Error::InvalidQuery);
1069 }
1070 let position = mask.trailing_zeros() as usize;
1071 if !key::supports(entity.fields[position].value) {
1072 return Err(Error::InvalidQuery);
1073 }
1074
1075 Ok(Self::Extremum {
1076 position,
1077 maximum,
1078 selected: None,
1079 })
1080 }
1081
1082 fn retained_bytes(&self) -> usize {
1083 match self {
1084 Self::Keys(_) => 0,
1085 Self::Numeric(state) => state.retained_bytes(),
1086 Self::Count { .. } => 8,
1087 Self::Distinct { key_bytes, .. } => 8 + key_bytes,
1088 Self::Extremum { selected, .. } => selected
1089 .as_ref()
1090 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
1091 }
1092 }
1093
1094 fn finish(self, needs_numeric_key: bool) -> Result<Completed, Error> {
1095 match self {
1096 Self::Keys(_) => Ok(Completed::Key),
1097 Self::Count { total, .. } => Ok(Completed::Count(total)),
1098 Self::Distinct { seen, .. } => Ok(Completed::Count(seen.len() as u64)),
1099 Self::Extremum { selected, .. } => Ok(Completed::Value(selected)),
1100 Self::Numeric(state) => state.finish(needs_numeric_key),
1101 }
1102 }
1103
1104 fn push(
1105 &mut self,
1106 entity: &EntitySchema,
1107 values: &[IndexValue<'_>],
1108 bytes: &[u8],
1109 spans: &[(u16, u16)],
1110 scratch: &mut Vec<u8>,
1111 allowance: usize,
1112 ) -> Result<(), Error> {
1113 match self {
1114 Self::Keys(_) => {}
1115 Self::Numeric(state) => state.push(values)?,
1116 Self::Distinct {
1117 mask,
1118 seen,
1119 key_bytes,
1120 } => {
1121 comparison_key(entity, *mask, values, scratch)?;
1122 if let Err(position) =
1123 seen.binary_search_by(|key| key.as_ref().cmp(scratch.as_slice()))
1124 {
1125 let size = scratch.len();
1126 if seen.len() == MAX_DISTINCT_VALUES || 8 + *key_bytes + size > allowance {
1127 return Err(Error::Limit);
1128 }
1129 seen.insert(position, Box::from(scratch.as_slice()));
1130 *key_bytes += size;
1131 }
1132 }
1133 Self::Count { presence, total } => {
1134 *total += u64::from(presence.is_none_or(|i| bytes[usize::from(spans[i].0)] != 0));
1135 }
1136 Self::Extremum {
1137 position,
1138 maximum,
1139 selected,
1140 } => {
1141 let value = values[*position];
1142 if value == IndexValue::Absent {
1143 return Ok(());
1144 }
1145 scratch.clear();
1146 value.append_component(entity.fields[*position].optional, scratch);
1147 if scratch.len() > MAX_COMPARISON_KEY {
1148 return Err(Error::Limit);
1149 }
1150 if selected.as_ref().is_none_or(|(old, _)| {
1151 if *maximum {
1152 scratch.as_slice() > old.as_slice()
1153 } else {
1154 scratch.as_slice() < old.as_slice()
1155 }
1156 }) {
1157 let (start, end) = spans[*position];
1158 let output = &bytes[usize::from(start)..usize::from(end)];
1159 if let Some((old_key, old_output)) = selected
1160 && old_key.len() == scratch.len()
1161 && old_output.len() == output.len()
1162 {
1163 old_key.copy_from_slice(scratch);
1165 old_output.copy_from_slice(output);
1166 return Ok(());
1167 }
1168 if scratch.len() + output.len() > allowance {
1169 return Err(Error::Limit);
1170 }
1171 let key = scratch.as_slice().to_vec();
1173 let output = output.to_vec();
1174 if key.capacity() + output.capacity() > allowance {
1175 return Err(Error::Limit);
1176 }
1177 *selected = Some((key, output));
1178 }
1179 }
1180 }
1181
1182 Ok(())
1183 }
1184}
1185
1186enum Completed {
1188 Summary {
1189 count: u64,
1190 sum: Option<Box<[u8]>>,
1191 average: Option<Box<[u8]>>,
1192 sort_key: Option<Box<[u8]>>,
1193 },
1194 Key,
1195 Count(u64),
1196 Value(Option<(Vec<u8>, Vec<u8>)>),
1197}
1198impl Completed {
1199 fn encoded_len(&self) -> usize {
1200 match self {
1201 Self::Summary { sum, average, .. } => {
1202 8 + sum.as_deref().map_or(0, <[u8]>::len)
1203 + average.as_deref().map_or(0, <[u8]>::len)
1204 }
1205 Self::Key => 0,
1206 Self::Count(_) => 8,
1207 Self::Value(value) => value.as_ref().map_or(0, |(_, bytes)| bytes.len()),
1208 }
1209 }
1210 fn result_key<'a>(&'a self, scratch: &'a mut [u8; 8]) -> Option<&'a [u8]> {
1212 match self {
1213 Self::Summary { sort_key, .. } => sort_key.as_deref(),
1214 Self::Key => None,
1215 Self::Count(total) => {
1216 *scratch = total.to_be_bytes();
1217
1218 Some(scratch)
1219 }
1220 Self::Value(selected) => selected.as_ref().map(|(key, _)| key.as_slice()),
1221 }
1222 }
1223
1224 fn retained_bytes(&self) -> usize {
1225 match self {
1226 Self::Summary { sort_key, .. } => {
1227 self.encoded_len() + sort_key.as_deref().map_or(0, <[u8]>::len)
1228 }
1229 Self::Key => 0,
1230 Self::Count(_) => 8,
1231 Self::Value(value) => value
1232 .as_ref()
1233 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
1234 }
1235 }
1236
1237 fn into_count(self) -> Result<u64, Error> {
1238 match self {
1239 Self::Count(count) => Ok(count),
1240 _ => Err(Error::Corrupt),
1241 }
1242 }
1243
1244 fn into_value(self) -> Result<Option<Vec<u8>>, Error> {
1245 match self {
1246 Self::Value(value) => Ok(value.map(|(_, bytes)| bytes)),
1247 _ => Err(Error::Corrupt),
1248 }
1249 }
1250}
1251
1252pub(super) struct Groups {
1253 summary_sum: Option<ValueSchema>,
1254 selection: Selection,
1255 mask: u32,
1256 initial: Reducer,
1258 rows: BTreeMap<Box<[u8]>, (Vec<u8>, Reducer)>,
1259 state_bytes: usize,
1260}
1261impl Groups {
1262 fn max_keys(&self) -> usize {
1263 if matches!(self.initial, Reducer::Keys(_)) {
1264 usize::from(u8::MAX)
1265 } else {
1266 MAX_GROUPS
1267 }
1268 }
1269
1270 fn first_occurrences(&self) -> Result<Vec<&[u8]>, Error> {
1272 let mut ordered = vec![&[][..]; self.rows.len()];
1273 for (bytes, reducer) in self.rows.values() {
1274 let Reducer::Keys(position) = reducer else {
1275 return Err(Error::Corrupt);
1276 };
1277 ordered[usize::from(*position)] = bytes;
1278 }
1279 Ok(ordered)
1280 }
1281
1282 fn into_output(self, limit: usize) -> Result<Vec<(Vec<u8>, Completed)>, Error> {
1283 let mut state_bytes = self.state_bytes;
1285 let key_order = matches!(
1286 self.selection.order,
1287 GroupOrder::Key | GroupOrder::KeyDescending
1288 );
1289 let bounded_rank = !key_order && limit < self.rows.len();
1290 let compare = |a: &Completed, b: &Completed| {
1291 let (mut sa, mut sb) = ([0; 8], [0; 8]);
1292 let order = match (self.selection.order, a, b) {
1293 (
1294 GroupOrder::Summary(SummaryMeasure::Count, _),
1295 Completed::Summary { count: left, .. },
1296 Completed::Summary { count: right, .. },
1297 ) => left.cmp(right),
1298 _ => a.result_key(&mut sa).cmp(&b.result_key(&mut sb)),
1299 };
1300 if matches!(
1301 self.selection.order,
1302 GroupOrder::AggregateDescending
1303 | GroupOrder::Summary(_, super::SortDirection::Descending)
1304 ) {
1305 order.reverse()
1306 } else {
1307 order
1308 }
1309 };
1310 let retain = limit.min(self.rows.len());
1311 let mut rows = Vec::with_capacity(retain);
1312 let mut oldest = 0;
1313 let needs_value_key = !self.selection.predicates.is_empty()
1314 || matches!(
1315 self.selection.order,
1316 GroupOrder::AggregateAscending | GroupOrder::AggregateDescending
1317 );
1318 for (record, reducer) in self.rows.into_values() {
1319 let previous = reducer.retained_bytes();
1320 let (result, accepted) = if let Some(sum) = self.summary_sum {
1321 let Reducer::Numeric(state) = reducer else {
1322 return Err(Error::Corrupt);
1323 };
1324 state.finish_summary(sum, &self.selection)?
1325 } else {
1326 let result = reducer.finish(needs_value_key)?;
1327 let mut scratch = [0; 8];
1328 let key = result.result_key(&mut scratch);
1329 let accepted = self.selection.accepts(|_| key);
1330 (result, accepted)
1331 };
1332 state_bytes = state_bytes - previous + result.retained_bytes();
1333 if state_bytes > MAX_STATE_BYTES {
1334 return Err(Error::Limit);
1335 }
1336 if accepted {
1337 if bounded_rank {
1338 let position =
1340 rows.partition_point(|(_, value)| !compare(value, &result).is_gt());
1341 if position < retain {
1342 if rows.len() == retain {
1343 rows.pop();
1344 }
1345 rows.insert(position, (record, result));
1346 }
1347 } else if rows.len() < retain {
1348 rows.push((record, result));
1349 } else if self.selection.order == GroupOrder::KeyDescending {
1350 rows[oldest] = (record, result);
1352 oldest = (oldest + 1) % retain;
1353 }
1354 }
1355 }
1356 if self.selection.order == GroupOrder::KeyDescending {
1357 rows.rotate_left(oldest);
1358 rows.reverse();
1359 } else if !key_order && !bounded_rank {
1360 rows.sort_by(|(_, a), (_, b)| compare(a, b));
1362 }
1363
1364 Ok(rows)
1365 }
1366
1367 fn push(
1368 &mut self,
1369 entity: &EntitySchema,
1370 values: &[IndexValue<'_>],
1371 bytes: &[u8],
1372 spans: &[(u16, u16)],
1373 scratch: &mut Vec<u8>,
1374 ) -> Result<(), Error> {
1375 comparison_key(entity, self.mask, values, scratch)?;
1376 let available = MAX_STATE_BYTES - self.state_bytes;
1377 if let Some((_, reducer)) = self.rows.get_mut(scratch.as_slice()) {
1378 let previous = reducer.retained_bytes();
1379 reducer.push(entity, values, bytes, spans, scratch, available + previous)?;
1380 self.state_bytes = self.state_bytes - previous + reducer.retained_bytes();
1381 return Ok(());
1382 }
1383
1384 let count = self.rows.len();
1385 let size = projection_size(spans, self.mask);
1386 let base = scratch.len() + size;
1387 if count == self.max_keys() || base + self.initial.retained_bytes() > available {
1388 return Err(Error::Limit);
1389 }
1390 let key = Box::<[u8]>::from(scratch.as_slice());
1392 let mut reducer = self.initial.clone();
1393 if let Reducer::Keys(position) = &mut reducer {
1394 *position = count as u8;
1395 }
1396 reducer.push(entity, values, bytes, spans, scratch, available - base)?;
1397 let output = copy_projection(bytes, spans, self.mask, size);
1398 let retained = key.len() + output.capacity() + reducer.retained_bytes();
1401 if retained > available {
1402 return Err(Error::Limit);
1403 }
1404 self.state_bytes += retained;
1405 self.rows.insert(key, (output, reducer));
1406
1407 Ok(())
1408 }
1409}