Skip to main content

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