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