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        changed: bool,
102        limit: usize,
103        finish: impl FnOnce() -> Result<(T, usize), Error>,
104    ) -> Result<JobStep<T>, Error> {
105        let (outcome, output_bytes) = match self.phase {
106            JobOutcome::Running => (JobOutcome::Running, 0),
107            JobOutcome::Invalidated => (JobOutcome::Invalidated, 0),
108            JobOutcome::Expired => (JobOutcome::Expired, 0),
109            JobOutcome::Complete(()) => {
110                let (value, bytes) = finish()?;
111                if bytes > limit {
112                    return Err(Error::RowTooLarge);
113                }
114
115                (JobOutcome::Complete(value), bytes)
116            }
117        };
118        jobs.save_if_changed(handle, self, changed)?;
119
120        Ok(JobStep {
121            sequence: self.sequence,
122            source_revision: self.revision,
123            examined: self.examined,
124            input_bytes: self.input_bytes,
125            output_bytes,
126            outcome,
127        })
128    }
129}
130
131impl<E: Entity, M: Memory> Query<'_, E, M> {
132    /// Retain an exact count job without scanning input. Expiry must be after the
133    /// host-captured `now` and at most one hour later. No write freeze is acquired.
134    /// Reconstruct this fluent query on every advance; predicates/access path bind
135    /// the job, while the per-call work limit may change. Limit never truncates input.
136    /// # Errors
137    /// Ordinary count admission, invalid expiry, or all 16 retained slots occupied.
138    /// # Panics
139    /// Supplier mutation failures trap the enclosing message.
140    pub fn start_count(
141        self,
142        jobs: &mut AggregateJobs<M>,
143        now: Timestamp,
144        expires: Timestamp,
145    ) -> Result<JobHandle, Error> {
146        self.start_count_job(jobs, now, expires, None)
147    }
148
149    /// Retain the count of present values in a named top-level field, of any stored
150    /// type. Empty values count; absent values do not. The field binds the job,
151    /// even for a required field. Uses `start_count`'s limits and expiry contract.
152    /// # Errors
153    /// Refuses unknown fields and ordinary count-job admission failures.
154    /// # Panics
155    /// Supplier mutation failures trap the enclosing message.
156    pub fn start_count_field(
157        self,
158        field: &str,
159        jobs: &mut AggregateJobs<M>,
160        now: Timestamp,
161        expires: Timestamp,
162    ) -> Result<JobHandle, Error> {
163        self.start_count_job(jobs, now, expires, Some(field))
164    }
165
166    fn start_count_job(
167        self,
168        jobs: &mut AggregateJobs<M>,
169        now: Timestamp,
170        expires: Timestamp,
171        field: Option<&str>,
172    ) -> Result<JobHandle, Error> {
173        let plan = self.aggregate_plan(None, false)?;
174        let mut reducer = self.count_reducer(field)?;
175        if self.request.bytes < 8 {
176            return Err(Error::RowTooLarge);
177        }
178
179        start(
180            jobs,
181            field_binding(binding(&plan, &reducer)?, field),
182            self.db.read()?.revision_by_id(E::SCHEMA.id)?,
183            now,
184            expires,
185            &Accumulator::Scalar(&mut reducer),
186        )
187    }
188
189    /// Advance count within `work_limit` (1..=512) and 64 KiB of source row/key
190    /// bytes. Each job admits at most one million examined candidates. A budget
191    /// boundary returns Running; it never changes the mathematical input set.
192    /// Supply zero first, then the last returned sequence. An older sequence only
193    /// reads saved progress; a future sequence refuses. Source changes invalidate
194    /// running jobs, including on retries; completed results keep their boundary.
195    /// # Errors
196    /// Refuses a foreign query/handle, future sequence, backward host time, resource
197    /// bounds or corruption without changing progress. No automatic restart.
198    /// # Panics
199    /// Supplier mutation failures trap the enclosing message.
200    pub fn resume_count(
201        self,
202        jobs: &mut AggregateJobs<M>,
203        handle: &JobHandle,
204        sequence: u64,
205        now: Timestamp,
206    ) -> Result<JobStep<u64>, Error> {
207        self.resume_count_job(jobs, handle, sequence, now, None)
208    }
209
210    /// Advance the present-field count with `resume_count`'s bounds, revision,
211    /// retry and expiry rules. Empty/all-absent input completes with zero.
212    /// # Errors
213    /// Refuses changed fields, row-count jobs and ordinary count resume failures.
214    /// # Panics
215    /// Supplier mutation failures trap the enclosing message.
216    pub fn resume_count_field(
217        self,
218        field: &str,
219        jobs: &mut AggregateJobs<M>,
220        handle: &JobHandle,
221        sequence: u64,
222        now: Timestamp,
223    ) -> Result<JobStep<u64>, Error> {
224        self.resume_count_job(jobs, handle, sequence, now, Some(field))
225    }
226
227    fn resume_count_job(
228        self,
229        jobs: &mut AggregateJobs<M>,
230        handle: &JobHandle,
231        sequence: u64,
232        now: Timestamp,
233        field: Option<&str>,
234    ) -> Result<JobStep<u64>, Error> {
235        let plan = self.aggregate_plan(None, false)?;
236        let mut record = jobs.load(handle)?;
237        let mut reducer = self.count_reducer(field)?;
238        let expected = field_binding(binding(&plan, &reducer)?, field);
239        let bytes = self.request.bytes;
240        let changed = prepare(
241            &*self.db.read()?,
242            E::SCHEMA,
243            self.request,
244            &plan,
245            Accumulator::Scalar(&mut reducer),
246            &mut record,
247            expected,
248            sequence,
249            now,
250        )?;
251
252        record.finish_and_save(jobs, handle, changed, bytes, || {
253            Ok((reducer.finish()?.into_count()?, 8))
254        })
255    }
256
257    /// Retain an integer, Decimal or finite float sum job with synchronous sum's exact result shape.
258    /// Same expiry, capacity and query-binding contract as [`Self::start_count`].
259    /// # Errors
260    /// Refuses unsupported sum shapes, query admission, expiry or occupied capacity.
261    /// # Panics
262    /// Supplier mutation failures trap the enclosing message.
263    pub fn start_sum<R: Value>(
264        self,
265        jobs: &mut AggregateJobs<M>,
266        now: Timestamp,
267        expires: Timestamp,
268    ) -> Result<JobHandle, Error> {
269        self.start_numeric::<R>(jobs, now, expires, Operation::Sum)
270    }
271
272    /// Advance exact sum under count's work/retry/invalidation contract. Check the
273    /// declared result width only after all input completes, allowing signed
274    /// prefixes to cancel across messages. Empty/all-absent input completes as None.
275    /// # Errors
276    /// Count's refusals plus arithmetic overflow or completed-result byte limits.
277    /// A refused finalization preserves the previous checkpoint.
278    /// # Panics
279    /// Supplier mutation failures trap the enclosing message.
280    pub fn resume_sum<R: Value>(
281        self,
282        jobs: &mut AggregateJobs<M>,
283        handle: &JobHandle,
284        sequence: u64,
285        now: Timestamp,
286    ) -> Result<JobStep<Option<R>>, Error> {
287        self.resume_numeric::<R>(jobs, handle, sequence, now, Operation::Sum)
288    }
289
290    /// Retain an exact finite float or integer/Decimal average. R declares a matching float or a Decimal field
291    /// with the source name and optionality. Decimal results declare scale 0–28.
292    /// Shares count/sum's expiry, capacity and revision contract. Average versus
293    /// sum and the result scale are bound to the job; they cannot change on resume.
294    /// # Errors
295    /// Refuses unsupported average shapes, query admission, expiry or occupied capacity.
296    /// # Panics
297    /// Supplier mutation failures trap the enclosing message.
298    pub fn start_avg<R: Value>(
299        self,
300        jobs: &mut AggregateJobs<M>,
301        now: Timestamp,
302        expires: Timestamp,
303    ) -> Result<JobHandle, Error> {
304        self.start_numeric::<R>(jobs, now, expires, Operation::Average)
305    }
306
307    /// Advance average under count's bounded work/retry/invalidation contract.
308    /// Retain the exact total and present count across steps; divide and round once
309    /// at completion to the input float width or the declared Decimal scale, nearest with ties to even.
310    /// Empty/all-absent input completes as None. Never average rounded page means.
311    /// # Errors
312    /// Count's refusals plus arithmetic overflow or completed-result byte limits.
313    /// A refused finalization preserves the prior exact checkpoint; no scale fallback.
314    /// # Panics
315    /// Supplier mutation failures trap the enclosing message.
316    pub fn resume_avg<R: Value>(
317        self,
318        jobs: &mut AggregateJobs<M>,
319        handle: &JobHandle,
320        sequence: u64,
321        now: Timestamp,
322    ) -> Result<JobStep<Option<R>>, Error> {
323        self.resume_numeric::<R>(jobs, handle, sequence, now, Operation::Average)
324    }
325
326    fn start_numeric<R: Value>(
327        self,
328        jobs: &mut AggregateJobs<M>,
329        now: Timestamp,
330        expires: Timestamp,
331        operation: Operation,
332    ) -> Result<JobHandle, Error> {
333        let (plan, mut reducer) = self.numeric_plan::<R>(None, operation)?;
334
335        start(
336            jobs,
337            binding(&plan, &reducer)?,
338            self.db.read()?.revision_by_id(E::SCHEMA.id)?,
339            now,
340            expires,
341            &Accumulator::Scalar(&mut reducer),
342        )
343    }
344
345    fn resume_numeric<R: Value>(
346        self,
347        jobs: &mut AggregateJobs<M>,
348        handle: &JobHandle,
349        sequence: u64,
350        now: Timestamp,
351        operation: Operation,
352    ) -> Result<JobStep<Option<R>>, Error> {
353        let (plan, reducer) = self.numeric_plan::<R>(None, operation)?;
354
355        self.resume_value(jobs, handle, sequence, now, (plan, reducer))
356    }
357
358    fn resume_value<R: Value>(
359        self,
360        jobs: &mut AggregateJobs<M>,
361        handle: &JobHandle,
362        sequence: u64,
363        now: Timestamp,
364        admitted: (Plan<'_>, Reducer),
365    ) -> Result<JobStep<Option<R>>, Error> {
366        let (plan, mut reducer) = admitted;
367        let mut record = jobs.load(handle)?;
368        let expected = binding(&plan, &reducer)?;
369        let limit = self.request.bytes;
370        let changed = prepare(
371            &*self.db.read()?,
372            E::SCHEMA,
373            self.request,
374            &plan,
375            Accumulator::Scalar(&mut reducer),
376            &mut record,
377            expected,
378            sequence,
379            now,
380        )?;
381
382        record.finish_and_save(jobs, handle, changed, limit, || {
383            let bytes = reducer.finish()?.into_value()?;
384            let size = bytes.as_ref().map_or(0, Vec::len);
385            let value = bytes.as_deref().map(decode_record).transpose()?;
386
387            Ok((value, size))
388        })
389    }
390}
391fn field_binding(binding: [u8; 32], field: Option<&str>) -> [u8; 32] {
392    let Some(field) = field else { return binding };
393    let mut hash = Sha256::new();
394    hash.update(b"ic-db:field-count-job:v1\0");
395    hash.update(binding);
396    hash.update((field.len() as u32).to_le_bytes());
397    hash.update(field.as_bytes());
398
399    hash.finalize().into()
400}
401
402fn binding(plan: &Plan<'_>, reducer: &Reducer) -> Result<[u8; 32], Error> {
403    let mut hash = Sha256::new();
404    // Algorithm identity is independent of the row schema. Changing checkpoint or
405    // accumulation semantics requires a new identity and explicit resume support.
406    hash.update(b"ic-db:scalar-job:v1\0");
407    hash.update(plan.binding);
408    match reducer {
409        // A field-count terminal adds its admitted field identity with field_binding.
410        Reducer::Count { .. } => hash.update([0]),
411        Reducer::Numeric(state) => {
412            hash.update([state.operation as u8, state.position as u8]);
413            let output = state.output();
414            match (crate::key::operand_type(output.value), state.operation) {
415                (crate::FieldType::Float32, _) => hash.update(b"binary32-exact:v1\0"),
416                (crate::FieldType::Float64, Operation::Sum) => {
417                    hash.update(b"binary64-exact-sum:v1\0")
418                }
419                (crate::FieldType::Float64, Operation::Average) => {
420                    hash.update(b"binary64-exact-average:v1\0")
421                }
422                _ => {}
423            }
424            let mut bytes = Vec::new();
425            crate::schema::encode_type(&mut bytes, output.value, output.optional, false)?;
426            hash.update(bytes);
427        }
428        // New payload identities; existing count/sum/average bindings stay stable.
429        Reducer::Extremum {
430            position, maximum, ..
431        } => {
432            hash.update([if *maximum { 4 } else { 3 }, *position as u8]);
433        }
434        _ => return Err(Error::InvalidQuery),
435    }
436
437    Ok(hash.finalize().into())
438}
439
440fn start<M: Memory>(
441    jobs: &mut AggregateJobs<M>,
442    binding: [u8; 32],
443    revision: u64,
444    now: Timestamp,
445    expires: Timestamp,
446    accumulator: &Accumulator<'_>,
447) -> Result<JobHandle, Error> {
448    let lifetime = expires
449        .as_millis()
450        .checked_sub(now.as_millis())
451        .ok_or(Error::Limit)?;
452    if !(1..=MAX_LIFETIME_MS).contains(&lifetime) {
453        return Err(Error::Limit);
454    }
455    let (count, state) = accumulator.checkpoint()?;
456
457    jobs.insert(Record {
458        generation: 0,
459        binding,
460        revision,
461        expires,
462        observed: now,
463        sequence: 0,
464        examined: 0,
465        input_bytes: 0,
466        phase: JobOutcome::Running,
467        cursor: Vec::new(),
468        count,
469        state,
470    })
471}
472
473// One shared concrete execution path. Type conversion happens before save, outside
474// this function. Preparation errors never persist a partial accumulator or cursor.
475#[expect(
476    clippy::too_many_arguments,
477    reason = "explicit admitted query and checkpoint inputs keep the shared resume boundary local"
478)]
479fn prepare<M: Memory>(
480    db: &Database<M>,
481    entity: &EntitySchema,
482    request: Request<'_>,
483    plan: &Plan<'_>,
484    mut accumulator: Accumulator<'_>,
485    record: &mut Record,
486    expected: [u8; 32],
487    sequence: u64,
488    now: Timestamp,
489) -> Result<bool, Error> {
490    if record.binding != expected || sequence > record.sequence {
491        return Err(Error::InvalidJob);
492    }
493    if now < record.observed {
494        return Err(Error::TimestampRegression);
495    }
496    let saved_sequence = record.sequence;
497    accumulator.restore(entity, record)?;
498    if now >= record.expires && !matches!(record.phase, JobOutcome::Expired) {
499        record.phase = JobOutcome::Expired;
500        record.sequence += 1;
501    } else if matches!(record.phase, JobOutcome::Running) {
502        if db.revision_by_id(entity.id)? != record.revision {
503            record.phase = JobOutcome::Invalidated;
504            record.sequence += 1;
505        } else if sequence == record.sequence {
506            let cursor = if record.cursor.is_empty() {
507                None
508            } else {
509                let cursor = QueryCursor::from_bytes(&record.cursor)?;
510                if cursor.binding != plan.binding {
511                    return Err(Error::Corrupt);
512                }
513                plan.validate_position(entity, &cursor)?;
514
515                Some(cursor)
516            };
517            let request = Request {
518                cursor: cursor.as_ref(),
519                work: request
520                    .work
521                    .min((MAX_CANDIDATES - record.examined) as usize),
522                ..request
523            };
524            let mut bytes = 0;
525            let page = execute_inner(
526                &db.map,
527                entity,
528                &request,
529                plan,
530                Some(&mut accumulator),
531                Some(&mut bytes),
532            )?;
533            record.examined += page.examined as u64;
534            record.input_bytes += bytes as u64;
535            record.cursor = page
536                .next
537                .as_ref()
538                .map_or_else(Vec::new, QueryCursor::to_bytes);
539            record.phase = if page.next.is_none() {
540                JobOutcome::Complete(())
541            } else {
542                JobOutcome::Running
543            };
544            record.sequence += 1;
545            (record.count, record.state) = accumulator.checkpoint()?;
546        }
547    }
548    // Every advance or phase transition increments the sequence. A later
549    // observation also needs persistence to enforce monotonic time on retries.
550    let changed = record.sequence != saved_sequence || record.observed != now;
551    record.observed = now;
552
553    Ok(changed)
554}