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