Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 20.2 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! The parallel import makes what the one-thread import makes: the same
5//! objects, the same map, the same report, and the same writes to the store,
6//! each hint given while the object it names is stored, or not, as it was
7//! then. It fails the same way too, leaves the same map when it does, and
8//! never leaves a map naming an object that was not stored.
9
10mod common;
11
12use std::collections::BTreeMap;
13use std::io;
14use std::sync::{Mutex, PoisonError};
15
16use braid_format::{Kind, MemoryObjects, ObjectId, Objects};
17use braid_git::{Error, GitMap, GitOid, ImportOptions, ImportReport, import, import_parallel};
18use common::{Entry, Item, Repo, exec, file, link, raw_tree, submodule};
19
20/// The thread counts the parallel import is compared at.
21const THREADS: [usize; 3] = [1, 2, 8];
22
23/// One write to the store: what was written, and the hint it came with, if
24/// any, with whether the object the hint names was stored already.
25#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
26struct Write {
27 kind: Kind,
28 id: ObjectId,
29 hint: Option<(ObjectId, bool)>,
30}
31
32/// Objects in memory that log every write, and can be told to refuse to
33/// store an object, or to lose one once stored.
34#[derive(Default)]
35struct Logged {
36 objects: MemoryObjects,
37 log: Mutex<Vec<Write>>,
38 refused: Mutex<Option<ObjectId>>,
39 lost: Mutex<Option<ObjectId>>,
40}
41
42impl Logged {
43 fn write(
44 &self,
45 kind: Kind,
46 payload: &[u8],
47 similar: Option<&ObjectId>,
48 ) -> Result<ObjectId, io::Error> {
49 let id = ObjectId::hash(kind, payload);
50 if *lock(&self.refused) == Some(id) {
51 return Err(io::Error::other("this store refuses that object"));
52 }
53 let hint = similar.map(|similar| {
54 let Ok(present) = self.objects.contains(similar);
55 (*similar, present)
56 });
57 let Ok(stored) = self.objects.put(kind, payload);
58 lock(&self.log).push(Write {
59 kind,
60 id: stored,
61 hint,
62 });
63 Ok(stored)
64 }
65
66 /// The first write of each object so far, in a canonical order: writing
67 /// an object again does nothing, and the parallel import does not repeat
68 /// a write its batch already makes.
69 fn writes(&self) -> Vec<Write> {
70 let mut seen = std::collections::HashSet::new();
71 let mut writes: Vec<Write> = lock(&self.log)
72 .iter()
73 .filter(|write| seen.insert(write.id))
74 .copied()
75 .collect();
76 writes.sort();
77 writes
78 }
79
80 /// Every object held, with its kind and payload.
81 fn contents(&self) -> BTreeMap<ObjectId, (Kind, Vec<u8>)> {
82 self.objects
83 .ids()
84 .into_iter()
85 .map(|id| {
86 let Ok(Some(found)) = self.objects.get(&id) else {
87 unreachable!("listed objects are held")
88 };
89 (id, found)
90 })
91 .collect()
92 }
93}
94
95impl Objects for Logged {
96 type Error = io::Error;
97
98 fn get(&self, id: &ObjectId) -> Result<Option<(Kind, Vec<u8>)>, Self::Error> {
99 if *lock(&self.lost) == Some(*id) {
100 return Ok(None);
101 }
102 let Ok(found) = self.objects.get(id);
103 Ok(found)
104 }
105
106 fn put(&self, kind: Kind, payload: &[u8]) -> Result<ObjectId, Self::Error> {
107 self.write(kind, payload, None)
108 }
109
110 fn put_similar(
111 &self,
112 kind: Kind,
113 payload: &[u8],
114 similar: &ObjectId,
115 ) -> Result<ObjectId, Self::Error> {
116 self.write(kind, payload, Some(similar))
117 }
118}
119
120fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
121 mutex.lock().unwrap_or_else(PoisonError::into_inner)
122}
123
124/// Imports with one thread (`None`) or on that many threads.
125fn run(
126 threads: Option<usize>,
127 git: &Repo,
128 objects: &Logged,
129 map: &mut GitMap,
130 options: &ImportOptions,
131) -> Result<ImportReport, Error> {
132 match threads {
133 None => import(git.path(), objects, map, options),
134 Some(threads) => import_parallel(git.path(), objects, map, options, threads),
135 }
136}
137
138/// Fifty lines, one of which says `version`, so that versions are close.
139fn text(version: usize) -> String {
140 (0..50)
141 .map(|n| format!("line {n} of {}\n", if n == 25 { version } else { 0 }))
142 .collect()
143}
144
145/// A file just large enough that the parallel import reads it twice rather
146/// than keep it until it is stored.
147fn large(version: usize) -> Vec<u8> {
148 let mut content = text(version).repeat((4 << 20) / 1000 + 1).into_bytes();
149 content.truncate((4 << 20) + 1);
150 content
151}
152
153const EMPTY_TREE: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
154
155/// Commits made by one `git fast-import`, to build a long history quickly.
156/// Each commit holds exactly the entries it is given, as a snapshot does.
157#[derive(Default)]
158struct FastImport {
159 stream: Vec<u8>,
160 marks: usize,
161}
162
163impl FastImport {
164 fn mark(&mut self) -> usize {
165 self.marks += 1;
166 self.marks
167 }
168
169 fn line(&mut self, line: &str) {
170 self.stream.extend_from_slice(line.as_bytes());
171 self.stream.push(b'\n');
172 }
173
174 fn data(&mut self, content: &[u8]) {
175 self.line(&format!("data {}", content.len()));
176 self.stream.extend_from_slice(content);
177 self.stream.push(b'\n');
178 }
179
180 /// A blob, by its mark.
181 fn blob(&mut self, content: &[u8]) -> String {
182 let mark = self.mark();
183 self.line("blob");
184 self.line(&format!("mark :{mark}"));
185 self.data(content);
186 format!(":{mark}")
187 }
188
189 /// A commit on `branch` after `parents`, by their marks; returns its own.
190 fn commit(
191 &mut self,
192 branch: &str,
193 parents: &[usize],
194 entries: &[Entry],
195 message: &str,
196 ) -> usize {
197 let mut files = Vec::new();
198 for (path, item) in entries {
199 let (mode, data) = match item {
200 Item::File(content) => ("100644", self.blob(content)),
201 Item::Exec(content) => ("100755", self.blob(content)),
202 Item::Link(target) => ("120000", self.blob(target)),
203 Item::Submodule(commit) => ("160000", commit.clone()),
204 };
205 files.push(format!("M {mode} {data} {}", String::from_utf8_lossy(path)));
206 }
207 let mark = self.mark();
208 let when = 1_700_000_000 + 60 * mark;
209 self.line(&format!("commit refs/heads/{branch}"));
210 self.line(&format!("mark :{mark}"));
211 self.line(&format!(
212 "author Ada Lovelace <ada@example.org> {when} +0100"
213 ));
214 self.line(&format!(
215 "committer Charles Babbage <charles@example.org> {when} +0100"
216 ));
217 self.data(message.as_bytes());
218 for (at, parent) in parents.iter().enumerate() {
219 self.line(&format!(
220 "{} :{parent}",
221 if at == 0 { "from" } else { "merge" }
222 ));
223 }
224 self.line("deleteall");
225 for file in files {
226 self.line(&file);
227 }
228 mark
229 }
230
231 /// An annotated tag on a commit, by its mark.
232 fn tag(&mut self, name: &str, commit: usize, message: &str) {
233 self.line(&format!("tag {name}"));
234 self.line(&format!("from :{commit}"));
235 self.line("tagger Ada Lovelace <ada@example.org> 1700000000 +0100");
236 self.data(message.as_bytes());
237 }
238}
239
240/// What commit `i` of the history holds: files edited in every commit, every
241/// few commits, or once in a while; deep directories; a directory that comes
242/// and goes, and one that grows; the same content at two paths; an
243/// executable, a symlink, a submodule; and for a few commits a file too large
244/// to keep in memory.
245fn files(i: usize) -> Vec<Entry> {
246 let mut entries = vec![
247 file("hot.txt", text(i)),
248 file("src/lib.rs", text(i / 3)),
249 file("src/deep/a/b/c.txt", text(i / 10)),
250 exec("run.sh", format!("#!/bin/sh\necho {}\n", i / 7)),
251 link("latest", format!("v{}", i / 5)),
252 file("same-1.txt", text(i / 9)),
253 file("same-2.txt", text(i / 9)),
254 ];
255 for n in 0..i / 25 {
256 entries.push(file(format!("grow/f{n}.txt"), text(n)));
257 }
258 if (i / 20).is_multiple_of(2) {
259 entries.push(file("toggle/x.txt", "comes and goes\n"));
260 }
261 if i >= 90 {
262 entries.push(submodule("vendor", &format!("{:040x}", 0x1000 + i / 30)));
263 }
264 if (60..63).contains(&i) {
265 entries.push(file("large.bin", large(i)));
266 }
267 entries
268}
269
270/// A history of more than two batches of the parallel import, made of
271/// [`files`], with a side branch merged twice; a commit whose trees are not
272/// canonical (an odd mode, a duplicate name, empty directories) and two
273/// after it; and annotated tags, one on another, one on a tree that no
274/// commit holds and one on a blob, with a plain tag on another blob.
275fn history() -> Repo {
276 let mut git = Repo::new();
277 let mut stream = FastImport::default();
278 let mut main: Option<usize> = None;
279 for i in 0..140 {
280 let entries = files(i);
281 let head = match (i, main) {
282 (40 | 110, Some(base)) => {
283 let mut side = base;
284 for n in 0..3 {
285 let mut entries = entries.clone();
286 entries.push(file("side.txt", text(i + n)));
287 side = stream.commit("side", &[side], &entries, &format!("side {i} {n}"));
288 }
289 let mut entries = entries.clone();
290 entries.push(file("side.txt", text(i + 2)));
291 stream.commit("main", &[base, side], &entries, &format!("merge {i}"))
292 }
293 _ => {
294 let parents: Vec<usize> = main.into_iter().collect();
295 stream.commit("main", &parents, &entries, &format!("commit {i}"))
296 }
297 };
298 main = Some(head);
299 if i == 50 {
300 stream.tag("v1", head, "release 1");
301 }
302 }
303 stream.line("done");
304 git.git_input(&["fast-import", "--quiet", "--done"], &stream.stream);
305
306 // A root that is not canonical, beside the usual files, then two more
307 // commits as usual.
308 let usual = git.tree(&files(140));
309 let x = git.blob(b"x\n");
310 let y = git.blob(b"y\n");
311 let odd = git.literally(
312 "tree",
313 &raw_tree(&[
314 ("100664", b"group-writable", &x),
315 ("100644", b"twice", &x),
316 ("100644", b"twice", &y),
317 ]),
318 );
319 let only_empty = git.mktree(&[("40000", "tree", EMPTY_TREE, b"empty")]);
320 let root = git.mktree(&[
321 ("40000", "tree", &usual, b"usual"),
322 ("40000", "tree", &odd, b"odd"),
323 ("40000", "tree", EMPTY_TREE, b"empty"),
324 ("40000", "tree", &only_empty, b"only-empty"),
325 ]);
326 let parent = git.head("main").unwrap();
327 let commit = git.commit(&root, &[&parent], "odd trees");
328 git.set_ref("refs/heads/main", &commit);
329 for i in 141..143 {
330 git.snapshot("main", &files(i), &format!("commit {i}"));
331 }
332
333 let release = git.git(&["rev-parse", "refs/tags/v1"]);
334 git.annotated_tag("v1-on-v1", &release, "a tag on a tag");
335 let loose_tree = git.tree(&[
336 file("only-here/a.txt", "a tree no commit holds\n"),
337 file("only-here/b.txt", text(1000)),
338 ]);
339 git.annotated_tag("tree-tag", &loose_tree, "a tree");
340 let tagged_blob = git.blob(b"a blob a tag points to\n");
341 git.annotated_tag("blob-tag", &tagged_blob, "a blob");
342 let plain_blob = git.blob(b"a blob a plain tag points to\n");
343 git.set_ref("refs/tags/plain-blob", &plain_blob);
344 git
345}
346
347/// Imports `git` with one thread and in parallel at every count of
348/// [`THREADS`], each into new objects and a new map, and checks that they
349/// all agree. Returns what the one-thread import made.
350fn assert_same(git: &Repo, options: &ImportOptions) -> (Logged, GitMap, ImportReport) {
351 let one = Logged::default();
352 let mut one_map = GitMap::new();
353 let one_report = run(None, git, &one, &mut one_map, options).unwrap();
354 for threads in THREADS {
355 let many = Logged::default();
356 let mut many_map = GitMap::new();
357 let report = run(Some(threads), git, &many, &mut many_map, options).unwrap();
358 assert_eq!(report, one_report, "{threads} threads");
359 assert_eq!(many_map.to_bytes(), one_map.to_bytes(), "{threads} threads");
360 assert!(many_map == one_map, "{threads} threads: the maps differ");
361 assert!(
362 many.contents() == one.contents(),
363 "{threads} threads: the objects differ"
364 );
365 assert_eq!(many.writes(), one.writes(), "{threads} threads");
366 }
367 (one, one_map, one_report)
368}
369
370/// Every git object reachable from a ref.
371fn git_objects(git: &Repo) -> Vec<GitOid> {
372 git.git(&["rev-list", "--objects", "--all"])
373 .lines()
374 .map(|line| line.split(' ').next().unwrap().parse().unwrap())
375 .collect()
376}
377
378/// Everything the map names is in the store: a resumed import trusts it.
379fn assert_mapped_objects_are_stored(git: &Repo, objects: &Logged, map: &GitMap) {
380 let stored = |id: &ObjectId| {
381 let Ok(found) = objects.objects.contains(id);
382 found
383 };
384 for oid in git_objects(git) {
385 if let Some(changeset) = map.changeset(&oid) {
386 assert!(stored(&changeset), "the changeset of commit {oid}");
387 }
388 if let Some(tree) = map.tree(&oid) {
389 assert!(stored(&tree), "the braid tree of tree {oid}");
390 }
391 if let Some(raw) = map.raw_tree(&oid) {
392 assert!(stored(&raw), "the raw bytes of tree {oid}");
393 }
394 if let Some((blob, _)) = map.blob(&oid) {
395 assert!(stored(&blob), "the braid blob of blob {oid}");
396 }
397 if let Some(tag) = map.tag(&oid) {
398 assert!(stored(&tag.raw), "the raw bytes of tag {oid}");
399 }
400 }
401}
402
403#[test]
404fn the_parallel_import_makes_what_the_one_thread_import_makes() {
405 let git = history();
406 let (one, map, report) = assert_same(&git, &ImportOptions::default());
407 // The history is what it says it is.
408 assert!(report.commits > 140, "{report:?}");
409 assert!(report.raw_trees >= 2, "{report:?}");
410 assert_eq!(report.tags, 4, "{report:?}");
411 assert!(
412 one.writes()
413 .iter()
414 .any(|write| write.kind == Kind::Blob && write.hint.is_some_and(|(_, stored)| stored)),
415 "blobs come with hints"
416 );
417 assert_mapped_objects_are_stored(&git, &one, &map);
418}
419
420#[test]
421fn a_parallel_import_continues_one_as_a_one_thread_import_does() {
422 let git = history();
423 // The tag on release 1 first, then everything, into the same objects
424 // and map: the second import only brings in what is new.
425 let first = ImportOptions {
426 refs: vec![b"refs/tags/v1".to_vec()],
427 };
428 let one = Logged::default();
429 let mut one_map = GitMap::new();
430 run(None, &git, &one, &mut one_map, &first).unwrap();
431 let one_report = run(None, &git, &one, &mut one_map, &ImportOptions::default()).unwrap();
432 for threads in THREADS {
433 let many = Logged::default();
434 let mut many_map = GitMap::new();
435 // Each half on either side: parallel after one thread, and the
436 // other way round.
437 run(None, &git, &many, &mut many_map, &first).unwrap();
438 let report = run(
439 Some(threads),
440 &git,
441 &many,
442 &mut many_map,
443 &ImportOptions::default(),
444 )
445 .unwrap();
446 assert_eq!(report, one_report, "{threads} threads");
447 assert_eq!(many_map.to_bytes(), one_map.to_bytes(), "{threads} threads");
448 assert!(many.contents() == one.contents(), "{threads} threads");
449 assert_eq!(many.writes(), one.writes(), "{threads} threads");
450
451 let other = Logged::default();
452 let mut other_map = GitMap::new();
453 run(Some(threads), &git, &other, &mut other_map, &first).unwrap();
454 let report = run(
455 None,
456 &git,
457 &other,
458 &mut other_map,
459 &ImportOptions::default(),
460 )
461 .unwrap();
462 assert_eq!(report, one_report, "{threads} threads");
463 assert_eq!(
464 other_map.to_bytes(),
465 one_map.to_bytes(),
466 "{threads} threads"
467 );
468 assert_eq!(other.writes(), one.writes(), "{threads} threads");
469 }
470}
471
472#[test]
473fn a_refused_name_stops_both_imports_at_the_same_commit_with_the_same_map() {
474 let mut git = history();
475 let hook = git.tree(&[exec("hooks/post-checkout", "#!/bin/sh\necho owned\n")]);
476 let evil = git.literally("tree", &raw_tree(&[("40000", b".GIT", &hook)]));
477 let parent = git.head("main").unwrap();
478 let commit = git.commit(&evil, &[&parent], "evil");
479 git.set_ref("refs/heads/main", &commit);
480 for threads in THREADS {
481 let one = Logged::default();
482 let mut one_map = GitMap::new();
483 let one_err = run(None, &git, &one, &mut one_map, &ImportOptions::default()).unwrap_err();
484 assert!(matches!(one_err, Error::RefusedPath { .. }), "{one_err}");
485 let many = Logged::default();
486 let mut many_map = GitMap::new();
487 let many_err = run(
488 Some(threads),
489 &git,
490 &many,
491 &mut many_map,
492 &ImportOptions::default(),
493 )
494 .unwrap_err();
495 assert_eq!(many_err.to_string(), one_err.to_string());
496 assert_eq!(many_map.to_bytes(), one_map.to_bytes(), "{threads} threads");
497 assert_eq!(many.writes(), one.writes(), "{threads} threads");
498 assert_mapped_objects_are_stored(&git, &many, &many_map);
499 }
500}
501
502#[test]
503fn a_store_that_fails_leaves_the_map_a_one_thread_import_leaves() {
504 let git = history();
505 let (_, clean_map, clean_report) = assert_same(&git, &ImportOptions::default());
506 // A version of the file edited in every commit, past the first batch.
507 let refused = ObjectId::hash(Kind::Blob, text(100).as_bytes());
508 let mut first: Option<(String, Vec<u8>)> = None;
509 for threads in [None, Some(1), Some(2), Some(8)] {
510 let objects = Logged::default();
511 *lock(&objects.refused) = Some(refused);
512 let mut map = GitMap::new();
513 let err = run(threads, &git, &objects, &mut map, &ImportOptions::default()).unwrap_err();
514 assert!(matches!(err, Error::Objects(_)), "{threads:?}: {err}");
515 assert!(map.counts().commits < clean_report.commits, "{threads:?}");
516 assert_mapped_objects_are_stored(&git, &objects, &map);
517 let failed = (err.to_string(), map.to_bytes());
518 match &first {
519 None => first = Some(failed),
520 Some(first) => assert!(*first == failed, "{threads:?}: another error or map"),
521 }
522
523 // Once the store works, the import resumes from that map and ends
524 // where an import that never failed does.
525 *lock(&objects.refused) = None;
526 run(threads, &git, &objects, &mut map, &ImportOptions::default()).unwrap();
527 assert_eq!(map.to_bytes(), clean_map.to_bytes(), "{threads:?}");
528 assert_mapped_objects_are_stored(&git, &objects, &map);
529 }
530}
531
532#[test]
533fn a_store_that_loses_what_it_stored_fails_the_checks_of_both_imports() {
534 let git = history();
535 let (_, clean_map, _) = assert_same(&git, &ImportOptions::default());
536 let commit: GitOid = git
537 .git(&["log", "--format=%H", "--grep=^commit 100$", "main"])
538 .parse()
539 .unwrap();
540 let root: GitOid = git
541 .git(&["rev-parse", &format!("{commit}^{{tree}}")])
542 .parse()
543 .unwrap();
544 // Read back by the check of the commit, and by the check of its tree.
545 for lost in [
546 clean_map.changeset(&commit).unwrap(),
547 clean_map.tree(&root).unwrap(),
548 ] {
549 let mut first: Option<(String, Vec<u8>)> = None;
550 for threads in [None, Some(1), Some(2), Some(8)] {
551 let objects = Logged::default();
552 *lock(&objects.lost) = Some(lost);
553 let mut map = GitMap::new();
554 let err =
555 run(threads, &git, &objects, &mut map, &ImportOptions::default()).unwrap_err();
556 assert!(err.to_string().contains("missing"), "{threads:?}: {err}");
557 assert!(map.changeset(&commit).is_none(), "{threads:?}");
558 let failed = (err.to_string(), map.to_bytes());
559 match &first {
560 None => first = Some(failed),
561 Some(first) => assert!(*first == failed, "{threads:?}: another error or map"),
562 }
563 }
564 }
565}