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.read()?.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) = group_output(
328 groups,
329 self.request.rows,
330 self.request.bytes,
331 decode_group_value,
332 )?;
333 Ok(Aggregate {
334 value,
335 examined: page.examined,
336 fetched: page.fetched,
337 output_bytes,
338 })
339 }
340
341 pub fn exists(self) -> Result<Aggregate<bool>, Error> {
354 let mut plan = self.aggregate_plan(None, false)?;
355 self.select_aggregate_row_path(&mut plan)?;
356 let mut found = false;
357 let page = execute(
358 &self.db.read()?.map,
359 E::SCHEMA,
360 &self.request,
361 &plan,
362 Some(Accumulator::Exists(&mut found)),
363 )?;
364 Ok(Aggregate {
365 value: found,
366 examined: page.examined,
367 fetched: page.fetched,
368 output_bytes: 1,
369 })
370 }
371
372 pub fn count(self) -> Result<Aggregate<u64>, Error> {
389 if self.request.bytes < 8 {
390 return Err(Error::RowTooLarge);
391 }
392 let mut plan = self.aggregate_plan(None, false)?;
393 if self.request.predicates.is_empty() && self.request.index.is_none() {
394 return Ok(Aggregate {
395 value: self.db.read()?.cardinality::<E>()?,
396 examined: 0,
397 fetched: 0,
398 output_bytes: 8,
399 });
400 }
401 if plan.index.is_none()
402 && let Some(count) = self.count_members(&plan)?
403 {
404 return Ok(count);
405 }
406 if super::order::select_aggregate_path(E::SCHEMA, &self.request, &mut plan)? {
407 return self.count_keys(&plan);
408 }
409 if plan.index.is_some()
410 && let Some(count) = self.count_members(&plan)?
411 {
412 return Ok(count);
413 }
414 let reducer = self.count_reducer(None)?;
415 self.scalar_count_value(&plan, reducer)
416 }
417
418 pub fn count_validated(self) -> Result<Aggregate<u64>, Error> {
423 self.scalar_count(None)
424 }
425
426 pub fn count_index_entries(self) -> Result<Aggregate<u64>, Error> {
438 if self.request.index.is_none() || !self.request.predicates.is_empty() {
439 return Err(Error::InvalidQuery);
440 }
441 if self.request.bytes < 8 {
442 return Err(Error::RowTooLarge);
443 }
444 let plan = self.aggregate_plan(None, false)?;
445 self.count_keys(&plan)
446 }
447
448 fn count_members(&self, plan: &Plan<'_>) -> Result<Option<Aggregate<u64>>, Error> {
449 let Some(members) = super::range::point_count_members(E::SCHEMA, plan, &self.request)
450 else {
451 return Ok(None);
452 };
453 let db = self.db.read()?;
454 let mut count = 0;
455 for member in &members {
456 let key = crate::store_key::StoreKey::new([plan.prefix.as_slice(), *member].concat())?;
457 count += u64::from(db.map.contains_key(&key));
458 }
459 Ok(Some(Aggregate {
460 value: count,
461 examined: members.len(),
462 fetched: 0,
463 output_bytes: 8,
464 }))
465 }
466
467 fn count_keys(&self, plan: &Plan<'_>) -> Result<Aggregate<u64>, Error> {
468 let bounds = super::range::bounds(E::SCHEMA, &self.request, plan)?;
469 let mut examined = 0;
470 if let Some(range) = bounds {
471 let terminal = super::range::terminal_key(&range, false);
472 let db = self.db.read()?;
473 let entries = db.map.range((range.0.as_ref(), range.1.as_ref()));
474 for entry in entries.take(self.request.work) {
475 examined += 1;
476 if examined == self.request.work && terminal.is_none_or(|end| end != entry.key()) {
477 return Err(Error::Limit);
478 }
479 }
480 }
481 Ok(Aggregate {
482 value: examined as u64,
483 examined,
484 fetched: 0,
485 output_bytes: 8,
486 })
487 }
488
489 pub fn count_field(self, field: &str) -> Result<Aggregate<u64>, Error> {
497 self.scalar_count(Some(field))
498 }
499
500 pub fn count_distinct<K: Value>(self) -> Result<Aggregate<u64>, Error> {
509 if self.request.bytes < 8 {
510 return Err(Error::RowTooLarge);
511 }
512 let (mut plan, reducer) = self.distinct_plan::<K>()?;
513 self.select_aggregate_row_path(&mut plan)?;
514 self.scalar_count_value(&plan, reducer)
515 }
516
517 fn distinct_plan<K: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
518 let plan = self.aggregate_plan(Some(K::definition()), false)?;
519 let reducer = Reducer::distinct(plan.projection.ok_or(Error::InvalidQuery)?);
520 Ok((plan, reducer))
521 }
522
523 fn select_aggregate_row_path(&self, plan: &mut Plan<'static>) -> Result<(), Error> {
524 if plan.index.is_none() {
525 super::order::select_aggregate_path(E::SCHEMA, &self.request, plan)?;
526 }
527 Ok(())
528 }
529
530 fn scalar_count(self, field: Option<&str>) -> Result<Aggregate<u64>, Error> {
531 if self.request.bytes < 8 {
532 return Err(Error::RowTooLarge);
533 }
534 let mut plan = self.aggregate_plan(None, false)?;
535 self.select_aggregate_row_path(&mut plan)?;
536 let reducer = self.count_reducer(field)?;
537 self.scalar_count_value(&plan, reducer)
538 }
539
540 fn scalar_count_value(
541 self,
542 plan: &Plan<'_>,
543 mut reducer: Reducer,
544 ) -> Result<Aggregate<u64>, Error> {
545 let page = execute(
546 &self.db.read()?.map,
547 E::SCHEMA,
548 &self.request,
549 plan,
550 Some(Accumulator::Scalar(&mut reducer)),
551 )?;
552 Ok(Aggregate {
553 value: reducer.finish()?.into_count()?,
554 examined: page.examined,
555 fetched: page.fetched,
556 output_bytes: 8,
557 })
558 }
559
560 pub fn group_count<K: Value>(self) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
577 self.group_counts(None)
578 }
579
580 pub fn group_count_field<K: Value>(
589 self,
590 field: &str,
591 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
592 self.group_counts(Some(field))
593 }
594
595 pub fn group_count_distinct<K: Value, R: Value>(
608 self,
609 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
610 let (plan, reducer) = self.group_distinct_plan::<K, R>()?;
611 self.group_count_values(plan, reducer)
612 }
613
614 fn group_distinct_plan<K: Value, R: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
615 let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
616 let operand = admit_projection(E::SCHEMA, R::definition())?;
617 admit_ordered_fields(E::SCHEMA, operand)?;
618 plan.selected |= operand;
619 Ok((plan, Reducer::distinct(operand)))
620 }
621
622 fn group_counts<K: Value>(
623 self,
624 field: Option<&str>,
625 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
626 let plan = self.aggregate_plan(Some(K::definition()), true)?;
627 let reducer = self.count_reducer(field)?;
628 self.group_count_values(plan, reducer)
629 }
630
631 fn group_count_values<K: Value>(
632 self,
633 mut plan: Plan<'static>,
634 reducer: Reducer,
635 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
636 self.select_aggregate_row_path(&mut plan)?;
637 let (groups, page) = self.grouped(&plan, reducer)?;
638 let (value, output_bytes) = group_output(
639 groups,
640 self.request.rows,
641 self.request.bytes,
642 decode_group_count,
643 )?;
644 Ok(Aggregate {
645 value,
646 examined: page.examined,
647 fetched: page.fetched,
648 output_bytes,
649 })
650 }
651
652 fn count_reducer(&self, field: Option<&str>) -> Result<Reducer, Error> {
653 let presence = field
655 .map(|name| E::SCHEMA.field_position(name).ok_or(Error::InvalidQuery))
656 .transpose()?
657 .filter(|&i| E::SCHEMA.fields[i].optional);
658 Ok(Reducer::Count { presence, total: 0 })
659 }
660
661 fn grouped(
662 &self,
663 plan: &Plan<'_>,
664 initial: Reducer,
665 ) -> Result<(Groups, QueryPage<Vec<u8>>), Error> {
666 if self.request.groups.page.is_some() {
667 return Err(Error::InvalidQuery);
668 }
669 let mut groups = self.admit_groups(plan, initial)?;
670 let page = execute(
671 &self.db.read()?.map,
672 E::SCHEMA,
673 &self.request,
674 plan,
675 Some(Accumulator::Groups(&mut groups)),
676 )?;
677 Ok((groups, page))
678 }
679
680 fn admit_groups(&self, plan: &Plan<'_>, initial: Reducer) -> Result<Groups, Error> {
681 Ok(Groups {
682 selection: self.request.groups.admit(E::SCHEMA, &initial)?,
683 mask: plan.projection.ok_or(Error::InvalidQuery)?,
684 initial,
685 rows: BTreeMap::new(),
686 state_bytes: 0,
687 })
688 }
689
690 fn aggregate_plan(
691 &self,
692 output: Option<&TypeSchema>,
693 group_output: bool,
694 ) -> Result<Plan<'static>, Error> {
695 if self.request.cursor.is_some()
696 || self.request.distinct
697 || self.request.order.is_some()
698 || self.request.descending
699 {
700 return Err(Error::InvalidQuery);
701 }
702 let db = self.db.read()?;
703 db.schema.admits(E::SCHEMA)?;
704 let mut plan = Plan::admit(
705 E::SCHEMA,
706 &self.request,
707 db.schema.fingerprint(),
708 db.incarnation,
709 output,
710 super::PlanOutput::Aggregate {
711 grouped: group_output,
712 },
713 )?;
714 if let Some(mask) = plan.projection {
715 admit_ordered_fields(E::SCHEMA, mask)?;
716 plan.selected |= mask;
717 }
718 Ok(plan)
719 }
720}
721
722fn group_output<T>(
723 groups: Groups,
724 rows: usize,
725 bytes: usize,
726 decode: fn(&[u8], Completed) -> Result<T, Error>,
727) -> Result<(Vec<T>, usize), Error> {
728 let mut output_bytes = 0;
729 let value = groups
730 .into_output()?
731 .into_iter()
732 .take(rows)
733 .map(|(key, result)| {
734 admit_output(key.len() + result.encoded_len(), bytes, &mut output_bytes)?;
735 decode(&key, result)
736 })
737 .collect::<Result<_, Error>>()?;
738 Ok((value, output_bytes))
739}
740
741fn decode_group_count<K: Value>(key: &[u8], result: Completed) -> Result<GroupCount<K>, Error> {
742 Ok(GroupCount {
743 key: decode_record(key)?,
744 count: result.into_count()?,
745 })
746}
747
748fn decode_group_value<K: Value, R: Value>(
749 key: &[u8],
750 result: Completed,
751) -> Result<GroupValue<K, R>, Error> {
752 let value = result.into_value()?;
753 Ok(GroupValue {
754 key: decode_record(key)?,
755 value: value.as_deref().map(decode_record).transpose()?,
756 })
757}
758
759fn decode_record<R: Value>(bytes: &[u8]) -> Result<R, Error> {
760 let mut reader = Decoder::new(bytes)?;
761 let value = R::decode_from(&mut reader)?;
762 reader.finish()?;
763 Ok(value)
764}
765
766pub(super) enum Accumulator<'a> {
768 Exists(&'a mut bool),
770 Scalar(&'a mut Reducer),
771 Groups(&'a mut Groups),
772}
773impl Accumulator<'_> {
774 pub(super) fn needs_spans(&self) -> bool {
775 !matches!(
776 self,
777 Self::Exists(_)
778 | Self::Scalar(
779 Reducer::Numeric(_)
780 | Reducer::Count { presence: None, .. }
781 | Reducer::Distinct { .. }
782 )
783 )
784 }
785
786 pub(super) fn push(
787 &mut self,
788 entity: &EntitySchema,
789 values: &[IndexValue<'_>],
790 bytes: &[u8],
791 spans: &[(u16, u16)],
792 ) -> Result<(), Error> {
793 match self {
794 Self::Exists(found) => {
795 **found = true;
796 Ok(())
797 }
798 Self::Scalar(state) => state.push(entity, values, bytes, spans, MAX_STATE_BYTES),
799 Self::Groups(state) => state.push(entity, values, bytes, spans),
800 }
801 }
802}
803
804#[derive(Clone)]
805pub(super) enum Reducer {
806 Numeric(numeric::NumericAggregate),
807 Distinct {
808 mask: u16,
809 seen: BTreeSet<Vec<u8>>,
810 },
811 Count {
812 presence: Option<usize>,
813 total: u64,
814 },
815 Extremum {
816 position: usize,
817 maximum: bool,
818 selected: Option<(Vec<u8>, Vec<u8>)>,
819 },
820}
821impl Reducer {
822 fn distinct(mask: u16) -> Self {
823 Self::Distinct {
824 mask,
825 seen: BTreeSet::new(),
826 }
827 }
828
829 fn extremum(entity: &EntitySchema, mask: u16, maximum: bool) -> Result<Self, Error> {
830 if mask.count_ones() != 1 {
831 return Err(Error::InvalidQuery);
832 }
833 let position = mask.trailing_zeros() as usize;
834 if !key::supports(entity.fields[position].value) {
835 return Err(Error::InvalidQuery);
836 }
837 Ok(Self::Extremum {
838 position,
839 maximum,
840 selected: None,
841 })
842 }
843
844 fn retained_bytes(&self) -> usize {
845 match self {
846 Self::Numeric(state) => state.retained_bytes(),
847 Self::Count { .. } => 8,
848 Self::Distinct { seen, .. } => 8 + seen.iter().map(Vec::capacity).sum::<usize>(),
849 Self::Extremum { selected, .. } => selected
850 .as_ref()
851 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
852 }
853 }
854
855 fn finish(self) -> Result<Completed, Error> {
856 match self {
857 Self::Count { total, .. } => Ok(Completed::Count(total)),
858 Self::Distinct { seen, .. } => Ok(Completed::Count(seen.len() as u64)),
859 Self::Extremum { selected, .. } => Ok(Completed::Value(selected)),
860 Self::Numeric(state) => state.finish(),
861 }
862 }
863
864 fn push(
865 &mut self,
866 entity: &EntitySchema,
867 values: &[IndexValue<'_>],
868 bytes: &[u8],
869 spans: &[(u16, u16)],
870 allowance: usize,
871 ) -> Result<(), Error> {
872 match self {
873 Self::Numeric(state) => state.push(values)?,
874 Self::Distinct { mask, seen } => {
875 let key = comparison_key(entity, *mask, values)?;
876 if !seen.contains(&key) {
877 if seen.len() == MAX_DISTINCT_VALUES
878 || 8 + seen.iter().map(Vec::capacity).sum::<usize>() + key.capacity()
879 > allowance
880 {
881 return Err(Error::Limit);
882 }
883 seen.insert(key);
884 }
885 }
886 Self::Count { presence, total } => {
887 *total += u64::from(presence.is_none_or(|i| bytes[usize::from(spans[i].0)] != 0));
888 }
889 Self::Extremum {
890 position,
891 maximum,
892 selected,
893 } => {
894 let value = values[*position];
895 if value == IndexValue::Absent {
896 return Ok(());
897 }
898 let mut key = Vec::new();
899 value.append_component(entity.fields[*position].optional, &mut key);
900 if key.len() > MAX_COMPARISON_KEY {
901 return Err(Error::Limit);
902 }
903 if selected
904 .as_ref()
905 .is_none_or(|(old, _)| if *maximum { key > *old } else { key < *old })
906 {
907 let (start, end) = spans[*position];
908 if key.capacity() + usize::from(end - start) > allowance {
909 return Err(Error::Limit);
910 }
911 let output = bytes[usize::from(start)..usize::from(end)].to_vec();
913 if key.capacity() + output.capacity() > allowance {
914 return Err(Error::Limit);
915 }
916 *selected = Some((key, output));
917 }
918 }
919 }
920 Ok(())
921 }
922}
923
924enum Completed {
926 Count(u64),
927 Value(Option<(Vec<u8>, Vec<u8>)>),
928}
929impl Completed {
930 fn encoded_len(&self) -> usize {
931 match self {
932 Self::Count(_) => 8,
933 Self::Value(value) => value.as_ref().map_or(0, |(_, bytes)| bytes.len()),
934 }
935 }
936 fn result_key<'a>(&'a self, scratch: &'a mut [u8; 8]) -> Option<&'a [u8]> {
938 match self {
939 Self::Count(total) => {
940 *scratch = total.to_be_bytes();
941 Some(scratch)
942 }
943 Self::Value(selected) => selected.as_ref().map(|(key, _)| key.as_slice()),
944 }
945 }
946
947 fn retained_bytes(&self) -> usize {
948 match self {
949 Self::Count(_) => 8,
950 Self::Value(value) => value
951 .as_ref()
952 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
953 }
954 }
955
956 fn into_count(self) -> Result<u64, Error> {
957 match self {
958 Self::Count(count) => Ok(count),
959 _ => Err(Error::Corrupt),
960 }
961 }
962
963 fn into_value(self) -> Result<Option<Vec<u8>>, Error> {
964 match self {
965 Self::Value(value) => Ok(value.map(|(_, bytes)| bytes)),
966 _ => Err(Error::Corrupt),
967 }
968 }
969}
970
971pub(super) struct Groups {
972 selection: Selection,
973 mask: u16,
974 initial: Reducer,
976 rows: BTreeMap<Vec<u8>, (Vec<u8>, Reducer)>,
977 state_bytes: usize,
978}
979impl Groups {
980 fn into_output(self) -> Result<Vec<(Vec<u8>, Completed)>, Error> {
981 let mut state_bytes = self.state_bytes;
983 let mut rows = self
984 .rows
985 .into_iter()
986 .map(|(key, (record, reducer))| {
987 let previous = reducer.retained_bytes();
988 let result = reducer.finish()?;
989 state_bytes = state_bytes - previous + result.retained_bytes();
990 if state_bytes > MAX_STATE_BYTES {
991 return Err(Error::Limit);
992 }
993 Ok((key, (record, result)))
994 })
995 .collect::<Result<Vec<_>, Error>>()?;
996 rows.retain(|(_, (_, result))| {
997 let mut scratch = [0; 8];
998 let actual = result.result_key(&mut scratch);
999 self.selection
1000 .predicates
1001 .split_inclusive(|(_, _, or_next)| !or_next)
1002 .all(|clause| {
1003 clause.iter().any(|(comparison, operand, _)| {
1004 comparison.accepts(actual, operand.as_deref(), self.selection.optional)
1005 })
1006 })
1007 });
1008 if self.selection.order == GroupOrder::KeyDescending {
1009 rows.reverse();
1012 } else if self.selection.order != GroupOrder::Key {
1013 rows.sort_unstable_by(|(ka, (_, a)), (kb, (_, b))| {
1014 let (mut sa, mut sb) = ([0; 8], [0; 8]);
1015 let order = a.result_key(&mut sa).cmp(&b.result_key(&mut sb));
1016 let order = if self.selection.order == GroupOrder::AggregateDescending {
1017 order.reverse()
1018 } else {
1019 order
1020 };
1021 order.then_with(|| ka.cmp(kb))
1022 });
1023 }
1024 Ok(rows.into_iter().map(|(_, row)| row).collect())
1025 }
1026
1027 fn push(
1028 &mut self,
1029 entity: &EntitySchema,
1030 values: &[IndexValue<'_>],
1031 bytes: &[u8],
1032 spans: &[(u16, u16)],
1033 ) -> Result<(), Error> {
1034 let key = comparison_key(entity, self.mask, values)?;
1035 let size = projection_size(spans, self.mask);
1036 if let Some((_, reducer)) = self.rows.get_mut(&key) {
1037 let previous = reducer.retained_bytes();
1038 reducer.push(
1039 entity,
1040 values,
1041 bytes,
1042 spans,
1043 MAX_STATE_BYTES - self.state_bytes + previous,
1044 )?;
1045 self.state_bytes = self.state_bytes - previous + reducer.retained_bytes();
1046 return Ok(());
1047 }
1048 let base = key.capacity() + size;
1049 let available = MAX_STATE_BYTES - self.state_bytes;
1050 if self.rows.len() == MAX_GROUPS || base + self.initial.retained_bytes() > available {
1051 return Err(Error::Limit);
1052 }
1053 let mut reducer = self.initial.clone();
1054 reducer.push(entity, values, bytes, spans, available - base)?;
1055 let output = copy_projection(bytes, spans, self.mask, size);
1056 let retained = key.capacity() + output.capacity() + reducer.retained_bytes();
1059 if retained > available {
1060 return Err(Error::Limit);
1061 }
1062 self.state_bytes += retained;
1063 self.rows.insert(key, (output, reducer));
1064 Ok(())
1065 }
1066}