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::{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            self.request.groups.admit_start_page()?;
54            let page_size = self.request.rows;
55            let query = self.group_page(page_size, after);
56            let plan = query.aggregate_plan(Some(K::definition()), true)?;
57            let job = query.retained_groups(plan, Reducer::Keys(0), None, None)?;
58            query.resume_groups(jobs, handle, sequence, now, job, |bytes, result| {
59                if !matches!(result, Completed::Key) {
60                    return Err(Error::Corrupt);
61                }
62                decode_record(bytes)
63            })
64        })
65    }
66
67    /// Retain an exact count of projected K tuples, including an absent tuple.
68    /// Checkpoints encode the full projected tuple, including fixed fields,
69    /// so saved keys can be validated on resume.
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        observe!(start, {
83            self.start_count_job(jobs, now, expires, CountInput::Distinct(K::definition()))
84        })
85    }
86
87    /// Advance DISTINCT count under scalar jobs' work/retry/revision/expiry rules.
88    /// Duplicates across steps count once; empty input returns zero, all-absent
89    /// tuples count once. Finish all input before returning a count. `limit`
90    /// never truncates input or relaxes key-set bounds.
91    /// # Errors
92    /// Refuses mismatched queries/projections, malformed saved keys, cardinality,
93    /// output or whole-frame bounds without changing the previous checkpoint.
94    /// # Panics
95    /// Supplier mutation failures trap the enclosing message.
96    pub fn resume_count_distinct<K: Value>(
97        self,
98        jobs: &mut AggregateJobs<M>,
99        handle: &JobHandle,
100        sequence: u64,
101        now: Timestamp,
102    ) -> Result<JobStep<u64>, Error> {
103        observe!(resume, {
104            self.resume_count_job(
105                jobs,
106                handle,
107                sequence,
108                now,
109                CountInput::Distinct(K::definition()),
110            )
111        })
112    }
113
114    /// Retain distinct R tuples separately in each K group, including absent tuples.
115    /// Projections may overlap. Checkpoints store full operand keys for validation on resume.
116    /// Keep at most 32 groups and 32 distinct keys per group inside one 16 KiB
117    /// whole-job frame. Key/operand projections, group selection and limit bind
118    /// the job. Work/output-byte limits may vary; no automatic spill.
119    /// # Errors
120    /// Refuses unsupported projections, expiry or occupied job capacity.
121    /// # Panics
122    /// Supplier mutation failures trap the enclosing message.
123    pub fn start_group_count_distinct<K: Value, R: Value>(
124        self,
125        jobs: &mut AggregateJobs<M>,
126        now: Timestamp,
127        expires: Timestamp,
128    ) -> Result<JobHandle, Error> {
129        observe!(start, {
130            self.request.groups.admit_start_page()?;
131            let (plan, reducer) = self.group_distinct_plan::<K, R>()?;
132
133            self.start_groups(jobs, now, expires, plan, reducer, None)
134        })
135    }
136
137    /// Advance grouped DISTINCT counts with grouped jobs' revision/retry/expiry rules.
138    /// Finish all input before filtering, ordering or limiting groups. Empty input
139    /// returns an empty vector; an all-absent tuple contributes one to its group.
140    /// Returns a GroupPage; use `group_page` to page completed selected groups.
141    /// # Errors
142    /// Refuses mismatched bindings, malformed saved sets, group/key cardinality,
143    /// output or frame bounds. Refusal preserves the previous checkpoint; output
144    /// filters and limits cannot conceal oversized state.
145    /// # Panics
146    /// Supplier mutation failures trap the enclosing message.
147    pub fn resume_group_count_distinct<K: Value, R: Value>(
148        self,
149        jobs: &mut AggregateJobs<M>,
150        handle: &JobHandle,
151        sequence: u64,
152        now: Timestamp,
153    ) -> Result<JobStep<GroupPage<GroupCount<K>>>, Error> {
154        observe!(resume, {
155            let (plan, reducer) = self.group_distinct_plan::<K, R>()?;
156            let job = self.retained_groups(plan, reducer, None, None)?;
157
158            self.resume_groups(jobs, handle, sequence, now, job, decode_group_count)
159        })
160    }
161}