Skip to main content

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

1//! Retained aggregates: exact input revision, atomic progress, explicit retry.
2
3mod checkpoint;
4mod distinct;
5mod extrema;
6mod grouped;
7pub(super) mod pages;
8mod storage;
9
10pub use pages::{GroupCursor, GroupPage};
11pub use storage::AggregateJobs;
12
13use super::{
14    super::{Database, Plan, Query, QueryCursor, Request, execute_inner},
15    Accumulator, Reducer, decode_record,
16    numeric::Operation,
17};
18use crate::{Entity, EntitySchema, Error, Timestamp, Value};
19use ic_storage::Memory;
20use sha2::{Digest, Sha256};
21use storage::Record;
22
23const MAX_CANDIDATES: u64 = 1_000_000;
24const MAX_LIFETIME_MS: i64 = 3_600_000;
25
26/// Opaque retained-job identity. The host must check caller authorization separately.
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct JobHandle {
29    incarnation: [u8; 16],
30    slot: u8,
31    generation: u64,
32}
33impl JobHandle {
34    /// Encode an exact, bounded transport handle; no query or accumulator travels in it.
35    #[must_use]
36    pub fn to_bytes(&self) -> Vec<u8> {
37        let mut bytes = vec![1, self.slot];
38        bytes.extend(self.incarnation);
39        bytes.extend(self.generation.to_le_bytes());
40
41        bytes
42    }
43
44    /// Decode framing; the job store also validates incarnation and slot generation.
45    /// # Errors
46    /// Refuses unsupported, malformed, zero or oversized handles.
47    pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
48        if bytes.len() != 26 || bytes[0] != 1 || !(1..=storage::SLOTS).contains(&bytes[1]) {
49            return Err(Error::InvalidJob);
50        }
51        let incarnation = bytes[2..18].try_into().map_err(|_| Error::InvalidJob)?;
52        let generation = u64::from_le_bytes(bytes[18..].try_into().map_err(|_| Error::InvalidJob)?);
53        if incarnation == [0; 16] || generation == 0 {
54            return Err(Error::InvalidJob);
55        }
56
57        Ok(Self {
58            incarnation,
59            slot: bytes[1],
60            generation,
61        })
62    }
63}
64
65/// Only Complete contains a result. Running never exposes a prefix as an exact total.
66#[derive(Debug, PartialEq, Eq)]
67pub enum JobOutcome<T> {
68    /// More input remains, or exhaustion has not yet been observed.
69    Running,
70    /// Exact result for the captured source revision, retained until expiry/cancellation.
71    Complete(T),
72    /// The source entity changed before completion. Start a new job explicitly.
73    Invalidated,
74    /// The host-captured time reached the fixed expiry. Cleanup is explicit.
75    Expired,
76}
77/// Saved progress. Older sequences do not rescan; revision and expiry checks still apply.
78#[derive(Debug)]
79pub struct JobStep<T> {
80    /// Supply this sequence on the next advance. Newly created jobs start at zero.
81    pub sequence: u64,
82    /// Entity revision captured at creation, including for completed historical results.
83    pub source_revision: u64,
84    /// Cumulative examined primary/index candidates, including residual nonmatches.
85    pub examined: u64,
86    /// Cumulative source row/key bytes, excluding supplier traversal/allocator overhead.
87    pub input_bytes: u64,
88    /// Encoded returned result/page size; zero while no result is available.
89    pub output_bytes: usize,
90    /// Explicit progress, completion, invalidation or expiry.
91    pub outcome: JobOutcome<T>,
92}
93
94impl Record {
95    // Conversion and output refusal happen before saving the prepared checkpoint.
96    // A refused result must leave the previous checkpoint available for retry.
97    fn finish_and_save<T, M: Memory>(
98        &self,
99        jobs: &mut AggregateJobs<M>,
100        handle: &JobHandle,
101        limit: usize,
102        finish: impl FnOnce() -> Result<(T, usize), Error>,
103    ) -> Result<JobStep<T>, Error> {
104        let (outcome, output_bytes) = match self.phase {
105            JobOutcome::Running => (JobOutcome::Running, 0),
106            JobOutcome::Invalidated => (JobOutcome::Invalidated, 0),
107            JobOutcome::Expired => (JobOutcome::Expired, 0),
108            JobOutcome::Complete(()) => {
109                let (value, bytes) = finish()?;
110                if bytes > limit {
111                    return Err(Error::RowTooLarge);
112                }
113
114                (JobOutcome::Complete(value), bytes)
115            }
116        };
117        jobs.save(handle, self)?;
118
119        Ok(JobStep {
120            sequence: self.sequence,
121            source_revision: self.revision,
122            examined: self.examined,
123            input_bytes: self.input_bytes,
124            output_bytes,
125            outcome,
126        })
127    }
128}
129
130impl<E: Entity, M: Memory> Query<'_, E, M> {
131    /// Retain an exact count job without scanning input. Expiry must be after the
132    /// host-captured `now` and at most one hour later. No write freeze is acquired.
133    /// Reconstruct this fluent query on every advance; predicates/access path bind
134    /// the job, while the per-call work limit may change. Limit never truncates input.
135    /// # Errors
136    /// Ordinary count admission, invalid expiry, or all 16 retained slots occupied.
137    /// # Panics
138    /// Supplier mutation failures trap the enclosing message.
139    pub fn start_count(
140        self,
141        jobs: &mut AggregateJobs<M>,
142        now: Timestamp,
143        expires: Timestamp,
144    ) -> Result<JobHandle, Error> {
145        self.start_count_job(jobs, now, expires, None)
146    }
147
148    /// Retain the count of present values in a named top-level field, of any stored
149    /// type. Empty values count; absent values do not. The field binds the job,
150    /// even for a required field. Uses `start_count`'s limits and expiry contract.
151    /// # Errors
152    /// Refuses unknown fields and ordinary count-job admission failures.
153    /// # Panics
154    /// Supplier mutation failures trap the enclosing message.
155    pub fn start_count_field(
156        self,
157        field: &str,
158        jobs: &mut AggregateJobs<M>,
159        now: Timestamp,
160        expires: Timestamp,
161    ) -> Result<JobHandle, Error> {
162        self.start_count_job(jobs, now, expires, Some(field))
163    }
164
165    fn start_count_job(
166        self,
167        jobs: &mut AggregateJobs<M>,
168        now: Timestamp,
169        expires: Timestamp,
170        field: Option<&str>,
171    ) -> Result<JobHandle, Error> {
172        let plan = self.aggregate_plan(None, false)?;
173        let mut reducer = self.count_reducer(field)?;
174        if self.request.bytes < 8 {
175            return Err(Error::RowTooLarge);
176        }
177
178        start(
179            jobs,
180            field_binding(binding(&plan, &reducer)?, field),
181            self.db.read()?.revision_by_id(E::SCHEMA.id)?,
182            now,
183            expires,
184            &Accumulator::Scalar(&mut reducer),
185        )
186    }
187
188    /// Advance count within `work_limit` (1..=512) and 64 KiB of source row/key
189    /// bytes. Each job admits at most one million examined candidates. A budget
190    /// boundary returns Running; it never changes the mathematical input set.
191    /// Supply zero first, then the last returned sequence. An older sequence only
192    /// reads saved progress; a future sequence refuses. Source changes invalidate
193    /// running jobs, including on retries; completed results keep their boundary.
194    /// # Errors
195    /// Refuses a foreign query/handle, future sequence, backward host time, resource
196    /// bounds or corruption without changing progress. No automatic restart.
197    /// # Panics
198    /// Supplier mutation failures trap the enclosing message.
199    pub fn resume_count(
200        self,
201        jobs: &mut AggregateJobs<M>,
202        handle: &JobHandle,
203        sequence: u64,
204        now: Timestamp,
205    ) -> Result<JobStep<u64>, Error> {
206        self.resume_count_job(jobs, handle, sequence, now, None)
207    }
208
209    /// Advance the present-field count with `resume_count`'s bounds, revision,
210    /// retry and expiry rules. Empty/all-absent input completes with zero.
211    /// # Errors
212    /// Refuses changed fields, row-count jobs and ordinary count resume failures.
213    /// # Panics
214    /// Supplier mutation failures trap the enclosing message.
215    pub fn resume_count_field(
216        self,
217        field: &str,
218        jobs: &mut AggregateJobs<M>,
219        handle: &JobHandle,
220        sequence: u64,
221        now: Timestamp,
222    ) -> Result<JobStep<u64>, Error> {
223        self.resume_count_job(jobs, handle, sequence, now, Some(field))
224    }
225
226    fn resume_count_job(
227        self,
228        jobs: &mut AggregateJobs<M>,
229        handle: &JobHandle,
230        sequence: u64,
231        now: Timestamp,
232        field: Option<&str>,
233    ) -> Result<JobStep<u64>, Error> {
234        let plan = self.aggregate_plan(None, false)?;
235        let mut record = jobs.load(handle)?;
236        let mut reducer = self.count_reducer(field)?;
237        let expected = field_binding(binding(&plan, &reducer)?, field);
238        let bytes = self.request.bytes;
239        prepare(
240            &*self.db.read()?,
241            E::SCHEMA,
242            self.request,
243            &plan,
244            Accumulator::Scalar(&mut reducer),
245            &mut record,
246            expected,
247            sequence,
248            now,
249        )?;
250
251        record.finish_and_save(jobs, handle, bytes, || {
252            Ok((reducer.finish()?.into_count()?, 8))
253        })
254    }
255
256    /// Retain an integer/Decimal sum job with synchronous sum's exact result shape.
257    /// Same expiry, capacity and query-binding contract as [`Self::start_count`].
258    /// # Errors
259    /// Refuses unsupported sum shapes, query admission, expiry or occupied capacity.
260    /// # Panics
261    /// Supplier mutation failures trap the enclosing message.
262    pub fn start_sum<R: Value>(
263        self,
264        jobs: &mut AggregateJobs<M>,
265        now: Timestamp,
266        expires: Timestamp,
267    ) -> Result<JobHandle, Error> {
268        self.start_numeric::<R>(jobs, now, expires, Operation::Sum)
269    }
270
271    /// Advance exact sum under count's work/retry/invalidation contract. Check the
272    /// declared result width only after all input completes, allowing signed
273    /// prefixes to cancel across messages. Empty/all-absent input completes as None.
274    /// # Errors
275    /// Count's refusals plus arithmetic overflow or completed-result byte limits.
276    /// A refused finalization preserves the previous checkpoint.
277    /// # Panics
278    /// Supplier mutation failures trap the enclosing message.
279    pub fn resume_sum<R: Value>(
280        self,
281        jobs: &mut AggregateJobs<M>,
282        handle: &JobHandle,
283        sequence: u64,
284        now: Timestamp,
285    ) -> Result<JobStep<Option<R>>, Error> {
286        self.resume_numeric::<R>(jobs, handle, sequence, now, Operation::Sum)
287    }
288
289    /// Retain an exact integer/Decimal average. R declares one Decimal field
290    /// with the source name and optionality, and its desired result scale (0–28).
291    /// Shares count/sum's expiry, capacity and revision contract. Average versus
292    /// sum and the result scale are bound to the job; they cannot change on resume.
293    /// # Errors
294    /// Refuses unsupported average shapes, query admission, expiry or occupied capacity.
295    /// # Panics
296    /// Supplier mutation failures trap the enclosing message.
297    pub fn start_avg<R: Value>(
298        self,
299        jobs: &mut AggregateJobs<M>,
300        now: Timestamp,
301        expires: Timestamp,
302    ) -> Result<JobHandle, Error> {
303        self.start_numeric::<R>(jobs, now, expires, Operation::Average)
304    }
305
306    /// Advance average under count's bounded work/retry/invalidation contract.
307    /// Retain the exact total and present count across steps; divide and round once
308    /// at completion to the declared Decimal scale, nearest with ties to even.
309    /// Empty/all-absent input completes as None. Never average rounded page means.
310    /// # Errors
311    /// Count's refusals plus arithmetic overflow or completed-result byte limits.
312    /// A refused finalization preserves the prior exact checkpoint; no scale fallback.
313    /// # Panics
314    /// Supplier mutation failures trap the enclosing message.
315    pub fn resume_avg<R: Value>(
316        self,
317        jobs: &mut AggregateJobs<M>,
318        handle: &JobHandle,
319        sequence: u64,
320        now: Timestamp,
321    ) -> Result<JobStep<Option<R>>, Error> {
322        self.resume_numeric::<R>(jobs, handle, sequence, now, Operation::Average)
323    }
324
325    fn start_numeric<R: Value>(
326        self,
327        jobs: &mut AggregateJobs<M>,
328        now: Timestamp,
329        expires: Timestamp,
330        operation: Operation,
331    ) -> Result<JobHandle, Error> {
332        let (plan, mut reducer) = self.numeric_plan::<R>(None, operation)?;
333
334        start(
335            jobs,
336            binding(&plan, &reducer)?,
337            self.db.read()?.revision_by_id(E::SCHEMA.id)?,
338            now,
339            expires,
340            &Accumulator::Scalar(&mut reducer),
341        )
342    }
343
344    fn resume_numeric<R: Value>(
345        self,
346        jobs: &mut AggregateJobs<M>,
347        handle: &JobHandle,
348        sequence: u64,
349        now: Timestamp,
350        operation: Operation,
351    ) -> Result<JobStep<Option<R>>, Error> {
352        let (plan, reducer) = self.numeric_plan::<R>(None, operation)?;
353
354        self.resume_value(jobs, handle, sequence, now, (plan, reducer))
355    }
356
357    fn resume_value<R: Value>(
358        self,
359        jobs: &mut AggregateJobs<M>,
360        handle: &JobHandle,
361        sequence: u64,
362        now: Timestamp,
363        admitted: (Plan<'_>, Reducer),
364    ) -> Result<JobStep<Option<R>>, Error> {
365        let (plan, mut reducer) = admitted;
366        let mut record = jobs.load(handle)?;
367        let expected = binding(&plan, &reducer)?;
368        let limit = self.request.bytes;
369        prepare(
370            &*self.db.read()?,
371            E::SCHEMA,
372            self.request,
373            &plan,
374            Accumulator::Scalar(&mut reducer),
375            &mut record,
376            expected,
377            sequence,
378            now,
379        )?;
380
381        record.finish_and_save(jobs, handle, limit, || {
382            let bytes = reducer.finish()?.into_value()?;
383            let size = bytes.as_ref().map_or(0, Vec::len);
384            let value = bytes.as_deref().map(decode_record).transpose()?;
385
386            Ok((value, size))
387        })
388    }
389}
390fn field_binding(binding: [u8; 32], field: Option<&str>) -> [u8; 32] {
391    let Some(field) = field else { return binding };
392    let mut hash = Sha256::new();
393    hash.update(b"ic-db:field-count-job:v1\0");
394    hash.update(binding);
395    hash.update((field.len() as u32).to_le_bytes());
396    hash.update(field.as_bytes());
397
398    hash.finalize().into()
399}
400
401fn binding(plan: &Plan<'_>, reducer: &Reducer) -> Result<[u8; 32], Error> {
402    let mut hash = Sha256::new();
403    // Algorithm identity is independent of the row schema. Changing checkpoint or
404    // accumulation semantics requires a new identity and explicit resume support.
405    hash.update(b"ic-db:scalar-job:v1\0");
406    hash.update(plan.binding);
407    match reducer {
408        // A field-count terminal adds its admitted field identity with field_binding.
409        Reducer::Count { .. } => hash.update([0]),
410        Reducer::Numeric(state) => {
411            hash.update([state.operation as u8, state.position as u8]);
412            let output = state.output();
413            let mut bytes = Vec::new();
414            crate::schema::encode_type(&mut bytes, output.value, output.optional, false)?;
415            hash.update(bytes);
416        }
417        // New payload identities; existing count/sum/average bindings stay stable.
418        Reducer::Extremum {
419            position, maximum, ..
420        } => {
421            hash.update([if *maximum { 4 } else { 3 }, *position as u8]);
422        }
423        _ => return Err(Error::InvalidQuery),
424    }
425
426    Ok(hash.finalize().into())
427}
428
429fn start<M: Memory>(
430    jobs: &mut AggregateJobs<M>,
431    binding: [u8; 32],
432    revision: u64,
433    now: Timestamp,
434    expires: Timestamp,
435    accumulator: &Accumulator<'_>,
436) -> Result<JobHandle, Error> {
437    let lifetime = expires
438        .as_millis()
439        .checked_sub(now.as_millis())
440        .ok_or(Error::Limit)?;
441    if !(1..=MAX_LIFETIME_MS).contains(&lifetime) {
442        return Err(Error::Limit);
443    }
444    let (count, state) = accumulator.checkpoint()?;
445
446    jobs.insert(Record {
447        generation: 0,
448        binding,
449        revision,
450        expires,
451        observed: now,
452        sequence: 0,
453        examined: 0,
454        input_bytes: 0,
455        phase: JobOutcome::Running,
456        cursor: Vec::new(),
457        count,
458        state,
459    })
460}
461
462// One shared concrete execution path. Type conversion happens before save, outside
463// this function. Preparation errors never persist a partial accumulator or cursor.
464#[expect(
465    clippy::too_many_arguments,
466    reason = "explicit admitted query and checkpoint inputs keep the shared resume boundary local"
467)]
468fn prepare<M: Memory>(
469    db: &Database<M>,
470    entity: &EntitySchema,
471    request: Request<'_>,
472    plan: &Plan<'_>,
473    mut accumulator: Accumulator<'_>,
474    record: &mut Record,
475    expected: [u8; 32],
476    sequence: u64,
477    now: Timestamp,
478) -> Result<(), Error> {
479    if record.binding != expected || sequence > record.sequence {
480        return Err(Error::InvalidJob);
481    }
482    if now < record.observed {
483        return Err(Error::TimestampRegression);
484    }
485    accumulator.restore(entity, record)?;
486    if now >= record.expires && !matches!(record.phase, JobOutcome::Expired) {
487        record.phase = JobOutcome::Expired;
488        record.sequence += 1;
489    } else if matches!(record.phase, JobOutcome::Running) {
490        if db.revision_by_id(entity.id)? != record.revision {
491            record.phase = JobOutcome::Invalidated;
492            record.sequence += 1;
493        } else if sequence == record.sequence {
494            let cursor = if record.cursor.is_empty() {
495                None
496            } else {
497                let cursor = QueryCursor::from_bytes(&record.cursor)?;
498                if cursor.binding != plan.binding {
499                    return Err(Error::Corrupt);
500                }
501                plan.validate_position(entity, &cursor.position)?;
502
503                Some(cursor)
504            };
505            let request = Request {
506                cursor: cursor.as_ref(),
507                work: request
508                    .work
509                    .min((MAX_CANDIDATES - record.examined) as usize),
510                ..request
511            };
512            let mut bytes = 0;
513            let page = execute_inner(
514                &db.map,
515                entity,
516                &request,
517                plan,
518                Some(&mut accumulator),
519                Some(&mut bytes),
520            )?;
521            record.examined += page.examined as u64;
522            record.input_bytes += bytes as u64;
523            record.cursor = page
524                .next
525                .as_ref()
526                .map_or_else(Vec::new, QueryCursor::to_bytes);
527            record.phase = if page.next.is_none() {
528                JobOutcome::Complete(())
529            } else {
530                JobOutcome::Running
531            };
532            record.sequence += 1;
533            (record.count, record.state) = accumulator.checkpoint()?;
534        }
535    }
536    record.observed = now;
537
538    Ok(())
539}