Skip to main content

storage_kit/store/
mod.rs

1//! Partition / packfile management — format v3.
2//!
3//! A `PartitionStore` owns exactly one partition's on-disk subtree:
4//!
5//! ```text
6//! <store_root>/<partition_id_hex>/
7//!   active/active.pack        — currently-open, appendable pack (no trailer)
8//!   packs/<xx>/<pack_id>.pack — sealed, immutable, content-addressed packs
9//!   packs/<xx>/<pack_id>.idx  — derived index, rebuildable, never authoritative
10//!   manifests/*.json          — manifests ingested into this partition
11//! ```
12//!
13//! No pack file, and no `PartitionStore`, ever spans more than one
14//! partition — that's the physical boundary the whole GC and dedup story
15//! relies on.
16
17pub mod packfile;
18
19use crate::addressing::{Hash, PartitionId};
20use crate::error::{Result, StorageError};
21use crate::partition::{self, EncryptionMode, PartitionRecord, PartitionSpec, RetentionClass};
22use packfile::PackWriter;
23use std::collections::HashMap;
24use std::fs;
25use std::path::{Path, PathBuf};
26
27/// Soft cap: an active pack is sealed once it reaches this size.
28pub const SEAL_CAP_BYTES: u64 = 128 * 1024 * 1024;
29
30/// Enumerate every **provisioned** partition under `store_root` — one with
31/// a `partition.json` record, not merely a 32-hex-char directory. Used by
32/// CLI commands (`ls`, `gc`, `push`) that operate "over every partition"
33/// when the caller doesn't name one explicitly.
34///
35/// Spec §3.7 rule 4: mkdir-on-first-write ended with the `create`/`open`
36/// split, so a bare directory with no record is an orphan, not a
37/// partition — `list_partitions` never reports one.
38pub fn list_partitions(store_root: &Path) -> Result<Vec<PartitionId>> {
39    if !store_root.exists() {
40        return Ok(Vec::new());
41    }
42    let mut out = Vec::new();
43    for entry in fs::read_dir(store_root)? {
44        let entry = entry?;
45        if !entry.file_type()?.is_dir() {
46            continue;
47        }
48        let name = entry.file_name();
49        let Some(name) = name.to_str() else { continue };
50        if name.len() == 32 && name.chars().all(|c| c.is_ascii_hexdigit()) {
51            let partition_id = PartitionId::from_hex(name)?;
52            if partition::is_provisioned(store_root, partition_id) {
53                out.push(partition_id);
54            }
55        }
56    }
57    out.sort_by_key(|p| p.to_hex());
58    Ok(out)
59}
60
61/// The full content-addressed storage contract a backend must satisfy:
62/// partition-scoped, immutable once written, hash-verified on every read.
63///
64/// Naming reconciliation (the design review, 2026-08-23): the 2026-06
65/// storage-alignment lock specified `ImmutableStore`/`MutableStore` as the
66/// trait vocabulary; the shipped v2 code (pre-relocation) split this same
67/// contract into `ReadBlock`/`WriteBlock` sub-traits plus a composed
68/// `ImmutableStore` marker. This trait collapses that split — same four
69/// methods, same signatures, same implementors — under the single locked
70/// name. No behavior changed by the collapse.
71pub trait ImmutableStore {
72    /// Fetch and verify content by hash.
73    fn get(&self, hash: &Hash) -> Result<Vec<u8>>;
74    fn has(&self, hash: &Hash) -> bool;
75    /// Store `data`, returning its content hash. A `put` for content already
76    /// present in this partition is a no-op dedup hit, not a duplicate
77    /// write.
78    fn put(&mut self, data: &[u8]) -> Result<Hash>;
79    fn partition_id(&self) -> PartitionId;
80}
81
82/// Cache-state store for the bitchain *protocol* layer (e.g. a "latest"
83/// pointer keyed by name) — distinct from [`ImmutableStore`], which has no
84/// notion of a mutable pointer: every address it serves is a stable content
85/// hash. Declared per the 2026-06 lock's target trait shape so the
86/// vocabulary exists; no implementation ships with this relocation
87/// — bitchain's manifest protocol treats manifests as immutable,
88/// content-addressed artifacts and has no current caller for this trait.
89pub trait MutableStore {
90    fn load(&self, key: &str) -> Result<Vec<u8>>;
91    fn store(&mut self, key: &str, data: &[u8]) -> Result<()>;
92    /// Compare-and-swap: succeeds (returns `Ok(true)`) only if the value
93    /// currently stored at `key` equals `expected` (`None` means "key must
94    /// not exist yet").
95    fn cas(&mut self, key: &str, expected: Option<&[u8]>, new: &[u8]) -> Result<bool>;
96    fn list(&self, prefix: &str) -> Result<Vec<String>>;
97}
98
99struct SealedPack {
100    pack_id: Hash,
101    path: PathBuf,
102    /// hash -> (byte offset, full entry meta) within this pack. Carries the
103    /// full record, not merely the offset, so a meta-preserving copy (GC's
104    /// repack) can read an entry's meta straight from the loaded index
105    /// without touching the pack at all.
106    offsets: HashMap<Hash, (u64, packfile::EntryMeta)>,
107}
108
109/// The reference `ImmutableStore` implementation: a single partition's
110/// packfiles on the local filesystem.
111pub struct PartitionStore {
112    root: PathBuf,
113    partition_id: PartitionId,
114    record: PartitionRecord,
115    active: PackWriter,
116    sealed: Vec<SealedPack>,
117    /// hash -> index into `sealed`, for O(1) dispatch on read.
118    sealed_lookup: HashMap<Hash, usize>,
119}
120
121impl PartitionStore {
122    /// Provision a new partition (spec §3.7). Fails with
123    /// [`StorageError::PartitionAlreadyProvisioned`] if `partition.json`
124    /// already exists. **The only place a partition directory is ever
125    /// created** — `open` creates none.
126    ///
127    /// Verifies `PartitionId::derive("{subject.kind}:{subject.id}") ==
128    /// partition_id`: a partition cannot be provisioned under a subject it
129    /// was not derived from. Writes the portable record
130    /// (`partition.json`, inside the partition directory, replicated) and
131    /// the local subject binding (`partitions.local.json`, at the store
132    /// root, never replicated) as two separate writes — see
133    /// [`crate::partition`] for why they are split.
134    ///
135    /// There is no default retention class: `spec.retention_class` is a
136    /// required field, and this method never substitutes one.
137    pub fn create(
138        store_root: &Path,
139        partition_id: PartitionId,
140        spec: PartitionSpec,
141    ) -> Result<Self> {
142        partition::verify_derivation(partition_id, &spec.subject)?;
143
144        if partition::is_provisioned(store_root, partition_id) {
145            return Err(StorageError::PartitionAlreadyProvisioned(
146                partition_id.to_hex(),
147            ));
148        }
149
150        let root = store_root.join(partition_id.to_hex());
151        fs::create_dir_all(&root)?;
152
153        let record =
154            partition::new_record(partition_id, spec.retention_class, spec.encryption_mode);
155        partition::write_new_record(store_root, partition_id, &record)?;
156        partition::bind_local(store_root, partition_id, &spec.subject, &spec.label)?;
157
158        Self::open_provisioned(store_root, partition_id, record)
159    }
160
161    /// Open an already-provisioned partition (spec §3.7). Fails with
162    /// [`StorageError::PartitionNotProvisioned`] if `partition.json` is
163    /// absent — there is no default retention class or fallback
164    /// behaviour, because defaulting here would be exactly the "decide
165    /// retention at ingest, not retrofit it" rule the record exists to
166    /// enforce. Creates no directories. Rebuilds/self-heals any missing
167    /// `.idx` files from their `.pack` counterparts — the index is
168    /// derived, never trusted blindly.
169    ///
170    /// Does **not** require `partitions.local.json` to have an entry for
171    /// this partition — a replica has no local binding and is still
172    /// readable.
173    pub fn open(store_root: &Path, partition_id: PartitionId) -> Result<Self> {
174        if !partition::is_provisioned(store_root, partition_id) {
175            return Err(StorageError::PartitionNotProvisioned(partition_id.to_hex()));
176        }
177        let record = partition::load_record(store_root, partition_id)?;
178        Self::open_provisioned(store_root, partition_id, record)
179    }
180
181    /// Shared mechanics for `create`/`open` once `partition.json` is known
182    /// to exist and has been loaded: scan sealed packs, open the active
183    /// pack. Both callers have already established provisioning; this
184    /// step performs no provisioning decisions of its own.
185    fn open_provisioned(
186        store_root: &Path,
187        partition_id: PartitionId,
188        record: PartitionRecord,
189    ) -> Result<Self> {
190        let root = store_root.join(partition_id.to_hex());
191        let packs_dir = root.join("packs");
192        let active_path = root.join("active").join("active.pack");
193        fs::create_dir_all(&packs_dir)?;
194
195        let active = PackWriter::open_active(&active_path, partition_id)?;
196
197        let mut sealed = Vec::new();
198        let mut sealed_lookup = HashMap::new();
199        if packs_dir.exists() {
200            for shard_entry in fs::read_dir(&packs_dir)? {
201                let shard_entry = shard_entry?;
202                if !shard_entry.file_type()?.is_dir() {
203                    continue;
204                }
205                for pack_entry in fs::read_dir(shard_entry.path())? {
206                    let pack_entry = pack_entry?;
207                    let path = pack_entry.path();
208                    if path.extension().and_then(|e| e.to_str()) != Some("pack") {
209                        continue;
210                    }
211                    let pack_id_hex = path
212                        .file_stem()
213                        .and_then(|s| s.to_str())
214                        .ok_or_else(|| StorageError::CorruptPack("bad pack filename".into()))?
215                        .to_string();
216                    let pack_id = Hash::from_hex(&pack_id_hex)?;
217
218                    let idx_path = path.with_extension("idx");
219                    let offsets = match packfile::read_index(&idx_path) {
220                        Ok(idx) => idx,
221                        Err(_) => {
222                            // Self-heal: rebuild from the pack and persist.
223                            let entries = packfile::rebuild_index_entries(&path)?;
224                            packfile::write_index(&idx_path, &partition_id, &entries)?;
225                            entries
226                                .into_iter()
227                                .map(|(off, m)| (m.hash, (off, m)))
228                                .collect()
229                        }
230                    };
231
232                    let idx = sealed.len();
233                    for hash in offsets.keys() {
234                        sealed_lookup.insert(*hash, idx);
235                    }
236                    sealed.push(SealedPack {
237                        pack_id,
238                        path,
239                        offsets,
240                    });
241                }
242            }
243        }
244
245        Ok(PartitionStore {
246            root,
247            partition_id,
248            record,
249            active,
250            sealed,
251            sealed_lookup,
252        })
253    }
254
255    pub fn partition_root(&self) -> &Path {
256        &self.root
257    }
258
259    /// The portable partition record this store was opened with.
260    /// Deliberately carries no [`crate::partition::Subject`] — see
261    /// [`crate::partition`]'s module docs for why that omission is the
262    /// guarantee, not an oversight.
263    pub fn record(&self) -> &PartitionRecord {
264        &self.record
265    }
266
267    /// This partition's retention class. Immutable for the partition's
268    /// lifetime — there is no `set_retention_class`; no transition is
269    /// legal in either direction. Minting a new partition and copying into
270    /// it is the only way to change one.
271    pub fn retention_class(&self) -> RetentionClass {
272        self.record.retention_class
273    }
274
275    /// This partition's encryption mode. Immutable for the partition's
276    /// lifetime — there is no `set_encryption_mode`; no transition is legal
277    /// in either direction. Minting a new partition and copying into it is
278    /// the only way to change one. This crate implements no encryption
279    /// today; `plaintext` is the only value any current caller can produce.
280    pub fn encryption_mode(&self) -> EncryptionMode {
281        self.record.encryption_mode
282    }
283
284    pub fn packs_dir(&self) -> PathBuf {
285        self.root.join("packs")
286    }
287
288    pub fn manifests_dir(&self) -> PathBuf {
289        self.root.join("manifests")
290    }
291
292    /// Persist `manifest_json` under this partition's `manifests/` tree so
293    /// `gc` can discover it as a root to keep alive.
294    pub fn write_manifest(&self, name: &str, manifest_json: &str) -> Result<PathBuf> {
295        let dir = self.manifests_dir();
296        fs::create_dir_all(&dir)?;
297        let path = dir.join(format!("{name}.json"));
298        fs::write(&path, manifest_json)?;
299        Ok(path)
300    }
301
302    pub fn list_manifests(&self) -> Result<Vec<PathBuf>> {
303        let dir = self.manifests_dir();
304        if !dir.exists() {
305            return Ok(Vec::new());
306        }
307        let mut out = Vec::new();
308        for entry in fs::read_dir(dir)? {
309            let entry = entry?;
310            if entry.path().extension().and_then(|e| e.to_str()) == Some("json") {
311                out.push(entry.path());
312            }
313        }
314        out.sort();
315        Ok(out)
316    }
317
318    /// List every entry hash currently reachable in this partition — both
319    /// sealed packs and the active pack.
320    pub fn all_hashes(&self) -> Vec<Hash> {
321        let mut out: Vec<Hash> = self.active.offsets.keys().copied().collect();
322        for pack in &self.sealed {
323            out.extend(pack.offsets.keys().copied());
324        }
325        out
326    }
327
328    pub fn sealed_pack_ids(&self) -> Vec<Hash> {
329        self.sealed.iter().map(|p| p.pack_id).collect()
330    }
331
332    /// Number of entries written into the still-open active pack (not yet
333    /// sealed into an immutable `.pack`). Exposed for `ls` summaries.
334    pub fn active_entry_count(&self) -> u64 {
335        self.active.entry_count
336    }
337
338    /// Verify every sealed pack's trailer + every entry's hash across the
339    /// whole partition (sealed and active). Returns the number of entries
340    /// checked.
341    pub fn verify_all(&self) -> Result<u64> {
342        let mut checked = 0u64;
343        for pack in &self.sealed {
344            packfile::verify_trailer(&pack.path)?;
345            for (offset, _meta) in pack.offsets.values() {
346                packfile::get_at(&pack.path, *offset)?;
347                checked += 1;
348            }
349        }
350        // Active pack has no trailer yet; verify each entry by hash.
351        for hash in self.active.offsets.keys() {
352            self.get(hash)?;
353            checked += 1;
354        }
355        Ok(checked)
356    }
357
358    fn seal_active_if_over_cap(&mut self) -> Result<()> {
359        if self.active.len < SEAL_CAP_BYTES {
360            return Ok(());
361        }
362        let fresh_active_path = self.root.join("active").join("active.pack");
363        let old = std::mem::replace(
364            &mut self.active,
365            // Placeholder; immediately overwritten below. `open_active` on
366            // a not-yet-existing path is cheap (just a header write).
367            PackWriter::open_active(
368                &fresh_active_path.with_extension("pack.next"),
369                self.partition_id,
370            )?,
371        );
372        let (pack_id, path) = old.seal(&self.packs_dir())?;
373        let offsets = packfile::read_index(&path.with_extension("idx"))?;
374        let idx = self.sealed.len();
375        for hash in offsets.keys() {
376            self.sealed_lookup.insert(*hash, idx);
377        }
378        self.sealed.push(SealedPack {
379            pack_id,
380            path,
381            offsets,
382        });
383        // Replace the throwaway placeholder with the real fresh active pack.
384        let _ = fs::remove_file(fresh_active_path.with_extension("pack.next"));
385        self.active = PackWriter::open_active(&fresh_active_path, self.partition_id)?;
386        Ok(())
387    }
388
389    /// Force-seal the current active pack even if it hasn't hit the soft
390    /// cap. Used by `gc` (which needs a clean set of sealed packs to
391    /// rewrite) and is otherwise optional — the 128 MiB cap is the normal
392    /// trigger.
393    pub fn seal_active(&mut self) -> Result<Option<Hash>> {
394        if self.active.entry_count == 0 {
395            return Ok(None);
396        }
397        let fresh_active_path = self.root.join("active").join("active.pack");
398        let old = std::mem::replace(
399            &mut self.active,
400            PackWriter::open_active(
401                &fresh_active_path.with_extension("pack.sealing"),
402                self.partition_id,
403            )?,
404        );
405        let (pack_id, path) = old.seal(&self.packs_dir())?;
406        let offsets = packfile::read_index(&path.with_extension("idx"))?;
407        let idx = self.sealed.len();
408        for hash in offsets.keys() {
409            self.sealed_lookup.insert(*hash, idx);
410        }
411        self.sealed.push(SealedPack {
412            pack_id,
413            path,
414            offsets,
415        });
416        let _ = fs::remove_file(fresh_active_path.with_extension("pack.sealing"));
417        self.active = PackWriter::open_active(&fresh_active_path, self.partition_id)?;
418        Ok(Some(pack_id))
419    }
420}
421
422impl PartitionStore {
423    /// Fetch `(meta, payload)` for `hash` **without** decoding, hash-
424    /// verifying, or validating reserved fields — the raw, byte-exact form
425    /// a meta-preserving copy (GC's repack) needs so it can relocate an
426    /// entry without interpreting what it means. Contrast
427    /// [`ImmutableStore::get`], which is the validated, decoded, verified
428    /// form real content reads go through. Additive: not part of the
429    /// frozen `ImmutableStore` trait.
430    pub fn get_raw(&self, hash: &Hash) -> Result<(packfile::EntryMeta, Vec<u8>)> {
431        if let Some(offset) = self.active.offsets.get(hash) {
432            return self.active.read_payload_at(*offset);
433        }
434        if let Some(&idx) = self.sealed_lookup.get(hash) {
435            let pack = &self.sealed[idx];
436            let (offset, _meta) = *pack.offsets.get(hash).ok_or_else(|| {
437                StorageError::NotFound(format!("{hash} indexed but missing in pack"))
438            })?;
439            return packfile::get_raw_at(&pack.path, offset);
440        }
441        Err(StorageError::NotFound(hash.to_hex()))
442    }
443
444    /// Append `payload` verbatim under `meta` — the byte-exact primitive a
445    /// meta-preserving copy (GC's repack) needs, bypassing the normal
446    /// encode path. `meta.hash` is trusted as-is: the caller is relocating
447    /// an already-hashed entry forward, not producing new content. Still
448    /// dedups against what this partition already holds. Additive: not
449    /// part of the frozen `ImmutableStore` trait, and carries no validation
450    /// — see [`packfile::EntryMeta::validate_reserved`]'s module docs for
451    /// why a byte-mover is deliberately meta-blind.
452    pub fn put_raw(&mut self, meta: packfile::EntryMeta, payload: &[u8]) -> Result<Hash> {
453        if self.has(&meta.hash) {
454            return Ok(meta.hash); // per-partition dedup, keyed by hash only
455        }
456        self.active.append_raw(&meta, payload)?;
457        self.seal_active_if_over_cap()?;
458        Ok(meta.hash)
459    }
460}
461
462impl ImmutableStore for PartitionStore {
463    fn get(&self, hash: &Hash) -> Result<Vec<u8>> {
464        if let Some(offset) = self.active.offsets.get(hash) {
465            let (meta, payload) = self.active.read_payload_at(*offset)?;
466            meta.validate_reserved()?;
467            let decoded = packfile::decode(meta.codec, &payload)?;
468            let actual = Hash::of(&decoded);
469            if actual != *hash {
470                return Err(StorageError::HashMismatch {
471                    expected: hash.to_hex(),
472                    actual: actual.to_hex(),
473                });
474            }
475            return Ok(decoded);
476        }
477        if let Some(&idx) = self.sealed_lookup.get(hash) {
478            let pack = &self.sealed[idx];
479            let (offset, _meta) = *pack.offsets.get(hash).ok_or_else(|| {
480                StorageError::NotFound(format!("{hash} indexed but missing in pack"))
481            })?;
482            return packfile::get_at(&pack.path, offset);
483        }
484        Err(StorageError::NotFound(hash.to_hex()))
485    }
486
487    fn has(&self, hash: &Hash) -> bool {
488        self.active.offsets.contains_key(hash) || self.sealed_lookup.contains_key(hash)
489    }
490
491    fn put(&mut self, data: &[u8]) -> Result<Hash> {
492        let hash = Hash::of(data);
493        if self.has(&hash) {
494            return Ok(hash); // per-partition dedup, keyed by hash only
495        }
496        let (codec, payload) = packfile::encode(data)?;
497        self.active
498            .append(hash, codec, data.len() as u64, &payload)?;
499        self.seal_active_if_over_cap()?;
500        Ok(hash)
501    }
502
503    fn partition_id(&self) -> PartitionId {
504        self.partition_id
505    }
506}
507
508#[cfg(test)]
509mod tests {
510    use super::*;
511    use crate::partition::{Subject, SubjectKind};
512    use tempfile::tempdir;
513
514    /// Provision a person partition for `name` with `retention_class`,
515    /// via the real `create()` path — mkdir-on-first-write ended, so every
516    /// test that wants a working store must provision one explicitly now.
517    fn create_person(dir: &Path, name: &str, retention_class: RetentionClass) -> PartitionStore {
518        let partition_id = PartitionId::for_person(name);
519        let spec = PartitionSpec {
520            subject: Subject {
521                kind: SubjectKind::Person,
522                id: name.to_string(),
523            },
524            retention_class,
525            encryption_mode: EncryptionMode::Plaintext,
526            label: None,
527        };
528        PartitionStore::create(dir, partition_id, spec).unwrap()
529    }
530
531    #[test]
532    fn put_dedups_within_partition() {
533        let dir = tempdir().unwrap();
534        let mut store = create_person(dir.path(), "dedup-test", RetentionClass::Standard);
535
536        let h1 = store.put(b"same bytes").unwrap();
537        let h2 = store.put(b"same bytes").unwrap();
538        assert_eq!(h1, h2);
539        assert_eq!(
540            store.active.entry_count, 1,
541            "second put must be a dedup no-op"
542        );
543    }
544
545    #[test]
546    fn put_then_get_roundtrips() {
547        let dir = tempdir().unwrap();
548        let mut store = create_person(dir.path(), "roundtrip-test", RetentionClass::Standard);
549        let hash = store.put(b"round trip me").unwrap();
550        let back = store.get(&hash).unwrap();
551        assert_eq!(back, b"round trip me");
552    }
553
554    #[test]
555    fn seal_then_reopen_still_reads() {
556        let dir = tempdir().unwrap();
557        let partition_id = PartitionId::for_person("seal-reopen-test");
558        let hash;
559        {
560            let mut store = create_person(dir.path(), "seal-reopen-test", RetentionClass::Standard);
561            hash = store.put(b"persist across reopen").unwrap();
562            store.seal_active().unwrap();
563        }
564        let store2 = PartitionStore::open(dir.path(), partition_id).unwrap();
565        let back = store2.get(&hash).unwrap();
566        assert_eq!(back, b"persist across reopen");
567    }
568
569    #[test]
570    fn partitions_are_isolated_directories() {
571        let dir = tempdir().unwrap();
572        let mut store_a = create_person(dir.path(), "partition-a", RetentionClass::Standard);
573        let mut store_b = create_person(dir.path(), "partition-b", RetentionClass::Standard);
574
575        let hash_a = store_a.put(b"only in a").unwrap();
576        let _hash_b = store_b.put(b"only in b").unwrap();
577
578        assert!(store_a.has(&hash_a));
579        assert!(!store_b.has(&hash_a));
580        assert_ne!(store_a.partition_root(), store_b.partition_root());
581    }
582
583    #[test]
584    fn open_on_an_unprovisioned_partition_fails() {
585        let dir = tempdir().unwrap();
586        let partition_id = PartitionId::for_person("never-created");
587        let err = match PartitionStore::open(dir.path(), partition_id) {
588            Err(e) => e,
589            Ok(_) => panic!("open() must not create a partition on first use"),
590        };
591        assert!(matches!(err, StorageError::PartitionNotProvisioned(_)));
592    }
593
594    #[test]
595    fn open_creates_no_directory() {
596        let dir = tempdir().unwrap();
597        let partition_id = PartitionId::for_person("open-creates-nothing");
598        let _ = PartitionStore::open(dir.path(), partition_id);
599        assert!(
600            !dir.path().join(partition_id.to_hex()).exists(),
601            "open() on an unprovisioned partition must create no directory"
602        );
603    }
604
605    #[test]
606    fn create_twice_fails_already_provisioned() {
607        let dir = tempdir().unwrap();
608        let partition_id = PartitionId::for_person("double-create");
609        let spec = || PartitionSpec {
610            subject: Subject {
611                kind: SubjectKind::Person,
612                id: "double-create".to_string(),
613            },
614            retention_class: RetentionClass::Standard,
615            encryption_mode: EncryptionMode::Plaintext,
616            label: None,
617        };
618        PartitionStore::create(dir.path(), partition_id, spec()).unwrap();
619        let err = match PartitionStore::create(dir.path(), partition_id, spec()) {
620            Err(e) => e,
621            Ok(_) => panic!("re-provisioning the same partition must fail"),
622        };
623        assert!(matches!(err, StorageError::PartitionAlreadyProvisioned(_)));
624    }
625
626    #[test]
627    fn create_rejects_a_subject_that_does_not_derive_the_partition_id() {
628        let dir = tempdir().unwrap();
629        // Deliberately mismatched: this id was not derived from the subject.
630        let partition_id = PartitionId::for_person("someone-else");
631        let spec = PartitionSpec {
632            subject: Subject {
633                kind: SubjectKind::Person,
634                id: "not-someone-else".to_string(),
635            },
636            retention_class: RetentionClass::Standard,
637            encryption_mode: EncryptionMode::Plaintext,
638            label: None,
639        };
640        let err = match PartitionStore::create(dir.path(), partition_id, spec) {
641            Err(e) => e,
642            Ok(_) => panic!(
643                "a partition must not be provisionable under a subject it wasn't derived from"
644            ),
645        };
646        assert!(matches!(err, StorageError::PartitionBoundary(_)));
647    }
648
649    #[test]
650    fn list_partitions_only_reports_provisioned_partitions() {
651        let dir = tempdir().unwrap();
652        let provisioned = create_person(dir.path(), "listed", RetentionClass::Standard);
653        let provisioned_id = provisioned.partition_id();
654
655        // An orphan: a 32-hex directory with no partition.json.
656        let orphan_id = PartitionId::for_person("orphan");
657        fs::create_dir_all(dir.path().join(orphan_id.to_hex())).unwrap();
658
659        let listed = list_partitions(dir.path()).unwrap();
660        assert!(listed.contains(&provisioned_id));
661        assert!(
662            !listed.contains(&orphan_id),
663            "a directory with no partition.json must not be reported as a partition"
664        );
665    }
666
667    #[test]
668    fn retention_class_is_visible_and_matches_what_was_provisioned() {
669        let dir = tempdir().unwrap();
670        let store = create_person(dir.path(), "durable-check", RetentionClass::Durable);
671        assert_eq!(store.retention_class(), RetentionClass::Durable);
672    }
673
674    #[test]
675    fn encryption_mode_is_visible_and_matches_what_was_provisioned() {
676        let dir = tempdir().unwrap();
677        let partition_id = PartitionId::for_person("sealed-required-check");
678        let spec = PartitionSpec {
679            subject: Subject {
680                kind: SubjectKind::Person,
681                id: "sealed-required-check".to_string(),
682            },
683            retention_class: RetentionClass::Standard,
684            encryption_mode: EncryptionMode::SealedRequired,
685            label: None,
686        };
687        let store = PartitionStore::create(dir.path(), partition_id, spec).unwrap();
688        assert_eq!(store.encryption_mode(), EncryptionMode::SealedRequired);
689
690        // Immutable across a reopen, same as retention_class.
691        let reopened = PartitionStore::open(dir.path(), partition_id).unwrap();
692        assert_eq!(reopened.encryption_mode(), EncryptionMode::SealedRequired);
693    }
694
695    #[test]
696    fn encryption_mode_defaults_to_plaintext_for_current_callers() {
697        // `create_person` is the standard test helper; it must produce the
698        // only value any current caller can produce — there is no
699        // encryption implemented yet.
700        let dir = tempdir().unwrap();
701        let store = create_person(dir.path(), "plaintext-check", RetentionClass::Standard);
702        assert_eq!(store.encryption_mode(), EncryptionMode::Plaintext);
703    }
704}