1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
//! Bounded aggregates over the shared scanner and exact reducers, without row history.
pub(super) mod jobs;
mod numeric;
use super::{
Comparison, MAX_COMPARISON_KEY, MAX_DISTINCT_VALUES, MAX_STATE_BYTES, MAX_TERMS, Plan, Query,
QueryPage, admit_ordered_fields, admit_output, admit_projection, comparison_key,
copy_projection, execute, projection_size,
};
use crate::{
Entity, EntitySchema, Error, FieldType, IndexValue, TypeSchema, Value, ValueSchema,
codec::Decoder, key,
};
use ic_storage::Memory;
use std::collections::{BTreeMap, BTreeSet};
const MAX_GROUPS: usize = 32;
/// Completed-group ordering. Aggregate ties always use ascending canonical keys.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum GroupOrder {
/// Ascending group-key tuple, in canonical field-name order (the default).
#[default]
Key,
/// Ascending aggregate value; absent values precede present values.
AggregateAscending,
/// Descending aggregate value; absent values follow present values.
AggregateDescending,
/// Descending group-key tuple, in canonical field-name order; absence sorts last.
KeyDescending,
}
#[derive(Default)]
pub(super) struct GroupRequest<'a> {
// The final bool joins this term to the next alternative in one OR clause.
predicates: Vec<(Comparison, IndexValue<'a>, bool)>,
order: Option<GroupOrder>,
page: Option<jobs::pages::PageRequest<'a>>,
}
impl GroupRequest<'_> {
pub(super) fn is_empty(&self) -> bool {
self.predicates.is_empty() && self.order.is_none() && self.page.is_none()
}
fn admit(&self, entity: &EntitySchema, reducer: &Reducer) -> Result<Selection, Error> {
if self
.page
.is_some_and(|page| !(1..=MAX_GROUPS).contains(&page.size))
{
return Err(Error::Limit);
}
let field = match reducer {
Reducer::Count { .. } | Reducer::Distinct { .. } => ValueSchema {
value: FieldType::Nat64,
optional: false,
},
Reducer::Extremum { position, .. } => {
let field = &entity.fields[*position];
ValueSchema {
value: field.value,
optional: field.optional,
}
}
Reducer::Numeric(state) => state.output(),
};
// Extrema/numeric results may be absent even with required input fields.
let absent_result = !matches!(reducer, Reducer::Count { .. } | Reducer::Distinct { .. });
let predicates = self
.predicates
.iter()
.map(|&(comparison, value, or_next)| {
if match value {
IndexValue::Text(text) => text.len() > crate::codec::MAX_ROW_BYTES,
IndexValue::Blob(bytes) => bytes.len() > crate::codec::MAX_ROW_BYTES,
_ => false,
} {
return Err(Error::Limit);
}
comparison.admit(field.value, absent_result, value)?;
let key = if value == IndexValue::Absent {
None
} else {
let mut key = Vec::new();
value.append_component(field.optional, &mut key);
if key.len() > MAX_COMPARISON_KEY {
return Err(Error::Limit);
}
Some(key)
};
Ok((comparison, key, or_next))
})
.collect::<Result<_, Error>>()?;
Ok(Selection {
predicates,
order: self.order.unwrap_or_default(),
optional: field.optional,
})
}
}
struct Selection {
predicates: Vec<(Comparison, Option<Vec<u8>>, bool)>,
order: GroupOrder,
// Physical comparison-key framing, distinct from an absent aggregate result.
optional: bool,
}
/// A completed aggregate and its execution costs. No partial result or cursor.
#[derive(Debug)]
pub struct Aggregate<T> {
/// Completed value over all matching input rows.
pub value: T,
/// Examined primary/index candidates, including residual nonmatches.
pub examined: usize,
/// Fetched and validated source rows.
pub fetched: usize,
/// Encoded result bytes, excluding transport framing.
pub output_bytes: usize,
}
/// One complete group. Absent optional key values belong to a group too.
#[derive(Debug)]
pub struct GroupCount<K> {
/// Projected grouping tuple in an ordinary named record.
pub key: K,
/// Matching rows, or present operand values for `group_count_field`.
pub count: u64,
}
/// One complete group's aggregate value, preserving all-absent groups.
#[derive(Debug)]
pub struct GroupValue<K, R> {
/// Projected grouping tuple, including optional absent keys.
pub key: K,
/// Single-field result record, or `None` when the group has no present operand.
pub value: Option<R>,
}
impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
/// Page completed retained groups, returning at most 1..=32 rows per response.
/// `limit` still caps the complete selected result and binds the job. Page size
/// and byte allowance may change. Supply None for the first page; continuation
/// is valid only for a completed job. Only grouped resume terminals accept this.
#[must_use]
pub fn group_page(mut self, size: usize, after: Option<&'a jobs::GroupCursor>) -> Self {
self.request.groups.page = Some(jobs::pages::PageRequest { size, after });
self
}
/// Add an AND predicate on the completed aggregate value, before group ordering
/// and output limits. At most eight terms. Counts require Nat64 operands;
/// extrema require the source type; sums require the declared result type.
/// Absent values support Eq/Ne only. Text and Blob extrema also accept StartsWith,
/// EndsWith and Contains.
/// Only grouped terminals accept this modifier, even for empty input.
#[must_use]
pub fn filter_groups(
mut self,
comparison: Comparison,
value: impl Into<IndexValue<'a>>,
) -> Self {
if self.request.groups.predicates.len() == MAX_TERMS {
self.request.over_limit = true;
} else {
self.request
.groups
.predicates
.push((comparison, value.into(), false));
}
self
}
/// Add an OR clause on completed aggregate values, ANDed with other group
/// filters. The clause must be nonempty; all group filters together permit
/// eight comparisons. Every operand is admitted before reading any rows.
/// Uses `filter_groups`' exact type and absence rules. All groups must finish
/// and validate before selection, ordering and output limits. Clause boundaries
/// bind retained jobs; a singleton clause is equivalent to `filter_groups`.
#[must_use]
pub fn filter_groups_any(mut self, alternatives: &[(Comparison, IndexValue<'a>)]) -> Self {
let count = alternatives.len();
if count == 0 || count > MAX_TERMS - self.request.groups.predicates.len() {
self.request.over_limit = true;
} else {
self.request.groups.predicates.extend(
alternatives
.iter()
.enumerate()
.map(|(i, &(comparison, value))| (comparison, value, i + 1 != count)),
);
}
self
}
/// Order completed groups before applying output limits. Only grouped
/// terminals accept this modifier. The last call selects the order.
#[must_use]
pub fn order_groups(mut self, order: GroupOrder) -> Self {
self.request.groups.order = Some(order);
self
}
/// Minimum present value of an exact single-field record projection.
/// Supports ordered scalars/unit enums without requiring an index. The result
/// preserves the declared type and optionality; empty/all-absent input returns
/// `None`. `limit` never truncates input. Only the winning record's bytes count
/// toward `byte_limit`; an absent result occupies zero payload bytes.
/// # Errors
/// Refuses multi-field projections, unsupported types, cursors, DISTINCT and
/// explicit ordering. Work exhaustion or a comparison key beyond 4096 bytes
/// returns `Limit`; an oversized winning result returns `RowTooLarge`.
/// Ordinary projection/query errors apply. Completion must precede `work_limit`.
/// # Panics
/// Supplier corruption traps without repair.
pub fn min<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
self.extremum(false)
}
/// Maximum present value, with the same types, bounds and empty-input behavior
/// as [`Self::min`]. Equal operands retain the first encountered value.
/// # Errors
/// The same projection, resource and query errors as [`Self::min`].
/// # Panics
/// Supplier corruption traps without repair.
pub fn max<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
self.extremum(true)
}
fn extremum<R: Value>(self, maximum: bool) -> Result<Aggregate<Option<R>>, Error> {
let (plan, reducer) = self.extremum_plan::<R>(maximum)?;
self.scalar_value(&plan, reducer)
}
fn extremum_plan<R: Value>(&self, maximum: bool) -> Result<(Plan<'a>, Reducer), Error> {
let plan = self.aggregate_plan(Some(R::definition()), false)?;
let reducer = Reducer::extremum(
E::SCHEMA,
plan.projection.ok_or(Error::InvalidQuery)?,
maximum,
)?;
Ok((plan, reducer))
}
fn scalar_value<R: Value>(
self,
plan: &Plan<'_>,
mut reducer: Reducer,
) -> Result<Aggregate<Option<R>>, Error> {
let page = execute(
&self.db.map,
E::SCHEMA,
&self.request,
plan,
Some(Accumulator::Scalar(&mut reducer)),
)?;
let mut output_bytes = 0;
let value = reducer
.finish()?
.into_value()?
.map(|bytes| {
admit_output(bytes.len(), self.request.bytes, &mut output_bytes)?;
decode_record(&bytes)
})
.transpose()?;
Ok(Aggregate {
value,
examined: page.examined,
fetched: page.fetched,
output_bytes,
})
}
/// Minimum present operand per group. `K` is an exact grouping record; `R`
/// is an exact single-field operand record. They may overlap. All-absent
/// groups retain `None`; empty input yields no groups. No index is required.
/// Groups default to ascending canonical field-name tuple order;
/// `filter_groups` and `order_groups` select completed results. `limit` selects
/// completed groups, never input rows. Output bytes are the key record plus
/// the present winning record; transport option framing is excluded.
/// At most 32 groups and 128 KiB of retained keys, records and reducer payloads
/// are admitted. Every comparison key is bounded to 4096 bytes. Winner growth
/// is charged, and replacement releases the previous winner's charge.
/// # Errors
/// The projection, work and shape refusals of [`Self::min`] apply. Group or
/// retained-state exhaustion returns `Limit`. An oversized output group
/// returns `RowTooLarge`; combined output exhaustion returns `Limit`.
/// # Panics
/// Supplier corruption traps without repair.
pub fn group_min<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
self.group_extrema(false)
}
/// Maximum present operand per group, with the contract of [`Self::group_min`].
/// # Errors
/// The same projection, work, state, shape and output refusals as grouped minimum.
/// # Panics
/// Supplier corruption traps without repair.
pub fn group_max<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
self.group_extrema(true)
}
fn group_extrema<K: Value, R: Value>(
self,
maximum: bool,
) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
let (plan, initial) = self.group_extremum_plan::<K, R>(maximum)?;
self.group_values(&plan, initial)
}
fn group_extremum_plan<K: Value, R: Value>(
&self,
maximum: bool,
) -> Result<(Plan<'a>, Reducer), Error> {
let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
let operand = admit_projection(E::SCHEMA, R::definition())?;
let initial = Reducer::extremum(E::SCHEMA, operand, maximum)?;
plan.selected |= operand;
Ok((plan, initial))
}
fn group_values<K: Value, R: Value>(
self,
plan: &Plan<'_>,
initial: Reducer,
) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
let (groups, page) = self.grouped(plan, initial)?;
let (value, output_bytes) = value_output(groups, self.request.rows, self.request.bytes)?;
Ok(Aggregate {
value,
examined: page.examined,
fetched: page.fetched,
output_bytes,
})
}
/// Whether at least one row matches, without materializing an entity.
/// Stops after validating the first matching row; later rows are not inspected.
/// Returns false only after observing the end of the selected input.
/// `limit` does not truncate input. The boolean result occupies one byte.
/// # Errors
/// Refuses cursors, DISTINCT, explicit ordering and group modifiers, as for
/// `count`. Exhausting `work_limit` without a match returns `Limit`, never
/// false; an exact-boundary no-match scan can conservatively refuse.
/// Ordinary admission and examined-row integrity errors still apply.
/// # Panics
/// Supplier corruption traps without repair, as for ordinary query execution.
pub fn exists(self) -> Result<Aggregate<bool>, Error> {
let plan = self.aggregate_plan(None, false)?;
let mut found = false;
let page = execute(
&self.db.map,
E::SCHEMA,
&self.request,
&plan,
Some(Accumulator::Exists(&mut found)),
)?;
Ok(Aggregate {
value: found,
examined: page.examined,
fetched: page.fetched,
output_bytes: 1,
})
}
/// Count all matching rows in one synchronous execution. Empty input yields zero.
/// Uses maintained cardinality for unfiltered input and physical index keys for
/// covered equality prefixes or primary-key comparison ranges. Other predicates use row execution. Use
/// [`Self::count_validated`] to check each visited row and selected index owner.
/// `limit` does not limit input; the scalar output occupies eight bytes.
/// Completion must be observed before `work_limit` is reached; an exact-boundary
/// scan can conservatively refuse. Use `start_count`/`resume_count` for retained work.
/// # Errors
/// Refuses cursors, DISTINCT, explicit ordering and the ordinary query failures.
/// Work exhaustion returns `Limit`, never a partial count. Too few output bytes
/// returns `RowTooLarge`.
/// # Panics
/// Supplier corruption traps without repair, as for ordinary query execution.
pub fn count(self) -> Result<Aggregate<u64>, Error> {
if self.request.bytes < 8 {
return Err(Error::RowTooLarge);
}
let mut plan = self.aggregate_plan(None, false)?;
if self.request.predicates.is_empty() && self.request.index.is_none() {
return Ok(Aggregate {
value: self.db.cardinality::<E>()?,
examined: 0,
fetched: 0,
output_bytes: 8,
});
}
if super::range::covers_primary(&plan)
|| super::order::count_prefix(E::SCHEMA, &self.request, &mut plan)?
{
return self.count_keys(&plan);
}
let reducer = self.count_reducer(None)?;
self.scalar_count_value(&plan, reducer)
}
/// Count by validating each visited row, including its selected index entry.
/// # Errors
/// Returns the same admission and resource errors as [`Self::count`], and
/// reports corruption encountered during traversal.
pub fn count_validated(self) -> Result<Aggregate<u64>, Error> {
self.scalar_count(None)
}
/// Count physical entries in the range selected by `using_index` and its
/// leading operands. This reads neither index values nor owner rows. A
/// dangling index entry counts as one. Use [`Self::count_validated`] to validate rows.
/// Like other scalar counts, the row limit does not truncate the input.
/// # Errors
/// Requires an explicit index. Row predicates, ordering, cursors, grouping
/// and DISTINCT refuse. Reaching the work limit before observing completion
/// returns `Limit`; fewer than eight output bytes returns `RowTooLarge`.
/// # Panics
/// Malformed supplier storage can trap during traversal.
pub fn count_index_entries(self) -> Result<Aggregate<u64>, Error> {
if self.request.index.is_none() || !self.request.predicates.is_empty() {
return Err(Error::InvalidQuery);
}
if self.request.bytes < 8 {
return Err(Error::RowTooLarge);
}
let plan = self.aggregate_plan(None, false)?;
self.count_keys(&plan)
}
fn count_keys(&self, plan: &Plan<'_>) -> Result<Aggregate<u64>, Error> {
let bounds = super::range::bounds(E::SCHEMA, &self.request, plan)?;
let examined = bounds.map_or(0, |range| {
self.db.map.range(range).take(self.request.work).count()
});
if examined == self.request.work {
return Err(Error::Limit);
}
Ok(Aggregate {
value: examined as u64,
examined,
fetched: 0,
output_bytes: 8,
})
}
/// Count present values of a top-level field, including non-scalar fields.
/// Empty input and all-absent input yield zero; present empty values count.
/// Limits, refusals and corruption traps are the same as [`Self::count`].
/// # Errors
/// Unknown fields refuse even for empty input. Ordinary count errors apply.
/// # Panics
/// Supplier corruption traps without repair.
pub fn count_field(self, field: &str) -> Result<Aggregate<u64>, Error> {
self.scalar_count(Some(field))
}
/// Count distinct projected tuples, including absent values, without an index.
/// Retain at most 32 distinct comparison keys, each at most 4096 bytes, within
/// the shared 128-KiB state bound. No projected records are retained. `limit`
/// never truncates this count. The scalar result occupies eight bytes.
/// # Errors
/// Ordinary count/projection errors and distinct-state exhaustion refuse.
/// # Panics
/// Supplier corruption traps without repair.
pub fn count_distinct<K: Value>(self) -> Result<Aggregate<u64>, Error> {
if self.request.bytes < 8 {
return Err(Error::RowTooLarge);
}
let (plan, reducer) = self.distinct_plan::<K>()?;
self.scalar_count_value(&plan, reducer)
}
fn distinct_plan<K: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
let plan = self.aggregate_plan(Some(K::definition()), false)?;
let reducer = Reducer::distinct(plan.projection.ok_or(Error::InvalidQuery)?);
Ok((plan, reducer))
}
fn scalar_count(self, field: Option<&str>) -> Result<Aggregate<u64>, Error> {
if self.request.bytes < 8 {
return Err(Error::RowTooLarge);
}
let plan = self.aggregate_plan(None, false)?;
let reducer = self.count_reducer(field)?;
self.scalar_count_value(&plan, reducer)
}
fn scalar_count_value(
self,
plan: &Plan<'_>,
mut reducer: Reducer,
) -> Result<Aggregate<u64>, Error> {
let page = execute(
&self.db.map,
E::SCHEMA,
&self.request,
plan,
Some(Accumulator::Scalar(&mut reducer)),
)?;
Ok(Aggregate {
value: reducer.finish()?.into_count()?,
examined: page.examined,
fetched: page.fetched,
output_bytes: 8,
})
}
/// Count matching rows grouped by an exact named-record projection.
/// Keys support ordered scalars/unit enums, including optional absence; no index
/// is required. Results default to ascending tuple order in canonical field-name order.
/// `filter_groups` and `order_groups` select completed results before output limits.
/// `limit` selects the first completed groups (1..=32), never input rows.
/// `byte_limit` bounds key-record bytes plus eight count bytes per group.
/// Empty input yields no groups. At most 32 groups and 128 KiB of key/output
/// state may be retained, independently of the requested output limit;
/// each comparison key is capped at 4096 bytes, independently of index-key limits.
/// # Errors
/// Refuses unsupported key types, cursors, DISTINCT and explicit ordering.
/// Work, group or retained-state exhaustion returns `Limit`, never partial groups.
/// Completion must be observed before `work_limit`; a boundary scan can refuse.
/// Ordinary projection/query integrity and byte-limit errors also apply.
/// # Panics
/// Supplier corruption traps without repair, as for ordinary query execution.
pub fn group_count<K: Value>(self) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
self.group_counts(None)
}
/// Count present operand values within each projected group. Groups whose
/// operands are all absent remain in the output with count zero. The operand
/// may be any top-level stored field and need not belong to the group key.
/// Bounds and ordering are the same as [`Self::group_count`].
/// # Errors
/// Unknown operands and ordinary grouped-count errors refuse.
/// # Panics
/// Supplier corruption traps without repair.
pub fn group_count_field<K: Value>(
self,
field: &str,
) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
self.group_counts(Some(field))
}
/// Count distinct projected `R` tuples within each projected `K` group.
/// Absence is a tuple component, as for [`Self::count_distinct`]; an all-absent
/// group has one distinct tuple, not zero. Projections may overlap. No index
/// is required. Complete input before group filtering/order and output limits.
/// Retain at most 32 groups and 32 distinct tuples per group, with one shared
/// 128-KiB state allowance and a 4096-byte cap per comparison key.
/// # Errors
/// Refuses unsupported projections, cursors, DISTINCT and explicit input order.
/// Work, cardinality or byte exhaustion returns `Limit`, never partial counts.
/// Ordinary grouped-count output and integrity errors apply.
/// # Panics
/// Supplier corruption traps without repair.
pub fn group_count_distinct<K: Value, R: Value>(
self,
) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
let (plan, reducer) = self.group_distinct_plan::<K, R>()?;
self.group_count_values(&plan, reducer)
}
fn group_distinct_plan<K: Value, R: Value>(&self) -> Result<(Plan<'static>, Reducer), Error> {
let mut plan = self.aggregate_plan(Some(K::definition()), true)?;
let operand = admit_projection(E::SCHEMA, R::definition())?;
admit_ordered_fields(E::SCHEMA, operand)?;
plan.selected |= operand;
Ok((plan, Reducer::distinct(operand)))
}
fn group_counts<K: Value>(
self,
field: Option<&str>,
) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
let plan = self.aggregate_plan(Some(K::definition()), true)?;
let reducer = self.count_reducer(field)?;
self.group_count_values(&plan, reducer)
}
fn group_count_values<K: Value>(
self,
plan: &Plan<'_>,
reducer: Reducer,
) -> Result<Aggregate<Vec<GroupCount<K>>>, Error> {
let (groups, page) = self.grouped(plan, reducer)?;
let (value, output_bytes) = count_output(groups, self.request.rows, self.request.bytes)?;
Ok(Aggregate {
value,
examined: page.examined,
fetched: page.fetched,
output_bytes,
})
}
fn count_reducer(&self, field: Option<&str>) -> Result<Reducer, Error> {
// Presence needs only the validated tag, not an ordered scalar slot.
let presence = field
.map(|name| {
E::SCHEMA
.fields
.iter()
.enumerate()
.find(|(_, f)| f.name == name)
.map(|(i, f)| f.optional.then_some(i))
.ok_or(Error::InvalidQuery)
})
.transpose()?
.flatten();
Ok(Reducer::Count { presence, total: 0 })
}
fn grouped(
&self,
plan: &Plan<'_>,
initial: Reducer,
) -> Result<(Groups, QueryPage<Vec<u8>>), Error> {
if self.request.groups.page.is_some() {
return Err(Error::InvalidQuery);
}
let mut groups = self.admit_groups(plan, initial)?;
let page = execute(
&self.db.map,
E::SCHEMA,
&self.request,
plan,
Some(Accumulator::Groups(&mut groups)),
)?;
Ok((groups, page))
}
fn admit_groups(&self, plan: &Plan<'_>, initial: Reducer) -> Result<Groups, Error> {
Ok(Groups {
selection: self.request.groups.admit(E::SCHEMA, &initial)?,
mask: plan.projection.ok_or(Error::InvalidQuery)?,
initial,
rows: BTreeMap::new(),
state_bytes: 0,
})
}
fn aggregate_plan(
&self,
output: Option<&TypeSchema>,
group_output: bool,
) -> Result<Plan<'static>, Error> {
if self.request.cursor.is_some()
|| self.request.distinct
|| self.request.order.is_some()
|| self.request.descending
{
return Err(Error::InvalidQuery);
}
self.db.schema.admits(E::SCHEMA)?;
let mut plan = Plan::admit(
E::SCHEMA,
&self.request,
self.db.schema.fingerprint(),
self.db.incarnation,
output,
group_output,
)?;
if let Some(mask) = plan.projection {
admit_ordered_fields(E::SCHEMA, mask)?;
plan.selected |= mask;
}
Ok(plan)
}
}
fn value_output<K: Value, R: Value>(
groups: Groups,
rows: usize,
bytes: usize,
) -> Result<(Vec<GroupValue<K, R>>, usize), Error> {
let mut output_bytes = 0;
let value = groups
.into_output()?
.into_iter()
.take(rows)
.map(|(key, reducer)| {
admit_output(key.len() + reducer.encoded_len(), bytes, &mut output_bytes)?;
decode_group_value(&key, reducer)
})
.collect::<Result<_, Error>>()?;
Ok((value, output_bytes))
}
fn count_output<K: Value>(
groups: Groups,
rows: usize,
bytes: usize,
) -> Result<(Vec<GroupCount<K>>, usize), Error> {
let mut output_bytes = 0;
let value = groups
.into_output()?
.into_iter()
.take(rows)
.map(|(key, reducer)| {
admit_output(key.len() + 8, bytes, &mut output_bytes)?;
decode_group_count(&key, reducer)
})
.collect::<Result<_, Error>>()?;
Ok((value, output_bytes))
}
fn decode_group_count<K: Value>(key: &[u8], result: Completed) -> Result<GroupCount<K>, Error> {
Ok(GroupCount {
key: decode_record(key)?,
count: result.into_count()?,
})
}
fn decode_group_value<K: Value, R: Value>(
key: &[u8],
result: Completed,
) -> Result<GroupValue<K, R>, Error> {
let value = result.into_value()?;
Ok(GroupValue {
key: decode_record(key)?,
value: value.as_deref().map(decode_record).transpose()?,
})
}
fn decode_record<R: Value>(bytes: &[u8]) -> Result<R, Error> {
let mut reader = Decoder::new(bytes)?;
let value = R::decode_from(&mut reader)?;
reader.finish()?;
Ok(value)
}
// Closed choices over delivered reducers and one grouping table, not user extensions.
pub(super) enum Accumulator<'a> {
// Synchronous existence can complete on the first matching row; no job state.
Exists(&'a mut bool),
Scalar(&'a mut Reducer),
Groups(&'a mut Groups),
}
impl Accumulator<'_> {
pub(super) fn needs_spans(&self) -> bool {
!matches!(
self,
Self::Exists(_)
| Self::Scalar(
Reducer::Numeric(_)
| Reducer::Count { presence: None, .. }
| Reducer::Distinct { .. }
)
)
}
pub(super) fn push(
&mut self,
entity: &EntitySchema,
values: &[IndexValue<'_>],
bytes: &[u8],
spans: &[(u16, u16)],
) -> Result<(), Error> {
match self {
Self::Exists(found) => {
**found = true;
Ok(())
}
Self::Scalar(state) => state.push(entity, values, bytes, spans, MAX_STATE_BYTES),
Self::Groups(state) => state.push(entity, values, bytes, spans),
}
}
}
#[derive(Clone)]
pub(super) enum Reducer {
Numeric(numeric::NumericAggregate),
Distinct {
mask: u16,
seen: BTreeSet<Vec<u8>>,
},
Count {
presence: Option<usize>,
total: u64,
},
Extremum {
position: usize,
maximum: bool,
selected: Option<(Vec<u8>, Vec<u8>)>,
},
}
impl Reducer {
fn distinct(mask: u16) -> Self {
Self::Distinct {
mask,
seen: BTreeSet::new(),
}
}
fn extremum(entity: &EntitySchema, mask: u16, maximum: bool) -> Result<Self, Error> {
if mask.count_ones() != 1 {
return Err(Error::InvalidQuery);
}
let position = mask.trailing_zeros() as usize;
if !key::supports(entity.fields[position].value) {
return Err(Error::InvalidQuery);
}
Ok(Self::Extremum {
position,
maximum,
selected: None,
})
}
fn retained_bytes(&self) -> usize {
match self {
Self::Numeric(state) => state.retained_bytes(),
Self::Count { .. } => 8,
Self::Distinct { seen, .. } => 8 + seen.iter().map(Vec::capacity).sum::<usize>(),
Self::Extremum { selected, .. } => selected
.as_ref()
.map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
}
}
fn finish(self) -> Result<Completed, Error> {
match self {
Self::Count { total, .. } => Ok(Completed::Count(total)),
Self::Distinct { seen, .. } => Ok(Completed::Count(seen.len() as u64)),
Self::Extremum { selected, .. } => Ok(Completed::Value(selected)),
Self::Numeric(state) => state.finish(),
}
}
fn push(
&mut self,
entity: &EntitySchema,
values: &[IndexValue<'_>],
bytes: &[u8],
spans: &[(u16, u16)],
allowance: usize,
) -> Result<(), Error> {
match self {
Self::Numeric(state) => state.push(values)?,
Self::Distinct { mask, seen } => {
let key = comparison_key(entity, *mask, values)?;
if !seen.contains(&key) {
if seen.len() == MAX_DISTINCT_VALUES
|| 8 + seen.iter().map(Vec::capacity).sum::<usize>() + key.capacity()
> allowance
{
return Err(Error::Limit);
}
seen.insert(key);
}
}
Self::Count { presence, total } => {
*total += u64::from(presence.is_none_or(|i| bytes[usize::from(spans[i].0)] != 0));
}
Self::Extremum {
position,
maximum,
selected,
} => {
let value = values[*position];
if value == IndexValue::Absent {
return Ok(());
}
let mut key = Vec::new();
value.append_component(entity.fields[*position].optional, &mut key);
if key.len() > MAX_COMPARISON_KEY {
return Err(Error::Limit);
}
if selected
.as_ref()
.is_none_or(|(old, _)| if *maximum { key > *old } else { key < *old })
{
let (start, end) = spans[*position];
if key.capacity() + usize::from(end - start) > allowance {
return Err(Error::Limit);
}
// Copy only a winner, after admitting its replacement charge.
let output = bytes[usize::from(start)..usize::from(end)].to_vec();
if key.capacity() + output.capacity() > allowance {
return Err(Error::Limit);
}
*selected = Some((key, output));
}
}
}
Ok(())
}
}
// Completed results cannot be advanced. All numeric range checks precede selection.
enum Completed {
Count(u64),
Value(Option<(Vec<u8>, Vec<u8>)>),
}
impl Completed {
fn encoded_len(&self) -> usize {
match self {
Self::Count(_) => 8,
Self::Value(value) => value.as_ref().map_or(0, |(_, bytes)| bytes.len()),
}
}
// Counts need only eight stack bytes; extrema borrow their retained ordered key.
fn result_key<'a>(&'a self, scratch: &'a mut [u8; 8]) -> Option<&'a [u8]> {
match self {
Self::Count(total) => {
*scratch = total.to_be_bytes();
Some(scratch)
}
Self::Value(selected) => selected.as_ref().map(|(key, _)| key.as_slice()),
}
}
fn retained_bytes(&self) -> usize {
match self {
Self::Count(_) => 8,
Self::Value(value) => value
.as_ref()
.map_or(0, |(key, bytes)| key.capacity() + bytes.capacity()),
}
}
fn into_count(self) -> Result<u64, Error> {
match self {
Self::Count(count) => Ok(count),
_ => Err(Error::Corrupt),
}
}
fn into_value(self) -> Result<Option<Vec<u8>>, Error> {
match self {
Self::Value(value) => Ok(value.map(|(_, bytes)| bytes)),
_ => Err(Error::Corrupt),
}
}
}
pub(super) struct Groups {
selection: Selection,
mask: u16,
// Never advanced: each new group receives its own empty reducer state.
initial: Reducer,
rows: BTreeMap<Vec<u8>, (Vec<u8>, Reducer)>,
state_bytes: usize,
}
impl Groups {
fn into_output(self) -> Result<Vec<(Vec<u8>, Completed)>, Error> {
// Accumulation has completed. Output filtering cannot relax input/state bounds.
let mut state_bytes = self.state_bytes;
let mut rows = self
.rows
.into_iter()
.map(|(key, (record, reducer))| {
let previous = reducer.retained_bytes();
let result = reducer.finish()?;
state_bytes = state_bytes - previous + result.retained_bytes();
if state_bytes > MAX_STATE_BYTES {
return Err(Error::Limit);
}
Ok((key, (record, result)))
})
.collect::<Result<Vec<_>, Error>>()?;
rows.retain(|(_, (_, result))| {
let mut scratch = [0; 8];
let actual = result.result_key(&mut scratch);
self.selection
.predicates
.split_inclusive(|(_, _, or_next)| !or_next)
.all(|clause| {
clause.iter().any(|(comparison, operand, _)| {
comparison.accepts(actual, operand.as_deref(), self.selection.optional)
})
})
});
if self.selection.order == GroupOrder::KeyDescending {
// BTreeMap supplied ascending canonical keys; reverse the completed,
// filtered rows before any output limit or page is selected.
rows.reverse();
} else if self.selection.order != GroupOrder::Key {
rows.sort_unstable_by(|(ka, (_, a)), (kb, (_, b))| {
let (mut sa, mut sb) = ([0; 8], [0; 8]);
let order = a.result_key(&mut sa).cmp(&b.result_key(&mut sb));
let order = if self.selection.order == GroupOrder::AggregateDescending {
order.reverse()
} else {
order
};
order.then_with(|| ka.cmp(kb))
});
}
Ok(rows.into_iter().map(|(_, row)| row).collect())
}
fn push(
&mut self,
entity: &EntitySchema,
values: &[IndexValue<'_>],
bytes: &[u8],
spans: &[(u16, u16)],
) -> Result<(), Error> {
let key = comparison_key(entity, self.mask, values)?;
let size = projection_size(spans, self.mask);
if let Some((_, reducer)) = self.rows.get_mut(&key) {
let previous = reducer.retained_bytes();
reducer.push(
entity,
values,
bytes,
spans,
MAX_STATE_BYTES - self.state_bytes + previous,
)?;
self.state_bytes = self.state_bytes - previous + reducer.retained_bytes();
return Ok(());
}
let base = key.capacity() + size;
let available = MAX_STATE_BYTES - self.state_bytes;
if self.rows.len() == MAX_GROUPS || base + self.initial.retained_bytes() > available {
return Err(Error::Limit);
}
let mut reducer = self.initial.clone();
reducer.push(entity, values, bytes, spans, available - base)?;
let output = copy_projection(bytes, spans, self.mask, size);
// Map/set nodes and fixed bookkeeping are independently bounded by the
// group and per-group distinct cardinality caps.
let retained = key.capacity() + output.capacity() + reducer.retained_bytes();
if retained > available {
return Err(Error::Limit);
}
self.state_bytes += retained;
self.rows.insert(key, (output, reducer));
Ok(())
}
}