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 / engine.rs

1413 lines · 52127 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//! Mount and transaction semantics for the canonical System Store v1 format.
17//!
18//! This layer only sees bounded 4096-byte Store units. Device geometry,
19//! provisioning, partitioning, and controller protocols belong below it.
20
21use alloc::vec;
22use alloc::vec::Vec;
23
24pub use super::checkpoint::Checkpoint;
25use super::checkpoint::CheckpointHook;
26use super::v1::{
27 object_unit_count, Catalog, CatalogEntry, CommitRecord, FormatError, ObjectId, Superblock,
28 MAX_CATALOG_ENTRIES, MAX_REGION_UNITS, MAX_TRANSACTION_OBJECTS, MAX_TRANSACTION_UNITS,
29 OBJECT_KIND_CATALOG, OBJECT_KIND_COMMIT_RECORD, OBJECT_VERSION_V1, STORE_UNIT_BYTES,
30};
31
32/// Narrow bounded Store-unit I/O consumed by the Store engine.
33pub trait StoreDevice {
34 type Error;
35
36 fn region_units(&self) -> u64;
37 fn read_unit(&mut self, unit: u64, out: &mut [u8; STORE_UNIT_BYTES])
38 -> Result<(), Self::Error>;
39 fn write_unit(&mut self, unit: u64, bytes: &[u8; STORE_UNIT_BYTES]) -> Result<(), Self::Error>;
40 fn flush(&mut self) -> Result<(), Self::Error>;
41}
42
43#[derive(Clone, Copy, Debug, Eq, PartialEq)]
44pub enum MountState {
45 Valid,
46 DegradedRecovery,
47}
48
49/// What `Store::open` found in the superblock slot that is not the active root.
50#[derive(Clone, Copy, Debug, Eq, PartialEq)]
51pub enum PeerCondition {
52 /// All-zero slot (never written).
53 Zero,
54 /// A second fully validated root.
55 Valid,
56 /// Non-zero bytes that are not a CRC-valid, supported, decodable superblock.
57 Malformed,
58 /// CRC-valid superblock whose object graph fails validation, newer than the active root.
59 GraphBadNewer,
60 /// CRC-valid superblock whose object graph fails validation, older than the active root.
61 GraphBadOlder,
62}
63
64#[derive(Clone, Copy, Debug, Eq, PartialEq)]
65pub enum MountError {
66 Io,
67 Unformatted,
68 ForeignOrUnknown,
69 UnsupportedVersion,
70 CorruptRecoveryRequired,
71 ConflictingRoots,
72 InconsistentHistory,
73}
74
75#[derive(Clone, Copy, Debug, Eq, PartialEq)]
76pub enum StoreError {
77 Io,
78 Corrupt,
79 ReadOnlyDegraded,
80 DuplicateObjectConflict,
81 NoSpace,
82 CatalogFull,
83 GenerationExhausted,
84 TransactionLimit,
85 InvalidObject,
86 NeedsReopen,
87 Format(FormatError),
88}
89
90#[derive(Clone, Copy, Debug)]
91pub struct ObjectInput<'a> {
92 pub kind: u16,
93 pub version: u16,
94 pub bytes: &'a [u8],
95}
96
97#[derive(Clone, Debug)]
98struct ValidatedRoot {
99 superblock: Superblock,
100 commit: CommitRecord,
101 commit_id: ObjectId,
102 catalog: Catalog,
103}
104
105#[derive(Debug)]
106pub struct Store<D> {
107 device: D,
108 root: ValidatedRoot,
109 state: MountState,
110 peer: PeerCondition,
111 poisoned: bool,
112}
113
114impl<D: StoreDevice> Store<D> {
115 /// Reads and validates both roots and their complete object graphs.
116 /// No write or flush is issued by this method.
117 pub fn open(mut device: D) -> Result<Self, MountError> {
118 let units = device.region_units();
119 if !(4..=MAX_REGION_UNITS).contains(&units) {
120 return Err(MountError::CorruptRecoveryRequired);
121 }
122 let mut raw = [[0u8; STORE_UNIT_BYTES]; 2];
123 device
124 .read_unit(0, &mut raw[0])
125 .map_err(|_| MountError::Io)?;
126 device
127 .read_unit(1, &mut raw[1])
128 .map_err(|_| MountError::Io)?;
129 let zero = [
130 raw[0].iter().all(|b| *b == 0),
131 raw[1].iter().all(|b| *b == 0),
132 ];
133 if zero == [true, true] {
134 return Err(MountError::Unformatted);
135 }
136 let magic = [has_superblock_magic(&raw[0]), has_superblock_magic(&raw[1])];
137 if !magic[0] && !magic[1] {
138 return Err(MountError::ForeignOrUnknown);
139 }
140 // The CRC is checked before version/features are inspected. A supported
141 // peer never hides a CRC-valid but unsupported root.
142 if (0..2).any(|i| crc_valid(&raw[i]) && unsupported_superblock(&raw[i])) {
143 return Err(MountError::UnsupportedVersion);
144 }
145
146 let mut roots: [Option<ValidatedRoot>; 2] = [None, None];
147 let mut graph_bad = [false; 2];
148 let mut malformed = [false; 2];
149 let mut crc_supported = [false; 2];
150 for slot in 0..2 {
151 if zero[slot] {
152 continue;
153 }
154 if !magic[slot] || !crc_valid(&raw[slot]) || unsupported_superblock(&raw[slot]) {
155 malformed[slot] = true;
156 continue;
157 }
158 crc_supported[slot] = true;
159 let sb = match Superblock::decode(&raw[slot], slot as u32) {
160 Ok(sb) if sb.region_units == units => sb,
161 _ => {
162 malformed[slot] = true;
163 continue;
164 }
165 };
166 match validate_root(&mut device, sb) {
167 Ok(root) => roots[slot] = Some(root),
168 Err(RootError::Io(_)) => return Err(MountError::Io),
169 Err(RootError::Graph) => graph_bad[slot] = true,
170 }
171 }
172
173 let mounted = |device, root, state, peer| Self {
174 device,
175 root,
176 state,
177 peer,
178 poisoned: false,
179 };
180 match (roots[0].take(), roots[1].take()) {
181 (Some(a), Some(b)) => {
182 let chosen = select_two(a, b)?;
183 Ok(mounted(
184 device,
185 chosen,
186 MountState::Valid,
187 PeerCondition::Valid,
188 ))
189 }
190 (Some(root), None) | (None, Some(root)) => {
191 let good_slot = if root.superblock.slot_id == 0 { 0 } else { 1 };
192 let other = 1 - good_slot;
193 if zero[other] {
194 Ok(mounted(
195 device,
196 root,
197 MountState::Valid,
198 PeerCondition::Zero,
199 ))
200 } else if malformed[other] {
201 if unsupported_superblock(&raw[other]) && crc_valid(&raw[other]) {
202 Err(MountError::UnsupportedVersion)
203 } else {
204 Ok(mounted(
205 device,
206 root,
207 MountState::DegradedRecovery,
208 PeerCondition::Malformed,
209 ))
210 }
211 } else if graph_bad[other] && crc_supported[other] {
212 if generation_of(&raw[other]) > root.superblock.generation {
213 Ok(mounted(
214 device,
215 root,
216 MountState::DegradedRecovery,
217 PeerCondition::GraphBadNewer,
218 ))
219 } else if generation_of(&raw[other]) < root.superblock.generation {
220 Ok(mounted(
221 device,
222 root,
223 MountState::Valid,
224 PeerCondition::GraphBadOlder,
225 ))
226 } else {
227 Err(MountError::CorruptRecoveryRequired)
228 }
229 } else {
230 Err(MountError::CorruptRecoveryRequired)
231 }
232 }
233 (None, None) => Err(MountError::CorruptRecoveryRequired),
234 }
235 }
236
237 pub fn mount_state(&self) -> MountState {
238 self.state
239 }
240 /// Condition of the non-active superblock slot as classified at open, or
241 /// `Valid` once a committed transaction has made it the previous root.
242 pub fn peer_condition(&self) -> PeerCondition {
243 self.peer
244 }
245 pub fn generation(&self) -> u64 {
246 self.root.commit.generation
247 }
248 pub fn committed_high_water(&self) -> u64 {
249 self.root.commit.committed_high_water
250 }
251 pub fn active_slot(&self) -> u32 {
252 self.root.superblock.slot_id
253 }
254 pub fn catalog(&self) -> &Catalog {
255 &self.root.catalog
256 }
257 pub fn into_device(self) -> D {
258 self.device
259 }
260
261 /// Reads one catalog object and independently verifies its descriptor,
262 /// semantic bytes, and physical zero padding.
263 pub fn read_object(&mut self, id: ObjectId) -> Result<Vec<u8>, StoreError> {
264 let entry = self
265 .root
266 .catalog
267 .entries
268 .binary_search_by_key(&id, |e| e.object_id)
269 .ok()
270 .map(|i| self.root.catalog.entries[i])
271 .ok_or(StoreError::InvalidObject)?;
272 read_application_object(&mut self.device, entry).map_err(map_root_error)
273 }
274
275 pub fn transact(&mut self, objects: &[ObjectInput<'_>]) -> Result<(), StoreError> {
276 self.transact_with_hook(objects, |_| {})
277 }
278
279 /// The hook observes logical crash boundaries and does not alter bytes or
280 /// ordering. Production callers should use `transact`.
281 pub fn transact_with_hook<F: CheckpointHook>(
282 &mut self,
283 objects: &[ObjectInput<'_>],
284 mut hook: F,
285 ) -> Result<(), StoreError> {
286 if self.poisoned {
287 return Err(StoreError::NeedsReopen);
288 }
289 if self.state == MountState::DegradedRecovery {
290 return Err(StoreError::ReadOnlyDegraded);
291 }
292 let plan = self.preflight(objects)?;
293 hook.on_checkpoint(Checkpoint::BeforeFirstWrite);
294 for (entry, bytes) in &plan.append {
295 if let Err(error) =
296 write_object(&mut self.device, entry.first_unit, entry.unit_count, bytes)
297 {
298 self.poisoned = true;
299 return Err(error);
300 }
301 }
302 hook.on_checkpoint(Checkpoint::AfterPayloadObjects);
303 if let Err(error) = write_object(
304 &mut self.device,
305 plan.catalog_first,
306 plan.catalog_units,
307 &plan.catalog_bytes,
308 ) {
309 self.poisoned = true;
310 return Err(error);
311 }
312 hook.on_checkpoint(Checkpoint::AfterCatalog);
313 if let Err(error) = write_one(&mut self.device, plan.commit_unit, &plan.commit_unit_bytes) {
314 self.poisoned = true;
315 return Err(error);
316 }
317 hook.on_checkpoint(Checkpoint::AfterCommitRecord);
318 self.device.flush().map_err(|_| {
319 self.poisoned = true;
320 StoreError::Io
321 })?;
322 hook.on_checkpoint(Checkpoint::AfterFirstFlush);
323 if let Err(error) = write_one(
324 &mut self.device,
325 u64::from(plan.superblock.slot_id),
326 &plan.superblock_bytes,
327 ) {
328 self.poisoned = true;
329 return Err(error);
330 }
331 hook.on_checkpoint(Checkpoint::AfterInactiveSuperblock);
332 self.device.flush().map_err(|_| {
333 self.poisoned = true;
334 StoreError::Io
335 })?;
336 hook.on_checkpoint(Checkpoint::AfterFinalFlush);
337 self.root = plan.root;
338 self.peer = PeerCondition::Valid;
339 Ok(())
340 }
341
342 fn preflight(&mut self, objects: &[ObjectInput<'_>]) -> Result<CommitPlan, StoreError> {
343 if objects.len() > MAX_TRANSACTION_OBJECTS {
344 return Err(StoreError::TransactionLimit);
345 }
346 let mut requested: Vec<(ObjectId, u16, u16, Vec<u8>, u32)> = Vec::new();
347 let mut app_units = 0u64;
348 for object in objects {
349 let id = ObjectId::calculate(object.kind, object.version, object.bytes)
350 .map_err(StoreError::Format)?;
351 let units = object_unit_count(object.bytes.len() as u64).map_err(StoreError::Format)?;
352 if let Some(existing) = requested.iter().find(|v| v.0 == id) {
353 if existing.1 != object.kind
354 || existing.2 != object.version
355 || existing.3.as_slice() != object.bytes
356 {
357 return Err(StoreError::DuplicateObjectConflict);
358 }
359 continue;
360 }
361 requested.push((
362 id,
363 object.kind,
364 object.version,
365 object.bytes.to_vec(),
366 units,
367 ));
368 }
369
370 let mut entries = self.root.catalog.entries.clone();
371 let mut append = Vec::new();
372 let mut next = self.root.commit.committed_high_water;
373 for (id, kind, version, bytes, units) in requested {
374 if let Ok(index) = entries.binary_search_by_key(&id, |e| e.object_id) {
375 let old = entries[index];
376 if old.kind != kind
377 || old.version != version
378 || old.byte_length != bytes.len() as u64
379 || old.unit_count != units
380 {
381 return Err(StoreError::DuplicateObjectConflict);
382 }
383 let verified =
384 read_application_object(&mut self.device, old).map_err(map_root_error)?;
385 if verified != bytes {
386 return Err(StoreError::DuplicateObjectConflict);
387 }
388 continue;
389 }
390 app_units = app_units
391 .checked_add(u64::from(units))
392 .ok_or(StoreError::NoSpace)?;
393 let entry = CatalogEntry {
394 object_id: id,
395 kind,
396 version,
397 first_unit: next,
398 byte_length: bytes.len() as u64,
399 unit_count: units,
400 flags: 0,
401 };
402 next = next
403 .checked_add(u64::from(units))
404 .ok_or(StoreError::NoSpace)?;
405 entries.push(entry);
406 append.push((entry, bytes));
407 }
408 entries.sort_by_key(|e| e.object_id);
409 if entries.len() > MAX_CATALOG_ENTRIES {
410 return Err(StoreError::CatalogFull);
411 }
412 // MAX_TRANSACTION_UNITS bounds appended application payload units.
413 if app_units > MAX_TRANSACTION_UNITS {
414 return Err(StoreError::TransactionLimit);
415 }
416 let catalog = Catalog { entries };
417 let catalog_bytes = catalog.encode().map_err(StoreError::Format)?;
418 let catalog_units =
419 object_unit_count(catalog_bytes.len() as u64).map_err(StoreError::Format)?;
420 let catalog_first = next;
421 let commit_unit = catalog_first
422 .checked_add(u64::from(catalog_units))
423 .ok_or(StoreError::NoSpace)?;
424 let high_water = commit_unit.checked_add(1).ok_or(StoreError::NoSpace)?;
425 if high_water > self.device.region_units() || high_water > MAX_REGION_UNITS {
426 return Err(StoreError::NoSpace);
427 }
428 let generation = self
429 .root
430 .commit
431 .generation
432 .checked_add(1)
433 .ok_or(StoreError::GenerationExhausted)?;
434 let catalog_id =
435 ObjectId::calculate(OBJECT_KIND_CATALOG, OBJECT_VERSION_V1, &catalog_bytes)
436 .map_err(StoreError::Format)?;
437 let commit = CommitRecord {
438 store_uuid: self.root.commit.store_uuid,
439 region_units: self.root.commit.region_units,
440 generation,
441 previous_generation: self.root.commit.generation,
442 previous_commit_id: self.root.commit_id,
443 previous_catalog_id: self.root.commit.catalog_id,
444 catalog_id,
445 catalog_first_unit: catalog_first,
446 catalog_byte_length: catalog_bytes.len() as u64,
447 catalog_unit_count: catalog_units,
448 catalog_entry_count: catalog.entries.len() as u32,
449 committed_high_water: high_water,
450 };
451 let commit_bytes = commit.encode().map_err(StoreError::Format)?;
452 let commit_id = commit.object_id().map_err(StoreError::Format)?;
453 let mut commit_unit_bytes = [0; STORE_UNIT_BYTES];
454 commit_unit_bytes[..commit_bytes.len()].copy_from_slice(&commit_bytes);
455 let slot = 1 - self.root.superblock.slot_id;
456 let superblock = Superblock {
457 store_uuid: commit.store_uuid,
458 slot_id: slot,
459 region_units: commit.region_units,
460 generation,
461 commit_record_id: commit_id,
462 commit_record_unit: commit_unit,
463 catalog_id,
464 catalog_first_unit: catalog_first,
465 catalog_byte_length: commit.catalog_byte_length,
466 catalog_unit_count: catalog_units,
467 catalog_entry_count: commit.catalog_entry_count,
468 committed_high_water: high_water,
469 };
470 let superblock_bytes = superblock.encode().map_err(StoreError::Format)?;
471 let root = ValidatedRoot {
472 superblock: superblock.clone(),
473 commit,
474 commit_id,
475 catalog,
476 };
477 Ok(CommitPlan {
478 append,
479 catalog_first,
480 catalog_units,
481 catalog_bytes,
482 commit_unit,
483 commit_unit_bytes,
484 superblock,
485 superblock_bytes,
486 root,
487 })
488 }
489}
490
491#[derive(Debug)]
492struct CommitPlan {
493 append: Vec<(CatalogEntry, Vec<u8>)>,
494 catalog_first: u64,
495 catalog_units: u32,
496 catalog_bytes: Vec<u8>,
497 commit_unit: u64,
498 commit_unit_bytes: [u8; STORE_UNIT_BYTES],
499 superblock: Superblock,
500 superblock_bytes: [u8; STORE_UNIT_BYTES],
501 root: ValidatedRoot,
502}
503
504enum RootError<E> {
505 Io(E),
506 Graph,
507}
508
509fn validate_root<D: StoreDevice>(
510 device: &mut D,
511 sb: Superblock,
512) -> Result<ValidatedRoot, RootError<D::Error>> {
513 if sb.region_units != device.region_units() {
514 return Err(RootError::Graph);
515 }
516 let mut commit_unit = [0; STORE_UNIT_BYTES];
517 device
518 .read_unit(sb.commit_record_unit, &mut commit_unit)
519 .map_err(RootError::Io)?;
520 let commit_bytes = &commit_unit[..super::v1::COMMIT_RECORD_BYTES];
521 if commit_unit[super::v1::COMMIT_RECORD_BYTES..]
522 .iter()
523 .any(|b| *b != 0)
524 {
525 return Err(RootError::Graph);
526 }
527 let commit_id = ObjectId::calculate(OBJECT_KIND_COMMIT_RECORD, OBJECT_VERSION_V1, commit_bytes)
528 .map_err(|_| RootError::Graph)?;
529 if commit_id != sb.commit_record_id {
530 return Err(RootError::Graph);
531 }
532 let commit = CommitRecord::decode(commit_bytes).map_err(|_| RootError::Graph)?;
533 sb.validate_commit(commit_id, &commit)
534 .map_err(|_| RootError::Graph)?;
535 let catalog_len = usize::try_from(commit.catalog_byte_length).map_err(|_| RootError::Graph)?;
536 let catalog_total =
537 usize::try_from(u64::from(commit.catalog_unit_count) * STORE_UNIT_BYTES as u64)
538 .map_err(|_| RootError::Graph)?;
539 let mut catalog_extent = vec![0; catalog_total];
540 for i in 0..commit.catalog_unit_count {
541 let start = i as usize * STORE_UNIT_BYTES;
542 let slice: &mut [u8; STORE_UNIT_BYTES] = (&mut catalog_extent
543 [start..start + STORE_UNIT_BYTES])
544 .try_into()
545 .map_err(|_| RootError::Graph)?;
546 device
547 .read_unit(commit.catalog_first_unit + u64::from(i), slice)
548 .map_err(RootError::Io)?;
549 }
550 let catalog_id = commit.catalog_id;
551 catalog_id
552 .validate_extent(
553 OBJECT_KIND_CATALOG,
554 OBJECT_VERSION_V1,
555 commit.catalog_byte_length,
556 &catalog_extent,
557 )
558 .map_err(|_| RootError::Graph)?;
559 let catalog = Catalog::decode(&catalog_extent[..catalog_len]).map_err(|_| RootError::Graph)?;
560 commit
561 .validates_catalog(catalog_id, &catalog)
562 .map_err(|_| RootError::Graph)?;
563 catalog
564 .validate_extents(
565 commit.region_units,
566 commit.catalog_first_unit,
567 commit.committed_high_water,
568 )
569 .map_err(|_| RootError::Graph)?;
570 for entry in catalog.entries.iter().copied() {
571 read_application_object(device, entry)?;
572 }
573 Ok(ValidatedRoot {
574 superblock: sb,
575 commit,
576 commit_id,
577 catalog,
578 })
579}
580
581fn read_application_object<D: StoreDevice>(
582 device: &mut D,
583 entry: CatalogEntry,
584) -> Result<Vec<u8>, RootError<D::Error>> {
585 let bytes_len = usize::try_from(u64::from(entry.unit_count) * STORE_UNIT_BYTES as u64)
586 .map_err(|_| RootError::Graph)?;
587 let mut extent = vec![0; bytes_len];
588 for i in 0..entry.unit_count {
589 let start = i as usize * STORE_UNIT_BYTES;
590 let slice: &mut [u8; STORE_UNIT_BYTES] = (&mut extent[start..start + STORE_UNIT_BYTES])
591 .try_into()
592 .map_err(|_| RootError::Graph)?;
593 device
594 .read_unit(entry.first_unit + u64::from(i), slice)
595 .map_err(RootError::Io)?;
596 }
597 entry
598 .object_id
599 .validate_extent(entry.kind, entry.version, entry.byte_length, &extent)
600 .map_err(|_| RootError::Graph)?;
601 let semantic = usize::try_from(entry.byte_length).map_err(|_| RootError::Graph)?;
602 Ok(extent[..semantic].to_vec())
603}
604
605fn select_two(a: ValidatedRoot, b: ValidatedRoot) -> Result<ValidatedRoot, MountError> {
606 if a.commit.generation == b.commit.generation {
607 if a.superblock.equivalent_root(&b.superblock) {
608 return Ok(a);
609 }
610 return Err(MountError::ConflictingRoots);
611 }
612 let (older, newer) = if a.commit.generation < b.commit.generation {
613 (a, b)
614 } else {
615 (b, a)
616 };
617 if older.commit.generation.checked_add(1) != Some(newer.commit.generation) {
618 return Err(MountError::InconsistentHistory);
619 }
620 if !newer
621 .commit
622 .identifies_predecessor(&older.commit, older.commit_id)
623 {
624 return Err(MountError::InconsistentHistory);
625 }
626 verify_append_transition(&older, &newer)?;
627 Ok(newer)
628}
629
630fn verify_append_transition(
631 older: &ValidatedRoot,
632 newer: &ValidatedRoot,
633) -> Result<(), MountError> {
634 for entry in &older.catalog.entries {
635 let index = newer
636 .catalog
637 .entries
638 .binary_search_by_key(&entry.object_id, |candidate| candidate.object_id)
639 .map_err(|_| MountError::InconsistentHistory)?;
640 if newer.catalog.entries[index] != *entry {
641 return Err(MountError::InconsistentHistory);
642 }
643 }
644 let mut added: Vec<CatalogEntry> = Vec::new();
645 for entry in &newer.catalog.entries {
646 match older
647 .catalog
648 .entries
649 .binary_search_by_key(&entry.object_id, |e| e.object_id)
650 {
651 Ok(i) if older.catalog.entries[i] != *entry => {
652 return Err(MountError::InconsistentHistory)
653 }
654 Ok(_) => {}
655 Err(_) => added.push(*entry),
656 }
657 }
658 added.sort_by_key(|e| e.first_unit);
659 let mut next = older.commit.committed_high_water;
660 for entry in added {
661 if entry.first_unit != next {
662 return Err(MountError::InconsistentHistory);
663 }
664 next = next
665 .checked_add(u64::from(entry.unit_count))
666 .ok_or(MountError::InconsistentHistory)?;
667 }
668 if next != newer.commit.catalog_first_unit {
669 return Err(MountError::InconsistentHistory);
670 }
671 Ok(())
672}
673
674fn write_object<D: StoreDevice>(
675 device: &mut D,
676 first: u64,
677 units: u32,
678 bytes: &[u8],
679) -> Result<(), StoreError> {
680 for i in 0..units {
681 let mut unit = [0; STORE_UNIT_BYTES];
682 let start = i as usize * STORE_UNIT_BYTES;
683 let end = core::cmp::min(start + STORE_UNIT_BYTES, bytes.len());
684 unit[..end - start].copy_from_slice(&bytes[start..end]);
685 write_one(device, first + u64::from(i), &unit)?;
686 }
687 Ok(())
688}
689
690fn write_one<D: StoreDevice>(
691 device: &mut D,
692 unit: u64,
693 bytes: &[u8; STORE_UNIT_BYTES],
694) -> Result<(), StoreError> {
695 device.write_unit(unit, bytes).map_err(|_| StoreError::Io)
696}
697
698fn has_superblock_magic(bytes: &[u8; STORE_UNIT_BYTES]) -> bool {
699 &bytes[..8] == b"AIENSTR1"
700}
701fn crc_valid(bytes: &[u8; STORE_UNIT_BYTES]) -> bool {
702 let expected = u32::from_le_bytes(bytes[168..172].try_into().unwrap_or([0; 4]));
703 let mut copy = *bytes;
704 copy[168..172].fill(0);
705 super::v1::crc32c(&copy) == expected
706}
707fn unsupported_superblock(bytes: &[u8; STORE_UNIT_BYTES]) -> bool {
708 has_superblock_magic(bytes)
709 && crc_valid(bytes)
710 && (u16::from_le_bytes([bytes[8], bytes[9]]) != 1
711 || u16::from_le_bytes([bytes[10], bytes[11]]) != 0
712 || bytes[12..28].iter().any(|b| *b != 0))
713}
714fn generation_of(bytes: &[u8; STORE_UNIT_BYTES]) -> u64 {
715 u64::from_le_bytes(bytes[56..64].try_into().unwrap_or([0; 8]))
716}
717fn map_root_error<E>(err: RootError<E>) -> StoreError {
718 match err {
719 RootError::Io(_) => StoreError::Io,
720 RootError::Graph => StoreError::Corrupt,
721 }
722}
723
724#[cfg(test)]
725mod tests {
726 use super::*;
727 use alloc::vec;
728
729 #[derive(Clone, Debug)]
730 struct MemoryDevice {
731 units: Vec<[u8; STORE_UNIT_BYTES]>,
732 reads: Vec<u64>,
733 writes: Vec<u64>,
734 flushes: usize,
735 fail_read: Option<u64>,
736 fail_write: Option<u64>,
737 fail_flush: bool,
738 }
739
740 impl StoreDevice for MemoryDevice {
741 type Error = ();
742 fn region_units(&self) -> u64 {
743 self.units.len() as u64
744 }
745 fn read_unit(&mut self, unit: u64, out: &mut [u8; STORE_UNIT_BYTES]) -> Result<(), ()> {
746 self.reads.push(unit);
747 if self.fail_read == Some(unit) {
748 return Err(());
749 }
750 *out = *self.units.get(unit as usize).ok_or(())?;
751 Ok(())
752 }
753 fn write_unit(&mut self, unit: u64, bytes: &[u8; STORE_UNIT_BYTES]) -> Result<(), ()> {
754 self.writes.push(unit);
755 if self.fail_write == Some(unit) {
756 return Err(());
757 }
758 *self.units.get_mut(unit as usize).ok_or(())? = *bytes;
759 Ok(())
760 }
761 fn flush(&mut self) -> Result<(), ()> {
762 self.flushes += 1;
763 if self.fail_flush {
764 return Err(());
765 }
766 Ok(())
767 }
768 }
769
770 fn blank(units: usize) -> MemoryDevice {
771 MemoryDevice {
772 units: vec![[0; STORE_UNIT_BYTES]; units],
773 reads: Vec::new(),
774 writes: Vec::new(),
775 flushes: 0,
776 fail_read: None,
777 fail_write: None,
778 fail_flush: false,
779 }
780 }
781
782 fn seed_genesis(mut dev: MemoryDevice) -> MemoryDevice {
783 let catalog = Catalog {
784 entries: Vec::new(),
785 };
786 let catalog_bytes = catalog.encode().unwrap();
787 let catalog_id =
788 ObjectId::calculate(OBJECT_KIND_CATALOG, OBJECT_VERSION_V1, &catalog_bytes).unwrap();
789 let commit = CommitRecord {
790 store_uuid: [0x5a; 16],
791 region_units: dev.region_units(),
792 generation: 1,
793 previous_generation: 0,
794 previous_commit_id: ObjectId([0; 32]),
795 previous_catalog_id: ObjectId([0; 32]),
796 catalog_id,
797 catalog_first_unit: 2,
798 catalog_byte_length: catalog_bytes.len() as u64,
799 catalog_unit_count: 1,
800 catalog_entry_count: 0,
801 committed_high_water: 4,
802 };
803 let mut cat_unit = [0; STORE_UNIT_BYTES];
804 cat_unit[..catalog_bytes.len()].copy_from_slice(&catalog_bytes);
805 dev.units[2] = cat_unit;
806 let mut commit_unit = [0; STORE_UNIT_BYTES];
807 commit_unit[..super::super::v1::COMMIT_RECORD_BYTES]
808 .copy_from_slice(&commit.encode().unwrap());
809 dev.units[3] = commit_unit;
810 dev.units[0] = Superblock {
811 store_uuid: commit.store_uuid,
812 slot_id: 0,
813 region_units: commit.region_units,
814 generation: 1,
815 commit_record_id: commit.object_id().unwrap(),
816 commit_record_unit: 3,
817 catalog_id,
818 catalog_first_unit: 2,
819 catalog_byte_length: commit.catalog_byte_length,
820 catalog_unit_count: 1,
821 catalog_entry_count: 0,
822 committed_high_water: 4,
823 }
824 .encode()
825 .unwrap();
826 dev
827 }
828
829 fn seed_full_catalog() -> MemoryDevice {
830 let region_units = 4_168usize;
831 let mut dev = blank(region_units);
832 let mut entries = Vec::with_capacity(MAX_CATALOG_ENTRIES);
833 for index in 0..MAX_CATALOG_ENTRIES {
834 let kind = 3 + index as u16;
835 let semantic = [kind as u8];
836 let id = ObjectId::calculate(kind, 1, &semantic).unwrap();
837 entries.push(CatalogEntry {
838 object_id: id,
839 kind,
840 version: 1,
841 first_unit: 2 + index as u64,
842 byte_length: 1,
843 unit_count: 1,
844 flags: 0,
845 });
846 dev.units[2 + index][0] = semantic[0];
847 }
848 entries.sort_by_key(|entry| entry.object_id);
849 let catalog = Catalog { entries };
850 let catalog_bytes = catalog.encode().unwrap();
851 let catalog_id = ObjectId::calculate(OBJECT_KIND_CATALOG, 1, &catalog_bytes).unwrap();
852 let catalog_first = 2 + MAX_CATALOG_ENTRIES as u64;
853 let catalog_units = object_unit_count(catalog_bytes.len() as u64).unwrap();
854 assert_eq!(catalog_units, 65);
855 for i in 0..catalog_units as usize {
856 let start = i * STORE_UNIT_BYTES;
857 let end = core::cmp::min(start + STORE_UNIT_BYTES, catalog_bytes.len());
858 dev.units[catalog_first as usize + i][..end - start]
859 .copy_from_slice(&catalog_bytes[start..end]);
860 }
861 let commit_unit = catalog_first + u64::from(catalog_units);
862 let high_water = commit_unit + 1;
863 let commit = CommitRecord {
864 store_uuid: [0x5a; 16],
865 region_units: region_units as u64,
866 generation: 1,
867 previous_generation: 0,
868 previous_commit_id: ObjectId([0; 32]),
869 previous_catalog_id: ObjectId([0; 32]),
870 catalog_id,
871 catalog_first_unit: catalog_first,
872 catalog_byte_length: catalog_bytes.len() as u64,
873 catalog_unit_count: catalog_units,
874 catalog_entry_count: MAX_CATALOG_ENTRIES as u32,
875 committed_high_water: high_water,
876 };
877 dev.units[commit_unit as usize][..super::super::v1::COMMIT_RECORD_BYTES]
878 .copy_from_slice(&commit.encode().unwrap());
879 dev.units[0] = Superblock {
880 store_uuid: commit.store_uuid,
881 slot_id: 0,
882 region_units: commit.region_units,
883 generation: 1,
884 commit_record_id: commit.object_id().unwrap(),
885 commit_record_unit: commit_unit,
886 catalog_id,
887 catalog_first_unit: catalog_first,
888 catalog_byte_length: commit.catalog_byte_length,
889 catalog_unit_count: catalog_units,
890 catalog_entry_count: commit.catalog_entry_count,
891 committed_high_water: high_water,
892 }
893 .encode()
894 .unwrap();
895 dev
896 }
897
898 fn seed_generation_two() -> MemoryDevice {
899 let mut store = Store::open(seed_genesis(blank(32))).unwrap();
900 store.transact(&one(b"next generation")).unwrap();
901 store.into_device()
902 }
903
904 fn rewrite_commit(dev: &mut MemoryDevice, slot: u32, unit: u64, commit: CommitRecord) {
905 let mut commit_unit = [0; STORE_UNIT_BYTES];
906 commit_unit[..super::super::v1::COMMIT_RECORD_BYTES]
907 .copy_from_slice(&commit.encode().unwrap());
908 dev.units[unit as usize] = commit_unit;
909 let mut sb = Superblock::decode(&dev.units[slot as usize], slot).unwrap();
910 sb.generation = commit.generation;
911 sb.commit_record_id = commit.object_id().unwrap();
912 dev.units[slot as usize] = sb.encode().unwrap();
913 }
914
915 fn seed_conflicting_same_generation_roots() -> MemoryDevice {
916 let mut dev = seed_genesis(blank(32));
917 let catalog = Catalog {
918 entries: Vec::new(),
919 };
920 let bytes = catalog.encode().unwrap();
921 let id = ObjectId::calculate(OBJECT_KIND_CATALOG, 1, &bytes).unwrap();
922 let mut catalog_unit = [0; STORE_UNIT_BYTES];
923 catalog_unit[..bytes.len()].copy_from_slice(&bytes);
924 dev.units[4] = catalog_unit;
925 let commit = CommitRecord {
926 store_uuid: [0x6b; 16],
927 region_units: dev.region_units(),
928 generation: 1,
929 previous_generation: 0,
930 previous_commit_id: ObjectId([0; 32]),
931 previous_catalog_id: ObjectId([0; 32]),
932 catalog_id: id,
933 catalog_first_unit: 4,
934 catalog_byte_length: bytes.len() as u64,
935 catalog_unit_count: 1,
936 catalog_entry_count: 0,
937 committed_high_water: 6,
938 };
939 dev.units[5][..super::super::v1::COMMIT_RECORD_BYTES]
940 .copy_from_slice(&commit.encode().unwrap());
941 dev.units[1] = Superblock {
942 store_uuid: commit.store_uuid,
943 slot_id: 1,
944 region_units: commit.region_units,
945 generation: 1,
946 commit_record_id: commit.object_id().unwrap(),
947 commit_record_unit: 5,
948 catalog_id: id,
949 catalog_first_unit: 4,
950 catalog_byte_length: commit.catalog_byte_length,
951 catalog_unit_count: 1,
952 catalog_entry_count: 0,
953 committed_high_water: 6,
954 }
955 .encode()
956 .unwrap();
957 dev
958 }
959
960 fn one<'a>(bytes: &'a [u8]) -> [ObjectInput<'a>; 1] {
961 [ObjectInput {
962 kind: 3,
963 version: 1,
964 bytes,
965 }]
966 }
967
968 #[test]
969 fn store_open_side_effect_free() {
970 let dev = seed_genesis(blank(32));
971 let store = Store::open(dev).unwrap();
972 let dev = store.into_device();
973 assert_eq!(dev.writes, []);
974 assert_eq!(dev.flushes, 0);
975 assert!(dev.reads.contains(&0) && dev.reads.contains(&1));
976 }
977
978 #[test]
979 fn store_full_graph_validation_rejects_damaged_payload_and_keeps_io_distinct() {
980 let mut dev = seed_genesis(blank(32));
981 let value = b"payload";
982 let id = ObjectId::calculate(3, 1, value).unwrap();
983 let entry = CatalogEntry {
984 object_id: id,
985 kind: 3,
986 version: 1,
987 first_unit: 2,
988 byte_length: value.len() as u64,
989 unit_count: 1,
990 flags: 0,
991 };
992 let catalog = Catalog {
993 entries: vec![entry],
994 };
995 let cat_bytes = catalog.encode().unwrap();
996 let cat_id =
997 ObjectId::calculate(OBJECT_KIND_CATALOG, OBJECT_VERSION_V1, &cat_bytes).unwrap();
998 let commit = CommitRecord {
999 store_uuid: [0x5a; 16],
1000 region_units: dev.region_units(),
1001 generation: 1,
1002 previous_generation: 0,
1003 previous_commit_id: ObjectId([0; 32]),
1004 previous_catalog_id: ObjectId([0; 32]),
1005 catalog_id: cat_id,
1006 catalog_first_unit: 3,
1007 catalog_byte_length: cat_bytes.len() as u64,
1008 catalog_unit_count: 1,
1009 catalog_entry_count: 1,
1010 committed_high_water: 5,
1011 };
1012 let mut payload = [0; STORE_UNIT_BYTES];
1013 payload[..value.len()].copy_from_slice(value);
1014 dev.units[2] = payload;
1015 let mut cat_unit = [0; STORE_UNIT_BYTES];
1016 cat_unit[..cat_bytes.len()].copy_from_slice(&cat_bytes);
1017 dev.units[3] = cat_unit;
1018 let mut cr = [0; STORE_UNIT_BYTES];
1019 cr[..super::super::v1::COMMIT_RECORD_BYTES].copy_from_slice(&commit.encode().unwrap());
1020 dev.units[4] = cr;
1021 dev.units[0] = Superblock {
1022 store_uuid: commit.store_uuid,
1023 slot_id: 0,
1024 region_units: commit.region_units,
1025 generation: 1,
1026 commit_record_id: commit.object_id().unwrap(),
1027 commit_record_unit: 4,
1028 catalog_id: cat_id,
1029 catalog_first_unit: 3,
1030 catalog_byte_length: commit.catalog_byte_length,
1031 catalog_unit_count: 1,
1032 catalog_entry_count: 1,
1033 committed_high_water: 5,
1034 }
1035 .encode()
1036 .unwrap();
1037 dev.units[2][STORE_UNIT_BYTES - 1] = 1;
1038 assert_eq!(
1039 Store::open(dev.clone()).err().unwrap(),
1040 MountError::CorruptRecoveryRequired
1041 );
1042 let mut io_dev = dev;
1043 io_dev.fail_read = Some(4);
1044 assert_eq!(Store::open(io_dev).err().unwrap(), MountError::Io);
1045 }
1046
1047 #[test]
1048 fn store_history_matrix_equivalent_and_adjacent_roots() {
1049 assert_eq!(
1050 Store::open(seed_conflicting_same_generation_roots())
1051 .err()
1052 .unwrap(),
1053 MountError::ConflictingRoots
1054 );
1055 let store = Store::open(seed_genesis(blank(32))).unwrap();
1056 let mut dev = store.into_device();
1057 // Slot is part of the CRC'd bytes; re-encode the equivalent root.
1058 let root = Superblock::decode(&dev.units[0], 0).unwrap();
1059 let mut peer = root;
1060 peer.slot_id = 1;
1061 dev.units[1] = peer.encode().unwrap();
1062 let store = Store::open(dev).unwrap();
1063 assert_eq!(store.generation(), 1);
1064 let value = b"next";
1065 let mut store = store;
1066 store.transact(&one(value)).unwrap();
1067 let dev = store.into_device();
1068 assert_eq!(Store::open(dev).unwrap().generation(), 2);
1069
1070 let mut wrong_previous = seed_generation_two();
1071 let mut record =
1072 CommitRecord::decode(&wrong_previous.units[6][..super::super::v1::COMMIT_RECORD_BYTES])
1073 .unwrap();
1074 record.previous_commit_id = ObjectId([0x33; 32]);
1075 rewrite_commit(&mut wrong_previous, 1, 6, record);
1076 assert_eq!(
1077 Store::open(wrong_previous).err().unwrap(),
1078 MountError::InconsistentHistory
1079 );
1080
1081 let mut non_adjacent = seed_generation_two();
1082 let mut record =
1083 CommitRecord::decode(&non_adjacent.units[6][..super::super::v1::COMMIT_RECORD_BYTES])
1084 .unwrap();
1085 record.generation = 3;
1086 record.previous_generation = 2;
1087 rewrite_commit(&mut non_adjacent, 1, 6, record);
1088 assert_eq!(
1089 Store::open(non_adjacent).err().unwrap(),
1090 MountError::InconsistentHistory
1091 );
1092
1093 let mut damaged_new = seed_generation_two();
1094 damaged_new.units[4][0] ^= 1;
1095 let mut recovered = Store::open(damaged_new).unwrap();
1096 assert_eq!(recovered.mount_state(), MountState::DegradedRecovery);
1097 assert_eq!(
1098 recovered.transact(&one(b"read only")),
1099 Err(StoreError::ReadOnlyDegraded)
1100 );
1101
1102 let mut damaged_old = seed_generation_two();
1103 damaged_old.units[2][0] ^= 1;
1104 let recovered = Store::open(damaged_old).unwrap();
1105 assert_eq!(recovered.mount_state(), MountState::Valid);
1106 assert_eq!(recovered.generation(), 2);
1107 }
1108
1109 #[test]
1110 fn store_history_rejects_deleting_an_old_catalog_entry() {
1111 let mut dev = seed_generation_two();
1112 let previous =
1113 CommitRecord::decode(&dev.units[6][..super::super::v1::COMMIT_RECORD_BYTES]).unwrap();
1114 let catalog = Catalog {
1115 entries: Vec::new(),
1116 };
1117 let catalog_bytes = catalog.encode().unwrap();
1118 let catalog_id = ObjectId::calculate(OBJECT_KIND_CATALOG, 1, &catalog_bytes).unwrap();
1119 let mut catalog_unit = [0; STORE_UNIT_BYTES];
1120 catalog_unit[..catalog_bytes.len()].copy_from_slice(&catalog_bytes);
1121 dev.units[7] = catalog_unit;
1122 let commit = CommitRecord {
1123 store_uuid: previous.store_uuid,
1124 region_units: previous.region_units,
1125 generation: 3,
1126 previous_generation: 2,
1127 previous_commit_id: previous.object_id().unwrap(),
1128 previous_catalog_id: previous.catalog_id,
1129 catalog_id,
1130 catalog_first_unit: 7,
1131 catalog_byte_length: catalog_bytes.len() as u64,
1132 catalog_unit_count: 1,
1133 catalog_entry_count: 0,
1134 committed_high_water: 9,
1135 };
1136 dev.units[8][..super::super::v1::COMMIT_RECORD_BYTES]
1137 .copy_from_slice(&commit.encode().unwrap());
1138 dev.units[0] = Superblock {
1139 store_uuid: commit.store_uuid,
1140 slot_id: 0,
1141 region_units: commit.region_units,
1142 generation: 3,
1143 commit_record_id: commit.object_id().unwrap(),
1144 commit_record_unit: 8,
1145 catalog_id,
1146 catalog_first_unit: 7,
1147 catalog_byte_length: catalog_bytes.len() as u64,
1148 catalog_unit_count: 1,
1149 catalog_entry_count: 0,
1150 committed_high_water: 9,
1151 }
1152 .encode()
1153 .unwrap();
1154 assert_eq!(
1155 Store::open(dev).err().unwrap(),
1156 MountError::InconsistentHistory
1157 );
1158 }
1159
1160 #[test]
1161 fn store_mount_classification_is_deterministic() {
1162 assert_eq!(
1163 Store::open(blank(8)).err().unwrap(),
1164 MountError::Unformatted
1165 );
1166 let mut foreign = blank(8);
1167 foreign.units[0][0] = 0x77;
1168 assert_eq!(
1169 Store::open(foreign).err().unwrap(),
1170 MountError::ForeignOrUnknown
1171 );
1172
1173 let mut unsupported = seed_genesis(blank(8));
1174 unsupported.units[0][8..10].copy_from_slice(&2u16.to_le_bytes());
1175 unsupported.units[0][168..172].fill(0);
1176 let crc = super::super::v1::crc32c(&unsupported.units[0]);
1177 unsupported.units[0][168..172].copy_from_slice(&crc.to_le_bytes());
1178 assert_eq!(
1179 Store::open(unsupported).err().unwrap(),
1180 MountError::UnsupportedVersion
1181 );
1182
1183 let mut bad_crc = seed_genesis(blank(8));
1184 bad_crc.units[0][168] ^= 1;
1185 assert_eq!(
1186 Store::open(bad_crc).err().unwrap(),
1187 MountError::CorruptRecoveryRequired
1188 );
1189 }
1190
1191 #[test]
1192 fn store_nospace_zero_writes() {
1193 let mut store = Store::open(seed_genesis(blank(6))).unwrap();
1194 assert_eq!(
1195 store.transact(&one(b"cannot fit")),
1196 Err(StoreError::NoSpace)
1197 );
1198 let dev = store.into_device();
1199 assert!(dev.writes.is_empty());
1200 assert_eq!(dev.flushes, 0);
1201 }
1202
1203 #[test]
1204 fn store_catalogfull_zero_writes() {
1205 let mut store = Store::open(seed_full_catalog()).unwrap();
1206 assert_eq!(
1207 store.transact(&one(b"new object")),
1208 Err(StoreError::CatalogFull)
1209 );
1210 let dev = store.into_device();
1211 assert!(dev.writes.is_empty());
1212 assert_eq!(dev.flushes, 0);
1213 }
1214
1215 #[test]
1216 fn store_generation_overflow_zero_writes() {
1217 let mut store = Store::open(seed_genesis(blank(32))).unwrap();
1218 store.root.commit.generation = u64::MAX;
1219 store.root.superblock.generation = u64::MAX;
1220 assert_eq!(
1221 store.transact(&one(b"overflow")),
1222 Err(StoreError::GenerationExhausted)
1223 );
1224 let dev = store.into_device();
1225 assert!(dev.writes.is_empty());
1226 assert_eq!(dev.flushes, 0);
1227 }
1228
1229 #[test]
1230 fn store_transaction_commit_dedup_and_tail_reuse() {
1231 let mut dev = seed_genesis(blank(32));
1232 dev.units[4].fill(0xa5); // uncommitted tail is reusable
1233 let mut store = Store::open(dev).unwrap();
1234 let value = b"committed payload";
1235 store.transact(&one(value)).unwrap();
1236 assert_eq!(store.generation(), 2);
1237 let dev = store.into_device();
1238 assert!(dev.writes.contains(&4));
1239 assert_eq!(dev.flushes, 2);
1240 let mut store = Store::open(dev).unwrap();
1241 let payload_id = ObjectId::calculate(3, 1, value).unwrap();
1242 let before = store.device.writes.len();
1243 store.transact(&one(value)).unwrap();
1244 let writes = &store.device.writes[before..];
1245 assert_eq!(writes, &[7, 8, 0]); // catalog, commit record, inactive root only
1246 assert_eq!(store.read_object(payload_id).unwrap(), value);
1247 }
1248
1249 #[test]
1250 fn store_checkpoint_order_does_not_change_persistent_bytes() {
1251 let initial = seed_genesis(blank(32));
1252 let mut plain = Store::open(initial.clone()).unwrap();
1253 plain.transact(&one(b"checkpointed")).unwrap();
1254 let plain = plain.into_device();
1255
1256 let mut observed = Store::open(initial).unwrap();
1257 let mut checkpoints = Vec::new();
1258 observed
1259 .transact_with_hook(&one(b"checkpointed"), |checkpoint| {
1260 checkpoints.push(checkpoint)
1261 })
1262 .unwrap();
1263 let observed = observed.into_device();
1264 assert_eq!(checkpoints, Checkpoint::ORDERED);
1265 assert_eq!(observed.units, plain.units);
1266 assert_eq!(observed.writes, plain.writes);
1267 assert_eq!(observed.flushes, plain.flushes);
1268 }
1269
1270 #[test]
1271 fn store_dedup_corruption_and_descriptor_conflict_fail_before_writes() {
1272 let mut store = Store::open(seed_genesis(blank(32))).unwrap();
1273 let value = b"dedup target";
1274 store.transact(&one(value)).unwrap();
1275 let mut store = Store::open(store.into_device()).unwrap();
1276 store.device.writes.clear();
1277 store.device.flushes = 0;
1278 store.device.units[4][0] ^= 1;
1279 assert_eq!(store.transact(&one(value)), Err(StoreError::Corrupt));
1280 assert!(store.device.writes.is_empty());
1281 assert_eq!(store.device.flushes, 0);
1282
1283 let mut store = Store::open(seed_generation_two()).unwrap();
1284 let id = store.root.catalog.entries[0].object_id;
1285 store.root.catalog.entries[0].kind += 1;
1286 store.device.writes.clear();
1287 store.device.flushes = 0;
1288 let conflicting = [ObjectInput {
1289 kind: 3,
1290 version: 1,
1291 bytes: b"next generation",
1292 }];
1293 assert_eq!(
1294 store.transact(&conflicting),
1295 Err(StoreError::DuplicateObjectConflict)
1296 );
1297 assert_eq!(store.root.catalog.entries[0].object_id, id);
1298 assert!(store.device.writes.is_empty());
1299 assert_eq!(store.device.flushes, 0);
1300 }
1301
1302 #[test]
1303 fn store_io_fail_closed() {
1304 let mut dev = seed_genesis(blank(32));
1305 dev.fail_read = Some(3);
1306 assert_eq!(Store::open(dev).err().unwrap(), MountError::Io);
1307 let mut store = Store::open(seed_genesis(blank(32))).unwrap();
1308 store.device.fail_write = Some(4);
1309 assert_eq!(store.transact(&one(b"fault")), Err(StoreError::Io));
1310 assert_eq!(store.transact(&one(b"again")), Err(StoreError::NeedsReopen));
1311 }
1312
1313 #[test]
1314 fn store_peer_condition_reports_open_classification() {
1315 let store = Store::open(seed_genesis(blank(32))).unwrap();
1316 assert_eq!(store.peer_condition(), PeerCondition::Zero);
1317
1318 let mut store = store;
1319 store.transact(&one(b"second generation")).unwrap();
1320 assert_eq!(store.peer_condition(), PeerCondition::Valid);
1321 let dev = store.into_device();
1322 let reopened = Store::open(dev).unwrap();
1323 assert_eq!(reopened.mount_state(), MountState::Valid);
1324 assert_eq!(reopened.peer_condition(), PeerCondition::Valid);
1325
1326 // Newer root whose commit record is gone: older root mounts read-only.
1327 let mut dev = reopened.into_device();
1328 let newer = Superblock::decode(&dev.units[1], 1).unwrap();
1329 assert_eq!(newer.generation, 2);
1330 dev.units[newer.commit_record_unit as usize] = [0; STORE_UNIT_BYTES];
1331 let store = Store::open(dev).unwrap();
1332 assert_eq!(store.generation(), 1);
1333 assert_eq!(store.mount_state(), MountState::DegradedRecovery);
1334 assert_eq!(store.peer_condition(), PeerCondition::GraphBadNewer);
1335 }
1336
1337 #[test]
1338 fn store_malformed_peer_recovery_matrix() {
1339 let rechecksum = |bytes: &mut [u8; STORE_UNIT_BYTES]| {
1340 bytes[168..172].fill(0);
1341 let crc = super::super::v1::crc32c(bytes);
1342 bytes[168..172].copy_from_slice(&crc.to_le_bytes());
1343 };
1344
1345 // 1. Bad CRC peer: Valid root in slot 0 + bad CRC in slot 1 -> DegradedRecovery
1346 let mut dev = seed_genesis(blank(32));
1347 dev.units[1][..8].copy_from_slice(b"AIENSTR1");
1348 dev.units[1][168] ^= 1;
1349 let store = Store::open(dev).unwrap();
1350 assert_eq!(store.mount_state(), MountState::DegradedRecovery);
1351 assert_eq!(store.peer_condition(), PeerCondition::Malformed);
1352 assert_eq!(store.generation(), 1);
1353
1354 // 2. Wrong magic peer: Valid root in slot 0 + non-zero wrong magic in slot 1 -> DegradedRecovery
1355 let mut dev = seed_genesis(blank(32));
1356 dev.units[1][..8].copy_from_slice(b"BADMAGIC");
1357 let store = Store::open(dev).unwrap();
1358 assert_eq!(store.mount_state(), MountState::DegradedRecovery);
1359 assert_eq!(store.peer_condition(), PeerCondition::Malformed);
1360 assert_eq!(store.generation(), 1);
1361
1362 // 3. Malformed shape peer: Valid root in slot 0 + non-zero reserved in slot 1 -> DegradedRecovery
1363 let mut dev = seed_genesis(blank(32));
1364 let root = Superblock::decode(&dev.units[0], 0).unwrap();
1365 let mut peer = root;
1366 peer.slot_id = 1;
1367 dev.units[1] = peer.encode().unwrap();
1368 dev.units[1][200] = 0xff; // non-zero reserved byte
1369 rechecksum(&mut dev.units[1]);
1370 let store = Store::open(dev).unwrap();
1371 assert_eq!(store.mount_state(), MountState::DegradedRecovery);
1372 assert_eq!(store.peer_condition(), PeerCondition::Malformed);
1373 assert_eq!(store.generation(), 1);
1374
1375 // 4. Unsupported version peer: Valid root in slot 0 + CRC-valid major=2 in slot 1 -> UnsupportedVersion
1376 let mut dev = seed_genesis(blank(32));
1377 let root = Superblock::decode(&dev.units[0], 0).unwrap();
1378 let mut peer = root;
1379 peer.slot_id = 1;
1380 dev.units[1] = peer.encode().unwrap();
1381 dev.units[1][8..10].copy_from_slice(&2u16.to_le_bytes()); // major = 2
1382 rechecksum(&mut dev.units[1]);
1383 assert_eq!(
1384 Store::open(dev).err().unwrap(),
1385 MountError::UnsupportedVersion
1386 );
1387
1388 // 5. I/O failure peer: Valid root in slot 0 + read error on slot 1 -> MountError::Io
1389 let mut dev = seed_genesis(blank(32));
1390 dev.fail_read = Some(1);
1391 assert_eq!(Store::open(dev).err().unwrap(), MountError::Io);
1392
1393 // 6. Two bad roots: bad CRC on slot 0 and slot 1 -> MountError::CorruptRecoveryRequired
1394 let mut dev = seed_genesis(blank(32));
1395 dev.units[0][168] ^= 1;
1396 dev.units[1][..8].copy_from_slice(b"AIENSTR1");
1397 dev.units[1][168] ^= 1;
1398 assert_eq!(
1399 Store::open(dev).err().unwrap(),
1400 MountError::CorruptRecoveryRequired
1401 );
1402
1403 // 7. Transact on DegradedRecovery -> Err(StoreError::ReadOnlyDegraded)
1404 let mut dev = seed_genesis(blank(32));
1405 dev.units[1][..8].copy_from_slice(b"BADMAGIC");
1406 let mut store = Store::open(dev).unwrap();
1407 assert_eq!(store.mount_state(), MountState::DegradedRecovery);
1408 assert_eq!(
1409 store.transact(&one(b"blocked mutation")),
1410 Err(StoreError::ReadOnlyDegraded)
1411 );
1412 }
1413}