Skip to main content

ic_db/store/query/aggregate/jobs/
storage.rs

1//! Fixed slots in one host-owned allocation; bounded frames use the owned codec.
2
3use super::{JobHandle, JobOutcome, MAX_CANDIDATES};
4use crate::{
5    Error, QueryCursor, Timestamp,
6    codec::{Decoder, Encoder},
7};
8use ic_storage::{Memory, RuntimeMemory, adapter::StableBTreeMap};
9
10pub(super) const SLOTS: u8 = 16;
11pub(super) const MAX_JOB_BYTES: usize = 16 * 1024;
12const MAGIC: &[u8; 8] = b"ICDBAJ02";
13
14/// Durable bounded aggregates in a host-governed allocation.
15/// Holds at most 16 jobs, each at most 16 KiB encoded bytes. Creation requires a
16/// fresh nonzero incarnation. Handles identify jobs; they do not authorize access.
17/// All mutation must run synchronously within one IC message, without awaits.
18/// Supplier failures trap; a later message trap rolls these changes back too.
19pub struct AggregateJobs<M: Memory> {
20    map: StableBTreeMap<u8, Vec<u8>, M>,
21    incarnation: [u8; 16],
22}
23impl<M: Memory> AggregateJobs<M> {
24    /// Create in an empty allocation, with a host-supplied fresh incarnation.
25    /// # Errors
26    /// Refuses a zero incarnation or a nonempty/unsupported supplier allocation.
27    /// # Panics
28    /// Supplier failures after mutation begins must trap the enclosing message.
29    pub fn create(memory: RuntimeMemory<M>, incarnation: [u8; 16]) -> Result<Self, Error> {
30        if incarnation == [0; 16] {
31            return Err(Error::InvalidJob);
32        }
33        if memory.size() != 0 {
34            return Err(Error::Exists);
35        }
36        let mut map = StableBTreeMap::create(memory);
37        map.insert(0, header(incarnation, 0));
38
39        Ok(Self { map, incarnation })
40    }
41
42    /// Reopen the current job-store format without modifying it.
43    /// # Errors
44    /// Refuses missing/corrupt headers and unsupported formats intact.
45    /// # Panics
46    /// Supplier corruption traps without repair.
47    pub fn open(memory: RuntimeMemory<M>) -> Result<Self, Error> {
48        if memory.size() == 0 {
49            return Err(Error::Corrupt);
50        }
51        let map: StableBTreeMap<u8, Vec<u8>, M> = StableBTreeMap::load(memory);
52        let bytes = map.get(&0).ok_or(Error::Corrupt)?;
53        let (incarnation, _) = read_header(&bytes)?;
54        if map.len() > u64::from(SLOTS) + 1
55            || map
56                .range(..)
57                .next_back()
58                .is_some_and(|entry| *entry.key() > SLOTS)
59        {
60            return Err(Error::Corrupt);
61        }
62
63        Ok(Self { map, incarnation })
64    }
65
66    /// Cancel one job, immediately releasing its logical slot. Repeated/stale
67    /// cancellation refuses; it cannot delete a subsequent occupant of that slot.
68    /// # Errors
69    /// Refuses a foreign, missing, stale or malformed handle/job frame. Cancellation
70    /// need not interpret a known frame's query-specific accumulator payload.
71    /// # Panics
72    /// Supplier mutation failures trap the enclosing message.
73    pub fn cancel(&mut self, handle: &JobHandle) -> Result<(), Error> {
74        self.with_record(handle, |_| ())?;
75        self.map.remove(&handle.slot);
76
77        Ok(())
78    }
79
80    /// Examine at most 16 slots and remove at most `limit` expired jobs (1..=16).
81    /// Time must be captured by the host; the database reads no clock. This does
82    /// not shrink stable memory or promise physical reclamation by the supplier.
83    /// # Errors
84    /// Refuses invalid limits or malformed records before removing any job.
85    /// # Panics
86    /// Supplier mutation failures trap the enclosing message.
87    pub fn cleanup_expired(&mut self, now: Timestamp, limit: usize) -> Result<usize, Error> {
88        if !(1..=usize::from(SLOTS)).contains(&limit) {
89            return Err(Error::Limit);
90        }
91        let mut expired = Vec::new();
92        for slot in 1..=SLOTS {
93            if let Some(bytes) = self.map.get(&slot) {
94                let record = Record::decode(&bytes)?;
95                if record.expires <= now && expired.len() < limit {
96                    expired.push(slot);
97                }
98            }
99        }
100        for slot in &expired {
101            self.map.remove(slot);
102        }
103
104        Ok(expired.len())
105    }
106
107    pub(super) fn insert(&mut self, mut record: Record) -> Result<JobHandle, Error> {
108        let slot = (1..=SLOTS)
109            .find(|slot| !self.map.contains_key(slot))
110            .ok_or(Error::JobCapacity)?;
111        let (incarnation, generation) = read_header(&self.map.get(&0).ok_or(Error::Corrupt)?)?;
112        if incarnation != self.incarnation {
113            return Err(Error::Corrupt);
114        }
115        let generation = generation.checked_add(1).ok_or(Error::Limit)?;
116        record.generation = generation;
117        let bytes = record.encode()?;
118        // No recoverable refusal after the first persistent write.
119        self.map.insert(0, header(incarnation, generation));
120        self.map.insert(slot, bytes);
121
122        Ok(JobHandle {
123            incarnation,
124            slot,
125            generation,
126        })
127    }
128
129    pub(super) fn load(&self, handle: &JobHandle) -> Result<Record, Error> {
130        self.with_record(handle, |record| record.into_owned())
131    }
132
133    // One identity/framing admission for owned resume and borrowed cancellation.
134    // Only resume needs owned cursor/accumulator bytes after the supplier buffer dies.
135    fn with_record<R>(
136        &self,
137        handle: &JobHandle,
138        inspect: impl FnOnce(Record<&[u8]>) -> R,
139    ) -> Result<R, Error> {
140        if handle.incarnation != self.incarnation {
141            return Err(Error::InvalidJob);
142        }
143        let bytes = self.map.get(&handle.slot).ok_or(Error::InvalidJob)?;
144        let record = Record::decode(&bytes)?;
145        if record.generation != handle.generation {
146            return Err(Error::InvalidJob);
147        }
148
149        Ok(inspect(record))
150    }
151
152    pub(super) fn save_if_changed(
153        &mut self,
154        handle: &JobHandle,
155        record: &Record,
156        changed: bool,
157    ) -> Result<(), Error> {
158        if changed {
159            self.map.insert(handle.slot, record.encode()?);
160        }
161
162        Ok(())
163    }
164}
165fn header(incarnation: [u8; 16], generation: u64) -> Vec<u8> {
166    let mut bytes = MAGIC.to_vec();
167    bytes.extend(crate::codec::ROW_CODEC_VERSION.to_le_bytes());
168    bytes.extend(incarnation);
169    bytes.extend(generation.to_le_bytes());
170
171    bytes
172}
173
174fn read_header(bytes: &[u8]) -> Result<([u8; 16], u64), Error> {
175    if bytes.len() != 36 {
176        return Err(Error::Corrupt);
177    }
178    if &bytes[..8] != MAGIC || bytes[8..12] != crate::codec::ROW_CODEC_VERSION.to_le_bytes() {
179        return Err(Error::InvalidJob);
180    }
181    let incarnation = bytes[12..28].try_into().map_err(|_| Error::Corrupt)?;
182    if incarnation == [0; 16] {
183        return Err(Error::Corrupt);
184    }
185
186    Ok((
187        incarnation,
188        u64::from_le_bytes(bytes[28..].try_into().map_err(|_| Error::Corrupt)?),
189    ))
190}
191
192// The byte boundary has two representations: a validated borrowed frame for
193// inspection, and owned cursor/state for advancing a job. Execution stays shared.
194pub(super) struct Record<Bytes = Vec<u8>> {
195    pub generation: u64,
196    pub binding: [u8; 32],
197    pub revision: u64,
198    pub expires: Timestamp,
199    pub observed: Timestamp,
200    pub sequence: u64,
201    pub examined: u64,
202    pub input_bytes: u64,
203    pub phase: JobOutcome<()>,
204    pub cursor: Bytes,
205    pub count: u64,
206    // Interpretation belongs to the query-bound accumulator, not the job store.
207    pub state: Bytes,
208}
209impl Record {
210    fn encode(&self) -> Result<Vec<u8>, Error> {
211        let mut e = Encoder::with_byte_limit(MAX_JOB_BYTES);
212        e.nat64(self.generation)?;
213        e.bytes(&self.binding)?;
214        e.nat64(self.revision)?;
215        e.timestamp(self.expires)?;
216        e.timestamp(self.observed)?;
217        e.nat64(self.sequence)?;
218        e.nat64(self.examined)?;
219        e.nat64(self.input_bytes)?;
220        e.nat8(match self.phase {
221            JobOutcome::Running => 0,
222            JobOutcome::Complete(()) => 1,
223            JobOutcome::Invalidated => 2,
224            JobOutcome::Expired => 3,
225        })?;
226        e.bytes(&self.cursor)?;
227        e.nat64(self.count)?;
228        e.bytes(&self.state)?;
229
230        Ok(e.finish())
231    }
232}
233impl<'a> Record<&'a [u8]> {
234    fn decode(bytes: &'a [u8]) -> Result<Self, Error> {
235        let mut d = Decoder::with_byte_limit(bytes, MAX_JOB_BYTES)?;
236        let record = Self {
237            generation: d.nat64()?,
238            binding: d.blob_ref(32)?.try_into().map_err(|_| Error::Corrupt)?,
239            revision: d.nat64()?,
240            expires: d.timestamp()?,
241            observed: d.timestamp()?,
242            sequence: d.nat64()?,
243            examined: d.nat64()?,
244            input_bytes: d.nat64()?,
245            phase: match d.nat8()? {
246                0 => JobOutcome::Running,
247                1 => JobOutcome::Complete(()),
248                2 => JobOutcome::Invalidated,
249                3 => JobOutcome::Expired,
250                _ => return Err(Error::Corrupt),
251            },
252            cursor: d.blob_ref(QueryCursor::MAX_ENCODED_BYTES)?,
253            count: d.nat64()?,
254            state: d.blob_ref(MAX_JOB_BYTES)?,
255        };
256        d.finish()?;
257        if record.generation == 0
258            || record.examined > MAX_CANDIDATES
259            || record.count > record.examined
260            || record.sequence > record.examined + 2
261            || record.input_bytes
262                > record.examined
263                    * super::super::super::candidate_byte_limit(crate::codec::MAX_ROW_BYTES) as u64
264            || (matches!(record.phase, JobOutcome::Complete(())) && !record.cursor.is_empty())
265            || (matches!(record.phase, JobOutcome::Running)
266                && (record.observed >= record.expires
267                    || (record.examined > 0 && record.cursor.is_empty())))
268        {
269            return Err(Error::Corrupt);
270        }
271
272        Ok(record)
273    }
274
275    fn into_owned(self) -> Record {
276        Record {
277            generation: self.generation,
278            binding: self.binding,
279            revision: self.revision,
280            expires: self.expires,
281            observed: self.observed,
282            sequence: self.sequence,
283            examined: self.examined,
284            input_bytes: self.input_bytes,
285            phase: self.phase,
286            cursor: self.cursor.to_vec(),
287            count: self.count,
288            state: self.state.to_vec(),
289        }
290    }
291}