Elffuss BraidHub

utopia-ia/elffuss-braid public

Merge the blame test fix: shortest-diff bound and own-diff check
Changeset818b87322bb6f537ef1d039055a99885ec2edffa86ed5ea5cad2b10eb080fb27
AuthorKikoCis <KikoCis@users.noreply.github.com> · 2026-10-16 02:27 +02:00
CommitterKikoCis <KikoCis@users.noreply.github.com> · 2026-10-16 02:27 +02:00
Parentsd287786cafb1, 38b3e04f7d4a

Browse the files at this changeset

4 files changed

modified crates/engine/src/blame.rs +71 −20
@@ -14,13 +14,14 @@
1414 //! where there was nothing, a directory or a gitlink, is all its own:
1515 //! renames are not followed.
1616 //!
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
17+//! The line diff, [`line_diff`], is imara-diff's Myers algorithm with its
18+//! indentation heuristic, which is what git's blame uses by default, so the
19+//! two agree line for line except in two ways. Git follows a file across
20+//! whole-file renames, and braid does not. And the two diffs can differ:
21+//! when a change has several shortest line diffs, they may keep different
22+//! copies of lines that repeat, such as closing braces and blank lines; and
23+//! neither always finds a shortest diff, so on some changes one inserts and
24+//! deletes a few more lines than the other. Blame then gives those lines to
2425 //! different changesets.
2526 //!
2627 //! The derived function `blame`, version 1, of a changeset and a path (the
@@ -36,6 +37,7 @@
3637 //! line without one is a line too, as in three-way merges.
3738
3839 use std::collections::HashMap;
40+use std::ops::Range;
3941 use std::rc::Rc;
4042
4143 use braid_format::codec::{Reader, put_id, put_uv};
@@ -208,27 +210,63 @@
208210 byte_lines(content).count()
209211 }
210212
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> {
213+/// One change of a line diff: lines of the old version, replaced by lines of
214+/// the new one.
215+#[derive(Clone, Debug, PartialEq, Eq)]
216+pub struct LineChange {
217+ /// The lines of the old version it replaces, counted from 0, end
218+ /// excluded; empty for an insertion, which goes before line `old.start`.
219+ pub old: Range<usize>,
220+ /// The lines of the new version it puts there; empty for a deletion.
221+ pub new: Range<usize>,
222+}
223+
224+/// The line diff blame uses between two versions of a file: its changes, in
225+/// order. The lines between changes are kept: equal, in the same order.
226+///
227+/// It is imara-diff's Myers algorithm with its indentation heuristic, which
228+/// is what git's blame uses by default. Like git's, it does not always find
229+/// the shortest diff: it gives up on it where the search would cost too
230+/// much, and its preprocessing, which sets aside lines that cannot be kept,
231+/// can miss it too. So a diff may insert, and delete, a few more lines than
232+/// the fewest possible, and not on the same changes as git's. Content of
233+/// [`i32::MAX`] bytes or more is not diffed: all of it is replaced.
234+pub fn line_diff(old: &[u8], new: &[u8]) -> Vec<LineChange> {
215235 if old.len() >= MAX_DIFF_BYTES || new.len() >= MAX_DIFF_BYTES {
216- return vec![id; count_lines(new)];
236+ let (old_lines, new_lines) = (count_lines(old), count_lines(new));
237+ if old_lines == 0 && new_lines == 0 {
238+ return Vec::new();
239+ }
240+ return vec![LineChange {
241+ old: 0..old_lines,
242+ new: 0..new_lines,
243+ }];
217244 }
218245 let input = InternedInput::new(old, new);
219246 let mut diff = Diff::compute(Algorithm::Myers, &input);
220247 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.
248+ diff.hunks()
249+ .map(|hunk| LineChange {
250+ old: hunk.before.start as usize..hunk.before.end as usize,
251+ new: hunk.after.start as usize..hunk.after.end as usize,
252+ })
253+ .collect()
254+}
255+
256+/// The origins of the lines of `new`, a later version of `old` whose lines
257+/// come from `old_origins`, when `id` made it: kept lines keep their origin,
258+/// the others are `id`'s.
259+fn carry(old: &[u8], new: &[u8], old_origins: &[ObjectId], id: ObjectId) -> Vec<ObjectId> {
260+ let mut origins = Vec::with_capacity(old_origins.len());
261+ // The next line of `old` that no change has reached yet.
223262 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;
263+ for change in line_diff(old, new) {
264+ origins.extend_from_slice(&old_origins[kept..change.old.start]);
265+ origins.extend(std::iter::repeat_n(id, change.new.len()));
266+ kept = change.old.end;
229267 }
230268 origins.extend_from_slice(&old_origins[kept..]);
231- debug_assert_eq!(origins.len(), input.after.len());
269+ debug_assert_eq!(origins.len(), count_lines(new));
232270 origins
233271 }
234272
@@ -380,6 +418,19 @@
380418 }
381419 }
382420
421+ #[test]
422+ fn line_diffs_list_changes_between_kept_lines() {
423+ let change = |old: Range<usize>, new: Range<usize>| LineChange { old, new };
424+ assert_eq!(
425+ line_diff(b"a\nb\nc\n", b"a\nB\nc\nd\n"),
426+ [change(1..2, 1..2), change(3..3, 3..4)]
427+ );
428+ assert_eq!(line_diff(b"x\ny\n", b"x\ny\n"), []);
429+ assert_eq!(line_diff(b"", b""), []);
430+ assert_eq!(line_diff(b"", b"one\n"), [change(0..0, 0..1)]);
431+ assert_eq!(line_diff(b"a\nb\n", b"b\n"), [change(0..1, 0..0)]);
432+ }
433+
383434 #[test]
384435 fn kept_lines_keep_their_origin() {
385436 let old = b"a\nb\nc\nd\n";
modified crates/engine/src/lib.rs +1 −1
@@ -78,7 +78,7 @@
7878 GraphNode, first_parent_chain_contains, is_ancestor, merge_base, merge_bases, skip_height,
7979 };
8080 pub use apply::apply;
81-pub use blame::Blame;
81+pub use blame::{Blame, LineChange, line_diff};
8282 pub use commit::{admit, commit};
8383 pub use derived::{DerivedIndex, DerivedKey, MemoryIndex};
8484 pub use diff::diff;
modified crates/repo/tests/history_vs_git.rs +171 −52
@@ -21,20 +21,25 @@
2121 //! changeset older than the one where the path last appeared on the
2222 //! first-parent chain is, for braid, that changeset's, and git must have
2323 //! 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.
24+//! - Git's diff and braid's can differ: when a change has several shortest
25+//! line diffs, they may keep different copies of lines that repeat, such
26+//! as closing braces; and neither always finds a shortest diff, so on some
27+//! changes one inserts a few more lines than the other. Where the two
28+//! blames differ, the tests walk the file's versions along the first-parent
29+//! chain: replaying git's own diffs (`git diff -U0`) must give git's blame
30+//! line for line; braid's blame at each version must be braid's own diff
31+//! applied to its blame at the version before, a diff that keeps only
32+//! equal lines; and that diff must never insert fewer lines than the
33+//! shortest one (`git diff --minimal -U0`), which would be a bug. Files
34+//! where the two diffs insert as many lines at every version count as
35+//! realigned, the others as heuristic divergences.
3136
3237 use std::collections::{BTreeMap, BTreeSet, HashMap};
3338 use std::ops::Range;
3439 use std::path::{Path, PathBuf};
3540 use std::process::{Command, Stdio};
3641
37-use braid_engine::{read_changes, read_changeset};
42+use braid_engine::{LineChange, read_changes, read_changeset};
3843 use braid_format::{EntryKind, ObjectId};
3944 use braid_git::{GitMap, GitOid, ImportOptions};
4045 use braid_repo::{Repo, RepoHistory};
@@ -371,10 +376,20 @@
371376 /// Lines git traced across a rename, which braid gives to the changeset
372377 /// where the path appeared.
373378 renamed_lines: usize,
374- /// Files and lines where git and braid kept different copies of equal
375- /// lines in equally short diffs.
379+ /// Files and lines where braid and git differ while their diffs insert
380+ /// as many lines at every version: they kept different copies of equal
381+ /// lines.
376382 realigned_files: usize,
377383 realigned_lines: usize,
384+ /// Files and lines where braid and git differ and, at some version,
385+ /// their diffs insert different numbers of lines, none fewer than the
386+ /// shortest diff.
387+ heuristic_files: usize,
388+ heuristic_lines: usize,
389+ /// Versions whose blame was checked against braid's own diff.
390+ versions_checked: usize,
391+ /// The files that differ, as `path at revision`, and why.
392+ differences: Vec<String>,
378393 }
379394
380395 /// `log -- <path>` for each path, against git.
@@ -523,9 +538,15 @@
523538 }
524539 }
525540
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>)> {
541+/// The hunks of `git diff -U0` between two blobs, or of `git diff --minimal
542+/// -U0`: for each, the lines it replaces and the lines it puts there,
543+/// counted from 0.
544+fn git_diff_hunks(
545+ git: &Path,
546+ old: &GitOid,
547+ new: &GitOid,
548+ minimal: bool,
549+) -> Vec<(Range<usize>, Range<usize>)> {
529550 if old == new {
530551 return Vec::new();
531552 }
@@ -538,6 +559,9 @@
538559 "--no-ext-diff",
539560 "--indent-heuristic",
540561 ]);
562+ if minimal {
563+ command.arg("--minimal");
564+ }
541565 command.args([old.to_hex(), new.to_hex()]);
542566 let range = |spec: &str| -> Range<usize> {
543567 let (start, len) = match spec.split_once(',') {
@@ -581,20 +605,100 @@
581605 origins
582606 }
583607
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'))
608+/// The lines of a blob, as blame counts them: each ends after a `\n`, and
609+/// a last line without one is a line too.
610+fn split_lines(content: &[u8]) -> Vec<&[u8]> {
611+ let mut lines: Vec<&[u8]> = content.split_inclusive(|byte| *byte == b'\n').collect();
612+ if content.is_empty() {
613+ lines.clear();
614+ }
615+ lines
616+}
617+
618+/// The lines of the new version that braid's line diff keeps, each paired
619+/// with a line of the old version, must be equal to it.
620+fn check_kept_lines(old: &[u8], new: &[u8], changes: &[LineChange], what: &str) {
621+ let (old, new) = (split_lines(old), split_lines(new));
622+ let (mut at_old, mut at_new) = (0, 0);
623+ for change in changes {
624+ assert_eq!(
625+ change.old.start - at_old,
626+ change.new.start - at_new,
627+ "{what}: as many kept lines on both sides"
628+ );
629+ while at_old < change.old.start {
630+ assert_eq!(old[at_old], new[at_new], "{what}: a kept line is equal");
631+ at_old += 1;
632+ at_new += 1;
633+ }
634+ (at_old, at_new) = (change.old.end, change.new.end);
635+ }
636+ assert_eq!(
637+ &old[at_old..],
638+ &new[at_new..],
639+ "{what}: the kept end is equal"
640+ );
641+}
642+
643+/// Braid's blame of every version of a file, oldest first, checked against
644+/// braid's own line diff: the first version is all its own, and each other
645+/// one is the diff applied to the blame of the version before, a diff that
646+/// keeps only equal lines. Returns each version's content and blame.
647+fn check_versions(
648+ imported: &Imported,
649+ history: &mut RepoHistory<'_>,
650+ path: &str,
651+ versions: &[(ObjectId, ObjectId)],
652+ tally: &mut Tally,
653+) -> Vec<(Vec<u8>, Vec<ObjectId>)> {
654+ let mut checked: Vec<(Vec<u8>, Vec<ObjectId>)> = Vec::new();
655+ for (changeset, blob) in versions {
656+ let what = format!("{path} at {changeset}");
657+ let content = braid_engine::read_blob(imported.repo.store(), *blob).unwrap();
658+ let lines = split_lines(&content).len();
659+ let own = history
660+ .blame(*changeset, path.as_bytes())
661+ .unwrap()
662+ .unwrap()
663+ .origins;
664+ assert_eq!(own.len(), lines, "{what}: one origin per line");
665+ match checked.last() {
666+ None => assert!(
667+ own.iter().all(|origin| origin == changeset),
668+ "{what}: a new file is all its own"
669+ ),
670+ Some((old_content, old_own)) => {
671+ let changes = braid_engine::line_diff(old_content, &content);
672+ check_kept_lines(old_content, &content, &changes, &what);
673+ let hunks: Vec<(Range<usize>, Range<usize>)> = changes
674+ .iter()
675+ .map(|change| (change.old.clone(), change.new.clone()))
676+ .collect();
677+ assert_eq!(
678+ own,
679+ replay(old_own, lines, &hunks, *changeset),
680+ "{what}: braid's blame follows braid's diff"
681+ );
682+ }
683+ }
684+ tally.versions_checked += 1;
685+ checked.push((content, own));
686+ }
687+ checked
688+}
689+
690+/// Lines a diff's hunks insert.
691+fn inserts(hunks: &[(Range<usize>, Range<usize>)]) -> usize {
692+ hunks.iter().map(|(_, after)| after.len()).sum()
588693 }
589694
590695 /// Blame of each file at `revision`, against git, line by line.
591696 ///
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.
697+/// Braid's blame of every version of the file is checked against braid's
698+/// own diff. Where braid's blame and git's differ, the documented rules must
699+/// explain it (see the module documentation): git's own diffs, replayed,
700+/// give git's blame, and braid's diff never inserts fewer lines than the
701+/// shortest one.
598702 fn compare_blames(
599703 git: &Path,
600704 imported: &Imported,
@@ -617,6 +721,12 @@
617721 "lines of {path} at {revision}"
618722 );
619723 let versions = versions(&imported.repo, at, path);
724+ let checked = check_versions(imported, history, path, &versions, tally);
725+ assert_eq!(
726+ checked.last().map(|(_, own)| own),
727+ Some(&blame.origins),
728+ "{path} at {revision}: the blame of its last version"
729+ );
620730 let appeared = versions[0].0;
621731 let mut height = |id: ObjectId| -> u64 {
622732 *heights
@@ -653,40 +763,49 @@
653763 continue;
654764 }
655765
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);
766+ // Git's blame, replayed from git's own diffs, and the lengths of the
767+ // two diffs at every version.
768+ let mut replayed: Vec<ObjectId> = Vec::new();
769+ let mut same_lengths = true;
770+ for (i, (changeset, blob)) in versions.iter().enumerate() {
771+ let lines = split_lines(&checked[i].0).len();
772+ if i == 0 {
773+ replayed = vec![*changeset; lines];
774+ continue;
775+ }
776+ let what = format!("{path} at {changeset}");
777+ let old = imported.map.git_blob(&versions[i - 1].1).unwrap();
661778 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);
779+ let inserted = braid_engine::line_diff(&checked[i - 1].0, &checked[i].0)
780+ .iter()
781+ .map(|change| change.new.len())
782+ .sum::<usize>();
783+ let fewest = inserts(&git_diff_hunks(git, &old, &new, true));
784+ assert!(
785+ inserted >= fewest,
786+ "{what}: braid's diff inserts {inserted} lines, the shortest diff {fewest}"
787+ );
788+ let git_hunks = git_diff_hunks(git, &old, &new, false);
789+ same_lengths &= inserted == inserts(&git_hunks);
790+ replayed = replay(&replayed, lines, &git_hunks, *changeset);
683791 }
684792 assert_eq!(
685- origins, wanted,
793+ replayed, wanted,
686794 "{path} at {revision}: git's own diffs, replayed, give git's blame"
687795 );
688- tally.realigned_files += 1;
689- tally.realigned_lines += differing;
796+ let why = if same_lengths {
797+ tally.realigned_files += 1;
798+ tally.realigned_lines += differing;
799+ "realigned"
800+ } else {
801+ tally.heuristic_files += 1;
802+ tally.heuristic_lines += differing;
803+ "heuristic"
804+ };
805+ let short = &revision[..revision.len().min(12)];
806+ tally
807+ .differences
808+ .push(format!("{path} at {short}: {differing} lines, {why}"));
690809 }
691810 }
692811
modified docs/design.md +14 −9
@@ -216,15 +216,20 @@
216216 and has no switch to turn that off. Braid's history of a path starts where
217217 the path last appeared: a line that git traces back across a rename is the
218218 changeset's that created the path.
219-- **Several shortest diffs.** When a change can be written as more than one
220- shortest line diff, git's diff and imara-diff's may pick different ones.
221- Both delete and insert as many lines; they keep different copies of lines
222- that repeat, such as closing braces and blank lines, and blame gives those
223- copies to different changesets. On this repository's own history, fewer
224- than one line in a thousand differs this way. The tests replay git's own
225- diffs along the same versions, which must give git's blame line for line,
226- and check that at every version braid's diff inserts as many lines as
227- git's.
219+- **The two diffs can differ.** Git's blame and braid's both use Myers'
220+ algorithm with an indentation heuristic, but not the same implementation.
221+ When a change has several shortest line diffs, they may keep different
222+ copies of lines that repeat, such as closing braces and blank lines. And
223+ neither always finds a shortest diff: both give up on it where the search
224+ would cost too much, and imara-diff's preprocessing can miss it too, so on
225+ a few changes one inserts and deletes more lines than the other. Blame
226+ then gives those lines to different changesets. On this repository's own
227+ history, fewer than one line in a thousand differs this way. Where the
228+ blames differ, the tests walk the versions of the file: replaying git's
229+ own diffs must give git's blame line for line, braid's blame at every
230+ version must be braid's own diff applied to its blame at the version
231+ before, and braid's diff must never insert fewer lines than the shortest
232+ diff (`git diff --minimal`).
228233
229234 ## Workspaces
230235