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::{Accumulator, GroupCount, Query, decode_group_count},
5    AggregateJobs, GroupPage, JobHandle, JobStep, prepare, start,
6};
7use crate::{Entity, Error, Timestamp, Value};
8use ic_storage::Memory;
9use sha2::{Digest, Sha256};
10
11impl<E: Entity, M: Memory> Query<'_, E, M> {
12    /// Retain an exact count of projected K tuples, including an absent tuple.
13    /// Uses synchronous `count_distinct` admission and equality without an index.
14    /// Retain at most 32 distinct keys inside the 16 KiB whole-job frame;
15    /// no spill. Query/projection/algorithm bind the job; work/byte limits may vary.
16    /// # Errors
17    /// Refuses unsupported projections, group modifiers, expiry and capacity.
18    /// # Panics
19    /// Supplier mutation failures trap the enclosing message.
20    pub fn start_count_distinct<K: Value>(
21        self,
22        jobs: &mut AggregateJobs<M>,
23        now: Timestamp,
24        expires: Timestamp,
25    ) -> Result<JobHandle, Error> {
26        let (plan, mut reducer) = self.distinct_plan::<K>()?;
27        if self.request.bytes < 8 {
28            return Err(Error::RowTooLarge);
29        }
30
31        start(
32            jobs,
33            binding(plan.binding),
34            self.db.read()?.revision_by_id(E::SCHEMA.id)?,
35            now,
36            expires,
37            &Accumulator::Scalar(&mut reducer),
38        )
39    }
40
41    /// Advance DISTINCT count under scalar jobs' work/retry/revision/expiry rules.
42    /// Duplicates across steps count once; empty input returns zero, all-absent
43    /// tuples count once. Finish all input before returning a count. `limit`
44    /// never truncates input or relaxes key-set bounds.
45    /// # Errors
46    /// Refuses mismatched queries/projections, malformed saved keys, cardinality,
47    /// output or whole-frame bounds without changing the previous checkpoint.
48    /// # Panics
49    /// Supplier mutation failures trap the enclosing message.
50    pub fn resume_count_distinct<K: Value>(
51        self,
52        jobs: &mut AggregateJobs<M>,
53        handle: &JobHandle,
54        sequence: u64,
55        now: Timestamp,
56    ) -> Result<JobStep<u64>, Error> {
57        let (plan, mut reducer) = self.distinct_plan::<K>()?;
58        let mut record = jobs.load(handle)?;
59        let bytes = self.request.bytes;
60        prepare(
61            &*self.db.read()?,
62            E::SCHEMA,
63            self.request,
64            &plan,
65            Accumulator::Scalar(&mut reducer),
66            &mut record,
67            binding(plan.binding),
68            sequence,
69            now,
70        )?;
71
72        record.finish_and_save(jobs, handle, bytes, || {
73            Ok((reducer.finish()?.into_count()?, 8))
74        })
75    }
76
77    /// Retain distinct R tuples separately in each K group, including absent tuples.
78    /// Projections may overlap. Uses synchronous `group_count_distinct` admission.
79    /// Keep at most 32 groups and 32 distinct keys per group inside one 16 KiB
80    /// whole-job frame. Key/operand projections, group selection and limit bind
81    /// the job. Work/output-byte limits may vary; no automatic spill.
82    /// # Errors
83    /// Refuses unsupported projections, expiry or occupied job capacity.
84    /// # Panics
85    /// Supplier mutation failures trap the enclosing message.
86    pub fn start_group_count_distinct<K: Value, R: Value>(
87        self,
88        jobs: &mut AggregateJobs<M>,
89        now: Timestamp,
90        expires: Timestamp,
91    ) -> Result<JobHandle, Error> {
92        if self.request.groups.page.is_some() {
93            return Err(Error::InvalidQuery);
94        }
95        let (plan, reducer) = self.group_distinct_plan::<K, R>()?;
96
97        self.start_groups(jobs, now, expires, plan, reducer, None)
98    }
99
100    /// Advance grouped DISTINCT counts with grouped jobs' revision/retry/expiry rules.
101    /// Finish all input before filtering, ordering or limiting groups. Empty input
102    /// returns an empty vector; an all-absent tuple contributes one to its group.
103    /// Returns a GroupPage; use `group_page` to page completed selected groups.
104    /// # Errors
105    /// Refuses mismatched bindings, malformed saved sets, group/key cardinality,
106    /// output or frame bounds. Refusal preserves the previous checkpoint; output
107    /// filters and limits cannot conceal oversized state.
108    /// # Panics
109    /// Supplier mutation failures trap the enclosing message.
110    pub fn resume_group_count_distinct<K: Value, R: Value>(
111        self,
112        jobs: &mut AggregateJobs<M>,
113        handle: &JobHandle,
114        sequence: u64,
115        now: Timestamp,
116    ) -> Result<JobStep<GroupPage<GroupCount<K>>>, Error> {
117        let (plan, reducer) = self.group_distinct_plan::<K, R>()?;
118        let job = self.retained_groups(plan, reducer, None)?;
119
120        self.resume_groups(jobs, handle, sequence, now, job, decode_group_count)
121    }
122}
123
124fn binding(query: [u8; 32]) -> [u8; 32] {
125    let mut hash = Sha256::new();
126    hash.update(b"ic-db:distinct-count-job:v1\0");
127    hash.update(query);
128
129    hash.finalize().into()
130}