Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 9.7 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Changed-path filters: Bloom filters of the paths a changeset changes and
5//! of their parent directories, so that a walk over history skips, without
6//! reading them, the changesets that cannot have touched a path.
7//!
8//! A filter with `n` entries has `ceil(10 n / 8)` bytes, so at least 10 bits
9//! per entry, and sets 7 bits per entry: the parameters of git's changed-path
10//! filters, for about one false positive in a hundred lookups. Its encoding,
11//! versioned with the record that holds it, is `uv n` followed by the bytes.
12//!
13//! The bits of an entry come from `h = BLAKE3-derive-key("elffuss-braid 2026
14//! changed-paths v1", path)`: with `a` and `b` its first two little-endian
15//! 64-bit words and `m` the number of bits, entry bit `i`, for `i` from 0
16//! to 6, is `(a + i b) mod m`, computed modulo 2⁶⁴; bit `j` of the filter is
17//! bit `j mod 8` of byte `j / 8`. A filter never says no for an entry it
18//! holds. An empty change list has no entries, and a filter that would hold
19//! more than [`MAX_ENTRIES`] has no bits: every path may match.
20
21use std::collections::HashSet;
22
23use braid_format::DecodeError;
24use braid_format::codec::{Reader, put_uv};
25
26/// Bits per entry, at least.
27const BITS_PER_ENTRY: u64 = 10;
28
29/// Bits set per entry.
30const HASHES: u64 = 7;
31
32/// A changeset whose paths and directories are more than this many has no
33/// filter: every path may match it.
34pub(crate) const MAX_ENTRIES: u64 = 1024;
35
36/// The key-derivation context of the entry hashes.
37const CONTEXT: &str = "elffuss-braid 2026 changed-paths v1";
38
39/// The hash of a path, from which the bits of every filter size come.
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub(crate) struct PathHash {
42 a: u64,
43 b: u64,
44}
45
46impl PathHash {
47 /// The hash of `path`.
48 pub(crate) fn of(path: &[u8]) -> Self {
49 let digest = blake3::derive_key(CONTEXT, path);
50 let word = |at: usize| {
51 let mut bytes = [0u8; 8];
52 bytes.copy_from_slice(&digest[at..at + 8]);
53 u64::from_le_bytes(bytes)
54 };
55 PathHash {
56 a: word(0),
57 b: word(8),
58 }
59 }
60
61 /// The bits of the entry in a filter of `bits` bits.
62 fn positions(self, bits: u64) -> impl Iterator<Item = u64> {
63 (0..HASHES).map(move |i| self.a.wrapping_add(i.wrapping_mul(self.b)) % bits)
64 }
65}
66
67/// The changed-path filter of one changeset.
68#[derive(Clone, Debug, PartialEq, Eq)]
69pub(crate) enum Filter {
70 /// The change list is empty: no path matches.
71 Empty,
72 /// A Bloom filter of `entries` entries.
73 Bits {
74 /// How many paths and directories it holds.
75 entries: u64,
76 /// The bits, `ceil(10 × entries / 8)` bytes of them.
77 bits: Vec<u8>,
78 },
79 /// More than [`MAX_ENTRIES`] entries: every path may match.
80 Full {
81 /// How many paths and directories there are.
82 entries: u64,
83 },
84}
85
86impl Filter {
87 /// The filter of a change list with these paths: the paths and all of
88 /// their parent directories.
89 pub(crate) fn build<'p>(paths: impl IntoIterator<Item = &'p [u8]>) -> Filter {
90 let mut entries: HashSet<&[u8]> = HashSet::new();
91 for path in paths {
92 if !entries.insert(path) {
93 continue;
94 }
95 // Every entry already holds its own directories, so the walk up
96 // stops at the first one already there.
97 let mut end = path.len();
98 while let Some(slash) = path[..end].iter().rposition(|byte| *byte == b'/') {
99 if !entries.insert(&path[..slash]) {
100 break;
101 }
102 end = slash;
103 }
104 }
105 let count = entries.len() as u64;
106 if count == 0 {
107 return Filter::Empty;
108 }
109 if count > MAX_ENTRIES {
110 return Filter::Full { entries: count };
111 }
112 let mut bits = vec![0u8; filter_bytes(count)];
113 let size = bits.len() as u64 * 8;
114 for entry in entries {
115 for bit in PathHash::of(entry).positions(size) {
116 bits[(bit / 8) as usize] |= 1 << (bit % 8);
117 }
118 }
119 Filter::Bits {
120 entries: count,
121 bits,
122 }
123 }
124
125 /// Whether the entry with this hash may be in the filter. `false` is
126 /// certain; `true` is wrong about once in a hundred times.
127 pub(crate) fn may_contain(&self, hash: PathHash) -> bool {
128 match self {
129 Filter::Empty => false,
130 Filter::Full { .. } => true,
131 Filter::Bits { bits, .. } => hash
132 .positions(bits.len() as u64 * 8)
133 .all(|bit| bits[(bit / 8) as usize] & (1 << (bit % 8)) != 0),
134 }
135 }
136
137 /// Whether the change list is empty.
138 pub(crate) fn is_empty(&self) -> bool {
139 matches!(self, Filter::Empty)
140 }
141
142 /// Appends the encoding: the number of entries, then the bits when there
143 /// are some.
144 pub(crate) fn encode(&self, out: &mut Vec<u8>) {
145 match self {
146 Filter::Empty => put_uv(out, 0),
147 Filter::Bits { entries, bits } => {
148 put_uv(out, *entries);
149 out.extend_from_slice(bits);
150 }
151 Filter::Full { entries } => put_uv(out, *entries),
152 }
153 }
154
155 /// Reads an encoding written by [`Filter::encode`].
156 pub(crate) fn decode(reader: &mut Reader<'_>) -> Result<Filter, DecodeError> {
157 let entries = reader.uv()?;
158 Ok(if entries == 0 {
159 Filter::Empty
160 } else if entries > MAX_ENTRIES {
161 Filter::Full { entries }
162 } else {
163 Filter::Bits {
164 entries,
165 bits: reader.take(filter_bytes(entries))?.to_vec(),
166 }
167 })
168 }
169}
170
171/// Bytes of the filter of `entries` entries.
172fn filter_bytes(entries: u64) -> usize {
173 (entries * BITS_PER_ENTRY).div_ceil(8) as usize
174}
175
176#[cfg(test)]
177mod tests {
178 use super::*;
179 use proptest::prelude::*;
180
181 fn encoded(filter: &Filter) -> Vec<u8> {
182 let mut out = Vec::new();
183 filter.encode(&mut out);
184 out
185 }
186
187 fn decoded(bytes: &[u8]) -> Result<Filter, DecodeError> {
188 let mut reader = Reader::new(bytes);
189 let filter = Filter::decode(&mut reader)?;
190 reader.finish()?;
191 Ok(filter)
192 }
193
194 #[test]
195 fn paths_and_their_directories_are_entries() {
196 let filter = Filter::build([&b"a/b/c.txt"[..], b"a/b/d.txt", b"e"]);
197 // a/b/c.txt, a/b/d.txt, a/b, a, e.
198 let Filter::Bits { entries, bits } = &filter else {
199 panic!("expected bits, got {filter:?}");
200 };
201 assert_eq!(*entries, 5);
202 assert_eq!(bits.len(), 7);
203 for entry in [&b"a/b/c.txt"[..], b"a/b/d.txt", b"a/b", b"a", b"e"] {
204 assert!(filter.may_contain(PathHash::of(entry)), "{entry:?}");
205 }
206 // Not certain, but these hashes are fixed: a test that fails here
207 // means that the hash changed.
208 assert!(!filter.may_contain(PathHash::of(b"a/b/c")));
209 assert!(!filter.may_contain(PathHash::of(b"a/x")));
210 }
211
212 #[test]
213 fn empty_and_full_filters() {
214 let empty = Filter::build([]);
215 assert!(empty.is_empty());
216 assert!(!empty.may_contain(PathHash::of(b"")));
217 assert_eq!(encoded(&empty), [0]);
218 assert_eq!(decoded(&[0]), Ok(Filter::Empty));
219
220 let names: Vec<Vec<u8>> = (0..MAX_ENTRIES)
221 .map(|i| format!("f{i}").into_bytes())
222 .collect();
223 let at_limit = Filter::build(names.iter().map(Vec::as_slice));
224 assert!(matches!(
225 at_limit,
226 Filter::Bits {
227 entries: MAX_ENTRIES,
228 ..
229 }
230 ));
231 // One more path, and its directory: over the limit.
232 let mut over = names.clone();
233 over.push(b"d/x".to_vec());
234 let full = Filter::build(over.iter().map(Vec::as_slice));
235 assert_eq!(
236 full,
237 Filter::Full {
238 entries: MAX_ENTRIES + 2
239 }
240 );
241 assert!(full.may_contain(PathHash::of(b"anything")));
242 assert_eq!(decoded(&encoded(&full)), Ok(full));
243 assert_eq!(decoded(&encoded(&at_limit)), Ok(at_limit));
244 }
245
246 #[test]
247 fn the_encoding_has_exactly_the_bytes_of_its_entries() {
248 let filter = Filter::build([&b"x"[..]]);
249 let bytes = encoded(&filter);
250 assert_eq!(bytes.len(), 1 + 2);
251 assert_eq!(decoded(&bytes), Ok(filter));
252 assert!(decoded(&bytes[..2]).is_err());
253 let mut longer = bytes.clone();
254 longer.push(0);
255 assert!(decoded(&longer).is_err());
256 }
257
258 #[test]
259 fn false_positives_are_rare() {
260 let changed: Vec<Vec<u8>> = (0..200)
261 .map(|i| format!("src/m{}/f{i}.rs", i % 7).into_bytes())
262 .collect();
263 let filter = Filter::build(changed.iter().map(Vec::as_slice));
264 let wrong = (0..10_000)
265 .filter(|i| filter.may_contain(PathHash::of(format!("other/g{i}").as_bytes())))
266 .count();
267 assert!(wrong < 300, "{wrong} false positives in 10000");
268 }
269
270 proptest! {
271 #[test]
272 fn no_false_negatives(
273 paths in proptest::collection::vec("[a-c]{1,3}(/[a-c]{1,3}){0,3}", 0..80),
274 ) {
275 let filter = Filter::build(paths.iter().map(|p| p.as_bytes()));
276 for path in &paths {
277 let mut prefix = path.as_str();
278 loop {
279 prop_assert!(filter.may_contain(PathHash::of(prefix.as_bytes())), "{prefix}");
280 match prefix.rfind('/') {
281 Some(slash) => prefix = &prefix[..slash],
282 None => break,
283 }
284 }
285 }
286 prop_assert_eq!(decoded(&encoded(&filter)), Ok(filter));
287 }
288 }
289}