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, Map, 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.meta.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.meta.sequence,
123            source_revision: self.meta.revision,
124            examined: self.meta.examined,
125            input_bytes: self.meta.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            let admitted = self.numeric_plan::<R>(None, Operation::Sum)?;
325            self.start_value(jobs, now, expires, admitted)
326        })
327    }
328
329    /// Advance exact sum under count's work/retry/invalidation contract. Check the
330    /// declared result width only after all input completes, allowing signed
331    /// prefixes to cancel across messages. Empty/all-absent input completes as None.
332    /// # Errors
333    /// Count's refusals plus arithmetic overflow or completed-result byte limits.
334    /// A refused finalization preserves the previous checkpoint.
335    /// # Panics
336    /// Supplier mutation failures trap the enclosing message.
337    pub fn resume_sum<R: Value>(
338        self,
339        jobs: &mut AggregateJobs<M>,
340        handle: &JobHandle,
341        sequence: u64,
342        now: Timestamp,
343    ) -> Result<JobStep<Option<R>>, Error> {
344        observe!(resume, {
345            self.resume_numeric::<R>(jobs, handle, sequence, now, Operation::Sum)
346        })
347    }
348
349    /// Retain a Duration, finite float or integer/Decimal average. R declares a matching Duration, float or Decimal result
350    /// with the source name and optionality. Decimal results declare scale 0–28.
351    /// Shares count/sum's expiry, capacity and revision contract. Average versus
352    /// sum and the result scale are bound to the job; they cannot change on resume.
353    /// # Errors
354    /// Refuses unsupported average shapes, query admission, expiry or occupied capacity.
355    /// # Panics
356    /// Supplier mutation failures trap the enclosing message.
357    pub fn start_avg<R: Value>(
358        self,
359        jobs: &mut AggregateJobs<M>,
360        now: Timestamp,
361        expires: Timestamp,
362    ) -> Result<JobHandle, Error> {
363        observe!(start, {
364            let admitted = self.numeric_plan::<R>(None, Operation::Average)?;
365            self.start_value(jobs, now, expires, admitted)
366        })
367    }
368
369    /// Advance average under count's bounded work/retry/invalidation contract.
370    /// Retain the exact total and present count across steps; divide and round once
371    /// at completion to the input float width or the declared Decimal scale, nearest with ties to even.
372    /// Empty/all-absent input completes as None. Never average rounded page means.
373    /// # Errors
374    /// Count's refusals plus arithmetic overflow or completed-result byte limits.
375    /// A refused finalization preserves the prior exact checkpoint; no scale fallback.
376    /// # Panics
377    /// Supplier mutation failures trap the enclosing message.
378    pub fn resume_avg<R: Value>(
379        self,
380        jobs: &mut AggregateJobs<M>,
381        handle: &JobHandle,
382        sequence: u64,
383        now: Timestamp,
384    ) -> Result<JobStep<Option<R>>, Error> {
385        observe!(resume, {
386            self.resume_numeric::<R>(jobs, handle, sequence, now, Operation::Average)
387        })
388    }
389
390    fn start_value(
391        &self,
392        jobs: &mut AggregateJobs<M>,
393        now: Timestamp,
394        expires: Timestamp,
395        admitted: (Plan<'_>, Reducer),
396    ) -> Result<JobHandle, Error> {
397        let (plan, mut reducer) = admitted;
398
399        start(
400            jobs,
401            binding(&plan, &reducer)?,
402            self.db.read()?.revision_by_id(E::SCHEMA.id)?,
403            now,
404            expires,
405            &Accumulator::Scalar(&mut reducer),
406        )
407    }
408
409    fn resume_numeric<R: Value>(
410        self,
411        jobs: &mut AggregateJobs<M>,
412        handle: &JobHandle,
413        sequence: u64,
414        now: Timestamp,
415        operation: Operation,
416    ) -> Result<JobStep<Option<R>>, Error> {
417        let (plan, reducer) = self.numeric_plan::<R>(None, operation)?;
418
419        self.resume_value(jobs, handle, sequence, now, (plan, reducer))
420    }
421
422    fn resume_value<R: Value>(
423        self,
424        jobs: &mut AggregateJobs<M>,
425        handle: &JobHandle,
426        sequence: u64,
427        now: Timestamp,
428        admitted: (Plan<'_>, Reducer),
429    ) -> Result<JobStep<Option<R>>, Error> {
430        let (plan, mut reducer) = admitted;
431        let mut record = jobs.load(handle)?;
432        let expected = binding(&plan, &reducer)?;
433        let limit = self.request.bytes;
434        let changed = prepare(
435            &*self.db.read()?,
436            E::SCHEMA,
437            self.request,
438            &plan,
439            Accumulator::Scalar(&mut reducer),
440            &mut record,
441            expected,
442            sequence,
443            now,
444        )?;
445
446        record.finish_and_save(jobs, handle, changed, limit, || {
447            scalar_output(reducer, limit)
448        })
449    }
450}
451fn field_binding(binding: [u8; 32], field: Option<&str>) -> [u8; 32] {
452    let Some(field) = field else { return binding };
453    let mut hash = Sha256::new();
454    hash.update(b"ic-db:field-count-job:v1\0");
455    hash.update(binding);
456    hash.update((field.len() as u32).to_le_bytes());
457    hash.update(field.as_bytes());
458
459    hash.finalize().into()
460}
461
462fn binding(plan: &Plan<'_>, reducer: &Reducer) -> Result<[u8; 32], Error> {
463    let mut hash = Sha256::new();
464    // Algorithm identity is independent of the row schema. Changing checkpoint or
465    // accumulation semantics requires a new identity and explicit resume support.
466    hash.update(b"ic-db:scalar-job:v1\0");
467    hash.update(plan.binding);
468    match reducer {
469        // A field-count terminal adds its admitted field identity with field_binding.
470        Reducer::Count { .. } => hash.update([0]),
471        Reducer::Numeric(state) => {
472            hash.update([state.operation as u8, state.position as u8]);
473            let output = state.output();
474            match (crate::key::operand_type(output.value), state.operation) {
475                (crate::FieldType::Float32, _) => hash.update(b"binary32-exact:v1\0"),
476                (crate::FieldType::Float64, Operation::Sum) => {
477                    hash.update(b"binary64-exact-sum:v1\0")
478                }
479                (crate::FieldType::Float64, Operation::Average) => {
480                    hash.update(b"binary64-exact-average:v1\0")
481                }
482                _ => {}
483            }
484            let mut bytes = Vec::new();
485            crate::schema::encode_type(&mut bytes, output.value, output.optional, false)?;
486            hash.update(bytes);
487        }
488        // New payload identities; existing count/sum/average bindings stay stable.
489        Reducer::Extremum {
490            position, maximum, ..
491        } => {
492            hash.update([if *maximum { 4 } else { 3 }, *position as u8]);
493        }
494        _ => return Err(Error::InvalidQuery),
495    }
496
497    Ok(hash.finalize().into())
498}
499
500fn start<M: Memory>(
501    jobs: &mut AggregateJobs<M>,
502    binding: [u8; 32],
503    revision: u64,
504    now: Timestamp,
505    expires: Timestamp,
506    accumulator: &Accumulator<'_>,
507) -> Result<JobHandle, Error> {
508    let lifetime = expires
509        .as_millis()
510        .checked_sub(now.as_millis())
511        .ok_or(Error::Limit)?;
512    if !(1..=MAX_LIFETIME_MS).contains(&lifetime) {
513        return Err(Error::Limit);
514    }
515    let (count, state) = accumulator.checkpoint()?;
516
517    jobs.insert(Record {
518        meta: storage::RecordMeta {
519            generation: 0,
520            binding,
521            revision,
522            expires,
523            observed: now,
524            sequence: 0,
525            examined: 0,
526            input_bytes: 0,
527            phase: JobOutcome::Running,
528        },
529        cursor: Vec::new(),
530        count,
531        state,
532    })
533}
534
535// One shared concrete execution path. Type conversion happens before save, outside
536// this function. Preparation errors never persist a partial accumulator or cursor.
537#[expect(
538    clippy::too_many_arguments,
539    reason = "explicit admitted query and checkpoint inputs keep the shared resume boundary local"
540)]
541fn prepare<M: Memory>(
542    db: &Database<M>,
543    entity: &EntitySchema,
544    request: Request<'_>,
545    plan: &Plan<'_>,
546    mut accumulator: Accumulator<'_>,
547    record: &mut Record,
548    expected: [u8; 32],
549    sequence: u64,
550    now: Timestamp,
551) -> Result<bool, Error> {
552    if record.meta.binding != expected || sequence > record.meta.sequence {
553        return Err(Error::InvalidJob);
554    }
555    if now < record.meta.observed {
556        return Err(Error::TimestampRegression);
557    }
558    let saved_sequence = record.meta.sequence;
559    accumulator.restore(entity, record)?;
560    if now >= record.meta.expires && !matches!(record.meta.phase, JobOutcome::Expired) {
561        record.meta.phase = JobOutcome::Expired;
562        record.meta.sequence += 1;
563    } else if matches!(record.meta.phase, JobOutcome::Running) {
564        if db.revision_by_id(entity.id)? != record.meta.revision {
565            record.meta.phase = JobOutcome::Invalidated;
566            record.meta.sequence += 1;
567        } else if sequence == record.meta.sequence {
568            execute_chunk(&db.map, entity, request, plan, &mut accumulator, record)?;
569            record.meta.sequence += 1;
570        }
571    }
572    // Every advance or phase transition increments the sequence. A later
573    // observation also needs persistence to enforce monotonic time on retries.
574    let changed = record.meta.sequence != saved_sequence || record.meta.observed != now;
575    record.meta.observed = now;
576
577    Ok(changed)
578}
579
580fn execute_chunk<M: Memory>(
581    map: &Map<M>,
582    entity: &EntitySchema,
583    request: Request<'_>,
584    plan: &Plan<'_>,
585    accumulator: &mut Accumulator<'_>,
586    record: &mut Record,
587) -> Result<(), Error> {
588    let cursor = if record.cursor.is_empty() {
589        None
590    } else {
591        let cursor = QueryCursor::from_bytes(&record.cursor)?;
592        plan.validate_cursor(entity, &cursor)?;
593
594        Some(cursor)
595    };
596    let request = Request {
597        cursor: cursor.as_ref(),
598        work: request
599            .work
600            .min((MAX_CANDIDATES - record.meta.examined) as usize),
601        ..request
602    };
603    let mut bytes = 0;
604    let page = execute_inner(
605        map,
606        entity,
607        &request,
608        plan,
609        super::super::range::bounds(entity, &request, plan)?,
610        Some(accumulator),
611        Some(&mut bytes),
612    )?;
613    record.meta.examined += page.examined as u64;
614    record.meta.input_bytes += bytes as u64;
615    record.cursor = page
616        .next
617        .as_ref()
618        .map_or_else(Vec::new, QueryCursor::to_bytes);
619    record.meta.phase = if page.next.is_none() {
620        JobOutcome::Complete(())
621    } else {
622        JobOutcome::Running
623    };
624    (record.count, record.state) = accumulator.checkpoint()?;
625
626    Ok(())
627}