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,
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#[derive(Clone, Debug, PartialEq, Eq)]
29pub struct JobHandle {
30 incarnation: [u8; 16],
31 slot: u8,
32 generation: u64,
33}
34impl JobHandle {
35 #[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 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#[derive(Debug, PartialEq, Eq)]
68pub enum JobOutcome<T> {
69 Running,
71 Complete(T),
73 Invalidated,
75 Expired,
77}
78#[derive(Debug)]
80pub struct JobStep<T> {
81 pub sequence: u64,
83 pub source_revision: u64,
85 pub examined: u64,
87 pub input_bytes: u64,
89 pub output_bytes: usize,
91 pub outcome: JobOutcome<T>,
93}
94
95impl Record {
96 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#[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 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 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 pub fn resume_count(
252 self,
253 jobs: &mut AggregateJobs<M>,
254 handle: &JobHandle,
255 sequence: u64,
256 now: Timestamp,
257 ) -> Result<JobStep<u64>, Error> {
258 observe!(resume, {
259 self.resume_count_job(jobs, handle, sequence, now, CountInput::Rows)
260 })
261 }
262
263 pub fn resume_count_field(
270 self,
271 field: &str,
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::Field(field))
279 })
280 }
281
282 fn resume_count_job(
283 self,
284 jobs: &mut AggregateJobs<M>,
285 handle: &JobHandle,
286 sequence: u64,
287 now: Timestamp,
288 input: CountInput<'_>,
289 ) -> Result<JobStep<u64>, Error> {
290 let plan = self.aggregate_plan(input.projection(), false)?;
291 let mut record = jobs.load(handle)?;
292 let (mut reducer, expected) = self.retained_count_state(&plan, input)?;
293 let bytes = self.request.bytes;
294 let changed = prepare(
295 &*self.db.read()?,
296 E::SCHEMA,
297 self.request,
298 &plan,
299 Accumulator::Scalar(&mut reducer),
300 &mut record,
301 expected,
302 sequence,
303 now,
304 )?;
305
306 record.finish_and_save(jobs, handle, changed, bytes, || {
307 Ok((reducer.finish(false)?.into_count()?, 8))
308 })
309 }
310
311 pub fn start_sum<R: Value>(
318 self,
319 jobs: &mut AggregateJobs<M>,
320 now: Timestamp,
321 expires: Timestamp,
322 ) -> Result<JobHandle, Error> {
323 observe!(start, {
324 self.start_numeric::<R>(jobs, now, expires, Operation::Sum)
325 })
326 }
327
328 pub fn resume_sum<R: Value>(
337 self,
338 jobs: &mut AggregateJobs<M>,
339 handle: &JobHandle,
340 sequence: u64,
341 now: Timestamp,
342 ) -> Result<JobStep<Option<R>>, Error> {
343 observe!(resume, {
344 self.resume_numeric::<R>(jobs, handle, sequence, now, Operation::Sum)
345 })
346 }
347
348 pub fn start_avg<R: Value>(
357 self,
358 jobs: &mut AggregateJobs<M>,
359 now: Timestamp,
360 expires: Timestamp,
361 ) -> Result<JobHandle, Error> {
362 observe!(start, {
363 self.start_numeric::<R>(jobs, now, expires, Operation::Average)
364 })
365 }
366
367 pub fn resume_avg<R: Value>(
377 self,
378 jobs: &mut AggregateJobs<M>,
379 handle: &JobHandle,
380 sequence: u64,
381 now: Timestamp,
382 ) -> Result<JobStep<Option<R>>, Error> {
383 observe!(resume, {
384 self.resume_numeric::<R>(jobs, handle, sequence, now, Operation::Average)
385 })
386 }
387
388 fn start_numeric<R: Value>(
389 self,
390 jobs: &mut AggregateJobs<M>,
391 now: Timestamp,
392 expires: Timestamp,
393 operation: Operation,
394 ) -> Result<JobHandle, Error> {
395 let (plan, mut reducer) = self.numeric_plan::<R>(None, operation)?;
396
397 start(
398 jobs,
399 binding(&plan, &reducer)?,
400 self.db.read()?.revision_by_id(E::SCHEMA.id)?,
401 now,
402 expires,
403 &Accumulator::Scalar(&mut reducer),
404 )
405 }
406
407 fn resume_numeric<R: Value>(
408 self,
409 jobs: &mut AggregateJobs<M>,
410 handle: &JobHandle,
411 sequence: u64,
412 now: Timestamp,
413 operation: Operation,
414 ) -> Result<JobStep<Option<R>>, Error> {
415 let (plan, reducer) = self.numeric_plan::<R>(None, operation)?;
416
417 self.resume_value(jobs, handle, sequence, now, (plan, reducer))
418 }
419
420 fn resume_value<R: Value>(
421 self,
422 jobs: &mut AggregateJobs<M>,
423 handle: &JobHandle,
424 sequence: u64,
425 now: Timestamp,
426 admitted: (Plan<'_>, Reducer),
427 ) -> Result<JobStep<Option<R>>, Error> {
428 let (plan, mut reducer) = admitted;
429 let mut record = jobs.load(handle)?;
430 let expected = binding(&plan, &reducer)?;
431 let limit = self.request.bytes;
432 let changed = prepare(
433 &*self.db.read()?,
434 E::SCHEMA,
435 self.request,
436 &plan,
437 Accumulator::Scalar(&mut reducer),
438 &mut record,
439 expected,
440 sequence,
441 now,
442 )?;
443
444 record.finish_and_save(jobs, handle, changed, limit, || {
445 scalar_output(reducer, limit)
446 })
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 hash.update(b"ic-db:scalar-job:v1\0");
465 hash.update(plan.binding);
466 match reducer {
467 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 Reducer::Extremum {
488 position, maximum, ..
489 } => {
490 hash.update([if *maximum { 4 } else { 3 }, *position as u8]);
491 }
492 _ => return Err(Error::InvalidQuery),
493 }
494
495 Ok(hash.finalize().into())
496}
497
498fn start<M: Memory>(
499 jobs: &mut AggregateJobs<M>,
500 binding: [u8; 32],
501 revision: u64,
502 now: Timestamp,
503 expires: Timestamp,
504 accumulator: &Accumulator<'_>,
505) -> Result<JobHandle, Error> {
506 let lifetime = expires
507 .as_millis()
508 .checked_sub(now.as_millis())
509 .ok_or(Error::Limit)?;
510 if !(1..=MAX_LIFETIME_MS).contains(&lifetime) {
511 return Err(Error::Limit);
512 }
513 let (count, state) = accumulator.checkpoint()?;
514
515 jobs.insert(Record {
516 generation: 0,
517 binding,
518 revision,
519 expires,
520 observed: now,
521 sequence: 0,
522 examined: 0,
523 input_bytes: 0,
524 phase: JobOutcome::Running,
525 cursor: Vec::new(),
526 count,
527 state,
528 })
529}
530
531#[expect(
534 clippy::too_many_arguments,
535 reason = "explicit admitted query and checkpoint inputs keep the shared resume boundary local"
536)]
537fn prepare<M: Memory>(
538 db: &Database<M>,
539 entity: &EntitySchema,
540 request: Request<'_>,
541 plan: &Plan<'_>,
542 mut accumulator: Accumulator<'_>,
543 record: &mut Record,
544 expected: [u8; 32],
545 sequence: u64,
546 now: Timestamp,
547) -> Result<bool, Error> {
548 if record.binding != expected || sequence > record.sequence {
549 return Err(Error::InvalidJob);
550 }
551 if now < record.observed {
552 return Err(Error::TimestampRegression);
553 }
554 let saved_sequence = record.sequence;
555 accumulator.restore(entity, record)?;
556 if now >= record.expires && !matches!(record.phase, JobOutcome::Expired) {
557 record.phase = JobOutcome::Expired;
558 record.sequence += 1;
559 } else if matches!(record.phase, JobOutcome::Running) {
560 if db.revision_by_id(entity.id)? != record.revision {
561 record.phase = JobOutcome::Invalidated;
562 record.sequence += 1;
563 } else if sequence == record.sequence {
564 let cursor = if record.cursor.is_empty() {
565 None
566 } else {
567 let cursor = QueryCursor::from_bytes(&record.cursor)?;
568 if cursor.binding != plan.binding {
569 return Err(Error::Corrupt);
570 }
571 plan.validate_position(entity, &cursor)?;
572
573 Some(cursor)
574 };
575 let request = Request {
576 cursor: cursor.as_ref(),
577 work: request
578 .work
579 .min((MAX_CANDIDATES - record.examined) as usize),
580 ..request
581 };
582 let mut bytes = 0;
583 let page = execute_inner(
584 &db.map,
585 entity,
586 &request,
587 plan,
588 super::super::range::bounds(entity, &request, plan)?,
589 Some(&mut accumulator),
590 Some(&mut bytes),
591 )?;
592 record.examined += page.examined as u64;
593 record.input_bytes += bytes as u64;
594 record.cursor = page
595 .next
596 .as_ref()
597 .map_or_else(Vec::new, QueryCursor::to_bytes);
598 record.phase = if page.next.is_none() {
599 JobOutcome::Complete(())
600 } else {
601 JobOutcome::Running
602 };
603 record.sequence += 1;
604 (record.count, record.state) = accumulator.checkpoint()?;
605 }
606 }
607 let changed = record.sequence != saved_sequence || record.observed != now;
610 record.observed = now;
611
612 Ok(changed)
613}