1pub(super) mod jobs;
3mod numeric;
4
5use super::{
6 Comparison, MAX_COMPARISON_KEY, MAX_DISTINCT_VALUES, MAX_STATE_BYTES, MAX_TERMS, Plan, Query,
7 QueryPage, admit_ordered_fields, admit_output, admit_projection, comparison_key,
8 copy_projection, execute, projection_size,
9};
10use crate::{
11 Entity, EntitySchema, Error, FieldType, IndexValue, TypeSchema, Value, ValueSchema,
12 codec::Decoder, key,
13};
14use ic_storage::Memory;
15use std::collections::{BTreeMap, BTreeSet};
16
17const MAX_GROUPS: usize = 32;
18
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
21pub enum GroupOrder {
22 #[default]
24 Key,
25 AggregateAscending,
27 AggregateDescending,
29 KeyDescending,
31}
32
33#[derive(Default)]
34pub(super) struct GroupRequest<'a> {
35 predicates: Vec<(Comparison, IndexValue<'a>, bool)>,
37 order: Option<GroupOrder>,
38 page: Option<jobs::pages::PageRequest<'a>>,
39}
40impl GroupRequest<'_> {
41 pub(super) fn is_empty(&self) -> bool {
42 self.predicates.is_empty() && self.order.is_none() && self.page.is_none()
43 }
44
45 fn admit(&self, entity: &EntitySchema, reducer: &Reducer) -> Result<Selection, Error> {
46 if self
47 .page
48 .is_some_and(|page| !(1..=MAX_GROUPS).contains(&page.size))
49 {
50 return Err(Error::Limit);
51 }
52 let field = match reducer {
53 Reducer::Count { .. } | Reducer::Distinct { .. } => ValueSchema {
54 value: FieldType::Nat64,
55 optional: false,
56 },
57 Reducer::Extremum { position, .. } => {
58 let field = &entity.fields[*position];
59 ValueSchema {
60 value: field.value,
61 optional: field.optional,
62 }
63 }
64 Reducer::Numeric(state) => state.output(),
65 };
66 let absent_result = !matches!(reducer, Reducer::Count { .. } | Reducer::Distinct { .. });
68 let predicates = self
69 .predicates
70 .iter()
71 .map(|&(comparison, value, or_next)| {
72 if match value {
73 IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
74 IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
75 _ => false,
76 } {
77 return Err(Error::Limit);
78 }
79 comparison.admit(field.value, absent_result, value)?;
80 let key = if value == IndexValue::Absent {
81 None
82 } else {
83 let mut key = Vec::new();
84 value.append_component(field.optional, &mut key);
85 if key.len() > MAX_COMPARISON_KEY {
86 return Err(Error::Limit);
87 }
88 Some(key)
89 };
90 Ok((comparison, key, or_next))
91 })
92 .collect::<Result<_, Error>>()?;
93 Ok(Selection {
94 predicates,
95 order: self.order.unwrap_or_default(),
96 optional: field.optional,
97 })
98 }
99}
100
101struct Selection {
102 predicates: Vec<(Comparison, Option<Vec<u8>>, bool)>,
103 order: GroupOrder,
104 optional: bool,
106}
107
108#[derive(Debug)]
110pub struct Aggregate<T> {
111 pub value: T,
113 pub examined: usize,
115 pub fetched: usize,
117 pub output_bytes: usize,
119}
120
121#[derive(Debug)]
123pub struct GroupCount<K> {
124 pub key: K,
126 pub count: u64,
128}
129
130#[derive(Debug)]
132pub struct GroupValue<K, R> {
133 pub key: K,
135 pub value: Option<R>,
137}
138
139impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
140 #[must_use]
145 pub fn group_page(mut self, size: usize, after: Option<&'a jobs::GroupCursor>) -> Self {
146 self.request.groups.page = Some(jobs::pages::PageRequest { size, after });
147 self
148 }
149
150 #[must_use]
157 pub fn filter_groups(
158 mut self,
159 comparison: Comparison,
160 value: impl Into<IndexValue<'a>>,
161 ) -> Self {
162 if self.request.groups.predicates.len() == MAX_TERMS {
163 self.request.over_limit = true;
164 } else {
165 self.request
166 .groups
167 .predicates
168 .push((comparison, value.into(), false));
169 }
170 self
171 }
172
173 #[must_use]
180 pub fn filter_groups_any(mut self, alternatives: &[(Comparison, IndexValue<'a>)]) -> Self {
181 let count = alternatives.len();
182 if count == 0 || count > MAX_TERMS - self.request.groups.predicates.len() {
183 self.request.over_limit = true;
184 } else {
185 self.request.groups.predicates.extend(
186 alternatives
187 .iter()
188 .enumerate()
189 .map(|(i, &(comparison, value))| (comparison, value, i + 1 != count)),
190 );
191 }
192 self
193 }
194
195 #[must_use]
198 pub fn order_groups(mut self, order: GroupOrder) -> Self {
199 self.request.groups.order = Some(order);
200 self
201 }
202
203 pub fn min<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
216 self.extremum(false)
217 }
218
219 pub fn max<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
226 self.extremum(true)
227 }
228
229 fn extremum<R: Value>(self, maximum: bool) -> Result<Aggregate<Option<R>>, Error> {
230 let (plan, reducer) = self.extremum_plan::<R>(maximum)?;
231 self.scalar_value(&plan, reducer)
232 }
233
234 fn extremum_plan<R: Value>(&self, maximum: bool) -> Result<(Plan<'a>, Reducer), Error> {
235 let plan = self.aggregate_plan(Some(R::definition()), false)?;
236 let reducer = Reducer::extremum(
237 E::SCHEMA,
238 plan.projection.ok_or(Error::InvalidQuery)?,
239 maximum,
240 )?;
241 Ok((plan, reducer))
242 }
243
244 fn scalar_value<R: Value>(
245 self,
246 plan: &Plan<'_>,
247 mut reducer: Reducer,
248 ) -> Result<Aggregate<Option<R>>, Error> {
249 let page = execute(
250 &self.db.map,
251 E::SCHEMA,
252 &self.request,
253 plan,
254 Some(Accumulator::Scalar(&mut reducer)),
255 )?;
256 let mut output_bytes = 0;
257 let value = reducer
258 .finish()?
259 .into_value()?
260 .map(|bytes| {
261 admit_output(bytes.len(), self.request.bytes, &mut output_bytes)?;
262 decode_record(&bytes)
263 })
264 .transpose()?;
265 Ok(Aggregate {
266 value,
267 examined: page.examined,
268 fetched: page.fetched,
269 output_bytes,
270 })
271 }
272
273 pub fn group_min<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
290 self.group_extrema(false)
291 }
292
293 pub fn group_max<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
299 self.group_extrema(true)
300 }
301
302 fn group_extrema<K: Value, R: Value>(
303 self,
304 maximum: bool,
305 ) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
306 let (plan, initial) = self.group_extremum_plan::<K, R>(maximum)?;
307 self.group_values(&plan, initial)
308 }
309
310 fn group_extremum_plan<K: Value, R: Value>(
311 &self,
312 maximum: bool,
313 ) -> Result<(Plan<'a>, Reducer), Error> {
314 let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
315 let operand = admit_projection(E::SCHEMA, R::definition())?;
316 let initial = Reducer::extremum(E::SCHEMA, operand, maximum)?;
317 plan.selected |= operand;
318 Ok((plan, initial))
319 }
320
321 fn group_values<K: Value, R: Value>(
322 self,
323 plan: &Plan<'_>,
324 initial: Reducer,
325 ) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
326 let (groups, page) = self.grouped(plan, initial)?;
327 let (value, output_bytes) = value_output(groups, self.request.rows, self.request.bytes)?;
328 Ok(Aggregate {
329 value,
330 examined: page.examined,
331 fetched: page.fetched,
332 output_bytes,
333 })
334 }
335
336 pub fn exists(self) -> Result<Aggregate<bool>, Error> {
348 let plan = self.aggregate_plan(None, false)?;
349 let mut found = false;
350 let page = execute(
351 &self.db.map,
352 E::SCHEMA,
353 &self.request,
354 &plan,
355 Some(Accumulator::Exists(&mut found)),
356 )?;
357 Ok(Aggregate {
358 value: found,
359 examined: page.examined,
360 fetched: page.fetched,
361 output_bytes: 1,
362 })
363 }
364
365 pub fn count(self) -> Result<Aggregate<u64>, Error> {
379 if self.request.bytes < 8 {
380 return Err(Error::RowTooLarge);
381 }
382 let mut plan = self.aggregate_plan(None, false)?;
383 if self.request.predicates.is_empty() && self.request.index.is_none() {
384 return Ok(Aggregate {
385 value: self.db.cardinality::<E>()?,
386 examined: 0,
387 fetched: 0,
388 output_bytes: 8,
389 });
390 }
391 if super::order::count_prefix(E::SCHEMA, &self.request, &mut plan)? {
392 return self.count_keys(&plan);
393 }
394 let reducer = self.count_reducer(None)?;
395 self.scalar_count_value(&plan, reducer)
396 }
397
398 pub fn count_validated(self) -> Result<Aggregate<u64>, Error> {
403 self.scalar_count(None)
404 }
405
406 pub fn count_index_entries(self) -> Result<Aggregate<u64>, Error> {
417 if self.request.index.is_none() || !self.request.predicates.is_empty() {
418 return Err(Error::InvalidQuery);
419 }
420 if self.request.bytes < 8 {
421 return Err(Error::RowTooLarge);
422 }
423 let plan = self.aggregate_plan(None, false)?;
424 self.count_keys(&plan)
425 }
426
427 fn count_keys(&self, plan: &Plan<'_>) -> Result<Aggregate<u64>, Error> {
428 let bounds = super::range::bounds(E::SCHEMA, &self.request, plan)?;
429 let examined = bounds.map_or(0, |range| {
430 self.db.map.range(range).take(self.request.work).count()
431 });
432 if examined == self.request.work {
433 return Err(Error::Limit);
434 }
435 Ok(Aggregate {
436 value: examined as u64,
437 examined,
438 fetched: 0,
439 output_bytes: 8,
440 })
441 }
442
443 pub fn count_field(self, field: &str) -> Result<Aggregate<u64>, Error> {
451 self.scalar_count(Some(field))
452 }
453
454 pub fn count_distinct<K: Value>(self) -> Result<Aggregate<u64>, Error> {
463 if self.request.bytes < 8 {
464 return Err(Error::RowTooLarge);
465 }
466 let (plan, reducer) = self.distinct_plan::<K>()?;
467 self.scalar_count_value(&plan, reducer)
468 }
469
470 fn distinct_plan<K: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
471 let plan = self.aggregate_plan(Some(K::definition()), false)?;
472 let reducer = Reducer::distinct(plan.projection.ok_or(Error::InvalidQuery)?);
473 Ok((plan, reducer))
474 }
475
476 fn scalar_count(self, field: Option<&str>) -> Result<Aggregate<u64>, Error> {
477 if self.request.bytes < 8 {
478 return Err(Error::RowTooLarge);
479 }
480 let plan = self.aggregate_plan(None, false)?;
481 let reducer = self.count_reducer(field)?;
482 self.scalar_count_value(&plan, reducer)
483 }
484
485 fn scalar_count_value(
486 self,
487 plan: &Plan<'_>,
488 mut reducer: Reducer,
489 ) -> Result<Aggregate<u64>, Error> {
490 let page = execute(
491 &self.db.map,
492 E::SCHEMA,
493 &self.request,
494 plan,
495 Some(Accumulator::Scalar(&mut reducer)),
496 )?;
497 Ok(Aggregate {
498 value: reducer.finish()?.into_count()?,
499 examined: page.examined,
500 fetched: page.fetched,
501 output_bytes: 8,
502 })
503 }
504
505 pub fn group_count<K: Value>(self) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
522 self.group_counts(None)
523 }
524
525 pub fn group_count_field<K: Value>(
534 self,
535 field: &str,
536 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
537 self.group_counts(Some(field))
538 }
539
540 pub fn group_count_distinct<K: Value, R: Value>(
553 self,
554 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
555 let (plan, reducer) = self.group_distinct_plan::<K, R>()?;
556 self.group_count_values(&plan, reducer)
557 }
558
559 fn group_distinct_plan<K: Value, R: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
560 let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
561 let operand = admit_projection(E::SCHEMA, R::definition())?;
562 admit_ordered_fields(E::SCHEMA, operand)?;
563 plan.selected |= operand;
564 Ok((plan, Reducer::distinct(operand)))
565 }
566
567 fn group_counts<K: Value>(
568 self,
569 field: Option<&str>,
570 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
571 let plan = self.aggregate_plan(Some(K::definition()), true)?;
572 let reducer = self.count_reducer(field)?;
573 self.group_count_values(&plan, reducer)
574 }
575
576 fn group_count_values<K: Value>(
577 self,
578 plan: &Plan<'_>,
579 reducer: Reducer,
580 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
581 let (groups, page) = self.grouped(plan, reducer)?;
582 let (value, output_bytes) = count_output(groups, self.request.rows, self.request.bytes)?;
583 Ok(Aggregate {
584 value,
585 examined: page.examined,
586 fetched: page.fetched,
587 output_bytes,
588 })
589 }
590
591 fn count_reducer(&self, field: Option<&str>) -> Result<Reducer, Error> {
592 let presence = field
594 .map(|name| {
595 E::SCHEMA
596 .fields
597 .iter()
598 .enumerate()
599 .find(|(_, f)| f.name == name)
600 .map(|(i, f)| f.optional.then_some(i))
601 .ok_or(Error::InvalidQuery)
602 })
603 .transpose()?
604 .flatten();
605 Ok(Reducer::Count { presence, total: 0 })
606 }
607
608 fn grouped(
609 &self,
610 plan: &Plan<'_>,
611 initial: Reducer,
612 ) -> Result<(Groups, QueryPage<Vec<u8>>), Error> {
613 if self.request.groups.page.is_some() {
614 return Err(Error::InvalidQuery);
615 }
616 let mut groups = self.admit_groups(plan, initial)?;
617 let page = execute(
618 &self.db.map,
619 E::SCHEMA,
620 &self.request,
621 plan,
622 Some(Accumulator::Groups(&mut groups)),
623 )?;
624 Ok((groups, page))
625 }
626
627 fn admit_groups(&self, plan: &Plan<'_>, initial: Reducer) -> Result<Groups, Error> {
628 Ok(Groups {
629 selection: self.request.groups.admit(E::SCHEMA, &initial)?,
630 mask: plan.projection.ok_or(Error::InvalidQuery)?,
631 initial,
632 rows: BTreeMap::new(),
633 state_bytes: 0,
634 })
635 }
636
637 fn aggregate_plan(
638 &self,
639 output: Option<&TypeSchema>,
640 group_output: bool,
641 ) -> Result<Plan<'static>, Error> {
642 if self.request.cursor.is_some()
643 || self.request.distinct
644 || self.request.order.is_some()
645 || self.request.descending
646 {
647 return Err(Error::InvalidQuery);
648 }
649 self.db.schema.admits(E::SCHEMA)?;
650 let mut plan = Plan::admit(
651 E::SCHEMA,
652 &self.request,
653 self.db.schema.fingerprint(),
654 self.db.incarnation,
655 output,
656 group_output,
657 )?;
658 if let Some(mask) = plan.projection {
659 admit_ordered_fields(E::SCHEMA, mask)?;
660 plan.selected |= mask;
661 }
662 Ok(plan)
663 }
664}
665
666fn value_output<K: Value, R: Value>(
667 groups: Groups,
668 rows: usize,
669 bytes: usize,
670) -> Result<(Vec<GroupValue<K, R>>, usize), Error> {
671 let mut output_bytes = 0;
672 let value = groups
673 .into_output()?
674 .into_iter()
675 .take(rows)
676 .map(|(key, reducer)| {
677 admit_output(key.len() + reducer.encoded_len(), bytes, &mut output_bytes)?;
678 decode_group_value(&key, reducer)
679 })
680 .collect::<Result<_, Error>>()?;
681 Ok((value, output_bytes))
682}
683
684fn count_output<K: Value>(
685 groups: Groups,
686 rows: usize,
687 bytes: usize,
688) -> Result<(Vec<GroupCount<K>>, usize), Error> {
689 let mut output_bytes = 0;
690 let value = groups
691 .into_output()?
692 .into_iter()
693 .take(rows)
694 .map(|(key, reducer)| {
695 admit_output(key.len() + 8, bytes, &mut output_bytes)?;
696 decode_group_count(&key, reducer)
697 })
698 .collect::<Result<_, Error>>()?;
699 Ok((value, output_bytes))
700}
701
702fn decode_group_count<K: Value>(key: &[u8], result: Completed) -> Result<GroupCount<K>, Error> {
703 Ok(GroupCount {
704 key: decode_record(key)?,
705 count: result.into_count()?,
706 })
707}
708
709fn decode_group_value<K: Value, R: Value>(
710 key: &[u8],
711 result: Completed,
712) -> Result<GroupValue<K, R>, Error> {
713 let value = result.into_value()?;
714 Ok(GroupValue {
715 key: decode_record(key)?,
716 value: value.as_deref().map(decode_record).transpose()?,
717 })
718}
719
720fn decode_record<R: Value>(bytes: &[u8]) -> Result<R, Error> {
721 let mut reader = Decoder::new(bytes)?;
722 let value = R::decode_from(&mut reader)?;
723 reader.finish()?;
724 Ok(value)
725}
726
727pub(super) enum Accumulator<'a> {
729 Exists(&'a mut bool),
731 Scalar(&'a mut Reducer),
732 Groups(&'a mut Groups),
733}
734impl Accumulator<'_> {
735 pub(super) fn needs_spans(&self) -> bool {
736 !matches!(
737 self,
738 Self::Exists(_)
739 | Self::Scalar(
740 Reducer::Numeric(_)
741 | Reducer::Count { presence: None, .. }
742 | Reducer::Distinct { .. }
743 )
744 )
745 }
746
747 pub(super) fn push(
748 &mut self,
749 entity: &EntitySchema,
750 values: &[IndexValue<'_>],
751 bytes: &[u8],
752 spans: &[(u16, u16)],
753 ) -> Result<(), Error> {
754 match self {
755 Self::Exists(found) => {
756 **found = true;
757 Ok(())
758 }
759 Self::Scalar(state) => state.push(entity, values, bytes, spans, MAX_STATE_BYTES),
760 Self::Groups(state) => state.push(entity, values, bytes, spans),
761 }
762 }
763}
764
765#[derive(Clone)]
766pub(super) enum Reducer {
767 Numeric(numeric::NumericAggregate),
768 Distinct {
769 mask: u16,
770 seen: BTreeSet<Vec<u8>>,
771 },
772 Count {
773 presence: Option<usize>,
774 total: u64,
775 },
776 Extremum {
777 position: usize,
778 maximum: bool,
779 selected: Option<(Vec<u8>, Vec<u8>)>,
780 },
781}
782impl Reducer {
783 fn distinct(mask: u16) -> Self {
784 Self::Distinct {
785 mask,
786 seen: BTreeSet::new(),
787 }
788 }
789
790 fn extremum(entity: &EntitySchema, mask: u16, maximum: bool) -> Result<Self, Error> {
791 if mask.count_ones() != 1 {
792 return Err(Error::InvalidQuery);
793 }
794 let position = mask.trailing_zeros() as usize;
795 if !key::supports(entity.fields[position].value) {
796 return Err(Error::InvalidQuery);
797 }
798 Ok(Self::Extremum {
799 position,
800 maximum,
801 selected: None,
802 })
803 }
804
805 fn retained_bytes(&self) -> usize {
806 match self {
807 Self::Numeric(state) => state.retained_bytes(),
808 Self::Count { .. } => 8,
809 Self::Distinct { seen, .. } => 8 + seen.iter().map(Vec::capacity).sum::<usize>(),
810 Self::Extremum { selected, .. } => selected
811 .as_ref()
812 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
813 }
814 }
815
816 fn finish(self) -> Result<Completed, Error> {
817 match self {
818 Self::Count { total, .. } => Ok(Completed::Count(total)),
819 Self::Distinct { seen, .. } => Ok(Completed::Count(seen.len() as u64)),
820 Self::Extremum { selected, .. } => Ok(Completed::Value(selected)),
821 Self::Numeric(state) => state.finish(),
822 }
823 }
824
825 fn push(
826 &mut self,
827 entity: &EntitySchema,
828 values: &[IndexValue<'_>],
829 bytes: &[u8],
830 spans: &[(u16, u16)],
831 allowance: usize,
832 ) -> Result<(), Error> {
833 match self {
834 Self::Numeric(state) => state.push(values)?,
835 Self::Distinct { mask, seen } => {
836 let key = comparison_key(entity, *mask, values)?;
837 if !seen.contains(&key) {
838 if seen.len() == MAX_DISTINCT_VALUES
839 || 8 + seen.iter().map(Vec::capacity).sum::<usize>() + key.capacity()
840 > allowance
841 {
842 return Err(Error::Limit);
843 }
844 seen.insert(key);
845 }
846 }
847 Self::Count { presence, total } => {
848 *total += u64::from(presence.is_none_or(|i| bytes[usize::from(spans[i].0)] != 0));
849 }
850 Self::Extremum {
851 position,
852 maximum,
853 selected,
854 } => {
855 let value = values[*position];
856 if value == IndexValue::Absent {
857 return Ok(());
858 }
859 let mut key = Vec::new();
860 value.append_component(entity.fields[*position].optional, &mut key);
861 if key.len() > MAX_COMPARISON_KEY {
862 return Err(Error::Limit);
863 }
864 if selected
865 .as_ref()
866 .is_none_or(|(old, _)| if *maximum { key > *old } else { key < *old })
867 {
868 let (start, end) = spans[*position];
869 if key.capacity() + usize::from(end - start) > allowance {
870 return Err(Error::Limit);
871 }
872 let output = bytes[usize::from(start)..usize::from(end)].to_vec();
874 if key.capacity() + output.capacity() > allowance {
875 return Err(Error::Limit);
876 }
877 *selected = Some((key, output));
878 }
879 }
880 }
881 Ok(())
882 }
883}
884
885enum Completed {
887 Count(u64),
888 Value(Option<(Vec<u8>, Vec<u8>)>),
889}
890impl Completed {
891 fn encoded_len(&self) -> usize {
892 match self {
893 Self::Count(_) => 8,
894 Self::Value(value) => value.as_ref().map_or(0, |(_, bytes)| bytes.len()),
895 }
896 }
897 fn result_key<'a>(&'a self, scratch: &'a mut [u8; 8]) -> Option<&'a [u8]> {
899 match self {
900 Self::Count(total) => {
901 *scratch = total.to_be_bytes();
902 Some(scratch)
903 }
904 Self::Value(selected) => selected.as_ref().map(|(key, _)| key.as_slice()),
905 }
906 }
907
908 fn retained_bytes(&self) -> usize {
909 match self {
910 Self::Count(_) => 8,
911 Self::Value(value) => value
912 .as_ref()
913 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
914 }
915 }
916 fn into_count(self) -> Result<u64, Error> {
917 match self {
918 Self::Count(count) => Ok(count),
919 _ => Err(Error::Corrupt),
920 }
921 }
922 fn into_value(self) -> Result<Option<Vec<u8>>, Error> {
923 match self {
924 Self::Value(value) => Ok(value.map(|(_, bytes)| bytes)),
925 _ => Err(Error::Corrupt),
926 }
927 }
928}
929
930pub(super) struct Groups {
931 selection: Selection,
932 mask: u16,
933 initial: Reducer,
935 rows: BTreeMap<Vec<u8>, (Vec<u8>, Reducer)>,
936 state_bytes: usize,
937}
938impl Groups {
939 fn into_output(self) -> Result<Vec<(Vec<u8>, Completed)>, Error> {
940 let mut state_bytes = self.state_bytes;
942 let mut rows = self
943 .rows
944 .into_iter()
945 .map(|(key, (record, reducer))| {
946 let previous = reducer.retained_bytes();
947 let result = reducer.finish()?;
948 state_bytes = state_bytes - previous + result.retained_bytes();
949 if state_bytes > MAX_STATE_BYTES {
950 return Err(Error::Limit);
951 }
952 Ok((key, (record, result)))
953 })
954 .collect::<Result<Vec<_>, Error>>()?;
955 rows.retain(|(_, (_, result))| {
956 let mut scratch = [0; 8];
957 let actual = result.result_key(&mut scratch);
958 self.selection
959 .predicates
960 .split_inclusive(|(_, _, or_next)| !or_next)
961 .all(|clause| {
962 clause.iter().any(|(comparison, operand, _)| {
963 comparison.accepts(actual, operand.as_deref(), self.selection.optional)
964 })
965 })
966 });
967 if self.selection.order == GroupOrder::KeyDescending {
968 rows.reverse();
971 } else if self.selection.order != GroupOrder::Key {
972 rows.sort_unstable_by(|(ka, (_, a)), (kb, (_, b))| {
973 let (mut sa, mut sb) = ([0; 8], [0; 8]);
974 let order = a.result_key(&mut sa).cmp(&b.result_key(&mut sb));
975 let order = if self.selection.order == GroupOrder::AggregateDescending {
976 order.reverse()
977 } else {
978 order
979 };
980 order.then_with(|| ka.cmp(kb))
981 });
982 }
983 Ok(rows.into_iter().map(|(_, row)| row).collect())
984 }
985
986 fn push(
987 &mut self,
988 entity: &EntitySchema,
989 values: &[IndexValue<'_>],
990 bytes: &[u8],
991 spans: &[(u16, u16)],
992 ) -> Result<(), Error> {
993 let key = comparison_key(entity, self.mask, values)?;
994 let size = projection_size(spans, self.mask);
995 if let Some((_, reducer)) = self.rows.get_mut(&key) {
996 let previous = reducer.retained_bytes();
997 reducer.push(
998 entity,
999 values,
1000 bytes,
1001 spans,
1002 MAX_STATE_BYTES - self.state_bytes + previous,
1003 )?;
1004 self.state_bytes = self.state_bytes - previous + reducer.retained_bytes();
1005 return Ok(());
1006 }
1007 let base = key.capacity() + size;
1008 let available = MAX_STATE_BYTES - self.state_bytes;
1009 if self.rows.len() == MAX_GROUPS || base + self.initial.retained_bytes() > available {
1010 return Err(Error::Limit);
1011 }
1012 let mut reducer = self.initial.clone();
1013 reducer.push(entity, values, bytes, spans, available - base)?;
1014 let output = copy_projection(bytes, spans, self.mask, size);
1015 let retained = key.capacity() + output.capacity() + reducer.retained_bytes();
1018 if retained > available {
1019 return Err(Error::Limit);
1020 }
1021 self.state_bytes += retained;
1022 self.rows.insert(key, (output, reducer));
1023 Ok(())
1024 }
1025}