Repository navigation
fix(diff): stop reporting differing files as identical, and align by LCS - #3268
Conversation
Review round on fork PR #115 found the cap fallback untested: the existing wholesale-replacement test uses 2x2 = 4 cells, so it exercises lcs_ops, never the cap branch. Add a 2001x2001 fixture (> 4M cells) that forces the cap path and asserts every line reports as removed + added with line numbers from each line's own file. Fork-authored amendment on top of the upstream rtk-ai#3268 cherry-picks. Co-Authored-By: Claude Fable 5 <[email protected]>
fix(diff): byte-accurate identity and LCS alignment (adopt upstream rtk-ai#3268)
KuSh
left a comment
There was a problem hiding this comment.
Requesting changes. #2668 made the same fix independently and is now closed as a duplicate of this one, chiefly because you bounded the DP table and it didn't — credit to @guyoron1 for that implementation and its cascade regression tests, which are worth borrowing from.
What's verified as correct: the byte-equality guard is the right fix for the reported [ok] Files are identical bug and correctly precedes any lines() call; the prefix/suffix trim plus LCS is a real improvement over positional compare; lcs_ops's u32 table cannot overflow (LCS length ≤ min(n,m) ≤ 4M); the unreachable! arms in ops_to_changes genuinely are unreachable given the run-splitting; and there are no callers of compute_diff/render_file_diff outside this file, so the blast radius is limited to rtk diff <f1> <f2>. cargo clippy --all-targets --all-features and all 32 diff_cmd tests pass.
The cascade bug you're fixing is worse in production than the issue describes, which is why this matters: on a 40-line file with one line inserted, the positional compare marks everything after the insertion as modified, the render grows past the raw baseline, and never_worse discards it and prints both files in full — 0% savings on precisely the case the command exists for.
Four things to fix, all inline. Two housekeeping notes:
cargo fmt --checkfails on three hunks, though the PR body says it's clean: thenotes.push(format!("line endings: …"))(rustfmt collapses it to one line), theassert!(out.contains("trailing newline: present vs absent"), …)intest_render_trailing_newline_difference_is_not_identical(rustfmt expands it), and thelet plain: String = (0..200).map(…).collect();intest_render_partial_crlf_matches_reported_repro.- #3519 touches the same
changes.is_empty()block, adding the same byte-equality guard scoped to just that fix, so the two will conflict textually. Your version names the actual cause rather than saying "whitespace or line endings" generically, which is the better message — just expect a rebase depending on which lands first.
|
Thanks for the repros — all four are fixed in 354202b, and the run-pairing one was worse than I'd have found on my own. Pairing across matched regions. Your diagnosis is exact: matched lines emitted no
The The cap branch. Your two design notes convinced me to change the branch rather than just test it. It returns counts only now, behind an
Credit noted to @guyoron1 for #2668. I haven't pulled its cascade regression tests across yet — happy to if you'd like them here rather than kept with that PR. |
KuSh
left a comment
There was a problem hiding this comment.
Re-reviewed after 354202b. All four earlier threads are genuinely fixed — I re-ran each original repro against the branch rather than reading the diff, and cargo test --bin rtk diff_cmd is 39/39 with cargo fmt --all --check and cargo clippy --all-targets clean. Those threads are resolved.
Requesting changes on one new issue, which I think is blocking: the cell cap keys off the size of the changed region rather than the amount of change, so it fires on ordinary medium files and then prints add/remove counts that are not true. It also regresses a case develop currently gets right. Details inline, along with a memory/latency note and two small ones.
KuSh
left a comment
There was a problem hiding this comment.
Re-reviewed after 06fb327. Replacing the LCS table with Myers was the right call rather than patching the cap — it dissolves the root cause instead of tuning around it, and all five earlier threads are genuinely fixed. I resolved them.
I also property-tested the new aligner rather than reading it, since it's a large hand-rolled algorithm: 40,000 random pairs where the emitted script must reconstruct file2 exactly and every line number must name the text it claims, plus 4,000 pairs checked for minimality against a brute-force LCS. Zero failures on all four properties. cargo fmt --all --check and cargo clippy --all-targets clean, 38/38 tests pass, and the perf numbers in the commit message reproduce (10.7 µs where the old table took 7.1 ms).
Requesting changes on two things, both around the new cap. The first is a message that states something false; the second is a capability regression against develop in a common case. The remaining three are non-blocking, and two of them are consequences of my own earlier review comments — noted as such inline.
One non-code item: the PR description still documents the LCS design — LCS_CELL_CAP, the (n + 1) * (m + 1) bound, 16MB, and tests "at 2001 x 2001" and "the lopsided 2,000,000 x 2 shape". None of that is in the branch any more, and those two tests no longer exist. Worth rewriting before merge so the commit message doesn't document an implementation that isn't there.
|
Thanks for re-running each repro rather than reading the diff — that caught the cap keying off the wrong thing, which I would not have found from the code. Nothing left open on my side. The PR description is rewritten: it still described the LCS table and the region-size counts, so it now covers Myers, the edit-distance cap, and the measured time and memory. |
|
Thanks for property-testing the aligner — 40,000 random pairs is a much better check than I could have written for it, and the three deleted tests were a genuine miss on my part. All five addressed in 819a971. The message. Both halves were wrong and you named why. The cliff. Fixed, and it no longer exists for the shape you named. Measured on 10,000-line files with in-place rewrites: I took your second option but not your reasoning for it. Equal lengths do not make a shift impossible — That is the difference between a non-minimal diff and a misleading one, and it is why I did not want to fall through to it silently. I did not take option 1 as the primary fix, because A cost in my own fallback, which I would rather you did not have to find. Unbounded, it built a change list the size of both files: two wholly different 100,000-line files gave 42MB and 200,002 output lines. Counting the differing positions first costs one pass and no allocation, and past 5,000 of them the exact count beats the list. Same pair now: 14MB and 2 lines, where the remaining 14MB is the cost of reading both files at all — The count is exact there, so that message states no span at all. The guard. Bounded rather than left as-is: the bypass now spends at most Reference frames. The header names them when the output actually mixes them: It only appears when both an addition and a removal are present, so The three tests. Restored verbatim; they still pass. You are right that they cover PR description. Already rewritten before your review landed — no
|
KuSh
left a comment
There was a problem hiding this comment.
Re-reviewed after 819a971. All five earlier threads are fixed and resolved — the cliff is genuinely gone (I re-measured 249 / 251 / 400 / 1000 / 4999 rewrites on 10,000-line files: every one names every changed line), the over-cap message's two halves now agree, the guard exception is bounded and documented in guard.rs rather than silent, the frame legend is gated correctly, and the three regression tests are back with their original payloads. The PR body no longer describes the LCS design. cargo fmt --all --check and cargo clippy --all-targets clean, 2524 tests pass.
I property-tested the new positional fallback rather than taking its comment's word: 2,000 forced past-cap equal-length pairs checking that the change list reconstructs file2, that every line number names the text it claims on the correct side, and that the counters match the list — zero failures. Re-ran the Myers properties after the isize → i32 change (40,000 pairs, including minimality against a brute-force LCS) — also zero.
Requesting changes on one regression the Myers rewrite introduced and has carried since 06fb327: a pure insertion or deletion larger than the cap is refused even though aligning it is trivial. lcs_ops had an n == 0 || m == 0 short-circuit and myers_ops does not, so appending a chunk of lines — or diffing an empty file against a populated one — now produces a message saying hundreds of lines differ when none do, and lists nothing. Both develop and the intermediate LCS revision handled that case correctly.
The rest are smaller. Two of them are unhandled corners of fixes I asked for last round, marked as such inline — the fixes were right, these are just cases they don't cover yet.
|
Two things an adversarial pass turned up after your review, both fixed in A near-pure insertion was still refused. A retained line inside the changed region keeps the prefix/suffix trim from emptying either side, so the short-circuit in The cap is on the Myers trace now, counted in cells, and each round records only the diagonals that could still be on an optimal path: reaching Since the banded window changes how the trace is indexed, and that is the part you property-tested, the properties are in the suite now: 4,000 random pairs whose script must reconstruct file2 with every line number naming the text it claims, and 2,000 checked for minimality against a brute-force LCS. Both were needed — an off-by-one in the per-round base produces a plausible script that no hand-written case catches.
Perf against your table, release, peak RSS above
|
KuSh
left a comment
There was a problem hiding this comment.
Re-reviewed after 29c49ca. All five earlier threads are fixed and resolved.
Moving the cap from edit distance to trace cells with a banded diagonal window is the right generalisation, and I want to credit the two issues your own adversarial pass caught that neither I nor my tooling did: the near-pure insertion with a retained line inside the changed region (which my suggested empty-side short-circuit would not have covered), and POSITIONAL_CHANGE_CAP bounding count but not bytes at 308MB RSS. Both are better catches than the finding they came from.
The band is the part I scrutinised hardest, since a wrong band returns non-minimal scripts silently rather than failing loudly. The derivation holds — reaching k at round d costs (d + k) / 2 deletions and (d - k) / 2 insertions, so k in [max(-d, d - 2m), min(d, 2n - d)] cannot drop an optimal path — and I property-tested it across 150,000 random pairs in five shape profiles (balanced, 1xN, Nx1, 2-symbol alphabet, 20-symbol alphabet), each checked for exact reconstruction of file2, per-side line-number anchoring, and minimality against a brute-force LCS. Zero failures on all three properties in all five profiles. cargo fmt --all --check and cargo clippy --all-targets clean, 2535 tests pass.
Four findings, none in the aligner itself. Two are corners of fixes I asked for in earlier rounds and are marked as such. One of them is a miss on my part rather than yours: I verified last round's cliff fix with a density sweep at equal lengths and reported it clean without checking the unequal-length path, which is where it still bites.
KuSh
left a comment
There was a problem hiding this comment.
Re-reviewed after 48ea2a4. All four earlier threads are fixed and resolved — script_too_large bounds the aligned listing, the parity-packed trace plus the doubled MAX_TRACE_CELLS moves the equal-length threshold from 353 to 706 rewritten lines and lets unequal-length pairs list instead of refusing, the legend gate is the condition I asked for, and guard.rs now describes the bound it actually keeps.
Dropping the unread parity from every snapshot is a genuinely good catch — a round computes one parity and the backtrack reads the other, so half of each snapshot was dead weight, and it buys 1.41x of reach before the constant is touched at all. I re-property-tested the packed trace across 210,000 random pairs in seven shape profiles (balanced, 1xN, Nx1, 1x120, 2-symbol alphabet, 24-symbol alphabet, near-identical), each checked for exact reconstruction of file2, per-side line-number anchoring, and minimality against a brute-force LCS. Zero failures on all three properties in all seven. On the branch, cargo fmt --all --check and cargo clippy --all-targets are clean, 2542 tests pass, and the pair that fills the new budget costs 5.3ms and +3.8MB peak RSS.
"On the branch" is the caveat, and it is the blocking finding: this no longer merges with upstream/develop, and the conflict is semantic rather than textual. Details inline. The other four are smaller, and one of them is a miss of mine from the last round.
A note on the aligner itself: I have now property-tested it across five separate revisions of this PR and it has never failed one. The findings below are all in the code around it.
48ea2a4 to
ecef036
Compare
|
Rebased onto 1 — semantic conflict with #3048 (blocking). Both breakages needed a decision, and I took the stronger option on each. Empty For the pairing, I didn't teach 2 — 3 — 4 — cost grows with 5 — the legend, and yours to own only in part; I wrote the string. It now names the markers present: One thing outside this PR. |
KuSh
left a comment
There was a problem hiding this comment.
Re-reviewed after ecef036. All five threads from the last round are fixed and resolved — the rebase closed both semantic breakages properly (FileComparison for the identity signal, Replaced for the classic grouping, verified byte-identical to diff on the insertion-shift case), the count budget moved ahead of the backtrack, the cap and its docstring now agree, the legend names the frames present, and the PR body documents the O(N) regime. I re-property-tested the aligner after the reshape: 180,000 random pairs across six profiles, checked for exact reconstruction, both-frame anchoring and minimality against a brute-force LCS. Zero failures.
Requesting changes on six things. Three are measurements I ran on the rendering strategy rather than defects in it — I went looking for whether rtk diff beats diff on the diffs an agent actually produces, and the answer is currently no. Three are memory and CI findings, two of them new.
The headline number: on 120 agent-typical diffs (40-600 line files, 1-15 edits) the condensed render is +32.1% against GNU diff, larger in 120 of 120 cases. never_worse therefore falls back essentially always, so what ships is the classic renderer at +0.3% — a reimplementation of diff that is marginally worse than diff.
But the per-line format is not the problem. Strip the four lines of framing and the same render is -6.7%, smaller in 119 of 120. ~ 21 old → new genuinely beats 21c22 / <old / --- / >new; the render then spends that saving five times over on a header, a counts line, a blank and a legend. That is a good position to be in, and the first comment below is where the tokens are.
I also checked whether some other format would be better, since a smaller fallback is a harder baseline to beat: it would not. Among patch-applicable formats that show both sides, GNU normal is already the optimum — unified -U0 headerless is +9.7%, unified -U0 +47.3%, context -C0 +93.1% and only applies 50/120, RCS -n never applies at all. Only an ed script beats it (-46.2%), by dropping the deleted text entirely, which is disqualifying for something an agent reads.
Reproduction details are in each comment; happy to share the harnesses.
fix(diff): refresh adoption of upstream rtk-ai#3268 — Myers alignment, FileComparison, listing budgets
acbe88c replaces the early snapshot ce07aff/54cb3a1 of the same upstream PR, and 7753ec7 is a test-only clippy amendment to it. Recorded in HEALED_SHAS so the delta advertises the fix once (60 -> 57). Co-Authored-By: Claude Fable 5.1 <[email protected]>
1ac2dbc to
0736b59
Compare
|
Force-pushed: rebased onto current
The Adopted fmt, clippy |
KuSh
left a comment
There was a problem hiding this comment.
Verified 0736b598 in a clean worktree, and separately merged onto the current develop tip, which is 37 commits ahead of this branch's base. Clean merge both ways: cargo fmt --all --check and cargo clippy --all-targets clean, 3098 tests on the branch and 3153 on the merge. The stale-base problem from the last round is gone — the branch builds on its own now.
The clippy blocker is fixed and I have resolved that thread.
The other five threads from my last review all still reproduce on this head, unchanged. Two of them reproduce bit-for-bit — the chrome overhead is still +32.1% against diff and smaller in 0/120 agent-typical diffs, and the classic fallback is still +0.3% and divergent in 23/120. I have left those open rather than repeating them here.
One new finding, and it is a regression against develop rather than a pre-existing gap. It is also downstream of something I asked for, so the first comment says so.
develop now carries the byte-equality verdict (0cb34ac, 428af61), so this branch no longer argues for it. The alignment fix and the reporting that depends on it remain. compute_diff compared line N to line N, so a single inserted or deleted line reported every line after it as modified. This aligns by Myers' greedy edit script, so one insertion reads as one insertion. The script folds into hunks, one per run of differing lines with no matched line between. Both renderers group by hunk: the classic fallback prints one NcM per region, as diff does, because the classic format cannot express which old line became which new line, and rendering the pairing split a region into an NcM plus a trailing NaM that diff never prints. Inside a hunk the condensed render pairs old and new lines by best similarity rather than by position, so an insertion at the head of a run no longer shifts every pairing after it into a rewrite that did not happen. Op::Keep carries a run length. One entry per matched line made the script scale with the file rather than with the change, 45MB of separators for a million-line pair with 700 rewrites. The aligner's trace is one flat vector with each round's bookkeeping stored inline, so MAX_TRACE_CELLS charges what is allocated: a per-round Vec cost 5.8x the cells being counted on a lopsided pair. The bool develop passes into render_diff cannot express the third case the aligner produces, a comparison that ran and then refused to build a listing because it would cost more than the raw text. FileComparison replaces the bool with Identical, InvisibleDifference and Lines, and DiffResult::unaligned carries the refusal reason. An empty change list is not a synonym for identical, and routing a refusal through the identical branch exits 0 on files that differ. The invisible-difference message keeps develop's wording, so the phrase diff_byte_accuracy_test matches on survives, and then names the measured cause instead of stopping at "no line-content change". It is shown whenever the case arises. A fixed token allowance above raw could not be met: the message's shortest form is ~20 tokens and a one-line pair ~2, so the ceiling sat under the message's floor and dropped it on 90% of one-line pairs, printing the two indistinguishable blobs it exists to replace. The render drops the file-pair header and the blank line, names the files in the frame legend by argument position instead of by path, and prints the counts line only once the listing runs to a screenful. On 120 agent-sized diffs the framing cost more than the change list saved: the body alone is 7% smaller than diff, and each line of chrome erased that.
0736b59 to
d4239ec
Compare
KuSh
left a comment
There was a problem hiding this comment.
Re-reviewed d4239ec in a clean worktree and verified every one of the seven resolutions independently. They all hold up:
chrome +32.1% → -2.0% vs GNU diff; smaller in 54/120 (was 0/120)
classic grouping 23/120 divergent → 7/120
Op::Keep 1,000,700 ops → 2,100; 51MB → 5MB RSS
trace accounting 1v100k 6→2MB; 1v333k 20→6MB, now bails at Err(200000)
invisible difference 4/5 lost → 0/5; the allowance mechanism is gone entirely
pairing 99.7% precision over 12,520 ground-truth rewrites
Two notes on my own comments rather than yours. You were right that my value = 1 / value = 9 repro is a genuine tie — both score 0.778, identical character sets differing by one digit — so no similarity-first rule separates them; I confirmed that and the rule change is real on a non-tie. And your "byte-identical in 120/120" does not quite generalise: I get 7 divergences, but all seven apply cleanly under patch, all seven have the same edit-line count as GNU, and all seven are the blank-line-heavy cases. That is LCS tie-breaking where several equally-minimal alignments exist, not a grouping bug, so I am not reopening it.
Gates clean on the branch and on a merge onto the current develop tip, which is 37 commits ahead of this branch's base: fmt, clippy, 3269 tests.
One new finding, and it is a consequence of the pairing rule I asked for. I prototyped three fixes and fuzzed all of them before writing it up; the numbers are in the comment. Two smaller ones below that.
…he cap a refusal hit `pair_rewrites` pairs by similarity, so two similar lines swapped and both edited pair crosswise. The condensed render listed them in file1 order with one number each, which read as two in-place edits and described a file2 that does not exist: `timeout = 60` rendered onto line 2, where `retries = 5` is. A crossed hunk now renders each `~` as `~ N→M`. A hunk that only shifted keeps the single number, since order already says where the new text goes, so output size is unchanged outside a crossing. A refusal by `POSITIONAL_BYTE_CAP` reached the count refusal's wording, so two 3MB single-line files reported "1 lines ... too many to list". Both `Unaligned` refusal variants carry which cap they hit, and the render names it: the byte form states the size of the text it declined to list. Tests: the crossed render as an exact string beside the shifted-only form, a property that rebuilds file2 from the condensed listing over 3,000 random similar-line pairs, and both byte refusal messages as exact strings.
KuSh
left a comment
There was a problem hiding this comment.
Round 9. Verified the two findings you fixed by running their repros against the release binary, and built d4239ec alongside to diff behaviour rather than read the diff.
Both hold. The crossed render is correct where it appears — ~ 151→197 / ~ 152→196 check against the real file — and rebuilding file2 from the rendered text over 199,828 aligned diffs gives 9,991 crossed renders and 0 mismatches. The byte refusal now names the cap and fixes the plural. Behaviour diff against d4239ec on 120 agent-typical diffs, regenerated with reorders so crossings are in the corpus: 0 output changes, 0 exit-code mismatches, identical bytes — which confirms "output size is unchanged outside a crossing". Both threads resolved.
Gates clean on the branch and merged onto the current develop tip, now 49 commits ahead of this branch's base: fmt, clippy, 3285 tests.
One blocking finding, which this push introduced, and two notes. One hypothesis I chased and dropped is recorded on the crossing thread so it does not get re-derived next round.
…sal claiming non-membership `~ N→M` carries both files' numbering, but the legend still called `~` a file1 marker, and gating the note on `diff.added` dropped it from a deletions-plus- crossing render entirely: two frames on screen, nothing saying so. The legend now keys on the shapes actually listed. A crossed `~` earns its own clause, `~ N→M spans both files`, owed whether or not a `+` is present, which also tells the two `~` shapes apart when one listing carries both and nothing in the markers does. The `EditScript` refusal said "only in a.txt: 1 line, only in b.txt: 1 line" for two 1.1MB minified files differing by one character. Those counts are pre-pairing, so the two lines would have rendered as a single `~`; "only in" is a claim about content and it was false in both halves. It now reads "1 line changed in a.txt, 1 line changed in b.txt", which states what is known without pairing them. Tests: the crossed render asserts through `render_diff` rather than `format_diff_changes`, which is where the legend is composed and why the inconsistency shipped green. `render_file_diff`'s docstring states that rule for render-shape assertions so the next one lands at the right level. New cases cover the legend for a crossing beside deletions, beside insertions, and beside a plain `~`.
rtk-ai#3788 rewrote the piped-stream half of diff_cmd.rs (condense_stdin, condense_unified_diff_strict) while this branch rewrote the file-versus-file half (Hunk, compute_diff, the renderers). The two conflicts are positional: both sides add code at the same offset. Resolved as a union -- develop's imports plus this branch's, and both blocks kept whole. Co-Authored-By: Claude Opus 5 <[email protected]>
There was a problem hiding this comment.
Round 10 (landing) — APPROVED, one follow-up filed
Claim: stop reporting byte-differing files as identical, and align the two sides by LCS rather than by position.
Scope: accept. (Stated now — rounds 1–9 predate the current template; frozen from here.)
Ran: round 9's repros against a build of 501dd01 merged onto develop; a mutation of frame_legend back to the round-9 bug; the conflict resolution with full gates; savings against develop on the same pairs.
Blocks merge (0 — cleared)
Round 9's blocking finding is fixed, verified by running it rather than reading the diff. Same shape, same header as the round-9 transcript:
+45 added, -0 removed, ~2 modified
(+ = file 2; ~ N→M spans both files) was: (~ = file 1; + = file 2)
~ 151→190 timeout = 30 → timeout = 60
And the direction where it went missing entirely — deletions plus a crossing, no + on screen:
+0 added, -45 removed, ~2 modified
(- = file 1; ~ N→M spans both files) was: no legend at all
Keying on the shapes listed rather than on diff.added is the right fix, and crossed_modified() is what makes the two ~ clauses separable.
Checked and correct — no need to re-verify
- The legend is now pinned where it is composed. Reverting
frame_legendto the round-9 behaviour (modified > 0instead ofmodified > crossed, and the crossing clause gated onadded > 0) fails three tests:test_render_crossed_pairing_carries_file2_line_numbers,test_render_frame_legend_names_the_crossed_shape,test_render_frame_legend_separates_the_two_modified_shapes. That closes the note about assertions sitting belowrender_diff— a regression to this exact bug can no longer ship green. - The byte refusal no longer claims non-membership: two 1.1MB single-line files give
1 line changed in m1.txt, 1 line changed in m2.txt; 2.2MB of text, too large to list. The asymmetric wording holds too. - Savings improve sharply against
develop. On the five pairs used above,developemits 16584 bytes against a 3478-byte raw diff (−377%: it dumps both files, thenever_worseinversion this PR exists to fix); this branch emits 3342 (+3.9%). Adversarial corpus, so the absolute number is not a traffic estimate — the direction is the point. - Gates on the merge with current
develop, not just on the branch: fmt clean, clippy clean,cargo test --all3424 passing, 0 failed.
Filed as follow-up
- #3926 — the
InvisibleDifferencegap at:73. It is reached only whenhunks.is_empty(), so a CRLF or trailing-newline difference coexisting with a line change still goes unmentioned. Re-ran on this head: rtk prints2c2 beta → gammawhere GNU prints1,2c1,2plus\ No newline at end of file.developgates on the same condition, so this PR leaves it open rather than introducing it, and the thread asked for an issue rather than a change here.
Your questions
None open — all three replies on 501dd01 were fixes rather than questions, and each is verified above.
Next
One mechanical merge and this lands. #3788 rewrote the piped-stream half of diff_cmd.rs (condense_stdin, condense_unified_diff_strict) while this branch rewrote the file-versus-file half (Hunk, compute_diff, the renderers), so both conflicts are positional — two insertions at one offset. Resolved as a union with nothing dropped from either side, and that is where the gates above were run.
Approving on the content
Rounds: landing (10 posted; budget is 3 — the overrun is on the review side, not yours). Threads: 0 open, 4 resolved this round.
chore(sync): Conflicted Sync of upstream/develop 2026-09-07 (42 commits), re-adopt rtk-ai#3268 head
…conflict Conflicted Sync of upstream/develop f749546 (dev-0.49.0-rc.416). One conflict, src/cmds/git/diff_cmd.rs: upstream merged its PR rtk-ai#3268 (9512e1a) with one round the fork's cherry-picks 8ca2e0e/091e4a5 lacked (501dd01). Upstream's file taken verbatim; the fork's two cherry-picks are superseded. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…perseded rtk-ai#3268 cherry-picks Upstream merged its PR rtk-ai#3268 (9512e1a) with the legend round 501dd01 the fork lacked. 091e4a5 heals by patch-id; 8ca2e0e gets a HEALED_SHAS entry (adjacency resolution changed its patch-id). Fork delta: 49 fixes. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Two defects in
src/cmds/git/diff_cmd.rs, both reachable from a plainrtk diff a b.1.
[ok] Files are identical— and exit 0 — for files that differrtk diff <f1> <f2>never runsdiff. It reads both files, reimplements the comparison, and fabricates the exit code itself, so there is no child process whose status could be propagated. Identity is then decided fromstr::lines():str::lines()strips a trailing\rand treats the final newline as optional, so any difference it normalizes away — CRLF vs LF, or a missing trailing newline — yields "identical", exit 0. Content differences were always caught correctly; this is specifically the invisible-difference case.That makes bare
diffunusable as a verification gate: a false "identical" silently passes a broken check.Reproduced with 200 lines, 25 of them given CRLF endings, text otherwise identical.
Fix: gate identity on byte equality before
lines()can normalize anything. When the bytes differ but the text matches, name the cause instead of rendering a change list of visually identical strings:That message opens with develop's wording, so the phrase
diff_byte_accuracy_testmatches on survives, and deliberately avoids the word "identical", so a reader grepping for it does not inherit the original bug.The cause is read from CRLF positions, not counts. Two files can hold the same number of CRLF terminators in different places, and reporting the counts there printed the same number on both sides, which reads as "no difference" to someone who was just told the files differ.
2.
compute_diffcompared positionally, so one insert desynchronized the restfor i in 0..max_len { lines1[i] vs lines2[i] }means a single inserted line makes every later pair compare unrelated lines. The whole tail renders as changed, and the output grows large enough that thenever_worseguard discards it and dumps both files concatenated.Measured on a 200-line file with one line inserted at the top: 403 lines of output before, 4 after.
Fix: trim the common prefix and suffix, then align the middle with Myers' greedy algorithm, which costs
O((n + m) * d)in the edit distance rather thanO(n * m)in the file size.The script folds into hunks: one per maximal run of edit steps with no matched line between them. The deletions in such a run are consecutive file1 lines and the insertions consecutive file2 lines whatever order the script interleaves them in, so the run's bounds are the hunk's.
Op::Keep(run)is the separator. Without it a deletion at line 1 and an insertion at line 41 were adjacent in the edit script even with 40 identical lines between them, and the run scanner paired them: sorting a three-line import block reporteduse zeta::A;as modified into itself, at a line number where file2 holds something else, with the add and remove counts zeroed.Keepcarries a run length rather than one entry per matched line, because one 48-byte entry per unchanged line made the script scale with the file rather than with the change — 45MB of separators for a million-line pair with 700 rewrites, invisible to every listing budget.Inside a hunk, old and new lines pair by best similarity, not position.
old[p]againstnew[p]was wrong whenever a run had unequal deletion and insertion counts: an insertion at the head of the run shifted every pairing after it, and the 0.5 threshold cannot repair a wrong pair because a rewritten line usually clears it against the line inserted beside it too. Candidates above the threshold are taken greedily by score, nearer the diagonal on ties, and the leftovers list as-and+. A character-set score cannot separatevalue = 9fromvalue = 2as rewrites ofvalue = 1— both score 0.78 — so that exact tie still resolves by position; the rule change fixes the cases where the scores differ. Hunks over 256 candidate cells pair by position, which ordinary diffs never reach.Line numbers come from each file:
-and~are numbered in file1,+in file2.A pure insertion or deletion needs no search at all. After trimming, one side is empty and the script is a single run, so it is built directly rather than handed to the aligner, which would spend its whole budget reaching the end of a trace it cannot use. Without that, appending 1000 lines to a 50-line file — or diffing an empty file against a populated one — reported hundreds of differing lines and listed none of them.
The cap is on the aligner's trace, counted in cells, not on the edit distance. An edit-distance cap refuses a pair whose alignment is trivial. A one-line file against a five-thousand-line one sharing a line in the middle has a minimal script of 4,999 insertions, so
d = 4999; the cap gave up and called it too different to align while develop's positional compare listed every addition. Diffing a small file against a large one is ordinary enough that the refusal was a capability regression, not a corner.Each round now records only the diagonals that could still be on an optimal path: reaching
kat rounddcosts(d + k) / 2deletions and(d - k) / 2insertions, and neither can exceed the side it consumes. On that lopsided pair the window is three diagonals wide however largedgrows, so the whole trace is ~15,000 cells and the alignment lands.Within that window only half of each snapshot is ever read. A round computes the diagonals of its own parity and the backtrack reads the opposite one, so the trace stores every other slot and the skipped ones are the ones the round is about to overwrite. Equal-length inputs get the full window, which is where the budget is spent:
MAX_TRACE_CELLS(1,000,000 cells, 4MB) bites atd = 1410, which is 705 scattered rewritten lines. A run of contiguous rewrites gets a narrower window and aligns further.The trace is one flat
Vec<i32>. Each round's record is its first diagonal, the snapshot, and the snapshot's length, so the backtrack walks records from the end and the budget charges exactly the cells stored. AVecper round cost 24 bytes of header plus an allocation each, which no budget saw: on a lopsided pair with a three-diagonal window the real peak was 5.8x the cells being counted (23MB at 333,000 rounds against a documented 4MB), and the whole trace was then discarded because the count check fired. One line against 333,000 now stops at round ~200,000 with the trace at 4MB.That constant is set against
POSITIONAL_CHANGE_CAPrather than in isolation. A rewritten line is one listed line and a replaced one is two, so the aligner tops out within a factor of 3 of the 5,000-line listing cap; an aligner that refuses an order of magnitude below what the listing path prints is a cliff, not a budget. Unequal lengths have no positional fallback, so the cliff was total there: 360 rewrites plus one insertion in a 2,000-line file listed nothing at all, and now names every change. The 4MB costs +3.4MB of measured peak RSS on the pair that fills it, and that search costs 7.0 ms user against 4.0 ms without it.An earlier revision capped the LCS table size, and that measures the trimmed middle: since the middle runs from the first differing line to the last, the trigger was "the edits are far apart" rather than "there is a lot of change". Two 2100-line files differing at only lines 5 and 2095 took the cap branch and reported
+2091 added, -2091 removed— the size of the changed region, presented as a count of changes. They align atd = 4and report two modifications at lines 5 and 2095.Past the budget there is no cliff for equal-length inputs: they pair by line position instead, which is a valid edit script there — it reconstructs file2 and every line number names the text it claims — and the render says the pairing is positional rather than presenting it as an alignment. Equal lengths do not make a shift impossible, so that label matters. On 10,000-line files, 250 through 4,999 rewrites all name every changed line.
All three listing paths are bounded by count and by bytes. A count says nothing about line length, and each listed line is cloned into an
Opand again into the render: five thousand ten-thousand-character lines sat insidePOSITIONAL_CHANGE_CAPand cost 308MB of RSS. Past either cap the exact count is reported instead — two wholly different 100,000-line files cost 16MB of peak RSS and 2 output lines, against 52MB, 1.9 s and 200,002 lines on master.The third path is the aligned one, and the band is what makes it reachable. While the cap sat on the edit distance a large script meant the aligner had already given up; a narrow window keeps the trace cheap while
dgrows instead. One line against a 60,000-line file sharing a line in the middle aligns and would build 59,999 changes, 11x the cap, from an input the empty-file case refuses at the same size for free.script_too_largeruns the same budget over the script before it becomes a change list, and states both sides rather than one figure, because the runs have not been paired at that point and a pairing turns two steps into either one~or one-plus one+. That pair goes from 60,003 output lines and 18.2MB to 2 lines and 15.4MB — the 60,003 were the raw concatenation, whichnever_worsehad already substituted for the whole build.For unequal lengths past the budget the branch states no count it has not computed. The floor is measured rather than derived from the constant: the aligner returns the round it gave up at, and every shorter script was tried and failed, so at least half that many lines differ. Where the differences sit is given as line bounds in each file, because the region between the first and the last is unrelated to how much changed inside it — 401 changed lines in a 100,000-line file span 79,801 of them, and a figure shaped like a count invites reading it as the amount of change.
Measured release-mode, peak RSS above a
diffon two one-line files, user time averaged over ten runs, because ~13 ms of the wall is process startup and tracking. The banded column was re-measured after the trace change; the LCS column is from the earlier revision:Every row but the last sits inside the <10 ms and <5MB budgets in CLAUDE.md, which the LCS table did not. On the 50MB pair the peak is the input:
runholds both files and builds arawconcatenation of them to feed the guard, which is ~200MB before the diff starts and which this PR does not change.Those rows are all 2,000-line files, and the ~7 ms figure above is the cost of a search that fills the trace budget, not the cost of
rtk diffin general. The bound is ond; the work is not. Each round scans the band and runs snakes across the input, so time grows with file length at a fixed change count. Measured release-mode on this branch, median of five runs, whole process including reading both files:Fewer changes costing more is not a measurement error: 700 rewrites sit inside
MAX_TRACE_CELLSand run the full search, while 1,300 exhaust it and fall through to the positional pairing, which is one pass. Both name every changed line.That is the price of an alignment that is correct, and the <10 ms in CLAUDE.md is a startup figure measured with
hyperfine 'rtk <cmd>'rather than a per-input ceiling. Stating it here so the 2,000-line table is not read as the cost of a million-line diff.What the render prints
The condensed body beats classic
diffby a few bytes per isolated edit — a~line carries both texts under one prefix, a+or-line saves the hunk header — and every line of framing spent that margin several times over. Measured on 120 agent-typical diffs (40–600-line files, 1–15 edits): the body alone is 7.4% smaller than GNUdiffand smaller in 119/120; with the previous header, blank line, counts line and legend it was 8% larger and smaller in 3/120, sonever_worsehanded back the classic diff every time andrtk diffshipped at +0.2% against the tool it replaces.So the render has no
file1 → file2header and no blank line: the caller typed both paths. The counts line appears only once the listing runs to 20 lines, where a reader stops counting markers and the line is a small fraction of what it summarises. It keeps its indent so it cannot be read as a listed line. A one-line rewrite in a 40-line file now renders as exactly~ 21 line 20 = 20; → line 20 = 21;and beats the classic diff.-and~are numbered in file1 and+in file2, so the render carries a legend whenever the output mixes frames: a+beside a-, or a+beside a~. It names the markers on screen —(~ = file 1; + = file 2),(- = file 1; + = file 2),(-,~ = file 1; + = file 2)— and the files by argument position rather than by path: with two fixture paths in it the legend alone cost more than the body saved. Output drawn from one file only stays bare, as does the positional fallback, which numbers both halves of a pair from the same position.The classic fallback is now byte-identical to GNU
diffon all 120 corpus pairs. It groups by region rather than by the pairing the condensed render chose, because the classic format has no way to express a pairing: splitting a region into anNcMplus a trailingNaMasserted one implicitly, anddiffnever prints that shape. That also makes it the rightnever_worsebaseline, since an inflated fallback is an easier bar for the condensed render to clear.runkeeps the invisible-difference message out ofnever_worseunconditionally. The raw fallback there is two blobs that look identical, which answers the question worse at any size, and the message competes with no change list: it fires only when the bytes differ and thelines()iterators match. A fixed token allowance above raw was tried and could not be met by construction — the message's shortest form is ~20 tokens and a one-line pair ~2, so the ceiling sat under the message's own floor and dropped it on 90% of one-line pairs.guard.rsnames the exception and why it is bounded by the case rather than by a count.Rebase onto develop
Develop merged #3048 after this branch opened, which added
format_classic_diff,select_file_diff_outputandtracking_baseline, and moved the render entry torender_diff(file1, file2, &diff). Two breakages survive a resolve that only reconciles the text, and neither fails to compile.An empty change list was overloaded. Develop reads
diff.changes.is_empty()as the identical / exit 0 signal in three places. This PR also produces an empty list for "the bytes differ butlines()cannot see it" and for every refusal to build an over-budget listing.FileComparisonnow carries the discriminator —Identical,InvisibleDifference(cause),Lines(DiffResult)— and the three call sites route on it, so an over-cap comparison cannot report two wholly different files as identical.Addedis numbered in file2, andformat_classic_diffgrouped a replacement by matching it against aRemovedwith the same number. That equality only holds while both sides carry file1's numbering. Rather than teach the grouping about the shift, the change list is a list of hunks, each carrying its start in both files, and both renderers read the hunk. The classic path never infers a pairing from line numbers at all.Carrying both frames also fixes the anchors that shift makes wrong:
NaMneeds file1's anchor and file2's range,NdMthe reverse, and neither is derivable from the other after an insertion. A property test replays the rendered script against file1 over 3,000 random pairs and asserts it reconstructs file2, with each hunk's<bodies naming file1 at the lines the header claims and each>body naming file2 at its own.The aligned listing's count budget moved ahead of the script.
myers_opsknows the edit distance the moment it reaches the end, and deletions minus insertions is the length difference, so both counts are exact before anything is cloned. One line against 40,000 of ~500 bytes — a shape the band aligns comfortably — refused only aftermyers_opsandmyers_backtrackhad allocated the whole script; it now refuses at the point of knowing. The byte half genuinely needs the text and still runs over the built script.POSITIONAL_CHANGE_CAPbounds differing positions, not rendered lines: a position whose two texts share no characters prints a-and a+, so 5,000 positions can render as 10,000 lines. The byte cap is what bounds the memory. The constant now says that, and a test pins it at exactly the cap.Testing
cargo fmt --all --check,cargo clippy --all-targets, andcargo test --allare clean on this branch: 3,111 unit tests and every integration test pass, 0 failures.diff_cmdis 92 tests. They cover both pairing repros, the file2 line numbering, two far-apart edits aligning rather than capping, the pure-insertion and empty-file shapes at the boundary, the lopsided pair, all three listing caps by count and by bytes, the region bounds, the frame legend in each path including+beside~, the unterminated-\rtail, and the equal-CRLF-count case. Two pin whatMAX_TRACE_CELLSis really choosing: scattered rewrites align at 700 and fall back at 720, and an 18%-changed 2,000-line file of unequal length still lists every change.Five come with the rebase: the classic renderer grouping a replacement across a shift, its
NdManchor in file2, an over-cap comparison not reading as identical, the legend naming only the markers present, and the listing cap admitting exactly 5,000 positions and rendering 10,000 lines. One assertsmyers_opsreturnsTooManyStepsrather than a script for the 60,000-line lopsided pair, which is the count budget firing before anything is allocated.The last round adds: the classic renderer emitting one
2,3c2,4for a two-into-three region and the same hunk whichever pairing the condensed render chose; similarity-first pairing on a shape where the scores differ, the exact-tie case pinned as a diagonal tie-break, and the positional fallback past the cell cap; a 100,000-line pair with three rewrites producing a script of at most 8 entries; one line against 250,000 exhausting the trace budget at the round the per-round overhead predicts; the render as exact strings with no header, no blank line, and no counts line under 20 listed lines; a single-edit render beating its classic diff; and the invisible-difference message surviving on one-line pairs, including"a\n"vs"a"and the equal-CRLF-count form, both in unit tests and intests/diff_byte_accuracy_test.rsend to end.The aligner is hand-rolled and the banded window changes how its trace is indexed, so three properties are asserted rather than argued: 4,000 random pairs whose emitted script must reconstruct file2 with every line number naming the text it claims on the correct side, 2,000 checked for minimality against a brute-force LCS, and 3,000 whose rendered classic diff must replay against file1 into file2 with every hunk header naming the right lines in both files. All use a seeded LCG so a failure reproduces exactly. The suite runs in 0.3 s.