From f9e28a8df41b0d0236cefe60c4e7a7c97c5073ea Mon Sep 17 00:00:00 2001 From: "Jeffrey C. Ollie" Date: Tue, 3 Nov 2026 23:22:42 -0600 Subject: [PATCH] diff: split a search past 256 steps early as git does Past step 256 of a search for a middle snake (only a comparison of more than 65,532 lines gets there) git splits the box early. Black-box probes of git pinned the rule: on a step where either search found a snake of 21 lines or more (a trigger, however close to its corner), the box is split at a snake of 20 or more lines found on that step that ends more than twice as many lines from its search's corner, in each text, as the steps taken; the forward search's furthest out in the nearer text if it has one, else the backward search's. A lone 20-line snake never splits, a trigger from the step before or after does not count, and a trigger the margin rules out still does. Refused instead, where git was not seen to follow the rule or the order of its choices is not known: a step with two triggers or two snakes as far out as each other, a box whose two searches both found a trigger far enough out in the 16 steps before step 257, an early split on the give-up step, one due on a step whose backward search then meets the forward one elsewhere, and any search past 256 steps in a range --patience or --histogram hands back. The two Ghostty commits updating its vendored simdutf, refused before, now match git byte for byte. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01P9FTtTrkEbuvbZnRyJCBir --- CONTRIBUTING.md | 2 +- GLOSSARY.md | 12 ++- README.md | 54 +++++++---- src/diff/LineDiff.zig | 191 +++++++++++++++++++++++++++++++------ src/diff/histogram.zig | 4 +- src/diff/patience.zig | 2 +- src/diff/tests.zig | 100 +++++++++++++++++-- tools/diff_tests.zig | 80 +++++++++++++++- tools/merge_diff_tests.zig | 40 +++++--- 9 files changed, 403 insertions(+), 82 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 21e5fdd..bf219e6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -101,7 +101,7 @@ running it, or the build fails as if the file were missing. | `src/TreeDiff.zig` | Two trees compared under a pathspec: the entries added, deleted and modified | | `src/IndexDiff.zig` | The index compared with a tree and with the working tree, from its stat data, racily clean entries hashed; the working tree reached through a seam, `statx` on Linux | | `src/diff.zig` | The diff layer's way in: the line diff, hunks and patches | -| `src/diff/LineDiff.zig` | Two texts compared line by line in git's edit script: whitespace options, the common tail set aside under `-U0`, discarding, Myers' linear-space algorithm with git's cost limit (searches past 256 steps refused), sliding | +| `src/diff/LineDiff.zig` | Two texts compared line by line in git's edit script: whitespace options, the common tail set aside under `-U0`, discarding, Myers' linear-space algorithm with git's cost limit and its early splits past 256 steps (refused where not known), sliding | | `src/diff/indent.zig` | The indent heuristic: indentation measured, splits scored, and the placement of a run chosen as git chooses it | | `src/diff/hunks.zig` | Changes gathered into hunks with context, the changes `--ignore-blank-lines` and `-I` leave out, `-W`'s hunks reaching over whole functions, and function names after `@@` | | `src/diff/funcname.zig` | Function lines as diff drivers find them: `xfuncname` and `funcname` patterns, several to a value with `!`, the text shown, and git's built-in drivers as patterns fitted to what git chooses | diff --git a/GLOSSARY.md b/GLOSSARY.md index 0addde9..53bda2a 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -671,9 +671,15 @@ way. **Cost limit**: How many steps the search for a middle snake runs before git gives up and splits where the search has reached (`costLimit`): 256, and more for a -comparison of more than 65,532 lines. A search that would run past 256 -steps is refused, because there git may also split early at a snake it -has found, by a rule only partly matched (`plain_steps`). +comparison of more than 65,532 lines. Past 256 steps git also splits +early, at a snake far enough from the search's corner, on a step that +found a long enough one (**Early split**). + +**Early split**: +A box split, past step 256 of its search, at a snake of at least 20 lines +that step found, ending far enough from the search's corner, when the +step found a snake of at least 21 lines (`plain_steps`). `--minimal` +never splits early. **Sliding**: Moving a run of changed lines up or down over equal lines, which leaves the diff --git a/README.md b/README.md index b781374..ceafca0 100644 --- a/README.md +++ b/README.md @@ -271,8 +271,9 @@ do: as his paper gives it, with what git was seen to add — lines that occur only in one text taken out first, lines that occur very often taken out where the lines around them say so, the search for a middle snake given - up at git's cost limit on large, much-changed texts (and refused where - it would search further, see below), runs of changes + up at git's cost limit on large, much-changed texts, and split early + past 256 steps as git splits it (refused in a few places, see below), + runs of changes slid and merged as git slides them, git's indent heuristic (on by default) placing each run by the indentation and blank lines around it, and the common tail git sets aside for a patch without context — and @@ -795,24 +796,39 @@ deliberate or not yet matched: could still place a run differently from git on input unlike any of those, and would then still write a correct patch. `--no-indent-heuristic` and `diff.indentHeuristic=false` turn it off; -- a line diff whose search for a middle snake would go on past 256 - steps is refused (`LineDiff.Error.LongSearchUnsupported`), wherever a - command compares lines: the patch, `--stat`, `--numstat`, - `--shortstat`, `--compact-summary`, `--dirstat=lines`, `--check`, `-G`, - `-B`, `-W`, a merge's combined diff and its counts against the first - parent, and `--no-index`, each with +- past 256 steps of a search for a middle snake, which only a comparison + of more than 65,532 lines can reach once the common head and tail and + the lines found in one text only are set aside, git splits the + comparison early, and zig-git does as git does: on a step where either + search found a run of at least 21 matching lines, at a run of at least + 20 that step found, ending more than twice as many lines from where + that search began, in each text, as the steps taken (the forward + search's furthest out in the nearer text, else the backward search's). + The rule was found by black-box probes of git, condition by condition. + Where it was not seen to hold, or where the order of git's choices is + not known, the line diff is refused (`LineDiff.Error.LongSearchUnsupported`): + an early split on a step that found two such runs of 21 or more, or + two runs to split at as far out as each other, a + comparison where both searches found one far enough out in the 16 + steps before step 257 (git was seen to split there at a run found + before step 257, by a rule not found), an early split on the step + where the search gives up, an early split due on a step where the + other search then meets it elsewhere, and any search past 256 steps in + a range `--patience` or `--histogram` hands back to Myers' algorithm. + The refusal applies wherever a command compares lines: the patch, + `--stat`, `--numstat`, `--shortstat`, `--compact-summary`, + `--dirstat=lines`, `--check`, `-G`, `-B`, `-W`, a merge's combined diff + and its counts against the first parent, and `--no-index`, each with `fatal: zig-git : 'a line diff searching past 256 steps' is not supported` - and exit status 128, what was written before it left in place. Only a - comparison of more than 65,532 lines, once the common head and tail and - the lines found in one text only are set aside, can search that long, - and past that step git sometimes splits the comparison early at a run - of matching lines it has found. Probes found most of the rule (from - step 257, a run of at least 21 lines ending more than twice as many - lines from where that search began, in each text, as the steps taken), - but git was also seen to split at runs of exactly 20 lines and at runs - found before step 257, by a rule not yet found. In 640 generated - comparisons of 5,000 to 100,000 lines, 145 were refused and the rest - matched git; `--minimal` never searches that way and is not refused; + and exit status 128, what was written before it left in place. On + 618 generated comparisons of 14,000 to 50,000 lines a side, most of + them searching past 256 steps, run as 1,854 `diff --no-index` with and + without the indent heuristic and with `-U0`, zig-git matched git on + 1,423 and refused 431, and differed on none; on 360 more of 5,000 to + 100,000 lines with a range of options it refused 21 and differed from + git only under `--histogram` (below). The Ghostty commits updating its + vendored simdutf, which split early, match git byte for byte. + `--minimal` never splits early and is not refused; - `--histogram` is matched by a model inferred from git's choices (`src/diff/histogram.zig`), whose rules were pinned by probes but which does not explain everything git does. Over 3,200 sampled commits of Ghostty and 400 of zig-git (`show`, its patch, `--stat` and `--numstat`) and 600 Ghostty merges (`show --cc`, `-c` and `--cc --stat`) it disagreed with diff --git a/src/diff/LineDiff.zig b/src/diff/LineDiff.zig index f72d87b..5fd5bfa 100644 --- a/src/diff/LineDiff.zig +++ b/src/diff/LineDiff.zig @@ -27,9 +27,12 @@ //! lengths is odd and the backward path's when it is even. When the //! search for a middle snake reaches `costLimit` steps without one, it //! gives up and splits the box at the furthest point either search has -//! reached. `--minimal` never gives up. A search that would go on past -//! 256 steps, which only a comparison of more than 65,535 lines can -//! need, is refused (`plain_steps`). +//! reached. Past 256 steps, which only a comparison of more than 65,535 +//! lines can reach, a step that finds a long enough snake splits the +//! box early at one far enough from the search's corner +//! (`plain_steps`). `--minimal` never does either. The few places +//! where git's choice past 256 steps is not known are refused +//! (`Error.LongSearchUnsupported`). //! 4. Each run of changed lines is slid up and down over equal lines, //! merging with the runs it meets, and left as low as it goes unless a //! position higher up lines up with a change in the other text. @@ -145,7 +148,8 @@ pub const Error = Allocator.Error || error{ /// A text of more lines than fit in 32 bits. TooManyLines, /// A comparison whose search for a middle snake went on past - /// `plain_steps` steps, where git's choice is not fully known. + /// `plain_steps` steps to where git's choice is not known: see + /// `plain_steps` for which. LongSearchUnsupported, }; @@ -255,7 +259,7 @@ pub fn compute(gpa: Allocator, old: []const u8, new: []const u8, options: Option var fb: []bool = &.{}; defer gpa.free(fb); switch (options.algorithm) { - .myers, .minimal => try diffClasses(gpa, ca, cb, xa, xb, options.algorithm == .minimal), + .myers, .minimal => try diffClasses(gpa, ca, cb, xa, xb, if (options.algorithm == .minimal) .minimal else .myers), .patience => { const anchored: AnchorCheck = .{ .lines = &kb, .texts = options.anchors }; try patience.diffClasses(gpa, ca, cb, xa, xb, if (options.anchors.len != 0) anchored.anchors() else null); @@ -365,8 +369,21 @@ pub fn costLimit(total: usize) usize { return @max(256, twiceRoot(total + 3)); } +/// How `diffClasses` compares. +pub const Mode = enum { + /// git's default, splitting a long search early (`plain_steps`). + myers, + /// `--minimal`: no line is provisional and the search never gives up. + minimal, + /// A range `--patience` or `--histogram` has nothing to match in. A + /// search past `plain_steps` steps is refused there: whether git splits + /// it early the same way was not tested. + fallback, +}; + /// Steps 1 to 3: which lines are changed, before sliding. -pub fn diffClasses(gpa: Allocator, ca: []const u32, cb: []const u32, a_changed: []bool, b_changed: []bool, minimal: bool) DiffError!void { +pub fn diffClasses(gpa: Allocator, ca: []const u32, cb: []const u32, a_changed: []bool, b_changed: []bool, mode: Mode) DiffError!void { + const minimal = mode == .minimal; @memset(a_changed, true); @memset(b_changed, true); var lo: usize = 0; @@ -421,7 +438,7 @@ pub fn diffClasses(gpa: Allocator, ca: []const u32, cb: []const u32, a_changed: defer gpa.free(xb); @memset(xa, false); @memset(xb, false); - try myers(gpa, sa, sb, xa, xb, if (minimal) std.math.maxInt(usize) else costLimit(sa.len + sb.len)); + try myers(gpa, sa, sb, xa, xb, if (minimal) std.math.maxInt(usize) else costLimit(sa.len + sb.len), mode == .myers); for (ia.items, xa) |i, x| a_changed[i] = x; for (ib.items, xb) |i, x| b_changed[i] = x; } @@ -464,29 +481,72 @@ const provisional_window = 100; /// Step 3: Myers' linear-space algorithm over `a` and `b`, marking what /// it does not match. -fn myers(gpa: Allocator, a: []const u32, b: []const u32, a_changed: []bool, b_changed: []bool, limit: usize) DiffError!void { +fn myers(gpa: Allocator, a: []const u32, b: []const u32, a_changed: []bool, b_changed: []bool, limit: usize, early_splits: bool) DiffError!void { const size = a.len + b.len + 3; const vf = try gpa.alloc(isize, size); defer gpa.free(vf); const vb = try gpa.alloc(isize, size); defer gpa.free(vb); - var s: Search = .{ .a = a, .b = b, .vf = vf, .vb = vb, .offset = @intCast(b.len + 1), .limit = limit }; + var s: Search = .{ .a = a, .b = b, .vf = vf, .vb = vb, .offset = @intCast(b.len + 1), .limit = limit, .early_splits = early_splits }; s.box(0, a.len, 0, b.len, a_changed, b_changed); if (s.too_long) return error.LongSearchUnsupported; } -/// The most steps a search for a middle snake is known to take as git -/// takes them. Past 256 steps, which only a comparison of more than -/// 65,535 lines can reach (`costLimit`), git sometimes splits the box -/// early at a snake it has found. The rule was partly found by -/// experiment: from step 257 on, a snake of at least 21 lines ending -/// more than twice as many lines from the search's corner, in each -/// text, as the steps taken, the one furthest from the corner in the -/// nearer text. But git sometimes splits at a 20-line snake, and -/// sometimes at a snake found before step 257, by a rule not yet found, -/// so such a comparison is refused rather than approximated. +/// The steps a search for a middle snake takes before git may split its +/// box early. Only a comparison of more than 65,535 lines can search +/// further (`costLimit`). From step 257 on (never with `--minimal`), once +/// both searches have taken a step: +/// +/// - the step may split early if either search found a snake of at +/// least `trigger_run` lines on it (a trigger), however close to its +/// corner; +/// - the box is then split at a snake of at least `candidate_run` lines +/// that search found on that step, ending more than twice as many +/// lines from its corner, in each text, as the steps taken: of the +/// forward search's such snakes if it has any, otherwise of the +/// backward search's, the one furthest from the corner in the nearer +/// text; +/// - with no such snake the search goes on. +/// +/// All of it was found by black-box experiment: probes with planted +/// snakes for each condition (a lone 20-line snake never splits; a 20-line +/// snake further out than a 21-line one found on the same step, by either +/// search, is split at; one found a step before or after is not; a +/// trigger the margin rules out still counts; the forward search's +/// snake is taken over a backward one further out), then generated +/// comparisons. +/// +/// What is refused (`Error.LongSearchUnsupported`) instead, because git +/// was not seen to follow the rule there or the order of its choices is +/// not known: +/// +/// - an early split on a step that found more than one trigger, or two +/// snakes to split at as far out as each other; +/// - a box whose two searches had each found, in the `lead_in` steps +/// before step 257, a trigger ending far enough out to split at (git +/// was seen to split such a box at a snake found before step 257, by a +/// rule not found); +/// - an early split on the step where the search would give up; +/// - an early split due after the forward search, on a step whose +/// backward search then meets it away from that snake; +/// - any search past 256 steps in a range `--patience` or `--histogram` +/// hands back (`Mode.fallback`), which was not tested. +/// +/// The first two were chosen from generated comparisons on which git +/// differed from the rule: every one of those (19 of 620) falls under one +/// or the other, as do 125 on which git agreed. pub const plain_steps = 256; +/// The shortest snake that lets a step past `plain_steps` split early. +pub const trigger_run = 21; + +/// The shortest snake an early split may be made at. +pub const candidate_run = 20; + +/// How many steps before `plain_steps` run out a trigger is looked for, +/// to refuse a box whose searches both found one there (`plain_steps`). +pub const lead_in = 16; + /// What `diffClasses` can fail with. pub const DiffError = Allocator.Error || error{ /// See `Error.LongSearchUnsupported`. @@ -501,12 +561,17 @@ const Search = struct { /// Index of diagonal 0 in `vf` and `vb`. offset: isize, limit: usize, - /// Set when some box's search went on past `plain_steps` steps. + /// Whether a search past `plain_steps` steps may split early; if not, + /// such a search is refused. + early_splits: bool, + /// Set when some box was split where git's choice is not known + /// (`plain_steps`). too_long: bool = false, const Split = struct { x0: usize, y0: usize, x1: usize, y1: usize }; fn box(s: *Search, ax0: usize, ax1: usize, by0: usize, by1: usize, a_changed: []bool, b_changed: []bool) void { + if (s.too_long) return; var x0 = ax0; var x1 = ax1; var y0 = by0; @@ -554,9 +619,24 @@ const Search = struct { var fmax: isize = 0; var bmin: isize = delta; var bmax: isize = delta; + // Whether each search found, in the `lead_in` steps before + // `plain_steps` ran out, a trigger far enough out to split at. + var lead_f = false; + var lead_b = false; var d: usize = 0; while (true) { d += 1; + const heuristic = s.limit != std.math.maxInt(usize); + // Past `plain_steps`, unless `--minimal`: the snakes this step + // finds, for an early split (`plain_steps`). + const watch = heuristic and d > plain_steps; + if (watch and (!s.early_splits or (lead_f and lead_b))) { + s.too_long = true; + return s.giveUp(x0, y0, n, m, fmin, fmax, bmin, bmax); + } + const look = watch or (heuristic and d + lead_in > plain_steps); + var f: Seen = .{}; + var bs: Seen = .{}; if (fmin > kmin) { fmin -= 1; s.fv(fmin - 1).* = -1; @@ -578,6 +658,7 @@ const Search = struct { s.fv(k).* = x; if (odd and bmin <= k and k <= bmax and s.bv(k).* <= x) return .{ .x0 = x0 + @as(usize, @intCast(sx)), .y0 = y0 + @as(usize, @intCast(sy)), .x1 = x0 + @as(usize, @intCast(x)), .y1 = y0 + @as(usize, @intCast(y)) }; + if (look) f.note(x - sx, d, x, y, x, y); } if (bmin > kmin) { bmin -= 1; @@ -598,19 +679,75 @@ const Search = struct { y -= 1; } s.bv(k).* = x; - if (!odd and fmin <= k and k <= fmax and x <= s.fv(k).*) + if (!odd and fmin <= k and k <= fmax and x <= s.fv(k).*) { + // Whether git would have split early after the forward + // search, before this one met it, is not known; it + // makes no difference when that split is on this snake. + if (watch and f.triggers != 0) if (f.best) |c| { + if (c.x - c.y != k or c.x < x or c.x > ex) s.too_long = true; + }; return .{ .x0 = x0 + @as(usize, @intCast(x)), .y0 = y0 + @as(usize, @intCast(y)), .x1 = x0 + @as(usize, @intCast(ex)), .y1 = y0 + @as(usize, @intCast(ey)) }; + } + if (look) bs.note(ex - x, d, x, y, n - x, m - y); } - if (d >= s.limit) return s.giveUp(x0, y0, n, m, fmin, fmax, bmin, bmax); - if (d == plain_steps and s.limit != std.math.maxInt(usize)) { - // Past here git may split the box early at a snake, by a - // rule only partly matched: give up and refuse. - s.too_long = true; - return s.giveUp(x0, y0, n, m, fmin, fmax, bmin, bmax); + if (!watch) { + lead_f = lead_f or f.far_trigger; + lead_b = lead_b or bs.far_trigger; } + const early: ?Candidate = if (watch and f.triggers + bs.triggers != 0) f.best orelse bs.best else null; + if (early) |p| { + // Which of the early split and the give-up git takes when + // both fall on one step is not known, nor how git chooses + // when the step found more than one trigger, or between + // snakes as far out as each other. + const tie = if (f.best != null) f.tie else bs.tie; + if (d >= s.limit or f.triggers + bs.triggers > 1 or tie) s.too_long = true; + const ux = x0 + @as(usize, @intCast(p.x)); + const uy = y0 + @as(usize, @intCast(p.y)); + return .{ .x0 = ux, .y0 = uy, .x1 = ux, .y1 = uy }; + } + if (d >= s.limit) return s.giveUp(x0, y0, n, m, fmin, fmax, bmin, bmax); } } + /// A snake an early split may be made at: where it ends, seen from + /// its search's corner, and how far that is in the nearer text. + const Candidate = struct { x: isize, y: isize, reach: isize }; + + /// What one search found on one step, for an early split. + const Seen = struct { + /// Snakes of at least `trigger_run` lines. + triggers: usize = 0, + /// Whether one of them ends far enough out to split at. + far_trigger: bool = false, + /// Where to split, if anywhere. + best: ?Candidate = null, + /// Whether another snake to split at is as far out as `best`. + tie: bool = false, + + /// Notes a snake of `run` lines found at step `d` that ends at + /// (`x`, `y`), `u` and `w` lines from its search's corner in each + /// text. + fn note(seen: *Seen, run: isize, d: usize, x: isize, y: isize, u: isize, w: isize) void { + const reach = @min(u, w); + const far = 2 * reach > 4 * @as(isize, @intCast(d)); + if (run >= trigger_run) { + seen.triggers += 1; + if (far) seen.far_trigger = true; + } + if (run < candidate_run or !far) return; + if (seen.best) |b| { + if (reach < b.reach) return; + if (reach == b.reach) { + seen.tie = true; + return; + } + } + seen.best = .{ .x = x, .y = y, .reach = reach }; + seen.tie = false; + } + }; + /// The point furthest along either search: the forward one only when /// it has come strictly further. fn giveUp(s: *Search, x0: usize, y0: usize, n: isize, m: isize, fmin: isize, fmax: isize, bmin: isize, bmax: isize) Split { diff --git a/src/diff/histogram.zig b/src/diff/histogram.zig index a00fa58..9423320 100644 --- a/src/diff/histogram.zig +++ b/src/diff/histogram.zig @@ -209,7 +209,7 @@ pub fn diffClasses(gpa: Allocator, ca: []const u32, cb: []const u32, a_changed: while (i < a1) : (i += 1) count[ca[i]] = 0; const b = best orelse { - try LineDiff.diffClasses(gpa, ca[a0..a1], cb[b0..b1], a_changed[a0..a1], b_changed[b0..b1], false); + try LineDiff.diffClasses(gpa, ca[a0..a1], cb[b0..b1], a_changed[a0..a1], b_changed[b0..b1], .fallback); continue; }; if (from_start) { @@ -223,7 +223,7 @@ pub fn diffClasses(gpa: Allocator, ca: []const u32, cb: []const u32, a_changed: @memset(b_changed[b0..y0], true); continue; } - try LineDiff.diffClasses(gpa, cb[b0..y0], ca[a0..x0], b_changed[b0..y0], a_changed[a0..x0], false); + try LineDiff.diffClasses(gpa, cb[b0..y0], ca[a0..x0], b_changed[b0..y0], a_changed[a0..x0], .fallback); var p0 = a0; var q0 = b0; var p1 = x0; diff --git a/src/diff/patience.zig b/src/diff/patience.zig index 6d7e3a7..ec5a494 100644 --- a/src/diff/patience.zig +++ b/src/diff/patience.zig @@ -111,7 +111,7 @@ pub fn diffClasses(gpa: Allocator, ca: []const u32, cb: []const u32, a_changed: for (cb[b0..b1]) |c| count_b[c] = 0; if (pairs.items.len == 0) { - try LineDiff.diffClasses(gpa, ca[a0..a1], cb[b0..b1], a_changed[a0..a1], b_changed[b0..b1], false); + try LineDiff.diffClasses(gpa, ca[a0..a1], cb[b0..b1], a_changed[a0..a1], b_changed[b0..b1], .fallback); continue; } diff --git a/src/diff/tests.zig b/src/diff/tests.zig index 4d3aa6c..5a47b52 100644 --- a/src/diff/tests.zig +++ b/src/diff/tests.zig @@ -547,22 +547,22 @@ fn blockSwap(gpa: std.mem.Allocator, half: usize, k: usize, old: *std.ArrayList( try new.appendSlice(gpa, a_part.items); } -test "a search for a middle snake past 256 steps is refused" { - // 65,534 lines search to 512 steps, where git may split a box early - // by a rule only partly found (the case that showed it, harness seed - // 302, was 67,479 lines). Below that, 256 steps and git's give-up. +test "a search past 256 steps that meets the other is not split early" { + // 65,534 lines search to 512 steps. The forward search finds A, a + // snake long and far out enough to split at, on the step the backward + // search meets it on that same snake: git keeps A either way. const gpa = testing.allocator; var old: std.ArrayList(u8) = .empty; defer old.deinit(gpa); var new: std.ArrayList(u8) = .empty; defer new.deinit(gpa); try blockSwap(gpa, 32767, 300, &old, &new); - try testing.expectError(error.LongSearchUnsupported, LineDiff.compute(gpa, old.items, new.items, .{ .indent_heuristic = false })); - try testing.expectError(error.LongSearchUnsupported, LineDiff.compute(gpa, old.items, new.items, .{})); - // --minimal never gives up, and keeps A. - var m = try LineDiff.compute(gpa, old.items, new.items, .{ .algorithm = .minimal, .indent_heuristic = false }); - defer m.deinit(gpa); - try testing.expectEqual(@as(usize, 303), countTrue(m.a_changed)); + for ([_]LineDiff.Options{ .{ .indent_heuristic = false }, .{}, .{ .algorithm = .minimal, .indent_heuristic = false } }) |options| { + var d = try LineDiff.compute(gpa, old.items, new.items, options); + defer d.deinit(gpa); + try testing.expectEqual(@as(usize, 303), countTrue(d.a_changed)); + try testing.expectEqual(@as(usize, 303), countTrue(d.b_changed)); + } // Two lines fewer: git gives up at 256 steps and keeps only C. old.clearRetainingCapacity(); @@ -573,6 +573,86 @@ test "a search for a middle snake past 256 steps is refused" { try testing.expectEqual(@as(usize, 32766 - 300), countTrue(d.a_changed)); } +/// One planted snake: `len` lines of A, from line `from` of it, put in +/// the new text's copy of C at line `at`. +const Plant = struct { from: usize, at: usize, len: usize }; + +/// a = x M A B C, b = y M C' B A, 35,000 lines or so each, where M is +/// 5,000 lines in common, A and C occur once in each text, and C' is C +/// with `plants` put in it, sorted by `at`. Every line occurs in both +/// texts, so none is taken out, and the forward search reaches line `at` +/// of C' against line `from` of A at step `from + at + 2`, 5,001 lines +/// from its corner and more. +fn plantedSnakes(gpa: std.mem.Allocator, plants: []const Plant, old: *std.ArrayList(u8), new: *std.ArrayList(u8)) !void { + const k = 490; + const m = 5000; + var total: usize = 0; + for (plants) |p| total += p.len; + const al = 35000 - k - 4 - m - total; + try old.print(gpa, "a{d}\n", .{al - 1}); + try new.print(gpa, "c0\n", .{}); + for (0..m) |i| { + try old.print(gpa, "m{d}\n", .{i}); + try new.print(gpa, "m{d}\n", .{i}); + } + for (0..al) |i| try old.print(gpa, "a{d}\n", .{i}); + var c: usize = 0; + var pos: usize = 0; + for (plants) |p| { + while (pos < p.at) : (pos += 1) { + try new.print(gpa, "c{d}\n", .{c}); + c += 1; + } + for (p.from..p.from + p.len) |i| try new.print(gpa, "a{d}\n", .{i}); + pos += p.len; + } + while (c < k) : (c += 1) try new.print(gpa, "c{d}\n", .{c}); + try old.appendSlice(gpa, "b0\nb1\nb2\n"); + try new.appendSlice(gpa, "b0\nb1\nb2\n"); + for (0..k) |i| try old.print(gpa, "c{d}\n", .{i}); + for (0..al) |i| try new.print(gpa, "a{d}\n", .{i}); +} + +fn expectPlanted(plants: []const Plant, deleted: usize, added: usize) !void { + const gpa = testing.allocator; + var old: std.ArrayList(u8) = .empty; + defer old.deinit(gpa); + var new: std.ArrayList(u8) = .empty; + defer new.deinit(gpa); + try plantedSnakes(gpa, plants, &old, &new); + var d = try LineDiff.compute(gpa, old.items, new.items, .{ .indent_heuristic = false }); + defer d.deinit(gpa); + try testing.expectEqual(deleted, countTrue(d.a_changed)); + try testing.expectEqual(added, countTrue(d.b_changed)); +} + +test "past 256 steps a step with a snake of 21 lines splits early" { + // Each count is git's (`diff --no-index --numstat`) for the same texts. + // A 21-line snake at step 302 is split at, a 20-line one is not. + try expectPlanted(&.{ .{ .from = 150, .at = 150, .len = 21 }, .{ .from = 40, .at = 300, .len = 1 } }, 644, 666); + try expectPlanted(&.{ .{ .from = 150, .at = 150, .len = 20 }, .{ .from = 40, .at = 300, .len = 1 } }, 494, 515); + // With a 21-line snake found on the same step, the 20-line one, which + // ends further out, is split at; found a step later, the 21-line one. + try expectPlanted(&.{ .{ .from = 150, .at = 150, .len = 20 }, .{ .from = 40, .at = 260, .len = 21 } }, 644, 685); + try expectPlanted(&.{ .{ .from = 150, .at = 150, .len = 20 }, .{ .from = 40, .at = 261, .len = 21 } }, 534, 575); + // A 19-line snake is not split at, even so. + try expectPlanted(&.{ .{ .from = 150, .at = 150, .len = 19 }, .{ .from = 40, .at = 260, .len = 21 } }, 534, 574); +} + +test "past 256 steps a step with two snakes of 21 lines is refused" { + // How git chooses between two triggers on one step is not known. + const gpa = testing.allocator; + var old: std.ArrayList(u8) = .empty; + defer old.deinit(gpa); + var new: std.ArrayList(u8) = .empty; + defer new.deinit(gpa); + try plantedSnakes(gpa, &.{ .{ .from = 150, .at = 150, .len = 21 }, .{ .from = 40, .at = 260, .len = 21 } }, &old, &new); + try testing.expectError(error.LongSearchUnsupported, LineDiff.compute(gpa, old.items, new.items, .{ .indent_heuristic = false })); + // --minimal never splits early. + var m = try LineDiff.compute(gpa, old.items, new.items, .{ .algorithm = .minimal, .indent_heuristic = false }); + defer m.deinit(gpa); +} + fn fuzzEngine(_: void, smith: *testing.Smith) anyerror!void { var buffer: [4096]u8 = undefined; const flags, const old, const new = splitInput(fuzz_input.bytes(smith, &buffer)); diff --git a/tools/diff_tests.zig b/tools/diff_tests.zig index a2b7db4..ff39ba8 100644 --- a/tools/diff_tests.zig +++ b/tools/diff_tests.zig @@ -218,12 +218,58 @@ test "diff --no-index: the search limit on large texts" { // 65,532 lines: git gives up after 256 steps, as zig-git does. try writeBlockSwap(&repo, 32766, "a1", "b1"); try same(&repo, &.{ "diff", "--no-index", n, "-U1", "a1", "b1" }); - // 65,534 lines: the search may go on to 512 steps, past where git's - // choices are known, so zig-git refuses; --minimal still answers. + // 65,534 lines: the search may go on to 512 steps, and finds the + // middle snake on a step that could also split early, at that snake. try writeBlockSwap(&repo, 32767, "a2", "b2"); - try refused(&repo, &.{ "diff", "--no-index", n, "-U1", "a2", "b2" }); - try refused(&repo, &.{ "diff", "--no-index", "-U1", "a2", "b2" }); + try same(&repo, &.{ "diff", "--no-index", n, "-U1", "a2", "b2" }); + try same(&repo, &.{ "diff", "--no-index", "-U1", "a2", "b2" }); try same(&repo, &.{ "diff", "--no-index", n, "--minimal", "-U1", "a2", "b2" }); + // Early splits nested five deep, as git makes them. + const gpa = testing.allocator; + var old: std.ArrayList(u8) = .empty; + defer old.deinit(gpa); + var new: std.ArrayList(u8) = .empty; + defer new.deinit(gpa); + try nestedSplits(gpa, &old, &new); + try write(&repo, "a3", old.items); + try write(&repo, "b3", new.items); + try same(&repo, &.{ "diff", "--no-index", n, "-U1", "a3", "b3" }); + try same(&repo, &.{ "diff", "--no-index", "a3", "b3" }); + // Two triggers on one step are refused; --minimal still answers. + old.clearRetainingCapacity(); + new.clearRetainingCapacity(); + try twoTriggers(gpa, &old, &new); + try write(&repo, "a4", old.items); + try write(&repo, "b4", new.items); + try refused(&repo, &.{ "diff", "--no-index", n, "-U1", "a4", "b4" }); + try refused(&repo, &.{ "diff", "--no-index", "a4", "b4" }); + try same(&repo, &.{ "diff", "--no-index", n, "--minimal", "-U1", "a4", "b4" }); +} + +/// Five units, each one differing line, 13,000 lines in common and then +/// 171 lines of A against 200 of C with A's last 21 lines put in C at line +/// 150, all of A and C repeated after the units so that no line is taken +/// out: each unit's 21-line snake splits early about 300 steps into the +/// box the unit before left, so the early splits nest five deep. +fn nestedSplits(gpa: std.mem.Allocator, old: *std.ArrayList(u8), new: *std.ArrayList(u8)) !void { + for (0..5) |u| { + try old.print(gpa, "c{d}_199\n", .{u}); + try new.print(gpa, "a{d}_0\n", .{u}); + for (0..13000) |i| { + try old.print(gpa, "m{d}_{d}\n", .{ u, i }); + try new.print(gpa, "m{d}_{d}\n", .{ u, i }); + } + for (0..171) |i| try old.print(gpa, "a{d}_{d}\n", .{ u, i }); + for (0..150) |i| try new.print(gpa, "c{d}_{d}\n", .{ u, i }); + for (150..171) |i| try new.print(gpa, "a{d}_{d}\n", .{ u, i }); + for (150..200) |i| try new.print(gpa, "c{d}_{d}\n", .{ u, i }); + } + try old.appendSlice(gpa, "b0\nb1\nb2\n"); + try new.appendSlice(gpa, "b0\nb1\nb2\n"); + for (0..5) |u| { + for (0..200) |i| try old.print(gpa, "c{d}_{d}\n", .{ u, i }); + for (0..171) |i| try new.print(gpa, "a{d}_{d}\n", .{ u, i }); + } } test "diff --no-index: the indent heuristic" { @@ -339,3 +385,29 @@ test "diff --no-index: --output" { defer testing.allocator.free(o); try testing.expectEqualStrings(g, o); } + +/// a = x M A B C, b = y M C' B A, 35,000 lines or so each, where M is +/// 5,000 lines in common, A and C occur once in each text, and C' is C with +/// A's lines 40 to 60 put in at line 260 and its lines 150 to 170 at line +/// 150: two 21-line snakes the forward search finds on one step, past step +/// 256, where how git chooses between them is not known, so zig-git +/// refuses. +fn twoTriggers(gpa: std.mem.Allocator, old: *std.ArrayList(u8), new: *std.ArrayList(u8)) !void { + const al = 35000 - 490 - 4 - 5000 - 42; + try old.print(gpa, "a{d}\n", .{al - 1}); + try new.appendSlice(gpa, "c0\n"); + for (0..5000) |i| { + try old.print(gpa, "m{d}\n", .{i}); + try new.print(gpa, "m{d}\n", .{i}); + } + for (0..al) |i| try old.print(gpa, "a{d}\n", .{i}); + for (0..150) |i| try new.print(gpa, "c{d}\n", .{i}); + for (150..171) |i| try new.print(gpa, "a{d}\n", .{i}); + for (150..239) |i| try new.print(gpa, "c{d}\n", .{i}); + for (40..61) |i| try new.print(gpa, "a{d}\n", .{i}); + for (239..490) |i| try new.print(gpa, "c{d}\n", .{i}); + try old.appendSlice(gpa, "b0\nb1\nb2\n"); + try new.appendSlice(gpa, "b0\nb1\nb2\n"); + for (0..490) |i| try old.print(gpa, "c{d}\n", .{i}); + for (0..al) |i| try new.print(gpa, "a{d}\n", .{i}); +} diff --git a/tools/merge_diff_tests.zig b/tools/merge_diff_tests.zig index 2fc5e31..f49cfa0 100644 --- a/tools/merge_diff_tests.zig +++ b/tools/merge_diff_tests.zig @@ -490,20 +490,30 @@ fn refusedWith(repo: *Repo, args: []const []const u8, message: []const u8) !void try testing.expectEqualStrings(message, ours.stderr); } -/// a = A B C, b = C B A, `half` lines each with B of three lines and C -/// of 300, which searches for a middle snake past 256 steps once `half` -/// is over 32,766. -fn blockSwap(gpa: std.mem.Allocator, half: usize, old: *std.ArrayList(u8), new: *std.ArrayList(u8)) !void { - var a_part: std.ArrayList(u8) = .empty; - defer a_part.deinit(gpa); - var c_part: std.ArrayList(u8) = .empty; - defer c_part.deinit(gpa); - for (0..half - 303) |i| try a_part.print(gpa, "a{d}\n", .{i}); - for (0..300) |i| try c_part.print(gpa, "c{d}\n", .{i}); - for ([_]*std.ArrayList(u8){ old, new }, [_][3][]const u8{ - .{ a_part.items, "b0\nb1\nb2\n", c_part.items }, - .{ c_part.items, "b0\nb1\nb2\n", a_part.items }, - }) |out, parts| for (parts) |p| try out.appendSlice(gpa, p); +/// a = x M A B C, b = y M C' B A, 35,000 lines or so each, where M is +/// 5,000 lines in common, A and C occur once in each text, and C' is C with +/// A's lines 40 to 60 put in at line 260 and its lines 150 to 170 at line +/// 150: two 21-line snakes the forward search finds on one step, past step +/// 256, where how git chooses between them is not known, so zig-git +/// refuses. +fn twoTriggers(gpa: std.mem.Allocator, old: *std.ArrayList(u8), new: *std.ArrayList(u8)) !void { + const al = 35000 - 490 - 4 - 5000 - 42; + try old.print(gpa, "a{d}\n", .{al - 1}); + try new.appendSlice(gpa, "c0\n"); + for (0..5000) |i| { + try old.print(gpa, "m{d}\n", .{i}); + try new.print(gpa, "m{d}\n", .{i}); + } + for (0..al) |i| try old.print(gpa, "a{d}\n", .{i}); + for (0..150) |i| try new.print(gpa, "c{d}\n", .{i}); + for (150..171) |i| try new.print(gpa, "a{d}\n", .{i}); + for (150..239) |i| try new.print(gpa, "c{d}\n", .{i}); + for (40..61) |i| try new.print(gpa, "a{d}\n", .{i}); + for (239..490) |i| try new.print(gpa, "c{d}\n", .{i}); + try old.appendSlice(gpa, "b0\nb1\nb2\n"); + try new.appendSlice(gpa, "b0\nb1\nb2\n"); + for (0..490) |i| try old.print(gpa, "c{d}\n", .{i}); + for (0..al) |i| try new.print(gpa, "a{d}\n", .{i}); } test "merges: counts against the first parent of a line diff searching too long" { @@ -517,7 +527,7 @@ test "merges: counts against the first parent of a line diff searching too long" defer old.deinit(gpa); var new: std.ArrayList(u8) = .empty; defer new.deinit(gpa); - try blockSwap(gpa, 32767, &old, &new); + try twoTriggers(gpa, &old, &new); try write(&repo, "large", old.items); try write(&repo, "small", "1\n"); try repo.git(&.{ "add", "." }); -- knotmirror 0.0.1