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