Skip to content

fix(gix-imara-diff): make histogram diffs match git diff --histogram - #3246

Merged
Sebastian Thiel (Byron) merged 5 commits into
GitoxideLabs:mainfrom
daniel-kindl:fix-histogram-git-parity
Nov 25, 2026
Merged

Sebastian Thiel (Byron) merged 5 commits into
GitoxideLabs:mainfrom
daniel-kindl:fix-histogram-git-parity

Conversation

@daniel-kindl

Copy link
Copy Markdown
Contributor

This pull request was written by Claude Code, an AI agent, which also made the change and ran the checks below. It is opened from the GitHub account of daniel-kindl.

Motivation

Diffy (https://github.com/daniel-kindl/diffy) is a code review desktop app. It stores review comments at hunk positions, so it needs hunks identical to git diff --histogram, with Git as its test oracle. In a comparison of 3,732 file pairs from git.git, tokio and ripgrep, gix-imara-diff was the closest crate, with 5 pairs that differ from Git 2.55.0. This change makes it identical on each of them.

Changes

The histogram diff and its postprocessing differed from Git's xdiff/ in four steps (line numbers for 0.3.4 and Git 2.55.0):

Step Before Git
1. Skip after a match skips later occurrences while the old-file position is not greater than end2, the match end in the new file (src/histogram/lcs.rs:135) compares with ae, the match end in the old file (xdiff/xhistogram.c:212)
2. Occurrence limit MAX_CHAIN_LEN is 63 (src/histogram.rs:14) accepts up to 64 occurrences (xdiff/xhistogram.c:289, :294)
3. Common prefix and suffix stripped before the histogram diff (src/lib.rs:276-277) not stripped for histogram (xdiff/xprepare.c:461)
4. Diff again after a slide none diffs a group again with Myers if it moved and the group in the other file isn't empty, for histogram only (xdiff/xdiffi.c:921-955, added in Git 2.54 by e417277ae9)
  • Step 2 also changes MAX_SIZE_CLASS to sclass_for_length(MAX_CHAIN_LEN). The list pool keeps up to MAX_CHAIN_LEN + 1 positions for each line, and with only MAX_CHAIN_LEN = 64 it panics with an index out of bounds.
  • For step 4, Diff gets a private rediff_after_slide flag. compute_with() sets it for Algorithm::Histogram only, so Myers output doesn't change.
  • The re-diff numbers the tokens of the two groups from zero, in buffers that both postprocessing passes reuse. Myers sizes its occurrence counts by the largest token, so with the tokens of the whole input each group would allocate counts for the whole vocabulary. With 1,000 shifted groups after 100,000 unique unchanged lines, that was 1.6 GB of allocations and 10 ms of postprocessing; now it is 68 KB and 0.38 ms (0.20 ms before this pull request). Like Git's xdl_fall_back_diff(), the counts cover only the tokens of the two groups.

Tests

tests/fixtures/make_histogram_baseline.sh has one small case for each step, and each case reversed. The four new tests in tests/integration/main.rs compare the hunks with Git's --unified=0 hunks, with --no-indent-heuristic (postprocess_no_heuristic()) and --indent-heuristic (postprocess_lines()). They need Git 2.54 or newer and skip with older versions, like the Myers baseline.

  • Each test fails when only its step is undone.
  • With the 0.3.4 source, the tests for steps 1, 2 and 3 fail. The step 4 case passes there, because stripping the common ends (step 3) hides it.

Checks

All with Git 2.55.0 on Linux, on main at a825f86:

Check Before After
cargo test -p gix-imara-diff pass pass (37 tests)
cargo test -p gix-diff pass pass (180 tests)
cargo test -p gix-merge pass pass (114 tests)
gix-diff slider baseline as in gix-diff/tests/README.md (gitoxide corpus, --count 2024, 2,180 cases) 2,176 exact 2,178 exact
Diffy corpus, 3,732 pairs, --indent-heuristic with postprocess_lines() 3,727 identical 3,732 identical
Diffy corpus, 3,732 pairs, --no-indent-heuristic with postprocess_no_heuristic() 3,732 identical
  • In the slider baseline, the change repairs both histogram OtherMismatch cases. f90a465…-e38b652… stays a likely slider-only mismatch for Myers and histogram, before and after this change.
  • A first version also diffed again for Myers. That made 2 Myers cases of the slider baseline differ from Git (5d3fdb8…-82dfeab… and bd2c392…-31a191f…), which is why the flag exists. No small input shows this, and the smallest the agent found has 9 and 522 lines, so there is no test for it here. It can be added as a fixture if wanted.
  • cargo fmt --check passes, and cargo clippy -p gix-imara-diff --all-targets has no warnings for this change.

Timing, best of 5 runs of Diff::compute() with postprocess_lines(), release build, one machine, two rounds: a 10 MB input takes 22.5-22.6 ms before and 23.8 ms after. A 50 MB input with many repeated lines takes 155.7-156.0 ms before and 165.6-166.4 ms after.

Not tested: Git versions other than 2.55.0, other platforms than Linux, and just test for the whole workspace.

The histogram diff and its postprocessing differed from Git's `xdiff/` in four steps,
so hunks could differ from `git diff --histogram` for the same input:

1. After a match, skip later occurrences of its first line up to the end of the match in
   the old file, like `xdiff/xhistogram.c`. The comparison used the end in the new file.
2. Accept lines with up to 64 occurrences as anchors, like Git, instead of 63. The list
   pool needs one more size class to hold `MAX_CHAIN_LEN + 1` positions.
3. Don't strip the common prefix and suffix before a histogram diff. Git doesn't, and
   stripping changes which lines histogram anchors.
4. Diff a change group again with Myers if it moved while sliding and the group in the
   other file isn't empty, for histogram diffs only, as Git 2.54 does in
   `xdl_change_compact()`.

`make_histogram_baseline.sh` has one case for each step, and its reverse. The tests
compare the hunks with Git's, with and without the indent heuristic. Each case fails
without its step.

The motivation is Diffy (https://github.com/daniel-kindl/diffy), a review app that stores
comments at hunk positions and needs hunks identical to `git diff --histogram`.
Myers sizes its occurrence counts by the largest token. The re-diff of a shifted
histogram group passed the tokens of the whole input, so each group allocated and
cleared counts for the whole vocabulary: O(groups × vocabulary) work in postprocessing.

Number the tokens of the two groups from zero instead, in reused buffers. Like Git's
`xdl_fall_back_diff()`, which prepares the two groups as separate files, the counts
still cover only the tokens of the groups, so the hunks don't change.

With 1,000 shifted groups after 100,000 unique unchanged lines, postprocessing
allocated 1.6 GB and took 10 ms. It now allocates 68 KB and takes 0.38 ms, where the
parent of the histogram change takes 0.20 ms.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-25T11:34:51.523081Z aca67aa PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Dangerous meat-proxy teritorry, where where I have no clue what is really going on and throw more tokens at
it to compensate. Let's hope tests and performance checks and auto-reviews help.

# Round 1

- [P1] Skip histogram match seeds that occur more than 65 times — gix-imara-diff/src/histogram.rs:14-14
  `ListHandle::push()` caps the reported count at 65, which still passes
`LcsSearch`’s initial cutoff. Git skips seeds that occur more than 65 times.
With one token per line, diffing `B×4 A A B A B×61` to `B A B A` now reports an
added `A`, while main and the supplied Git report only deletions. Track count
overflow separately from the stored positions and add this case to the Git
comparison
- [P2] Avoid rescanning long unchanged tails on every split — gix-imara-diff/src/lib.rs:275-276
  When small edits separated by unique matching lines precede a long repetitive
suffix, `Histogram::run()` rebuilds and scans the histogram over that same
suffix on every split, even though the repeated line cannot beat the rarer
anchor. In an optimized build, 1,001 one-line replacements before an unchanged
500,000-line repetitive suffix went from about 3 ms on main to 600 ms with
identical hunks. Reuse occurrence data across splits or retain the trimmed path
for callers that do not require exact Git placement.
- [P2] Discard oversized token maps before re-diffing small groups — gix-imara-diff/src/postprocess.rs:223-223
  `HashMap::clear()` resets every retained bucket, so one large shifted group
makes every later small group pay for the largest group's map. With roughly
400,000 distinct tokens in the first group and 5,000 small groups afterward,
postprocessing took about 45 ms versus 10 ms when the oversized map was
discarded, with identical hunks. Drop or shrink the map when its capacity is
much larger than the current pair of groups.
- [P3] Gate only the re-diff fixture on Git 2.54 — gix-imara-diff/tests/integration/main.rs:895-899
  On Git older than 2.54, there is no fixture archive to fall back to, so all
four tests return success without computing a diff. Only `rediff-after-slide`
needs the 2.54 behavior; the other three fixtures produce the same hunks with
Git’s re-diff step disabled, in both directions and with both heuristics. Split
the version-dependent case out so the other regressions still run against older Git

# Round 2
- [P2] Preserve Git's common-tail trimming for histogram blame — gix-imara-diff/src/lib.rs:276-276
  With histogram blame, inserting `b` at line 3 of a file containing
`b` followed by 513 `a` lines now credits the unchanged `a` on line 4 to
the inserting commit. Both main and `git blame` credit the parent. Git's
zero-context `xdi_diff()` trims common 1 KiB tail blocks, while `gix-blame`
now diffs the full blobs. Apply Git's trim at the blame boundary rather
than restoring it for all histogram diffs, and add a `git blame` comparison.
- [P2] Count histogram edits after postprocessing — gix-imara-diff/src/postprocess.rs:155-159
  For the new `rediff-after-slide` fixture, `Platform::line_counts()` now
reports three insertions and three removals, while `Platform::lines()` and Git's
`--numstat` report two of each, as main did. Re-diffing can clear change flags,
but `line_counts()` and the query engine's direct counts still read them before
postprocessing. Use the same postprocessed histogram diff for those statistics
and check the counts against Git.
- [P2] Avoid rescanning unchanged tails with multiple frequent tokens — gix-imara-diff/src/histogram.rs:95-98
  The single-token shortcut doesn't help when an unchanged suffix alternates
between two frequent lines, so each split rebuilds the histogram and scans that
suffix again even though neither line can seed a match. In an optimized build,
1,001 replacements separated by unique anchors before a 500,000-line alternating
suffix took about 0.9 seconds versus 3 milliseconds on main, with identical
hunks. Reuse occurrence data across splits or extend the shortcut to suffixes
whose tokens all exceed the seed limit.

# Round 3

- [P2] Reuse histogram data for mixed-frequency common suffixes — gix-imara-diff/src/histogram.rs:92-93
  Two blank lines at the end of a long repetitive suffix defeat the cache:
`FrequentTail::find()` only caches suffixes where every token occurs at
least 66 times. The histogram then rescans the unchanged suffix at every
split. In a release build, 1,002 one-line replacements separated by unique
matching lines before 500,000 shared `x` lines and two blanks took about 600
ms versus 2 ms on main, with identical edit counts. Reuse occurrence data
for mixed-frequency suffixes and verify that hunk placement still matches Git.

Assisted-by: GPT 6.2 Sol
Co-authored-by: GPT 6.2 Sol <codex@openai.com>
… splits

Another case of extreme meat-proxying - assuming the tests cover everything.

<!-- agent -->
An unchanged tail of distinct pairs could defeat the cache because each token
occurred below the seed limit. The histogram rebuilt and searched that tail
at each split even after a unique prefix anchor made the tail ineligible.

Index the common suffix once after the first split and retain candidate order
with a forward cursor for each occurrence count. Clip occurrences as the
active range shrinks and combine suffix and prefix counts before trying seeds.

With 1,000 edits before 500,000 paired lines, release compute time fell from
1.19 s to 8.7 ms. The paired and overlapping-tail fixtures matched the Git
checkout's hunks, as did 30,988 differential comparisons. The affected
crate tests passed.

Assisted-by: GPT 6.2 Sol
Co-authored-by: GPT 6.2 Sol <codex@openai.com>
Meat-proxy rubber stamp. I have no idea if this is good or not, and it would
take too long to try to find out.
Given everything, I'd think it's good, and the performance numbers certainly
speak very clearly. Most importantly I hope that this algorithm is very resistent
against adversarial input, as it's used when encountering repos with
reduced trust.

<!-- agent -->
A changed or appended final line could leave a long shared block outside
common-suffix alignment, forcing the histogram to scan it at every split.
Index the largest common block after the first match, checking alignment
at both ends. Keep the original before occurrence counts and search order
across the block and the surrounding lines. Account for overlap when every
eligible cached token also occurs outside the block. Keep the uncached
search on the direct occurrence path and reuse the seed count for lookup.

Add a `histogram` Criterion target in `gix-diff` covering source-like edits,
dense and sparse replacements, paired and repetitive tails, overlapping
tokens, terminal edits, and re-diffing a large shifted group followed by
small groups. Fixture setup and correctness checks are outside timing.

On the 50,000-line controls, replacing the final line took 0.47 ms and
appending one took 0.54 ms. On `main` those cases took 9.92 and 9.77 ms.
The overlapping tail fell from 8.15 ms on `28731f5` to 1.14 ms, and the
dense edits without a shared tail fell from 13.96 to 8.74 ms. `main` took
0.86 and 7.47 ms respectively. The 250,000-line paired tail took 3.07 ms
with Git-compatible seed counts and 0.56 ms on `main` with common-end
trimming.

### In-process comparison with Git

On arm64 macOS, a runner linked to Git `f7de81456940` called
`xdl_do_histogram_diff()` on prepared records and `xdl_diff()` on resident
file bytes. Gitoxide ran the equivalent pre-interned histogram and full
diff on the same inputs. Full-diff timing includes line classification,
change compaction, and hunk collection. Both timers exclude file reads,
process launch, and patch formatting. Each number is the median of nine
iterations, in milliseconds. All 12 cases matched exact hunk ranges.

| Workload | Git histogram | Gitoxide histogram | Git full diff | Gitoxide full diff |
|---|---:|---:|---:|---:|
| Source-like edits, 2,048 functions | 1.98 | **0.96** | 2.24 | **1.20** |
| Sparse edits without a shared tail, 8,192 lines | 0.18 | **0.08** | 0.30 | **0.21** |
| Dense edits without a shared tail, 4,000 lines | 17.10 | **9.20** | 17.09 | **9.27** |
| Paired shared tail, 125,000 lines | 84.83 | **1.25** | 87.62 | **3.42** |
| Paired shared tail, 250,000 lines | 337.19 | **3.11** | 341.82 | **7.84** |
| Paired block before a changed final line, 50,000 lines | 17.79 | **0.47** | 18.47 | **1.31** |
| Paired block before an appended line, 50,000 lines | 17.72 | **0.56** | 18.64 | **1.41** |
| Alternating shared tail, 250,000 lines | 344.14 | **2.33** | 346.78 | **5.94** |
| Mixed-frequency shared tail, 250,000 lines | 379.87 | **3.00** | 383.24 | **6.46** |
| Overlapping tail, 25,000 lines | 7.52 | **1.14** | 8.15 | **1.79** |
| Overlapping tail, 50,000 lines | 15.24 | **2.26** | 16.46 | **3.60** |
| Large shifted group followed by 1,000 small ones | 8.72 | **4.99** | 12.05 | **9.62** |

Check the block boundaries, clipping, and shifted alignment against Git
`f7de8145694`. Match exact hunks on 12,370 Git comparisons and preserve the
previous hunks on 150,000 generated pairs, both raw and postprocessed.

Assisted-by: GPT 6.2 Sol
Assisted-by: GPT 6.1 Sol
@Byron
Sebastian Thiel (Byron) merged commit 2bcb31d into GitoxideLabs:main Nov 25, 2026
47 of 54 checks passed
Daniel Kindl (daniel-kindl) added a commit to daniel-kindl/diffy that referenced this pull request Nov 25, 2026
Closes #37

## Summary

- Records the result of Q62 in `docs/maps/diffy-v0.1.md`. gitoxide
merged the Q60 patch in GitoxideLabs/gitoxide#3246, with three
maintainer commits. No gix-imara-diff release has the fix yet, so the
Q61 copy stays.
- Adds three notes: the merge and the maintainer commits, the newest
crates.io version, and an input where the Q60 copy differs from Git.
- Removes Q62 from the open questions. Adds Q68 (owner): what the
patched copy holds until a release. `Next` stays Q48.
- No ADR. ADR 0002 already covers the copy and when Diffy drops it.

## Evidence

- The maintainer review found a seed limit case. Each line is one token:
`B` 4 times, `A A B A`, then `B` 61 times, against `B A B A`. On
2026-11-25, Diffy's Q60 copy removes 66 lines and adds 1. Git 2.55.0 and
gitoxide `2bcb31d` remove 65 lines and add none, with the same hunks.
- `node scripts/check-maps.mjs`, `check-context.mjs` and
`check-adrs.mjs` pass on a clean clone. `check-dashes.mjs` passes, and
`check-writing.mjs` has 0 warnings.
- Observability: none. The change is documentation only.

## Risk and rollback

Low. The change is documentation only. Revert the commit to roll back.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants