1pub(super) mod jobs;
4mod numeric;
5
6use super::{
7 Comparison, MAX_COMPARISON_KEY, MAX_DISTINCT_VALUES, MAX_STATE_BYTES, MAX_TERMS, Plan, Query,
8 QueryPage, admit_ordered_fields, admit_output, admit_projection, comparison_key,
9 copy_projection, execute, projection_size,
10};
11use crate::{
12 Entity, EntitySchema, Error, FieldType, IndexValue, TypeSchema, Value, ValueSchema,
13 codec::Decoder, key,
14};
15use ic_storage::Memory;
16use std::collections::{BTreeMap, BTreeSet};
17
18const MAX_GROUPS: usize = 32;
19
20#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
22pub enum GroupOrder {
23 #[default]
25 Key,
26 AggregateAscending,
28 AggregateDescending,
30 KeyDescending,
32}
33
34#[derive(Default)]
35pub(super) struct GroupRequest<'a> {
36 predicates: Vec<(Comparison, IndexValue<'a>, bool)>,
38 order: Option<GroupOrder>,
39 page: Option<jobs::pages::PageRequest<'a>>,
40}
41impl GroupRequest<'_> {
42 pub(super) fn is_empty(&self) -> bool {
43 self.predicates.is_empty() && self.order.is_none() && self.page.is_none()
44 }
45
46 fn admit(&self, entity: &EntitySchema, reducer: &Reducer) -> Result<Selection, Error> {
47 if self
48 .page
49 .is_some_and(|page| !(1..=MAX_GROUPS).contains(&page.size))
50 {
51 return Err(Error::Limit);
52 }
53 let field = match reducer {
54 Reducer::Count { .. } | Reducer::Distinct { .. } => ValueSchema {
55 value: FieldType::Nat64,
56 optional: false,
57 },
58 Reducer::Extremum { position, .. } => {
59 let field = &entity.fields[*position];
60
61 ValueSchema {
62 value: field.value,
63 optional: field.optional,
64 }
65 }
66 Reducer::Numeric(state) => state.output(),
67 };
68 let absent_result = !matches!(reducer, Reducer::Count { .. } | Reducer::Distinct { .. });
70 let predicates = self
71 .predicates
72 .iter()
73 .map(|&(comparison, value, or_next)| {
74 if match value {
75 IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
76 IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
77 _ => false,
78 } {
79 return Err(Error::Limit);
80 }
81 comparison.admit(field.value, absent_result, value)?;
82 let key = if value == IndexValue::Absent {
83 None
84 } else {
85 let mut key = Vec::new();
86 value.append_component(field.optional, &mut key);
87 if key.len() > MAX_COMPARISON_KEY {
88 return Err(Error::Limit);
89 }
90
91 Some(key)
92 };
93
94 Ok((comparison, key, or_next))
95 })
96 .collect::<Result<_, Error>>()?;
97
98 Ok(Selection {
99 predicates,
100 order: self.order.unwrap_or_default(),
101 optional: field.optional,
102 })
103 }
104}
105
106struct Selection {
107 predicates: Vec<(Comparison, Option<Vec<u8>>, bool)>,
108 order: GroupOrder,
109 optional: bool,
111}
112
113#[derive(Debug)]
115pub struct Aggregate<T> {
116 pub value: T,
118 pub examined: usize,
120 pub fetched: usize,
122 pub output_bytes: usize,
124}
125
126#[derive(Debug)]
128pub struct GroupCount<K> {
129 pub key: K,
131 pub count: u64,
133}
134
135#[derive(Debug)]
137pub struct GroupValue<K, R> {
138 pub key: K,
140 pub value: Option<R>,
142}
143
144impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
145 #[must_use]
150 pub fn group_page(mut self, size: usize, after: Option<&'a jobs::GroupCursor>) -> Self {
151 self.request.groups.page = Some(jobs::pages::PageRequest { size, after });
152
153 self
154 }
155
156 #[must_use]
163 pub fn filter_groups(
164 mut self,
165 comparison: Comparison,
166 value: impl Into<IndexValue<'a>>,
167 ) -> Self {
168 if self.request.groups.predicates.len() == MAX_TERMS {
169 self.request.over_limit = true;
170 } else {
171 self.request
172 .groups
173 .predicates
174 .push((comparison, value.into(), false));
175 }
176
177 self
178 }
179
180 #[must_use]
187 pub fn filter_groups_any(mut self, alternatives: &[(Comparison, IndexValue<'a>)]) -> Self {
188 let count = alternatives.len();
189 if count == 0 || count > MAX_TERMS - self.request.groups.predicates.len() {
190 self.request.over_limit = true;
191 } else {
192 self.request.groups.predicates.extend(
193 alternatives
194 .iter()
195 .enumerate()
196 .map(|(i, &(comparison, value))| (comparison, value, i + 1 != count)),
197 );
198 }
199
200 self
201 }
202
203 #[must_use]
206 pub fn order_groups(mut self, order: GroupOrder) -> Self {
207 self.request.groups.order = Some(order);
208
209 self
210 }
211
212 pub fn min<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
225 self.extremum(false)
226 }
227
228 pub fn max<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
235 self.extremum(true)
236 }
237
238 fn extremum<R: Value>(self, maximum: bool) -> Result<Aggregate<Option<R>>, Error> {
239 let (plan, reducer) = self.extremum_plan::<R>(maximum)?;
240
241 self.scalar_value(&plan, reducer)
242 }
243
244 fn extremum_plan<R: Value>(&self, maximum: bool) -> Result<(Plan<'a>, Reducer), Error> {
245 let plan = self.aggregate_plan(Some(R::definition()), false)?;
246 let reducer = Reducer::extremum(
247 E::SCHEMA,
248 plan.projection.ok_or(Error::InvalidQuery)?,
249 maximum,
250 )?;
251
252 Ok((plan, reducer))
253 }
254
255 fn scalar_value<R: Value>(
256 self,
257 plan: &Plan<'_>,
258 mut reducer: Reducer,
259 ) -> Result<Aggregate<Option<R>>, Error> {
260 let page = execute(
261 &self.db.read()?.map,
262 E::SCHEMA,
263 &self.request,
264 plan,
265 Some(Accumulator::Scalar(&mut reducer)),
266 )?;
267 let mut output_bytes = 0;
268 let value = reducer
269 .finish()?
270 .into_value()?
271 .map(|bytes| {
272 admit_output(bytes.len(), self.request.bytes, &mut output_bytes)?;
273
274 decode_record(&bytes)
275 })
276 .transpose()?;
277
278 Ok(Aggregate {
279 value,
280 examined: page.examined,
281 fetched: page.fetched,
282 output_bytes,
283 })
284 }
285
286 pub fn group_min<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
303 self.group_extrema(false)
304 }
305
306 pub fn group_max<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
312 self.group_extrema(true)
313 }
314
315 fn group_extrema<K: Value, R: Value>(
316 self,
317 maximum: bool,
318 ) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
319 let (plan, initial) = self.group_extremum_plan::<K, R>(maximum)?;
320
321 self.group_values(&plan, initial)
322 }
323
324 fn group_extremum_plan<K: Value, R: Value>(
325 &self,
326 maximum: bool,
327 ) -> Result<(Plan<'a>, Reducer), Error> {
328 let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
329 let operand = admit_projection(E::SCHEMA, R::definition())?;
330 let initial = Reducer::extremum(E::SCHEMA, operand, maximum)?;
331 plan.selected |= operand;
332
333 Ok((plan, initial))
334 }
335
336 fn group_values<K: Value, R: Value>(
337 self,
338 plan: &Plan<'_>,
339 initial: Reducer,
340 ) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
341 let (groups, page) = self.grouped(plan, initial)?;
342 let (value, output_bytes) = group_output(
343 groups,
344 self.request.rows,
345 self.request.bytes,
346 decode_group_value,
347 )?;
348
349 Ok(Aggregate {
350 value,
351 examined: page.examined,
352 fetched: page.fetched,
353 output_bytes,
354 })
355 }
356
357 pub fn exists(self) -> Result<Aggregate<bool>, Error> {
370 let mut plan = self.aggregate_plan(None, false)?;
371 self.select_aggregate_row_path(&mut plan)?;
372 let mut found = false;
373 let page = execute(
374 &self.db.read()?.map,
375 E::SCHEMA,
376 &self.request,
377 &plan,
378 Some(Accumulator::Exists(&mut found)),
379 )?;
380
381 Ok(Aggregate {
382 value: found,
383 examined: page.examined,
384 fetched: page.fetched,
385 output_bytes: 1,
386 })
387 }
388
389 pub fn count(self) -> Result<Aggregate<u64>, Error> {
406 if self.request.bytes < 8 {
407 return Err(Error::RowTooLarge);
408 }
409 let mut plan = self.aggregate_plan(None, false)?;
410 if self.request.predicates.is_empty() && self.request.index.is_none() {
411 return Ok(Aggregate {
412 value: self.db.read()?.cardinality::<E>()?,
413 examined: 0,
414 fetched: 0,
415 output_bytes: 8,
416 });
417 }
418 if plan.index.is_none()
419 && let Some(count) = self.count_members(&plan)?
420 {
421 return Ok(count);
422 }
423 if super::order::select_aggregate_path(E::SCHEMA, &self.request, &mut plan)? {
424 return self.count_keys(&plan);
425 }
426 if plan.index.is_some()
427 && let Some(count) = self.count_members(&plan)?
428 {
429 return Ok(count);
430 }
431 let reducer = self.count_reducer(None)?;
432
433 self.scalar_count_value(&plan, reducer)
434 }
435
436 pub fn count_validated(self) -> Result<Aggregate<u64>, Error> {
441 self.scalar_count(None)
442 }
443
444 pub fn count_index_entries(self) -> Result<Aggregate<u64>, Error> {
456 if self.request.index.is_none() || !self.request.predicates.is_empty() {
457 return Err(Error::InvalidQuery);
458 }
459 if self.request.bytes < 8 {
460 return Err(Error::RowTooLarge);
461 }
462 let plan = self.aggregate_plan(None, false)?;
463
464 self.count_keys(&plan)
465 }
466
467 fn count_members(&self, plan: &Plan<'_>) -> Result<Option<Aggregate<u64>>, Error> {
468 let Some(members) = super::range::point_count_members(E::SCHEMA, plan, &self.request)
469 else {
470 return Ok(None);
471 };
472 let db = self.db.read()?;
473 let mut count = 0;
474 for member in &members {
475 let key = crate::store_key::StoreKey::new([plan.prefix.as_slice(), *member].concat())?;
476 count += u64::from(db.map.contains_key(&key));
477 }
478
479 Ok(Some(Aggregate {
480 value: count,
481 examined: members.len(),
482 fetched: 0,
483 output_bytes: 8,
484 }))
485 }
486
487 fn count_keys(&self, plan: &Plan<'_>) -> Result<Aggregate<u64>, Error> {
488 let bounds = super::range::bounds(E::SCHEMA, &self.request, plan)?;
489 let mut examined = 0;
490 if let Some(range) = bounds {
491 let terminal = super::range::terminal_key(&range, false);
492 let db = self.db.read()?;
493 let entries = db.map.range((range.0.as_ref(), range.1.as_ref()));
494 for entry in entries.take(self.request.work) {
495 examined += 1;
496 if examined == self.request.work && terminal.is_none_or(|end| end != entry.key()) {
497 return Err(Error::Limit);
498 }
499 }
500 }
501
502 Ok(Aggregate {
503 value: examined as u64,
504 examined,
505 fetched: 0,
506 output_bytes: 8,
507 })
508 }
509
510 pub fn count_field(self, field: &str) -> Result<Aggregate<u64>, Error> {
518 self.scalar_count(Some(field))
519 }
520
521 pub fn count_distinct<K: Value>(self) -> Result<Aggregate<u64>, Error> {
530 if self.request.bytes < 8 {
531 return Err(Error::RowTooLarge);
532 }
533 let (mut plan, reducer) = self.distinct_plan::<K>()?;
534 self.select_aggregate_row_path(&mut plan)?;
535
536 self.scalar_count_value(&plan, reducer)
537 }
538
539 fn distinct_plan<K: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
540 let plan = self.aggregate_plan(Some(K::definition()), false)?;
541 let reducer = Reducer::distinct(plan.projection.ok_or(Error::InvalidQuery)?);
542
543 Ok((plan, reducer))
544 }
545
546 fn select_aggregate_row_path(&self, plan: &mut Plan<'static>) -> Result<(), Error> {
547 if plan.index.is_none() {
548 super::order::select_aggregate_path(E::SCHEMA, &self.request, plan)?;
549 }
550
551 Ok(())
552 }
553
554 fn scalar_count(self, field: Option<&str>) -> Result<Aggregate<u64>, Error> {
555 if self.request.bytes < 8 {
556 return Err(Error::RowTooLarge);
557 }
558 let mut plan = self.aggregate_plan(None, false)?;
559 self.select_aggregate_row_path(&mut plan)?;
560 let reducer = self.count_reducer(field)?;
561
562 self.scalar_count_value(&plan, reducer)
563 }
564
565 fn scalar_count_value(
566 self,
567 plan: &Plan<'_>,
568 mut reducer: Reducer,
569 ) -> Result<Aggregate<u64>, Error> {
570 let page = execute(
571 &self.db.read()?.map,
572 E::SCHEMA,
573 &self.request,
574 plan,
575 Some(Accumulator::Scalar(&mut reducer)),
576 )?;
577
578 Ok(Aggregate {
579 value: reducer.finish()?.into_count()?,
580 examined: page.examined,
581 fetched: page.fetched,
582 output_bytes: 8,
583 })
584 }
585
586 pub fn group_count<K: Value>(self) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
603 self.group_counts(None)
604 }
605
606 pub fn group_count_field<K: Value>(
615 self,
616 field: &str,
617 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
618 self.group_counts(Some(field))
619 }
620
621 pub fn group_count_distinct<K: Value, R: Value>(
634 self,
635 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
636 let (plan, reducer) = self.group_distinct_plan::<K, R>()?;
637
638 self.group_count_values(plan, reducer)
639 }
640
641 fn group_distinct_plan<K: Value, R: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
642 let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
643 let operand = admit_projection(E::SCHEMA, R::definition())?;
644 admit_ordered_fields(E::SCHEMA, operand)?;
645 plan.selected |= operand;
646
647 Ok((plan, Reducer::distinct(operand)))
648 }
649
650 fn group_counts<K: Value>(
651 self,
652 field: Option<&str>,
653 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
654 let plan = self.aggregate_plan(Some(K::definition()), true)?;
655 let reducer = self.count_reducer(field)?;
656
657 self.group_count_values(plan, reducer)
658 }
659
660 fn group_count_values<K: Value>(
661 self,
662 mut plan: Plan<'static>,
663 reducer: Reducer,
664 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
665 self.select_aggregate_row_path(&mut plan)?;
666 let (groups, page) = self.grouped(&plan, reducer)?;
667 let (value, output_bytes) = group_output(
668 groups,
669 self.request.rows,
670 self.request.bytes,
671 decode_group_count,
672 )?;
673
674 Ok(Aggregate {
675 value,
676 examined: page.examined,
677 fetched: page.fetched,
678 output_bytes,
679 })
680 }
681
682 fn count_reducer(&self, field: Option<&str>) -> Result<Reducer, Error> {
683 let presence = field
685 .map(|name| E::SCHEMA.field_position(name).ok_or(Error::InvalidQuery))
686 .transpose()?
687 .filter(|&i| E::SCHEMA.fields[i].optional);
688
689 Ok(Reducer::Count { presence, total: 0 })
690 }
691
692 fn grouped(
693 &self,
694 plan: &Plan<'_>,
695 initial: Reducer,
696 ) -> Result<(Groups, QueryPage<Vec<u8>>), Error> {
697 if self.request.groups.page.is_some() {
698 return Err(Error::InvalidQuery);
699 }
700 let mut groups = self.admit_groups(plan, initial)?;
701 let page = execute(
702 &self.db.read()?.map,
703 E::SCHEMA,
704 &self.request,
705 plan,
706 Some(Accumulator::Groups(&mut groups)),
707 )?;
708
709 Ok((groups, page))
710 }
711
712 fn admit_groups(&self, plan: &Plan<'_>, initial: Reducer) -> Result<Groups, Error> {
713 Ok(Groups {
714 selection: self.request.groups.admit(E::SCHEMA, &initial)?,
715 mask: plan.projection.ok_or(Error::InvalidQuery)?,
716 initial,
717 rows: BTreeMap::new(),
718 state_bytes: 0,
719 })
720 }
721
722 fn aggregate_plan(
723 &self,
724 output: Option<&TypeSchema>,
725 group_output: bool,
726 ) -> Result<Plan<'static>, Error> {
727 if self.request.cursor.is_some()
728 || self.request.distinct
729 || self.request.order.is_some()
730 || self.request.descending
731 {
732 return Err(Error::InvalidQuery);
733 }
734 let db = self.db.read()?;
735 db.schema.admits(E::SCHEMA)?;
736 let mut plan = Plan::admit(
737 E::SCHEMA,
738 &self.request,
739 db.schema.fingerprint(),
740 db.incarnation,
741 output,
742 super::PlanOutput::Aggregate {
743 grouped: group_output,
744 },
745 )?;
746 if let Some(mask) = plan.projection {
747 admit_ordered_fields(E::SCHEMA, mask)?;
748 plan.selected |= mask;
749 }
750
751 Ok(plan)
752 }
753}
754
755fn group_output<T>(
756 groups: Groups,
757 rows: usize,
758 bytes: usize,
759 decode: fn(&[u8], Completed) -> Result<T, Error>,
760) -> Result<(Vec<T>, usize), Error> {
761 let mut output_bytes = 0;
762 let value = groups
763 .into_output()?
764 .into_iter()
765 .take(rows)
766 .map(|(key, result)| {
767 admit_output(key.len() + result.encoded_len(), bytes, &mut output_bytes)?;
768
769 decode(&key, result)
770 })
771 .collect::<Result<_, Error>>()?;
772
773 Ok((value, output_bytes))
774}
775
776fn decode_group_count<K: Value>(key: &[u8], result: Completed) -> Result<GroupCount<K>, Error> {
777 Ok(GroupCount {
778 key: decode_record(key)?,
779 count: result.into_count()?,
780 })
781}
782
783fn decode_group_value<K: Value, R: Value>(
784 key: &[u8],
785 result: Completed,
786) -> Result<GroupValue<K, R>, Error> {
787 let value = result.into_value()?;
788
789 Ok(GroupValue {
790 key: decode_record(key)?,
791 value: value.as_deref().map(decode_record).transpose()?,
792 })
793}
794
795fn decode_record<R: Value>(bytes: &[u8]) -> Result<R, Error> {
796 let mut reader = Decoder::new(bytes)?;
797 let value = R::decode_from(&mut reader)?;
798 reader.finish()?;
799
800 Ok(value)
801}
802
803pub(super) enum Accumulator<'a> {
805 Exists(&'a mut bool),
807 Scalar(&'a mut Reducer),
808 Groups(&'a mut Groups),
809}
810impl Accumulator<'_> {
811 pub(super) fn needs_spans(&self) -> bool {
812 !matches!(
813 self,
814 Self::Exists(_)
815 | Self::Scalar(
816 Reducer::Numeric(_)
817 | Reducer::Count { presence: None, .. }
818 | Reducer::Distinct { .. }
819 )
820 )
821 }
822
823 pub(super) fn push(
824 &mut self,
825 entity: &EntitySchema,
826 values: &[IndexValue<'_>],
827 bytes: &[u8],
828 spans: &[(u16, u16)],
829 ) -> Result<(), Error> {
830 match self {
831 Self::Exists(found) => {
832 **found = true;
833
834 Ok(())
835 }
836 Self::Scalar(state) => state.push(entity, values, bytes, spans, MAX_STATE_BYTES),
837 Self::Groups(state) => state.push(entity, values, bytes, spans),
838 }
839 }
840}
841
842#[derive(Clone)]
843pub(super) enum Reducer {
844 Numeric(numeric::NumericAggregate),
845 Distinct {
846 mask: u16,
847 seen: BTreeSet<Vec<u8>>,
848 },
849 Count {
850 presence: Option<usize>,
851 total: u64,
852 },
853 Extremum {
854 position: usize,
855 maximum: bool,
856 selected: Option<(Vec<u8>, Vec<u8>)>,
857 },
858}
859impl Reducer {
860 fn distinct(mask: u16) -> Self {
861 Self::Distinct {
862 mask,
863 seen: BTreeSet::new(),
864 }
865 }
866
867 fn extremum(entity: &EntitySchema, mask: u16, maximum: bool) -> Result<Self, Error> {
868 if mask.count_ones() != 1 {
869 return Err(Error::InvalidQuery);
870 }
871 let position = mask.trailing_zeros() as usize;
872 if !key::supports(entity.fields[position].value) {
873 return Err(Error::InvalidQuery);
874 }
875
876 Ok(Self::Extremum {
877 position,
878 maximum,
879 selected: None,
880 })
881 }
882
883 fn retained_bytes(&self) -> usize {
884 match self {
885 Self::Numeric(state) => state.retained_bytes(),
886 Self::Count { .. } => 8,
887 Self::Distinct { seen, .. } => 8 + seen.iter().map(Vec::capacity).sum::<usize>(),
888 Self::Extremum { selected, .. } => selected
889 .as_ref()
890 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
891 }
892 }
893
894 fn finish(self) -> Result<Completed, Error> {
895 match self {
896 Self::Count { total, .. } => Ok(Completed::Count(total)),
897 Self::Distinct { seen, .. } => Ok(Completed::Count(seen.len() as u64)),
898 Self::Extremum { selected, .. } => Ok(Completed::Value(selected)),
899 Self::Numeric(state) => state.finish(),
900 }
901 }
902
903 fn push(
904 &mut self,
905 entity: &EntitySchema,
906 values: &[IndexValue<'_>],
907 bytes: &[u8],
908 spans: &[(u16, u16)],
909 allowance: usize,
910 ) -> Result<(), Error> {
911 match self {
912 Self::Numeric(state) => state.push(values)?,
913 Self::Distinct { mask, seen } => {
914 let key = comparison_key(entity, *mask, values)?;
915 if !seen.contains(&key) {
916 if seen.len() == MAX_DISTINCT_VALUES
917 || 8 + seen.iter().map(Vec::capacity).sum::<usize>() + key.capacity()
918 > allowance
919 {
920 return Err(Error::Limit);
921 }
922 seen.insert(key);
923 }
924 }
925 Self::Count { presence, total } => {
926 *total += u64::from(presence.is_none_or(|i| bytes[usize::from(spans[i].0)] != 0));
927 }
928 Self::Extremum {
929 position,
930 maximum,
931 selected,
932 } => {
933 let value = values[*position];
934 if value == IndexValue::Absent {
935 return Ok(());
936 }
937 let mut key = Vec::new();
938 value.append_component(entity.fields[*position].optional, &mut key);
939 if key.len() > MAX_COMPARISON_KEY {
940 return Err(Error::Limit);
941 }
942 if selected
943 .as_ref()
944 .is_none_or(|(old, _)| if *maximum { key > *old } else { key < *old })
945 {
946 let (start, end) = spans[*position];
947 if key.capacity() + usize::from(end - start) > allowance {
948 return Err(Error::Limit);
949 }
950 let output = bytes[usize::from(start)..usize::from(end)].to_vec();
952 if key.capacity() + output.capacity() > allowance {
953 return Err(Error::Limit);
954 }
955 *selected = Some((key, output));
956 }
957 }
958 }
959
960 Ok(())
961 }
962}
963
964enum Completed {
966 Count(u64),
967 Value(Option<(Vec<u8>, Vec<u8>)>),
968}
969impl Completed {
970 fn encoded_len(&self) -> usize {
971 match self {
972 Self::Count(_) => 8,
973 Self::Value(value) => value.as_ref().map_or(0, |(_, bytes)| bytes.len()),
974 }
975 }
976 fn result_key<'a>(&'a self, scratch: &'a mut [u8; 8]) -> Option<&'a [u8]> {
978 match self {
979 Self::Count(total) => {
980 *scratch = total.to_be_bytes();
981
982 Some(scratch)
983 }
984 Self::Value(selected) => selected.as_ref().map(|(key, _)| key.as_slice()),
985 }
986 }
987
988 fn retained_bytes(&self) -> usize {
989 match self {
990 Self::Count(_) => 8,
991 Self::Value(value) => value
992 .as_ref()
993 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
994 }
995 }
996
997 fn into_count(self) -> Result<u64, Error> {
998 match self {
999 Self::Count(count) => Ok(count),
1000 _ => Err(Error::Corrupt),
1001 }
1002 }
1003
1004 fn into_value(self) -> Result<Option<Vec<u8>>, Error> {
1005 match self {
1006 Self::Value(value) => Ok(value.map(|(_, bytes)| bytes)),
1007 _ => Err(Error::Corrupt),
1008 }
1009 }
1010}
1011
1012pub(super) struct Groups {
1013 selection: Selection,
1014 mask: u16,
1015 initial: Reducer,
1017 rows: BTreeMap<Vec<u8>, (Vec<u8>, Reducer)>,
1018 state_bytes: usize,
1019}
1020impl Groups {
1021 fn into_output(self) -> Result<Vec<(Vec<u8>, Completed)>, Error> {
1022 let mut state_bytes = self.state_bytes;
1024 let mut rows = self
1025 .rows
1026 .into_iter()
1027 .map(|(key, (record, reducer))| {
1028 let previous = reducer.retained_bytes();
1029 let result = reducer.finish()?;
1030 state_bytes = state_bytes - previous + result.retained_bytes();
1031 if state_bytes > MAX_STATE_BYTES {
1032 return Err(Error::Limit);
1033 }
1034
1035 Ok((key, (record, result)))
1036 })
1037 .collect::<Result<Vec<_>, Error>>()?;
1038 rows.retain(|(_, (_, result))| {
1039 let mut scratch = [0; 8];
1040 let actual = result.result_key(&mut scratch);
1041
1042 self.selection
1043 .predicates
1044 .split_inclusive(|(_, _, or_next)| !or_next)
1045 .all(|clause| {
1046 clause.iter().any(|(comparison, operand, _)| {
1047 comparison.accepts(actual, operand.as_deref(), self.selection.optional)
1048 })
1049 })
1050 });
1051 if self.selection.order == GroupOrder::KeyDescending {
1052 rows.reverse();
1055 } else if self.selection.order != GroupOrder::Key {
1056 rows.sort_unstable_by(|(ka, (_, a)), (kb, (_, b))| {
1057 let (mut sa, mut sb) = ([0; 8], [0; 8]);
1058 let order = a.result_key(&mut sa).cmp(&b.result_key(&mut sb));
1059 let order = if self.selection.order == GroupOrder::AggregateDescending {
1060 order.reverse()
1061 } else {
1062 order
1063 };
1064
1065 order.then_with(|| ka.cmp(kb))
1066 });
1067 }
1068
1069 Ok(rows.into_iter().map(|(_, row)| row).collect())
1070 }
1071
1072 fn push(
1073 &mut self,
1074 entity: &EntitySchema,
1075 values: &[IndexValue<'_>],
1076 bytes: &[u8],
1077 spans: &[(u16, u16)],
1078 ) -> Result<(), Error> {
1079 let key = comparison_key(entity, self.mask, values)?;
1080 let size = projection_size(spans, self.mask);
1081 if let Some((_, reducer)) = self.rows.get_mut(&key) {
1082 let previous = reducer.retained_bytes();
1083 reducer.push(
1084 entity,
1085 values,
1086 bytes,
1087 spans,
1088 MAX_STATE_BYTES - self.state_bytes + previous,
1089 )?;
1090 self.state_bytes = self.state_bytes - previous + reducer.retained_bytes();
1091
1092 return Ok(());
1093 }
1094 let base = key.capacity() + size;
1095 let available = MAX_STATE_BYTES - self.state_bytes;
1096 if self.rows.len() == MAX_GROUPS || base + self.initial.retained_bytes() > available {
1097 return Err(Error::Limit);
1098 }
1099 let mut reducer = self.initial.clone();
1100 reducer.push(entity, values, bytes, spans, available - base)?;
1101 let output = copy_projection(bytes, spans, self.mask, size);
1102 let retained = key.capacity() + output.capacity() + reducer.retained_bytes();
1105 if retained > available {
1106 return Err(Error::Limit);
1107 }
1108 self.state_bytes += retained;
1109 self.rows.insert(key, (output, reducer));
1110
1111 Ok(())
1112 }
1113}