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