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