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