ic-db 0.23.2

Experimental embedded Internet Computer database
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
//! Retained aggregates: exact input revision, atomic progress, explicit retry.
mod checkpoint;
mod distinct;
mod extrema;
mod grouped;
pub(super) mod pages;
mod storage;
pub use pages::{GroupCursor, GroupPage};
pub use storage::AggregateJobs;

use super::super::{Database, Plan, Query, QueryCursor, Request, execute_inner};
use super::{Accumulator, Reducer, decode_record, numeric::Operation};
use crate::{Entity, EntitySchema, Error, Timestamp, Value};
use ic_storage::Memory;
use sha2::{Digest, Sha256};
use storage::Record;

const MAX_CANDIDATES: u64 = 1_000_000;
const MAX_LIFETIME_MS: i64 = 3_600_000;

/// Opaque retained-job identity. The host must check caller authorization separately.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct JobHandle {
    incarnation: [u8; 16],
    slot: u8,
    generation: u64,
}
impl JobHandle {
    /// Encode an exact, bounded transport handle; no query or accumulator travels in it.
    #[must_use]
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut bytes = vec![1, self.slot];
        bytes.extend(self.incarnation);
        bytes.extend(self.generation.to_le_bytes());
        bytes
    }
    /// Decode framing; the job store also validates incarnation and slot generation.
    /// # Errors
    /// Refuses unsupported, malformed, zero or oversized handles.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
        if bytes.len() != 26 || bytes[0] != 1 || !(1..=storage::SLOTS).contains(&bytes[1]) {
            return Err(Error::InvalidJob);
        }
        let incarnation = bytes[2..18].try_into().map_err(|_| Error::InvalidJob)?;
        let generation = u64::from_le_bytes(bytes[18..].try_into().map_err(|_| Error::InvalidJob)?);
        if incarnation == [0; 16] || generation == 0 {
            return Err(Error::InvalidJob);
        }
        Ok(Self {
            incarnation,
            slot: bytes[1],
            generation,
        })
    }
}

/// Only Complete contains a result. Running never exposes a prefix as an exact total.
#[derive(Debug, PartialEq, Eq)]
pub enum JobOutcome<T> {
    /// More input remains, or exhaustion has not yet been observed.
    Running,
    /// Exact result for the captured source revision, retained until expiry/cancellation.
    Complete(T),
    /// The source entity changed before completion. Start a new job explicitly.
    Invalidated,
    /// The host-captured time reached the fixed expiry. Cleanup is explicit.
    Expired,
}
/// Saved progress. Older sequences do not rescan; revision and expiry checks still apply.
#[derive(Debug)]
pub struct JobStep<T> {
    /// Supply this sequence on the next advance. Newly created jobs start at zero.
    pub sequence: u64,
    /// Entity revision captured at creation, including for completed historical results.
    pub source_revision: u64,
    /// Cumulative examined primary/index candidates, including residual nonmatches.
    pub examined: u64,
    /// Cumulative source row/key bytes, excluding supplier traversal/allocator overhead.
    pub input_bytes: u64,
    /// Encoded returned result/page size; zero while no result is available.
    pub output_bytes: usize,
    /// Explicit progress, completion, invalidation or expiry.
    pub outcome: JobOutcome<T>,
}
impl<T> JobStep<T> {
    fn try_map<R>(self, f: impl FnOnce(T) -> Result<R, Error>) -> Result<JobStep<R>, Error> {
        Ok(JobStep {
            sequence: self.sequence,
            source_revision: self.source_revision,
            examined: self.examined,
            input_bytes: self.input_bytes,
            output_bytes: self.output_bytes,
            outcome: match self.outcome {
                JobOutcome::Running => JobOutcome::Running,
                JobOutcome::Invalidated => JobOutcome::Invalidated,
                JobOutcome::Expired => JobOutcome::Expired,
                JobOutcome::Complete(value) => JobOutcome::Complete(f(value)?),
            },
        })
    }
}

impl JobStep<()> {
    // Conversion and output refusal happen before saving the prepared checkpoint.
    fn finish<T>(
        self,
        limit: usize,
        finish: impl FnOnce() -> Result<(T, usize), Error>,
    ) -> Result<JobStep<T>, Error> {
        let mut output_bytes = 0;
        let mut step = self.try_map(|()| {
            let (value, bytes) = finish()?;
            if bytes > limit {
                return Err(Error::RowTooLarge);
            }
            output_bytes = bytes;
            Ok(value)
        })?;
        step.output_bytes = output_bytes;
        Ok(step)
    }
}

impl<E: Entity, M: Memory> Query<'_, E, M> {
    /// Retain an exact count job without scanning input. Expiry must be after the
    /// host-captured `now` and at most one hour later. No write freeze is acquired.
    /// Reconstruct this fluent query on every advance; predicates/access path bind
    /// the job, while work/output limits may change. Limit never truncates input.
    /// # Errors
    /// Ordinary count admission, invalid expiry, or all 16 retained slots occupied.
    /// # Panics
    /// Supplier mutation failures trap the enclosing message.
    pub fn start_count<J: Memory>(
        self,
        jobs: &mut AggregateJobs<J>,
        now: Timestamp,
        expires: Timestamp,
    ) -> Result<JobHandle, Error> {
        self.start_count_job(jobs, now, expires, None)
    }

    /// Retain the count of present values in a named top-level field, of any stored
    /// type. Empty values count; absent values do not. The field binds the job,
    /// even for a required field. Uses `start_count`'s limits and expiry contract.
    /// # Errors
    /// Refuses unknown fields and ordinary count-job admission failures.
    /// # Panics
    /// Supplier mutation failures trap the enclosing message.
    pub fn start_count_field(
        self,
        field: &str,
        jobs: &mut AggregateJobs<impl Memory>,
        now: Timestamp,
        expires: Timestamp,
    ) -> Result<JobHandle, Error> {
        self.start_count_job(jobs, now, expires, Some(field))
    }

    fn start_count_job(
        self,
        jobs: &mut AggregateJobs<impl Memory>,
        now: Timestamp,
        expires: Timestamp,
        field: Option<&str>,
    ) -> Result<JobHandle, Error> {
        let plan = self.aggregate_plan(None, false)?;
        let reducer = self.count_reducer(field)?;
        if self.request.bytes < 8 {
            return Err(Error::RowTooLarge);
        }
        start(
            jobs,
            field_binding(binding(&plan, &reducer)?, field),
            self.db.revision_by_id(E::ID)?,
            now,
            expires,
            vec![0; 32],
        )
    }

    /// Advance count within `work_limit` (1..=512) and 64 KiB of source row/key
    /// bytes. Each job admits at most one million examined candidates. A budget
    /// boundary returns Running; it never changes the mathematical input set.
    /// Supply zero first, then the last returned sequence. An older sequence only
    /// reads saved progress; a future sequence refuses. Source changes invalidate
    /// running jobs, including on retries; completed results keep their boundary.
    /// # Errors
    /// Refuses a foreign query/handle, future sequence, backward host time, resource
    /// bounds or corruption without changing progress. No automatic restart.
    /// # Panics
    /// Supplier mutation failures trap the enclosing message.
    pub fn resume_count<J: Memory>(
        self,
        jobs: &mut AggregateJobs<J>,
        handle: &JobHandle,
        sequence: u64,
        now: Timestamp,
    ) -> Result<JobStep<u64>, Error> {
        self.resume_count_job(jobs, handle, sequence, now, None)
    }

    /// Advance the present-field count with `resume_count`'s bounds, revision,
    /// retry and expiry rules. Empty/all-absent input completes with zero.
    /// # Errors
    /// Refuses changed fields, row-count jobs and ordinary count resume failures.
    /// # Panics
    /// Supplier mutation failures trap the enclosing message.
    pub fn resume_count_field(
        self,
        field: &str,
        jobs: &mut AggregateJobs<impl Memory>,
        handle: &JobHandle,
        sequence: u64,
        now: Timestamp,
    ) -> Result<JobStep<u64>, Error> {
        self.resume_count_job(jobs, handle, sequence, now, Some(field))
    }

    fn resume_count_job(
        self,
        jobs: &mut AggregateJobs<impl Memory>,
        handle: &JobHandle,
        sequence: u64,
        now: Timestamp,
        field: Option<&str>,
    ) -> Result<JobStep<u64>, Error> {
        let plan = self.aggregate_plan(None, false)?;
        let mut record = jobs.load(handle)?;
        let mut reducer = self.count_reducer(field)?;
        let expected = field_binding(binding(&plan, &reducer)?, field);
        let bytes = self.request.bytes;
        let step = prepare(
            self.db,
            E::SCHEMA,
            self.request,
            &plan,
            Accumulator::Scalar(&mut reducer),
            &mut record,
            expected,
            sequence,
            now,
        )?
        .finish(bytes, || Ok((reducer.finish()?.into_count()?, 8)))?;
        jobs.save(handle, &record)?;
        Ok(step)
    }

    /// Retain an integer/Decimal sum job with synchronous sum's exact result shape.
    /// Same expiry, capacity and query-binding contract as [`Self::start_count`].
    /// # Errors
    /// Refuses unsupported sum shapes, query admission, expiry or occupied capacity.
    /// # Panics
    /// Supplier mutation failures trap the enclosing message.
    pub fn start_sum<R: Value>(
        self,
        jobs: &mut AggregateJobs<impl Memory>,
        now: Timestamp,
        expires: Timestamp,
    ) -> Result<JobHandle, Error> {
        self.start_numeric::<R>(jobs, now, expires, Operation::Sum)
    }

    /// Advance exact sum under count's work/retry/invalidation contract. Check the
    /// declared result width only after all input completes, allowing signed
    /// prefixes to cancel across messages. Empty/all-absent input completes as None.
    /// # Errors
    /// Count's refusals plus arithmetic overflow or completed-result byte limits.
    /// A refused finalization preserves the previous checkpoint.
    /// # Panics
    /// Supplier mutation failures trap the enclosing message.
    pub fn resume_sum<R: Value>(
        self,
        jobs: &mut AggregateJobs<impl Memory>,
        handle: &JobHandle,
        sequence: u64,
        now: Timestamp,
    ) -> Result<JobStep<Option<R>>, Error> {
        self.resume_numeric::<R>(jobs, handle, sequence, now, Operation::Sum)
    }

    /// Retain an exact integer/Decimal average. R declares one Decimal field
    /// with the source name and optionality, and its desired result scale (0–28).
    /// Shares count/sum's expiry, capacity and revision contract. Average versus
    /// sum and the result scale are bound to the job; they cannot change on resume.
    /// # Errors
    /// Refuses unsupported average shapes, query admission, expiry or occupied capacity.
    /// # Panics
    /// Supplier mutation failures trap the enclosing message.
    pub fn start_avg<R: Value>(
        self,
        jobs: &mut AggregateJobs<impl Memory>,
        now: Timestamp,
        expires: Timestamp,
    ) -> Result<JobHandle, Error> {
        self.start_numeric::<R>(jobs, now, expires, Operation::Average)
    }

    /// Advance average under count's bounded work/retry/invalidation contract.
    /// Retain the exact total and present count across steps; divide and round once
    /// at completion to the declared Decimal scale, nearest with ties to even.
    /// Empty/all-absent input completes as None. Never average rounded page means.
    /// # Errors
    /// Count's refusals plus arithmetic overflow or completed-result byte limits.
    /// A refused finalization preserves the prior exact checkpoint; no scale fallback.
    /// # Panics
    /// Supplier mutation failures trap the enclosing message.
    pub fn resume_avg<R: Value>(
        self,
        jobs: &mut AggregateJobs<impl Memory>,
        handle: &JobHandle,
        sequence: u64,
        now: Timestamp,
    ) -> Result<JobStep<Option<R>>, Error> {
        self.resume_numeric::<R>(jobs, handle, sequence, now, Operation::Average)
    }

    fn start_numeric<R: Value>(
        self,
        jobs: &mut AggregateJobs<impl Memory>,
        now: Timestamp,
        expires: Timestamp,
        operation: Operation,
    ) -> Result<JobHandle, Error> {
        let (plan, reducer) = self.numeric_plan::<R>(None, operation)?;
        start(
            jobs,
            binding(&plan, &reducer)?,
            self.db.revision_by_id(E::ID)?,
            now,
            expires,
            vec![0; 32],
        )
    }

    fn resume_numeric<R: Value>(
        self,
        jobs: &mut AggregateJobs<impl Memory>,
        handle: &JobHandle,
        sequence: u64,
        now: Timestamp,
        operation: Operation,
    ) -> Result<JobStep<Option<R>>, Error> {
        let (plan, reducer) = self.numeric_plan::<R>(None, operation)?;
        self.resume_value(jobs, handle, sequence, now, (plan, reducer))
    }

    fn resume_value<R: Value>(
        self,
        jobs: &mut AggregateJobs<impl Memory>,
        handle: &JobHandle,
        sequence: u64,
        now: Timestamp,
        admitted: (Plan<'_>, Reducer),
    ) -> Result<JobStep<Option<R>>, Error> {
        let (plan, mut reducer) = admitted;
        let mut record = jobs.load(handle)?;
        let expected = binding(&plan, &reducer)?;
        let limit = self.request.bytes;
        let step = prepare(
            self.db,
            E::SCHEMA,
            self.request,
            &plan,
            Accumulator::Scalar(&mut reducer),
            &mut record,
            expected,
            sequence,
            now,
        )?
        .finish(limit, || {
            let bytes = reducer.finish()?.into_value()?;
            let size = bytes.as_ref().map_or(0, Vec::len);
            let value = bytes.as_deref().map(decode_record).transpose()?;
            Ok((value, size))
        })?;
        jobs.save(handle, &record)?;
        Ok(step)
    }
}
fn field_binding(binding: [u8; 32], field: Option<&str>) -> [u8; 32] {
    let Some(field) = field else { return binding };
    let mut hash = Sha256::new();
    hash.update(b"ic-db:field-count-job:v1\0");
    hash.update(binding);
    hash.update((field.len() as u32).to_le_bytes());
    hash.update(field.as_bytes());
    hash.finalize().into()
}

fn binding(plan: &Plan<'_>, reducer: &Reducer) -> Result<[u8; 32], Error> {
    let mut hash = Sha256::new();
    // Algorithm identity is independent of the row schema. Changing checkpoint or
    // accumulation semantics requires a new identity and explicit resume support.
    hash.update(b"ic-db:scalar-job:v1\0");
    hash.update(plan.binding);
    match reducer {
        // A field-count terminal adds its admitted field identity with field_binding.
        Reducer::Count { .. } => hash.update([0]),
        Reducer::Numeric(state) => {
            hash.update([state.operation as u8, state.position as u8]);
            let output = state.output();
            let mut bytes = Vec::new();
            crate::schema::encode_type(&mut bytes, output.value, output.optional, false)?;
            hash.update(bytes);
        }
        // New payload identities; existing count/sum/average bindings stay stable.
        Reducer::Extremum {
            position, maximum, ..
        } => {
            hash.update([if *maximum { 4 } else { 3 }, *position as u8]);
        }
        _ => return Err(Error::InvalidQuery),
    }
    Ok(hash.finalize().into())
}
fn start<M: Memory>(
    jobs: &mut AggregateJobs<M>,
    binding: [u8; 32],
    revision: u64,
    now: Timestamp,
    expires: Timestamp,
    state: Vec<u8>,
) -> Result<JobHandle, Error> {
    let lifetime = expires
        .as_millis()
        .checked_sub(now.as_millis())
        .ok_or(Error::Limit)?;
    if !(1..=MAX_LIFETIME_MS).contains(&lifetime) {
        return Err(Error::Limit);
    }
    jobs.insert(Record {
        generation: 0,
        binding,
        revision,
        expires,
        observed: now,
        sequence: 0,
        examined: 0,
        input_bytes: 0,
        phase: JobOutcome::Running,
        cursor: Vec::new(),
        count: 0,
        state,
    })
}

// One shared concrete execution path. Type conversion happens before save, outside
// this function. Preparation errors never persist a partial accumulator or cursor.
#[expect(
    clippy::too_many_arguments,
    reason = "explicit admitted query and checkpoint inputs keep the shared resume boundary local"
)]
fn prepare<M: Memory>(
    db: &Database<M>,
    entity: &EntitySchema,
    request: Request<'_>,
    plan: &Plan<'_>,
    mut accumulator: Accumulator<'_>,
    record: &mut Record,
    expected: [u8; 32],
    sequence: u64,
    now: Timestamp,
) -> Result<JobStep<()>, Error> {
    if record.binding != expected || sequence > record.sequence {
        return Err(Error::InvalidJob);
    }
    if now < record.observed {
        return Err(Error::TimestampRegression);
    }
    accumulator.restore(entity, record)?;
    if now >= record.expires && !matches!(record.phase, JobOutcome::Expired) {
        record.phase = JobOutcome::Expired;
        record.sequence += 1;
    } else if matches!(record.phase, JobOutcome::Running) {
        if db.revision_by_id(entity.id)? != record.revision {
            record.phase = JobOutcome::Invalidated;
            record.sequence += 1;
        } else if sequence == record.sequence {
            let cursor = if record.cursor.is_empty() {
                None
            } else {
                let cursor = QueryCursor::from_bytes(&record.cursor)?;
                if cursor.binding != plan.binding {
                    return Err(Error::Corrupt);
                }
                plan.validate_position(entity, &cursor.position)?;
                Some(cursor)
            };
            let request = Request {
                cursor: cursor.as_ref(),
                work: request
                    .work
                    .min((MAX_CANDIDATES - record.examined) as usize),
                ..request
            };
            let mut bytes = 0;
            let page = execute_inner(
                &db.map,
                entity,
                &request,
                plan,
                Some(&mut accumulator),
                Some(&mut bytes),
            )?;
            record.examined += page.examined as u64;
            record.input_bytes += bytes as u64;
            record.cursor = page
                .next
                .as_ref()
                .map_or_else(Vec::new, QueryCursor::to_bytes);
            record.phase = if page.next.is_none() {
                JobOutcome::Complete(())
            } else {
                JobOutcome::Running
            };
            record.sequence += 1;
            accumulator.checkpoint(record)?;
        }
    }
    record.observed = now;
    let outcome = match record.phase {
        JobOutcome::Running => JobOutcome::Running,
        JobOutcome::Invalidated => JobOutcome::Invalidated,
        JobOutcome::Expired => JobOutcome::Expired,
        JobOutcome::Complete(()) => JobOutcome::Complete(()),
    };
    Ok(JobStep {
        sequence: record.sequence,
        source_revision: record.revision,
        examined: record.examined,
        input_bytes: record.input_bytes,
        output_bytes: 0,
        outcome,
    })
}