Skip to main content

storage_kit/
addressing.rs

1//! `(partition_id, content_id)` addressing — format v3, per the 2026-09-23
2//! storage-addressing rulings (the design and security reviews, ruling
3//! independently and converging on the same answer — Branch A).
4//!
5//! Physical storage is keyed by **hash alone** (BLAKE3 of the plaintext);
6//! that is the only thing dedup and the packfile layer ever look at.
7//! `Context` and `Address` — the 16-byte partition-scoped logical-identity
8//! field the 2026-06 storage lock named as `(hash, context)` — are retired
9//! from this crate entirely. Both rulings found the same thing from
10//! different seats: the lock's dedup clause ("same bytes, different
11//! contexts = same payload deduplicated under one hash") is satisfied by
12//! hash-only keying and **violated** by compositing the storage key on a
13//! context, so making `context` real was never a way to honour the lock —
14//! it was the option that broke it. The lock's other half — context
15//! travelling with the address, tracking logical identity separately —
16//! already lives one layer up, in `bitchain`'s `ManifestEntry { path,
17//! context, root_hash }`, which `bitchain` now owns byte-for-byte
18//! (`storage-addressing-hash-context-ruling-2026-09-23.md`,
19//! `storage-addressing-hash-context-ruling-security-2026-09-23.md`).
20//!
21//! `storage-kit` addresses by `(partition_id, content_id)` and knows
22//! nothing of logical identity. It never will: `PartitionId::derive` is the
23//! only free-form-string identity constructor this crate exposes, and its
24//! use is gated by `PartitionStore::create`'s derivation check against a
25//! closed `subject.kind` vocabulary — see `partition.rs`. A field minted
26//! inline from an arbitrary string, with no such gate, cannot carry a
27//! guardrail; that is why `Context::derive(&str)` is gone rather than
28//! reserved.
29
30use crate::error::{Result, StorageError};
31use std::fmt;
32
33/// Length in bytes of a BLAKE3 content hash.
34pub const HASH_LEN: usize = 32;
35/// Length in bytes of a partition id.
36pub const PARTITION_ID_LEN: usize = 16;
37
38/// A BLAKE3 content hash. This is the sole key for physical block storage
39/// and dedup within a partition.
40#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
41pub struct Hash([u8; HASH_LEN]);
42
43impl Hash {
44    /// Hash `bytes` with BLAKE3. This defines block identity for the entire
45    /// storage engine — never change the algorithm without a format version
46    /// bump.
47    pub fn of(bytes: &[u8]) -> Self {
48        Hash(*blake3::hash(bytes).as_bytes())
49    }
50
51    pub fn from_bytes(bytes: [u8; HASH_LEN]) -> Self {
52        Hash(bytes)
53    }
54
55    pub fn as_bytes(&self) -> &[u8; HASH_LEN] {
56        &self.0
57    }
58
59    pub fn to_hex(&self) -> String {
60        hex::encode(self.0)
61    }
62
63    pub fn from_hex(s: &str) -> Result<Self> {
64        let bytes = hex::decode(s)
65            .map_err(|e| StorageError::InvalidAddress(format!("bad hash hex: {e}")))?;
66        let arr: [u8; HASH_LEN] = bytes
67            .try_into()
68            .map_err(|_| StorageError::InvalidAddress("hash must be 32 bytes".into()))?;
69        Ok(Hash(arr))
70    }
71}
72
73impl fmt::Debug for Hash {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        write!(f, "Hash({})", self.to_hex())
76    }
77}
78
79impl fmt::Display for Hash {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        write!(f, "{}", self.to_hex())
82    }
83}
84
85/// A 16-byte partition id: the physical storage boundary. Canonical
86/// construction is `BLAKE3(household/namespace-id)[0:16]`. No pack ever
87/// spans partitions; dedup and GC are both scoped to a single partition.
88#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
89pub struct PartitionId([u8; PARTITION_ID_LEN]);
90
91impl PartitionId {
92    /// Derive a canonical partition id from a household/namespace string.
93    pub fn derive(namespace: &str) -> Self {
94        let full = blake3::hash(namespace.as_bytes());
95        let mut out = [0u8; PARTITION_ID_LEN];
96        out.copy_from_slice(&full.as_bytes()[..PARTITION_ID_LEN]);
97        PartitionId(out)
98    }
99
100    /// Derive the partition id for a **person's** own partition (R3,
101    /// standalone-first identity):
102    /// `PartitionId::derive("person:{account_id}")`. The `person:` prefix is
103    /// the domain separator from [`PartitionId::for_household`] — a person
104    /// and a household never land on the same partition even if
105    /// `account_id` and a household id happen to coincide as strings.
106    ///
107    /// Additive: does not change how any existing `PartitionId` is derived
108    /// or stored on disk. No dedup ever crosses a partition boundary (see
109    /// the crate-root docs, "R3 partitions"); shared content is copied into
110    /// a household partition, never referenced across partitions.
111    pub fn for_person(account_id: &str) -> Self {
112        PartitionId::derive(&format!("person:{account_id}"))
113    }
114
115    /// Derive the partition id for a **household's** shared partition (R3,
116    /// standalone-first identity):
117    /// `PartitionId::derive("household:{hid}")`. See
118    /// [`PartitionId::for_person`] for the domain-separation rationale and
119    /// the no-cross-partition-dedup rule.
120    pub fn for_household(hid: &str) -> Self {
121        PartitionId::derive(&format!("household:{hid}"))
122    }
123
124    /// Derive the partition id for a **service's** own partition (spec
125    /// the format-reservations spec §R.5): a headless
126    /// principal gets its own partition rather than a second wrap of a
127    /// person's key, because its key cannot be derived by wrapping a
128    /// person's — the security review ruled a service principal needs
129    /// independent key custody so, e.g., division CI cannot run under a
130    /// person's principal. `service:` is the domain-separator prefix,
131    /// naming this the third and last member of the closed `subject.kind`
132    /// vocabulary alongside [`PartitionId::for_person`] and
133    /// [`PartitionId::for_household`] — see the module docs there for the
134    /// domain-separation rationale and the no-cross-partition-dedup rule.
135    pub fn for_service(service_id: &str) -> Self {
136        PartitionId::derive(&format!("service:{service_id}"))
137    }
138
139    pub fn from_bytes(bytes: [u8; PARTITION_ID_LEN]) -> Self {
140        PartitionId(bytes)
141    }
142
143    pub fn as_bytes(&self) -> &[u8; PARTITION_ID_LEN] {
144        &self.0
145    }
146
147    pub fn to_hex(&self) -> String {
148        hex::encode(self.0)
149    }
150
151    pub fn from_hex(s: &str) -> Result<Self> {
152        let bytes = hex::decode(s)
153            .map_err(|e| StorageError::InvalidAddress(format!("bad partition id hex: {e}")))?;
154        let arr: [u8; PARTITION_ID_LEN] = bytes
155            .try_into()
156            .map_err(|_| StorageError::InvalidAddress("partition id must be 16 bytes".into()))?;
157        Ok(PartitionId(arr))
158    }
159
160    /// The two-hex-char shard prefix used for the `packs/<prefix>/` fanout
161    /// directory of the *pack id* (not the partition id itself) — kept here
162    /// as a shared helper since both packfile and partition-store need the
163    /// identical prefixing rule.
164    pub fn shard_prefix(hex_id: &str) -> &str {
165        &hex_id[..2.min(hex_id.len())]
166    }
167}
168
169impl fmt::Debug for PartitionId {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        write!(f, "PartitionId({})", self.to_hex())
172    }
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178
179    #[test]
180    fn hash_roundtrips_through_hex() {
181        let h = Hash::of(b"hello world");
182        let hex = h.to_hex();
183        let h2 = Hash::from_hex(&hex).unwrap();
184        assert_eq!(h, h2);
185    }
186
187    #[test]
188    fn partition_id_derivation_is_deterministic() {
189        let a = PartitionId::derive("household:acme");
190        let b = PartitionId::derive("household:acme");
191        assert_eq!(a, b);
192    }
193
194    #[test]
195    fn for_person_matches_the_prefixed_derive_convention() {
196        let a = PartitionId::for_person("acct-123");
197        let b = PartitionId::derive("person:acct-123");
198        assert_eq!(a, b);
199    }
200
201    #[test]
202    fn for_household_matches_the_prefixed_derive_convention() {
203        let a = PartitionId::for_household("hid-abc");
204        let b = PartitionId::derive("household:hid-abc");
205        assert_eq!(a, b);
206    }
207
208    #[test]
209    fn person_and_household_partitions_are_domain_separated() {
210        // Same raw id string, different domain prefix -- must never collide,
211        // even though `PartitionId::for_household` reuses the exact bytes
212        // "acme" that a bare `PartitionId::derive("acme")` would hash.
213        let person = PartitionId::for_person("acme");
214        let household = PartitionId::for_household("acme");
215        assert_ne!(person, household);
216    }
217
218    #[test]
219    fn for_person_is_deterministic() {
220        let a = PartitionId::for_person("acct-123");
221        let b = PartitionId::for_person("acct-123");
222        assert_eq!(a, b);
223    }
224
225    #[test]
226    fn for_service_matches_the_prefixed_derive_convention() {
227        let a = PartitionId::for_service("svc-1");
228        let b = PartitionId::derive("service:svc-1");
229        assert_eq!(a, b);
230    }
231
232    #[test]
233    fn for_service_is_deterministic() {
234        let a = PartitionId::for_service("svc-1");
235        let b = PartitionId::for_service("svc-1");
236        assert_eq!(a, b);
237    }
238
239    #[test]
240    fn service_partitions_are_domain_separated_from_person_and_household() {
241        // Same raw id string across all three domain prefixes -- a service
242        // id must never collide with a person or household id, even though
243        // all three derive from the exact bytes "acme".
244        let person = PartitionId::for_person("acme");
245        let household = PartitionId::for_household("acme");
246        let service = PartitionId::for_service("acme");
247        assert_ne!(service, person);
248        assert_ne!(service, household);
249    }
250}