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
161///
162/// ResumePoint
163/// Caller-supplied retry sequence and message time for a scalar job advance.
164///
165#[derive(Clone, Copy)]
166struct ResumePoint {
167    sequence: u64,
168    now: Timestamp,
169}
170
171impl<E: Entity, M: Memory> Query<'_, E, M> {
172    /// Retain an exact count job without scanning input. Expiry must be after the
173    /// host-captured `now` and at most one hour later. No write freeze is acquired.
174    /// Reconstruct this fluent query on every advance; predicates/access path bind
175    /// the job, while the per-call work limit may change. Limit never truncates input.
176    /// # Errors
177    /// Ordinary count admission, invalid expiry, or all 16 retained slots occupied.
178    /// # Panics
179    /// Supplier mutation failures trap the enclosing message.
180    pub fn start_count(
181        self,
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::Rows)
188        })
189    }
190
191    /// Retain the count of present values in a named top-level field, of any stored
192    /// type. Empty values count; absent values do not. The field binds the job,
193    /// even for a required field. Uses `start_count`'s limits and expiry contract.
194    /// # Errors
195    /// Refuses unknown fields and ordinary count-job admission failures.
196    /// # Panics
197    /// Supplier mutation failures trap the enclosing message.
198    pub fn start_count_field(
199        self,
200        field: &str,
201        jobs: &mut AggregateJobs<M>,
202        now: Timestamp,
203        expires: Timestamp,
204    ) -> Result<JobHandle, Error> {
205        observe!(start, {
206            self.start_count_job(jobs, now, expires, CountInput::Field(field))
207        })
208    }
209
210    fn start_count_job(
211        self,
212        jobs: &mut AggregateJobs<M>,
213        now: Timestamp,
214        expires: Timestamp,
215        input: CountInput<'_>,
216    ) -> Result<JobHandle, Error> {
217        let plan = self.aggregate_plan(input.projection(), false)?;
218        let (mut reducer, expected) = self.retained_count_state(&plan, input)?;
219        if self.request.bytes < 8 {
220            return Err(Error::RowTooLarge);
221        }
222
223        start(
224            jobs,
225            expected,
226            self.db.read()?.revision_by_id(E::SCHEMA.id)?,
227            now,
228            expires,
229            &Accumulator::Scalar(&mut reducer),
230        )
231    }
232
233    fn retained_count_state(
234        &self,
235        plan: &Plan<'_>,
236        input: CountInput<'_>,
237    ) -> Result<(Reducer, [u8; 32]), Error> {
238        let field = match input {
239            CountInput::Rows => None,
240            CountInput::Field(name) => Some(name),
241            CountInput::Distinct(_) => {
242                let mut hash = Sha256::new();
243                hash.update(b"ic-db:distinct-count-job:v1\0");
244                hash.update(plan.binding);
245                return Ok((
246                    Reducer::distinct(plan.projection.ok_or(Error::InvalidQuery)?),
247                    hash.finalize().into(),
248                ));
249            }
250        };
251        let reducer = self.count_reducer(field)?;
252        let expected = field_binding(binding(plan, &reducer)?, field);
253
254        Ok((reducer, expected))
255    }
256
257    /// Advance count within `work_limit` (1..=512) and 64 KiB of source row/key
258    /// bytes. Each job admits at most one million examined candidates. A budget
259    /// boundary returns Running if candidates remain. Exhausting the range can
260    /// complete the count on the last work unit. Index scans read each visited
261    /// owner and check that the stored row agrees with the index entry.
262    /// Supply zero first, then the last returned sequence. An older sequence only
263    /// reads saved progress; a future sequence refuses. Source changes invalidate
264    /// running jobs, including on retries; completed results keep their boundary.
265    /// # Errors
266    /// Refuses a foreign query/handle, future sequence, backward host time, resource
267    /// bounds or corruption without changing progress. No automatic restart.
268    /// # Panics
269    /// Supplier mutation failures trap the enclosing message.
270    pub fn resume_count(
271        self,
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::Rows)
279        })
280    }
281
282    /// Advance the present-field count with `resume_count`'s bounds, revision,
283    /// retry and expiry rules. Empty/all-absent input completes with zero.
284    /// # Errors
285    /// Refuses changed fields, row-count jobs and ordinary count resume failures.
286    /// # Panics
287    /// Supplier mutation failures trap the enclosing message.
288    pub fn resume_count_field(
289        self,
290        field: &str,
291        jobs: &mut AggregateJobs<M>,
292        handle: &JobHandle,
293        sequence: u64,
294        now: Timestamp,
295    ) -> Result<JobStep<u64>, Error> {
296        observe!(resume, {
297            self.resume_count_job(jobs, handle, sequence, now, CountInput::Field(field))
298        })
299    }
300
301    fn resume_count_job(
302        self,
303        jobs: &mut AggregateJobs<M>,
304        handle: &JobHandle,
305        sequence: u64,
306        now: Timestamp,
307        input: CountInput<'_>,
308    ) -> Result<JobStep<u64>, Error> {
309        let plan = self.aggregate_plan(input.projection(), false)?;
310        self.advance_scalar(
311            jobs,
312            handle,
313            ResumePoint { sequence, now },
314            &plan,
315            |query, plan| query.retained_count_state(plan, input),
316            |reducer, _| 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, reducer) = admitted;
440        self.advance_scalar(
441            jobs,
442            handle,
443            ResumePoint { sequence, now },
444            &plan,
445            |_, plan| {
446                let expected = binding(plan, &reducer)?;
447                Ok((reducer, expected))
448            },
449            scalar_output,
450        )
451    }
452
453    fn advance_scalar<T>(
454        self,
455        jobs: &mut AggregateJobs<M>,
456        handle: &JobHandle,
457        point: ResumePoint,
458        plan: &Plan<'_>,
459        state: impl FnOnce(&Self, &Plan<'_>) -> Result<(Reducer, [u8; 32]), Error>,
460        finish: fn(Reducer, usize) -> Result<(T, usize), Error>,
461    ) -> Result<JobStep<T>, Error> {
462        let mut record = jobs.load(handle)?;
463        let (mut reducer, expected) = state(&self, plan)?;
464        let limit = self.request.bytes;
465        let changed = prepare(
466            &*self.db.read()?,
467            E::SCHEMA,
468            self.request,
469            plan,
470            Accumulator::Scalar(&mut reducer),
471            &mut record,
472            expected,
473            point.sequence,
474            point.now,
475        )?;
476
477        record.finish_and_save(jobs, handle, changed, limit, || finish(reducer, limit))
478    }
479}
480fn field_binding(binding: [u8; 32], field: Option<&str>) -> [u8; 32] {
481    let Some(field) = field else { return binding };
482    let mut hash = Sha256::new();
483    hash.update(b"ic-db:field-count-job:v1\0");
484    hash.update(binding);
485    hash.update((field.len() as u32).to_le_bytes());
486    hash.update(field.as_bytes());
487
488    hash.finalize().into()
489}
490
491fn binding(plan: &Plan<'_>, reducer: &Reducer) -> Result<[u8; 32], Error> {
492    let mut hash = Sha256::new();
493    // Algorithm identity is independent of the row schema. Changing checkpoint or
494    // accumulation semantics requires a new identity and explicit resume support.
495    hash.update(b"ic-db:scalar-job:v1\0");
496    hash.update(plan.binding);
497    match reducer {
498        // A field-count terminal adds its admitted field identity with field_binding.
499        Reducer::Count { .. } => hash.update([0]),
500        Reducer::Numeric(state) => {
501            hash.update([state.operation as u8, state.position as u8]);
502            let output = state.output();
503            match (crate::key::operand_type(output.value), state.operation) {
504                (crate::FieldType::Float32, _) => hash.update(b"binary32-exact:v1\0"),
505                (crate::FieldType::Float64, Operation::Sum) => {
506                    hash.update(b"binary64-exact-sum:v1\0")
507                }
508                (crate::FieldType::Float64, Operation::Average) => {
509                    hash.update(b"binary64-exact-average:v1\0")
510                }
511                _ => {}
512            }
513            let mut bytes = Vec::new();
514            crate::schema::encode_type(&mut bytes, output.value, output.optional, false)?;
515            hash.update(bytes);
516        }
517        // New payload identities; existing count/sum/average bindings stay stable.
518        Reducer::Extremum {
519            position, maximum, ..
520        } => {
521            hash.update([if *maximum { 4 } else { 3 }, *position as u8]);
522        }
523        _ => return Err(Error::InvalidQuery),
524    }
525
526    Ok(hash.finalize().into())
527}
528
529fn start<M: Memory>(
530    jobs: &mut AggregateJobs<M>,
531    binding: [u8; 32],
532    revision: u64,
533    now: Timestamp,
534    expires: Timestamp,
535    accumulator: &Accumulator<'_>,
536) -> Result<JobHandle, Error> {
537    let lifetime = expires
538        .as_millis()
539        .checked_sub(now.as_millis())
540        .ok_or(Error::Limit)?;
541    if !(1..=MAX_LIFETIME_MS).contains(&lifetime) {
542        return Err(Error::Limit);
543    }
544    let (count, state) = accumulator.checkpoint()?;
545
546    jobs.insert(Record {
547        meta: storage::RecordMeta {
548            generation: 0,
549            binding,
550            revision,
551            expires,
552            observed: now,
553            sequence: 0,
554            examined: 0,
555            input_bytes: 0,
556            phase: JobOutcome::Running,
557        },
558        cursor: Vec::new(),
559        count,
560        state,
561    })
562}
563
564// One shared concrete execution path. Type conversion happens before save, outside
565// this function. Preparation errors never persist a partial accumulator or cursor.
566#[expect(
567    clippy::too_many_arguments,
568    reason = "explicit admitted query and checkpoint inputs keep the shared resume boundary local"
569)]
570fn prepare<M: Memory>(
571    db: &Database<M>,
572    entity: &EntitySchema,
573    request: Request<'_>,
574    plan: &Plan<'_>,
575    mut accumulator: Accumulator<'_>,
576    record: &mut Record,
577    expected: [u8; 32],
578    sequence: u64,
579    now: Timestamp,
580) -> Result<bool, Error> {
581    if record.meta.binding != expected || sequence > record.meta.sequence {
582        return Err(Error::InvalidJob);
583    }
584    if now < record.meta.observed {
585        return Err(Error::TimestampRegression);
586    }
587    let saved_sequence = record.meta.sequence;
588    accumulator.restore(entity, record)?;
589    if now >= record.meta.expires && !matches!(record.meta.phase, JobOutcome::Expired) {
590        record.meta.phase = JobOutcome::Expired;
591        record.meta.sequence += 1;
592    } else if matches!(record.meta.phase, JobOutcome::Running) {
593        if db.revision_by_id(entity.id)? != record.meta.revision {
594            record.meta.phase = JobOutcome::Invalidated;
595            record.meta.sequence += 1;
596        } else if sequence == record.meta.sequence {
597            execute_chunk(&db.map, entity, request, plan, &mut accumulator, record)?;
598            record.meta.sequence += 1;
599        }
600    }
601    // Every advance or phase transition increments the sequence. A later
602    // observation also needs persistence to enforce monotonic time on retries.
603    let changed = record.meta.sequence != saved_sequence || record.meta.observed != now;
604    record.meta.observed = now;
605
606    Ok(changed)
607}
608
609fn execute_chunk<M: Memory>(
610    map: &Map<M>,
611    entity: &EntitySchema,
612    request: Request<'_>,
613    plan: &Plan<'_>,
614    accumulator: &mut Accumulator<'_>,
615    record: &mut Record,
616) -> Result<(), Error> {
617    let cursor = if record.cursor.is_empty() {
618        None
619    } else {
620        let cursor = QueryCursor::from_bytes(&record.cursor)?;
621        plan.validate_cursor(entity, &cursor)?;
622
623        Some(cursor)
624    };
625    let request = Request {
626        cursor: cursor.as_ref(),
627        work: request
628            .work
629            .min((MAX_CANDIDATES - record.meta.examined) as usize),
630        ..request
631    };
632    let mut bytes = 0;
633    let page = execute_inner(
634        map,
635        entity,
636        &request,
637        plan,
638        super::super::range::bounds(entity, &request, plan)?,
639        Some(accumulator),
640        Some(&mut bytes),
641    )?;
642    record.meta.examined += page.examined as u64;
643    record.meta.input_bytes += bytes as u64;
644    record.cursor = page
645        .next
646        .as_ref()
647        .map_or_else(Vec::new, QueryCursor::to_bytes);
648    record.meta.phase = if page.next.is_none() {
649        JobOutcome::Complete(())
650    } else {
651        JobOutcome::Running
652    };
653    (record.count, record.state) = accumulator.checkpoint()?;
654
655    Ok(())
656}