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(
250 self,
251 jobs: &mut AggregateJobs<M>,
252 handle: &JobHandle,
253 sequence: u64,
254 now: Timestamp,
255 ) -> Result<JobStep<u64>, Error> {
256 observe!(resume, {
257 self.resume_count_job(jobs, handle, sequence, now, CountInput::Rows)
258 })
259 }
260
261 pub fn resume_count_field(
268 self,
269 field: &str,
270 jobs: &mut AggregateJobs<M>,
271 handle: &JobHandle,
272 sequence: u64,
273 now: Timestamp,
274 ) -> Result<JobStep<u64>, Error> {
275 observe!(resume, {
276 self.resume_count_job(jobs, handle, sequence, now, CountInput::Field(field))
277 })
278 }
279
280 fn resume_count_job(
281 self,
282 jobs: &mut AggregateJobs<M>,
283 handle: &JobHandle,
284 sequence: u64,
285 now: Timestamp,
286 input: CountInput<'_>,
287 ) -> Result<JobStep<u64>, Error> {
288 let plan = self.aggregate_plan(input.projection(), false)?;
289 let mut record = jobs.load(handle)?;
290 let (mut reducer, expected) = self.retained_count_state(&plan, input)?;
291 let bytes = self.request.bytes;
292 let changed = prepare(
293 &*self.db.read()?,
294 E::SCHEMA,
295 self.request,
296 &plan,
297 Accumulator::Scalar(&mut reducer),
298 &mut record,
299 expected,
300 sequence,
301 now,
302 )?;
303
304 record.finish_and_save(jobs, handle, changed, bytes, || {
305 Ok((reducer.finish(false)?.into_count()?, 8))
306 })
307 }
308
309 pub fn start_sum<R: Value>(
316 self,
317 jobs: &mut AggregateJobs<M>,
318 now: Timestamp,
319 expires: Timestamp,
320 ) -> Result<JobHandle, Error> {
321 observe!(start, {
322 self.start_numeric::<R>(jobs, now, expires, Operation::Sum)
323 })
324 }
325
326 pub fn resume_sum<R: Value>(
335 self,
336 jobs: &mut AggregateJobs<M>,
337 handle: &JobHandle,
338 sequence: u64,
339 now: Timestamp,
340 ) -> Result<JobStep<Option<R>>, Error> {
341 observe!(resume, {
342 self.resume_numeric::<R>(jobs, handle, sequence, now, Operation::Sum)
343 })
344 }
345
346 pub fn start_avg<R: Value>(
355 self,
356 jobs: &mut AggregateJobs<M>,
357 now: Timestamp,
358 expires: Timestamp,
359 ) -> Result<JobHandle, Error> {
360 observe!(start, {
361 self.start_numeric::<R>(jobs, now, expires, Operation::Average)
362 })
363 }
364
365 pub fn resume_avg<R: Value>(
375 self,
376 jobs: &mut AggregateJobs<M>,
377 handle: &JobHandle,
378 sequence: u64,
379 now: Timestamp,
380 ) -> Result<JobStep<Option<R>>, Error> {
381 observe!(resume, {
382 self.resume_numeric::<R>(jobs, handle, sequence, now, Operation::Average)
383 })
384 }
385
386 fn start_numeric<R: Value>(
387 self,
388 jobs: &mut AggregateJobs<M>,
389 now: Timestamp,
390 expires: Timestamp,
391 operation: Operation,
392 ) -> Result<JobHandle, Error> {
393 let (plan, mut reducer) = self.numeric_plan::<R>(None, operation)?;
394
395 start(
396 jobs,
397 binding(&plan, &reducer)?,
398 self.db.read()?.revision_by_id(E::SCHEMA.id)?,
399 now,
400 expires,
401 &Accumulator::Scalar(&mut reducer),
402 )
403 }
404
405 fn resume_numeric<R: Value>(
406 self,
407 jobs: &mut AggregateJobs<M>,
408 handle: &JobHandle,
409 sequence: u64,
410 now: Timestamp,
411 operation: Operation,
412 ) -> Result<JobStep<Option<R>>, Error> {
413 let (plan, reducer) = self.numeric_plan::<R>(None, operation)?;
414
415 self.resume_value(jobs, handle, sequence, now, (plan, reducer))
416 }
417
418 fn resume_value<R: Value>(
419 self,
420 jobs: &mut AggregateJobs<M>,
421 handle: &JobHandle,
422 sequence: u64,
423 now: Timestamp,
424 admitted: (Plan<'_>, Reducer),
425 ) -> Result<JobStep<Option<R>>, Error> {
426 let (plan, mut reducer) = admitted;
427 let mut record = jobs.load(handle)?;
428 let expected = binding(&plan, &reducer)?;
429 let limit = self.request.bytes;
430 let changed = prepare(
431 &*self.db.read()?,
432 E::SCHEMA,
433 self.request,
434 &plan,
435 Accumulator::Scalar(&mut reducer),
436 &mut record,
437 expected,
438 sequence,
439 now,
440 )?;
441
442 record.finish_and_save(jobs, handle, changed, limit, || {
443 scalar_output(reducer, limit)
444 })
445 }
446}
447fn field_binding(binding: [u8; 32], field: Option<&str>) -> [u8; 32] {
448 let Some(field) = field else { return binding };
449 let mut hash = Sha256::new();
450 hash.update(b"ic-db:field-count-job:v1\0");
451 hash.update(binding);
452 hash.update((field.len() as u32).to_le_bytes());
453 hash.update(field.as_bytes());
454
455 hash.finalize().into()
456}
457
458fn binding(plan: &Plan<'_>, reducer: &Reducer) -> Result<[u8; 32], Error> {
459 let mut hash = Sha256::new();
460 hash.update(b"ic-db:scalar-job:v1\0");
463 hash.update(plan.binding);
464 match reducer {
465 Reducer::Count { .. } => hash.update([0]),
467 Reducer::Numeric(state) => {
468 hash.update([state.operation as u8, state.position as u8]);
469 let output = state.output();
470 match (crate::key::operand_type(output.value), state.operation) {
471 (crate::FieldType::Float32, _) => hash.update(b"binary32-exact:v1\0"),
472 (crate::FieldType::Float64, Operation::Sum) => {
473 hash.update(b"binary64-exact-sum:v1\0")
474 }
475 (crate::FieldType::Float64, Operation::Average) => {
476 hash.update(b"binary64-exact-average:v1\0")
477 }
478 _ => {}
479 }
480 let mut bytes = Vec::new();
481 crate::schema::encode_type(&mut bytes, output.value, output.optional, false)?;
482 hash.update(bytes);
483 }
484 Reducer::Extremum {
486 position, maximum, ..
487 } => {
488 hash.update([if *maximum { 4 } else { 3 }, *position as u8]);
489 }
490 _ => return Err(Error::InvalidQuery),
491 }
492
493 Ok(hash.finalize().into())
494}
495
496fn start<M: Memory>(
497 jobs: &mut AggregateJobs<M>,
498 binding: [u8; 32],
499 revision: u64,
500 now: Timestamp,
501 expires: Timestamp,
502 accumulator: &Accumulator<'_>,
503) -> Result<JobHandle, Error> {
504 let lifetime = expires
505 .as_millis()
506 .checked_sub(now.as_millis())
507 .ok_or(Error::Limit)?;
508 if !(1..=MAX_LIFETIME_MS).contains(&lifetime) {
509 return Err(Error::Limit);
510 }
511 let (count, state) = accumulator.checkpoint()?;
512
513 jobs.insert(Record {
514 generation: 0,
515 binding,
516 revision,
517 expires,
518 observed: now,
519 sequence: 0,
520 examined: 0,
521 input_bytes: 0,
522 phase: JobOutcome::Running,
523 cursor: Vec::new(),
524 count,
525 state,
526 })
527}
528
529#[expect(
532 clippy::too_many_arguments,
533 reason = "explicit admitted query and checkpoint inputs keep the shared resume boundary local"
534)]
535fn prepare<M: Memory>(
536 db: &Database<M>,
537 entity: &EntitySchema,
538 request: Request<'_>,
539 plan: &Plan<'_>,
540 mut accumulator: Accumulator<'_>,
541 record: &mut Record,
542 expected: [u8; 32],
543 sequence: u64,
544 now: Timestamp,
545) -> Result<bool, Error> {
546 if record.binding != expected || sequence > record.sequence {
547 return Err(Error::InvalidJob);
548 }
549 if now < record.observed {
550 return Err(Error::TimestampRegression);
551 }
552 let saved_sequence = record.sequence;
553 accumulator.restore(entity, record)?;
554 if now >= record.expires && !matches!(record.phase, JobOutcome::Expired) {
555 record.phase = JobOutcome::Expired;
556 record.sequence += 1;
557 } else if matches!(record.phase, JobOutcome::Running) {
558 if db.revision_by_id(entity.id)? != record.revision {
559 record.phase = JobOutcome::Invalidated;
560 record.sequence += 1;
561 } else if sequence == record.sequence {
562 let cursor = if record.cursor.is_empty() {
563 None
564 } else {
565 let cursor = QueryCursor::from_bytes(&record.cursor)?;
566 if cursor.binding != plan.binding {
567 return Err(Error::Corrupt);
568 }
569 plan.validate_position(entity, &cursor)?;
570
571 Some(cursor)
572 };
573 let request = Request {
574 cursor: cursor.as_ref(),
575 work: request
576 .work
577 .min((MAX_CANDIDATES - record.examined) as usize),
578 ..request
579 };
580 let mut bytes = 0;
581 let page = execute_inner(
582 &db.map,
583 entity,
584 &request,
585 plan,
586 super::super::range::bounds(entity, &request, plan)?,
587 Some(&mut accumulator),
588 Some(&mut bytes),
589 )?;
590 record.examined += page.examined as u64;
591 record.input_bytes += bytes as u64;
592 record.cursor = page
593 .next
594 .as_ref()
595 .map_or_else(Vec::new, QueryCursor::to_bytes);
596 record.phase = if page.next.is_none() {
597 JobOutcome::Complete(())
598 } else {
599 JobOutcome::Running
600 };
601 record.sequence += 1;
602 (record.count, record.state) = accumulator.checkpoint()?;
603 }
604 }
605 let changed = record.sequence != saved_sequence || record.observed != now;
608 record.observed = now;
609
610 Ok(changed)
611}