ic_db/store/query/aggregate/jobs/distinct.rs
1//! Retained tuple DISTINCT counts using the existing exact key-set reducer.
2
3use super::{
4 super::{Completed, GroupCount, Query, Reducer, decode_group_count, decode_record},
5 AggregateJobs, CountInput, GroupCursor, GroupPage, JobHandle, JobStep,
6};
7use crate::{Entity, Error, Timestamp, Value};
8use ic_storage::Memory;
9
10impl<'a, E: Entity, M: Memory> Query<'a, E, M> {
11 /// Start exact enumeration of distinct projected records.
12 /// Defaults to ascending. Use `order_groups` for descending keys or first occurrence
13 /// in input traversal order. First occurrence defaults to ascending primary key.
14 /// Use `order_by` for an order supplied by primary or index traversal and
15 /// `descending` to reverse the traversal, including its primary-key tie-breaker.
16 /// The job retains up to 255 tuples in its 16 KiB frame and invalidates on a source
17 /// change before completion. Absent tuple components participate in equality.
18 /// # Errors
19 /// Refuses incompatible projections, group modifiers, unsupported input orders, expiry or capacity.
20 /// # Panics
21 /// Supplier mutation failures trap the enclosing message.
22 pub fn start_distinct<K: Value>(
23 self,
24 jobs: &mut AggregateJobs<M>,
25 now: Timestamp,
26 expires: Timestamp,
27 ) -> Result<JobHandle, Error> {
28 observe!(start, {
29 let plan = self.aggregate_plan(Some(K::definition()), true)?;
30 self.start_group_value(jobs, now, expires, (plan, Reducer::Keys(0)))
31 })
32 }
33
34 /// Advance a DISTINCT job or page its completed result. Pass `None` until a
35 /// completed page supplies a cursor. `limit` selects the page size (1–32);
36 /// it and the per-call work and byte allowances may change between calls.
37 /// # Errors
38 /// Refuses incomplete-state cursors, changed queries and exhausted tuple, frame
39 /// or output bounds. Tuple or frame exhaustion returns `Error::Limit` and preserves
40 /// the last successful checkpoint. Reducing the output page size cannot resolve
41 /// retained-state exhaustion. Cancel the job to release its slot.
42 /// # Panics
43 /// Supplier mutation failures trap the enclosing message.
44 pub fn resume_distinct<K: Value>(
45 self,
46 jobs: &mut AggregateJobs<M>,
47 handle: &JobHandle,
48 sequence: u64,
49 now: Timestamp,
50 after: Option<&'a GroupCursor>,
51 ) -> Result<JobStep<GroupPage<K>>, Error> {
52 observe!(resume, {
53 if self.request.groups.page.is_some() {
54 return Err(Error::InvalidQuery);
55 }
56 let page_size = self.request.rows;
57 let query = self.group_page(page_size, after);
58 let plan = query.aggregate_plan(Some(K::definition()), true)?;
59 let job = query.retained_groups(plan, Reducer::Keys(0), None, None)?;
60 query.resume_groups(jobs, handle, sequence, now, job, |bytes, result| {
61 if !matches!(result, Completed::Key) {
62 return Err(Error::Corrupt);
63 }
64 decode_record(bytes)
65 })
66 })
67 }
68
69 /// Retain an exact count of projected K tuples, including an absent tuple.
70 /// Checkpoints encode the full projected tuple, including fixed fields,
71 /// so saved keys can be validated on resume.
72 /// Retain at most 32 distinct keys inside the 16 KiB whole-job frame;
73 /// no spill. Query/projection/algorithm bind the job; work/byte limits may vary.
74 /// # Errors
75 /// Refuses unsupported projections, group modifiers, expiry and capacity.
76 /// # Panics
77 /// Supplier mutation failures trap the enclosing message.
78 pub fn start_count_distinct<K: Value>(
79 self,
80 jobs: &mut AggregateJobs<M>,
81 now: Timestamp,
82 expires: Timestamp,
83 ) -> Result<JobHandle, Error> {
84 observe!(start, {
85 self.start_count_job(jobs, now, expires, CountInput::Distinct(K::definition()))
86 })
87 }
88
89 /// Advance DISTINCT count under scalar jobs' work/retry/revision/expiry rules.
90 /// Duplicates across steps count once; empty input returns zero, all-absent
91 /// tuples count once. Finish all input before returning a count. `limit`
92 /// never truncates input or relaxes key-set bounds.
93 /// # Errors
94 /// Refuses mismatched queries/projections, malformed saved keys, cardinality,
95 /// output or whole-frame bounds without changing the previous checkpoint.
96 /// # Panics
97 /// Supplier mutation failures trap the enclosing message.
98 pub fn resume_count_distinct<K: Value>(
99 self,
100 jobs: &mut AggregateJobs<M>,
101 handle: &JobHandle,
102 sequence: u64,
103 now: Timestamp,
104 ) -> Result<JobStep<u64>, Error> {
105 observe!(resume, {
106 self.resume_count_job(
107 jobs,
108 handle,
109 sequence,
110 now,
111 CountInput::Distinct(K::definition()),
112 )
113 })
114 }
115
116 /// Retain distinct R tuples separately in each K group, including absent tuples.
117 /// Projections may overlap. Checkpoints store full operand keys for validation on resume.
118 /// Keep at most 32 groups and 32 distinct keys per group inside one 16 KiB
119 /// whole-job frame. Key/operand projections, group selection and limit bind
120 /// the job. Work/output-byte limits may vary; no automatic spill.
121 /// # Errors
122 /// Refuses unsupported projections, expiry or occupied job capacity.
123 /// # Panics
124 /// Supplier mutation failures trap the enclosing message.
125 pub fn start_group_count_distinct<K: Value, R: Value>(
126 self,
127 jobs: &mut AggregateJobs<M>,
128 now: Timestamp,
129 expires: Timestamp,
130 ) -> Result<JobHandle, Error> {
131 observe!(start, {
132 if self.request.groups.page.is_some() {
133 return Err(Error::InvalidQuery);
134 }
135 let (plan, reducer) = self.group_distinct_plan::<K, R>()?;
136
137 self.start_groups(jobs, now, expires, plan, reducer, None)
138 })
139 }
140
141 /// Advance grouped DISTINCT counts with grouped jobs' revision/retry/expiry rules.
142 /// Finish all input before filtering, ordering or limiting groups. Empty input
143 /// returns an empty vector; an all-absent tuple contributes one to its group.
144 /// Returns a GroupPage; use `group_page` to page completed selected groups.
145 /// # Errors
146 /// Refuses mismatched bindings, malformed saved sets, group/key cardinality,
147 /// output or frame bounds. Refusal preserves the previous checkpoint; output
148 /// filters and limits cannot conceal oversized state.
149 /// # Panics
150 /// Supplier mutation failures trap the enclosing message.
151 pub fn resume_group_count_distinct<K: Value, R: Value>(
152 self,
153 jobs: &mut AggregateJobs<M>,
154 handle: &JobHandle,
155 sequence: u64,
156 now: Timestamp,
157 ) -> Result<JobStep<GroupPage<GroupCount<K>>>, Error> {
158 observe!(resume, {
159 let (plan, reducer) = self.group_distinct_plan::<K, R>()?;
160 let job = self.retained_groups(plan, reducer, None, None)?;
161
162 self.resume_groups(jobs, handle, sequence, now, job, decode_group_count)
163 })
164 }
165}