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