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::Keys => {
55 if !self.predicates.is_empty() || self.order.is_some() {
56 return Err(Error::InvalidQuery);
57 }
58
59 return Ok(Selection {
60 predicates: Vec::new(),
61 order: GroupOrder::Key,
62 optional: false,
63 });
64 }
65 Reducer::Count { .. } | Reducer::Distinct { .. } => ValueSchema {
66 value: FieldType::Nat64,
67 optional: false,
68 },
69 Reducer::Extremum { position, .. } => {
70 let field = &entity.fields[*position];
71
72 ValueSchema {
73 value: field.value,
74 optional: field.optional,
75 }
76 }
77 Reducer::Numeric(state) => state.output(),
78 };
79 let absent_result = !matches!(reducer, Reducer::Count { .. } | Reducer::Distinct { .. });
81 let predicates = self
82 .predicates
83 .iter()
84 .map(|&(comparison, value, or_next)| {
85 if match value {
86 IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
87 IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
88 _ => false,
89 } {
90 return Err(Error::Limit);
91 }
92 comparison.admit(field.value, absent_result, value)?;
93 let key = if value == IndexValue::Absent {
94 None
95 } else {
96 let mut key = Vec::new();
97 value.append_component(field.optional, &mut key);
98 if key.len() > MAX_COMPARISON_KEY {
99 return Err(Error::Limit);
100 }
101
102 Some(key)
103 };
104
105 Ok((comparison, key, or_next))
106 })
107 .collect::<Result<_, Error>>()?;
108
109 Ok(Selection {
110 predicates,
111 order: self.order.unwrap_or_default(),
112 optional: field.optional,
113 })
114 }
115}
116
117struct Selection {
118 predicates: Vec<(Comparison, Option<Vec<u8>>, bool)>,
119 order: GroupOrder,
120 optional: bool,
122}
123
124#[derive(Debug)]
126pub struct Aggregate<T> {
127 pub value: T,
129 pub examined: usize,
131 pub fetched: usize,
133 pub output_bytes: usize,
135}
136
137#[derive(Debug)]
139pub struct GroupCount<K> {
140 pub key: K,
142 pub count: u64,
144}
145
146#[derive(Debug)]
148pub struct GroupValue<K, R> {
149 pub key: K,
151 pub value: Option<R>,
153}
154
155impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
156 #[must_use]
161 pub fn group_page(mut self, size: usize, after: Option<&'a jobs::GroupCursor>) -> Self {
162 self.request.groups.page = Some(jobs::pages::PageRequest { size, after });
163
164 self
165 }
166
167 #[must_use]
174 pub fn filter_groups(
175 mut self,
176 comparison: Comparison,
177 value: impl Into<IndexValue<'a>>,
178 ) -> Self {
179 if self.request.groups.predicates.len() == MAX_TERMS {
180 self.request.over_limit = true;
181 } else {
182 self.request
183 .groups
184 .predicates
185 .push((comparison, value.into(), false));
186 }
187
188 self
189 }
190
191 #[must_use]
198 pub fn filter_groups_any(mut self, alternatives: &[(Comparison, IndexValue<'a>)]) -> Self {
199 let count = alternatives.len();
200 if count == 0 || count > MAX_TERMS - self.request.groups.predicates.len() {
201 self.request.over_limit = true;
202 } else {
203 self.request.groups.predicates.extend(
204 alternatives
205 .iter()
206 .enumerate()
207 .map(|(i, &(comparison, value))| (comparison, value, i + 1 != count)),
208 );
209 }
210
211 self
212 }
213
214 #[must_use]
217 pub fn order_groups(mut self, order: GroupOrder) -> Self {
218 self.request.groups.order = Some(order);
219
220 self
221 }
222
223 pub fn min<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
236 self.extremum(false)
237 }
238
239 pub fn max<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
246 self.extremum(true)
247 }
248
249 fn extremum<R: Value>(self, maximum: bool) -> Result<Aggregate<Option<R>>, Error> {
250 let (plan, reducer) = self.extremum_plan::<R>(maximum)?;
251
252 self.scalar_value(&plan, reducer)
253 }
254
255 fn extremum_plan<R: Value>(&self, maximum: bool) -> Result<(Plan<'a>, Reducer), Error> {
256 let plan = self.aggregate_plan(Some(R::definition()), false)?;
257 let reducer = Reducer::extremum(
258 E::SCHEMA,
259 plan.projection.ok_or(Error::InvalidQuery)?,
260 maximum,
261 )?;
262
263 Ok((plan, reducer))
264 }
265
266 fn scalar_value<R: Value>(
267 self,
268 plan: &Plan<'_>,
269 mut reducer: Reducer,
270 ) -> Result<Aggregate<Option<R>>, Error> {
271 let page = execute(
272 &self.db.read()?.map,
273 E::SCHEMA,
274 &self.request,
275 plan,
276 Some(Accumulator::Scalar(&mut reducer)),
277 )?;
278 let mut output_bytes = 0;
279 let value = reducer
280 .finish()?
281 .into_value()?
282 .map(|bytes| {
283 admit_output(bytes.len(), self.request.bytes, &mut output_bytes)?;
284
285 decode_record(&bytes)
286 })
287 .transpose()?;
288
289 Ok(Aggregate {
290 value,
291 examined: page.examined,
292 fetched: page.fetched,
293 output_bytes,
294 })
295 }
296
297 pub fn group_min<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
314 self.group_extrema(false)
315 }
316
317 pub fn group_max<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
323 self.group_extrema(true)
324 }
325
326 fn group_extrema<K: Value, R: Value>(
327 self,
328 maximum: bool,
329 ) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
330 let (plan, initial) = self.group_extremum_plan::<K, R>(maximum)?;
331
332 self.group_values(&plan, initial)
333 }
334
335 fn group_extremum_plan<K: Value, R: Value>(
336 &self,
337 maximum: bool,
338 ) -> Result<(Plan<'a>, Reducer), Error> {
339 let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
340 let operand = admit_projection(E::SCHEMA, R::definition())?;
341 let initial = Reducer::extremum(E::SCHEMA, operand, maximum)?;
342 plan.selected |= operand;
343
344 Ok((plan, initial))
345 }
346
347 fn group_values<K: Value, R: Value>(
348 self,
349 plan: &Plan<'_>,
350 initial: Reducer,
351 ) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
352 let (groups, page) = self.grouped(plan, initial)?;
353 let (value, output_bytes) = group_output(
354 groups,
355 self.request.rows,
356 self.request.bytes,
357 decode_group_value,
358 )?;
359
360 Ok(Aggregate {
361 value,
362 examined: page.examined,
363 fetched: page.fetched,
364 output_bytes,
365 })
366 }
367
368 pub fn exists(self) -> Result<Aggregate<bool>, Error> {
381 let mut plan = self.aggregate_plan(None, false)?;
382 self.select_aggregate_row_path(&mut plan)?;
383 let mut found = false;
384 let page = execute(
385 &self.db.read()?.map,
386 E::SCHEMA,
387 &self.request,
388 &plan,
389 Some(Accumulator::Exists(&mut found)),
390 )?;
391
392 Ok(Aggregate {
393 value: found,
394 examined: page.examined,
395 fetched: page.fetched,
396 output_bytes: 1,
397 })
398 }
399
400 pub fn count(self) -> Result<Aggregate<u64>, Error> {
417 if self.request.bytes < 8 {
418 return Err(Error::RowTooLarge);
419 }
420 let mut plan = self.aggregate_plan(None, false)?;
421 if self.request.predicates.is_empty() && self.request.index.is_none() {
422 return Ok(Aggregate {
423 value: self.db.read()?.cardinality::<E>()?,
424 examined: 0,
425 fetched: 0,
426 output_bytes: 8,
427 });
428 }
429 if plan.index.is_none()
430 && let Some(count) = self.count_members(&plan)?
431 {
432 return Ok(count);
433 }
434 if super::order::select_aggregate_path(E::SCHEMA, &self.request, &mut plan)? {
435 return self.count_keys(&plan);
436 }
437 if plan.index.is_some()
438 && let Some(count) = self.count_members(&plan)?
439 {
440 return Ok(count);
441 }
442 let reducer = self.count_reducer(None)?;
443
444 self.scalar_count_value(&plan, reducer)
445 }
446
447 pub fn count_validated(self) -> Result<Aggregate<u64>, Error> {
452 self.scalar_count(None)
453 }
454
455 pub fn count_index_entries(self) -> Result<Aggregate<u64>, Error> {
467 if self.request.index.is_none() || !self.request.predicates.is_empty() {
468 return Err(Error::InvalidQuery);
469 }
470 if self.request.bytes < 8 {
471 return Err(Error::RowTooLarge);
472 }
473 let plan = self.aggregate_plan(None, false)?;
474
475 self.count_keys(&plan)
476 }
477
478 fn count_members(&self, plan: &Plan<'_>) -> Result<Option<Aggregate<u64>>, Error> {
479 let Some(members) = super::range::point_count_members(E::SCHEMA, plan, &self.request)
480 else {
481 return Ok(None);
482 };
483 let db = self.db.read()?;
484 let mut count = 0;
485 for member in &members {
486 let key = crate::store_key::StoreKey::new([plan.prefix.as_slice(), *member].concat())?;
487 count += u64::from(db.map.contains_key(&key));
488 }
489
490 Ok(Some(Aggregate {
491 value: count,
492 examined: members.len(),
493 fetched: 0,
494 output_bytes: 8,
495 }))
496 }
497
498 fn count_keys(&self, plan: &Plan<'_>) -> Result<Aggregate<u64>, Error> {
499 let bounds = super::range::bounds(E::SCHEMA, &self.request, plan)?;
500 let mut examined = 0;
501 if let Some(range) = bounds {
502 let terminal = super::range::terminal_key(&range, false);
503 let db = self.db.read()?;
504 let entries = db.map.range((range.0.as_ref(), range.1.as_ref()));
505 for entry in entries.take(self.request.work) {
506 examined += 1;
507 if examined == self.request.work && terminal.is_none_or(|end| end != entry.key()) {
508 return Err(Error::Limit);
509 }
510 }
511 }
512
513 Ok(Aggregate {
514 value: examined as u64,
515 examined,
516 fetched: 0,
517 output_bytes: 8,
518 })
519 }
520
521 pub fn count_field(self, field: &str) -> Result<Aggregate<u64>, Error> {
529 self.scalar_count(Some(field))
530 }
531
532 pub fn count_distinct<K: Value>(self) -> Result<Aggregate<u64>, Error> {
541 if self.request.bytes < 8 {
542 return Err(Error::RowTooLarge);
543 }
544 let (mut plan, reducer) = self.distinct_plan::<K>()?;
545 self.select_aggregate_row_path(&mut plan)?;
546
547 self.scalar_count_value(&plan, reducer)
548 }
549
550 fn distinct_plan<K: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
551 let plan = self.aggregate_plan(Some(K::definition()), false)?;
552 let reducer = Reducer::distinct(plan.projection.ok_or(Error::InvalidQuery)?);
553
554 Ok((plan, reducer))
555 }
556
557 fn select_aggregate_row_path(&self, plan: &mut Plan<'static>) -> Result<(), Error> {
558 if plan.index.is_none() {
559 super::order::select_aggregate_path(E::SCHEMA, &self.request, plan)?;
560 }
561
562 Ok(())
563 }
564
565 fn scalar_count(self, field: Option<&str>) -> Result<Aggregate<u64>, Error> {
566 if self.request.bytes < 8 {
567 return Err(Error::RowTooLarge);
568 }
569 let mut plan = self.aggregate_plan(None, false)?;
570 self.select_aggregate_row_path(&mut plan)?;
571 let reducer = self.count_reducer(field)?;
572
573 self.scalar_count_value(&plan, reducer)
574 }
575
576 fn scalar_count_value(
577 self,
578 plan: &Plan<'_>,
579 mut reducer: Reducer,
580 ) -> Result<Aggregate<u64>, Error> {
581 let page = execute(
582 &self.db.read()?.map,
583 E::SCHEMA,
584 &self.request,
585 plan,
586 Some(Accumulator::Scalar(&mut reducer)),
587 )?;
588
589 Ok(Aggregate {
590 value: reducer.finish()?.into_count()?,
591 examined: page.examined,
592 fetched: page.fetched,
593 output_bytes: 8,
594 })
595 }
596
597 pub fn group_count<K: Value>(self) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
614 self.group_counts(None)
615 }
616
617 pub fn group_count_field<K: Value>(
626 self,
627 field: &str,
628 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
629 self.group_counts(Some(field))
630 }
631
632 pub fn group_count_distinct<K: Value, R: Value>(
645 self,
646 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
647 let (plan, reducer) = self.group_distinct_plan::<K, R>()?;
648
649 self.group_count_values(plan, reducer)
650 }
651
652 fn group_distinct_plan<K: Value, R: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
653 let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
654 let operand = admit_projection(E::SCHEMA, R::definition())?;
655 admit_ordered_fields(E::SCHEMA, operand)?;
656 plan.selected |= operand;
657
658 Ok((plan, Reducer::distinct(operand)))
659 }
660
661 fn group_counts<K: Value>(
662 self,
663 field: Option<&str>,
664 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
665 let plan = self.aggregate_plan(Some(K::definition()), true)?;
666 let reducer = self.count_reducer(field)?;
667
668 self.group_count_values(plan, reducer)
669 }
670
671 fn group_count_values<K: Value>(
672 self,
673 mut plan: Plan<'static>,
674 reducer: Reducer,
675 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
676 self.select_aggregate_row_path(&mut plan)?;
677 let (groups, page) = self.grouped(&plan, reducer)?;
678 let (value, output_bytes) = group_output(
679 groups,
680 self.request.rows,
681 self.request.bytes,
682 decode_group_count,
683 )?;
684
685 Ok(Aggregate {
686 value,
687 examined: page.examined,
688 fetched: page.fetched,
689 output_bytes,
690 })
691 }
692
693 fn count_reducer(&self, field: Option<&str>) -> Result<Reducer, Error> {
694 let presence = field
696 .map(|name| E::SCHEMA.field_position(name).ok_or(Error::InvalidQuery))
697 .transpose()?
698 .filter(|&i| E::SCHEMA.fields[i].optional);
699
700 Ok(Reducer::Count { presence, total: 0 })
701 }
702
703 fn grouped(
704 &self,
705 plan: &Plan<'_>,
706 initial: Reducer,
707 ) -> Result<(Groups, QueryPage<Vec<u8>>), Error> {
708 if self.request.groups.page.is_some() {
709 return Err(Error::InvalidQuery);
710 }
711 let mut groups = self.admit_groups(plan, initial)?;
712 let page = execute(
713 &self.db.read()?.map,
714 E::SCHEMA,
715 &self.request,
716 plan,
717 Some(Accumulator::Groups(&mut groups)),
718 )?;
719
720 Ok((groups, page))
721 }
722
723 fn admit_groups(&self, plan: &Plan<'_>, initial: Reducer) -> Result<Groups, Error> {
724 Ok(Groups {
725 selection: self.request.groups.admit(E::SCHEMA, &initial)?,
726 mask: plan.projection.ok_or(Error::InvalidQuery)?,
727 initial,
728 rows: BTreeMap::new(),
729 state_bytes: 0,
730 })
731 }
732
733 fn aggregate_plan(
734 &self,
735 output: Option<&TypeSchema>,
736 group_output: bool,
737 ) -> Result<Plan<'static>, Error> {
738 if self.request.cursor.is_some()
739 || self.request.distinct
740 || self.request.order.is_some()
741 || self.request.descending
742 {
743 return Err(Error::InvalidQuery);
744 }
745 let db = self.db.read()?;
746 db.schema.admits(E::SCHEMA)?;
747 let mut plan = Plan::admit(
748 E::SCHEMA,
749 &self.request,
750 db.schema.fingerprint(),
751 db.incarnation,
752 output,
753 super::PlanOutput::Aggregate {
754 grouped: group_output,
755 },
756 )?;
757 if let Some(mask) = plan.projection {
758 admit_ordered_fields(E::SCHEMA, mask)?;
759 plan.selected |= mask;
760 }
761
762 Ok(plan)
763 }
764}
765
766fn group_output<T>(
767 groups: Groups,
768 rows: usize,
769 bytes: usize,
770 decode: fn(&[u8], Completed) -> Result<T, Error>,
771) -> Result<(Vec<T>, usize), Error> {
772 let mut output_bytes = 0;
773 let value = groups
774 .into_output()?
775 .into_iter()
776 .take(rows)
777 .map(|(key, result)| {
778 admit_output(key.len() + result.encoded_len(), bytes, &mut output_bytes)?;
779
780 decode(&key, result)
781 })
782 .collect::<Result<_, Error>>()?;
783
784 Ok((value, output_bytes))
785}
786
787fn decode_group_count<K: Value>(key: &[u8], result: Completed) -> Result<GroupCount<K>, Error> {
788 Ok(GroupCount {
789 key: decode_record(key)?,
790 count: result.into_count()?,
791 })
792}
793
794fn decode_group_value<K: Value, R: Value>(
795 key: &[u8],
796 result: Completed,
797) -> Result<GroupValue<K, R>, Error> {
798 let value = result.into_value()?;
799
800 Ok(GroupValue {
801 key: decode_record(key)?,
802 value: value.as_deref().map(decode_record).transpose()?,
803 })
804}
805
806fn decode_record<R: Value>(bytes: &[u8]) -> Result<R, Error> {
807 let mut reader = Decoder::new(bytes)?;
808 let value = R::decode_from(&mut reader)?;
809 reader.finish()?;
810
811 Ok(value)
812}
813
814pub(super) enum Accumulator<'a> {
816 Exists(&'a mut bool),
818 Scalar(&'a mut Reducer),
819 Groups(&'a mut Groups),
820}
821impl Accumulator<'_> {
822 pub(super) fn needs_spans(&self) -> bool {
823 !matches!(
824 self,
825 Self::Exists(_)
826 | Self::Scalar(
827 Reducer::Numeric(_)
828 | Reducer::Count { presence: None, .. }
829 | Reducer::Distinct { .. }
830 )
831 )
832 }
833
834 pub(super) fn push(
835 &mut self,
836 entity: &EntitySchema,
837 values: &[IndexValue<'_>],
838 bytes: &[u8],
839 spans: &[(u16, u16)],
840 ) -> Result<(), Error> {
841 match self {
842 Self::Exists(found) => {
843 **found = true;
844
845 Ok(())
846 }
847 Self::Scalar(state) => state.push(entity, values, bytes, spans, MAX_STATE_BYTES),
848 Self::Groups(state) => state.push(entity, values, bytes, spans),
849 }
850 }
851}
852
853#[derive(Clone)]
854pub(super) enum Reducer {
855 Keys,
856 Numeric(numeric::NumericAggregate),
857 Distinct {
858 mask: u16,
859 seen: BTreeSet<Vec<u8>>,
860 },
861 Count {
862 presence: Option<usize>,
863 total: u64,
864 },
865 Extremum {
866 position: usize,
867 maximum: bool,
868 selected: Option<(Vec<u8>, Vec<u8>)>,
869 },
870}
871impl Reducer {
872 fn distinct(mask: u16) -> Self {
873 Self::Distinct {
874 mask,
875 seen: BTreeSet::new(),
876 }
877 }
878
879 fn extremum(entity: &EntitySchema, mask: u16, maximum: bool) -> Result<Self, Error> {
880 if mask.count_ones() != 1 {
881 return Err(Error::InvalidQuery);
882 }
883 let position = mask.trailing_zeros() as usize;
884 if !key::supports(entity.fields[position].value) {
885 return Err(Error::InvalidQuery);
886 }
887
888 Ok(Self::Extremum {
889 position,
890 maximum,
891 selected: None,
892 })
893 }
894
895 fn retained_bytes(&self) -> usize {
896 match self {
897 Self::Keys => 0,
898 Self::Numeric(state) => state.retained_bytes(),
899 Self::Count { .. } => 8,
900 Self::Distinct { seen, .. } => 8 + seen.iter().map(Vec::capacity).sum::<usize>(),
901 Self::Extremum { selected, .. } => selected
902 .as_ref()
903 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
904 }
905 }
906
907 fn finish(self) -> Result<Completed, Error> {
908 match self {
909 Self::Keys => Ok(Completed::Key),
910 Self::Count { total, .. } => Ok(Completed::Count(total)),
911 Self::Distinct { seen, .. } => Ok(Completed::Count(seen.len() as u64)),
912 Self::Extremum { selected, .. } => Ok(Completed::Value(selected)),
913 Self::Numeric(state) => state.finish(),
914 }
915 }
916
917 fn push(
918 &mut self,
919 entity: &EntitySchema,
920 values: &[IndexValue<'_>],
921 bytes: &[u8],
922 spans: &[(u16, u16)],
923 allowance: usize,
924 ) -> Result<(), Error> {
925 match self {
926 Self::Keys => {}
927 Self::Numeric(state) => state.push(values)?,
928 Self::Distinct { mask, seen } => {
929 let key = comparison_key(entity, *mask, values)?;
930 if !seen.contains(&key) {
931 if seen.len() == MAX_DISTINCT_VALUES
932 || 8 + seen.iter().map(Vec::capacity).sum::<usize>() + key.capacity()
933 > allowance
934 {
935 return Err(Error::Limit);
936 }
937 seen.insert(key);
938 }
939 }
940 Self::Count { presence, total } => {
941 *total += u64::from(presence.is_none_or(|i| bytes[usize::from(spans[i].0)] != 0));
942 }
943 Self::Extremum {
944 position,
945 maximum,
946 selected,
947 } => {
948 let value = values[*position];
949 if value == IndexValue::Absent {
950 return Ok(());
951 }
952 let mut key = Vec::new();
953 value.append_component(entity.fields[*position].optional, &mut key);
954 if key.len() > MAX_COMPARISON_KEY {
955 return Err(Error::Limit);
956 }
957 if selected
958 .as_ref()
959 .is_none_or(|(old, _)| if *maximum { key > *old } else { key < *old })
960 {
961 let (start, end) = spans[*position];
962 if key.capacity() + usize::from(end - start) > allowance {
963 return Err(Error::Limit);
964 }
965 let output = bytes[usize::from(start)..usize::from(end)].to_vec();
967 if key.capacity() + output.capacity() > allowance {
968 return Err(Error::Limit);
969 }
970 *selected = Some((key, output));
971 }
972 }
973 }
974
975 Ok(())
976 }
977}
978
979enum Completed {
981 Key,
982 Count(u64),
983 Value(Option<(Vec<u8>, Vec<u8>)>),
984}
985impl Completed {
986 fn encoded_len(&self) -> usize {
987 match self {
988 Self::Key => 0,
989 Self::Count(_) => 8,
990 Self::Value(value) => value.as_ref().map_or(0, |(_, bytes)| bytes.len()),
991 }
992 }
993 fn result_key<'a>(&'a self, scratch: &'a mut [u8; 8]) -> Option<&'a [u8]> {
995 match self {
996 Self::Key => None,
997 Self::Count(total) => {
998 *scratch = total.to_be_bytes();
999
1000 Some(scratch)
1001 }
1002 Self::Value(selected) => selected.as_ref().map(|(key, _)| key.as_slice()),
1003 }
1004 }
1005
1006 fn retained_bytes(&self) -> usize {
1007 match self {
1008 Self::Key => 0,
1009 Self::Count(_) => 8,
1010 Self::Value(value) => value
1011 .as_ref()
1012 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
1013 }
1014 }
1015
1016 fn into_count(self) -> Result<u64, Error> {
1017 match self {
1018 Self::Count(count) => Ok(count),
1019 _ => Err(Error::Corrupt),
1020 }
1021 }
1022
1023 fn into_value(self) -> Result<Option<Vec<u8>>, Error> {
1024 match self {
1025 Self::Value(value) => Ok(value.map(|(_, bytes)| bytes)),
1026 _ => Err(Error::Corrupt),
1027 }
1028 }
1029}
1030
1031pub(super) struct Groups {
1032 selection: Selection,
1033 mask: u16,
1034 initial: Reducer,
1036 rows: BTreeMap<Vec<u8>, (Vec<u8>, Reducer)>,
1037 state_bytes: usize,
1038}
1039impl Groups {
1040 fn max_keys(&self) -> usize {
1041 if matches!(self.initial, Reducer::Keys) {
1042 usize::from(u8::MAX)
1043 } else {
1044 MAX_GROUPS
1045 }
1046 }
1047
1048 fn into_output(self) -> Result<Vec<(Vec<u8>, Completed)>, Error> {
1049 let mut state_bytes = self.state_bytes;
1051 let mut rows = self
1052 .rows
1053 .into_iter()
1054 .map(|(key, (record, reducer))| {
1055 let previous = reducer.retained_bytes();
1056 let result = reducer.finish()?;
1057 state_bytes = state_bytes - previous + result.retained_bytes();
1058 if state_bytes > MAX_STATE_BYTES {
1059 return Err(Error::Limit);
1060 }
1061
1062 Ok((key, (record, result)))
1063 })
1064 .collect::<Result<Vec<_>, Error>>()?;
1065 rows.retain(|(_, (_, result))| {
1066 let mut scratch = [0; 8];
1067 let actual = result.result_key(&mut scratch);
1068
1069 self.selection
1070 .predicates
1071 .split_inclusive(|(_, _, or_next)| !or_next)
1072 .all(|clause| {
1073 clause.iter().any(|(comparison, operand, _)| {
1074 comparison.accepts(actual, operand.as_deref(), self.selection.optional)
1075 })
1076 })
1077 });
1078 if self.selection.order == GroupOrder::KeyDescending {
1079 rows.reverse();
1082 } else if self.selection.order != GroupOrder::Key {
1083 rows.sort_unstable_by(|(ka, (_, a)), (kb, (_, b))| {
1084 let (mut sa, mut sb) = ([0; 8], [0; 8]);
1085 let order = a.result_key(&mut sa).cmp(&b.result_key(&mut sb));
1086 let order = if self.selection.order == GroupOrder::AggregateDescending {
1087 order.reverse()
1088 } else {
1089 order
1090 };
1091
1092 order.then_with(|| ka.cmp(kb))
1093 });
1094 }
1095
1096 Ok(rows.into_iter().map(|(_, row)| row).collect())
1097 }
1098
1099 fn push(
1100 &mut self,
1101 entity: &EntitySchema,
1102 values: &[IndexValue<'_>],
1103 bytes: &[u8],
1104 spans: &[(u16, u16)],
1105 ) -> Result<(), Error> {
1106 let key = comparison_key(entity, self.mask, values)?;
1107 let size = projection_size(spans, self.mask);
1108 if let Some((_, reducer)) = self.rows.get_mut(&key) {
1109 let previous = reducer.retained_bytes();
1110 reducer.push(
1111 entity,
1112 values,
1113 bytes,
1114 spans,
1115 MAX_STATE_BYTES - self.state_bytes + previous,
1116 )?;
1117 self.state_bytes = self.state_bytes - previous + reducer.retained_bytes();
1118
1119 return Ok(());
1120 }
1121 let base = key.capacity() + size;
1122 let available = MAX_STATE_BYTES - self.state_bytes;
1123 if self.rows.len() == self.max_keys() || base + self.initial.retained_bytes() > available {
1124 return Err(Error::Limit);
1125 }
1126 let mut reducer = self.initial.clone();
1127 reducer.push(entity, values, bytes, spans, available - base)?;
1128 let output = copy_projection(bytes, spans, self.mask, size);
1129 let retained = key.capacity() + output.capacity() + reducer.retained_bytes();
1132 if retained > available {
1133 return Err(Error::Limit);
1134 }
1135 self.state_bytes += retained;
1136 self.rows.insert(key, (output, reducer));
1137
1138 Ok(())
1139 }
1140}