storage_kit/lib.rs
1//! # Storage Kit — bitchain's content-addressed storage engine (format v3)
2//!
3//! Content-addressed binary storage: BLAKE3 `(partition_id, content_id)`
4//! addressing, recursive fragmentation (fixed 1024-child fanout),
5//! Zstd-compressed packfiles, per-partition dedup, plus the async transport
6//! `backend` layer (local/S3/HTTP). Locked by design decision;
7//! relocated here from `slash-builder/bitchain` 2026-08-23 per
8//! a follow-up design decision that this was a *location* defect, not a
9//! *shape* defect.
10//!
11//! Layering:
12//! - [`addressing`] — `Hash`, `PartitionId`
13//! - [`fragment`] — chunking + the leaf/list-node recursive tree
14//! - [`store`] — the [`store::ImmutableStore`]/[`store::MutableStore`]
15//! traits and the reference local-filesystem packfile implementation
16//! ([`store::PartitionStore`])
17//! - [`backend`] — async transport wrappers (`LocalBackend`, `S3Backend`,
18//! `HttpBackend`) over the same content-addressed contract, for host
19//! applications that need non-blocking I/O
20//!
21//! `bitchain` (`slash-builder/bitchain`) is this crate's first consumer: it
22//! depends on `storage-kit` for the engine and keeps only the CLI command
23//! surface, the manifest protocol format, and GC. **This crate does not
24//! depend on `bitchain`** — the dependency direction inverted with this
25//! relocation; `Manifest`/`ManifestEntry` (the v2 manifest schema) stay in
26//! `bitchain`, not here.
27//!
28//! **v1 is not read by this crate.** Format v3 is the primary surface; a
29//! `--legacy` v1 read path is a bitchain-CLI-level decision, not this
30//! crate's concern.
31//!
32//! ## The namespace layer (`ns` feature, additive)
33//!
34//! [`ns`] is a second, independent layer: one path-addressed file tree over mounted backends (an OS directory confined
35//! with `cap-std`, an in-memory tree), with versions, atomic replace and a polling watcher. It shares no types or
36//! dependencies with the content-addressed engine below and is not part of the frozen surface described next.
37//!
38//! ## Frozen public surface (interface lock, 2026-08-26)
39//!
40//! **The root re-export block below *is* the frozen surface.** Names, signatures,
41//! field shapes, trait method sets, and enum variants are all locked;
42//! breaking any of them requires a design decision, not a patch, and
43//! (this crate is pre-1.0) bumps the **minor** version (the commit title says so, and release-plz carries it into `CHANGELOG.md`).
44//!
45//! Three rules make "frozen" mean one unambiguous thing:
46//!
47//! 1. **The root re-exports are complete.** A consumer must never have to
48//! reach through a module path to use the locked engine. If it is part
49//! of the contract it is re-exported here; the `tests/conformance.rs`
50//! suite is required to compile against the root re-exports alone. If
51//! a case cannot be written that way, this block is what gets fixed.
52//! As of 2026-09-22 (A4, standalone-first partitions), [`HttpBackend`]
53//! and [`S3Backend`] are re-exported behind the `http`/`s3` Cargo
54//! features respectively — still frozen names/shapes when the feature
55//! is enabled, just not unconditionally compiled. The same holds for
56//! the [`ns`] module (feature `ns`): additive, and outside the frozen
57//! engine surface described here. `default = ["s3", "http", "ns"]`
58//! means every consumer that hasn't opted out with
59//! `default-features = false` sees the engine unchanged (and gains
60//! the `ns` module and its three small direct dependencies).
61//! 2. **Being re-exported here is necessary but not sufficient.** Until
62//! 2026-09-23 `Context` and `Address` were re-exported while held
63//! explicitly outside the freeze pending a ruling — see "`Context` and
64//! `Address` are retired" below for how that resolved. Nothing is held
65//! out of the freeze silently; a future exception would be named here
66//! the same way.
67//! 3. **Not everything public is frozen.** [`store::packfile`] is public
68//! because the on-disk format is inspectable, but only its *format*
69//! constants ([`store::packfile::PACK_MAGIC`],
70//! [`store::packfile::IDX_MAGIC`], [`store::packfile::FORMAT_VERSION`],
71//! and the `*_LEN` layout constants) carry the freeze — those are wire
72//! format and change only with [`FORMAT_VERSION`]. Its writer/reader
73//! API (`PackWriter`, `encode`/`decode`, `read_index`, …) is
74//! **implementation, explicitly outside the lock**, and may change in a
75//! minor release. Bind to [`ImmutableStore`] instead.
76//!
77//! ### `Context` and `Address` are retired, not provisional (2026-09-23)
78//!
79//! The 2026-06 storage lock named **`(hash, context)` addressing** as a
80//! pillar of the format. Two independent 2026-09-23 rulings —
81//! the design and security reviews', reached from different seats
82//! and converging on the same answer — retire it: `storage_kit` addresses
83//! by `(partition_id, content_id)` and knows nothing of logical identity.
84//! The 2026-06 lock's `(hash, context)` address is satisfied across two
85//! layers, not one: **the engine** holds the hash and deduplicates on it
86//! alone — which is exactly what the lock's own clause *"same bytes,
87//! different contexts = same payload deduplicated under one hash"*
88//! requires — and **the product's manifest** holds the context, per
89//! reference, beside the path (`bitchain`'s `ManifestEntry`, which
90//! `bitchain` now owns byte-for-byte). Re-introducing a context field into
91//! the pack entry would make identical bytes store twice, which the lock
92//! forbids, and would place an open-vocabulary opaque identifier in a
93//! cleartext replicated header, which the key design forbids.
94//!
95//! `Context` and `Address` no longer exist in this crate; the
96//! `Address`-vs-`Hash` typing of [`FragmentTree::root`] is gone with them —
97//! `tree.root` is a bare [`struct@Hash`]. The "internal fragmentation nodes are
98//! anonymous" rule [`fragment`] used to state in terms of `Context` is gone
99//! too: there is no longer a context for an internal node to be anonymous
100//! *relative to*. See
101//! `storage-addressing-hash-context-ruling-2026-09-23.md` and
102//! `storage-addressing-hash-context-ruling-security-2026-09-23.md` for the
103//! full rulings.
104//!
105//! `tests/conformance.rs`'s former "every address is anonymous" tripwire is
106//! replaced, not merely deleted — per both rulings, that is a condition of
107//! this retirement, not optional — by three cases asserting the property
108//! directly: same-bytes-one-partition dedup to exactly one physical entry,
109//! no unauthenticated caller-supplied value in any cleartext header, and no
110//! free-form logical-identity constructor on the public surface other than
111//! [`PartitionId`], whose use is gated by [`PartitionStore::create`]'s
112//! derivation check against the closed `subject.kind` vocabulary.
113//!
114//! **This crate deliberately owns no manifest type.** The v2
115//! `Manifest`/`ManifestEntry` schema lives in `bitchain`, and
116//! `bitchain-volume`'s `bcv-cas` keeps its own distinct flat manifest
117//! shape over the same engine (dependency inversion, re-affirmed 2026-08-26).
118//! Two products, two manifest formats, one storage engine — that is the
119//! intended factoring, and it is why a kit-owned `Manifest` would be
120//! wrong. Both manifest formats are wire formats and are governed by their
121//! own products under spec-kit discipline, not here.
122//!
123//! ## R3 partitions — person, household, and service (additive, 2026-09-22)
124//!
125//! [`PartitionId::for_person`], [`PartitionId::for_household`], and
126//! [`PartitionId::for_service`] are additive convenience constructors
127//! matching the "Standalone-first identity" ruling (R3) and its `service:`
128//! extension (the format-reservations spec §R.5): **one
129//! partition per person, one per household, and one per headless service
130//! principal**, derived as `PartitionId::derive(&format!
131//! ("person:{account_id}"))` / `PartitionId::derive(&format!
132//! ("household:{hid}"))` / `PartitionId::derive(&format!
133//! ("service:{service_id}"))` respectively. The `person:`/`household:`/
134//! `service:` string prefix is the domain separator — it guarantees these
135//! three partitions can never collide even if the raw ids happen to share a
136//! value, and it matches the canonical-construction convention
137//! [`PartitionId::derive`] already documents. `service` exists because a
138//! headless principal needs a partition whose key is not a second wrap of a
139//! person's — a division CI job cannot run under a person's principal.
140//! Existing `PartitionId` derivation, encoding, and on-disk format are
141//! unchanged; these are additive helpers over the same constructor, not a
142//! new type or a new addressing scheme.
143//!
144//! **No-cross-partition-dedup rule (R3, binding):** this crate's dedup is
145//! and stays scoped to a single partition ([`store::ImmutableStore::put`]
146//! dedups only within the partition it was opened on; no pack ever spans
147//! partitions — see [`store`]). Content shared into a household is a
148//! **copy** written into the household partition, not a cross-partition
149//! reference — callers wrap that copy under a per-member household key
150//! above this crate, since this crate has no key-wrapping concept. This
151//! crate provides no cross-partition dedup primitive and none should be
152//! added without a format-version-bumping ruling.
153//!
154//! ## Partition provisioning and the metadata record (2026-09-23)
155//!
156//! [`PartitionStore::open`] **no longer creates a partition on first
157//! use.** [`PartitionStore::create`]/[`PartitionStore::open`] split
158//! mkdir-on-first-write into an explicit provisioning step
159//! ([`error::StorageError::PartitionNotProvisioned`] /
160//! [`error::StorageError::PartitionAlreadyProvisioned`]), per
161//! the format-reservations spec §3.7 — a behavioural
162//! break in a frozen name that the spec states is itself the
163//! design decision authorizing it, scoped to exactly this change.
164//! [`list_partitions`] reports only provisioned partitions.
165//!
166//! Every partition now carries a portable [`partition::PartitionRecord`]
167//! (`partition.json`, replicated with the data — its `retention_class`
168//! and key-epoch state are properties of the bytes) and, at the store
169//! root outside every partition directory, a local
170//! [`partition::LocalBinding`] (`partitions.local.json`, never
171//! replicated). See [`partition`] for the full schema and for the
172//! structural mechanism — not a code-review convention — that guarantees
173//! retention reaches a person partition identically to a household
174//! partition.
175//!
176//! This work's own `partition.json` schema is unaffected by the pack/idx
177//! entry layout landing alongside it in the same v3 bump (see "`Context`
178//! and `Address` are retired" above) — `format_version` here follows
179//! [`FORMAT_VERSION`] and nothing else about this record's shape changes.
180
181pub mod addressing;
182pub mod backend;
183pub mod error;
184pub mod fragment;
185pub mod partition;
186pub mod store;
187
188// The namespace layer (docs are on the module itself). Unsafe code is forbidden in this module and everything under it.
189#[cfg(feature = "ns")]
190#[forbid(unsafe_code)]
191pub mod ns;
192
193pub use addressing::{Hash, PartitionId};
194#[cfg(feature = "http")]
195pub use backend::HttpBackend;
196#[cfg(feature = "s3")]
197pub use backend::S3Backend;
198pub use backend::{AsyncImmutableStore, LocalBackend};
199pub use error::{Result, StorageError};
200pub use fragment::{
201 build_fragment_tree, read_fragment_tree, walk_hashes, ChunkingProfile, FragmentTree, RootType,
202};
203pub use partition::{
204 copy_partition_record, EncryptionMode, LocalBinding, PartitionKey, PartitionRecord,
205 PartitionSpec, RetentionClass, Subject, SubjectKind,
206};
207/// Re-exported so external inspectors (e.g. `tests/conformance.rs`, held to
208/// the root-re-exports-only rule above) can reach the on-disk format
209/// constants and the raw reader/writer without a `storage_kit::store::…`
210/// module path. Only the `*_LEN`/`*_MAGIC`/`FORMAT_VERSION` constants carry
211/// the freeze; see [`store::packfile`]'s module docs.
212pub use store::packfile;
213pub use store::{list_partitions, ImmutableStore, MutableStore, PartitionStore};
214
215/// On-disk storage format version this crate implements. This is **not** the
216/// crate's SemVer version (see `Cargo.toml` and the table in `README.md`); the
217/// two are independent. See `manifest::FORMAT_VERSION`
218/// (in `bitchain`) and `store::packfile::FORMAT_VERSION` for the same
219/// constant scoped to each wire artifact — all are required to stay in
220/// lockstep.
221pub const FORMAT_VERSION: u32 = 3;
222
223/// Crate version, sourced from `Cargo.toml`.
224pub const VERSION: &str = env!("CARGO_PKG_VERSION");
225
226#[cfg(test)]
227mod tests {
228 use super::*;
229
230 #[test]
231 fn format_version_is_three() {
232 assert_eq!(FORMAT_VERSION, 3);
233 }
234
235 #[test]
236 fn version_is_set() {
237 assert!(!VERSION.is_empty());
238 }
239}