Skip to main content

ic_db/store/query/aggregate/jobs/
grouped.rs

1//! Retained grouped aggregates with bounded complete finalization.
2
3use super::{
4    super::super::Plan,
5    super::{
6        Accumulator, Completed, GroupCount, GroupOrder, GroupValue, Groups, Query, Reducer,
7        decode_group_count, decode_group_value, numeric::Operation,
8    },
9    AggregateJobs, GroupPage, JobHandle, JobStep, field_binding, pages, prepare, start,
10};
11use crate::{Entity, Error, Timestamp, Value};
12use ic_storage::Memory;
13use sha2::{Digest, Sha256};
14
15pub(super) struct GroupJob<'a> {
16    plan: Plan<'a>,
17    groups: Groups,
18    binding: [u8; 32],
19}
20
21impl<E: Entity, M: Memory> Query<'_, E, M> {
22    /// Retain grouped row counts without scanning input. K is the same exact key
23    /// record as synchronous `group_count`. Group predicates, order and output
24    /// row limit bind the job; work/output-byte allowances may change on resume.
25    /// Keep at most 32 groups and the complete job frame within 16 KiB,
26    /// including progress and encoded key records. No spill or partial output.
27    /// # Errors
28    /// Refuses group/query admission, invalid expiry or occupied job capacity.
29    /// # Panics
30    /// Supplier mutation failures trap the enclosing message.
31    pub fn start_group_count<K: Value>(
32        self,
33        jobs: &mut AggregateJobs<M>,
34        now: Timestamp,
35        expires: Timestamp,
36    ) -> Result<JobHandle, Error> {
37        self.start_group_count_job::<K>(jobs, now, expires, None)
38    }
39
40    /// Retain present-field counts per exact key record. Any top-level stored field
41    /// is accepted; empty values count. Groups containing only absent values remain
42    /// with count zero. Uses `start_group_count`'s bounds and selection binding.
43    /// # Errors
44    /// Refuses unknown fields and ordinary grouped-count admission failures.
45    /// # Panics
46    /// Supplier mutation failures trap the enclosing message.
47    pub fn start_group_count_field<K: Value>(
48        self,
49        field: &str,
50        jobs: &mut AggregateJobs<M>,
51        now: Timestamp,
52        expires: Timestamp,
53    ) -> Result<JobHandle, Error> {
54        self.start_group_count_job::<K>(jobs, now, expires, Some(field))
55    }
56
57    fn start_group_count_job<K: Value>(
58        self,
59        jobs: &mut AggregateJobs<M>,
60        now: Timestamp,
61        expires: Timestamp,
62        field: Option<&str>,
63    ) -> Result<JobHandle, Error> {
64        if self.request.groups.page.is_some() {
65            return Err(Error::InvalidQuery);
66        }
67        let plan = self.aggregate_plan(Some(K::definition()), true)?;
68
69        self.start_groups(jobs, now, expires, plan, self.count_reducer(field)?, field)
70    }
71
72    /// Advance grouped counts with scalar jobs' revision/retry/work/expiry contract.
73    /// Empty input completes as an empty vector; absent keys form their own group.
74    /// Finalize all input before filtering, ordering and selecting completed groups.
75    /// Use `group_page` to page completed output; otherwise all selected groups must fit.
76    /// # Errors
77    /// Refuses mismatched queries/keys/selection, cardinality or the 16 KiB job
78    /// frame. Group/output bounds apply before saving; a refusal preserves prior
79    /// progress. `limit` never limits input or relaxes retained-state bounds.
80    /// # Panics
81    /// Supplier mutation failures trap the enclosing message.
82    pub fn resume_group_count<K: Value>(
83        self,
84        jobs: &mut AggregateJobs<M>,
85        handle: &JobHandle,
86        sequence: u64,
87        now: Timestamp,
88    ) -> Result<JobStep<GroupPage<GroupCount<K>>>, Error> {
89        self.resume_group_count_job::<K>(jobs, handle, sequence, now, None)
90    }
91
92    /// Advance grouped present-field counts with `resume_group_count`'s lifecycle.
93    /// Finish all input before selection; zero-count groups are retained. The field
94    /// binds the job, including required fields whose count equals the row count.
95    /// # Errors
96    /// Refuses changed fields, row-count jobs and ordinary grouped-count failures.
97    /// # Panics
98    /// Supplier mutation failures trap the enclosing message.
99    pub fn resume_group_count_field<K: Value>(
100        self,
101        field: &str,
102        jobs: &mut AggregateJobs<M>,
103        handle: &JobHandle,
104        sequence: u64,
105        now: Timestamp,
106    ) -> Result<JobStep<GroupPage<GroupCount<K>>>, Error> {
107        self.resume_group_count_job::<K>(jobs, handle, sequence, now, Some(field))
108    }
109
110    fn resume_group_count_job<K: Value>(
111        self,
112        jobs: &mut AggregateJobs<M>,
113        handle: &JobHandle,
114        sequence: u64,
115        now: Timestamp,
116        field: Option<&str>,
117    ) -> Result<JobStep<GroupPage<GroupCount<K>>>, Error> {
118        let plan = self.aggregate_plan(Some(K::definition()), true)?;
119        let job = self.retained_groups(plan, self.count_reducer(field)?, field)?;
120
121        self.resume_groups(jobs, handle, sequence, now, job, decode_group_count)
122    }
123
124    /// Retain grouped integer, Decimal or Float64 sums with `group_sum`'s exact result types.
125    /// Uses grouped counts' 32-group/16 KiB frame, revision and expiry bounds.
126    /// Key/result types, operation and completed-group selection bind the job.
127    /// # Errors
128    /// Refuses invalid query/result shapes, expiry or exhausted job capacity.
129    /// # Panics
130    /// Supplier mutation failures trap the enclosing message.
131    pub fn start_group_sum<K: Value, R: Value>(
132        self,
133        jobs: &mut AggregateJobs<M>,
134        now: Timestamp,
135        expires: Timestamp,
136    ) -> Result<JobHandle, Error> {
137        self.start_group_numeric::<K, R>(jobs, now, expires, Operation::Sum)
138    }
139
140    /// Advance grouped sums; all-absent groups have `None`, present zero is a value.
141    /// Finish every group before filtering/order/limit. Overflow in an excluded
142    /// group still refuses. Output and frame refusals preserve the saved checkpoint.
143    /// Returns a GroupPage; use `group_page` to page the completed selected groups.
144    /// # Errors
145    /// Grouped-count resume failures and `group_sum` arithmetic/result errors apply.
146    /// # Panics
147    /// Supplier mutation failures trap the enclosing message.
148    pub fn resume_group_sum<K: Value, R: Value>(
149        self,
150        jobs: &mut AggregateJobs<M>,
151        handle: &JobHandle,
152        sequence: u64,
153        now: Timestamp,
154    ) -> Result<JobStep<GroupPage<GroupValue<K, R>>>, Error> {
155        self.resume_group_numeric::<K, R>(jobs, handle, sequence, now, Operation::Sum)
156    }
157
158    /// Retain grouped averages, saving exact totals and each group's present count.
159    /// Round once at completion to R's Decimal scale, nearest with ties to even.
160    /// Bounds and query binding match `start_group_sum`; no precision fallback.
161    /// # Errors
162    /// Refuses invalid average shapes, expiry or exhausted job capacity.
163    /// # Panics
164    /// Supplier mutation failures trap the enclosing message.
165    pub fn start_group_avg<K: Value, R: Value>(
166        self,
167        jobs: &mut AggregateJobs<M>,
168        now: Timestamp,
169        expires: Timestamp,
170    ) -> Result<JobHandle, Error> {
171        self.start_group_numeric::<K, R>(jobs, now, expires, Operation::Average)
172    }
173
174    /// Advance grouped averages with `resume_group_sum`'s complete-input contract.
175    /// Selection compares completed rounded values. Absent operands do not enter
176    /// the denominator; all-absent groups remain `None`. Never average chunk means.
177    /// # Errors
178    /// Grouped-count resume failures and `group_avg` arithmetic/result errors apply.
179    /// # Panics
180    /// Supplier mutation failures trap the enclosing message.
181    pub fn resume_group_avg<K: Value, R: Value>(
182        self,
183        jobs: &mut AggregateJobs<M>,
184        handle: &JobHandle,
185        sequence: u64,
186        now: Timestamp,
187    ) -> Result<JobStep<GroupPage<GroupValue<K, R>>>, Error> {
188        self.resume_group_numeric::<K, R>(jobs, handle, sequence, now, Operation::Average)
189    }
190
191    fn start_group_numeric<K: Value, R: Value>(
192        self,
193        jobs: &mut AggregateJobs<M>,
194        now: Timestamp,
195        expires: Timestamp,
196        operation: Operation,
197    ) -> Result<JobHandle, Error> {
198        let admitted = self.numeric_plan::<R>(Some(K::definition()), operation)?;
199
200        self.start_group_value(jobs, now, expires, admitted)
201    }
202
203    pub(super) fn start_group_value(
204        self,
205        jobs: &mut AggregateJobs<M>,
206        now: Timestamp,
207        expires: Timestamp,
208        admitted: (Plan<'_>, Reducer),
209    ) -> Result<JobHandle, Error> {
210        if self.request.groups.page.is_some() {
211            return Err(Error::InvalidQuery);
212        }
213        let (plan, reducer) = admitted;
214
215        self.start_groups(jobs, now, expires, plan, reducer, None)
216    }
217
218    pub(super) fn start_groups(
219        &self,
220        jobs: &mut AggregateJobs<M>,
221        now: Timestamp,
222        expires: Timestamp,
223        plan: Plan<'_>,
224        reducer: Reducer,
225        field: Option<&str>,
226    ) -> Result<JobHandle, Error> {
227        let mut job = self.retained_groups(plan, reducer, field)?;
228
229        start(
230            jobs,
231            job.binding,
232            self.db.read()?.revision_by_id(E::SCHEMA.id)?,
233            now,
234            expires,
235            &Accumulator::Groups(&mut job.groups),
236        )
237    }
238
239    fn resume_group_numeric<K: Value, R: Value>(
240        self,
241        jobs: &mut AggregateJobs<M>,
242        handle: &JobHandle,
243        sequence: u64,
244        now: Timestamp,
245        operation: Operation,
246    ) -> Result<JobStep<GroupPage<GroupValue<K, R>>>, Error> {
247        let admitted = self.numeric_plan::<R>(Some(K::definition()), operation)?;
248
249        self.resume_group_value(jobs, handle, sequence, now, admitted)
250    }
251
252    pub(super) fn resume_group_value<K: Value, R: Value>(
253        self,
254        jobs: &mut AggregateJobs<M>,
255        handle: &JobHandle,
256        sequence: u64,
257        now: Timestamp,
258        admitted: (Plan<'_>, Reducer),
259    ) -> Result<JobStep<GroupPage<GroupValue<K, R>>>, Error> {
260        let (plan, reducer) = admitted;
261        let job = self.retained_groups(plan, reducer, None)?;
262
263        self.resume_groups(jobs, handle, sequence, now, job, decode_group_value)
264    }
265
266    pub(super) fn resume_groups<T>(
267        self,
268        jobs: &mut AggregateJobs<M>,
269        handle: &JobHandle,
270        sequence: u64,
271        now: Timestamp,
272        job: GroupJob<'_>,
273        decode: fn(&[u8], Completed) -> Result<T, Error>,
274    ) -> Result<JobStep<GroupPage<T>>, Error> {
275        let GroupJob {
276            plan,
277            mut groups,
278            binding,
279        } = job;
280        let mut record = jobs.load(handle)?;
281        let page = self.request.groups.page;
282        pages::admit(page, handle, &record)?;
283        let (rows, bytes) = (self.request.rows, self.request.bytes);
284        let changed = prepare(
285            &*self.db.read()?,
286            E::SCHEMA,
287            self.request,
288            &plan,
289            Accumulator::Groups(&mut groups),
290            &mut record,
291            binding,
292            sequence,
293            now,
294        )?;
295
296        record.finish_and_save(jobs, handle, changed, bytes, || {
297            pages::group_page(groups, rows, bytes, page, handle, decode)
298        })
299    }
300
301    pub(super) fn retained_groups<'p>(
302        &self,
303        plan: Plan<'p>,
304        reducer: Reducer,
305        field: Option<&str>,
306    ) -> Result<GroupJob<'p>, Error> {
307        let groups = self.admit_groups(&plan, reducer)?;
308        let binding = field_binding(group_binding(&plan, &groups, self.request.rows)?, field);
309
310        Ok(GroupJob {
311            plan,
312            groups,
313            binding,
314        })
315    }
316}
317
318fn group_binding(plan: &Plan<'_>, groups: &Groups, rows: usize) -> Result<[u8; 32], Error> {
319    let mut hash = Sha256::new();
320    match &groups.initial {
321        Reducer::Keys(_) => {
322            hash.update(b"ic-db:distinct-keys-job:v1\0");
323            hash.update(plan.binding);
324            if groups.selection.order == GroupOrder::KeyDescending {
325                hash.update(b"key-descending\0");
326            } else if groups.selection.order == GroupOrder::FirstOccurrence {
327                hash.update(b"first-occurrence:v1\0");
328            }
329
330            return Ok(hash.finalize().into());
331        }
332        Reducer::Numeric(_) => {
333            hash.update(b"ic-db:group-numeric-job:v1\0");
334            hash.update(super::binding(plan, &groups.initial)?);
335        }
336        Reducer::Extremum { .. } => {
337            hash.update(b"ic-db:group-extremum-job:v1\0");
338            hash.update(super::binding(plan, &groups.initial)?);
339        }
340        Reducer::Distinct { mask, .. } => {
341            hash.update(b"ic-db:group-distinct-count-job:v1\0");
342            hash.update(mask.to_le_bytes());
343        }
344        Reducer::Count { .. } => hash.update(b"ic-db:group-count-job:v1\0"),
345    }
346    hash.update(plan.binding);
347    hash.update([
348        rows as u8,
349        match groups.selection.order {
350            GroupOrder::Key => 0,
351            GroupOrder::AggregateAscending => 1,
352            GroupOrder::AggregateDescending => 2,
353            GroupOrder::KeyDescending => 3,
354            GroupOrder::FirstOccurrence => return Err(Error::InvalidQuery),
355        },
356    ]);
357    hash.update([groups.selection.predicates.len() as u8]);
358    for (comparison, operand, _) in &groups.selection.predicates {
359        hash.update([*comparison as u8]);
360        // Frame admitted operands so binding never relies on implicit widths.
361        let bytes = operand.as_deref().unwrap_or_default();
362        hash.update((bytes.len() as u32).to_le_bytes());
363        hash.update(bytes);
364    }
365    // Preserve conjunction-only bindings; add identity only for actual OR clauses.
366    let clauses = groups
367        .selection
368        .predicates
369        .iter()
370        .enumerate()
371        .fold(0_u8, |mask, (i, (_, _, or_next))| {
372            mask | (u8::from(*or_next) << i)
373        });
374    if clauses != 0 {
375        hash.update(b"group-or-clauses\0");
376        hash.update([clauses]);
377    }
378
379    Ok(hash.finalize().into())
380}