1mod 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, decode_record,
16 numeric::Operation,
17};
18use crate::{Entity, EntitySchema, Error, Timestamp, Value};
19use ic_storage::Memory;
20use sha2::{Digest, Sha256};
21use storage::Record;
22
23const MAX_CANDIDATES: u64 = 1_000_000;
24const MAX_LIFETIME_MS: i64 = 3_600_000;
25
26#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct JobHandle {
29 incarnation: [u8; 16],
30 slot: u8,
31 generation: u64,
32}
33impl JobHandle {
34 #[must_use]
36 pub fn to_bytes(&self) -> Vec<u8> {
37 let mut bytes = vec![1, self.slot];
38 bytes.extend(self.incarnation);
39 bytes.extend(self.generation.to_le_bytes());
40
41 bytes
42 }
43
44 pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
48 if bytes.len() != 26 || bytes[0] != 1 || !(1..=storage::SLOTS).contains(&bytes[1]) {
49 return Err(Error::InvalidJob);
50 }
51 let incarnation = bytes[2..18].try_into().map_err(|_| Error::InvalidJob)?;
52 let generation = u64::from_le_bytes(bytes[18..].try_into().map_err(|_| Error::InvalidJob)?);
53 if incarnation == [0; 16] || generation == 0 {
54 return Err(Error::InvalidJob);
55 }
56
57 Ok(Self {
58 incarnation,
59 slot: bytes[1],
60 generation,
61 })
62 }
63}
64
65#[derive(Debug, PartialEq, Eq)]
67pub enum JobOutcome<T> {
68 Running,
70 Complete(T),
72 Invalidated,
74 Expired,
76}
77#[derive(Debug)]
79pub struct JobStep<T> {
80 pub sequence: u64,
82 pub source_revision: u64,
84 pub examined: u64,
86 pub input_bytes: u64,
88 pub output_bytes: usize,
90 pub outcome: JobOutcome<T>,
92}
93
94impl Record {
95 fn finish_and_save<T, M: Memory>(
98 &self,
99 jobs: &mut AggregateJobs<M>,
100 handle: &JobHandle,
101 changed: bool,
102 limit: usize,
103 finish: impl FnOnce() -> Result<(T, usize), Error>,
104 ) -> Result<JobStep<T>, Error> {
105 let (outcome, output_bytes) = match self.phase {
106 JobOutcome::Running => (JobOutcome::Running, 0),
107 JobOutcome::Invalidated => (JobOutcome::Invalidated, 0),
108 JobOutcome::Expired => (JobOutcome::Expired, 0),
109 JobOutcome::Complete(()) => {
110 let (value, bytes) = finish()?;
111 if bytes > limit {
112 return Err(Error::RowTooLarge);
113 }
114
115 (JobOutcome::Complete(value), bytes)
116 }
117 };
118 jobs.save_if_changed(handle, self, changed)?;
119
120 Ok(JobStep {
121 sequence: self.sequence,
122 source_revision: self.revision,
123 examined: self.examined,
124 input_bytes: self.input_bytes,
125 output_bytes,
126 outcome,
127 })
128 }
129}
130
131impl<E: Entity, M: Memory> Query<'_, E, M> {
132 pub fn start_count(
141 self,
142 jobs: &mut AggregateJobs<M>,
143 now: Timestamp,
144 expires: Timestamp,
145 ) -> Result<JobHandle, Error> {
146 observe!(start, { self.start_count_job(jobs, now, expires, None) })
147 }
148
149 pub fn start_count_field(
157 self,
158 field: &str,
159 jobs: &mut AggregateJobs<M>,
160 now: Timestamp,
161 expires: Timestamp,
162 ) -> Result<JobHandle, Error> {
163 observe!(start, {
164 self.start_count_job(jobs, now, expires, Some(field))
165 })
166 }
167
168 fn start_count_job(
169 self,
170 jobs: &mut AggregateJobs<M>,
171 now: Timestamp,
172 expires: Timestamp,
173 field: Option<&str>,
174 ) -> Result<JobHandle, Error> {
175 let plan = self.aggregate_plan(None, false)?;
176 let mut reducer = self.count_reducer(field)?;
177 if self.request.bytes < 8 {
178 return Err(Error::RowTooLarge);
179 }
180
181 start(
182 jobs,
183 field_binding(binding(&plan, &reducer)?, field),
184 self.db.read()?.revision_by_id(E::SCHEMA.id)?,
185 now,
186 expires,
187 &Accumulator::Scalar(&mut reducer),
188 )
189 }
190
191 pub fn resume_count(
203 self,
204 jobs: &mut AggregateJobs<M>,
205 handle: &JobHandle,
206 sequence: u64,
207 now: Timestamp,
208 ) -> Result<JobStep<u64>, Error> {
209 observe!(resume, {
210 self.resume_count_job(jobs, handle, sequence, now, None)
211 })
212 }
213
214 pub fn resume_count_field(
221 self,
222 field: &str,
223 jobs: &mut AggregateJobs<M>,
224 handle: &JobHandle,
225 sequence: u64,
226 now: Timestamp,
227 ) -> Result<JobStep<u64>, Error> {
228 observe!(resume, {
229 self.resume_count_job(jobs, handle, sequence, now, Some(field))
230 })
231 }
232
233 fn resume_count_job(
234 self,
235 jobs: &mut AggregateJobs<M>,
236 handle: &JobHandle,
237 sequence: u64,
238 now: Timestamp,
239 field: Option<&str>,
240 ) -> Result<JobStep<u64>, Error> {
241 let plan = self.aggregate_plan(None, false)?;
242 let mut record = jobs.load(handle)?;
243 let mut reducer = self.count_reducer(field)?;
244 let expected = field_binding(binding(&plan, &reducer)?, field);
245 let bytes = self.request.bytes;
246 let changed = prepare(
247 &*self.db.read()?,
248 E::SCHEMA,
249 self.request,
250 &plan,
251 Accumulator::Scalar(&mut reducer),
252 &mut record,
253 expected,
254 sequence,
255 now,
256 )?;
257
258 record.finish_and_save(jobs, handle, changed, bytes, || {
259 Ok((reducer.finish()?.into_count()?, 8))
260 })
261 }
262
263 pub fn start_sum<R: Value>(
270 self,
271 jobs: &mut AggregateJobs<M>,
272 now: Timestamp,
273 expires: Timestamp,
274 ) -> Result<JobHandle, Error> {
275 observe!(start, {
276 self.start_numeric::<R>(jobs, now, expires, Operation::Sum)
277 })
278 }
279
280 pub fn resume_sum<R: Value>(
289 self,
290 jobs: &mut AggregateJobs<M>,
291 handle: &JobHandle,
292 sequence: u64,
293 now: Timestamp,
294 ) -> Result<JobStep<Option<R>>, Error> {
295 observe!(resume, {
296 self.resume_numeric::<R>(jobs, handle, sequence, now, Operation::Sum)
297 })
298 }
299
300 pub fn start_avg<R: Value>(
309 self,
310 jobs: &mut AggregateJobs<M>,
311 now: Timestamp,
312 expires: Timestamp,
313 ) -> Result<JobHandle, Error> {
314 observe!(start, {
315 self.start_numeric::<R>(jobs, now, expires, Operation::Average)
316 })
317 }
318
319 pub fn resume_avg<R: Value>(
329 self,
330 jobs: &mut AggregateJobs<M>,
331 handle: &JobHandle,
332 sequence: u64,
333 now: Timestamp,
334 ) -> Result<JobStep<Option<R>>, Error> {
335 observe!(resume, {
336 self.resume_numeric::<R>(jobs, handle, sequence, now, Operation::Average)
337 })
338 }
339
340 fn start_numeric<R: Value>(
341 self,
342 jobs: &mut AggregateJobs<M>,
343 now: Timestamp,
344 expires: Timestamp,
345 operation: Operation,
346 ) -> Result<JobHandle, Error> {
347 let (plan, mut reducer) = self.numeric_plan::<R>(None, operation)?;
348
349 start(
350 jobs,
351 binding(&plan, &reducer)?,
352 self.db.read()?.revision_by_id(E::SCHEMA.id)?,
353 now,
354 expires,
355 &Accumulator::Scalar(&mut reducer),
356 )
357 }
358
359 fn resume_numeric<R: Value>(
360 self,
361 jobs: &mut AggregateJobs<M>,
362 handle: &JobHandle,
363 sequence: u64,
364 now: Timestamp,
365 operation: Operation,
366 ) -> Result<JobStep<Option<R>>, Error> {
367 let (plan, reducer) = self.numeric_plan::<R>(None, operation)?;
368
369 self.resume_value(jobs, handle, sequence, now, (plan, reducer))
370 }
371
372 fn resume_value<R: Value>(
373 self,
374 jobs: &mut AggregateJobs<M>,
375 handle: &JobHandle,
376 sequence: u64,
377 now: Timestamp,
378 admitted: (Plan<'_>, Reducer),
379 ) -> Result<JobStep<Option<R>>, Error> {
380 let (plan, mut reducer) = admitted;
381 let mut record = jobs.load(handle)?;
382 let expected = binding(&plan, &reducer)?;
383 let limit = self.request.bytes;
384 let changed = prepare(
385 &*self.db.read()?,
386 E::SCHEMA,
387 self.request,
388 &plan,
389 Accumulator::Scalar(&mut reducer),
390 &mut record,
391 expected,
392 sequence,
393 now,
394 )?;
395
396 record.finish_and_save(jobs, handle, changed, limit, || {
397 let bytes = reducer.finish()?.into_value()?;
398 let size = bytes.as_ref().map_or(0, Vec::len);
399 let value = bytes.as_deref().map(decode_record).transpose()?;
400
401 Ok((value, size))
402 })
403 }
404}
405fn field_binding(binding: [u8; 32], field: Option<&str>) -> [u8; 32] {
406 let Some(field) = field else { return binding };
407 let mut hash = Sha256::new();
408 hash.update(b"ic-db:field-count-job:v1\0");
409 hash.update(binding);
410 hash.update((field.len() as u32).to_le_bytes());
411 hash.update(field.as_bytes());
412
413 hash.finalize().into()
414}
415
416fn binding(plan: &Plan<'_>, reducer: &Reducer) -> Result<[u8; 32], Error> {
417 let mut hash = Sha256::new();
418 hash.update(b"ic-db:scalar-job:v1\0");
421 hash.update(plan.binding);
422 match reducer {
423 Reducer::Count { .. } => hash.update([0]),
425 Reducer::Numeric(state) => {
426 hash.update([state.operation as u8, state.position as u8]);
427 let output = state.output();
428 match (crate::key::operand_type(output.value), state.operation) {
429 (crate::FieldType::Float32, _) => hash.update(b"binary32-exact:v1\0"),
430 (crate::FieldType::Float64, Operation::Sum) => {
431 hash.update(b"binary64-exact-sum:v1\0")
432 }
433 (crate::FieldType::Float64, Operation::Average) => {
434 hash.update(b"binary64-exact-average:v1\0")
435 }
436 _ => {}
437 }
438 let mut bytes = Vec::new();
439 crate::schema::encode_type(&mut bytes, output.value, output.optional, false)?;
440 hash.update(bytes);
441 }
442 Reducer::Extremum {
444 position, maximum, ..
445 } => {
446 hash.update([if *maximum { 4 } else { 3 }, *position as u8]);
447 }
448 _ => return Err(Error::InvalidQuery),
449 }
450
451 Ok(hash.finalize().into())
452}
453
454fn start<M: Memory>(
455 jobs: &mut AggregateJobs<M>,
456 binding: [u8; 32],
457 revision: u64,
458 now: Timestamp,
459 expires: Timestamp,
460 accumulator: &Accumulator<'_>,
461) -> Result<JobHandle, Error> {
462 let lifetime = expires
463 .as_millis()
464 .checked_sub(now.as_millis())
465 .ok_or(Error::Limit)?;
466 if !(1..=MAX_LIFETIME_MS).contains(&lifetime) {
467 return Err(Error::Limit);
468 }
469 let (count, state) = accumulator.checkpoint()?;
470
471 jobs.insert(Record {
472 generation: 0,
473 binding,
474 revision,
475 expires,
476 observed: now,
477 sequence: 0,
478 examined: 0,
479 input_bytes: 0,
480 phase: JobOutcome::Running,
481 cursor: Vec::new(),
482 count,
483 state,
484 })
485}
486
487#[expect(
490 clippy::too_many_arguments,
491 reason = "explicit admitted query and checkpoint inputs keep the shared resume boundary local"
492)]
493fn prepare<M: Memory>(
494 db: &Database<M>,
495 entity: &EntitySchema,
496 request: Request<'_>,
497 plan: &Plan<'_>,
498 mut accumulator: Accumulator<'_>,
499 record: &mut Record,
500 expected: [u8; 32],
501 sequence: u64,
502 now: Timestamp,
503) -> Result<bool, Error> {
504 if record.binding != expected || sequence > record.sequence {
505 return Err(Error::InvalidJob);
506 }
507 if now < record.observed {
508 return Err(Error::TimestampRegression);
509 }
510 let saved_sequence = record.sequence;
511 accumulator.restore(entity, record)?;
512 if now >= record.expires && !matches!(record.phase, JobOutcome::Expired) {
513 record.phase = JobOutcome::Expired;
514 record.sequence += 1;
515 } else if matches!(record.phase, JobOutcome::Running) {
516 if db.revision_by_id(entity.id)? != record.revision {
517 record.phase = JobOutcome::Invalidated;
518 record.sequence += 1;
519 } else if sequence == record.sequence {
520 let cursor = if record.cursor.is_empty() {
521 None
522 } else {
523 let cursor = QueryCursor::from_bytes(&record.cursor)?;
524 if cursor.binding != plan.binding {
525 return Err(Error::Corrupt);
526 }
527 plan.validate_position(entity, &cursor)?;
528
529 Some(cursor)
530 };
531 let request = Request {
532 cursor: cursor.as_ref(),
533 work: request
534 .work
535 .min((MAX_CANDIDATES - record.examined) as usize),
536 ..request
537 };
538 let mut bytes = 0;
539 let page = execute_inner(
540 &db.map,
541 entity,
542 &request,
543 plan,
544 Some(&mut accumulator),
545 Some(&mut bytes),
546 )?;
547 record.examined += page.examined as u64;
548 record.input_bytes += bytes as u64;
549 record.cursor = page
550 .next
551 .as_ref()
552 .map_or_else(Vec::new, QueryCursor::to_bytes);
553 record.phase = if page.next.is_none() {
554 JobOutcome::Complete(())
555 } else {
556 JobOutcome::Running
557 };
558 record.sequence += 1;
559 (record.count, record.state) = accumulator.checkpoint()?;
560 }
561 }
562 let changed = record.sequence != saved_sequence || record.observed != now;
565 record.observed = now;
566
567 Ok(changed)
568}