Skip to main content

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