Skip to content

fix(diff): stop reporting differing files as identical, and align by LCS - #3268

Merged
KuSh merged 4 commits into
rtk-ai:developfrom
iliaal:up/diff-correctness
Sep 8, 2026
Merged

KuSh merged 4 commits into
rtk-ai:developfrom
iliaal:up/diff-correctness

Conversation

@iliaal

@iliaal iliaal commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Two defects in src/cmds/git/diff_cmd.rs, both reachable from a plain rtk diff a b.

1. [ok] Files are identical — and exit 0 — for files that differ

$ cmp a.txt b.txt                    # differ: byte 56, line 8; exit 1
$ rtk diff a.txt b.txt               # [ok] Files are identical; exit 0

rtk diff <f1> <f2> never runs diff. 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 from str::lines():

let lines1: Vec<&str> = content1.lines().collect();
let lines2: Vec<&str> = content2.lines().collect();
if compute_diff(&lines1, &lines2).changes.is_empty() {
    return ("[ok] Files are identical\n".to_string(), 0);
}

str::lines() strips a trailing \r and 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 diff unusable 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:

$ rtk diff a.txt b.txt
files differ only in whitespace or line endings (line endings: 0 CRLF vs 25 CRLF)
$ echo $?
1

That message opens with develop's wording, so the phrase diff_byte_accuracy_test matches 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_diff compared positionally, so one insert desynchronized the rest

for 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 the never_worse guard 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.

+   1 INSERTED

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 than O(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 reported use zeta::A; as modified into itself, at a line number where file2 holds something else, with the add and remove counts zeroed. Keep carries 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] against new[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 separate value = 9 from value = 2 as rewrites of value = 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 k at round d costs (d + k) / 2 deletions and (d - k) / 2 insertions, and neither can exceed the side it consumes. On that lopsided pair the window is three diagonals wide however large d grows, 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 at d = 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. A Vec per 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_CAP rather 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 at d = 4 and 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 Op and again into the render: five thousand ten-thousand-character lines sat inside POSITIONAL_CHANGE_CAP and 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 d grows 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_large runs 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, which never_worse had 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 diff on 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:

case LCS table banded Myers
2000 lines, 2 edits 1980 apart 9.0 ms user, 13.6MB 1.0 ms user, 0.0MB
1999 × 1999 wholly different 9.8 ms user, 14.4MB 5.0 ms user, 1.6MB
1500 × 1500 wholly different 7.4MB 1.7MB
1 line vs 5000, one shared inside refused 1.0 ms user, 0.4MB
5000 × 10,000-char lines, 50MB a side 308MB 197MB
baseline (two 1-line files) 1.5 ms user, 0.2MB 2.0 ms user, 0.0MB

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: run holds both files and builds a raw concatenation 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 diff in general. The bound is on d; 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:

case user time path taken
200,000 lines, 1,300 scattered rewrites 21 ms positional fallback
500,000 lines, 1,300 scattered rewrites 40 ms positional fallback
1,000,000 lines, 1,300 scattered rewrites 60 ms positional fallback
1,000,000 lines, 700 scattered rewrites 78 ms aligned
two 4-line files 2 ms aligned

Fewer changes costing more is not a measurement error: 700 rewrites sit inside MAX_TRACE_CELLS and 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 diff by 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 GNU diff and smaller in 119/120; with the previous header, blank line, counts line and legend it was 8% larger and smaller in 3/120, so never_worse handed back the classic diff every time and rtk diff shipped at +0.2% against the tool it replaces.

So the render has no file1 → file2 header 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 diff on 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 an NcM plus a trailing NaM asserted one implicitly, and diff never prints that shape. That also makes it the right never_worse baseline, since an inflated fallback is an easier bar for the condensed render to clear.

run keeps the invisible-difference message out of never_worse unconditionally. 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 the lines() 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.rs names 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_output and tracking_baseline, and moved the render entry to render_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 but lines() cannot see it" and for every refusal to build an over-budget listing. FileComparison now 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.

Added is numbered in file2, and format_classic_diff grouped a replacement by matching it against a Removed with 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: NaM needs file1's anchor and file2's range, NdM the 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_ops knows 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 after myers_ops and myers_backtrack had 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_CAP bounds 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, and cargo test --all are clean on this branch: 3,111 unit tests and every integration test pass, 0 failures.

diff_cmd is 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-\r tail, and the equal-CRLF-count case. Two pin what MAX_TRACE_CELLS is 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 NdM anchor 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 asserts myers_ops returns TooManySteps rather 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,4 for 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 in tests/diff_byte_accuracy_test.rs end 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.

dev1abz added a commit to dev1abz/rtk that referenced this pull request Aug 7, 2026
kylehgc added a commit to kylehgc/rtk that referenced this pull request Aug 17, 2026
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]>
kylehgc added a commit to kylehgc/rtk that referenced this pull request Aug 17, 2026
fix(diff): byte-accurate identity and LCS alignment (adopt upstream rtk-ai#3268)

@KuSh KuSh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 --check fails on three hunks, though the PR body says it's clean: the notes.push(format!("line endings: …")) (rustfmt collapses it to one line), the assert!(out.contains("trailing newline: present vs absent"), …) in test_render_trailing_newline_difference_is_not_identical (rustfmt expands it), and the let plain: String = (0..200).map(…).collect(); in test_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.

Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
@iliaal

iliaal commented Aug 30, 2026

Copy link
Copy Markdown
Contributor Author

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 Op, so "the run of insertions that follows" was true of the vector and false of the file. Took your Op::Keep suggestion over tracking the last matched index — it makes the invariant visible at the unreachable! arms, as you said. ops_to_changes skips Keep and starts a fresh run after it, so runs only fold when they're adjacent in the files. Both repros now report +1 added, -1 removed, ~0 modified, and the sorted-import case no longer claims a line was modified into itself. Covered by test_compute_diff_does_not_pair_across_matched_lines and test_compute_diff_reorder_is_not_a_line_modified_into_itself.

Added(dline, …). Fixed — the Added half takes the insertion's own line number now. Your a = ["x", "AAAA"] / b = ["NEW", "x", "BBBB"] case gives Added(3, "BBBB"). Pinned by test_compute_diff_added_line_numbers_come_from_file2.

The N vs N bytes fallback. Agreed, that's the one number you least want to print there. describe_invisible_difference compares CRLF positions now, not counts. Equal counts in different places report 1 CRLF on each side, first differing at line 1; the byte-length clause is gone. The remaining fallback string can't fire — lines() normalizes only the \r before a newline and the final newline, so one of the two checks always matches — but it no longer says anything that reads as "identical" if it somehow does.

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 alignment_skipped flag on DiffResult, so it never builds the change list that never_worse was always going to discard, and never pays the two full copies of both files to get there. render_file_diff prints the counts plus too large to align line by line; counts only, and the flag keeps it out of the changes.is_empty() path so it can't be mistaken for the bytes-differ-lines-match case. The cap measures (n + 1) * (m + 1) rather than n * m, so your 2,000,000 × 2 shape is caught instead of allocating 24MB, and the doc comment's 16MB claim now holds for every shape. Tests at 2001 × 2001 and at 2,000,000 × 2, plus a render-level test. test_compute_diff_wholesale_replacement_still_pairs_by_similarity is renamed to test_compute_diff_adjacent_replacement_pairs_by_similarity — you're right that the old name would have kept readers believing the branch was covered.

cargo fmt --check. My mistake; it's clean now, and I've verified it rather than asserted it.

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 KuSh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved

@KuSh KuSh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
@iliaal

iliaal commented Aug 31, 2026

Copy link
Copy Markdown
Contributor Author

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. rtk proxy diff is named as the escape hatch for the over-cap case.

@iliaal

iliaal commented Aug 31, 2026

Copy link
Copy Markdown
Contributor Author

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. MAX_EDIT_DISTANCE counts operations, so the line floor is half of it, and the region figure is a span rather than a count — your 40x swing on the same 251 edits makes that plain. The message now says over 350 lines differ and labels the second number: changed region spans 2000 vs 2001 lines.

The cliff. Fixed, and it no longer exists for the shape you named. Measured on 10,000-line files with in-place rewrites:

249 rewrites → all 249 named
250 rewrites → all 250 named
251 rewrites → all 251 named      (was: no change list)
400 rewrites → all 400 named, paired by line position
1000 rewrites → all 1000 named, paired by line position

I took your second option but not your reasoning for it. Equal lengths do not make a shift impossible — a = [X, 1, 2, 3], b = [1, 2, 3, Y] is equal-length with one deletion and one insertion, and positional pairing reports all four lines as rewritten. What is true is weaker and still sufficient: on equal-length inputs, positional pairing is a valid edit script by both of your property criteria — it reconstructs file2, and every line number names the text it claims. It is only non-minimal. So the render says so, on its own line:

   +22 added, -22 removed, ~378 modified

   paired by line position: too different to align

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 d = 2000 at 32MB contradicts the 5MB budget you held me to last round. What it did buy: the trace holds i32 rather than isize now, which pays for raising the cap from 500 to 700 at the same ~2MB.

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 — rtk diff on a 4-line pair of the same size measures 13MB. Master takes 1.9 s and 52MB on it.

big_a.txt → big_b.txt
   100000 lines differ, too many to list; use `rtk proxy diff` for the full text

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 INVISIBLE_DIFF_TOKEN_ALLOWANCE (16 tokens) above raw, so your "a\n" / "a" case falls back to raw while the three-line CSV still gets its message. guard.rs names the exception and its bound in the module doc, so the doc and the code agree either way you read them.

Reference frames. The header names them when the output actually mixes them:

a.txt → b.txt
   +1 added, -1 removed, ~0 modified
   (- numbered in a.txt, + in b.txt)

It only appears when both an addition and a removal are present, so ~-only output is unchanged. I went with the legend rather than annotating each pair because unpaired adds and removes have the same property, not just the split replacements.

The three tests. Restored verbatim; they still pass. You are right that they cover ops_to_changes, which Myers did not touch. I removed them by replacing a block that happened to contain them, which is a bad way to delete a test.

PR description. Already rewritten before your review landed — no LCS_CELL_CAP, no 16MB, no 2,000,000 x 2. It now covers the positional fallback and its bound too.

cargo fmt --all --check and cargo clippy --all-targets --all-features -- -D warnings clean; cargo test --all at 2522 passed across three consecutive runs, with the same two pre-existing hooks::rewrite_cmd::tests::unattestable_passthrough failures that reproduce with this branch's changes stashed.

@KuSh KuSh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
@iliaal

iliaal commented Aug 31, 2026

Copy link
Copy Markdown
Contributor Author

Two things an adversarial pass turned up after your review, both fixed in 29c49ca, and one of them is a capability regression against develop that I would have expected you to find next round.

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 87be79f does not fire. A one-line file against a five-thousand-line one sharing a line in the middle needs d = 4999; the edit-distance cap gave up and reported "too different to align" while GNU diff produced 4,999 insertions and develop's positional compare listed them. Diffing a small file against a large one is ordinary enough that this mattered.

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 k at round d costs (d + k) / 2 deletions and (d - k) / 2 insertions, and neither can exceed the side it consumes. On that lopsided pair the window is three diagonals wide however large d grows, so the whole trace is a few thousand cells and the alignment lands. Equal-length inputs get the full 2d + 1 window, so the budget bites at d = 706 — 353 rewritten lines, against 350 before. A run of contiguous rewrites gets a narrower window and now aligns to about 500, which is why test_compute_diff_equal_lengths_have_no_cliff sweeps the density instead of pinning the boundary.

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.

POSITIONAL_CHANGE_CAP bounded the list by count, not by bytes. Each listed line is cloned into an Op and again into a DiffChange before formatting. Five thousand ten-thousand-character lines sat inside the count cap and cost 308MB of RSS against a 50MB input, so the comment claiming the cap kept the fallback near a megabyte was true only for short lines. Both listing paths check bytes now, and the same input reports its exact count at 105MB — the cost of reading the files at all.

Perf against your table, release, peak RSS above diff on two one-line files: 2,000 lines with 2 edits 1,980 apart 0.2MB; 1,999 x 1,999 wholly different 0.3MB; the new lopsided pair 0.5MB; two wholly different 100,000-line files 6.4MB.

cargo fmt --all --check and cargo clippy --all-targets clean, diff_cmd 57/57, cargo test --all 2533 passed — same two unattestable_passthrough failures this branch does not touch.

@KuSh KuSh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/core/guard.rs Resolved

@KuSh KuSh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
@iliaal
iliaal force-pushed the up/diff-correctness branch from 48ea2a4 to ecef036 Compare September 1, 2026 01:23
@iliaal

iliaal commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto develop as a single commit (ecef036). All five findings addressed; details per thread.

1 — semantic conflict with #3048 (blocking). Both breakages needed a decision, and I took the stronger option on each.

Empty changes is no longer a signal at all. FileComparison carries the discriminator — Identical, InvisibleDifference(cause), Lines(DiffResult) — and classic_fallback, select_file_diff_output and tracking_baseline route on it. An over-cap comparison can't reach the identical branch. tracking_baseline now keys on whether a classic diff exists rather than on changes.is_empty(), since identical files, an invisible difference and a refused listing all lack one and all fall back to the dump.

For the pairing, I didn't teach format_classic_diff about the file2 frame — I removed the inference. Every DiffChange carries a position in each file, and a dissimilar in-place rewrite stays one Replaced instead of a Removed plus an Added, so the grouping is structural. That also fixes what your finding implies but doesn't state: NaM needs file1's anchor with file2's range and NdM the reverse, and neither is derivable from the other after a shift — develop's start - 1 was only right because positional numbering made the frames coincide. A property test replays the rendered script against file1 over 3,000 random pairs, asserting it reconstructs file2 with each hunk's < bodies naming file1 at the header's lines and each > body naming file2 at its own. On shapes GNU diff renders the same way the output is byte-identical to it.

2 — script_too_large allocating first. Closed the count half as you described. myers_ops returns Ok(Aligned::TooManySteps { removed, added }) at the point it reaches (n, m): the script has d steps and deletions minus insertions is n - m, so both counts are exact with nothing cloned. Your 40,000-line pair now refuses without a backtrack. The byte half still runs over the built script — bounding it from the raw slices would over-refuse a small script inside large files, and the count check already catches the shape that made it expensive.

3 — POSITIONAL_CHANGE_CAP 2x off. Took your second option. The constant and too_much_to_list now say the cap is on differing positions and the render prints up to two lines each; a test pins 5,000 positions rendering 10,000 lines with disjoint character sets, so the documented number is checked rather than asserted.

4 — cost grows with N. Added to the PR body with my own measurements, since mine are on different hardware and longer lines: 21 / 40 / 60 ms at 200k / 500k / 1M lines with 1,300 rewrites, and 78 ms at 1M lines with 700. The inversion is the same one you saw and it's the fallback boundary — 1,300 exhausts MAX_TRACE_CELLS and pairs positionally in one pass, 700 runs the full search. Both name every changed line. The body now says the ~7 ms is a filled trace budget on 2,000-line files, not the cost of rtk diff.

5 — the legend, and yours to own only in part; I wrote the string. It now names the markers present: (~ numbered in a.txt, + in b.txt) for your insertion-plus-rewrite shape, (- numbered in ...) when only - is there, (- and ~ numbered in ...) when both are.

One thing outside this PR. origin/develop at e8541d1 doesn't compile. src/cmds/php/phpt_cmd.rs calls lazy_static::lazy_static! with no such dependency in Cargo.toml, and src/discover/rules.rs:581 builds an RtkRule missing pipeline_final_safe — both from #1503, and develop's CI has been red since that merge. CI here will be red until it's fixed. I verified with a local workaround for those two files that isn't part of this branch; cargo fmt --all --check and cargo clippy --all-targets are clean and 2,930 unit plus 83 integration tests pass, 0 failures. diff_cmd is 79 tests. Happy to send the two-line fix as its own PR if that helps.

@KuSh KuSh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
kylehgc added a commit to kylehgc/rtk that referenced this pull request Sep 1, 2026
fix(diff): refresh adoption of upstream rtk-ai#3268 — Myers alignment, FileComparison, listing budgets
kylehgc added a commit to kylehgc/rtk that referenced this pull request Sep 1, 2026
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]>
@iliaal
iliaal force-pushed the up/diff-correctness branch 2 times, most recently from 1ac2dbc to 0736b59 Compare September 4, 2026 11:32
@iliaal

iliaal commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Force-pushed: rebased onto current develop, scope narrowed.

develop gained the byte-equality verdict independently (0cb34ac, 428af61), so this branch no longer argues for it. The alignment fix is what's left.

compute_diff compared line N to line N, so one inserted or deleted line reported every line after it as modified. It now aligns by LCS.

The bytes_equal bool can't express the third state the aligner produces: a comparison that ran, then refused to build a listing that would cost more than the raw text. FileComparison replaces it with Identical, InvisibleDifference and Lines, with the refusal reason in DiffResult::unaligned. Routing a refusal through the identical branch exits 0 on files that differ.

Adopted IDENTICAL_FILES_MESSAGE and render_file_header from develop. The invisible-difference message now opens with develop's "whitespace or line endings" wording so diff_byte_accuracy_test passes unchanged, then names the measured cause instead of stopping there.

fmt, clippy -D warnings, and the full suite pass.

@KuSh KuSh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
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.
@iliaal
iliaal force-pushed the up/diff-correctness branch from 0736b59 to d4239ec Compare September 5, 2026 20:25

@KuSh KuSh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
…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 KuSh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
Comment thread src/cmds/git/diff_cmd.rs Resolved
iliaal and others added 2 commits September 7, 2026 19:42
…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]>

@KuSh KuSh left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_legend to the round-9 behaviour (modified > 0 instead of modified > crossed, and the crossing clause gated on added > 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 below render_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, develop emits 16584 bytes against a 3478-byte raw diff (−377%: it dumps both files, the never_worse inversion 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 --all 3424 passing, 0 failed.

Filed as follow-up

  • #3926 — the InvisibleDifference gap at :73. It is reached only when hunks.is_empty(), so a CRLF or trailing-newline difference coexisting with a line change still goes unmentioned. Re-ran on this head: rtk prints 2c2 beta → gamma where GNU prints 1,2c1,2 plus \ No newline at end of file. develop gates 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.

@KuSh
KuSh merged commit 9512e1a into rtk-ai:develop Sep 8, 2026
11 checks passed
@rtk-release-bot rtk-release-bot Bot mentioned this pull request Sep 8, 2026
kylehgc added a commit to kylehgc/rtk that referenced this pull request Sep 8, 2026
chore(sync): Conflicted Sync of upstream/develop 2026-09-07 (42 commits), re-adopt rtk-ai#3268 head
kylehgc added a commit to kylehgc/rtk that referenced this pull request Sep 8, 2026
…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]>
kylehgc added a commit to kylehgc/rtk that referenced this pull request Sep 8, 2026
…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]>
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