Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 8.9 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Derived data: values computed from changesets, stored as derived objects
5//! keyed by their inputs, and always recomputable.
6//!
7//! A derived value is what a named function, at some version, gives for some
8//! inputs. Its key is
9//!
10//! ```text
11//! BLAKE3-derive-key("elffuss-braid 2026 derived v1",
12//! bytes function | uv version | uv n | n × [32] input id | bytes argument)
13//! ```
14//!
15//! with the codec of the format (`uv` and `bytes`); the argument is empty for
16//! functions of ids alone. The value is stored as a derived object, a
17//! *record*, whose payload is the key followed by the value's encoding:
18//! `[32] key | value`. Each function versions its encoding on its own: a new
19//! encoding is a new version, so a new key.
20//!
21//! A record's id depends on its value, so a [`DerivedIndex`] maps keys to
22//! record ids. The index is only a cache: a record is used when its payload
23//! starts with the key and its value decodes, and a value whose record is
24//! missing, damaged or unindexed is computed again.
25//!
26//! Every value is a deterministic function of its inputs. Two processes that
27//! compute the same value store the same bytes under the same id, storing an
28//! object twice does nothing, and recording a key twice in the index does
29//! nothing either: computing a missing value is safe while other processes do
30//! the same, and the order in which values are computed never changes them.
31
32use core::convert::Infallible;
33use core::fmt;
34use std::collections::HashMap;
35use std::sync::Mutex;
36
37use braid_format::codec::{put_bytes, put_id, put_uv};
38use braid_format::{Kind, ObjectId};
39
40/// The key of a derived value: a hash of the function, its version and its
41/// inputs, `BLAKE3-derive-key("elffuss-braid 2026 derived v1", bytes function
42/// | uv version | uv n | n × [32] input id | bytes argument)` with the codec
43/// of the format (section 8 of the format spec).
44#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
45pub struct DerivedKey([u8; 32]);
46
47impl DerivedKey {
48 /// Length of a key in bytes.
49 pub const LEN: usize = 32;
50
51 /// The key of `function` at `version` over `inputs` and `argument`.
52 pub fn new(function: &str, version: u64, inputs: &[ObjectId], argument: &[u8]) -> Self {
53 let mut preimage =
54 Vec::with_capacity(function.len() + inputs.len() * ObjectId::LEN + argument.len() + 16);
55 put_bytes(&mut preimage, function.as_bytes());
56 put_uv(&mut preimage, version);
57 put_uv(&mut preimage, inputs.len() as u64);
58 for input in inputs {
59 put_id(&mut preimage, input);
60 }
61 put_bytes(&mut preimage, argument);
62 DerivedKey(*ObjectId::hash(Kind::Derived, &preimage).as_bytes())
63 }
64
65 /// Wraps raw key bytes.
66 pub const fn from_bytes(bytes: [u8; 32]) -> Self {
67 DerivedKey(bytes)
68 }
69
70 /// The raw key bytes.
71 pub const fn as_bytes(&self) -> &[u8; 32] {
72 &self.0
73 }
74}
75
76impl fmt::Display for DerivedKey {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 fmt::Display::fmt(&ObjectId::from_bytes(self.0), f)
79 }
80}
81
82impl fmt::Debug for DerivedKey {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 write!(f, "DerivedKey({self})")
85 }
86}
87
88/// Where the records of derived values are found from their keys.
89///
90/// An index is a cache: it may lack keys, and what it says is checked
91/// against the record. Implementations must make the records an entry names
92/// durable before the entry, so that an index never outlives its records.
93pub trait DerivedIndex {
94 /// Why a lookup or a write failed.
95 type Error: std::error::Error + Send + Sync + 'static;
96
97 /// The id of the record of `key`, if the index knows one. When a key was
98 /// recorded more than once, the last entry counts.
99 fn find(&self, key: &DerivedKey) -> Result<Option<ObjectId>, Self::Error>;
100
101 /// Records where the records of these keys are, in order. Recording an
102 /// entry that is already there does nothing.
103 fn record(&self, entries: &[(DerivedKey, ObjectId)]) -> Result<(), Self::Error>;
104}
105
106impl<T: DerivedIndex + ?Sized> DerivedIndex for &T {
107 type Error = T::Error;
108
109 fn find(&self, key: &DerivedKey) -> Result<Option<ObjectId>, Self::Error> {
110 (**self).find(key)
111 }
112
113 fn record(&self, entries: &[(DerivedKey, ObjectId)]) -> Result<(), Self::Error> {
114 (**self).record(entries)
115 }
116}
117
118/// A derived index kept in memory, for tests and short-lived work.
119#[derive(Debug, Default)]
120pub struct MemoryIndex {
121 map: Mutex<HashMap<DerivedKey, ObjectId>>,
122}
123
124impl MemoryIndex {
125 /// An empty index.
126 pub fn new() -> Self {
127 Self::default()
128 }
129
130 /// Number of keys recorded.
131 pub fn len(&self) -> usize {
132 self.lock().len()
133 }
134
135 /// Whether no key is recorded.
136 pub fn is_empty(&self) -> bool {
137 self.len() == 0
138 }
139
140 /// Every entry, sorted by key.
141 pub fn entries(&self) -> Vec<(DerivedKey, ObjectId)> {
142 let mut entries: Vec<_> = self.lock().iter().map(|(k, v)| (*k, *v)).collect();
143 entries.sort();
144 entries
145 }
146
147 fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<DerivedKey, ObjectId>> {
148 // Every operation is a single insert or lookup: a panic cannot leave
149 // the map half-written.
150 self.map
151 .lock()
152 .unwrap_or_else(|poisoned| poisoned.into_inner())
153 }
154}
155
156impl DerivedIndex for MemoryIndex {
157 type Error = Infallible;
158
159 fn find(&self, key: &DerivedKey) -> Result<Option<ObjectId>, Self::Error> {
160 Ok(self.lock().get(key).copied())
161 }
162
163 fn record(&self, entries: &[(DerivedKey, ObjectId)]) -> Result<(), Self::Error> {
164 let mut map = self.lock();
165 for (key, id) in entries {
166 map.insert(*key, *id);
167 }
168 Ok(())
169 }
170}
171
172/// The payload of the record of `key` holding `value`.
173pub(crate) fn encode_record(key: &DerivedKey, value: &[u8]) -> Vec<u8> {
174 let mut payload = Vec::with_capacity(DerivedKey::LEN + value.len());
175 payload.extend_from_slice(key.as_bytes());
176 payload.extend_from_slice(value);
177 payload
178}
179
180/// The value in a record's payload, if the record is the one of `key`.
181pub(crate) fn record_value<'p>(key: &DerivedKey, payload: &'p [u8]) -> Option<&'p [u8]> {
182 payload.strip_prefix(key.as_bytes().as_slice())
183}
184
185#[cfg(test)]
186mod tests {
187 use super::*;
188
189 #[test]
190 fn keys_hash_the_documented_preimage() {
191 let input = ObjectId::hash(Kind::Changeset, b"c");
192 let key = DerivedKey::new("graph", 1, &[input], b"");
193 let mut preimage = vec![5];
194 preimage.extend_from_slice(b"graph");
195 preimage.extend_from_slice(&[1, 1]);
196 preimage.extend_from_slice(input.as_bytes());
197 preimage.push(0);
198 assert_eq!(
199 key.as_bytes(),
200 blake3::derive_key("elffuss-braid 2026 derived v1", &preimage).as_slice()
201 );
202 assert_eq!(
203 key.to_string(),
204 ObjectId::from_bytes(*key.as_bytes()).to_hex()
205 );
206 }
207
208 #[test]
209 fn every_part_of_the_preimage_counts() {
210 let a = ObjectId::hash(Kind::Changeset, b"a");
211 let b = ObjectId::hash(Kind::Changeset, b"b");
212 let keys = [
213 DerivedKey::new("graph", 1, &[a], b""),
214 DerivedKey::new("graph", 2, &[a], b""),
215 DerivedKey::new("paths", 1, &[a], b""),
216 DerivedKey::new("graph", 1, &[b], b""),
217 DerivedKey::new("graph", 1, &[a, b], b""),
218 DerivedKey::new("graph", 1, &[a], b"x"),
219 // The lengths keep the parts apart.
220 DerivedKey::new("grap", 1, &[a], b"h"),
221 ];
222 for (i, x) in keys.iter().enumerate() {
223 for y in &keys[i + 1..] {
224 assert_ne!(x, y);
225 }
226 }
227 }
228
229 #[test]
230 fn records_start_with_their_key() {
231 let a = DerivedKey::new("f", 1, &[], b"a");
232 let b = DerivedKey::new("f", 1, &[], b"b");
233 let payload = encode_record(&a, b"value");
234 assert_eq!(record_value(&a, &payload), Some(&b"value"[..]));
235 assert_eq!(record_value(&b, &payload), None);
236 assert_eq!(record_value(&a, &payload[..10]), None);
237 assert_eq!(record_value(&a, a.as_bytes()), Some(&b""[..]));
238 }
239
240 #[test]
241 fn memory_index() {
242 let index = MemoryIndex::new();
243 assert!(index.is_empty());
244 let key = DerivedKey::new("f", 1, &[], b"");
245 let one = ObjectId::hash(Kind::Derived, b"one");
246 let two = ObjectId::hash(Kind::Derived, b"two");
247 assert_eq!(index.find(&key).unwrap(), None);
248 index.record(&[(key, one), (key, one)]).unwrap();
249 assert_eq!(index.find(&key).unwrap(), Some(one));
250 // The last entry for a key counts.
251 <&MemoryIndex as DerivedIndex>::record(&&index, &[(key, two)]).unwrap();
252 assert_eq!(index.find(&key).unwrap(), Some(two));
253 assert_eq!(index.len(), 1);
254 assert_eq!(index.entries(), [(key, two)]);
255 }
256}