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