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