interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-kernel / src / store / checkpoint.rs

349 lines · 12994 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Crash Checkpoint ABI for AIENOS System Store transactions.
17//!
18//! Provides a tiny test-only checkpoint interface consumed by crash controllers,
19//! integration tests (e.g. QEMU crash injection), and the store transaction engine.
20//!
21//! Checkpoints define deterministic, crash-consistent observation boundaries during
22//! a store transaction commit sequence:
23//! 1. `BeforeFirstWrite` ("before_first_write")
24//! 2. `AfterPayloads` ("after_payloads" / "after_payload_objects")
25//! 3. `AfterCatalog` ("after_catalog")
26//! 4. `AfterCommitRecord` ("after_commit_record")
27//! 5. `AfterFirstFlush` ("after_first_flush")
28//! 6. `AfterSuperblockWrite` ("after_superblock_write" / "after_inactive_superblock")
29//! 7. `AfterFinalFlush` ("after_final_flush")
30//!
31//! Architectural invariants:
32//! - Deterministic ordering: sequence strictly advances from 0 to 6.
33//! - Non-mutating: observing a checkpoint never mutates storage buffers or persisted bytes.
34//! - Non-flushing: observing a checkpoint performs zero device flushes.
35//! - Ephemeral: checkpoints are an in-memory observation ABI and do not exist on disk.
36//! - Production elision: null hook (`NullCheckpointHook` / `null_hook`) is zero-sized and
37//! elided at compile time with zero runtime overhead or serial output.
38//! - Serial observation: formatted strings match `CHECKPOINT: <name>` as recognized
39//! by crash controllers.
40
41extern crate alloc;
42
43use alloc::format;
44use alloc::string::String;
45use alloc::vec::Vec;
46use core::fmt;
47use core::str::FromStr;
48
49/// Prefix recognized by the QEMU crash controller harness.
50pub const CHECKPOINT_PREFIX: &str = "CHECKPOINT: ";
51
52/// Total count of distinct checkpoints in the transaction commit sequence.
53pub const CHECKPOINT_COUNT: usize = 7;
54
55/// Canonical checkpoint identifiers during transaction commit.
56#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
57#[repr(u8)]
58pub enum Checkpoint {
59 /// Before any block or unit write for the transaction is initiated.
60 BeforeFirstWrite = 0,
61 /// After all payload/application objects have been written to disk units.
62 AfterPayloads = 1,
63 /// After the new catalog units have been written to disk.
64 AfterCatalog = 2,
65 /// After the commit record unit has been written to disk.
66 AfterCommitRecord = 3,
67 /// After the first device flush (persisting payload, catalog, and commit record).
68 AfterFirstFlush = 4,
69 /// After the inactive superblock has been updated with the new commit reference.
70 AfterSuperblockWrite = 5,
71 /// After the final device flush (persisting the newly activated superblock).
72 AfterFinalFlush = 6,
73}
74
75impl Checkpoint {
76 /// Alias matching the Codex store engine variant name.
77 pub const AfterPayloadObjects: Checkpoint = Checkpoint::AfterPayloads;
78 /// Alias matching the Codex store engine variant name.
79 pub const AfterInactiveSuperblock: Checkpoint = Checkpoint::AfterSuperblockWrite;
80
81 /// All 7 canonical checkpoints in their exact deterministic execution order.
82 pub const ORDERED: [Checkpoint; CHECKPOINT_COUNT] = [
83 Checkpoint::BeforeFirstWrite,
84 Checkpoint::AfterPayloads,
85 Checkpoint::AfterCatalog,
86 Checkpoint::AfterCommitRecord,
87 Checkpoint::AfterFirstFlush,
88 Checkpoint::AfterSuperblockWrite,
89 Checkpoint::AfterFinalFlush,
90 ];
91
92 /// Returns the canonical lower_snake_case name of the checkpoint.
93 #[inline]
94 pub const fn as_str(&self) -> &'static str {
95 match self {
96 Checkpoint::BeforeFirstWrite => "before_first_write",
97 Checkpoint::AfterPayloads => "after_payloads",
98 Checkpoint::AfterCatalog => "after_catalog",
99 Checkpoint::AfterCommitRecord => "after_commit_record",
100 Checkpoint::AfterFirstFlush => "after_first_flush",
101 Checkpoint::AfterSuperblockWrite => "after_superblock_write",
102 Checkpoint::AfterFinalFlush => "after_final_flush",
103 }
104 }
105
106 /// Returns the store engine variant alias name.
107 #[inline]
108 pub const fn engine_name(&self) -> &'static str {
109 match self {
110 Checkpoint::BeforeFirstWrite => "before_first_write",
111 Checkpoint::AfterPayloads => "after_payload_objects",
112 Checkpoint::AfterCatalog => "after_catalog",
113 Checkpoint::AfterCommitRecord => "after_commit_record",
114 Checkpoint::AfterFirstFlush => "after_first_flush",
115 Checkpoint::AfterSuperblockWrite => "after_inactive_superblock",
116 Checkpoint::AfterFinalFlush => "after_final_flush",
117 }
118 }
119
120 /// Returns all accepted names and aliases for this checkpoint.
121 pub const fn aliases(&self) -> &'static [&'static str] {
122 match self {
123 Checkpoint::BeforeFirstWrite => &["before_first_write"],
124 Checkpoint::AfterPayloads => &["after_payloads", "after_payload_objects"],
125 Checkpoint::AfterCatalog => &["after_catalog"],
126 Checkpoint::AfterCommitRecord => &["after_commit_record"],
127 Checkpoint::AfterFirstFlush => &["after_first_flush"],
128 Checkpoint::AfterSuperblockWrite => {
129 &["after_superblock_write", "after_inactive_superblock"]
130 }
131 Checkpoint::AfterFinalFlush => &["after_final_flush"],
132 }
133 }
134
135 /// Deterministic 0-indexed execution order.
136 #[inline]
137 pub const fn order(&self) -> u8 {
138 *self as u8
139 }
140
141 /// Returns the checkpoint corresponding to an execution index (0..6), if valid.
142 pub const fn from_order(order: u8) -> Option<Checkpoint> {
143 match order {
144 0 => Some(Checkpoint::BeforeFirstWrite),
145 1 => Some(Checkpoint::AfterPayloads),
146 2 => Some(Checkpoint::AfterCatalog),
147 3 => Some(Checkpoint::AfterCommitRecord),
148 4 => Some(Checkpoint::AfterFirstFlush),
149 5 => Some(Checkpoint::AfterSuperblockWrite),
150 6 => Some(Checkpoint::AfterFinalFlush),
151 _ => None,
152 }
153 }
154
155 /// Returns the next checkpoint in the commit sequence, or `None` if at final flush.
156 pub const fn next(&self) -> Option<Checkpoint> {
157 Self::from_order(self.order() + 1)
158 }
159
160 /// Returns the previous checkpoint in the commit sequence, or `None` if at initial point.
161 pub const fn prev(&self) -> Option<Checkpoint> {
162 if self.order() == 0 {
163 None
164 } else {
165 Self::from_order(self.order() - 1)
166 }
167 }
168
169 /// Formats the checkpoint into the canonical serial string `CHECKPOINT: <name>`.
170 pub fn format_serial(&self) -> String {
171 format_checkpoint(*self)
172 }
173}
174
175impl fmt::Display for Checkpoint {
176 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177 write!(f, "{}", self.as_str())
178 }
179}
180
181/// Error returned when parsing an unrecognized checkpoint name.
182#[derive(Debug, Clone, Copy, PartialEq, Eq)]
183pub struct ParseCheckpointError;
184
185impl fmt::Display for ParseCheckpointError {
186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187 write!(f, "unknown or invalid crash checkpoint identifier")
188 }
189}
190
191impl FromStr for Checkpoint {
192 type Err = ParseCheckpointError;
193
194 fn from_str(s: &str) -> Result<Self, Self::Err> {
195 parse_checkpoint(s).ok_or(ParseCheckpointError)
196 }
197}
198
199/// Parses a checkpoint identifier from a string.
200///
201/// Accepts:
202/// - Canonical names: `"before_first_write"`, `"after_payloads"`, `"after_catalog"`,
203/// `"after_commit_record"`, `"after_first_flush"`, `"after_superblock_write"`, `"after_final_flush"`
204/// - Engine aliases: `"after_payload_objects"`, `"after_inactive_superblock"`
205/// - Full serial lines: `"CHECKPOINT: <name>"`
206/// - Surrounding whitespace or newlines.
207pub fn parse_checkpoint(input: &str) -> Option<Checkpoint> {
208 let trimmed = input.trim();
209 let name = if let Some(stripped) = trimmed.strip_prefix("CHECKPOINT:") {
210 stripped.trim()
211 } else {
212 trimmed
213 };
214
215 match name {
216 "before_first_write" => Some(Checkpoint::BeforeFirstWrite),
217 "after_payloads" | "after_payload_objects" => Some(Checkpoint::AfterPayloads),
218 "after_catalog" => Some(Checkpoint::AfterCatalog),
219 "after_commit_record" => Some(Checkpoint::AfterCommitRecord),
220 "after_first_flush" => Some(Checkpoint::AfterFirstFlush),
221 "after_superblock_write" | "after_inactive_superblock" => {
222 Some(Checkpoint::AfterSuperblockWrite)
223 }
224 "after_final_flush" => Some(Checkpoint::AfterFinalFlush),
225 _ => None,
226 }
227}
228
229/// Formats a checkpoint into the canonical serial line: `CHECKPOINT: <canonical_name>`.
230pub fn format_checkpoint(checkpoint: Checkpoint) -> String {
231 format!("{}{}", CHECKPOINT_PREFIX, checkpoint.as_str())
232}
233
234/// Formats a checkpoint with an explicit name or alias into serial format: `CHECKPOINT: <name>`.
235pub fn format_checkpoint_with_name(name: &str) -> String {
236 format!("{}{}", CHECKPOINT_PREFIX, name)
237}
238
239/// Formats a checkpoint into a stack-allocated byte buffer without heap allocation.
240/// Returns the resulting string slice on success, or `None` if the buffer is too small.
241pub fn format_checkpoint_buf(checkpoint: Checkpoint, buf: &mut [u8]) -> Option<&str> {
242 let prefix = CHECKPOINT_PREFIX.as_bytes();
243 let name = checkpoint.as_str().as_bytes();
244 let total = prefix.len() + name.len();
245 if buf.len() < total {
246 return None;
247 }
248 buf[..prefix.len()].copy_from_slice(prefix);
249 buf[prefix.len()..total].copy_from_slice(name);
250 core::str::from_utf8(&buf[..total]).ok()
251}
252
253/// Logs a checkpoint to standard output if running with `std`.
254/// In bare-metal `no_std`, this is a no-op unless a specific console writer is plugged.
255pub fn log_checkpoint(checkpoint: Checkpoint) {
256 #[cfg(feature = "std")]
257 {
258 println!("{}{}", CHECKPOINT_PREFIX, checkpoint.as_str());
259 }
260 #[cfg(not(feature = "std"))]
261 {
262 let _ = checkpoint;
263 }
264}
265
266/// Logs a checkpoint to an arbitrary `core::fmt::Write` destination.
267pub fn log_checkpoint_to<W: fmt::Write>(writer: &mut W, checkpoint: Checkpoint) -> fmt::Result {
268 writeln!(writer, "{}{}", CHECKPOINT_PREFIX, checkpoint.as_str())
269}
270
271/// Interface for crash checkpoint observers.
272pub trait CheckpointHook {
273 /// Fired synchronously at the specified checkpoint boundary.
274 ///
275 /// Implementors MUST NOT:
276 /// - Mutate storage device buffers or bytes.
277 /// - Trigger I/O flushes.
278 /// - Persist checkpoint state to media.
279 fn on_checkpoint(&mut self, checkpoint: Checkpoint);
280}
281
282/// Zero-sized null hook that compiles down to a no-op with zero runtime overhead.
283///
284/// Intended for production builds where crash injection / checkpoint observation
285/// is disabled.
286#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
287pub struct NullCheckpointHook;
288
289impl CheckpointHook for NullCheckpointHook {
290 #[inline(always)]
291 fn on_checkpoint(&mut self, _checkpoint: Checkpoint) {
292 // Compile-time no-op.
293 }
294}
295
296/// Compile-time elided function pointer hook.
297#[inline(always)]
298pub fn null_hook(_checkpoint: Checkpoint) {
299 // Compile-time no-op.
300}
301
302/// Closure adapter allowing any `FnMut(Checkpoint)` to act as a `CheckpointHook`.
303impl<F: FnMut(Checkpoint)> CheckpointHook for F {
304 #[inline(always)]
305 fn on_checkpoint(&mut self, checkpoint: Checkpoint) {
306 (self)(checkpoint);
307 }
308}
309
310/// Test helper hook that records observed checkpoints in sequence.
311#[derive(Debug, Clone, Default, PartialEq, Eq)]
312pub struct RecordingHook {
313 pub visited: Vec<Checkpoint>,
314}
315
316impl RecordingHook {
317 pub const fn new() -> Self {
318 Self {
319 visited: Vec::new(),
320 }
321 }
322}
323
324impl CheckpointHook for RecordingHook {
325 fn on_checkpoint(&mut self, checkpoint: Checkpoint) {
326 self.visited.push(checkpoint);
327 }
328}
329
330/// Serial hook that writes `CHECKPOINT: <name>\n` lines to a string buffer.
331#[derive(Debug, Default)]
332pub struct SerialCaptureHook {
333 pub output: String,
334}
335
336impl SerialCaptureHook {
337 pub fn new() -> Self {
338 Self {
339 output: String::new(),
340 }
341 }
342}
343
344impl CheckpointHook for SerialCaptureHook {
345 fn on_checkpoint(&mut self, checkpoint: Checkpoint) {
346 use fmt::Write;
347 let _ = writeln!(self.output, "{}{}", CHECKPOINT_PREFIX, checkpoint.as_str());
348 }
349}