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