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> {
376 self.scalar_count(None)
377 }
378
379 pub fn count_index_entries(self) -> Result<Aggregate<u64>, Error> {
390 if self.request.index.is_none() || !self.request.predicates.is_empty() {
391 return Err(Error::InvalidQuery);
392 }
393 if self.request.bytes < 8 {
394 return Err(Error::RowTooLarge);
395 }
396 let plan = self.aggregate_plan(None, false)?;
397 let bounds = super::range::bounds(E::SCHEMA, &self.request, &plan)?;
398 let examined = bounds.map_or(0, |range| {
399 self.db.map.range(range).take(self.request.work).count()
400 });
401 if examined == self.request.work {
402 return Err(Error::Limit);
403 }
404 Ok(Aggregate {
405 value: examined as u64,
406 examined,
407 fetched: 0,
408 output_bytes: 8,
409 })
410 }
411
412 pub fn count_field(self, field: &str) -> Result<Aggregate<u64>, Error> {
420 self.scalar_count(Some(field))
421 }
422
423 pub fn count_distinct<K: Value>(self) -> Result<Aggregate<u64>, Error> {
432 if self.request.bytes < 8 {
433 return Err(Error::RowTooLarge);
434 }
435 let (plan, reducer) = self.distinct_plan::<K>()?;
436 self.scalar_count_value(&plan, reducer)
437 }
438
439 fn distinct_plan<K: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
440 let plan = self.aggregate_plan(Some(K::definition()), false)?;
441 let reducer = Reducer::distinct(plan.projection.ok_or(Error::InvalidQuery)?);
442 Ok((plan, reducer))
443 }
444
445 fn scalar_count(self, field: Option<&str>) -> Result<Aggregate<u64>, Error> {
446 if self.request.bytes < 8 {
447 return Err(Error::RowTooLarge);
448 }
449 let plan = self.aggregate_plan(None, false)?;
450 let reducer = self.count_reducer(field)?;
451 self.scalar_count_value(&plan, reducer)
452 }
453
454 fn scalar_count_value(
455 self,
456 plan: &Plan<'_>,
457 mut reducer: Reducer,
458 ) -> Result<Aggregate<u64>, Error> {
459 let page = execute(
460 &self.db.map,
461 E::SCHEMA,
462 &self.request,
463 plan,
464 Some(Accumulator::Scalar(&mut reducer)),
465 )?;
466 Ok(Aggregate {
467 value: reducer.finish()?.into_count()?,
468 examined: page.examined,
469 fetched: page.fetched,
470 output_bytes: 8,
471 })
472 }
473
474 pub fn group_count<K: Value>(self) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
491 self.group_counts(None)
492 }
493
494 pub fn group_count_field<K: Value>(
503 self,
504 field: &str,
505 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
506 self.group_counts(Some(field))
507 }
508
509 pub fn group_count_distinct<K: Value, R: Value>(
522 self,
523 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
524 let (plan, reducer) = self.group_distinct_plan::<K, R>()?;
525 self.group_count_values(&plan, reducer)
526 }
527
528 fn group_distinct_plan<K: Value, R: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
529 let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
530 let operand = admit_projection(E::SCHEMA, R::definition())?;
531 admit_ordered_fields(E::SCHEMA, operand)?;
532 plan.selected |= operand;
533 Ok((plan, Reducer::distinct(operand)))
534 }
535
536 fn group_counts<K: Value>(
537 self,
538 field: Option<&str>,
539 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
540 let plan = self.aggregate_plan(Some(K::definition()), true)?;
541 let reducer = self.count_reducer(field)?;
542 self.group_count_values(&plan, reducer)
543 }
544
545 fn group_count_values<K: Value>(
546 self,
547 plan: &Plan<'_>,
548 reducer: Reducer,
549 ) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
550 let (groups, page) = self.grouped(plan, reducer)?;
551 let (value, output_bytes) = count_output(groups, self.request.rows, self.request.bytes)?;
552 Ok(Aggregate {
553 value,
554 examined: page.examined,
555 fetched: page.fetched,
556 output_bytes,
557 })
558 }
559
560 fn count_reducer(&self, field: Option<&str>) -> Result<Reducer, Error> {
561 let presence = field
563 .map(|name| {
564 E::SCHEMA
565 .fields
566 .iter()
567 .enumerate()
568 .find(|(_, f)| f.name == name)
569 .map(|(i, f)| f.optional.then_some(i))
570 .ok_or(Error::InvalidQuery)
571 })
572 .transpose()?
573 .flatten();
574 Ok(Reducer::Count { presence, total: 0 })
575 }
576
577 fn grouped(
578 &self,
579 plan: &Plan<'_>,
580 initial: Reducer,
581 ) -> Result<(Groups, QueryPage<Vec<u8>>), Error> {
582 if self.request.groups.page.is_some() {
583 return Err(Error::InvalidQuery);
584 }
585 let mut groups = self.admit_groups(plan, initial)?;
586 let page = execute(
587 &self.db.map,
588 E::SCHEMA,
589 &self.request,
590 plan,
591 Some(Accumulator::Groups(&mut groups)),
592 )?;
593 Ok((groups, page))
594 }
595
596 fn admit_groups(&self, plan: &Plan<'_>, initial: Reducer) -> Result<Groups, Error> {
597 Ok(Groups {
598 selection: self.request.groups.admit(E::SCHEMA, &initial)?,
599 mask: plan.projection.ok_or(Error::InvalidQuery)?,
600 initial,
601 rows: BTreeMap::new(),
602 state_bytes: 0,
603 })
604 }
605
606 fn aggregate_plan(
607 &self,
608 output: Option<&TypeSchema>,
609 group_output: bool,
610 ) -> Result<Plan<'static>, Error> {
611 if self.request.cursor.is_some()
612 || self.request.distinct
613 || self.request.order.is_some()
614 || self.request.descending
615 {
616 return Err(Error::InvalidQuery);
617 }
618 self.db.schema.admits(E::SCHEMA)?;
619 let mut plan = Plan::admit(
620 E::SCHEMA,
621 &self.request,
622 self.db.schema.fingerprint(),
623 self.db.incarnation,
624 output,
625 group_output,
626 )?;
627 if let Some(mask) = plan.projection {
628 admit_ordered_fields(E::SCHEMA, mask)?;
629 plan.selected |= mask;
630 }
631 Ok(plan)
632 }
633}
634
635fn value_output<K: Value, R: Value>(
636 groups: Groups,
637 rows: usize,
638 bytes: usize,
639) -> Result<(Vec<GroupValue<K, R>>, usize), Error> {
640 let mut output_bytes = 0;
641 let value = groups
642 .into_output()?
643 .into_iter()
644 .take(rows)
645 .map(|(key, reducer)| {
646 admit_output(key.len() + reducer.encoded_len(), bytes, &mut output_bytes)?;
647 decode_group_value(&key, reducer)
648 })
649 .collect::<Result<_, Error>>()?;
650 Ok((value, output_bytes))
651}
652
653fn count_output<K: Value>(
654 groups: Groups,
655 rows: usize,
656 bytes: usize,
657) -> Result<(Vec<GroupCount<K>>, usize), Error> {
658 let mut output_bytes = 0;
659 let value = groups
660 .into_output()?
661 .into_iter()
662 .take(rows)
663 .map(|(key, reducer)| {
664 admit_output(key.len() + 8, bytes, &mut output_bytes)?;
665 decode_group_count(&key, reducer)
666 })
667 .collect::<Result<_, Error>>()?;
668 Ok((value, output_bytes))
669}
670
671fn decode_group_count<K: Value>(key: &[u8], result: Completed) -> Result<GroupCount<K>, Error> {
672 Ok(GroupCount {
673 key: decode_record(key)?,
674 count: result.into_count()?,
675 })
676}
677
678fn decode_group_value<K: Value, R: Value>(
679 key: &[u8],
680 result: Completed,
681) -> Result<GroupValue<K, R>, Error> {
682 let value = result.into_value()?;
683 Ok(GroupValue {
684 key: decode_record(key)?,
685 value: value.as_deref().map(decode_record).transpose()?,
686 })
687}
688
689fn decode_record<R: Value>(bytes: &[u8]) -> Result<R, Error> {
690 let mut reader = Decoder::new(bytes)?;
691 let value = R::decode_from(&mut reader)?;
692 reader.finish()?;
693 Ok(value)
694}
695
696pub(super) enum Accumulator<'a> {
698 Exists(&'a mut bool),
700 Scalar(&'a mut Reducer),
701 Groups(&'a mut Groups),
702}
703impl Accumulator<'_> {
704 pub(super) fn needs_spans(&self) -> bool {
705 !matches!(
706 self,
707 Self::Exists(_)
708 | Self::Scalar(
709 Reducer::Numeric(_)
710 | Reducer::Count { presence: None, .. }
711 | Reducer::Distinct { .. }
712 )
713 )
714 }
715
716 pub(super) fn push(
717 &mut self,
718 entity: &EntitySchema,
719 values: &[IndexValue<'_>],
720 bytes: &[u8],
721 spans: &[(u16, u16)],
722 ) -> Result<(), Error> {
723 match self {
724 Self::Exists(found) => {
725 **found = true;
726 Ok(())
727 }
728 Self::Scalar(state) => state.push(entity, values, bytes, spans, MAX_STATE_BYTES),
729 Self::Groups(state) => state.push(entity, values, bytes, spans),
730 }
731 }
732}
733
734#[derive(Clone)]
735pub(super) enum Reducer {
736 Numeric(numeric::NumericAggregate),
737 Distinct {
738 mask: u16,
739 seen: BTreeSet<Vec<u8>>,
740 },
741 Count {
742 presence: Option<usize>,
743 total: u64,
744 },
745 Extremum {
746 position: usize,
747 maximum: bool,
748 selected: Option<(Vec<u8>, Vec<u8>)>,
749 },
750}
751impl Reducer {
752 fn distinct(mask: u16) -> Self {
753 Self::Distinct {
754 mask,
755 seen: BTreeSet::new(),
756 }
757 }
758
759 fn extremum(entity: &EntitySchema, mask: u16, maximum: bool) -> Result<Self, Error> {
760 if mask.count_ones() != 1 {
761 return Err(Error::InvalidQuery);
762 }
763 let position = mask.trailing_zeros() as usize;
764 if !key::supports(entity.fields[position].value) {
765 return Err(Error::InvalidQuery);
766 }
767 Ok(Self::Extremum {
768 position,
769 maximum,
770 selected: None,
771 })
772 }
773
774 fn retained_bytes(&self) -> usize {
775 match self {
776 Self::Numeric(state) => state.retained_bytes(),
777 Self::Count { .. } => 8,
778 Self::Distinct { seen, .. } => 8 + seen.iter().map(Vec::capacity).sum::<usize>(),
779 Self::Extremum { selected, .. } => selected
780 .as_ref()
781 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
782 }
783 }
784
785 fn finish(self) -> Result<Completed, Error> {
786 match self {
787 Self::Count { total, .. } => Ok(Completed::Count(total)),
788 Self::Distinct { seen, .. } => Ok(Completed::Count(seen.len() as u64)),
789 Self::Extremum { selected, .. } => Ok(Completed::Value(selected)),
790 Self::Numeric(state) => state.finish(),
791 }
792 }
793
794 fn push(
795 &mut self,
796 entity: &EntitySchema,
797 values: &[IndexValue<'_>],
798 bytes: &[u8],
799 spans: &[(u16, u16)],
800 allowance: usize,
801 ) -> Result<(), Error> {
802 match self {
803 Self::Numeric(state) => state.push(values)?,
804 Self::Distinct { mask, seen } => {
805 let key = comparison_key(entity, *mask, values)?;
806 if !seen.contains(&key) {
807 if seen.len() == MAX_DISTINCT_VALUES
808 || 8 + seen.iter().map(Vec::capacity).sum::<usize>() + key.capacity()
809 > allowance
810 {
811 return Err(Error::Limit);
812 }
813 seen.insert(key);
814 }
815 }
816 Self::Count { presence, total } => {
817 *total += u64::from(presence.is_none_or(|i| bytes[usize::from(spans[i].0)] != 0));
818 }
819 Self::Extremum {
820 position,
821 maximum,
822 selected,
823 } => {
824 let value = values[*position];
825 if value == IndexValue::Absent {
826 return Ok(());
827 }
828 let mut key = Vec::new();
829 value.append_component(entity.fields[*position].optional, &mut key);
830 if key.len() > MAX_COMPARISON_KEY {
831 return Err(Error::Limit);
832 }
833 if selected
834 .as_ref()
835 .is_none_or(|(old, _)| if *maximum { key > *old } else { key < *old })
836 {
837 let (start, end) = spans[*position];
838 if key.capacity() + usize::from(end - start) > allowance {
839 return Err(Error::Limit);
840 }
841 let output = bytes[usize::from(start)..usize::from(end)].to_vec();
843 if key.capacity() + output.capacity() > allowance {
844 return Err(Error::Limit);
845 }
846 *selected = Some((key, output));
847 }
848 }
849 }
850 Ok(())
851 }
852}
853
854enum Completed {
856 Count(u64),
857 Value(Option<(Vec<u8>, Vec<u8>)>),
858}
859impl Completed {
860 fn encoded_len(&self) -> usize {
861 match self {
862 Self::Count(_) => 8,
863 Self::Value(value) => value.as_ref().map_or(0, |(_, bytes)| bytes.len()),
864 }
865 }
866 fn result_key<'a>(&'a self, scratch: &'a mut [u8; 8]) -> Option<&'a [u8]> {
868 match self {
869 Self::Count(total) => {
870 *scratch = total.to_be_bytes();
871 Some(scratch)
872 }
873 Self::Value(selected) => selected.as_ref().map(|(key, _)| key.as_slice()),
874 }
875 }
876
877 fn retained_bytes(&self) -> usize {
878 match self {
879 Self::Count(_) => 8,
880 Self::Value(value) => value
881 .as_ref()
882 .map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
883 }
884 }
885 fn into_count(self) -> Result<u64, Error> {
886 match self {
887 Self::Count(count) => Ok(count),
888 _ => Err(Error::Corrupt),
889 }
890 }
891 fn into_value(self) -> Result<Option<Vec<u8>>, Error> {
892 match self {
893 Self::Value(value) => Ok(value.map(|(_, bytes)| bytes)),
894 _ => Err(Error::Corrupt),
895 }
896 }
897}
898
899pub(super) struct Groups {
900 selection: Selection,
901 mask: u16,
902 initial: Reducer,
904 rows: BTreeMap<Vec<u8>, (Vec<u8>, Reducer)>,
905 state_bytes: usize,
906}
907impl Groups {
908 fn into_output(self) -> Result<Vec<(Vec<u8>, Completed)>, Error> {
909 let mut state_bytes = self.state_bytes;
911 let mut rows = self
912 .rows
913 .into_iter()
914 .map(|(key, (record, reducer))| {
915 let previous = reducer.retained_bytes();
916 let result = reducer.finish()?;
917 state_bytes = state_bytes - previous + result.retained_bytes();
918 if state_bytes > MAX_STATE_BYTES {
919 return Err(Error::Limit);
920 }
921 Ok((key, (record, result)))
922 })
923 .collect::<Result<Vec<_>, Error>>()?;
924 rows.retain(|(_, (_, result))| {
925 let mut scratch = [0; 8];
926 let actual = result.result_key(&mut scratch);
927 self.selection
928 .predicates
929 .split_inclusive(|(_, _, or_next)| !or_next)
930 .all(|clause| {
931 clause.iter().any(|(comparison, operand, _)| {
932 comparison.accepts(actual, operand.as_deref(), self.selection.optional)
933 })
934 })
935 });
936 if self.selection.order == GroupOrder::KeyDescending {
937 rows.reverse();
940 } else if self.selection.order != GroupOrder::Key {
941 rows.sort_unstable_by(|(ka, (_, a)), (kb, (_, b))| {
942 let (mut sa, mut sb) = ([0; 8], [0; 8]);
943 let order = a.result_key(&mut sa).cmp(&b.result_key(&mut sb));
944 let order = if self.selection.order == GroupOrder::AggregateDescending {
945 order.reverse()
946 } else {
947 order
948 };
949 order.then_with(|| ka.cmp(kb))
950 });
951 }
952 Ok(rows.into_iter().map(|(_, row)| row).collect())
953 }
954
955 fn push(
956 &mut self,
957 entity: &EntitySchema,
958 values: &[IndexValue<'_>],
959 bytes: &[u8],
960 spans: &[(u16, u16)],
961 ) -> Result<(), Error> {
962 let key = comparison_key(entity, self.mask, values)?;
963 let size = projection_size(spans, self.mask);
964 if let Some((_, reducer)) = self.rows.get_mut(&key) {
965 let previous = reducer.retained_bytes();
966 reducer.push(
967 entity,
968 values,
969 bytes,
970 spans,
971 MAX_STATE_BYTES - self.state_bytes + previous,
972 )?;
973 self.state_bytes = self.state_bytes - previous + reducer.retained_bytes();
974 return Ok(());
975 }
976 let base = key.capacity() + size;
977 let available = MAX_STATE_BYTES - self.state_bytes;
978 if self.rows.len() == MAX_GROUPS || base + self.initial.retained_bytes() > available {
979 return Err(Error::Limit);
980 }
981 let mut reducer = self.initial.clone();
982 reducer.push(entity, values, bytes, spans, available - base)?;
983 let output = copy_projection(bytes, spans, self.mask, size);
984 let retained = key.capacity() + output.capacity() + reducer.retained_bytes();
987 if retained > available {
988 return Err(Error::Limit);
989 }
990 self.state_bytes += retained;
991 self.rows.insert(key, (output, reducer));
992 Ok(())
993 }
994}