Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 9.2 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Property tests: every encoding is canonical, and a directory's nodes depend
5//! only on its set of entries.
6
7use std::collections::{BTreeMap, HashMap};
8
9use braid_format::codec::{Reader, put_sv, put_uv};
10use braid_format::tree::{MAX_FLAT_ENTRIES, MAX_NODE_ENTRIES};
11use braid_format::{
12 Change, ChangeOp, Changeset, ChangesetParts, Entry, EntryKind, GitId, Kind, Node, ObjectId,
13 Signature, build_directory, read_directory, validate_name,
14};
15use proptest::prelude::*;
16
17fn object_id() -> impl Strategy<Value = ObjectId> {
18 any::<[u8; 32]>().prop_map(ObjectId::from_bytes)
19}
20
21fn git_id() -> impl Strategy<Value = GitId> {
22 prop_oneof![
23 any::<[u8; 20]>().prop_map(GitId::Sha1),
24 any::<[u8; 32]>().prop_map(GitId::Sha256),
25 ]
26}
27
28/// Names from a small alphabet, so that sets collide and sort interestingly,
29/// plus arbitrary Unicode; anything invalid is filtered out.
30fn name() -> impl Strategy<Value = Vec<u8>> {
31 prop_oneof![
32 "[a-c.][a-c0-2.]{0,6}".prop_map(String::into_bytes),
33 "\\PC{1,6}".prop_map(String::into_bytes),
34 ]
35 .prop_filter("valid name", |n| validate_name(n).is_ok())
36}
37
38fn entry_kind() -> impl Strategy<Value = EntryKind> {
39 prop_oneof![
40 (object_id(), any::<u64>()).prop_map(|(blob, size)| EntryKind::File { blob, size }),
41 (object_id(), any::<u64>()).prop_map(|(blob, size)| EntryKind::Executable { blob, size }),
42 object_id().prop_map(|tree| EntryKind::Tree { tree }),
43 git_id().prop_map(|commit| EntryKind::Gitlink { commit }),
44 ]
45}
46
47fn entries(max: usize) -> impl Strategy<Value = Vec<Entry>> {
48 prop::collection::btree_map(name(), entry_kind(), 0..max).prop_map(|map: BTreeMap<_, _>| {
49 map.into_iter()
50 .map(|(name, kind)| Entry { name, kind })
51 .collect()
52 })
53}
54
55/// Many distinct names, to exercise split directories.
56fn wide_entries() -> impl Strategy<Value = Vec<Entry>> {
57 (MAX_FLAT_ENTRIES - 10..6000usize, any::<u64>()).prop_map(|(n, seed)| {
58 (0..n)
59 .map(|i| Entry {
60 name: format!("n{:x}-{i}", seed.wrapping_mul(i as u64 + 1) % 9973).into_bytes(),
61 kind: EntryKind::File {
62 blob: ObjectId::hash(Kind::Blob, &i.to_le_bytes()),
63 size: i as u64,
64 },
65 })
66 .collect()
67 })
68}
69
70fn signature() -> impl Strategy<Value = Signature> {
71 (
72 prop::collection::vec(any::<u8>(), 0..20),
73 prop::collection::vec(any::<u8>(), 0..20),
74 any::<i64>(),
75 any::<i64>(),
76 )
77 .prop_map(|(name, email, seconds, offset_minutes)| Signature {
78 name,
79 email,
80 seconds,
81 offset_minutes,
82 })
83}
84
85fn change_op() -> impl Strategy<Value = ChangeOp> {
86 prop_oneof![
87 Just(ChangeOp::Delete),
88 (object_id(), any::<u64>()).prop_map(|(blob, size)| ChangeOp::File { blob, size }),
89 (object_id(), any::<u64>()).prop_map(|(blob, size)| ChangeOp::Symlink { blob, size }),
90 git_id().prop_map(|commit| ChangeOp::Gitlink { commit }),
91 ]
92}
93
94fn changeset_parts() -> impl Strategy<Value = ChangesetParts> {
95 (
96 prop::collection::vec(object_id(), 0..4),
97 object_id(),
98 prop::collection::btree_map(
99 prop::collection::vec(name(), 1..4).prop_map(|parts| parts.join(&b'/')),
100 change_op(),
101 0..20,
102 ),
103 signature(),
104 signature(),
105 prop::collection::vec(any::<u8>(), 0..64),
106 prop::collection::vec(
107 (
108 prop::collection::vec(any::<u8>(), 0..8),
109 prop::collection::vec(any::<u8>(), 0..8),
110 ),
111 0..4,
112 ),
113 prop::option::of(object_id()),
114 )
115 .prop_map(
116 |(parents, root, changes, author, committer, message, extras, git_origin)| {
117 ChangesetParts {
118 parents,
119 root,
120 changes: changes
121 .into_iter()
122 .map(|(path, op)| Change { path, op })
123 .collect(),
124 author,
125 committer,
126 message,
127 extras,
128 git_origin,
129 }
130 },
131 )
132}
133
134fn node_sizes(nodes: &[(ObjectId, Vec<u8>)]) -> Vec<usize> {
135 nodes
136 .iter()
137 .map(|(_, bytes)| match Node::decode(bytes).unwrap() {
138 Node::Flat(e) | Node::Leaf(e) => e.len(),
139 Node::Internal { children, .. } => children.len(),
140 })
141 .collect()
142}
143
144proptest! {
145 #[test]
146 fn integers_round_trip(u in any::<u64>(), s in any::<i64>()) {
147 let mut out = Vec::new();
148 put_uv(&mut out, u);
149 put_sv(&mut out, s);
150 let mut reader = Reader::new(&out);
151 prop_assert_eq!(reader.uv().unwrap(), u);
152 prop_assert_eq!(reader.sv().unwrap(), s);
153 prop_assert!(reader.finish().is_ok());
154 }
155
156 #[test]
157 fn small_directories_round_trip(entries in entries(40)) {
158 let dir = build_directory(entries.clone()).unwrap();
159 prop_assert_eq!(dir.nodes.len(), 1);
160 let (id, bytes) = &dir.nodes[0];
161 let node = Node::decode(bytes).unwrap();
162 prop_assert_eq!(&node.encode(), bytes);
163 prop_assert_eq!(node.id(), *id);
164 prop_assert_eq!(node, Node::Flat(entries));
165 }
166
167 #[test]
168 fn directory_ignores_input_order(mut entries in entries(40), seed in any::<u64>()) {
169 let sorted = build_directory(entries.clone()).unwrap();
170 let n = entries.len().max(1);
171 entries.rotate_left((seed as usize) % n);
172 entries.reverse();
173 prop_assert_eq!(build_directory(entries).unwrap(), sorted);
174 }
175
176 #[test]
177 fn decoders_never_panic(bytes in prop::collection::vec(any::<u8>(), 0..300)) {
178 // Whatever the bytes, decoding either fails or round-trips exactly.
179 if let Ok(node) = Node::decode(&bytes) {
180 prop_assert_eq!(node.encode(), bytes.clone());
181 }
182 if let Ok(changeset) = Changeset::decode(&bytes) {
183 prop_assert_eq!(changeset.encode(), bytes);
184 }
185 }
186
187 #[test]
188 fn changesets_round_trip(parts in changeset_parts()) {
189 let assembled = parts.assemble().unwrap();
190 let decoded = Changeset::decode(&assembled.encoded).unwrap();
191 prop_assert_eq!(&decoded, &assembled.changeset);
192 prop_assert_eq!(decoded.encode(), assembled.encoded);
193 prop_assert_eq!(decoded.id(), assembled.id);
194 }
195}
196
197proptest! {
198 #![proptest_config(ProptestConfig::with_cases(24))]
199
200 #[test]
201 fn split_directories_are_canonical(entries in wide_entries(), seed in any::<u64>()) {
202 let mut sorted = entries.clone();
203 sorted.sort_by(|a, b| a.name.cmp(&b.name));
204 sorted.dedup_by(|a, b| a.name == b.name);
205 let dir = build_directory(sorted.clone()).unwrap();
206
207 // Every node decodes and re-encodes to itself.
208 for (id, bytes) in &dir.nodes {
209 let node = Node::decode(bytes).unwrap();
210 prop_assert_eq!(&node.encode(), bytes);
211 prop_assert_eq!(node.id(), *id);
212 }
213
214 // Size limits: nothing above the maximum, and a split directory is
215 // never stored flat.
216 let sizes = node_sizes(&dir.nodes);
217 prop_assert!(sizes.iter().all(|s| *s <= MAX_NODE_ENTRIES.max(MAX_FLAT_ENTRIES)));
218 if sorted.len() > MAX_FLAT_ENTRIES {
219 prop_assert!(dir.nodes.len() >= 3);
220 prop_assert!(sizes.iter().all(|s| *s <= MAX_NODE_ENTRIES));
221 }
222
223 // Reading the nodes back gives the entries and passes the canonical check.
224 let store: HashMap<ObjectId, Vec<u8>> = dir.nodes.iter().cloned().collect();
225 prop_assert_eq!(read_directory(dir.root(), |id| store.get(id).cloned()).unwrap(), sorted.clone());
226
227 // Boundaries depend on names only: new contents, same node sizes.
228 let recontent: Vec<Entry> = sorted
229 .iter()
230 .map(|e| Entry {
231 name: e.name.clone(),
232 kind: EntryKind::File {
233 blob: ObjectId::hash(Kind::Blob, &seed.to_le_bytes()),
234 size: seed,
235 },
236 })
237 .collect();
238 prop_assert_eq!(node_sizes(&build_directory(recontent).unwrap().nodes), sizes.clone());
239
240 // Removing one entry keeps every leaf that ends before it: the scan up
241 // to there is unchanged, so an edit never rewrites earlier leaves.
242 if sorted.len() > MAX_FLAT_ENTRIES + 1 {
243 let victim = (seed as usize) % sorted.len();
244 let mut smaller = sorted.clone();
245 let removed = smaller.remove(victim);
246 let after_leaves = leaves(&build_directory(smaller).unwrap().nodes);
247 for (last, id) in leaves(&dir.nodes) {
248 if last < removed.name {
249 prop_assert!(after_leaves.iter().any(|(_, a)| *a == id));
250 }
251 }
252 }
253 }
254}
255
256fn leaves(nodes: &[(ObjectId, Vec<u8>)]) -> Vec<(Vec<u8>, ObjectId)> {
257 nodes
258 .iter()
259 .filter_map(|(id, bytes)| match Node::decode(bytes).unwrap() {
260 Node::Leaf(e) => Some((e.last().unwrap().name.clone(), *id)),
261 _ => None,
262 })
263 .collect()
264}