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> {
349 let mut plan = self.aggregate_plan(None, false)?;
350 if plan.index.is_none() && !super::range::covers_primary(&plan) {
351 super::order::select_covered_prefix(E::SCHEMA, &self.request, &mut plan)?;
352 }
353 let mut found = false;
354 let page = execute(
355 &self.db.map,
356 E::SCHEMA,
357 &self.request,
358 &plan,
359 Some(Accumulator::Exists(&mut found)),
360 )?;
361 Ok(Aggregate {
362 value: found,
363 examined: page.examined,
364 fetched: page.fetched,
365 output_bytes: 1,
366 })
367 }
368
369 pub fn count(self) -> Result<Aggregate<u64>, Error> {
383 if self.request.bytes < 8 {
384 return Err(Error::RowTooLarge);
385 }
386 let mut plan = self.aggregate_plan(None, false)?;
387 if self.request.predicates.is_empty() && self.request.index.is_none() {
388 return Ok(Aggregate {
389 value: self.db.cardinality::<E>()?,
390 examined: 0,
391 fetched: 0,
392 output_bytes: 8,
393 });
394 }
395 if super::range::covers_primary(&plan)
396 || super::order::select_covered_prefix(E::SCHEMA, &self.request, &mut plan)?
397 {
398 return self.count_keys(&plan);
399 }
400 let reducer = self.count_reducer(None)?;
401 self.scalar_count_value(&plan, reducer)
402 }
403
404 pub fn count_validated(self) -> Result<Aggregate<u64>, Error> {
409 self.scalar_count(None)
410 }
411
412 pub fn count_index_entries(self) -> Result<Aggregate<u64>, Error> {
423 if self.request.index.is_none() || !self.request.predicates.is_empty() {
424 return Err(Error::InvalidQuery);
425 }
426 if self.request.bytes < 8 {
427 return Err(Error::RowTooLarge);
428 }
429 let plan = self.aggregate_plan(None, false)?;
430 self.count_keys(&plan)
431 }
432
433 fn count_keys(&self, plan: &Plan<'_>) -> Result<Aggregate<u64>, Error> {
434 let bounds = super::range::bounds(E::SCHEMA, &self.request, plan)?;
435 let mut examined = 0;
436 if let Some(range) = bounds {
437 let terminal = super::range::terminal_key(&range, false);
438 let entries = self.db.map.range((range.0.as_ref(), range.1.as_ref()));
439 for entry in entries.take(self.request.work) {
440 examined += 1;
441 if examined == self.request.work && terminal.is_none_or(|end| end != entry.key()) {
442 return Err(Error::Limit);
443 }
444 }
445 }
446 Ok(Aggregate {
447 value: examined as u64,
448 examined,
449 fetched: 0,
450 output_bytes: 8,
451 })
452 }
453
454 pub fn count_field(self, field: &str) -> Result<Aggregate<u64>, Error> {
462 self.scalar_count(Some(field))
463 }
464
465 pub fn count_distinct<K: Value>(self) -> Result<Aggregate<u64>, Error> {
474 if self.request.bytes < 8 {
475 return Err(Error::RowTooLarge);
476 }
477 let (plan, reducer) = self.distinct_plan::<K>()?;
478 self.scalar_count_value(&plan, reducer)
479 }
480
481 fn distinct_plan<K: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
482 let plan = self.aggregate_plan(Some(K::definition()), false)?;
483 let reducer = Reducer::distinct(plan.projection.ok_or(Error::InvalidQuery)?);
484 Ok((plan, reducer))
485 }
486
487 fn scalar_count(self, field: Option<&str>) -> Result<Aggregate<u64>, Error> {
488 if self.request.bytes < 8 {
489 return Err(Error::RowTooLarge);
490 }
491 let plan = self.aggregate_plan(None, false)?;
492 let reducer = self.count_reducer(field)?;
493 self.scalar_count_value(&plan, reducer)
494 }
495
496 fn scalar_count_value(
497 self,
498 plan: &Plan<'_>,
499 mut reducer: Reducer,
500 ) -> Result<Aggregate<u64>, Error> {
501 let page = execute(
502 &self.db.map,
503 E::SCHEMA,
504 &self.request,
505 plan,
506 Some(Accumulator::Scalar(&mut reducer)),
507 )?;
508 Ok(Aggregate {
509 value: reducer.finish()?.into_count()?,
510 examined: page.examined,
511 fetched: page.fetched,
512 output_bytes: 8,
513 })
514 }
515
516 pub fn group_count<K: Value>(self) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
533 self.group_counts(None)
534 }
535
536 pub fn group_count_field<K: Value>(
545 self,
546 field: &str,
547 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
548 self.group_counts(Some(field))
549 }
550
551 pub fn group_count_distinct<K: Value, R: Value>(
564 self,
565 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
566 let (plan, reducer) = self.group_distinct_plan::<K, R>()?;
567 self.group_count_values(&plan, reducer)
568 }
569
570 fn group_distinct_plan<K: Value, R: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
571 let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
572 let operand = admit_projection(E::SCHEMA, R::definition())?;
573 admit_ordered_fields(E::SCHEMA, operand)?;
574 plan.selected |= operand;
575 Ok((plan, Reducer::distinct(operand)))
576 }
577
578 fn group_counts<K: Value>(
579 self,
580 field: Option<&str>,
581 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
582 let plan = self.aggregate_plan(Some(K::definition()), true)?;
583 let reducer = self.count_reducer(field)?;
584 self.group_count_values(&plan, reducer)
585 }
586
587 fn group_count_values<K: Value>(
588 self,
589 plan: &Plan<'_>,
590 reducer: Reducer,
591 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
592 let (groups, page) = self.grouped(plan, reducer)?;
593 let (value, output_bytes) = count_output(groups, self.request.rows, self.request.bytes)?;
594 Ok(Aggregate {
595 value,
596 examined: page.examined,
597 fetched: page.fetched,
598 output_bytes,
599 })
600 }
601
602 fn count_reducer(&self, field: Option<&str>) -> Result<Reducer, Error> {
603 let presence = field
605 .map(|name| {
606 E::SCHEMA
607 .fields
608 .iter()
609 .enumerate()
610 .find(|(_, f)| f.name == name)
611 .map(|(i, f)| f.optional.then_some(i))
612 .ok_or(Error::InvalidQuery)
613 })
614 .transpose()?
615 .flatten();
616 Ok(Reducer::Count { presence, total: 0 })
617 }
618
619 fn grouped(
620 &self,
621 plan: &Plan<'_>,
622 initial: Reducer,
623 ) -> Result<(Groups, QueryPage<Vec<u8>>), Error> {
624 if self.request.groups.page.is_some() {
625 return Err(Error::InvalidQuery);
626 }
627 let mut groups = self.admit_groups(plan, initial)?;
628 let page = execute(
629 &self.db.map,
630 E::SCHEMA,
631 &self.request,
632 plan,
633 Some(Accumulator::Groups(&mut groups)),
634 )?;
635 Ok((groups, page))
636 }
637
638 fn admit_groups(&self, plan: &Plan<'_>, initial: Reducer) -> Result<Groups, Error> {
639 Ok(Groups {
640 selection: self.request.groups.admit(E::SCHEMA, &initial)?,
641 mask: plan.projection.ok_or(Error::InvalidQuery)?,
642 initial,
643 rows: BTreeMap::new(),
644 state_bytes: 0,
645 })
646 }
647
648 fn aggregate_plan(
649 &self,
650 output: Option<&TypeSchema>,
651 group_output: bool,
652 ) -> Result<Plan<'static>, Error> {
653 if self.request.cursor.is_some()
654 || self.request.distinct
655 || self.request.order.is_some()
656 || self.request.descending
657 {
658 return Err(Error::InvalidQuery);
659 }
660 self.db.schema.admits(E::SCHEMA)?;
661 let mut plan = Plan::admit(
662 E::SCHEMA,
663 &self.request,
664 self.db.schema.fingerprint(),
665 self.db.incarnation,
666 output,
667 group_output,
668 )?;
669 if let Some(mask) = plan.projection {
670 admit_ordered_fields(E::SCHEMA, mask)?;
671 plan.selected |= mask;
672 }
673 Ok(plan)
674 }
675}
676
677fn value_output<K: Value, R: Value>(
678 groups: Groups,
679 rows: usize,
680 bytes: usize,
681) -> Result<(Vec<GroupValue<K, R>>, usize), Error> {
682 let mut output_bytes = 0;
683 let value = groups
684 .into_output()?
685 .into_iter()
686 .take(rows)
687 .map(|(key, reducer)| {
688 admit_output(key.len() + reducer.encoded_len(), bytes, &mut output_bytes)?;
689 decode_group_value(&key, reducer)
690 })
691 .collect::<Result<_, Error>>()?;
692 Ok((value, output_bytes))
693}
694
695fn count_output<K: Value>(
696 groups: Groups,
697 rows: usize,
698 bytes: usize,
699) -> Result<(Vec<GroupCount<K>>, usize), Error> {
700 let mut output_bytes = 0;
701 let value = groups
702 .into_output()?
703 .into_iter()
704 .take(rows)
705 .map(|(key, reducer)| {
706 admit_output(key.len() + 8, bytes, &mut output_bytes)?;
707 decode_group_count(&key, reducer)
708 })
709 .collect::<Result<_, Error>>()?;
710 Ok((value, output_bytes))
711}
712
713fn decode_group_count<K: Value>(key: &[u8], result: Completed) -> Result<GroupCount<K>, Error> {
714 Ok(GroupCount {
715 key: decode_record(key)?,
716 count: result.into_count()?,
717 })
718}
719
720fn decode_group_value<K: Value, R: Value>(
721 key: &[u8],
722 result: Completed,
723) -> Result<GroupValue<K, R>, Error> {
724 let value = result.into_value()?;
725 Ok(GroupValue {
726 key: decode_record(key)?,
727 value: value.as_deref().map(decode_record).transpose()?,
728 })
729}
730
731fn decode_record<R: Value>(bytes: &[u8]) -> Result<R, Error> {
732 let mut reader = Decoder::new(bytes)?;
733 let value = R::decode_from(&mut reader)?;
734 reader.finish()?;
735 Ok(value)
736}
737
738pub(super) enum Accumulator<'a> {
740 Exists(&'a mut bool),
742 Scalar(&'a mut Reducer),
743 Groups(&'a mut Groups),
744}
745impl Accumulator<'_> {
746 pub(super) fn needs_spans(&self) -> bool {
747 !matches!(
748 self,
749 Self::Exists(_)
750 | Self::Scalar(
751 Reducer::Numeric(_)
752 | Reducer::Count { presence: None, .. }
753 | Reducer::Distinct { .. }
754 )
755 )
756 }
757
758 pub(super) fn push(
759 &mut self,
760 entity: &EntitySchema,
761 values: &[IndexValue<'_>],
762 bytes: &[u8],
763 spans: &[(u16, u16)],
764 ) -> Result<(), Error> {
765 match self {
766 Self::Exists(found) => {
767 **found = true;
768 Ok(())
769 }
770 Self::Scalar(state) => state.push(entity, values, bytes, spans, MAX_STATE_BYTES),
771 Self::Groups(state) => state.push(entity, values, bytes, spans),
772 }
773 }
774}
775
776#[derive(Clone)]
777pub(super) enum Reducer {
778 Numeric(numeric::NumericAggregate),
779 Distinct {
780 mask: u16,
781 seen: BTreeSet<Vec<u8>>,
782 },
783 Count {
784 presence: Option<usize>,
785 total: u64,
786 },
787 Extremum {
788 position: usize,
789 maximum: bool,
790 selected: Option<(Vec<u8>, Vec<u8>)>,
791 },
792}
793impl Reducer {
794 fn distinct(mask: u16) -> Self {
795 Self::Distinct {
796 mask,
797 seen: BTreeSet::new(),
798 }
799 }
800
801 fn extremum(entity: &EntitySchema, mask: u16, maximum: bool) -> Result<Self, Error> {
802 if mask.count_ones() != 1 {
803 return Err(Error::InvalidQuery);
804 }
805 let position = mask.trailing_zeros() as usize;
806 if !key::supports(entity.fields[position].value) {
807 return Err(Error::InvalidQuery);
808 }
809 Ok(Self::Extremum {
810 position,
811 maximum,
812 selected: None,
813 })
814 }
815
816 fn retained_bytes(&self) -> usize {
817 match self {
818 Self::Numeric(state) => state.retained_bytes(),
819 Self::Count { .. } => 8,
820 Self::Distinct { seen, .. } => 8 + seen.iter().map(Vec::capacity).sum::<usize>(),
821 Self::Extremum { selected, .. } => selected
822 .as_ref()
823 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
824 }
825 }
826
827 fn finish(self) -> Result<Completed, Error> {
828 match self {
829 Self::Count { total, .. } => Ok(Completed::Count(total)),
830 Self::Distinct { seen, .. } => Ok(Completed::Count(seen.len() as u64)),
831 Self::Extremum { selected, .. } => Ok(Completed::Value(selected)),
832 Self::Numeric(state) => state.finish(),
833 }
834 }
835
836 fn push(
837 &mut self,
838 entity: &EntitySchema,
839 values: &[IndexValue<'_>],
840 bytes: &[u8],
841 spans: &[(u16, u16)],
842 allowance: usize,
843 ) -> Result<(), Error> {
844 match self {
845 Self::Numeric(state) => state.push(values)?,
846 Self::Distinct { mask, seen } => {
847 let key = comparison_key(entity, *mask, values)?;
848 if !seen.contains(&key) {
849 if seen.len() == MAX_DISTINCT_VALUES
850 || 8 + seen.iter().map(Vec::capacity).sum::<usize>() + key.capacity()
851 > allowance
852 {
853 return Err(Error::Limit);
854 }
855 seen.insert(key);
856 }
857 }
858 Self::Count { presence, total } => {
859 *total += u64::from(presence.is_none_or(|i| bytes[usize::from(spans[i].0)] != 0));
860 }
861 Self::Extremum {
862 position,
863 maximum,
864 selected,
865 } => {
866 let value = values[*position];
867 if value == IndexValue::Absent {
868 return Ok(());
869 }
870 let mut key = Vec::new();
871 value.append_component(entity.fields[*position].optional, &mut key);
872 if key.len() > MAX_COMPARISON_KEY {
873 return Err(Error::Limit);
874 }
875 if selected
876 .as_ref()
877 .is_none_or(|(old, _)| if *maximum { key > *old } else { key < *old })
878 {
879 let (start, end) = spans[*position];
880 if key.capacity() + usize::from(end - start) > allowance {
881 return Err(Error::Limit);
882 }
883 let output = bytes[usize::from(start)..usize::from(end)].to_vec();
885 if key.capacity() + output.capacity() > allowance {
886 return Err(Error::Limit);
887 }
888 *selected = Some((key, output));
889 }
890 }
891 }
892 Ok(())
893 }
894}
895
896enum Completed {
898 Count(u64),
899 Value(Option<(Vec<u8>, Vec<u8>)>),
900}
901impl Completed {
902 fn encoded_len(&self) -> usize {
903 match self {
904 Self::Count(_) => 8,
905 Self::Value(value) => value.as_ref().map_or(0, |(_, bytes)| bytes.len()),
906 }
907 }
908 fn result_key<'a>(&'a self, scratch: &'a mut [u8; 8]) -> Option<&'a [u8]> {
910 match self {
911 Self::Count(total) => {
912 *scratch = total.to_be_bytes();
913 Some(scratch)
914 }
915 Self::Value(selected) => selected.as_ref().map(|(key, _)| key.as_slice()),
916 }
917 }
918
919 fn retained_bytes(&self) -> usize {
920 match self {
921 Self::Count(_) => 8,
922 Self::Value(value) => value
923 .as_ref()
924 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
925 }
926 }
927 fn into_count(self) -> Result<u64, Error> {
928 match self {
929 Self::Count(count) => Ok(count),
930 _ => Err(Error::Corrupt),
931 }
932 }
933 fn into_value(self) -> Result<Option<Vec<u8>>, Error> {
934 match self {
935 Self::Value(value) => Ok(value.map(|(_, bytes)| bytes)),
936 _ => Err(Error::Corrupt),
937 }
938 }
939}
940
941pub(super) struct Groups {
942 selection: Selection,
943 mask: u16,
944 initial: Reducer,
946 rows: BTreeMap<Vec<u8>, (Vec<u8>, Reducer)>,
947 state_bytes: usize,
948}
949impl Groups {
950 fn into_output(self) -> Result<Vec<(Vec<u8>, Completed)>, Error> {
951 let mut state_bytes = self.state_bytes;
953 let mut rows = self
954 .rows
955 .into_iter()
956 .map(|(key, (record, reducer))| {
957 let previous = reducer.retained_bytes();
958 let result = reducer.finish()?;
959 state_bytes = state_bytes - previous + result.retained_bytes();
960 if state_bytes > MAX_STATE_BYTES {
961 return Err(Error::Limit);
962 }
963 Ok((key, (record, result)))
964 })
965 .collect::<Result<Vec<_>, Error>>()?;
966 rows.retain(|(_, (_, result))| {
967 let mut scratch = [0; 8];
968 let actual = result.result_key(&mut scratch);
969 self.selection
970 .predicates
971 .split_inclusive(|(_, _, or_next)| !or_next)
972 .all(|clause| {
973 clause.iter().any(|(comparison, operand, _)| {
974 comparison.accepts(actual, operand.as_deref(), self.selection.optional)
975 })
976 })
977 });
978 if self.selection.order == GroupOrder::KeyDescending {
979 rows.reverse();
982 } else if self.selection.order != GroupOrder::Key {
983 rows.sort_unstable_by(|(ka, (_, a)), (kb, (_, b))| {
984 let (mut sa, mut sb) = ([0; 8], [0; 8]);
985 let order = a.result_key(&mut sa).cmp(&b.result_key(&mut sb));
986 let order = if self.selection.order == GroupOrder::AggregateDescending {
987 order.reverse()
988 } else {
989 order
990 };
991 order.then_with(|| ka.cmp(kb))
992 });
993 }
994 Ok(rows.into_iter().map(|(_, row)| row).collect())
995 }
996
997 fn push(
998 &mut self,
999 entity: &EntitySchema,
1000 values: &[IndexValue<'_>],
1001 bytes: &[u8],
1002 spans: &[(u16, u16)],
1003 ) -> Result<(), Error> {
1004 let key = comparison_key(entity, self.mask, values)?;
1005 let size = projection_size(spans, self.mask);
1006 if let Some((_, reducer)) = self.rows.get_mut(&key) {
1007 let previous = reducer.retained_bytes();
1008 reducer.push(
1009 entity,
1010 values,
1011 bytes,
1012 spans,
1013 MAX_STATE_BYTES - self.state_bytes + previous,
1014 )?;
1015 self.state_bytes = self.state_bytes - previous + reducer.retained_bytes();
1016 return Ok(());
1017 }
1018 let base = key.capacity() + size;
1019 let available = MAX_STATE_BYTES - self.state_bytes;
1020 if self.rows.len() == MAX_GROUPS || base + self.initial.retained_bytes() > available {
1021 return Err(Error::Limit);
1022 }
1023 let mut reducer = self.initial.clone();
1024 reducer.push(entity, values, bytes, spans, available - base)?;
1025 let output = copy_projection(bytes, spans, self.mask, size);
1026 let retained = key.capacity() + output.capacity() + reducer.retained_bytes();
1029 if retained > available {
1030 return Err(Error::Limit);
1031 }
1032 self.state_bytes += retained;
1033 self.rows.insert(key, (output, reducer));
1034 Ok(())
1035 }
1036}