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