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 /// Uses synchronous `count_distinct` admission and equality without an index.
71 /// Retain at most 32 distinct keys inside the 16 KiB whole-job frame;
72 /// no spill. Query/projection/algorithm bind the job; work/byte limits may vary.
73 /// # Errors
74 /// Refuses unsupported projections, group modifiers, expiry and capacity.
75 /// # Panics
76 /// Supplier mutation failures trap the enclosing message.
77 pub fn start_count_distinct<K: Value>(
78 self,
79 jobs: &mut AggregateJobs<M>,
80 now: Timestamp,
81 expires: Timestamp,
82 ) -> Result<JobHandle, Error> {
83 observe!(start, {
84 self.start_count_job(jobs, now, expires, CountInput::Distinct(K::definition()))
85 })
86 }
87
88 /// Advance DISTINCT count under scalar jobs' work/retry/revision/expiry rules.
89 /// Duplicates across steps count once; empty input returns zero, all-absent
90 /// tuples count once. Finish all input before returning a count. `limit`
91 /// never truncates input or relaxes key-set bounds.
92 /// # Errors
93 /// Refuses mismatched queries/projections, malformed saved keys, cardinality,
94 /// output or whole-frame bounds without changing the previous checkpoint.
95 /// # Panics
96 /// Supplier mutation failures trap the enclosing message.
97 pub fn resume_count_distinct<K: Value>(
98 self,
99 jobs: &mut AggregateJobs<M>,
100 handle: &JobHandle,
101 sequence: u64,
102 now: Timestamp,
103 ) -> Result<JobStep<u64>, Error> {
104 observe!(resume, {
105 self.resume_count_job(
106 jobs,
107 handle,
108 sequence,
109 now,
110 CountInput::Distinct(K::definition()),
111 )
112 })
113 }
114
115 /// Retain distinct R tuples separately in each K group, including absent tuples.
116 /// Projections may overlap. Uses synchronous `group_count_distinct` admission.
117 /// Keep at most 32 groups and 32 distinct keys per group inside one 16 KiB
118 /// whole-job frame. Key/operand projections, group selection and limit bind
119 /// the job. Work/output-byte limits may vary; no automatic spill.
120 /// # Errors
121 /// Refuses unsupported projections, expiry or occupied job capacity.
122 /// # Panics
123 /// Supplier mutation failures trap the enclosing message.
124 pub fn start_group_count_distinct<K: Value, R: Value>(
125 self,
126 jobs: &mut AggregateJobs<M>,
127 now: Timestamp,
128 expires: Timestamp,
129 ) -> Result<JobHandle, Error> {
130 observe!(start, {
131 if self.request.groups.page.is_some() {
132 return Err(Error::InvalidQuery);
133 }
134 let (plan, reducer) = self.group_distinct_plan::<K, R>()?;
135
136 self.start_groups(jobs, now, expires, plan, reducer, None)
137 })
138 }
139
140 /// Advance grouped DISTINCT counts with grouped jobs' revision/retry/expiry rules.
141 /// Finish all input before filtering, ordering or limiting groups. Empty input
142 /// returns an empty vector; an all-absent tuple contributes one to its group.
143 /// Returns a GroupPage; use `group_page` to page completed selected groups.
144 /// # Errors
145 /// Refuses mismatched bindings, malformed saved sets, group/key cardinality,
146 /// output or frame bounds. Refusal preserves the previous checkpoint; output
147 /// filters and limits cannot conceal oversized state.
148 /// # Panics
149 /// Supplier mutation failures trap the enclosing message.
150 pub fn resume_group_count_distinct<K: Value, R: Value>(
151 self,
152 jobs: &mut AggregateJobs<M>,
153 handle: &JobHandle,
154 sequence: u64,
155 now: Timestamp,
156 ) -> Result<JobStep<GroupPage<GroupCount<K>>>, Error> {
157 observe!(resume, {
158 let (plan, reducer) = self.group_distinct_plan::<K, R>()?;
159 let job = self.retained_groups(plan, reducer, None, None)?;
160
161 self.resume_groups(jobs, handle, sequence, now, job, decode_group_count)
162 })
163 }
164}