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