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