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