Elffuss BraidHub

utopia-ia/elffuss-braid public

Merge derived data: ancestry, path history and blame
Changesetf8f43175152ef3cc75f5b01a0b22d0e2fd8cc31759d67167b1fcc5e7100f09ea
AuthorKikoCis <KikoCis@users.noreply.github.com> · 2026-10-16 01:33 +02:00
CommitterKikoCis <KikoCis@users.noreply.github.com> · 2026-10-16 01:33 +02:00
Parents71ae7b5a0cf6, e02541b06336

Browse the files at this changeset

21 files changed

modified Cargo.lock +1 −0
@@ -496,6 +496,7 @@
496496 name = "elffuss-braid-engine"
497497 version = "0.0.1"
498498 dependencies = [
499+ "blake3",
499500 "elffuss-braid-format",
500501 "imara-diff",
501502 "proptest",
modified README.md +8 −0
@@ -104,6 +104,8 @@
104104 cd /tmp/demo
105105 braid git import /path/to/any/git/repository # every branch and tag
106106 braid log main -n 5
107+braid log main -- src/lib.rs # only the changes to a path
108+braid blame main src/lib.rs # who last changed each line
107109 braid show main --json
108110 braid fsck
109111 ```
@@ -172,6 +174,12 @@
172174 - `braid show` and `braid diff <from> <to>` list the files a change adds,
173175 modifies, deletes or turns into another type (`A`, `M`, `D`, `T`), as
174176 `git diff --name-status` does.
177+- `braid log [rev] -- <path>...` lists the changesets that touched a path,
178+ along first parents, and `braid blame <rev> <path>` names the changeset,
179+ the agent and the date of each line. Both read derived data kept in the
180+ store: generation numbers and skip pointers for ancestry, changed-path
181+ filters, and blame records, computed the first time they are needed.
182+ `braid derive --all` computes them ahead of time, after a large import.
175183
176184 `braid status --help`, `braid land --help` and `braid update --help` describe
177185 every JSON field.
added crates/cli/src/history.rs +208 −0
@@ -0,0 +1,208 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! The commands answered with derived data: `log -- <path>`, `blame` and
5+//! `derive`.
6+
7+use std::collections::HashMap;
8+use std::io::{self, Write};
9+use std::process::ExitCode;
10+
11+use anyhow::{Result, bail};
12+use braid_format::{Changeset, ObjectId, validate_path};
13+use braid_repo::Repo;
14+use serde_json::{Value, json};
15+
16+use crate::{
17+ Cli, agent_of, format_signature_time, open_repo, print_json, read_changeset, resolve_changeset,
18+};
19+
20+/// The long help of `blame`.
21+pub(crate) const BLAME_HELP: &str =
22+ "Show, for each line of a file, the changeset that last changed it,
23+following first parents from the revision: a merge on the first-parent
24+chain owns the lines it brought in. Renames are not followed: the lines of
25+a file are new where the path appeared.
26+
27+Each line prints the changeset's short id, its agent (or author when it
28+names no agent), the author's date, the line number and the line. With
29+--json, blame prints changeset, the full id of the revision, path, and
30+lines: one per line, with line (counted from 1), changeset, agent (or
31+null), author, time and content.
32+
33+The path is given from the repository's root. Blame data is derived and
34+kept in the store, so blaming the file again, at this revision or a later
35+one, reuses it.";
36+
37+/// The long help of `derive`.
38+pub(crate) const DERIVE_HELP: &str =
39+ "Compute the derived data of every changeset reachable from the revisions
40+(main when none is given, every ref with --all): its generation number and
41+first-parent skip pointer, which make ancestry queries and merge bases
42+cheap, and its changed-path filter, which lets log -- <path> and blame skip
43+changesets. Blame data, per file, is computed by blame itself.
44+
45+Derived data is computed when a command first needs it, so this is only a
46+way to pay that cost ahead of time, after a large import for example.
47+With --json, derive prints changesets, how many are reachable, and
48+computed, how many records were missing and computed.";
49+
50+/// A path given on the command line, as the repository names it: from the
51+/// root, without `./` in front or `/` at the end. `.` and the empty path are
52+/// the root.
53+pub(crate) fn repo_path(text: &str) -> Result<Vec<u8>> {
54+ let mut path = text.trim_end_matches('/');
55+ while let Some(rest) = path.strip_prefix("./") {
56+ path = rest.trim_start_matches('/');
57+ }
58+ if path.is_empty() || path == "." {
59+ return Ok(Vec::new());
60+ }
61+ if let Err(err) = validate_path(path.as_bytes()) {
62+ bail!("{text:?} is not a path in the repository: {err}");
63+ }
64+ Ok(path.as_bytes().to_vec())
65+}
66+
67+/// The changesets on the first-parent chain of `head` that touch one of
68+/// `paths`, newest first, at most `limit`.
69+pub(crate) fn path_log(
70+ repo: &Repo,
71+ head: ObjectId,
72+ paths: &[String],
73+ limit: usize,
74+) -> Result<Vec<ObjectId>> {
75+ let paths = paths
76+ .iter()
77+ .map(|path| repo_path(path))
78+ .collect::<Result<Vec<_>>>()?;
79+ let paths: Vec<&[u8]> = paths.iter().map(Vec::as_slice).collect();
80+ let mut history = repo.history();
81+ let found = history.path_log(head, &paths, limit)?;
82+ history.flush()?;
83+ Ok(found)
84+}
85+
86+pub(crate) fn blame(cli: &Cli, revision: &str, path: &str) -> Result<ExitCode> {
87+ let repo = open_repo(cli)?;
88+ let at = resolve_changeset(&repo, revision)?;
89+ let file = repo_path(path)?;
90+ let mut history = repo.history();
91+ let blame = history.blame(at, &file)?;
92+ history.flush()?;
93+ let Some(blame) = blame else {
94+ bail!("{path:?} is not a file at {}", at.short());
95+ };
96+
97+ // Each changeset that owns lines, read once.
98+ let mut changesets: HashMap<ObjectId, Changeset> = HashMap::new();
99+ for origin in &blame.origins {
100+ if !changesets.contains_key(origin) {
101+ changesets.insert(*origin, read_changeset(&repo, origin)?);
102+ }
103+ }
104+ let who = |id: &ObjectId| {
105+ let changeset = &changesets[id];
106+ agent_of(changeset)
107+ .unwrap_or_else(|| String::from_utf8_lossy(&changeset.author.name).into_owned())
108+ };
109+ let text = |line: &[u8]| {
110+ let line = line.strip_suffix(b"\n").unwrap_or(line);
111+ String::from_utf8_lossy(line).into_owned()
112+ };
113+
114+ if cli.json {
115+ let lines: Vec<Value> = blame
116+ .lines()
117+ .enumerate()
118+ .map(|(n, (line, origin))| {
119+ let changeset = &changesets[&origin];
120+ json!({
121+ "line": n + 1,
122+ "changeset": origin.to_hex(),
123+ "agent": agent_of(changeset),
124+ "author": String::from_utf8_lossy(&changeset.author.name),
125+ "time": format_signature_time(&changeset.author),
126+ "content": text(line),
127+ })
128+ })
129+ .collect();
130+ print_json(&json!({
131+ "changeset": at.to_hex(),
132+ "path": String::from_utf8_lossy(&file),
133+ "lines": lines,
134+ }))?;
135+ return Ok(ExitCode::SUCCESS);
136+ }
137+
138+ let width = blame
139+ .origins
140+ .iter()
141+ .map(|origin| who(origin).chars().count())
142+ .max()
143+ .unwrap_or(0);
144+ let digits = blame.origins.len().to_string().len();
145+ let mut out = io::stdout().lock();
146+ for (n, (line, origin)) in blame.lines().enumerate() {
147+ writeln!(
148+ out,
149+ "{} {:<width$} {} {:>digits$} {}",
150+ origin.short(),
151+ who(&origin),
152+ format_signature_time(&changesets[&origin].author),
153+ n + 1,
154+ text(line),
155+ )?;
156+ }
157+ Ok(ExitCode::SUCCESS)
158+}
159+
160+pub(crate) fn derive(cli: &Cli, all: bool, revisions: &[String]) -> Result<ExitCode> {
161+ let repo = open_repo(cli)?;
162+ let mut heads = Vec::new();
163+ for revision in revisions {
164+ heads.push(resolve_changeset(&repo, revision)?);
165+ }
166+ if all {
167+ heads.extend(repo.ref_changesets()?);
168+ } else if revisions.is_empty() {
169+ heads.push(resolve_changeset(&repo, "main")?);
170+ }
171+ let mut history = repo.history();
172+ let report = history.derive(&heads)?;
173+ if cli.json {
174+ print_json(&json!({
175+ "changesets": report.changesets,
176+ "computed": report.computed,
177+ }))?;
178+ } else {
179+ println!(
180+ "{} changesets; {} derived records computed",
181+ report.changesets, report.computed
182+ );
183+ }
184+ Ok(ExitCode::SUCCESS)
185+}
186+
187+#[cfg(test)]
188+mod tests {
189+ use super::*;
190+
191+ #[test]
192+ fn paths_are_taken_from_the_root() {
193+ for (text, path) in [
194+ ("src/lib.rs", "src/lib.rs"),
195+ ("src/", "src"),
196+ ("./src//", "src"),
197+ ("././a", "a"),
198+ (".", ""),
199+ ("", ""),
200+ ("./", ""),
201+ ] {
202+ assert_eq!(repo_path(text).unwrap(), path.as_bytes(), "{text:?}");
203+ }
204+ for bad in ["/abs", "a//b", "a/../b", ".."] {
205+ assert!(repo_path(bad).is_err(), "{bad:?}");
206+ }
207+ }
208+}
modified crates/cli/src/main.rs +61 −10
@@ -3,6 +3,7 @@
33
44 //! `braid`, the command-line tool.
55
6+mod history;
67 mod sync;
78 mod work;
89
@@ -87,7 +88,9 @@
8788 },
8889 /// Revert the newest operation that is not already undone.
8990 Undo,
90- /// Show history, following first parents.
91+ /// Show history, following first parents; after `--`, only the
92+ /// changesets that change one of the paths or anything below them.
93+ #[command(long_about = LOG_HELP)]
9194 Log {
9295 /// Where to start: a ref, a changeset id, or a short id (6 hex
9396 /// digits or more).
@@ -96,6 +99,28 @@
9699 /// How many changesets to show.
97100 #[arg(short = 'n', long, default_value_t = 20)]
98101 limit: usize,
102+ /// Paths, from the repository's root, after `--`.
103+ #[arg(last = true, value_name = "PATH")]
104+ paths: Vec<String>,
105+ },
106+ /// Show the changeset that last changed each line of a file, along
107+ /// first parents.
108+ #[command(long_about = history::BLAME_HELP)]
109+ Blame {
110+ /// The revision: a ref, a changeset id, or a short id.
111+ revision: String,
112+ /// The file, from the repository's root.
113+ path: String,
114+ },
115+ /// Compute derived data ahead of time: generation numbers, skip
116+ /// pointers and changed-path filters.
117+ #[command(long_about = history::DERIVE_HELP)]
118+ Derive {
119+ /// Every changeset reachable from any ref.
120+ #[arg(long)]
121+ all: bool,
122+ /// Revisions whose history to derive (default: main, unless --all).
123+ revisions: Vec<String>,
99124 },
100125 /// Show one changeset: parents, root, signatures, agent, message, and
101126 /// the files it changes against its first parent, as A, M, D or T.
@@ -248,7 +273,13 @@
248273 action: OpAction::Log { limit },
249274 } => op_log(cli, *limit),
250275 Command::Undo => undo(cli),
251- Command::Log { revision, limit } => log(cli, revision, *limit),
276+ Command::Log {
277+ revision,
278+ limit,
279+ paths,
280+ } => log(cli, revision, *limit, paths),
281+ Command::Blame { revision, path } => history::blame(cli, revision, path),
282+ Command::Derive { all, revisions } => history::derive(cli, *all, revisions),
252283 Command::Show { revision } => show(cli, revision),
253284 Command::Diff { from, to } => diff(cli, from, to),
254285 Command::Git {
@@ -668,17 +699,37 @@
668699 .to_owned()
669700 }
670701
671-fn log(cli: &Cli, revision: &str, limit: usize) -> Result<ExitCode> {
702+/// The long help of `log`.
703+const LOG_HELP: &str = "Show history from a revision, following first parents, newest first: the
704+short id, the author's date, the author with the agent, and the subject.
705+
706+With paths after `--` (log main -- src/lib.rs docs), only the changesets
707+whose changes, against their first parent, touch one of the paths or
708+anything below them, as `git log --first-parent -- <path>` lists them.
709+Paths are given from the repository's root and renames are not followed.
710+Changed-path filters, derived data kept in the store, let the walk skip the
711+other changesets without reading them.
712+
713+With --json, log prints each changeset as show does, without its changes.";
714+
715+fn log(cli: &Cli, revision: &str, limit: usize, paths: &[String]) -> Result<ExitCode> {
672716 let repo = open_repo(cli)?;
673- let mut next = Some(resolve_changeset(&repo, revision)?);
717+ let head = resolve_changeset(&repo, revision)?;
674718 let mut entries = Vec::new();
675- while let Some(id) = next {
676- if entries.len() == limit {
677- break;
719+ if paths.is_empty() {
720+ let mut next = Some(head);
721+ while let Some(id) = next {
722+ if entries.len() == limit {
723+ break;
724+ }
725+ let changeset = read_changeset(&repo, &id)?;
726+ next = changeset.parents.first().copied();
727+ entries.push((id, changeset));
728+ }
729+ } else {
730+ for id in history::path_log(&repo, head, paths, limit)? {
731+ entries.push((id, read_changeset(&repo, &id)?));
678732 }
679- let changeset = read_changeset(&repo, &id)?;
680- next = changeset.parents.first().copied();
681- entries.push((id, changeset));
682733 }
683734 if cli.json {
684735 print_json(&Value::Array(
added crates/cli/tests/history.rs +286 −0
@@ -0,0 +1,286 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! End-to-end tests of the commands that read derived data: `log -- <path>`,
5+//! `blame` and `derive`.
6+
7+use std::path::{Path, PathBuf};
8+use std::process::Command;
9+
10+use serde_json::Value;
11+
12+fn braid() -> Command {
13+ Command::new(env!("CARGO_BIN_EXE_braid"))
14+}
15+
16+/// A repository with its own scratch directory for file contents.
17+struct Repo {
18+ _dir: tempfile::TempDir,
19+ root: PathBuf,
20+ inputs: PathBuf,
21+}
22+
23+impl Repo {
24+ fn new() -> Self {
25+ let dir = tempfile::tempdir().unwrap();
26+ let root = dir.path().join("repo");
27+ let inputs = dir.path().join("inputs");
28+ std::fs::create_dir(&inputs).unwrap();
29+ let init = braid().arg("init").arg(&root).output().unwrap();
30+ assert!(init.status.success());
31+ Repo {
32+ _dir: dir,
33+ root,
34+ inputs,
35+ }
36+ }
37+
38+ fn braid(&self, agent: &str) -> Command {
39+ let mut command = braid();
40+ command
41+ .arg("--repo")
42+ .arg(&self.root)
43+ .env("BRAID_AGENT", agent)
44+ .env("BRAID_AUTHOR", "Ada Lovelace <ada@example.org>")
45+ .env("TZ", "UTC0");
46+ command
47+ }
48+
49+ /// Lands on main, as `agent`, a changeset on main's head that sets and
50+ /// deletes these files. Returns its id.
51+ fn change(
52+ &self,
53+ agent: &str,
54+ sets: &[(&str, &str)],
55+ deletes: &[&str],
56+ message: &str,
57+ ) -> String {
58+ let base = self.head().unwrap_or_else(|| "none".to_owned());
59+ let mut command = self.braid(agent);
60+ command.args([
61+ "change", "create", "--base", &base, "-m", message, "--land", "main",
62+ ]);
63+ for (n, (path, content)) in sets.iter().enumerate() {
64+ let input = self.inputs.join(format!("{message}-{n}"));
65+ std::fs::write(&input, content).unwrap();
66+ command
67+ .arg("--set")
68+ .arg(format!("{path}=@{}", input.display()));
69+ }
70+ for path in deletes {
71+ command.args(["--delete", path]);
72+ }
73+ let made = json(&mut command);
74+ made["change"].as_str().unwrap().to_owned()
75+ }
76+
77+ fn head(&self) -> Option<String> {
78+ let refs = json(self.braid("tester").arg("refs"));
79+ refs["refs"]["main"].as_str().map(str::to_owned)
80+ }
81+}
82+
83+fn output(command: &mut Command) -> std::process::Output {
84+ let out = command.output().unwrap();
85+ assert!(
86+ out.status.success(),
87+ "{command:?}: {}",
88+ String::from_utf8_lossy(&out.stderr)
89+ );
90+ out
91+}
92+
93+fn json(command: &mut Command) -> Value {
94+ serde_json::from_slice(&output(command.arg("--json")).stdout).unwrap()
95+}
96+
97+fn text(command: &mut Command) -> String {
98+ String::from_utf8(output(command).stdout).unwrap()
99+}
100+
101+fn error(command: &mut Command) -> String {
102+ let out = command.output().unwrap();
103+ assert!(!out.status.success(), "{command:?} should fail");
104+ String::from_utf8(out.stderr).unwrap()
105+}
106+
107+/// The ids `log` lists. `--json` goes first: after `--`, it would be a
108+/// path.
109+fn log_ids(repo: &Repo, args: &[&str]) -> Vec<String> {
110+ let out = output(repo.braid("tester").args(["--json", "log"]).args(args));
111+ let log: Value = serde_json::from_slice(&out.stdout).unwrap();
112+ log.as_array()
113+ .unwrap()
114+ .iter()
115+ .map(|entry| entry["id"].as_str().unwrap().to_owned())
116+ .collect()
117+}
118+
119+/// A small history: four changesets by three agents.
120+fn history() -> (Repo, [String; 4]) {
121+ let repo = Repo::new();
122+ let one = repo.change(
123+ "agent-1",
124+ &[
125+ ("README.md", "# Demo\n"),
126+ ("src/lib.rs", "fn a() {}\nfn b() {}\n"),
127+ ("src/util.rs", "fn u() {}\n"),
128+ ],
129+ &[],
130+ "one",
131+ );
132+ let two = repo.change(
133+ "agent-2",
134+ &[("src/lib.rs", "fn a() {}\nfn b2() {}\nfn c() {}\n")],
135+ &[],
136+ "two",
137+ );
138+ let three = repo.change("agent-1", &[], &["src/util.rs"], "three");
139+ let four = repo.change(
140+ "agent-3",
141+ &[("README.md", "# Demo\n\nMore.\n")],
142+ &[],
143+ "four",
144+ );
145+ (repo, [one, two, three, four])
146+}
147+
148+#[test]
149+fn log_lists_the_changes_to_paths() {
150+ let (repo, [one, two, three, four]) = history();
151+ assert_eq!(
152+ log_ids(&repo, &["--", "src/lib.rs"]),
153+ [two.as_str(), one.as_str()]
154+ );
155+ assert_eq!(
156+ log_ids(&repo, &["main", "--", "src"]),
157+ [three.as_str(), two.as_str(), one.as_str()]
158+ );
159+ assert_eq!(
160+ log_ids(&repo, &["main", "--", "./src/"]),
161+ [three.as_str(), two.as_str(), one.as_str()]
162+ );
163+ assert_eq!(
164+ log_ids(&repo, &["main", "--", "src/util.rs"]),
165+ [three.as_str(), one.as_str()]
166+ );
167+ assert_eq!(
168+ log_ids(&repo, &["main", "-n", "1", "--", "src"]),
169+ [three.as_str()]
170+ );
171+ assert_eq!(
172+ log_ids(&repo, &["main", "--", "README.md", "src/util.rs"]),
173+ [four.as_str(), three.as_str(), one.as_str()]
174+ );
175+ assert_eq!(log_ids(&repo, &["main", "--", "."]).len(), 4);
176+ assert!(log_ids(&repo, &["main", "--", "nothing"]).is_empty());
177+ // From an earlier changeset, and without paths as before.
178+ assert_eq!(log_ids(&repo, &[&two, "--", "README.md"]), [one.as_str()]);
179+ assert_eq!(
180+ log_ids(&repo, &[]),
181+ [four.as_str(), three.as_str(), two.as_str(), one.as_str()]
182+ );
183+
184+ let lines = text(
185+ repo.braid("tester")
186+ .args(["log", "main", "--", "src/lib.rs"]),
187+ );
188+ let lines: Vec<&str> = lines.lines().collect();
189+ assert_eq!(lines.len(), 2);
190+ assert!(lines[0].starts_with(&two[..12]), "{lines:?}");
191+ assert!(lines[0].ends_with("(agent-2) two"), "{lines:?}");
192+
193+ let err = error(repo.braid("tester").args(["log", "main", "--", "../x"]));
194+ assert!(err.contains("not a path in the repository"), "{err}");
195+}
196+
197+#[test]
198+fn blame_names_the_changeset_of_each_line() {
199+ let (repo, [one, two, _, four]) = history();
200+ let blame = json(repo.braid("tester").args(["blame", "main", "src/lib.rs"]));
201+ assert_eq!(blame["changeset"], four.as_str());
202+ assert_eq!(blame["path"], "src/lib.rs");
203+ let lines = blame["lines"].as_array().unwrap();
204+ let summary: Vec<(u64, &str, &str, &str)> = lines
205+ .iter()
206+ .map(|line| {
207+ (
208+ line["line"].as_u64().unwrap(),
209+ line["changeset"].as_str().unwrap(),
210+ line["agent"].as_str().unwrap(),
211+ line["content"].as_str().unwrap(),
212+ )
213+ })
214+ .collect();
215+ assert_eq!(
216+ summary,
217+ [
218+ (1, one.as_str(), "agent-1", "fn a() {}"),
219+ (2, two.as_str(), "agent-2", "fn b2() {}"),
220+ (3, two.as_str(), "agent-2", "fn c() {}"),
221+ ]
222+ );
223+ assert_eq!(lines[0]["author"], "Ada Lovelace");
224+ assert!(lines[0]["time"].as_str().unwrap().ends_with("+0000"));
225+
226+ // Text: short id, agent, date, line number and the line.
227+ let out = text(repo.braid("tester").args(["blame", "main", "src/lib.rs"]));
228+ let rows: Vec<&str> = out.lines().collect();
229+ assert_eq!(rows.len(), 3);
230+ let first: Vec<&str> = rows[0].split(" ").collect();
231+ assert_eq!(first[0], &one[..12]);
232+ assert_eq!(first[1], "agent-1");
233+ assert!(first[2].ends_with("+0000"), "{rows:?}");
234+ assert_eq!(first[3], "1");
235+ assert_eq!(first[4], "fn a() {}");
236+ assert!(rows[1].starts_with(&two[..12]), "{rows:?}");
237+
238+ // At an earlier changeset, a file deleted since can be blamed.
239+ let util = json(repo.braid("tester").args(["blame", &two, "src/util.rs"]));
240+ assert_eq!(util["lines"][0]["changeset"], one.as_str());
241+ for (revision, path) in [
242+ ("main", "src/util.rs"),
243+ ("main", "src"),
244+ ("main", "nothing"),
245+ ] {
246+ let err = error(repo.braid("tester").args(["blame", revision, path]));
247+ assert!(err.contains("is not a file at"), "{err}");
248+ }
249+ assert!(
250+ text(repo.braid("tester").args(["blame", "--help"])).contains("Renames are not followed")
251+ );
252+}
253+
254+#[test]
255+fn derive_computes_once_and_keeps_the_store_clean() {
256+ let (repo, [_, two, _, _]) = history();
257+ let derived = json(repo.braid("tester").arg("derive"));
258+ assert_eq!(derived["changesets"], 4);
259+ // Commit graph data and a changed-path filter for each.
260+ assert_eq!(derived["computed"], 8);
261+ let again = json(repo.braid("tester").args(["derive", "--all"]));
262+ assert_eq!(again["changesets"], 4);
263+ assert_eq!(again["computed"], 0);
264+ let partial = json(repo.braid("tester").args(["derive", &two]));
265+ assert_eq!(partial["changesets"], 2);
266+ assert_eq!(partial["computed"], 0);
267+ assert!(
268+ Path::new(&repo.root)
269+ .join(".braid/store/derived/index")
270+ .exists()
271+ );
272+
273+ let out = text(repo.braid("tester").arg("derive"));
274+ assert_eq!(out, "4 changesets; 0 derived records computed\n");
275+ // Derived records are ordinary objects: the store stays clean.
276+ assert_eq!(json(repo.braid("tester").arg("fsck"))["clean"], true);
277+
278+ // A repository without main needs revisions or --all.
279+ let empty = Repo::new();
280+ let err = error(empty.braid("tester").arg("derive"));
281+ assert!(err.contains("main"), "{err}");
282+ assert_eq!(
283+ json(empty.braid("tester").args(["derive", "--all"]))["changesets"],
284+ 0
285+ );
286+}
modified crates/engine/Cargo.toml +1 −0
@@ -14,6 +14,7 @@
1414
1515 [dependencies]
1616 braid-format.workspace = true
17+blake3.workspace = true
1718 imara-diff = { version = "0.2.0", default-features = false }
1819 thiserror = "2.0"
1920 unicode-normalization = "0.1.25"
modified crates/engine/src/ancestry.rs +507 −6
@@ -3,16 +3,44 @@
33
44 //! Ancestry: first-parent chains and merge bases.
55 //!
6-//! These walk history one changeset at a time, so they cost time proportional
7-//! to the part of history they cover. Generation numbers and skip pointers,
8-//! stored as derived data, will make them logarithmic.
6+//! The free functions walk history one changeset at a time, reading only
7+//! objects, so they cost time proportional to the part of history they
8+//! cover. The methods of [`History`] of the same names give the same answers
9+//! with commit graph data, derived data stored per changeset:
10+//!
11+//! - the **generation**, 1 for a changeset without parents and otherwise 1
12+//! more than the largest generation of its parents, so that an ancestor
13+//! always has a smaller generation than its descendants and walks stop as
14+//! soon as they go below the one they look for;
15+//! - the **height**, the number of first parents down to a changeset
16+//! without parents, and a **skip pointer** to the first-parent ancestor at
17+//! height [`skip_height`]`(height)`, the rule of Bitcoin's block index:
18+//! following skip pointers reaches any first-parent ancestor in a number of
19+//! steps that grows with the logarithm of the distance.
20+//!
21+//! The derived function `graph`, version 1, of a changeset is:
22+//!
23+//! ```text
24+//! uv n, n × [32] parents, in order
25+//! uv generation
26+//! uv height
27+//! [32] skip pointer, when the height is not 0
28+//! ```
29+//!
30+//! It depends on the parents' values, so computing it for a changeset
31+//! computes it for every ancestor that lacks it, once; afterwards a query
32+//! reads only the records it needs.
933
10-use std::collections::{HashMap, HashSet, VecDeque};
34+use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque};
35+use std::rc::Rc;
1136
12-use braid_format::{ObjectId, Objects};
37+use braid_format::codec::{Reader, put_id, put_uv};
38+use braid_format::{DecodeError, Kind, ObjectId, Objects};
1339
1440 use crate::access::read_changeset;
15-use crate::error::Error;
41+use crate::derived::{DerivedIndex, DerivedKey};
42+use crate::error::{Error, store_error};
43+use crate::history::History;
1644
1745 /// Whether `base` is `head` or one of its first-parent ancestors no more than
1846 /// `limit` steps away. Walking stops at the limit, so `false` also means "not
@@ -168,9 +196,400 @@
168196 }
169197 }
170198
199+/// The derived function of commit graph data.
200+const GRAPH: &str = "graph";
201+
202+/// The version of its encoding.
203+const GRAPH_VERSION: u64 = 1;
204+
205+/// What the commit graph records of a changeset: the value of the derived
206+/// function `graph`, version 1 (section 8 of the format spec).
207+#[derive(Clone, Debug, PartialEq, Eq)]
208+pub struct GraphNode {
209+ /// The parents, in order.
210+ pub parents: Vec<ObjectId>,
211+ /// 1 without parents, otherwise 1 more than the largest generation of
212+ /// the parents.
213+ pub generation: u64,
214+ /// The number of first parents down to a changeset without parents.
215+ pub height: u64,
216+ /// The first-parent ancestor at height [`skip_height`]`(height)`; `None`
217+ /// exactly when the height is 0.
218+ pub skip: Option<ObjectId>,
219+}
220+
221+impl GraphNode {
222+ fn encode(&self) -> Vec<u8> {
223+ let mut out = Vec::with_capacity(16 + 32 * (self.parents.len() + 1));
224+ put_uv(&mut out, self.parents.len() as u64);
225+ for parent in &self.parents {
226+ put_id(&mut out, parent);
227+ }
228+ put_uv(&mut out, self.generation);
229+ put_uv(&mut out, self.height);
230+ if let Some(skip) = &self.skip {
231+ put_id(&mut out, skip);
232+ }
233+ out
234+ }
235+
236+ /// Decodes a value, checking what it can without other records.
237+ fn decode(value: &[u8]) -> Option<GraphNode> {
238+ let read = || -> Result<GraphNode, DecodeError> {
239+ let mut reader = Reader::new(value);
240+ let count = reader.count(ObjectId::LEN)?;
241+ let mut parents = Vec::with_capacity(count);
242+ for _ in 0..count {
243+ parents.push(reader.id()?);
244+ }
245+ let generation = reader.uv()?;
246+ let height = reader.uv()?;
247+ let skip = if height == 0 {
248+ None
249+ } else {
250+ Some(reader.id()?)
251+ };
252+ reader.finish()?;
253+ Ok(GraphNode {
254+ parents,
255+ generation,
256+ height,
257+ skip,
258+ })
259+ };
260+ let node = read().ok()?;
261+ let consistent = if node.parents.is_empty() {
262+ node.generation == 1 && node.height == 0
263+ } else {
264+ node.generation >= 2 && node.height >= 1
265+ };
266+ consistent.then_some(node)
267+ }
268+}
269+
270+/// The height the skip pointer of a changeset at `height` points to, by the
271+/// rule of Bitcoin's block index: 0 below 2; for an even height, the height
272+/// with its lowest set bit cleared; for an odd one, 1 more than `height - 1`
273+/// with its two lowest set bits cleared. Always below `height` when `height`
274+/// is not 0.
275+pub fn skip_height(height: u64) -> u64 {
276+ fn clear_lowest_bit(n: u64) -> u64 {
277+ n & n.wrapping_sub(1)
278+ }
279+ if height < 2 {
280+ 0
281+ } else if height & 1 == 1 {
282+ clear_lowest_bit(clear_lowest_bit(height - 1)) + 1
283+ } else {
284+ clear_lowest_bit(height)
285+ }
286+}
287+
288+/// Flags of the walk that finds merge bases.
289+const FROM_A: u8 = 1;
290+const FROM_B: u8 = 2;
291+const FROM_BOTH: u8 = FROM_A | FROM_B;
292+/// Below a merge base already found, so not a best one.
293+const STALE: u8 = 4;
294+
295+impl<O: Objects, I: DerivedIndex> History<'_, O, I> {
296+ /// The commit graph data of a changeset, computed for it and for its
297+ /// ancestors when missing.
298+ pub fn graph(&mut self, id: ObjectId) -> Result<GraphNode, Error> {
299+ let node = self.node(id)?;
300+ Ok(GraphNode::clone(&node))
301+ }
302+
303+ /// The generation of a changeset (see [`GraphNode::generation`]).
304+ pub fn generation(&mut self, id: ObjectId) -> Result<u64, Error> {
305+ Ok(self.node(id)?.generation)
306+ }
307+
308+ /// The changeset `steps` first parents below `id` (`id` itself for 0), or
309+ /// `None` when the chain is shorter. Logarithmic in `steps`.
310+ pub fn first_parent_ancestor(
311+ &mut self,
312+ id: ObjectId,
313+ steps: u64,
314+ ) -> Result<Option<ObjectId>, Error> {
315+ let height = self.node(id)?.height;
316+ if steps > height {
317+ return Ok(None);
318+ }
319+ Ok(Some(self.ancestor_at(id, height - steps)?))
320+ }
321+
322+ /// Whether `base` is `head` or one of its first-parent ancestors no more
323+ /// than `limit` steps away, as [`first_parent_chain_contains`] says, with
324+ /// skip pointers: logarithmic in the distance.
325+ pub fn first_parent_chain_contains(
326+ &mut self,
327+ head: ObjectId,
328+ base: ObjectId,
329+ limit: usize,
330+ ) -> Result<bool, Error> {
331+ if head == base {
332+ return Ok(true);
333+ }
334+ if limit == 0 {
335+ return Ok(false);
336+ }
337+ let top = self.node(head)?;
338+ if !self.is_changeset(base)? {
339+ return Ok(false);
340+ }
341+ let target = self.node(base)?;
342+ if target.height >= top.height || top.height - target.height > limit as u64 {
343+ return Ok(false);
344+ }
345+ Ok(self.ancestor_at(head, target.height)? == base)
346+ }
347+
348+ /// Whether `ancestor` is `descendant` or one of its ancestors, as
349+ /// [`is_ancestor`] says. A first-parent ancestor is found through skip
350+ /// pointers; otherwise the walk back from `descendant` never goes below
351+ /// the generation of `ancestor`.
352+ pub fn is_ancestor(&mut self, ancestor: ObjectId, descendant: ObjectId) -> Result<bool, Error> {
353+ self.all_ancestors(&[ancestor], descendant)
354+ }
355+
356+ /// Whether each of `ids` is `head` or one of its ancestors: the answer of
357+ /// [`is_ancestor`] for all of them at once. The walk back from `head`
358+ /// never goes below the smallest generation among them.
359+ pub fn all_ancestors(&mut self, ids: &[ObjectId], head: ObjectId) -> Result<bool, Error> {
360+ let mut wanted: HashSet<ObjectId> = ids.iter().copied().collect();
361+ wanted.remove(&head);
362+ if wanted.is_empty() {
363+ return Ok(true);
364+ }
365+ let top = self.node(head)?;
366+ let mut floor = u64::MAX;
367+ let mut off_chain = HashSet::new();
368+ for id in wanted {
369+ if !self.is_changeset(id)? {
370+ return Ok(false);
371+ }
372+ let node = self.node(id)?;
373+ if node.generation >= top.generation {
374+ return Ok(false);
375+ }
376+ if node.height < top.height && self.ancestor_at(head, node.height)? == id {
377+ continue;
378+ }
379+ floor = floor.min(node.generation);
380+ off_chain.insert(id);
381+ }
382+ if off_chain.is_empty() {
383+ return Ok(true);
384+ }
385+ let mut seen = HashSet::from([head]);
386+ let mut stack = vec![head];
387+ while let Some(id) = stack.pop() {
388+ let node = self.node(id)?;
389+ for &parent in &node.parents {
390+ if !seen.insert(parent) {
391+ continue;
392+ }
393+ if off_chain.remove(&parent) && off_chain.is_empty() {
394+ return Ok(true);
395+ }
396+ if self.node(parent)?.generation > floor {
397+ stack.push(parent);
398+ }
399+ }
400+ }
401+ Ok(false)
402+ }
403+
404+ /// The best common ancestors of `a` and `b`, sorted by id, as
405+ /// [`merge_bases`] says.
406+ ///
407+ /// When one is a first-parent ancestor of the other, skip pointers find
408+ /// it. Otherwise the walk goes down from both in order of generation,
409+ /// marking what it reaches from each side; a changeset reached from both
410+ /// is a best common ancestor unless it is below one already found, and
411+ /// the walk stops when everything left to visit is below one. It visits
412+ /// the changesets between `a`, `b` and their merge bases, never all of
413+ /// history unless the histories are unrelated.
414+ pub fn merge_bases(&mut self, a: ObjectId, b: ObjectId) -> Result<Vec<ObjectId>, Error> {
415+ let (top_a, top_b) = (self.node(a)?, self.node(b)?);
416+ if a == b {
417+ return Ok(vec![a]);
418+ }
419+ if top_b.height < top_a.height && self.ancestor_at(a, top_b.height)? == b {
420+ return Ok(vec![b]);
421+ }
422+ if top_a.height < top_b.height && self.ancestor_at(b, top_a.height)? == a {
423+ return Ok(vec![a]);
424+ }
425+
426+ let mut flags: HashMap<ObjectId, u8> = HashMap::from([(a, FROM_A), (b, FROM_B)]);
427+ let mut queue = BinaryHeap::from([(top_a.generation, a), (top_b.generation, b)]);
428+ // Queued changesets, and those of them that are not stale.
429+ let mut queued = HashSet::from([a, b]);
430+ let mut live = HashSet::from([a, b]);
431+ let mut bases = Vec::new();
432+ while !live.is_empty() {
433+ let Some((_, id)) = queue.pop() else {
434+ break;
435+ };
436+ queued.remove(&id);
437+ live.remove(&id);
438+ let mut mark = flags[&id];
439+ if mark & (FROM_BOTH | STALE) == FROM_BOTH {
440+ bases.push(id);
441+ mark |= STALE;
442+ flags.insert(id, mark);
443+ }
444+ let node = self.node(id)?;
445+ for &parent in &node.parents {
446+ let old = flags.get(&parent).copied().unwrap_or(0);
447+ let new = old | mark;
448+ if new == old {
449+ continue;
450+ }
451+ flags.insert(parent, new);
452+ if queued.insert(parent) {
453+ let generation = self.node(parent)?.generation;
454+ queue.push((generation, parent));
455+ }
456+ if new & STALE == 0 {
457+ live.insert(parent);
458+ } else {
459+ live.remove(&parent);
460+ }
461+ }
462+ }
463+ bases.sort();
464+ Ok(bases)
465+ }
466+
467+ /// One best common ancestor of `a` and `b`, the one with the smallest id,
468+ /// as [`merge_base`] says.
469+ pub fn merge_base(&mut self, a: ObjectId, b: ObjectId) -> Result<Option<ObjectId>, Error> {
470+ Ok(self.merge_bases(a, b)?.into_iter().next())
471+ }
472+
473+ /// Whether `id` is stored as a changeset.
474+ fn is_changeset(&mut self, id: ObjectId) -> Result<bool, Error> {
475+ if self.nodes.contains_key(&id) {
476+ return Ok(true);
477+ }
478+ Ok(matches!(
479+ self.objects.stat(&id).map_err(store_error)?,
480+ Some((Kind::Changeset, _))
481+ ))
482+ }
483+
484+ /// The first-parent ancestor of `id` at `height`, which must not be above
485+ /// the height of `id`, through skip pointers where they get closer.
486+ fn ancestor_at(&mut self, id: ObjectId, height: u64) -> Result<ObjectId, Error> {
487+ let mut at = id;
488+ let mut node = self.node(id)?;
489+ while node.height > height {
490+ let current = node.height;
491+ let skip = skip_height(current);
492+ let skip_below = skip_height(current - 1);
493+ // Take the skip pointer when it lands on the target, or above it
494+ // where the parent's own pointer would not land closer.
495+ let jump = skip == height
496+ || (skip > height && !(skip_below + 2 < skip && skip_below >= height));
497+ let (next, expected) = match (node.skip, node.parents.first()) {
498+ (Some(skip_to), _) if jump => (skip_to, skip),
499+ (_, Some(parent)) => (*parent, current - 1),
500+ (_, None) => return Err(Error::DerivedData { id: at }),
501+ };
502+ at = next;
503+ node = self.node(at)?;
504+ if node.height != expected {
505+ return Err(Error::DerivedData { id: at });
506+ }
507+ }
508+ Ok(at)
509+ }
510+
511+ /// The commit graph data of `id`, from memory, from its record, or
512+ /// computed with that of every ancestor that lacks it.
513+ pub(crate) fn node(&mut self, id: ObjectId) -> Result<Rc<GraphNode>, Error> {
514+ if let Some(node) = self.nodes.get(&id) {
515+ return Ok(Rc::clone(node));
516+ }
517+ if let Some(node) = self.load_node(id)? {
518+ return Ok(node);
519+ }
520+ // Depth first, parents before children, with an explicit stack: a
521+ // history can be far longer than a thread's stack is deep.
522+ let mut parents_of: HashMap<ObjectId, Vec<ObjectId>> = HashMap::new();
523+ let mut stack = vec![(id, false)];
524+ while let Some((top, expanded)) = stack.pop() {
525+ if self.nodes.contains_key(&top) {
526+ continue;
527+ }
528+ if expanded {
529+ let parents = parents_of.remove(&top).unwrap_or_default();
530+ self.compute_node(top, parents)?;
531+ continue;
532+ }
533+ if top != id && self.load_node(top)?.is_some() {
534+ continue;
535+ }
536+ let parents = read_changeset(self.objects, top)?.parents;
537+ stack.push((top, true));
538+ for parent in &parents {
539+ if !self.nodes.contains_key(parent) {
540+ stack.push((*parent, false));
541+ }
542+ }
543+ parents_of.insert(top, parents);
544+ }
545+ self.nodes
546+ .get(&id)
547+ .cloned()
548+ .ok_or(Error::DerivedData { id })
549+ }
550+
551+ /// The commit graph data of `id` from its record, remembered.
552+ fn load_node(&mut self, id: ObjectId) -> Result<Option<Rc<GraphNode>>, Error> {
553+ let key = DerivedKey::new(GRAPH, GRAPH_VERSION, &[id], b"");
554+ let Some(node) = self.load(&key, GraphNode::decode)? else {
555+ return Ok(None);
556+ };
557+ let node = Rc::new(node);
558+ self.nodes.insert(id, Rc::clone(&node));
559+ Ok(Some(node))
560+ }
561+
562+ /// Computes and stores the commit graph data of `id`, whose parents have
563+ /// theirs.
564+ fn compute_node(&mut self, id: ObjectId, parents: Vec<ObjectId>) -> Result<(), Error> {
565+ let mut generation = 0;
566+ for parent in &parents {
567+ generation = generation.max(self.node(*parent)?.generation);
568+ }
569+ let (height, skip) = match parents.first() {
570+ None => (0, None),
571+ Some(first) => {
572+ let height = self.node(*first)?.height + 1;
573+ (height, Some(self.ancestor_at(*first, skip_height(height))?))
574+ }
575+ };
576+ let node = GraphNode {
577+ parents,
578+ generation: generation + 1,
579+ height,
580+ skip,
581+ };
582+ let key = DerivedKey::new(GRAPH, GRAPH_VERSION, &[id], b"");
583+ self.save(key, &node.encode())?;
584+ self.nodes.insert(id, Rc::new(node));
585+ Ok(())
586+ }
587+}
588+
171589 #[cfg(test)]
172590 mod tests {
173591 use super::*;
592+ use crate::derived::MemoryIndex;
174593 use crate::testing::Repo;
175594
176595 /// A changeset with these parents, distinguished by a file named `name`.
@@ -269,5 +688,87 @@
269688 let one = node(&repo, &[], "one");
270689 let two = node(&repo, &[], "two");
271690 assert_eq!(merge_base(&repo.objects, one, two).unwrap(), None);
691+ let index = MemoryIndex::new();
692+ let mut history = History::new(&repo.objects, &index);
693+ assert_eq!(history.merge_bases(one, two).unwrap(), []);
694+ assert!(!history.is_ancestor(one, two).unwrap());
695+ }
696+
697+ #[test]
698+ fn graph_data_counts_generations_and_heights() {
699+ let repo = Repo::new();
700+ let root = node(&repo, &[], "root");
701+ let a = node(&repo, &[root], "a");
702+ let b = node(&repo, &[a], "b");
703+ let side = node(&repo, &[root], "side");
704+ let merge = node(&repo, &[side, b], "merge");
705+ let index = MemoryIndex::new();
706+ let mut history = History::new(&repo.objects, &index);
707+ let graph = history.graph(merge).unwrap();
708+ // The merge is one above its highest parent, b, but its first
709+ // parent is the side branch: height 2.
710+ assert_eq!(graph.generation, 4);
711+ assert_eq!(graph.height, 2);
712+ assert_eq!(graph.parents, [side, b]);
713+ assert_eq!(graph.skip, Some(root));
714+ assert_eq!(history.graph(root).unwrap().skip, None);
715+ assert_eq!(history.generation(b).unwrap(), 3);
716+ assert_eq!(history.first_parent_ancestor(merge, 1).unwrap(), Some(side));
717+ assert_eq!(history.first_parent_ancestor(merge, 2).unwrap(), Some(root));
718+ assert_eq!(history.first_parent_ancestor(merge, 3).unwrap(), None);
719+ // One record per changeset, recorded on flush.
720+ assert_eq!(history.computed(), 5);
721+ history.flush().unwrap();
722+ assert_eq!(index.len(), 5);
723+ let decoded = GraphNode::decode(&graph.encode()).unwrap();
724+ assert_eq!(decoded, graph);
725+ // Values that contradict themselves are refused.
726+ let mut bad = graph.clone();
727+ bad.generation = 1;
728+ assert_eq!(GraphNode::decode(&bad.encode()), None);
729+ }
730+
731+ #[test]
732+ fn history_answers_what_the_walks_answer() {
733+ let repo = Repo::new();
734+ let root = node(&repo, &[], "root");
735+ let mid = node(&repo, &[root], "mid");
736+ let a = node(&repo, &[mid], "a");
737+ let d = node(&repo, &[mid], "d");
738+ let b = node(&repo, &[root, d], "b");
739+ let x = node(&repo, &[a], "x");
740+ let y = node(&repo, &[b], "y");
741+ let m1 = node(&repo, &[x, y], "m1");
742+ let m2 = node(&repo, &[y, x], "m2");
743+ let octopus = node(&repo, &[m1, a, d, b], "octopus");
744+ let all = [root, mid, a, d, b, x, y, m1, m2, octopus];
745+ let index = MemoryIndex::new();
746+ let mut history = History::new(&repo.objects, &index);
747+ let objects = &repo.objects;
748+ for p in all {
749+ for q in all {
750+ assert_eq!(
751+ history.merge_bases(p, q).unwrap(),
752+ merge_bases(objects, p, q).unwrap()
753+ );
754+ assert_eq!(
755+ history.is_ancestor(p, q).unwrap(),
756+ is_ancestor(objects, p, q).unwrap()
757+ );
758+ for limit in [0, 1, 2, usize::MAX] {
759+ assert_eq!(
760+ history.first_parent_chain_contains(p, q, limit).unwrap(),
761+ first_parent_chain_contains(objects, p, q, limit).unwrap()
762+ );
763+ }
764+ }
765+ }
766+ let mut expected = vec![x, y];
767+ expected.sort();
768+ assert_eq!(history.merge_bases(m1, m2).unwrap(), expected);
769+ assert_eq!(history.merge_bases(a, b).unwrap(), [mid]);
770+ assert!(history.all_ancestors(&[a, d, root], octopus).unwrap());
771+ assert!(!history.all_ancestors(&[m2, a], octopus).unwrap());
772+ assert!(history.all_ancestors(&[], root).unwrap());
272773 }
273774 }
added crates/engine/src/blame.rs +507 −0
@@ -0,0 +1,507 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Blame: the changeset that last changed each line of a file, along first
5+//! parents.
6+//!
7+//! The content of a file at a changeset `C` is the one the last changeset
8+//! on `C`'s first-parent chain whose change list sets the file gave it. Its
9+//! blame is derived data of that changeset and the path, computed from the
10+//! blame at the previous changeset on the chain that names the path: when
11+//! the path was a file there, a line diff between the two contents carries
12+//! the lines that were kept over with their changesets, and the lines added
13+//! or changed are the new changeset's. A file that a changeset creates,
14+//! where there was nothing, a directory or a gitlink, is all its own:
15+//! renames are not followed.
16+//!
17+//! The line diff is imara-diff's Myers algorithm with its indentation
18+//! heuristic, which is what git's blame uses by default, so the two agree
19+//! line for line with two exceptions. Git follows a file across whole-file
20+//! renames, and braid does not. And when a change has several shortest line
21+//! diffs, the two implementations may pick different ones: they delete and
22+//! insert as many lines, but keep different copies of lines that repeat,
23+//! such as closing braces and blank lines, and blame gives those copies to
24+//! different changesets.
25+//!
26+//! The derived function `blame`, version 1, of a changeset and a path (the
27+//! argument of the key) is:
28+//!
29+//! ```text
30+//! uv k, k × [32] changesets, in the order their first lines come
31+//! uv r, r × (uv changeset index, uv lines) runs of lines, in order
32+//! ```
33+//!
34+//! Runs are not empty, two runs in a row never have the same changeset, and
35+//! every changeset listed has lines. A line ends after a `\n`, and a last
36+//! line without one is a line too, as in three-way merges.
37+
38+use std::collections::HashMap;
39+use std::rc::Rc;
40+
41+use braid_format::codec::{Reader, put_id, put_uv};
42+use braid_format::{ChangeOp, DecodeError, EntryKind, ObjectId, Objects};
43+use imara_diff::sources::byte_lines;
44+use imara_diff::{Algorithm, Diff, InternedInput};
45+
46+use crate::access::{entry_at, read_blob, read_changeset};
47+use crate::bloom::PathHash;
48+use crate::derived::{DerivedIndex, DerivedKey};
49+use crate::error::Error;
50+use crate::history::History;
51+
52+/// The derived function of blame records.
53+const BLAME: &str = "blame";
54+
55+/// The version of its encoding.
56+const BLAME_VERSION: u64 = 1;
57+
58+/// Content this long or longer is not diffed: a new version of it is all new
59+/// lines.
60+const MAX_DIFF_BYTES: usize = i32::MAX as usize;
61+
62+/// Who last changed each line of a file.
63+#[derive(Clone, Debug, PartialEq, Eq)]
64+pub struct Blame {
65+ /// The changeset the file's content comes from: the last one, on the
66+ /// first-parent chain of the changeset blamed, whose change list sets the
67+ /// file.
68+ pub changeset: ObjectId,
69+ /// The file's content.
70+ pub content: Vec<u8>,
71+ /// For each line of the content, in order, the changeset that last
72+ /// changed it.
73+ pub origins: Vec<ObjectId>,
74+}
75+
76+impl Blame {
77+ /// Each line, with its line ending if it has one, and the changeset that
78+ /// last changed it.
79+ pub fn lines(&self) -> impl Iterator<Item = (&[u8], ObjectId)> + '_ {
80+ byte_lines(&self.content).zip(self.origins.iter().copied())
81+ }
82+}
83+
84+impl<O: Objects, I: DerivedIndex> History<'_, O, I> {
85+ /// The blame of `path` at `changeset`: for each line of the file there,
86+ /// the changeset on the first-parent chain that last changed it. `None`
87+ /// when the path holds no file there: nothing, a directory or a gitlink.
88+ /// A symlink's target is blamed as a file.
89+ ///
90+ /// Blame records are computed for the changesets that set the file and
91+ /// lack one, back to the newest that has one or to where the file was
92+ /// created; finding those changesets costs a walk down the chain with
93+ /// changed-path filters.
94+ pub fn blame(&mut self, changeset: ObjectId, path: &[u8]) -> Result<Option<Blame>, Error> {
95+ let root = read_changeset(self.objects, changeset)?.root;
96+ let blob = match entry_at(self.objects, root, path)? {
97+ Some(
98+ EntryKind::File { blob, .. }
99+ | EntryKind::Executable { blob, .. }
100+ | EntryKind::Symlink { blob, .. },
101+ ) => blob,
102+ _ => return Ok(None),
103+ };
104+ let hash = PathHash::of(path);
105+ // The change list of some changeset on the chain must have set the
106+ // file, unless derived data says otherwise.
107+ let last = match self.last_change(Some(changeset), path, hash)? {
108+ Some((last, op)) if file_blob(&op) == Some(blob) => last,
109+ _ => return Err(Error::DerivedData { id: changeset }),
110+ };
111+ let (origins, content) = self.origins(last, blob, path, hash)?;
112+ Ok(Some(Blame {
113+ changeset: last,
114+ content,
115+ origins,
116+ }))
117+ }
118+
119+ /// The origins of the lines of `path` at `last`, which set it to `blob`,
120+ /// and its content.
121+ fn origins(
122+ &mut self,
123+ last: ObjectId,
124+ blob: ObjectId,
125+ path: &[u8],
126+ hash: PathHash,
127+ ) -> Result<(Vec<ObjectId>, Vec<u8>), Error> {
128+ // The changesets that set the file without a blame record, newest
129+ // first, down to one with a record or to the one that created it.
130+ let mut chain: Vec<(ObjectId, ObjectId)> = Vec::new();
131+ let mut base: Option<(Vec<ObjectId>, Vec<u8>)> = None;
132+ let mut current = (last, blob);
133+ loop {
134+ if let Some(runs) = self.load_blame(current.0, path)? {
135+ let content = read_blob(self.objects, current.1)?;
136+ // A record that does not fit the content is ignored, and
137+ // made again.
138+ if runs.lines() == count_lines(&content) {
139+ base = Some((runs.expand(), content));
140+ break;
141+ }
142+ }
143+ chain.push(current);
144+ let parent = self.changed_paths(current.0)?.first_parent;
145+ match self.last_change(parent, path, hash)? {
146+ Some((id, op)) => match file_blob(&op) {
147+ Some(blob) => current = (id, blob),
148+ None => break,
149+ },
150+ None => break,
151+ }
152+ }
153+
154+ let (mut origins, mut content) = match base {
155+ Some((origins, content)) => (origins, Some(content)),
156+ None => (Vec::new(), None),
157+ };
158+ for (id, blob) in chain.into_iter().rev() {
159+ let new = read_blob(self.objects, blob)?;
160+ origins = match &content {
161+ Some(old) => carry(old, &new, &origins, id),
162+ None => vec![id; count_lines(&new)],
163+ };
164+ self.save_blame(id, path, &origins)?;
165+ content = Some(new);
166+ }
167+ // The loop above ran at least once, or the base was found.
168+ Ok((origins, content.unwrap_or_default()))
169+ }
170+
171+ /// The blame record of `path` at `id`, if there is a valid one.
172+ fn load_blame(&mut self, id: ObjectId, path: &[u8]) -> Result<Option<Rc<Runs>>, Error> {
173+ let memo = (id, path.to_vec());
174+ if let Some(runs) = self.blames.get(&memo) {
175+ return Ok(Some(Rc::clone(runs)));
176+ }
177+ let key = DerivedKey::new(BLAME, BLAME_VERSION, &[id], path);
178+ let Some(runs) = self.load(&key, Runs::decode)? else {
179+ return Ok(None);
180+ };
181+ let runs = Rc::new(runs);
182+ self.blames.insert(memo, Rc::clone(&runs));
183+ Ok(Some(runs))
184+ }
185+
186+ /// Stores the blame record of `path` at `id`.
187+ fn save_blame(&mut self, id: ObjectId, path: &[u8], origins: &[ObjectId]) -> Result<(), Error> {
188+ let runs = Runs::of(origins);
189+ let key = DerivedKey::new(BLAME, BLAME_VERSION, &[id], path);
190+ self.save(key, &runs.encode())?;
191+ self.blames.insert((id, path.to_vec()), Rc::new(runs));
192+ Ok(())
193+ }
194+}
195+
196+/// The blob a change sets, for the changes that set a file.
197+fn file_blob(op: &ChangeOp) -> Option<ObjectId> {
198+ match op {
199+ ChangeOp::File { blob, .. }
200+ | ChangeOp::Executable { blob, .. }
201+ | ChangeOp::Symlink { blob, .. } => Some(*blob),
202+ ChangeOp::Gitlink { .. } | ChangeOp::Delete => None,
203+ }
204+}
205+
206+/// The number of lines of `content`.
207+fn count_lines(content: &[u8]) -> usize {
208+ byte_lines(content).count()
209+}
210+
211+/// The origins of the lines of `new`, a later version of `old` whose lines
212+/// come from `old_origins`, when `id` made it: kept lines keep their origin,
213+/// the others are `id`'s.
214+fn carry(old: &[u8], new: &[u8], old_origins: &[ObjectId], id: ObjectId) -> Vec<ObjectId> {
215+ if old.len() >= MAX_DIFF_BYTES || new.len() >= MAX_DIFF_BYTES {
216+ return vec![id; count_lines(new)];
217+ }
218+ let input = InternedInput::new(old, new);
219+ let mut diff = Diff::compute(Algorithm::Myers, &input);
220+ diff.postprocess_lines(&input);
221+ let mut origins = Vec::with_capacity(input.after.len());
222+ // The next line of `old` that is not in a hunk yet.
223+ let mut kept = 0;
224+ for hunk in diff.hunks() {
225+ let start = hunk.before.start as usize;
226+ origins.extend_from_slice(&old_origins[kept..start]);
227+ origins.extend(std::iter::repeat_n(id, hunk.after.len()));
228+ kept = hunk.before.end as usize;
229+ }
230+ origins.extend_from_slice(&old_origins[kept..]);
231+ debug_assert_eq!(origins.len(), input.after.len());
232+ origins
233+}
234+
235+/// A blame record: the origins of the lines of a file, as runs.
236+#[derive(Clone, Debug, PartialEq, Eq)]
237+pub(crate) struct Runs {
238+ /// The changesets, in the order their first lines come.
239+ changesets: Vec<ObjectId>,
240+ /// Runs of lines: an index into `changesets`, and how many lines.
241+ runs: Vec<(usize, u64)>,
242+}
243+
244+impl Runs {
245+ /// The runs of these origins, line by line.
246+ fn of(origins: &[ObjectId]) -> Runs {
247+ let mut changesets = Vec::new();
248+ let mut index: HashMap<ObjectId, usize> = HashMap::new();
249+ let mut runs: Vec<(usize, u64)> = Vec::new();
250+ for origin in origins {
251+ let at = *index.entry(*origin).or_insert_with(|| {
252+ changesets.push(*origin);
253+ changesets.len() - 1
254+ });
255+ match runs.last_mut() {
256+ Some((last, lines)) if *last == at => *lines += 1,
257+ _ => runs.push((at, 1)),
258+ }
259+ }
260+ Runs { changesets, runs }
261+ }
262+
263+ /// The number of lines.
264+ fn lines(&self) -> usize {
265+ self.runs.iter().map(|(_, lines)| *lines as usize).sum()
266+ }
267+
268+ /// The origin of each line.
269+ fn expand(&self) -> Vec<ObjectId> {
270+ let mut origins = Vec::with_capacity(self.lines());
271+ for (at, lines) in &self.runs {
272+ origins.extend(std::iter::repeat_n(self.changesets[*at], *lines as usize));
273+ }
274+ origins
275+ }
276+
277+ fn encode(&self) -> Vec<u8> {
278+ let mut out = Vec::new();
279+ put_uv(&mut out, self.changesets.len() as u64);
280+ for changeset in &self.changesets {
281+ put_id(&mut out, changeset);
282+ }
283+ put_uv(&mut out, self.runs.len() as u64);
284+ for (at, lines) in &self.runs {
285+ put_uv(&mut out, *at as u64);
286+ put_uv(&mut out, *lines);
287+ }
288+ out
289+ }
290+
291+ /// Decodes a record, accepting only the encoding [`Runs::of`] makes.
292+ fn decode(value: &[u8]) -> Option<Runs> {
293+ let read = || -> Result<Runs, DecodeError> {
294+ let mut reader = Reader::new(value);
295+ let count = reader.count(ObjectId::LEN)?;
296+ let mut changesets = Vec::with_capacity(count);
297+ for _ in 0..count {
298+ changesets.push(reader.id()?);
299+ }
300+ let run_count = reader.count(2)?;
301+ let mut runs = Vec::with_capacity(run_count);
302+ for _ in 0..run_count {
303+ let at = reader.position();
304+ let index = usize::try_from(reader.uv()?).ok();
305+ let lines = reader.uv()?;
306+ let invalid = DecodeError::Invalid { at, what: "run" };
307+ let Some(index) = index.filter(|index| *index < count) else {
308+ return Err(invalid);
309+ };
310+ // Changesets come in the order of their first runs, and two
311+ // runs in a row have different changesets.
312+ let seen = runs.iter().map(|(i, _)| i + 1).max().unwrap_or(0);
313+ let repeats = runs.last().is_some_and(|(last, _)| *last == index);
314+ if lines == 0 || index > seen || repeats {
315+ return Err(invalid);
316+ }
317+ runs.push((index, lines));
318+ }
319+ reader.finish()?;
320+ let used = runs.iter().map(|(i, _)| i + 1).max().unwrap_or(0);
321+ if used != count {
322+ return Err(DecodeError::Invalid {
323+ at: 0,
324+ what: "unused changeset",
325+ });
326+ }
327+ Ok(Runs { changesets, runs })
328+ };
329+ read().ok()
330+ }
331+}
332+
333+#[cfg(test)]
334+mod tests {
335+ use super::*;
336+ use crate::derived::MemoryIndex;
337+ use crate::testing::{Repo, delete, gitlink};
338+ use braid_format::Kind;
339+
340+ fn id(n: u8) -> ObjectId {
341+ ObjectId::hash(Kind::Changeset, &[n])
342+ }
343+
344+ #[test]
345+ fn runs_round_trip_and_are_canonical() {
346+ let origins = [id(1), id(1), id(2), id(1), id(3), id(3)];
347+ let runs = Runs::of(&origins);
348+ assert_eq!(runs.changesets, [id(1), id(2), id(3)]);
349+ assert_eq!(runs.runs, [(0, 2), (1, 1), (0, 1), (2, 2)]);
350+ assert_eq!(runs.lines(), 6);
351+ assert_eq!(runs.expand(), origins);
352+ assert_eq!(Runs::decode(&runs.encode()), Some(runs.clone()));
353+ assert_eq!(Runs::of(&[]).encode(), [0, 0]);
354+ assert_eq!(Runs::decode(&[0, 0]), Some(Runs::of(&[])));
355+
356+ let encode = |changesets: &[ObjectId], runs: &[(u64, u64)]| {
357+ let mut out = Vec::new();
358+ put_uv(&mut out, changesets.len() as u64);
359+ for changeset in changesets {
360+ put_id(&mut out, changeset);
361+ }
362+ put_uv(&mut out, runs.len() as u64);
363+ for (at, lines) in runs {
364+ put_uv(&mut out, *at);
365+ put_uv(&mut out, *lines);
366+ }
367+ out
368+ };
369+ assert!(Runs::decode(&encode(&[id(1), id(2)], &[(0, 1), (1, 2)])).is_some());
370+ for (changesets, runs) in [
371+ // An empty run, two runs in a row from one changeset, an index
372+ // out of range, changesets out of order, one never used.
373+ (&[id(1)][..], &[(0, 0)][..]),
374+ (&[id(1)], &[(0, 1), (0, 1)]),
375+ (&[id(1)], &[(1, 1)]),
376+ (&[id(1), id(2)], &[(1, 1), (0, 1)]),
377+ (&[id(1), id(2)], &[(0, 1)]),
378+ ] {
379+ assert_eq!(Runs::decode(&encode(changesets, runs)), None, "{runs:?}");
380+ }
381+ }
382+
383+ #[test]
384+ fn kept_lines_keep_their_origin() {
385+ let old = b"a\nb\nc\nd\n";
386+ let new = b"a\nB\nc\nd\ne\n";
387+ let origins = [id(1), id(2), id(3), id(4)];
388+ assert_eq!(
389+ carry(old, new, &origins, id(9)),
390+ [id(1), id(9), id(3), id(4), id(9)]
391+ );
392+ assert_eq!(carry(b"", b"x\ny", &[], id(9)), [id(9), id(9)]);
393+ assert_eq!(carry(b"x\n", b"", &[id(1)], id(9)), []);
394+ // A last line that gains its newline is a changed line.
395+ assert_eq!(
396+ carry(b"a\nb", b"a\nb\n", &[id(1), id(2)], id(9)),
397+ [id(1), id(9)]
398+ );
399+ }
400+
401+ fn blame<O: Objects, I: DerivedIndex>(
402+ history: &mut History<'_, O, I>,
403+ at: ObjectId,
404+ path: &str,
405+ ) -> Vec<(String, ObjectId)> {
406+ let blame = history.blame(at, path.as_bytes()).unwrap().unwrap();
407+ blame
408+ .lines()
409+ .map(|(line, origin)| (String::from_utf8(line.to_vec()).unwrap(), origin))
410+ .collect()
411+ }
412+
413+ fn origins<O: Objects, I: DerivedIndex>(
414+ history: &mut History<'_, O, I>,
415+ at: ObjectId,
416+ ) -> Vec<ObjectId> {
417+ history.blame(at, b"f").unwrap().unwrap().origins
418+ }
419+
420+ #[test]
421+ fn lines_go_to_the_changeset_that_last_changed_them() {
422+ let repo = Repo::new();
423+ let one = repo.commit(&[], vec![repo.set("f", "a\nb\nc\n"), repo.set("g", "1\n")]);
424+ let two = repo.commit(&[one], vec![repo.set("f", "a\nB\nc\n")]);
425+ let other = repo.commit(&[two], vec![repo.set("g", "2\n")]);
426+ // A side branch adds a line; the merge brings it in, so the line is
427+ // the merge's along first parents.
428+ let side = repo.commit(&[two], vec![repo.set("f", "a\nB\nc\nside\n")]);
429+ let merge = repo.commit(&[other, side], vec![repo.set("f", "a\nB\nc\nside\n")]);
430+ let exec = repo.commit(&[merge], vec![repo.exec("f", "a\nB\nc\nside\n")]);
431+
432+ let index = MemoryIndex::new();
433+ let mut history = History::new(&repo.objects, &index);
434+ let line = |text: &str, origin| (text.to_owned(), origin);
435+ assert_eq!(
436+ blame(&mut history, exec, "f"),
437+ [
438+ line("a\n", one),
439+ line("B\n", two),
440+ line("c\n", one),
441+ line("side\n", merge)
442+ ]
443+ );
444+ // Blamed at a changeset that did not touch the file.
445+ assert_eq!(
446+ blame(&mut history, other, "f"),
447+ [line("a\n", one), line("B\n", two), line("c\n", one)]
448+ );
449+ assert_eq!(blame(&mut history, other, "g"), [line("2\n", other)]);
450+ let whole = history.blame(exec, b"f").unwrap().unwrap();
451+ assert_eq!(whole.changeset, exec);
452+ assert_eq!(whole.content, b"a\nB\nc\nside\n");
453+ // Records for the changesets that set f, once each.
454+ let computed = history.computed();
455+ history.blame(exec, b"f").unwrap();
456+ assert_eq!(history.computed(), computed);
457+
458+ // Nothing to blame: a missing path, a directory.
459+ assert_eq!(history.blame(exec, b"nothing").unwrap(), None);
460+ let dir = repo.commit(&[exec], vec![repo.set("d/x", "1\n")]);
461+ assert_eq!(history.blame(dir, b"d").unwrap(), None);
462+ }
463+
464+ #[test]
465+ fn a_file_created_again_starts_over() {
466+ let repo = Repo::new();
467+ let one = repo.commit(&[], vec![repo.set("f", "a\nb\n")]);
468+ let gone = repo.commit(&[one], vec![delete("f")]);
469+ let back = repo.commit(&[gone], vec![repo.set("f", "a\nb\nc\n")]);
470+ let link = repo.commit(&[back], vec![gitlink("f", 7)]);
471+ let file = repo.commit(&[link], vec![repo.set("f", "a\nb\nc\n")]);
472+ let index = MemoryIndex::new();
473+ let mut history = History::new(&repo.objects, &index);
474+ assert_eq!(origins(&mut history, back), [back, back, back]);
475+ assert_eq!(origins(&mut history, file), [file, file, file]);
476+ assert_eq!(history.blame(link, b"f").unwrap(), None);
477+ assert_eq!(history.blame(gone, b"f").unwrap(), None);
478+ }
479+
480+ #[test]
481+ fn records_made_in_any_order_are_the_same() {
482+ let repo = Repo::new();
483+ let mut at = repo.commit(&[], vec![repo.set("f", "1\n2\n3\n")]);
484+ let mut chain = vec![at];
485+ for (i, content) in ["1\n2\n3\n4\n", "0\n1\n3\n4\n", "0\n1\n3\n4\n5\n", "x\n"]
486+ .iter()
487+ .enumerate()
488+ {
489+ let other = repo.set(&format!("other{i}"), "x");
490+ at = repo.commit(&[at], vec![repo.set("f", content), other]);
491+ chain.push(at);
492+ }
493+ let forward = MemoryIndex::new();
494+ let mut history = History::new(&repo.objects, &forward);
495+ for at in &chain {
496+ history.blame(*at, b"f").unwrap();
497+ }
498+ history.flush().unwrap();
499+ let backward = MemoryIndex::new();
500+ let mut history = History::new(&repo.objects, &backward);
501+ for at in chain.iter().rev() {
502+ history.blame(*at, b"f").unwrap();
503+ }
504+ history.flush().unwrap();
505+ assert_eq!(forward.entries(), backward.entries());
506+ }
507+}
added crates/engine/src/bloom.rs +289 −0
@@ -0,0 +1,289 @@
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+
21+use std::collections::HashSet;
22+
23+use braid_format::DecodeError;
24+use braid_format::codec::{Reader, put_uv};
25+
26+/// Bits per entry, at least.
27+const BITS_PER_ENTRY: u64 = 10;
28+
29+/// Bits set per entry.
30+const 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.
34+pub(crate) const MAX_ENTRIES: u64 = 1024;
35+
36+/// The key-derivation context of the entry hashes.
37+const 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)]
41+pub(crate) struct PathHash {
42+ a: u64,
43+ b: u64,
44+}
45+
46+impl 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)]
69+pub(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+
86+impl 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.
172+fn filter_bytes(entries: u64) -> usize {
173+ (entries * BITS_PER_ENTRY).div_ceil(8) as usize
174+}
175+
176+#[cfg(test)]
177+mod 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+}
added crates/engine/src/derived.rs +256 −0
@@ -0,0 +1,256 @@
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+
32+use core::convert::Infallible;
33+use core::fmt;
34+use std::collections::HashMap;
35+use std::sync::Mutex;
36+
37+use braid_format::codec::{put_bytes, put_id, put_uv};
38+use 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)]
45+pub struct DerivedKey([u8; 32]);
46+
47+impl 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+
76+impl 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+
82+impl 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.
93+pub 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+
106+impl<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)]
120+pub struct MemoryIndex {
121+ map: Mutex<HashMap<DerivedKey, ObjectId>>,
122+}
123+
124+impl 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+
156+impl 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`.
173+pub(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`.
181+pub(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)]
186+mod 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+}
modified crates/engine/src/error.rs +8 −0
@@ -173,6 +173,14 @@
173173 theirs: ObjectId,
174174 },
175175
176+ /// Derived data about a changeset contradicts the history it was derived
177+ /// from: a record made by a faulty version, or tampered with.
178+ #[error("the derived data of {id} contradicts its history")]
179+ DerivedData {
180+ /// The changeset.
181+ id: ObjectId,
182+ },
183+
176184 /// Two changesets to merge have several best common ancestors, as after
177185 /// criss-cross merges, with different trees: the merge would depend on
178186 /// which one it started from.
added crates/engine/src/history.rs +495 −0
@@ -0,0 +1,495 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! History queries answered with derived data: the history of paths, here,
5+//! ancestry in [`ancestry`](crate::ancestry), and blame in
6+//! [`blame`](crate::blame).
7+//!
8+//! A [`History`] reads objects, finds derived records through a
9+//! [`DerivedIndex`], computes the values that are missing, stores them as
10+//! records and remembers every value it used. It records the new records in
11+//! the index by batches, and at the end when [`History::flush`] is called; a
12+//! value computed and never recorded is only computed again later.
13+//!
14+//! # Changed paths
15+//!
16+//! The derived function `changed-paths`, version 1, of a changeset is its
17+//! first parent and a Bloom filter (see `bloom.rs`) of the paths its change
18+//! list names and of their parent directories:
19+//!
20+//! ```text
21+//! u8 1 if there is a first parent, else 0
22+//! [32] the first parent, if there is one
23+//! uv the number of entries, then the filter's bytes
24+//! ```
25+//!
26+//! It depends on the changeset alone, so the walk down a first-parent chain
27+//! reads one small record per changeset, and reads a change list only when
28+//! the filter says that the changeset may touch the path.
29+
30+use core::fmt;
31+use std::collections::{HashMap, HashSet};
32+use std::rc::Rc;
33+
34+use braid_format::codec::{Reader, put_id};
35+use braid_format::{Change, ChangeOp, DecodeError, Kind, ObjectId, Objects};
36+
37+use crate::access::{read_changes, read_changeset};
38+use crate::ancestry::GraphNode;
39+use crate::blame::Runs;
40+use crate::bloom::{Filter, PathHash};
41+use crate::derived::{DerivedIndex, DerivedKey, encode_record, record_value};
42+use crate::error::{Error, store_error};
43+
44+/// The derived function of changed-path records.
45+const CHANGED_PATHS: &str = "changed-paths";
46+
47+/// The version of its encoding.
48+const CHANGED_PATHS_VERSION: u64 = 1;
49+
50+/// New records are recorded in the index once this many wait.
51+const RECORD_BATCH: usize = 4096;
52+
53+/// History queries over the objects of `O`, with the derived data found
54+/// through `I`, computed when missing.
55+///
56+/// A `History` keeps every derived value it reads or computes in memory, so
57+/// a query never reads the same value twice; drop it to free them. Call
58+/// [`flush`](Self::flush) before dropping it to record the new values in the
59+/// index.
60+pub struct History<'o, O, I> {
61+ pub(crate) objects: &'o O,
62+ index: I,
63+ /// Commit graph data, by changeset.
64+ pub(crate) nodes: HashMap<ObjectId, Rc<GraphNode>>,
65+ /// Changed-path records, by changeset.
66+ paths: HashMap<ObjectId, Rc<ChangedPaths>>,
67+ /// Blame records, by changeset and path.
68+ pub(crate) blames: HashMap<(ObjectId, Vec<u8>), Rc<Runs>>,
69+ /// Records stored and not recorded in the index yet.
70+ pending: Vec<(DerivedKey, ObjectId)>,
71+ /// Records this history computed and stored.
72+ computed: u64,
73+}
74+
75+impl<O, I> fmt::Debug for History<'_, O, I> {
76+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77+ f.debug_struct("History")
78+ .field("nodes", &self.nodes.len())
79+ .field("paths", &self.paths.len())
80+ .field("blames", &self.blames.len())
81+ .field("pending", &self.pending.len())
82+ .field("computed", &self.computed)
83+ .finish_non_exhaustive()
84+ }
85+}
86+
87+/// What [`History::derive`] did.
88+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
89+pub struct DeriveReport {
90+ /// Changesets reachable from the heads.
91+ pub changesets: u64,
92+ /// Records computed and stored; the others were there already.
93+ pub computed: u64,
94+}
95+
96+impl<'o, O: Objects, I: DerivedIndex> History<'o, O, I> {
97+ /// A history over `objects`, finding and recording derived records
98+ /// through `index`.
99+ pub fn new(objects: &'o O, index: I) -> Self {
100+ History {
101+ objects,
102+ index,
103+ nodes: HashMap::new(),
104+ paths: HashMap::new(),
105+ blames: HashMap::new(),
106+ pending: Vec::new(),
107+ computed: 0,
108+ }
109+ }
110+
111+ /// The objects this history reads.
112+ pub fn objects(&self) -> &'o O {
113+ self.objects
114+ }
115+
116+ /// How many derived records this history computed and stored.
117+ pub fn computed(&self) -> u64 {
118+ self.computed
119+ }
120+
121+ /// Records in the index every record stored since the last flush.
122+ pub fn flush(&mut self) -> Result<(), Error> {
123+ if self.pending.is_empty() {
124+ return Ok(());
125+ }
126+ self.index.record(&self.pending).map_err(store_error)?;
127+ self.pending.clear();
128+ Ok(())
129+ }
130+
131+ /// The value of `key`, from its record, if the index knows the record
132+ /// and `decode` accepts its value. Anything else is a miss.
133+ pub(crate) fn load<T>(
134+ &mut self,
135+ key: &DerivedKey,
136+ decode: impl FnOnce(&[u8]) -> Option<T>,
137+ ) -> Result<Option<T>, Error> {
138+ let Some(record) = self.index.find(key).map_err(store_error)? else {
139+ return Ok(None);
140+ };
141+ let payload = match self.objects.get(&record).map_err(store_error)? {
142+ Some((Kind::Derived, payload)) if ObjectId::hash(Kind::Derived, &payload) == record => {
143+ payload
144+ }
145+ _ => return Ok(None),
146+ };
147+ Ok(record_value(key, &payload).and_then(decode))
148+ }
149+
150+ /// Stores `value` as the record of `key`.
151+ pub(crate) fn save(&mut self, key: DerivedKey, value: &[u8]) -> Result<(), Error> {
152+ let record = self
153+ .objects
154+ .put(Kind::Derived, &encode_record(&key, value))
155+ .map_err(store_error)?;
156+ self.pending.push((key, record));
157+ self.computed += 1;
158+ if self.pending.len() >= RECORD_BATCH {
159+ self.flush()?;
160+ }
161+ Ok(())
162+ }
163+
164+ /// The changed-path record of a changeset.
165+ pub(crate) fn changed_paths(&mut self, id: ObjectId) -> Result<Rc<ChangedPaths>, Error> {
166+ if let Some(record) = self.paths.get(&id) {
167+ return Ok(Rc::clone(record));
168+ }
169+ let key = DerivedKey::new(CHANGED_PATHS, CHANGED_PATHS_VERSION, &[id], b"");
170+ let record = match self.load(&key, ChangedPaths::decode)? {
171+ Some(record) => record,
172+ None => {
173+ let changeset = read_changeset(self.objects, id)?;
174+ let changes = read_changes(self.objects, id, &changeset)?;
175+ let record = ChangedPaths {
176+ first_parent: changeset.parents.first().copied(),
177+ filter: Filter::build(changes.iter().map(|change| change.path.as_slice())),
178+ };
179+ self.save(key, &record.encode())?;
180+ record
181+ }
182+ };
183+ let record = Rc::new(record);
184+ self.paths.insert(id, Rc::clone(&record));
185+ Ok(record)
186+ }
187+
188+ /// The changesets on the first-parent chain of `head`, newest first,
189+ /// whose change list touches one of `paths`: changes the path itself or
190+ /// anything below it. At most `limit` of them.
191+ ///
192+ /// A path is given from the repository's root, without a leading or
193+ /// trailing `/`; the empty path matches every changeset that changes
194+ /// something. Like `git log --first-parent -- <path>`, a changeset counts
195+ /// when it differs from its first parent there, and renames are not
196+ /// followed.
197+ ///
198+ /// The walk reads one changed-path record per changeset, and the change
199+ /// list of a changeset only when its filter may hold one of the paths: the
200+ /// cost follows the length of the chain walked, in filter checks, plus the
201+ /// changesets that touch the paths.
202+ pub fn path_log(
203+ &mut self,
204+ head: ObjectId,
205+ paths: &[&[u8]],
206+ limit: usize,
207+ ) -> Result<Vec<ObjectId>, Error> {
208+ let wanted: Vec<(&[u8], PathHash)> = paths
209+ .iter()
210+ .map(|path| (*path, PathHash::of(path)))
211+ .collect();
212+ let mut found = Vec::new();
213+ let mut next = Some(head);
214+ while let Some(id) = next {
215+ if found.len() >= limit {
216+ break;
217+ }
218+ let record = self.changed_paths(id)?;
219+ let maybe = wanted.iter().any(|(path, hash)| {
220+ if path.is_empty() {
221+ !record.filter.is_empty()
222+ } else {
223+ record.filter.may_contain(*hash)
224+ }
225+ });
226+ if maybe {
227+ let changeset = read_changeset(self.objects, id)?;
228+ let changes = read_changes(self.objects, id, &changeset)?;
229+ if wanted.iter().any(|(path, _)| touches(&changes, path)) {
230+ found.push(id);
231+ }
232+ }
233+ next = record.first_parent;
234+ }
235+ Ok(found)
236+ }
237+
238+ /// The first changeset, from `from` down its first-parent chain, whose
239+ /// change list names exactly `path`, with what it does there.
240+ pub(crate) fn last_change(
241+ &mut self,
242+ from: Option<ObjectId>,
243+ path: &[u8],
244+ hash: PathHash,
245+ ) -> Result<Option<(ObjectId, ChangeOp)>, Error> {
246+ let mut next = from;
247+ while let Some(id) = next {
248+ let record = self.changed_paths(id)?;
249+ if record.filter.may_contain(hash) {
250+ let changeset = read_changeset(self.objects, id)?;
251+ let changes = read_changes(self.objects, id, &changeset)?;
252+ if let Ok(at) = changes.binary_search_by(|change| change.path.as_slice().cmp(path))
253+ {
254+ return Ok(Some((id, changes[at].op.clone())));
255+ }
256+ }
257+ next = record.first_parent;
258+ }
259+ Ok(None)
260+ }
261+
262+ /// Computes the derived data of every changeset reachable from `heads`
263+ /// that is missing: commit graph data and changed-path records. Blame
264+ /// records, per file, are computed when asked for. Records everything
265+ /// in the index before returning.
266+ pub fn derive(&mut self, heads: &[ObjectId]) -> Result<DeriveReport, Error> {
267+ let before = self.computed;
268+ let mut seen: HashSet<ObjectId> = HashSet::new();
269+ let mut stack = heads.to_vec();
270+ while let Some(id) = stack.pop() {
271+ if !seen.insert(id) {
272+ continue;
273+ }
274+ let node = self.node(id)?;
275+ self.changed_paths(id)?;
276+ stack.extend(node.parents.iter().filter(|parent| !seen.contains(*parent)));
277+ }
278+ self.flush()?;
279+ Ok(DeriveReport {
280+ changesets: seen.len() as u64,
281+ computed: self.computed - before,
282+ })
283+ }
284+}
285+
286+/// Whether a sorted change list touches `path`: names it, or a path below
287+/// it. The empty path is touched by any change.
288+pub(crate) fn touches(changes: &[Change], path: &[u8]) -> bool {
289+ if path.is_empty() {
290+ return !changes.is_empty();
291+ }
292+ if changes
293+ .binary_search_by(|change| change.path.as_slice().cmp(path))
294+ .is_ok()
295+ {
296+ return true;
297+ }
298+ // Paths below `path` sort together, from `path/` on.
299+ let mut below = path.to_vec();
300+ below.push(b'/');
301+ let at = changes.partition_point(|change| change.path.as_slice() < below.as_slice());
302+ changes
303+ .get(at)
304+ .is_some_and(|change| change.path.starts_with(&below))
305+}
306+
307+/// The changed-path record of a changeset.
308+#[derive(Clone, Debug, PartialEq, Eq)]
309+pub(crate) struct ChangedPaths {
310+ /// The first parent.
311+ pub(crate) first_parent: Option<ObjectId>,
312+ /// The filter of the paths the change list names, and their directories.
313+ pub(crate) filter: Filter,
314+}
315+
316+impl ChangedPaths {
317+ fn encode(&self) -> Vec<u8> {
318+ let mut out = Vec::new();
319+ match &self.first_parent {
320+ Some(parent) => {
321+ out.push(1);
322+ put_id(&mut out, parent);
323+ }
324+ None => out.push(0),
325+ }
326+ self.filter.encode(&mut out);
327+ out
328+ }
329+
330+ fn decode(value: &[u8]) -> Option<ChangedPaths> {
331+ let read = || -> Result<ChangedPaths, DecodeError> {
332+ let mut reader = Reader::new(value);
333+ let at = reader.position();
334+ let first_parent = match reader.u8()? {
335+ 0 => None,
336+ 1 => Some(reader.id()?),
337+ _ => {
338+ return Err(DecodeError::Invalid {
339+ at,
340+ what: "first parent flag",
341+ });
342+ }
343+ };
344+ let filter = Filter::decode(&mut reader)?;
345+ reader.finish()?;
346+ Ok(ChangedPaths {
347+ first_parent,
348+ filter,
349+ })
350+ };
351+ read().ok()
352+ }
353+}
354+
355+#[cfg(test)]
356+mod tests {
357+ use super::*;
358+ use crate::derived::MemoryIndex;
359+ use crate::testing::{Repo, delete};
360+
361+ fn log(repo: &Repo, head: ObjectId, path: &str) -> Vec<ObjectId> {
362+ let index = MemoryIndex::new();
363+ let mut history = History::new(&repo.objects, &index);
364+ history
365+ .path_log(head, &[path.as_bytes()], usize::MAX)
366+ .unwrap()
367+ }
368+
369+ #[test]
370+ fn touching_is_by_path_or_below_it() {
371+ let repo = Repo::new();
372+ let changes = vec![
373+ repo.set("a", "1"),
374+ repo.set("a-b/c", "2"),
375+ repo.set("a.txt", "3"),
376+ repo.set("a/x/y", "4"),
377+ repo.set("b", "5"),
378+ ];
379+ for (path, expected) in [
380+ ("a", true),
381+ ("a/x", true),
382+ ("a/x/y", true),
383+ ("a/y", false),
384+ ("a-b", true),
385+ ("a-", false),
386+ ("b", true),
387+ ("c", false),
388+ ("", true),
389+ ] {
390+ assert_eq!(touches(&changes, path.as_bytes()), expected, "{path}");
391+ }
392+ assert!(!touches(&[], b""));
393+ assert!(!touches(&[repo.set("ab", "1")], b"a"));
394+ }
395+
396+ #[test]
397+ fn records_round_trip() {
398+ let parent = ObjectId::hash(Kind::Changeset, b"p");
399+ for record in [
400+ ChangedPaths {
401+ first_parent: Some(parent),
402+ filter: Filter::build([&b"a/b"[..]]),
403+ },
404+ ChangedPaths {
405+ first_parent: None,
406+ filter: Filter::Empty,
407+ },
408+ ] {
409+ assert_eq!(ChangedPaths::decode(&record.encode()), Some(record));
410+ }
411+ assert_eq!(ChangedPaths::decode(&[2, 0]), None);
412+ assert_eq!(ChangedPaths::decode(&[0, 0, 0]), None);
413+ }
414+
415+ #[test]
416+ fn the_log_of_a_path_follows_first_parents() {
417+ let repo = Repo::new();
418+ let root = repo.commit(&[], vec![repo.set("a/f", "1"), repo.set("b", "1")]);
419+ let edit = repo.commit(&[root], vec![repo.set("a/f", "2")]);
420+ let other = repo.commit(&[edit], vec![repo.set("b", "2")]);
421+ // A side branch changes a/g; the merge brings it to the first
422+ // parent's history, so the merge touches a.
423+ let side = repo.commit(&[root], vec![repo.set("a/g", "1")]);
424+ let merge = repo.commit(&[other, side], vec![repo.set("a/g", "1")]);
425+ let gone = repo.commit(&[merge], vec![delete("a/f")]);
426+ let empty = repo.commit(&[gone], Vec::new());
427+ let back = repo.commit(&[empty], vec![repo.set("a/f", "3")]);
428+
429+ assert_eq!(log(&repo, back, "a/f"), [back, gone, edit, root]);
430+ assert_eq!(log(&repo, back, "a/g"), [merge]);
431+ assert_eq!(log(&repo, back, "a"), [back, gone, merge, edit, root]);
432+ assert_eq!(log(&repo, back, "b"), [other, root]);
433+ assert_eq!(log(&repo, back, "a/f/x"), []);
434+ assert_eq!(log(&repo, back, "c"), []);
435+ assert_eq!(log(&repo, back, ""), [back, gone, merge, other, edit, root]);
436+ // The side branch is not on the first-parent chain.
437+ assert_eq!(log(&repo, side, "a/g"), [side]);
438+
439+ let index = MemoryIndex::new();
440+ let mut history = History::new(&repo.objects, &index);
441+ assert_eq!(
442+ history.path_log(back, &[b"b", b"a/g"], usize::MAX).unwrap(),
443+ [merge, other, root]
444+ );
445+ assert_eq!(history.path_log(back, &[b"a"], 2).unwrap(), [back, gone]);
446+ assert_eq!(history.path_log(back, &[b"a"], 0).unwrap(), []);
447+ assert_eq!(
448+ history
449+ .last_change(Some(back), b"a/f", PathHash::of(b"a/f"))
450+ .unwrap()
451+ .map(|(id, _)| id),
452+ Some(back)
453+ );
454+ assert_eq!(
455+ history
456+ .last_change(Some(empty), b"a/f", PathHash::of(b"a/f"))
457+ .unwrap(),
458+ Some((gone, ChangeOp::Delete))
459+ );
460+ }
461+
462+ #[test]
463+ fn records_are_stored_once_and_reused() {
464+ let repo = Repo::new();
465+ let root = repo.commit(&[], vec![repo.set("f", "1")]);
466+ let head = repo.commit(&[root], vec![repo.set("f", "2")]);
467+ let index = MemoryIndex::new();
468+ let mut first = History::new(&repo.objects, &index);
469+ assert_eq!(first.path_log(head, &[b"f"], 10).unwrap(), [head, root]);
470+ assert_eq!(first.computed(), 2);
471+ // Not in the index until flushed.
472+ assert!(index.is_empty());
473+ first.flush().unwrap();
474+ assert_eq!(index.len(), 2);
475+
476+ let mut second = History::new(&repo.objects, &index);
477+ assert_eq!(second.path_log(head, &[b"f"], 10).unwrap(), [head, root]);
478+ assert_eq!(second.computed(), 0);
479+
480+ // A record that is gone, or another value under the key, is computed
481+ // again.
482+ let key = DerivedKey::new(CHANGED_PATHS, CHANGED_PATHS_VERSION, &[head], b"");
483+ let elsewhere = repo.objects.put(Kind::Derived, b"not a record").unwrap();
484+ index
485+ .record(&[(key, ObjectId::hash(Kind::Derived, b"gone"))])
486+ .unwrap();
487+ let mut third = History::new(&repo.objects, &index);
488+ assert_eq!(third.path_log(head, &[b"f"], 10).unwrap(), [head, root]);
489+ assert_eq!(third.computed(), 1);
490+ index.record(&[(key, elsewhere)]).unwrap();
491+ let mut fourth = History::new(&repo.objects, &index);
492+ assert_eq!(fourth.path_log(head, &[b"f"], 10).unwrap(), [head, root]);
493+ assert_eq!(fourth.computed(), 1);
494+ }
495+}
modified crates/engine/src/lib.rs +18 −4
@@ -14,7 +14,11 @@
1414 //! - [`commit`] and [`admit`]: creating a changeset, and the check a store
1515 //! runs before it accepts one.
1616 //! - [`first_parent_chain_contains`], [`is_ancestor`] and [`merge_base`]:
17-//! ancestry.
17+//! ancestry, walking history.
18+//! - [`History`]: the same ancestry queries with generation numbers and skip
19+//! pointers, the history of a path ([`History::path_log`]) with
20+//! changed-path filters, and [`History::blame`], all answered with derived
21+//! data ([`DerivedKey`], [`DerivedIndex`]) computed when missing.
1822 //! - [`merge3`]: three-way merges of file contents.
1923 //! - [`land`]: landing a change on a branch, with conflicts reported as data.
2024 //! - [`merge`]: merging two changesets into a merge changeset, with the same
@@ -40,8 +44,9 @@
4044 //! [`apply`], [`diff`], [`admit`], [`land`] and [`merge`] read only the
4145 //! directories on the changed paths, so their cost follows the size of the
4246 //! change times the depth of the tree, plus the size of each directory they
43-//! touch. Ancestry queries walk history and are proportional to the distance
44-//! they cover.
47+//! touch. The free ancestry functions walk history and are proportional to
48+//! the distance they cover; [`History`] reads derived data instead, so its
49+//! queries cost what they visit once that data exists.
4550 //!
4651 //! [`Objects`]: braid_format::Objects
4752
@@ -50,9 +55,13 @@
5055 mod access;
5156 mod ancestry;
5257 mod apply;
58+mod blame;
59+mod bloom;
5360 mod commit;
61+mod derived;
5462 mod diff;
5563 mod error;
64+mod history;
5665 mod land;
5766 mod merge;
5867 mod path;
@@ -65,11 +74,16 @@
6574 EMPTY_TREE, entry_at, read_blob, read_changes, read_changeset, read_object, read_tree,
6675 stat_object, write_tree,
6776 };
68-pub use ancestry::{first_parent_chain_contains, is_ancestor, merge_base, merge_bases};
77+pub use ancestry::{
78+ GraphNode, first_parent_chain_contains, is_ancestor, merge_base, merge_bases, skip_height,
79+};
6980 pub use apply::apply;
81+pub use blame::Blame;
7082 pub use commit::{admit, commit};
83+pub use derived::{DerivedIndex, DerivedKey, MemoryIndex};
7184 pub use diff::diff;
7285 pub use error::{ApplyProblem, Error, StoreError};
86+pub use history::{DeriveReport, History};
7387 pub use land::{AGENT, Conflict, ConflictKind, LandOutcome, REBASED_FROM, land};
7488 pub use merge::{BINARY_SNIFF_BYTES, ConflictHunk, HunkSide, MergeResult, is_binary, merge3};
7589 pub use path::MAX_PATH_DEPTH;
added crates/engine/tests/history.rs +392 −0
@@ -0,0 +1,392 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Property tests of the history queries on random histories: the ancestry
5+//! of [`History`], with generation numbers and skip pointers, answers what
6+//! the walking functions answer, on histories with octopus merges and
7+//! criss-cross merges; skip pointers find every first-parent ancestor; and
8+//! derived records are the same whatever order they are computed in.
9+
10+use std::collections::BTreeSet;
11+
12+use braid_engine::{
13+ DerivedIndex, History, MemoryIndex, commit, first_parent_chain_contains, is_ancestor,
14+ merge_base, merge_bases, read_changeset, skip_height,
15+};
16+use braid_format::{Change, ChangeOp, Kind, MemoryObjects, ObjectId, Objects, Signature};
17+use proptest::prelude::*;
18+use proptest::sample::Index;
19+
20+/// How the next changesets of a random history are made.
21+#[derive(Clone, Debug)]
22+enum Step {
23+ /// A changeset without parents.
24+ Root,
25+ /// A changeset on one parent.
26+ Child(Index),
27+ /// A merge of two to five parents, which may repeat.
28+ Merge(Vec<Index>),
29+ /// Two merges of the same two parents, in both orders.
30+ CrissCross(Index, Index),
31+}
32+
33+fn step() -> impl Strategy<Value = Step> {
34+ prop_oneof![
35+ 1 => Just(Step::Root),
36+ 6 => any::<Index>().prop_map(Step::Child),
37+ 3 => proptest::collection::vec(any::<Index>(), 2..=5).prop_map(Step::Merge),
38+ 2 => (any::<Index>(), any::<Index>()).prop_map(|(a, b)| Step::CrissCross(a, b)),
39+ ]
40+}
41+
42+fn signature() -> Signature {
43+ Signature {
44+ name: b"Ada".to_vec(),
45+ email: b"ada@example.org".to_vec(),
46+ seconds: 1_700_000_000,
47+ offset_minutes: 0,
48+ }
49+}
50+
51+/// A changeset with these parents that adds a file of its own, and changes
52+/// a shared one every third time.
53+fn node(objects: &MemoryObjects, parents: Vec<ObjectId>, n: usize) -> ObjectId {
54+ let mut changes = Vec::new();
55+ let mut set = |path: String, content: String| {
56+ let blob = objects.put(Kind::Blob, content.as_bytes()).unwrap();
57+ changes.push(Change {
58+ path: path.into_bytes(),
59+ op: ChangeOp::File {
60+ blob,
61+ size: content.len() as u64,
62+ },
63+ });
64+ };
65+ set(format!("n/{n}"), format!("{n}\n"));
66+ if n.is_multiple_of(3) {
67+ set("shared".to_owned(), format!("{n}\n"));
68+ }
69+ commit(
70+ objects,
71+ parents,
72+ changes,
73+ signature(),
74+ signature(),
75+ format!("{n}\n").into_bytes(),
76+ Vec::new(),
77+ )
78+ .unwrap()
79+}
80+
81+/// Builds a history from `steps`; returns every changeset, oldest first.
82+fn build(objects: &MemoryObjects, steps: &[Step]) -> Vec<ObjectId> {
83+ let mut nodes: Vec<ObjectId> = Vec::new();
84+ for step in steps {
85+ let pick = |index: &Index| nodes[index.index(nodes.len())];
86+ let made = match step {
87+ _ if nodes.is_empty() => vec![node(objects, Vec::new(), 0)],
88+ Step::Root => vec![node(objects, Vec::new(), nodes.len())],
89+ Step::Child(parent) => vec![node(objects, vec![pick(parent)], nodes.len())],
90+ Step::Merge(parents) => {
91+ vec![node(
92+ objects,
93+ parents.iter().map(pick).collect(),
94+ nodes.len(),
95+ )]
96+ }
97+ Step::CrissCross(a, b) => {
98+ let (a, b) = (pick(a), pick(b));
99+ let first = node(objects, vec![a, b], nodes.len());
100+ let second = node(objects, vec![b, a], nodes.len() + 1);
101+ vec![first, second]
102+ }
103+ };
104+ nodes.extend(made);
105+ }
106+ nodes
107+}
108+
109+/// `head` and all its ancestors, by walking.
110+fn all_ancestors_of(objects: &MemoryObjects, head: ObjectId) -> BTreeSet<ObjectId> {
111+ let mut seen = BTreeSet::from([head]);
112+ let mut stack = vec![head];
113+ while let Some(id) = stack.pop() {
114+ for parent in read_changeset(objects, id).unwrap().parents {
115+ if seen.insert(parent) {
116+ stack.push(parent);
117+ }
118+ }
119+ }
120+ seen
121+}
122+
123+/// The first-parent ancestor `steps` below `id`, by walking.
124+fn walk_first_parents(objects: &MemoryObjects, id: ObjectId, steps: u64) -> Option<ObjectId> {
125+ let mut at = id;
126+ for _ in 0..steps {
127+ at = *read_changeset(objects, at).unwrap().parents.first()?;
128+ }
129+ Some(at)
130+}
131+
132+/// Every pair of the history's changesets, or about 120 of them spread over
133+/// all of it.
134+fn pairs(nodes: &[ObjectId]) -> Vec<(ObjectId, ObjectId)> {
135+ let every = (nodes.len() * nodes.len()).div_ceil(120);
136+ let mut pairs = Vec::new();
137+ for (i, a) in nodes.iter().enumerate() {
138+ for (j, b) in nodes.iter().enumerate() {
139+ if (i * nodes.len() + j) % every == (i + j) % every {
140+ pairs.push((*a, *b));
141+ }
142+ }
143+ }
144+ pairs
145+}
146+
147+fn check_ancestry(
148+ objects: &MemoryObjects,
149+ history: &mut History<'_, MemoryObjects, &MemoryIndex>,
150+ nodes: &[ObjectId],
151+) -> Result<(), TestCaseError> {
152+ for (a, b) in pairs(nodes) {
153+ prop_assert_eq!(
154+ history.merge_bases(a, b).unwrap(),
155+ merge_bases(objects, a, b).unwrap(),
156+ "merge bases of {} and {}",
157+ a.short(),
158+ b.short()
159+ );
160+ prop_assert_eq!(
161+ history.merge_base(a, b).unwrap(),
162+ merge_base(objects, a, b).unwrap()
163+ );
164+ prop_assert_eq!(
165+ history.is_ancestor(a, b).unwrap(),
166+ is_ancestor(objects, a, b).unwrap(),
167+ "is {} an ancestor of {}",
168+ a.short(),
169+ b.short()
170+ );
171+ for limit in [0, 1, 3, usize::MAX] {
172+ prop_assert_eq!(
173+ history.first_parent_chain_contains(a, b, limit).unwrap(),
174+ first_parent_chain_contains(objects, a, b, limit).unwrap(),
175+ "is {} on the chain of {} within {}",
176+ b.short(),
177+ a.short(),
178+ limit
179+ );
180+ }
181+ }
182+ // Several at once, against every ancestor found by walking.
183+ for (i, head) in nodes.iter().enumerate().step_by(3) {
184+ let ancestors = all_ancestors_of(objects, *head);
185+ for wanted in [
186+ nodes
187+ .iter()
188+ .skip(i % 3)
189+ .step_by(4)
190+ .copied()
191+ .collect::<Vec<_>>(),
192+ nodes.iter().take(i).step_by(5).copied().collect(),
193+ ] {
194+ let expected = wanted.iter().all(|id| ancestors.contains(id));
195+ prop_assert_eq!(history.all_ancestors(&wanted, *head).unwrap(), expected);
196+ }
197+ }
198+ // Ids that are not changesets are nobody's ancestors.
199+ let absent = ObjectId::hash(Kind::Changeset, b"absent");
200+ let head = *nodes.last().unwrap();
201+ prop_assert!(!history.is_ancestor(absent, head).unwrap());
202+ prop_assert!(
203+ !history
204+ .first_parent_chain_contains(head, absent, usize::MAX)
205+ .unwrap()
206+ );
207+ Ok(())
208+}
209+
210+proptest! {
211+ #![proptest_config(ProptestConfig::with_cases(32))]
212+
213+ #[test]
214+ fn ancestry_with_derived_data_equals_the_walks(
215+ steps in proptest::collection::vec(step(), 1..24),
216+ ) {
217+ let objects = MemoryObjects::new();
218+ let nodes = build(&objects, &steps);
219+ let index = MemoryIndex::new();
220+
221+ // With everything computed in this history.
222+ let mut history = History::new(&objects, &index);
223+ check_ancestry(&objects, &mut history, &nodes)?;
224+ history.flush().unwrap();
225+
226+ // With everything read back from records.
227+ let mut again = History::new(&objects, &index);
228+ check_ancestry(&objects, &mut again, &nodes)?;
229+ prop_assert_eq!(again.computed(), 0);
230+ }
231+
232+ #[test]
233+ fn skip_pointers_reach_every_first_parent_ancestor(
234+ steps in proptest::collection::vec(step(), 1..60),
235+ ) {
236+ let objects = MemoryObjects::new();
237+ let nodes = build(&objects, &steps);
238+ let index = MemoryIndex::new();
239+ let mut history = History::new(&objects, &index);
240+ for id in &nodes {
241+ let node = history.graph(*id).unwrap();
242+ for steps in 0..=node.height + 1 {
243+ prop_assert_eq!(
244+ history.first_parent_ancestor(*id, steps).unwrap(),
245+ walk_first_parents(&objects, *id, steps).filter(|_| steps <= node.height)
246+ );
247+ }
248+ if let Some(skip) = node.skip {
249+ prop_assert_eq!(history.graph(skip).unwrap().height, skip_height(node.height));
250+ }
251+ let parents = read_changeset(&objects, *id).unwrap().parents;
252+ let mut generation = 0;
253+ for parent in &parents {
254+ generation = generation.max(history.generation(*parent).unwrap());
255+ }
256+ prop_assert_eq!(node.generation, generation + 1);
257+ prop_assert_eq!(&node.parents, &parents);
258+ }
259+ }
260+
261+ #[test]
262+ fn derived_records_do_not_depend_on_the_order_they_are_made_in(
263+ steps in proptest::collection::vec(step(), 1..30),
264+ order in any::<u64>(),
265+ ) {
266+ let objects = MemoryObjects::new();
267+ let nodes = build(&objects, &steps);
268+
269+ // Oldest first, newest first, and in a shuffled order.
270+ let mut shuffled = nodes.clone();
271+ let mut state = order | 1;
272+ for i in (1..shuffled.len()).rev() {
273+ state ^= state << 13;
274+ state ^= state >> 7;
275+ state ^= state << 17;
276+ shuffled.swap(i, (state % (i as u64 + 1)) as usize);
277+ }
278+ let mut orders = vec![nodes.clone(), nodes.iter().rev().copied().collect(), shuffled];
279+ let mut results = Vec::new();
280+ for order in orders.drain(..) {
281+ let index = MemoryIndex::new();
282+ let mut history = History::new(&objects, &index);
283+ for id in &order {
284+ history.derive(&[*id]).unwrap();
285+ history.blame(*id, b"shared").unwrap();
286+ }
287+ history.flush().unwrap();
288+ results.push(index.entries());
289+ }
290+ prop_assert_eq!(&results[0], &results[1]);
291+ prop_assert_eq!(&results[0], &results[2]);
292+ // Two records per changeset, plus blame records.
293+ let changesets: BTreeSet<ObjectId> = nodes.iter().copied().collect();
294+ prop_assert!(results[0].len() >= 2 * changesets.len());
295+ }
296+}
297+
298+#[test]
299+fn skip_heights_follow_the_rule() {
300+ let expected = [0, 0, 0, 1, 0, 1, 4, 1, 0, 1, 8, 1, 8, 1, 12, 9, 0, 1];
301+ for (height, skip) in expected.iter().enumerate() {
302+ assert_eq!(skip_height(height as u64), *skip, "height {height}");
303+ }
304+ for height in 1..10_000u64 {
305+ assert!(skip_height(height) < height);
306+ }
307+ // Large heights land far away: following pointers takes few steps.
308+ assert_eq!(skip_height(1 << 40), 0);
309+ assert_eq!(skip_height((1 << 40) + 2), 1 << 40);
310+}
311+
312+#[test]
313+fn a_long_chain_is_walked_in_few_records() {
314+ // A chain of 3000 changesets: once its graph data exists, reaching the
315+ // root reads a few dozen records, not thousands.
316+ let objects = MemoryObjects::new();
317+ let edit = |parents: Vec<ObjectId>, n: usize| {
318+ let content = format!("{n}\n");
319+ let blob = objects.put(Kind::Blob, content.as_bytes()).unwrap();
320+ let change = Change {
321+ path: b"f".to_vec(),
322+ op: ChangeOp::File {
323+ blob,
324+ size: content.len() as u64,
325+ },
326+ };
327+ let message = content.clone().into_bytes();
328+ commit(
329+ &objects,
330+ parents,
331+ vec![change],
332+ signature(),
333+ signature(),
334+ message,
335+ Vec::new(),
336+ )
337+ .unwrap()
338+ };
339+ let mut at = edit(Vec::new(), 0);
340+ let root = at;
341+ for n in 1..3000 {
342+ at = edit(vec![at], n);
343+ }
344+ let index = MemoryIndex::new();
345+ let mut history = History::new(&objects, &index);
346+ history.derive(&[at]).unwrap();
347+
348+ let counting = Counting {
349+ inner: &index,
350+ lookups: std::cell::Cell::new(0),
351+ };
352+ let mut fresh = History::new(&objects, &counting);
353+ assert!(fresh.is_ancestor(root, at).unwrap());
354+ assert!(
355+ fresh
356+ .first_parent_chain_contains(at, root, usize::MAX)
357+ .unwrap()
358+ );
359+ assert_eq!(fresh.merge_bases(at, root).unwrap(), [root]);
360+ assert_eq!(fresh.first_parent_ancestor(at, 2999).unwrap(), Some(root));
361+ assert!(
362+ counting.lookups.get() < 100,
363+ "{} lookups",
364+ counting.lookups.get()
365+ );
366+}
367+
368+/// An index that counts lookups.
369+#[derive(Debug)]
370+struct Counting<'i> {
371+ inner: &'i MemoryIndex,
372+ lookups: std::cell::Cell<usize>,
373+}
374+
375+impl DerivedIndex for Counting<'_> {
376+ type Error = std::convert::Infallible;
377+
378+ fn find(
379+ &self,
380+ key: &braid_engine::DerivedKey,
381+ ) -> Result<Option<ObjectId>, std::convert::Infallible> {
382+ self.lookups.set(self.lookups.get() + 1);
383+ self.inner.find(key)
384+ }
385+
386+ fn record(
387+ &self,
388+ entries: &[(braid_engine::DerivedKey, ObjectId)],
389+ ) -> Result<(), std::convert::Infallible> {
390+ self.inner.record(entries)
391+ }
392+}
added crates/repo/src/history.rs +141 −0
@@ -0,0 +1,141 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! History queries over a repository: the engine's [`History`] on the store,
5+//! with the store's derived index.
6+
7+use braid_engine::{DerivedIndex, DerivedKey, History};
8+use braid_format::{Kind, ObjectId, Objects};
9+use braid_store::{DerivedIndexFile, Store};
10+
11+use crate::{Error, Repo};
12+
13+/// The derived index of a repository's store, as the engine uses it.
14+///
15+/// Before it records entries, it makes everything this process wrote to the
16+/// store durable, so that the index never names a record a crash could lose.
17+#[derive(Clone, Copy, Debug)]
18+pub struct StoreIndex<'r> {
19+ store: &'r Store,
20+ file: &'r DerivedIndexFile,
21+}
22+
23+impl DerivedIndex for StoreIndex<'_> {
24+ type Error = braid_store::Error;
25+
26+ fn find(&self, key: &DerivedKey) -> Result<Option<ObjectId>, Self::Error> {
27+ self.file.find(key.as_bytes())
28+ }
29+
30+ fn record(&self, entries: &[(DerivedKey, ObjectId)]) -> Result<(), Self::Error> {
31+ self.store.sync()?;
32+ let entries: Vec<([u8; 32], ObjectId)> = entries
33+ .iter()
34+ .map(|(key, record)| (*key.as_bytes(), *record))
35+ .collect();
36+ self.file.append(&entries)
37+ }
38+}
39+
40+/// History queries over a repository's store.
41+pub type RepoHistory<'r> = History<'r, Store, StoreIndex<'r>>;
42+
43+impl Repo {
44+ /// History queries over the store, finding derived data through the
45+ /// store's derived index and computing what is missing. Call
46+ /// [`History::flush`] when done, so that what was computed is kept.
47+ pub fn history(&self) -> RepoHistory<'_> {
48+ History::new(
49+ &self.store,
50+ StoreIndex {
51+ store: &self.store,
52+ file: &self.derived,
53+ },
54+ )
55+ }
56+
57+ /// The changesets the refs point at, without repeats, sorted.
58+ pub fn ref_changesets(&self) -> Result<Vec<ObjectId>, Error> {
59+ let mut heads = Vec::new();
60+ for (_, id) in self.store.refs()?.iter() {
61+ if matches!(self.store.stat(&id)?, Some((Kind::Changeset, _))) {
62+ heads.push(id);
63+ }
64+ }
65+ heads.sort();
66+ heads.dedup();
67+ Ok(heads)
68+ }
69+}
70+
71+#[cfg(test)]
72+mod tests {
73+ use super::*;
74+ use braid_format::{Change, ChangeOp, Signature};
75+ use braid_store::RefUpdate;
76+
77+ fn signature() -> Signature {
78+ Signature {
79+ name: b"Ada".to_vec(),
80+ email: b"ada@example.org".to_vec(),
81+ seconds: 1_700_000_000,
82+ offset_minutes: 0,
83+ }
84+ }
85+
86+ fn change(repo: &Repo, parents: Vec<ObjectId>, content: &str) -> ObjectId {
87+ let blob = repo.store().put(Kind::Blob, content.as_bytes()).unwrap();
88+ let change = Change {
89+ path: b"f".to_vec(),
90+ op: ChangeOp::File {
91+ blob,
92+ size: content.len() as u64,
93+ },
94+ };
95+ braid_engine::commit(
96+ repo.store(),
97+ parents,
98+ vec![change],
99+ signature(),
100+ signature(),
101+ b"change\n".to_vec(),
102+ Vec::new(),
103+ )
104+ .unwrap()
105+ }
106+
107+ #[test]
108+ fn derived_data_is_kept_between_processes() {
109+ let dir = tempfile::tempdir().unwrap();
110+ let repo = Repo::init(dir.path()).unwrap();
111+ let one = change(&repo, Vec::new(), "1\n");
112+ let two = change(&repo, vec![one], "1\n2\n");
113+ repo.store().sync().unwrap();
114+ repo.store()
115+ .transact("test", "main", |_| {
116+ Ok::<_, std::convert::Infallible>(vec![RefUpdate::new("main", None, Some(two))])
117+ })
118+ .unwrap();
119+ assert_eq!(repo.ref_changesets().unwrap(), [two]);
120+
121+ let mut history = repo.history();
122+ let report = history.derive(&[two]).unwrap();
123+ assert_eq!(report.changesets, 2);
124+ assert_eq!(report.computed, 4);
125+ let blame = history.blame(two, b"f").unwrap().unwrap();
126+ assert_eq!(blame.origins, [one, two]);
127+ history.flush().unwrap();
128+
129+ // Another process finds everything, and the store stays clean.
130+ let again = Repo::open(dir.path()).unwrap();
131+ let mut history = again.history();
132+ assert_eq!(history.derive(&[two]).unwrap().computed, 0);
133+ assert_eq!(
134+ history.blame(two, b"f").unwrap().unwrap().origins,
135+ [one, two]
136+ );
137+ assert_eq!(history.path_log(two, &[b"f"], 10).unwrap(), [two, one]);
138+ assert_eq!(history.computed(), 0);
139+ assert!(again.store().fsck().unwrap().is_clean());
140+ }
141+}
modified crates/repo/src/lib.rs +11 −1
@@ -17,12 +17,17 @@
1717 //! A revision is a ref name, a full object id, or a short id: at least
1818 //! [`MIN_SHORT_ID`] hex digits that start the id of exactly one stored
1919 //! object (see [`Repo::resolve`]).
20+//!
21+//! [`Repo::history`] answers history queries (ancestry, the changes to a
22+//! path, blame) with the derived data the store keeps, computing what is
23+//! missing.
2024
2125 #![forbid(unsafe_code)]
2226
2327 mod clock;
2428 mod config;
2529 mod git;
30+mod history;
2631 mod link;
2732 mod remote;
2833 mod sync;
@@ -33,7 +38,7 @@
3338 use std::path::{Path, PathBuf};
3439
3540 use braid_format::{Kind, ObjectId, Objects};
36-use braid_store::{Options, Store};
41+use braid_store::{DerivedIndexFile, Options, Store};
3742
3843 pub use braid_engine::{Conflict, ConflictHunk, ConflictKind, HunkSide};
3944 pub use clock::{local_now, signature_now};
@@ -42,6 +47,7 @@
4247 GIT_EXPORT_AGENT, GitImport, MAP_REF, REMOTE_PREFIX, braid_ref_for_git, git_ref_for_braid,
4348 remote_ref,
4449 };
50+pub use history::{RepoHistory, StoreIndex};
4551 pub use link::{Location, WORKSPACES_DIR, WorkspaceLink, locate};
4652 pub use remote::Remote;
4753 pub use sync::{MIRRORS_DIR, SyncOptions, SyncOutcome, SyncReport};
@@ -188,6 +194,8 @@
188194 pub struct Repo {
189195 root: PathBuf,
190196 store: Store,
197+ /// The store's derived index, read when first needed.
198+ derived: DerivedIndexFile,
191199 }
192200
193201 impl Repo {
@@ -202,6 +210,7 @@
202210 Ok(Repo {
203211 root: dir.to_path_buf(),
204212 store,
213+ derived: DerivedIndexFile::new(&store_dir),
205214 })
206215 }
207216
@@ -215,6 +224,7 @@
215224 Ok(Repo {
216225 root: dir.to_path_buf(),
217226 store,
227+ derived: DerivedIndexFile::new(&store_dir),
218228 })
219229 }
220230
added crates/repo/tests/history_vs_git.rs +963 −0
@@ -0,0 +1,963 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Differential tests of the history queries, with the git command line as
5+//! the oracle: on fixture repositories built here, on random histories, and
6+//! on the history of this repository, imported into braid and mapped back
7+//! through the git map.
8+//!
9+//! - `log -- <path>` against `git log --first-parent --format=%H -- <path>`,
10+//! for every path a history ever had, its directories, and paths it never
11+//! had;
12+//! - merge bases against `git merge-base --all`;
13+//! - blame against `git blame --first-parent --line-porcelain` (no `-w`,
14+//! `-M` or `-C`), line by line, for every file at several revisions.
15+//!
16+//! Blame differs from git's in two documented ways, and the tests check that
17+//! it differs in no other:
18+//!
19+//! - Git's blame follows a file across whole-file renames (it has no switch
20+//! to turn that off), and braid's does not. A line that git traces to a
21+//! changeset older than the one where the path last appeared on the
22+//! first-parent chain is, for braid, that changeset's, and git must have
23+//! reached it under another file name.
24+//! - When a change has several shortest line diffs, git's diff and braid's
25+//! may keep different copies of lines that repeat, such as closing braces,
26+//! and give them to different changesets. Where the two blames differ for
27+//! that reason, replaying git's own diffs (`git diff -U0`) along the same
28+//! versions must give git's blame line for line, and at every version
29+//! braid's blame must give the changeset that made it as many lines as
30+//! git's diff inserts: both diffs are equally short.
31+
32+use std::collections::{BTreeMap, BTreeSet, HashMap};
33+use std::ops::Range;
34+use std::path::{Path, PathBuf};
35+use std::process::{Command, Stdio};
36+
37+use braid_engine::{read_changes, read_changeset};
38+use braid_format::{EntryKind, ObjectId};
39+use braid_git::{GitMap, GitOid, ImportOptions};
40+use braid_repo::{Repo, RepoHistory};
41+use tempfile::TempDir;
42+
43+/// Variables that would point git at another repository or change what it
44+/// reads.
45+const LEAKY_VARIABLES: [&str; 12] = [
46+ "GIT_DIR",
47+ "GIT_WORK_TREE",
48+ "GIT_INDEX_FILE",
49+ "GIT_OBJECT_DIRECTORY",
50+ "GIT_ALTERNATE_OBJECT_DIRECTORIES",
51+ "GIT_COMMON_DIR",
52+ "GIT_NAMESPACE",
53+ "GIT_CEILING_DIRECTORIES",
54+ "GIT_REPLACE_REF_BASE",
55+ "GIT_NO_REPLACE_OBJECTS",
56+ "GIT_GRAFT_FILE",
57+ "GIT_SHALLOW_FILE",
58+];
59+
60+/// A git command in `dir`, without the user's or the system's
61+/// configuration, with fixed identities, the clock at `seconds`, and
62+/// literal pathspecs.
63+fn git_command(dir: &Path, seconds: i64) -> Command {
64+ let mut command = Command::new("git");
65+ command.current_dir(dir);
66+ for variable in LEAKY_VARIABLES {
67+ command.env_remove(variable);
68+ }
69+ let date = format!("{seconds} +0200");
70+ command
71+ .env("GIT_CONFIG_GLOBAL", "/dev/null")
72+ .env("GIT_CONFIG_NOSYSTEM", "1")
73+ .env("GIT_LITERAL_PATHSPECS", "1")
74+ .env("GIT_AUTHOR_NAME", "Ada Lovelace")
75+ .env("GIT_AUTHOR_EMAIL", "ada@example.org")
76+ .env("GIT_AUTHOR_DATE", &date)
77+ .env("GIT_COMMITTER_NAME", "Charles Babbage")
78+ .env("GIT_COMMITTER_EMAIL", "charles@example.org")
79+ .env("GIT_COMMITTER_DATE", &date)
80+ .args([
81+ "-c",
82+ "init.defaultBranch=main",
83+ "-c",
84+ "commit.gpgSign=false",
85+ "-c",
86+ "core.autocrlf=false",
87+ "-c",
88+ "core.quotePath=false",
89+ "-c",
90+ "gc.auto=0",
91+ ]);
92+ command
93+}
94+
95+/// Runs git and returns its standard output; `None` when it exits with 1,
96+/// as `git merge-base` does when there is no answer.
97+fn run(mut command: Command) -> Option<Vec<u8>> {
98+ let output = command
99+ .stdin(Stdio::null())
100+ .output()
101+ .expect("git must be installed to run these tests");
102+ match output.status.code() {
103+ Some(0) => Some(output.stdout),
104+ Some(1) if output.stderr.is_empty() => None,
105+ _ => panic!(
106+ "{command:?} failed: {}",
107+ String::from_utf8_lossy(&output.stderr)
108+ ),
109+ }
110+}
111+
112+fn text(bytes: Vec<u8>) -> String {
113+ String::from_utf8(bytes).unwrap()
114+}
115+
116+/// A git repository with a work tree, in a temporary directory.
117+struct Fixture {
118+ _dir: TempDir,
119+ work: PathBuf,
120+ clock: i64,
121+}
122+
123+impl Fixture {
124+ fn new() -> Self {
125+ let dir = tempfile::tempdir().unwrap();
126+ let work = dir.path().join("work");
127+ std::fs::create_dir(&work).unwrap();
128+ let mut fixture = Fixture {
129+ _dir: dir,
130+ work,
131+ clock: 1_700_000_000,
132+ };
133+ fixture.git(&["init", "-q"]);
134+ fixture
135+ }
136+
137+ fn git(&mut self, args: &[&str]) -> String {
138+ let mut command = git_command(&self.work, self.clock);
139+ command.args(args);
140+ let out = run(command).unwrap_or_else(|| panic!("git {args:?} exited with 1"));
141+ text(out).trim().to_owned()
142+ }
143+
144+ fn write(&self, path: &str, content: &str) {
145+ let path = self.work.join(path);
146+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
147+ std::fs::write(path, content).unwrap();
148+ }
149+
150+ fn remove(&self, path: &str) {
151+ std::fs::remove_file(self.work.join(path)).unwrap();
152+ }
153+
154+ /// Makes a file executable, in the work tree where the file system can
155+ /// say so, and in the index.
156+ fn make_executable(&mut self, path: &str) {
157+ #[cfg(unix)]
158+ {
159+ use std::os::unix::fs::PermissionsExt;
160+ let file = self.work.join(path);
161+ std::fs::set_permissions(file, std::fs::Permissions::from_mode(0o755)).unwrap();
162+ }
163+ self.git(&["update-index", "--chmod=+x", path]);
164+ }
165+
166+ /// Commits everything in the work tree, even nothing.
167+ fn commit(&mut self, message: &str) -> String {
168+ self.clock += 60;
169+ self.git(&["add", "-A"]);
170+ self.git(&["commit", "-q", "--allow-empty", "-m", message]);
171+ self.git(&["rev-parse", "HEAD"])
172+ }
173+
174+ /// Merges `others` into the current branch with a merge commit.
175+ fn merge(&mut self, others: &[&str], message: &str) -> String {
176+ self.clock += 60;
177+ let mut args = vec!["merge", "-q", "--no-ff", "--no-edit", "-m", message];
178+ args.extend(others);
179+ self.git(&args);
180+ self.git(&["rev-parse", "HEAD"])
181+ }
182+
183+ fn checkout(&mut self, branch: &str) {
184+ self.git(&["checkout", "-q", branch]);
185+ }
186+
187+ fn branch(&mut self, branch: &str) {
188+ self.git(&["checkout", "-q", "-b", branch]);
189+ }
190+}
191+
192+/// Lines `1..=n` of a file, each naming `tag`.
193+fn lines(tag: &str, n: usize) -> String {
194+ (1..=n).map(|i| format!("{tag} {i}\n")).collect()
195+}
196+
197+/// Builds a history with everything blame and path history meet: edits,
198+/// renames, deletions and re-additions, a file that becomes a directory,
199+/// mode changes, an empty commit, merges whose side branches change files,
200+/// an octopus merge, criss-cross merges, and blocks of lines that move and
201+/// repeat.
202+fn build_fixture() -> Fixture {
203+ let mut f = Fixture::new();
204+ f.write("README.md", &lines("readme", 6));
205+ f.write("src/lib.rs", &lines("lib", 12));
206+ f.write("src/util.rs", &lines("util", 10));
207+ f.write("docs/a.txt", &lines("a", 5));
208+ f.write("docs/read me.txt", "spaces\n");
209+ f.write("notes", "a file for now\n");
210+ f.write("caf\u{e9}.txt", &lines("caf\u{e9}", 3));
211+ f.commit("First");
212+
213+ let lib = lines("lib", 12).replace("lib 3\n", "LIB 3\n") + "lib 13\n";
214+ f.write("src/lib.rs", &lib);
215+ f.commit("Edit lib");
216+
217+ f.remove("docs/a.txt");
218+ f.commit("Remove a");
219+
220+ // A side branch edits util and adds a file; main edits the README.
221+ f.branch("side");
222+ f.write(
223+ "src/util.rs",
224+ &lines("util", 10).replace("util 5\n", "side 5\n"),
225+ );
226+ f.write("side.txt", &lines("side", 3));
227+ f.commit("Side work");
228+ f.checkout("main");
229+ f.write("README.md", &(lines("readme", 6) + "readme 7\n"));
230+ f.commit("Readme grows");
231+ f.merge(&["side"], "Merge side");
232+
233+ // A rename with an edit, and a rename of a whole directory.
234+ f.git(&["mv", "src/util.rs", "src/helpers.rs"]);
235+ let helpers = lines("util", 10).replace("util 5\n", "side 5\n") + "helpers 11\n";
236+ f.write("src/helpers.rs", &helpers);
237+ f.commit("Rename util to helpers");
238+ f.git(&["mv", "docs", "manual"]);
239+ f.commit("Rename docs to manual");
240+
241+ // Deleted earlier, added again with some of the old lines.
242+ f.write("docs/a.txt", &(lines("a", 3) + "new a 4\n"));
243+ f.commit("Add a again");
244+
245+ // A file that becomes a directory.
246+ f.remove("notes");
247+ f.write("notes/today.txt", &lines("today", 2));
248+ f.commit("Notes become a directory");
249+
250+ // A mode change only, then an empty commit.
251+ f.make_executable("src/lib.rs");
252+ f.commit("Make lib executable");
253+ f.commit("Nothing");
254+
255+ // An octopus merge of three branches.
256+ for (branch, file) in [
257+ ("o1", "o1.txt"),
258+ ("o2", "src/o2.rs"),
259+ ("o3", "manual/o3.md"),
260+ ] {
261+ f.branch(branch);
262+ f.write(file, &lines(branch, 4));
263+ f.commit(&format!("Work on {branch}"));
264+ f.checkout("main");
265+ }
266+ f.write("src/lib.rs", &(lib.clone() + "lib 14\n"));
267+ f.commit("Lib grows");
268+ f.merge(&["o1", "o2", "o3"], "Octopus");
269+
270+ // Criss-cross: x and y merge each other.
271+ f.branch("x");
272+ f.write("x.txt", &lines("x", 3));
273+ let x1 = f.commit("x 1");
274+ f.checkout("main");
275+ f.branch("y");
276+ f.write("y.txt", &lines("y", 3));
277+ let y1 = f.commit("y 1");
278+ f.merge(&[x1.as_str()], "y merges x");
279+ f.checkout("x");
280+ f.merge(&[y1.as_str()], "x merges y");
281+ f.write("x.txt", &(lines("x", 3) + "x 4\n"));
282+ f.commit("x 2");
283+ f.checkout("y");
284+ f.write("y.txt", &(lines("y", 3) + "y 4\n"));
285+ f.commit("y 2");
286+ f.checkout("main");
287+ f.merge(&["x"], "Merge x");
288+ f.merge(&["y"], "Merge y");
289+
290+ // Blocks that move, lines that repeat, a line that loses its newline.
291+ let blocks = "fn one() {\n 1\n}\n\nfn two() {\n 2\n}\n\nfn three() {\n 3\n}\n";
292+ f.write("src/blocks.rs", blocks);
293+ f.commit("Blocks");
294+ let swapped = "fn three() {\n 3\n}\n\nfn one() {\n 1\n}\n\nfn two() {\n 2\n}\n";
295+ f.write("src/blocks.rs", swapped);
296+ f.commit("Move three up");
297+ f.write(
298+ "src/blocks.rs",
299+ &(swapped.to_owned() + "\nfn one() {\n 1\n}\n"),
300+ );
301+ f.commit("Repeat one");
302+ f.write("README.md", &(lines("readme", 6) + "readme 7"));
303+ f.commit("README without a final newline");
304+ f.write(
305+ "src/lib.rs",
306+ &lib.replace("lib 7\n", "").replace("lib 9\n", "LIB 9\n"),
307+ );
308+ f.commit("Lib shrinks");
309+ f
310+}
311+
312+/// A braid repository with a git repository imported, and the map back.
313+struct Imported {
314+ _dir: TempDir,
315+ repo: Repo,
316+ map: GitMap,
317+}
318+
319+impl Imported {
320+ /// Imports every branch and tag.
321+ fn all(git: &Path) -> Self {
322+ let dir = tempfile::tempdir().unwrap();
323+ let repo = Repo::init(dir.path()).unwrap();
324+ repo.git_import(git, "test").unwrap();
325+ let map = repo.git_map().unwrap();
326+ Imported {
327+ _dir: dir,
328+ repo,
329+ map,
330+ }
331+ }
332+
333+ /// Imports what `HEAD` reaches.
334+ fn head(git: &Path) -> Self {
335+ let dir = tempfile::tempdir().unwrap();
336+ let repo = Repo::init(dir.path()).unwrap();
337+ let mut map = GitMap::new();
338+ braid_git::import(
339+ git,
340+ repo.store(),
341+ &mut map,
342+ &ImportOptions {
343+ refs: vec![b"HEAD".to_vec()],
344+ },
345+ )
346+ .unwrap();
347+ Imported {
348+ _dir: dir,
349+ repo,
350+ map,
351+ }
352+ }
353+
354+ fn changeset(&self, commit: &str) -> ObjectId {
355+ let oid: GitOid = commit
356+ .parse()
357+ .unwrap_or_else(|_| panic!("{commit:?} is not a commit id"));
358+ self.map
359+ .changeset(&oid)
360+ .unwrap_or_else(|| panic!("commit {commit} was not imported"))
361+ }
362+}
363+
364+/// What the comparisons found.
365+#[derive(Debug, Default)]
366+struct Tally {
367+ paths: usize,
368+ merge_bases: usize,
369+ blamed_files: usize,
370+ blamed_lines: usize,
371+ /// Lines git traced across a rename, which braid gives to the changeset
372+ /// where the path appeared.
373+ renamed_lines: usize,
374+ /// Files and lines where git and braid kept different copies of equal
375+ /// lines in equally short diffs.
376+ realigned_files: usize,
377+ realigned_lines: usize,
378+}
379+
380+/// `log -- <path>` for each path, against git.
381+fn compare_path_logs(
382+ git: &Path,
383+ imported: &Imported,
384+ history: &mut RepoHistory<'_>,
385+ revision: &str,
386+ paths: &BTreeSet<String>,
387+ tally: &mut Tally,
388+) {
389+ let head = imported.changeset(&rev_parse(git, revision));
390+ for path in paths {
391+ let mut command = git_command(git, 0);
392+ command.args(["log", "--first-parent", "--format=%H", revision, "--", path]);
393+ let expected: Vec<ObjectId> = text(run(command).unwrap())
394+ .lines()
395+ .map(|commit| imported.changeset(commit))
396+ .collect();
397+ let braid_path = if path == "." { "" } else { path.as_str() };
398+ let found = history
399+ .path_log(head, &[braid_path.as_bytes()], usize::MAX)
400+ .unwrap();
401+ assert_eq!(found, expected, "log {revision} -- {path}");
402+ tally.paths += 1;
403+ }
404+}
405+
406+/// Merge bases of each pair, against git.
407+fn compare_merge_bases(
408+ git: &Path,
409+ imported: &Imported,
410+ history: &mut RepoHistory<'_>,
411+ pairs: &[(String, String)],
412+ tally: &mut Tally,
413+) {
414+ for (a, b) in pairs {
415+ let mut command = git_command(git, 0);
416+ command.args(["merge-base", "--all", a, b]);
417+ let mut expected: Vec<ObjectId> = run(command)
418+ .map(text)
419+ .unwrap_or_default()
420+ .lines()
421+ .map(|commit| imported.changeset(commit))
422+ .collect();
423+ expected.sort();
424+ let (x, y) = (
425+ imported.changeset(&rev_parse(git, a)),
426+ imported.changeset(&rev_parse(git, b)),
427+ );
428+ assert_eq!(
429+ history.merge_bases(x, y).unwrap(),
430+ expected,
431+ "merge bases of {a} and {b}"
432+ );
433+ // The walking version agrees too.
434+ assert_eq!(
435+ braid_engine::merge_bases(imported.repo.store(), x, y).unwrap(),
436+ expected
437+ );
438+ tally.merge_bases += 1;
439+ }
440+}
441+
442+/// One line of `git blame --line-porcelain`: the commit and the file name
443+/// the line has there.
444+struct GitLine {
445+ commit: String,
446+ filename: String,
447+}
448+
449+fn git_blame(git: &Path, revision: &str, path: &str) -> Vec<GitLine> {
450+ let mut command = git_command(git, 0);
451+ command.args([
452+ "blame",
453+ "--first-parent",
454+ "--line-porcelain",
455+ revision,
456+ "--",
457+ path,
458+ ]);
459+ let output = run(command).unwrap();
460+ let mut lines = Vec::new();
461+ let mut commit = None;
462+ let mut filename = None;
463+ for line in output.split(|byte| *byte == b'\n') {
464+ if line.first() == Some(&b'\t') {
465+ lines.push(GitLine {
466+ commit: commit.take().unwrap(),
467+ filename: filename.take().unwrap(),
468+ });
469+ } else if commit.is_none()
470+ && line.len() > 41
471+ && line[40] == b' '
472+ && line[..40].iter().all(u8::is_ascii_hexdigit)
473+ {
474+ commit = Some(text(line[..40].to_vec()));
475+ } else if let Some(name) = line.strip_prefix(b"filename ") {
476+ filename = Some(text(name.to_vec()));
477+ }
478+ }
479+ lines
480+}
481+
482+/// The versions of a file along the first-parent chain of `at`, oldest
483+/// first: each changeset that set it since it last appeared there, where
484+/// its first parent had no file, with the blob it set. Found by reading
485+/// changesets, without derived data.
486+fn versions(repo: &Repo, at: ObjectId, path: &str) -> Vec<(ObjectId, ObjectId)> {
487+ let objects = repo.store();
488+ let file = |kind: &EntryKind| {
489+ matches!(
490+ kind,
491+ EntryKind::File { .. } | EntryKind::Executable { .. } | EntryKind::Symlink { .. }
492+ )
493+ };
494+ let mut found = Vec::new();
495+ let mut current = at;
496+ loop {
497+ let changeset = read_changeset(objects, current).unwrap();
498+ let changes = read_changes(objects, current, &changeset).unwrap();
499+ let parent = changeset.parents.first().copied();
500+ let set = changes
501+ .iter()
502+ .find(|change| change.path == path.as_bytes())
503+ .and_then(|change| change.op.to_entry())
504+ .filter(file);
505+ if let Some(kind) = set {
506+ let (EntryKind::File { blob, .. }
507+ | EntryKind::Executable { blob, .. }
508+ | EntryKind::Symlink { blob, .. }) = kind
509+ else {
510+ unreachable!("only files are kept")
511+ };
512+ found.push((current, blob));
513+ let before = parent.and_then(|parent| {
514+ let root = read_changeset(objects, parent).unwrap().root;
515+ braid_engine::entry_at(objects, root, path.as_bytes()).unwrap()
516+ });
517+ if !before.as_ref().is_some_and(file) {
518+ found.reverse();
519+ return found;
520+ }
521+ }
522+ current = parent.unwrap_or_else(|| panic!("{path} never appeared"));
523+ }
524+}
525+
526+/// The hunks of `git diff -U0` between two blobs: for each, the lines it
527+/// replaces and the lines it puts there, counted from 0.
528+fn git_diff_hunks(git: &Path, old: &GitOid, new: &GitOid) -> Vec<(Range<usize>, Range<usize>)> {
529+ if old == new {
530+ return Vec::new();
531+ }
532+ let mut command = git_command(git, 0);
533+ command.args([
534+ "diff",
535+ "-U0",
536+ "--text",
537+ "--no-color",
538+ "--no-ext-diff",
539+ "--indent-heuristic",
540+ ]);
541+ command.args([old.to_hex(), new.to_hex()]);
542+ let range = |spec: &str| -> Range<usize> {
543+ let (start, len) = match spec.split_once(',') {
544+ Some((start, len)) => (start.parse::<usize>().unwrap(), len.parse().unwrap()),
545+ None => (spec.parse().unwrap(), 1),
546+ };
547+ if len == 0 {
548+ start..start
549+ } else {
550+ start - 1..start - 1 + len
551+ }
552+ };
553+ text(run(command).unwrap())
554+ .lines()
555+ .filter_map(|line| line.strip_prefix("@@ -"))
556+ .map(|header| {
557+ let (before, rest) = header.split_once(" +").unwrap();
558+ let after = rest.split_once(" @@").unwrap().0;
559+ (range(before), range(after))
560+ })
561+ .collect()
562+}
563+
564+/// The origins of the lines of a new version, from those of the old one
565+/// and the hunks that make it, for the changeset `id` that made it.
566+fn replay(
567+ old: &[ObjectId],
568+ new_lines: usize,
569+ hunks: &[(Range<usize>, Range<usize>)],
570+ id: ObjectId,
571+) -> Vec<ObjectId> {
572+ let mut origins = Vec::with_capacity(new_lines);
573+ let mut kept = 0;
574+ for (before, after) in hunks {
575+ origins.extend_from_slice(&old[kept..before.start]);
576+ origins.extend(std::iter::repeat_n(id, after.len()));
577+ kept = before.end;
578+ }
579+ origins.extend_from_slice(&old[kept..]);
580+ assert_eq!(origins.len(), new_lines);
581+ origins
582+}
583+
584+/// Lines of a blob, as blame counts them.
585+fn count_lines(content: &[u8]) -> usize {
586+ let breaks = content.iter().filter(|byte| **byte == b'\n').count();
587+ breaks + usize::from(content.last().is_some_and(|byte| *byte != b'\n'))
588+}
589+
590+/// Blame of each file at `revision`, against git, line by line.
591+///
592+/// Where the two differ, the documented rule must explain it: replaying
593+/// git's own diffs of the file's versions along the first-parent chain gives
594+/// git's blame line for line, and for every version braid's blame gives the
595+/// changeset that made it as many lines as git's diff inserts. So both
596+/// diffs of every change are equally short, and the blames differ only in
597+/// which of the equal lines each diff keeps.
598+fn compare_blames(
599+ git: &Path,
600+ imported: &Imported,
601+ history: &mut RepoHistory<'_>,
602+ revision: &str,
603+ files: &[String],
604+ tally: &mut Tally,
605+) {
606+ let at = imported.changeset(revision);
607+ let mut heights: HashMap<ObjectId, u64> = HashMap::new();
608+ for path in files {
609+ let expected = git_blame(git, revision, path);
610+ let blame = history
611+ .blame(at, path.as_bytes())
612+ .unwrap()
613+ .unwrap_or_else(|| panic!("no blame for {path} at {revision}"));
614+ assert_eq!(
615+ blame.origins.len(),
616+ expected.len(),
617+ "lines of {path} at {revision}"
618+ );
619+ let versions = versions(&imported.repo, at, path);
620+ let appeared = versions[0].0;
621+ let mut height = |id: ObjectId| -> u64 {
622+ *heights
623+ .entry(id)
624+ .or_insert_with(|| history.graph(id).unwrap().height)
625+ };
626+ let floor = height(appeared);
627+ let mut wanted = Vec::with_capacity(expected.len());
628+ for (n, line) in expected.iter().enumerate() {
629+ let git_origin = imported.changeset(&line.commit);
630+ wanted.push(if height(git_origin) >= floor {
631+ git_origin
632+ } else {
633+ // Git followed a rename; braid starts where the path appeared.
634+ assert_ne!(
635+ &line.filename,
636+ path,
637+ "line {} of {path} at {revision}: git found it before the path appeared, under the same name",
638+ n + 1
639+ );
640+ tally.renamed_lines += 1;
641+ appeared
642+ });
643+ }
644+ tally.blamed_files += 1;
645+ tally.blamed_lines += expected.len();
646+ let differing = blame
647+ .origins
648+ .iter()
649+ .zip(&wanted)
650+ .filter(|(origin, wanted)| origin != wanted)
651+ .count();
652+ if differing == 0 {
653+ continue;
654+ }
655+
656+ let mut origins: Vec<ObjectId> = Vec::new();
657+ let mut old: Option<GitOid> = None;
658+ for (changeset, blob) in &versions {
659+ let content = braid_engine::read_blob(imported.repo.store(), *blob).unwrap();
660+ let lines = count_lines(&content);
661+ let new = imported.map.git_blob(blob).unwrap();
662+ origins = match old {
663+ None => vec![*changeset; lines],
664+ Some(old) => {
665+ let hunks = git_diff_hunks(git, &old, &new);
666+ let inserted: usize = hunks.iter().map(|(_, after)| after.len()).sum();
667+ let own = history
668+ .blame(*changeset, path.as_bytes())
669+ .unwrap()
670+ .unwrap()
671+ .origins
672+ .iter()
673+ .filter(|origin| **origin == *changeset)
674+ .count();
675+ assert_eq!(
676+ own, inserted,
677+ "{path} at {changeset}: braid's diff and git's insert as many lines"
678+ );
679+ replay(&origins, lines, &hunks, *changeset)
680+ }
681+ };
682+ old = Some(new);
683+ }
684+ assert_eq!(
685+ origins, wanted,
686+ "{path} at {revision}: git's own diffs, replayed, give git's blame"
687+ );
688+ tally.realigned_files += 1;
689+ tally.realigned_lines += differing;
690+ }
691+}
692+
693+/// The commit a revision names.
694+fn rev_parse(git: &Path, revision: &str) -> String {
695+ let mut command = git_command(git, 0);
696+ command.args(["rev-parse", "--verify", "--end-of-options"]);
697+ command.arg(format!("{revision}^{{commit}}"));
698+ text(run(command).unwrap()).trim().to_owned()
699+}
700+
701+/// Every path a history ever had, from `git log`, with their directories.
702+fn every_path(git: &Path, revision: &str) -> BTreeSet<String> {
703+ let mut command = git_command(git, 0);
704+ command.args(["log", "--format=", "--name-only", "--no-renames", revision]);
705+ let mut paths = BTreeSet::new();
706+ for path in text(run(command).unwrap())
707+ .lines()
708+ .filter(|l| !l.is_empty())
709+ {
710+ let mut dir = path;
711+ paths.insert(path.to_owned());
712+ while let Some(slash) = dir.rfind('/') {
713+ dir = &dir[..slash];
714+ paths.insert(dir.to_owned());
715+ }
716+ }
717+ paths
718+}
719+
720+/// The files at a revision.
721+fn files_at(git: &Path, revision: &str) -> Vec<String> {
722+ let mut command = git_command(git, 0);
723+ command.args(["ls-tree", "-r", "--name-only", "-z", revision]);
724+ text(run(command).unwrap())
725+ .split('\0')
726+ .filter(|path| !path.is_empty())
727+ .map(str::to_owned)
728+ .collect()
729+}
730+
731+/// The commits of the first-parent chain of a revision, newest first.
732+fn first_parents(git: &Path, revision: &str) -> Vec<String> {
733+ let mut command = git_command(git, 0);
734+ command.args(["rev-list", "--first-parent", revision]);
735+ text(run(command).unwrap())
736+ .lines()
737+ .map(str::to_owned)
738+ .collect()
739+}
740+
741+/// Every commit, newest first.
742+fn all_commits(git: &Path, revisions: &[&str]) -> Vec<String> {
743+ let mut command = git_command(git, 0);
744+ command.arg("rev-list").args(revisions);
745+ text(run(command).unwrap())
746+ .lines()
747+ .map(str::to_owned)
748+ .collect()
749+}
750+
751+/// About `target` pairs of commits, spread over all of them, each once.
752+fn spread_pairs(commits: &[String], target: usize) -> Vec<(String, String)> {
753+ let n = commits.len();
754+ let total = n * (n + 1) / 2;
755+ let every = total.div_ceil(target).max(1);
756+ let mut pairs = Vec::new();
757+ let mut k = 0;
758+ for i in 0..n {
759+ for j in i..n {
760+ if k % every == 0 {
761+ pairs.push((commits[i].clone(), commits[j].clone()));
762+ }
763+ k += 1;
764+ }
765+ }
766+ pairs
767+}
768+
769+#[test]
770+fn a_fixture_history_matches_git() {
771+ let fixture = build_fixture();
772+ let git = fixture.work.as_path();
773+ let imported = Imported::all(git);
774+ let mut history = imported.repo.history();
775+ let mut tally = Tally::default();
776+
777+ // Path history, for every path and directory, and paths never there.
778+ let mut paths = every_path(git, "main");
779+ paths.extend([
780+ "nothing".to_owned(),
781+ "src/nothing.rs".to_owned(),
782+ ".".to_owned(),
783+ ]);
784+ for revision in ["main", "main~3", "x", "y"] {
785+ compare_path_logs(git, &imported, &mut history, revision, &paths, &mut tally);
786+ }
787+
788+ // Merge bases of pairs of every commit, criss-cross ones included.
789+ let commits = all_commits(git, &["--all"]);
790+ let mut pairs = spread_pairs(&commits, 150);
791+ let x = imported.repo.resolve("x").unwrap();
792+ let y = imported.repo.resolve("y").unwrap();
793+ assert_eq!(history.merge_bases(x, y).unwrap().len(), 2, "criss-cross");
794+ pairs.push(("x".to_owned(), "y".to_owned()));
795+ compare_merge_bases(git, &imported, &mut history, &pairs, &mut tally);
796+
797+ // Blame of every file at every revision of main's first-parent chain.
798+ for revision in first_parents(git, "main") {
799+ let files = files_at(git, &revision);
800+ compare_blames(git, &imported, &mut history, &revision, &files, &mut tally);
801+ }
802+ history.flush().unwrap();
803+ eprintln!("{tally:?}");
804+ assert!(tally.renamed_lines > 0, "the fixture has renames");
805+}
806+
807+/// Commits of a random history built with plumbing: `count` commits whose
808+/// parents are picked by a fixed generator, many of them merges, some of
809+/// them octopus merges, some criss-cross.
810+fn random_history(fixture: &mut Fixture, seed: u64, count: usize) -> Vec<String> {
811+ let mut state = seed | 1;
812+ let mut next = |below: usize| {
813+ state ^= state << 13;
814+ state ^= state >> 7;
815+ state ^= state << 17;
816+ (state % below as u64) as usize
817+ };
818+ let tree = fixture.git(&["mktree"]);
819+ let mut commits: Vec<String> = Vec::new();
820+ let mut has_child = BTreeSet::new();
821+ for n in 0..count {
822+ let parents: Vec<usize> = match (commits.len(), next(10)) {
823+ (0, _) | (_, 0) => Vec::new(),
824+ (len, 1..=4) => vec![next(len)],
825+ (len, 5..=7) => vec![next(len), next(len)],
826+ (len, 8) => (0..2 + next(3)).map(|_| next(len)).collect(),
827+ (len, _) if len >= 2 => {
828+ // Two merges of the same pair, in both orders.
829+ let (a, b) = (next(len), next(len));
830+ fixture.clock += 1;
831+ let message = format!("{n} criss");
832+ let first = fixture.git(&[
833+ "commit-tree",
834+ &tree,
835+ "-p",
836+ &commits[a],
837+ "-p",
838+ &commits[b],
839+ "-m",
840+ &message,
841+ ]);
842+ has_child.extend([a, b]);
843+ commits.push(first);
844+ vec![b, a]
845+ }
846+ _ => Vec::new(),
847+ };
848+ fixture.clock += 1;
849+ let mut args = vec!["commit-tree".to_owned(), tree.clone()];
850+ for parent in &parents {
851+ args.extend(["-p".to_owned(), commits[*parent].clone()]);
852+ has_child.insert(*parent);
853+ }
854+ args.extend(["-m".to_owned(), format!("{n}")]);
855+ let args: Vec<&str> = args.iter().map(String::as_str).collect();
856+ let commit = fixture.git(&args);
857+ commits.push(commit);
858+ }
859+ // A branch for every commit nothing descends from, so that the import
860+ // brings them all.
861+ for (n, commit) in commits.iter().enumerate() {
862+ if !has_child.contains(&n) {
863+ fixture.git(&["update-ref", &format!("refs/heads/tip{n}"), commit]);
864+ }
865+ }
866+ commits
867+}
868+
869+#[test]
870+fn merge_bases_of_random_histories_match_git() {
871+ let mut tally = Tally::default();
872+ for seed in [7, 1234, 98765] {
873+ let mut fixture = Fixture::new();
874+ let commits = random_history(&mut fixture, seed, 40);
875+ let git = fixture.work.clone();
876+ let imported = Imported::all(&git);
877+ let mut history = imported.repo.history();
878+ let pairs = spread_pairs(&commits, 120);
879+ compare_merge_bases(&git, &imported, &mut history, &pairs, &mut tally);
880+ }
881+ eprintln!("{tally:?}");
882+}
883+
884+/// The repository these tests live in, when it is a full git checkout.
885+fn this_repository() -> Option<PathBuf> {
886+ let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
887+ if !root.join(".git").exists() {
888+ eprintln!("skipped: the sources are not in a git checkout");
889+ return None;
890+ }
891+ let mut command = git_command(&root, 0);
892+ command.args(["rev-parse", "--is-shallow-repository"]);
893+ if text(run(command).unwrap()).trim() != "false" {
894+ eprintln!("skipped: this checkout is shallow");
895+ return None;
896+ }
897+ Some(root)
898+}
899+
900+#[test]
901+fn the_history_of_this_repository_matches_git() {
902+ let Some(root) = this_repository() else {
903+ return;
904+ };
905+ let head = text(
906+ run({
907+ let mut command = git_command(&root, 0);
908+ command.args(["rev-parse", "HEAD"]);
909+ command
910+ })
911+ .unwrap(),
912+ )
913+ .trim()
914+ .to_owned();
915+ let imported = Imported::head(&root);
916+ let mut history = imported.repo.history();
917+ let mut tally = Tally::default();
918+
919+ let mut paths = every_path(&root, &head);
920+ paths.extend(["nothing".to_owned(), ".".to_owned()]);
921+ compare_path_logs(&root, &imported, &mut history, &head, &paths, &mut tally);
922+
923+ let commits = all_commits(&root, &[&head]);
924+ let pairs = spread_pairs(&commits, 150);
925+ compare_merge_bases(&root, &imported, &mut history, &pairs, &mut tally);
926+
927+ // Every file at HEAD, and some of the files at older revisions along the
928+ // first-parent chain.
929+ let chain = first_parents(&root, &head);
930+ compare_blames(
931+ &root,
932+ &imported,
933+ &mut history,
934+ &head,
935+ &files_at(&root, &head),
936+ &mut tally,
937+ );
938+ for revision in chain.iter().skip(1).step_by(6) {
939+ let files: Vec<String> = files_at(&root, revision).into_iter().step_by(4).collect();
940+ compare_blames(&root, &imported, &mut history, revision, &files, &mut tally);
941+ }
942+ history.flush().unwrap();
943+ eprintln!("{tally:?}");
944+ assert!(tally.blamed_lines > 0);
945+}
946+
947+/// The paths of a git history and their map to braid, for debugging a
948+/// failure by hand: `cargo test -p elffuss-braid-repo --test
949+/// history_vs_git -- --ignored --nocapture`.
950+#[test]
951+#[ignore = "prints the fixture's history"]
952+fn print_the_fixture() {
953+ let fixture = build_fixture();
954+ let mut command = git_command(&fixture.work, 0);
955+ command.args(["log", "--graph", "--all", "--format=%h %s", "--name-status"]);
956+ eprintln!("{}", text(run(command).unwrap()));
957+ let imported = Imported::all(&fixture.work);
958+ let mut by_commit = BTreeMap::new();
959+ for (commit, changeset) in imported.map.commits() {
960+ by_commit.insert(commit.to_hex(), changeset.short());
961+ }
962+ eprintln!("{by_commit:#?}");
963+}
added crates/store/src/derived.rs +300 −0
@@ -0,0 +1,300 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! The derived index: where the records of derived values are, by key
5+//! (format spec, section 7).
6+//!
7+//! A derived value is stored as a derived object whose payload starts with
8+//! its key, and this index maps keys to the ids of those objects. It is a
9+//! cache: losing it, or part of it, only means computing values again, and
10+//! whoever reads an entry checks the record it names. So it needs no sync of
11+//! its own; but its writer makes the records durable first, so an entry never
12+//! outlives the record it names.
13+//!
14+//! ```text
15+//! derived/index append-only, 72-byte entries at multiples of 72:
16+//! [32] key | [32] record id | u32 0 | u32 crc32c of the 68 bytes before it
17+//! ```
18+//!
19+//! A writer takes an exclusive lock on the file, appends its entries at the
20+//! first multiple of 72 at or after the end, and lets go: entries of
21+//! different writers never interleave, and the remains of an append cut short
22+//! by a crash fail their CRC and are skipped. Readers take no lock. A handle
23+//! reads the whole file when first asked, and on a miss reads what was
24+//! appended since. When a key has several entries, the last one counts.
25+//! Entries are never removed; a compacted form can come with the store's own
26+//! indexes.
27+
28+use std::collections::HashMap;
29+use std::fs::{self, File, OpenOptions};
30+use std::io;
31+use std::path::{Path, PathBuf};
32+use std::sync::{Mutex, MutexGuard};
33+
34+use braid_format::ObjectId;
35+
36+use crate::error::{Error, io_error};
37+use crate::fsutil::{read_range, write_all_at};
38+
39+/// The directory of the derived index, inside the store.
40+pub const DERIVED_DIR: &str = "derived";
41+
42+/// The file of entries, inside [`DERIVED_DIR`].
43+const INDEX_FILE: &str = "index";
44+
45+/// Bytes per entry.
46+const ENTRY_LEN: u64 = 72;
47+
48+/// The derived index of a store, opened by this process.
49+///
50+/// Creating a handle does no I/O: the file is read when it is first needed.
51+/// A handle is `Send` and `Sync`.
52+#[derive(Debug)]
53+pub struct DerivedIndexFile {
54+ path: PathBuf,
55+ state: Mutex<State>,
56+}
57+
58+#[derive(Debug, Default)]
59+struct State {
60+ /// What the entries read so far say, the last entry of a key winning.
61+ map: HashMap<[u8; 32], ObjectId>,
62+ /// The file, once it exists.
63+ file: Option<File>,
64+ /// Where reading resumes: the end of the last whole slot read.
65+ read_to: u64,
66+}
67+
68+impl DerivedIndexFile {
69+ /// The derived index of the store at `store_root`.
70+ pub fn new(store_root: impl AsRef<Path>) -> Self {
71+ DerivedIndexFile {
72+ path: store_root.as_ref().join(DERIVED_DIR).join(INDEX_FILE),
73+ state: Mutex::new(State::default()),
74+ }
75+ }
76+
77+ /// The id of the record of `key`, if an entry names one. A miss reads
78+ /// what other processes appended since this handle last looked.
79+ pub fn find(&self, key: &[u8; 32]) -> Result<Option<ObjectId>, Error> {
80+ let mut state = self.lock();
81+ if let Some(id) = state.map.get(key) {
82+ return Ok(Some(*id));
83+ }
84+ self.refresh(&mut state)?;
85+ Ok(state.map.get(key).copied())
86+ }
87+
88+ /// Appends entries, in order, after making sure nobody else is
89+ /// appending. The records they name must already be durable.
90+ pub fn append(&self, entries: &[([u8; 32], ObjectId)]) -> Result<(), Error> {
91+ if entries.is_empty() {
92+ return Ok(());
93+ }
94+ let dir = self.path.parent().unwrap_or(Path::new("."));
95+ fs::create_dir_all(dir).map_err(io_error("create", dir))?;
96+ let file = OpenOptions::new()
97+ .read(true)
98+ .write(true)
99+ .create(true)
100+ .truncate(false)
101+ .open(&self.path)
102+ .map_err(io_error("open", &self.path))?;
103+ file.lock().map_err(io_error("lock", &self.path))?;
104+ let mut bytes = Vec::with_capacity(entries.len() * ENTRY_LEN as usize);
105+ for (key, id) in entries {
106+ bytes.extend_from_slice(&encode(key, id));
107+ }
108+ let end = file
109+ .metadata()
110+ .map_err(io_error("read the size of", &self.path))?
111+ .len();
112+ let at = end.next_multiple_of(ENTRY_LEN);
113+ write_all_at(&file, &bytes, at).map_err(io_error("append to", &self.path))?;
114+ // Closing the file lets the next writer in.
115+ drop(file);
116+ let mut state = self.lock();
117+ for (key, id) in entries {
118+ state.map.insert(*key, *id);
119+ }
120+ Ok(())
121+ }
122+
123+ /// Reads the entries appended since the last read.
124+ fn refresh(&self, state: &mut State) -> Result<(), Error> {
125+ if state.file.is_none() {
126+ match File::open(&self.path) {
127+ Ok(file) => state.file = Some(file),
128+ Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()),
129+ Err(err) => return Err(io_error("open", &self.path)(err)),
130+ }
131+ }
132+ let Some(file) = &state.file else {
133+ return Ok(());
134+ };
135+ let len = file
136+ .metadata()
137+ .map_err(io_error("read the size of", &self.path))?
138+ .len();
139+ // Only whole slots: the last one may still be being written.
140+ let end = len - len % ENTRY_LEN;
141+ if end <= state.read_to {
142+ return Ok(());
143+ }
144+ let bytes = read_range(file, state.read_to, end - state.read_to)
145+ .map_err(io_error("read", &self.path))?;
146+ for slot in bytes.chunks_exact(ENTRY_LEN as usize) {
147+ if let Some((key, id)) = decode(slot) {
148+ state.map.insert(key, id);
149+ }
150+ }
151+ state.read_to = end;
152+ Ok(())
153+ }
154+
155+ fn lock(&self) -> MutexGuard<'_, State> {
156+ // Every change to the state is complete before it is visible.
157+ self.state
158+ .lock()
159+ .unwrap_or_else(|poisoned| poisoned.into_inner())
160+ }
161+}
162+
163+/// The bytes of one entry.
164+fn encode(key: &[u8; 32], id: &ObjectId) -> [u8; ENTRY_LEN as usize] {
165+ let mut out = [0u8; ENTRY_LEN as usize];
166+ out[0..32].copy_from_slice(key);
167+ out[32..64].copy_from_slice(id.as_bytes());
168+ // out[64..68] stays zero.
169+ let crc = crc32c::crc32c(&out[..68]);
170+ out[68..72].copy_from_slice(&crc.to_le_bytes());
171+ out
172+}
173+
174+/// The key and record id of an entry, or `None` if it fails its checks.
175+fn decode(slot: &[u8]) -> Option<([u8; 32], ObjectId)> {
176+ if slot.len() != ENTRY_LEN as usize || slot[64..68] != [0; 4] {
177+ return None;
178+ }
179+ let mut crc = [0u8; 4];
180+ crc.copy_from_slice(&slot[68..72]);
181+ if crc32c::crc32c(&slot[..68]) != u32::from_le_bytes(crc) {
182+ return None;
183+ }
184+ let mut key = [0u8; 32];
185+ key.copy_from_slice(&slot[..32]);
186+ let mut id = [0u8; 32];
187+ id.copy_from_slice(&slot[32..64]);
188+ Some((key, ObjectId::from_bytes(id)))
189+}
190+
191+#[cfg(test)]
192+mod tests {
193+ use super::*;
194+ use braid_format::Kind;
195+
196+ fn key(n: u32) -> [u8; 32] {
197+ *ObjectId::hash(Kind::Derived, &n.to_le_bytes()).as_bytes()
198+ }
199+
200+ fn id(n: u32) -> ObjectId {
201+ ObjectId::hash(Kind::Blob, &n.to_le_bytes())
202+ }
203+
204+ #[test]
205+ fn entries_round_trip_and_damage_is_caught() {
206+ let bytes = encode(&key(1), &id(2));
207+ assert_eq!(decode(&bytes), Some((key(1), id(2))));
208+ for i in 0..bytes.len() {
209+ let mut damaged = bytes;
210+ damaged[i] ^= 0x10;
211+ assert_eq!(decode(&damaged), None, "byte {i}");
212+ }
213+ assert_eq!(decode(&[0; 72]), None);
214+ assert_eq!(decode(&bytes[..71]), None);
215+ }
216+
217+ #[test]
218+ fn appends_are_seen_by_other_handles() {
219+ let dir = tempfile::tempdir().unwrap();
220+ let writer = DerivedIndexFile::new(dir.path());
221+ let reader = DerivedIndexFile::new(dir.path());
222+ // No file yet: a miss, and nothing created.
223+ assert_eq!(reader.find(&key(1)).unwrap(), None);
224+ assert!(!dir.path().join(DERIVED_DIR).exists());
225+
226+ writer.append(&[(key(1), id(1)), (key(2), id(2))]).unwrap();
227+ assert_eq!(writer.find(&key(1)).unwrap(), Some(id(1)));
228+ assert_eq!(reader.find(&key(2)).unwrap(), Some(id(2)));
229+ writer.append(&[(key(3), id(3)), (key(1), id(4))]).unwrap();
230+ assert_eq!(reader.find(&key(3)).unwrap(), Some(id(3)));
231+ // The last entry of a key counts, once read.
232+ assert_eq!(reader.find(&key(1)).unwrap(), Some(id(4)));
233+ writer.append(&[]).unwrap();
234+
235+ let fresh = DerivedIndexFile::new(dir.path());
236+ assert_eq!(fresh.find(&key(1)).unwrap(), Some(id(4)));
237+ assert_eq!(fresh.find(&key(9)).unwrap(), None);
238+ }
239+
240+ #[test]
241+ fn torn_appends_are_skipped_and_written_after() {
242+ let dir = tempfile::tempdir().unwrap();
243+ let index = DerivedIndexFile::new(dir.path());
244+ index.append(&[(key(1), id(1)), (key(2), id(2))]).unwrap();
245+ let path = dir.path().join(DERIVED_DIR).join(INDEX_FILE);
246+ // A crash in the middle of the next append left half an entry, and
247+ // damaged the second one.
248+ let file = OpenOptions::new().write(true).open(&path).unwrap();
249+ write_all_at(&file, &encode(&key(3), &id(3))[..40], 2 * ENTRY_LEN).unwrap();
250+ write_all_at(&file, &[0xff], ENTRY_LEN + 3).unwrap();
251+ drop(file);
252+
253+ index.append(&[(key(4), id(4))]).unwrap();
254+ assert_eq!(fs::metadata(&path).unwrap().len(), 4 * ENTRY_LEN);
255+ let fresh = DerivedIndexFile::new(dir.path());
256+ assert_eq!(fresh.find(&key(1)).unwrap(), Some(id(1)));
257+ assert_eq!(fresh.find(&key(2)).unwrap(), None);
258+ assert_eq!(fresh.find(&key(3)).unwrap(), None);
259+ assert_eq!(fresh.find(&key(4)).unwrap(), Some(id(4)));
260+ }
261+
262+ #[test]
263+ fn concurrent_writers_never_mix_their_entries() {
264+ let dir = tempfile::tempdir().unwrap();
265+ let root = dir.path().to_path_buf();
266+ // Separate handles open the file separately, so their locks exclude
267+ // each other as those of separate processes do.
268+ let threads: Vec<_> = (0..8u32)
269+ .map(|t| {
270+ let root = root.clone();
271+ std::thread::spawn(move || {
272+ let index = DerivedIndexFile::new(&root);
273+ for round in 0..20u32 {
274+ let entries: Vec<_> = (0..5u32)
275+ .map(|i| {
276+ let n = t * 1000 + round * 10 + i;
277+ (key(n), id(n))
278+ })
279+ .collect();
280+ index.append(&entries).unwrap();
281+ }
282+ })
283+ })
284+ .collect();
285+ for thread in threads {
286+ thread.join().unwrap();
287+ }
288+ let path = root.join(DERIVED_DIR).join(INDEX_FILE);
289+ assert_eq!(fs::metadata(&path).unwrap().len(), 8 * 20 * 5 * ENTRY_LEN);
290+ let index = DerivedIndexFile::new(&root);
291+ for t in 0..8u32 {
292+ for round in 0..20u32 {
293+ for i in 0..5u32 {
294+ let n = t * 1000 + round * 10 + i;
295+ assert_eq!(index.find(&key(n)).unwrap(), Some(id(n)));
296+ }
297+ }
298+ }
299+ }
300+}
modified crates/store/src/lib.rs +6 −0
@@ -76,8 +76,12 @@
7676 //! oplog/lock empty; locked exclusively by transactions, shared by readers
7777 //! oplog/log operation records, append-only
7878 //! oplog/ckpt.<seq> every ref as of operation <seq>
79+//! derived/index where the records of derived values are, by key
7980 //! ```
8081 //!
82+//! The derived index is a cache with its own rules: see
83+//! [`DerivedIndexFile`].
84+//!
8185 //! Segment names are 32 random lowercase hex digits. Files whose names start
8286 //! with `tmp-` are still being written, or were left by a writer that died;
8387 //! they are never read, and are removed once they are a minute old and
@@ -154,6 +158,7 @@
154158
155159 #![forbid(unsafe_code)]
156160
161+mod derived;
157162 mod error;
158163 mod fsck;
159164 mod fsutil;
@@ -172,6 +177,7 @@
172177
173178 pub use braid_format::{Kind, ObjectId, Objects};
174179
180+pub use derived::{DERIVED_DIR, DerivedIndexFile};
175181 pub use error::{Error, TransactError};
176182 pub use fsck::{FsckReport, Problem};
177183 pub use oplog::{Operation, RefUpdate, Refs};
modified docs/design.md +105 −5
@@ -84,6 +84,37 @@
8484 filters, blame, git mappings) is stored as records keyed by their inputs, and
8585 can always be recomputed.
8686
87+### Derived data
88+
89+Everything that is not in a changeset is derived data: computed from
90+changesets, stored, and always recomputable. A derived value is what a named
91+function, at some version, gives for some inputs, and its key is
92+`BLAKE3-derive-key("elffuss-braid 2026 derived v1", function ‖ version ‖ input
93+ids ‖ argument)`. The encodings are in section 8 of the format spec.
94+
95+- **Records.** A value is stored as an ordinary derived object whose payload
96+ is its key followed by its encoding, which each function versions on its
97+ own: a new encoding is a new version, so new keys. The object's id depends
98+ on the value, so the store keeps a *derived index* next to its segments,
99+ `derived/index`: an append-only file of fixed-size entries, a key and a
100+ record id, each with a checksum.
101+- **A cache, checked on use.** The index is never trusted: a record is used
102+ only when its payload starts with the key and its value decodes, and a
103+ value whose record is missing, damaged or unindexed is computed again.
104+ Losing the index, or part of it, costs only time.
105+- **Many processes, no database.** Values are deterministic functions of their
106+ inputs, so two processes that compute the same value store the same bytes
107+ under the same id; storing an object twice does nothing, and two entries
108+ for a key name the same record. Writers append to the index under an
109+ exclusive lock, at a multiple of the entry size, so a crash leaves at worst
110+ an entry that fails its checksum, and readers take no lock. Records are
111+ made durable before an entry names them.
112+- **Lazy.** A value is computed the first time a command needs it, with the
113+ values it depends on, and recorded when the command finishes. `braid
114+ derive` computes them ahead of time, after a large import for example.
115+- The git map is a derived record too, but a single one, found through the
116+ ref `braid/git-map` rather than the index.
117+
87118 ## Landing on a branch
88119
89120 `land` takes a changeset `C` built on base `B` and moves a branch to include it.
@@ -116,6 +147,66 @@
116147 contained it. An acknowledged landing is durable. Readers only see durable
117148 heads.
118149
150+## History
151+
152+Three derived functions answer history queries without walking all of
153+history every time. The engine's `History` reads them through the derived
154+index, computes what is missing, and remembers what it read.
155+
156+- **Commit graph data** (`graph`, per changeset): the parents, the
157+ generation (1 without parents, otherwise 1 more than the largest of the
158+ parents'), the height along first parents, and a skip pointer to the
159+ first-parent ancestor at the height that Bitcoin's block index picks for
160+ its skip pointers. Following skip pointers reaches any first-parent
161+ ancestor in a number of steps that grows with the logarithm of the
162+ distance. With them, `is_ancestor` and `first_parent_chain_contains` find a
163+ first-parent ancestor in logarithmic time, and every other walk stops
164+ below the generation it looks for, since an ancestor always has a smaller
165+ generation. `merge_bases` walks down from both sides in order of
166+ generation, marking what each side reaches; a changeset reached from both
167+ is a merge base unless it is below one already found, and the walk stops
168+ when everything left to visit is. The answers are those of the walking
169+ functions, which landing, merging, workspaces and git sync still use,
170+ since they are given only objects; property tests compare the two on
171+ random histories with octopus and criss-cross merges.
172+- **Changed-path filters** (`changed-paths`, per changeset): the first parent
173+ and a Bloom filter, with git's parameters (10 bits per entry, 7 hashes), of
174+ the paths the change list names and their parent directories. `braid log
175+ [rev] -- <path>...` lists, newest first, the changesets on the first-parent
176+ chain whose change list touches a path or anything below it, as `git log
177+ --first-parent -- <path>` does, without following renames. It reads one
178+ small record per changeset walked, and a change list only where the filter
179+ lets the changeset through: the ones that touched the path, and about one
180+ in a hundred of the others.
181+- **Blame** (`blame`, per changeset and path, where the changeset sets the
182+ file): the changeset that last changed each line, as runs. It is computed
183+ from the blame of the previous version of the file on the first-parent
184+ chain and a line diff between the two versions, imara-diff's Myers
185+ algorithm with its indentation heuristic, which is what git's blame uses by
186+ default; a merge on the first-parent chain owns the lines it brought in.
187+ Blaming a file computes the records of the versions that lack one, back to
188+ the newest that has one, so blaming it again, at the same revision or a
189+ later one, costs one diff per new version. `braid blame <rev> <path>`
190+ prints the short id, the agent or the author, the date, the line number
191+ and the line; `--json` gives the same per line.
192+
193+Blame differs from git's on purpose in two ways, and the differential tests
194+check that it differs in no other:
195+
196+- **Renames are not followed.** Git follows a file across whole-file renames,
197+ and has no switch to turn that off. Braid's history of a path starts where
198+ the path last appeared: a line that git traces back across a rename is the
199+ changeset's that created the path.
200+- **Several shortest diffs.** When a change can be written as more than one
201+ shortest line diff, git's diff and imara-diff's may pick different ones.
202+ Both delete and insert as many lines; they keep different copies of lines
203+ that repeat, such as closing braces and blank lines, and blame gives those
204+ copies to different changesets. On this repository's own history, fewer
205+ than one line in a thousand differs this way. The tests replay git's own
206+ diffs along the same versions, which must give git's blame line for line,
207+ and check that at every version braid's diff inserts as many lines as
208+ git's.
209+
119210 ## Workspaces
120211
121212 - One workspace per agent, all sharing one store. No staging area: tracked
@@ -267,10 +358,16 @@
267358 file system shim that drops unsynced writes.
268359 - **Properties.** Encodings round-trip canonically; incremental tree updates
269360 equal building from scratch; disjoint landings commute; a changeset's change
270- list equals the diff of its trees.
361+ list equals the diff of its trees; ancestry with derived data answers what
362+ the walks answer on random histories; changed-path filters never miss a
363+ path they hold; derived records do not depend on the order they are
364+ computed in.
271365 - **Fuzzing** of every decoder, the git importer, path validation and merges.
272366 - **Differential tests with git as the oracle** on real histories: tree diffs,
273- path history, merge bases and three-way merges. Braid merging cleanly where
367+ path history (`git log --first-parent -- <path>`), merge bases (`git
368+ merge-base --all`), blame (`git blame --first-parent`, with the two
369+ differences above checked as such) and three-way merges, on fixtures, on
370+ random histories and on this repository's own. Braid merging cleanly where
274371 git reports a conflict is treated as a critical bug.
275372 - **Round trips** of real public repositories through import and export, bit
276373 for bit.
@@ -282,9 +379,12 @@
282379 them.
283380
284381 - Commit and land: proportional to the changed paths times the tree depth.
285-- `log -- path`: proportional to the changes that touched the path.
286-- Ancestry and merge base: logarithmic, using skip pointers and generation
287- numbers.
382+- `log -- path`: proportional to the changes that touched the path, plus one
383+ filter check per changeset walked.
384+- Ancestry and merge base: logarithmic for first-parent ancestors, using skip
385+ pointers; otherwise proportional to the changesets above the generation
386+ looked for. Derived data is computed once, the first time.
387+- Blame: one line diff per version of the file not blamed before.
288388 - A lazy sparse clone: proportional to the objects under the requested paths.
289389 - Store size: at most twice a garbage-collected git repository of the same
290390 history.
modified docs/spec/format-v1.md +76 −1
@@ -3,7 +3,8 @@
33 **Status: frozen.** Sections 1 to 5 (ids, the codec, trees, changesets and
44 names) are implemented in `crates/format` and frozen: any change to hashed bytes
55 needs a new format version. Sections 6 and 7 describe the git mapping and the
6-on-disk storage, which are not hashed and can still change.
6+on-disk storage, which are not hashed and can still change. Section 8 describes
7+derived data, whose encodings each have a version of their own.
78
89 Every golden vector below is pinned by the Rust tests and recomputed by
910 [`check_vectors.py`](check_vectors.py), a second implementation written from
@@ -325,6 +326,7 @@
325326 .braid/store/oplog/lock empty; locked exclusively by transactions, shared by readers
326327 .braid/store/oplog/log operation records, append-only
327328 .braid/store/oplog/ckpt.<seq> every ref as of operation <seq>
329+.braid/store/derived/index where the records of derived values are, by key
328330 ```
329331
330332 Segment names are 32 random lowercase hex digits. Files whose names start with
@@ -411,7 +413,80 @@
411413 [32] BLAKE3 hash of everything before it
412414 ```
413415
416+**Derived index entry**, 72 bytes at a multiple of 72:
417+
418+```
419+[32] key | [32] record id | u32 0 | u32 crc32c of the 68 bytes before it
420+```
421+
422+The derived index is a cache of where the records of section 8 are. A writer
423+locks the file exclusively, appends its entries at the first multiple of 72 at
424+or after the end, and unlocks; the records the entries name are durable
425+first. Readers take no lock, skip entries that fail their CRC, and let the last
426+entry of a key count. The file needs no sync: losing entries only means
427+computing values again.
428+
414429 **Planned, not implemented yet:** a binary fuse filter in indexes for fast
415430 misses, merged indexes, one-level zstd deltas against the same path in the
416431 first parent (codec 3), per-repository dictionaries (codec 2), and FastCDC
417432 chunking of blobs of 4 MiB or more.
433+
434+## 8. Derived data (not frozen, versioned per function)
435+
436+Values computed from changesets are stored as derived objects (kind 5), so
437+their ids follow section 2, but their payloads are not part of format v1:
438+each function versions its encoding, and a new encoding is a new version, so
439+new keys. They are implemented in `crates/engine`.
440+
441+**Key** of the value of `function` at `version`:
442+
443+```
444+BLAKE3-derive-key("elffuss-braid 2026 derived v1",
445+ bytes function | uv version | uv n | n × [32] input id | bytes argument)
446+```
447+
448+**Record**: a derived object whose payload is `[32] key` followed by the
449+value. A reader uses a record only when it starts with the key and the value
450+decodes; anything else is computed again.
451+
452+**`graph`, version 1**, of a changeset (the input is its id):
453+
454+```
455+uv n, n × [32] parents, in order
456+uv generation 1 without parents, else 1 + the largest of the parents'
457+uv height 0 without parents, else 1 + the first parent's
458+[32] skip present when height > 0: the first-parent ancestor at
459+ skip_height(height)
460+```
461+
462+`skip_height(h)` is 0 for `h < 2`; for an even `h`, `h` with its lowest set
463+bit cleared; for an odd `h`, 1 + (`h - 1` with its two lowest set bits
464+cleared).
465+
466+**`changed-paths`, version 1**, of a changeset (the input is its id):
467+
468+```
469+u8 1, then [32] the first parent; or 0 without parents
470+uv n the paths the change list names and all their parent
471+ directories, each once
472+ filter ceil(10 n / 8) bytes when 0 < n ≤ 1024, else nothing
473+```
474+
475+The bits of an entry come from `h = BLAKE3-derive-key("elffuss-braid 2026
476+changed-paths v1", path)`: with `a` and `b` its first two little-endian 64-bit
477+words and `m` the number of bits of the filter, its bits are `(a + i·b) mod m`
478+for `i` from 0 to 6, computed modulo 2⁶⁴; bit `j` is bit `j mod 8` of byte
479+`j / 8`. With `n = 0` no path matches; with `n > 1024` every path may.
480+
481+**`blame`, version 1**, of a changeset and a path (the input is the
482+changeset's id, the argument the path), for a changeset whose change list sets
483+the path to a file, an executable or a symlink:
484+
485+```
486+uv k, k × [32] changesets, in the order their first lines come
487+uv r, r × (uv index of the changeset, uv lines) runs, in line order
488+```
489+
490+Runs are not empty, two runs in a row never have the same changeset, and every
491+changeset listed has lines. A line ends after `\n`; a last line without one
492+is a line too.