Skip to content

Make word diff, cleanup and patching linear with the same output - #17

Merged
ajitk merged 20 commits into
word-tokens-past-surrogate-gapfrom
faster-word-diff
Nov 12, 2026
Merged

ajitk merged 20 commits into
word-tokens-past-surrogate-gapfrom
faster-word-diff

Conversation

@distill-ai-dev

@distill-ai-dev distill-ai-dev commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #16. Faster word diff, cleanup and patching, same output. Also fixes one panic and one stack overflow in diff_cleanup_merge.

  • every cleanup pass now does one pass over the diff. They used to rescan or Vec::remove after each change, which is quadratic: semantic went 3.3 s → 7 ms on 30,000 shuffled words, and at 80,000 pieces lossless went 2.8 s → 18 ms, overlaps 8.9 s → 47 ms, efficiency 10.5 s → 27 ms, merge shifts 2.8 s → 34 ms
  • diff_cleanup_merge returns an empty diff when everything cancels (it panicked on subtract overflow) and runs its rounds in a loop (it recursed once per round and could overflow the stack)
  • diff_words_tochars hashes each word once and borrows it from the input. Word ids use the std keyed HashMap, so tokens with a shared prefix can't pile into one bucket
  • patch_splitmax, patch_make and patch_apply stop splicing the whole text per edit: splitting one patch of 40,000 edits 11.4 s → 14 ms, applying 20,000 sparse patches 484 → 22 ms
  • bitap zeroes only its search window, and rfind_sub searches backward from the expected spot

Tests

  • Each rewrite keeps the old loop in the tests as the reference and compares against it on seeded random inputs with pinned branch counts.
  • 43 real page pairs: all four cleanup passes hash the same before and after.

Not covered

  • patch_make still scans the whole text once per patch to check its context is unique, as the reference does.
  • patch_apply on same-length word edits is about 7% slower (1.88 → 2.02 ms at 20,000 words).
  • Merge with long chains of shifting edits is still one round per link.

Semantic cleanup rescanned from two equalities back after every
elimination, which is quadratic when a diff holds many small equalities,
as word diffs of reordered text do. Keep a stack of the equalities still
standing with the edit lengths after each, and recheck only the top one
when the edits after it grow. Output is unchanged.

Cleanup of a real 24,000-token page pair drops from 53 ms to 1.7 ms, and
of a 30,000-word shuffle from 3.3 s to 7 ms.
Word packing built an owned String per token for the map key and another
for each placeholder, and looked every word up three times. It now borrows
its keys from the input, finds or inserts with one fx-hashed lookup and
pushes the placeholder char directly.

The stretches both texts share at their ends hold the same words in both,
so they are packed once and copied to the second text. The cut backs off to
a whitespace char, where a token ends in both texts.

Output is unchanged. On 43 real page pairs packing drops from 19.6 ms to
7.5 ms.
ajitk added 14 commits November 12, 2026 08:07
Word packing had moved to the internal Fx-style hasher, whose result
keeps the token's first bytes in its low bits, the ones the map indexes
by. 4,096 words with a common three-letter prefix filled 32 buckets;
200,000 took 211 ms to pack instead of 32 ms, and words chosen to
collide took 3.7 s. The word map uses the std hasher again, which costs
0.7 ms over 43 real page pairs.

Line packing had the same weakness: 4,096 numbered lines landed in one
bucket, and diff_main in line mode took 1.1 s on 100,000 of them
against 23 ms for random lines. The hasher now rotates its well-mixed
high bits down, which brings that case to 12 ms.

No output changes: neither map's order reaches the result.
The passes below gain reference loops to test against, which would push
cleanup.rs past a thousand lines.
A diff made only of empty pieces merges down to nothing, and the shift
sweep then subtracted one from a zero length and panicked. The reference
returns an empty list.
The second half of diff_cleanup_merge removed each crossed equality with
Vec::remove, so a diff where every edit slides cost one shift of the tail
per edit. Compact in place instead and drop the leftover slots once.

20,000 / 40,000 / 80,000 alternating pieces, hand-built diff:
before 114 / 650 / 2,833 ms, after 8 / 16 / 34 ms. Output is unchanged;
the test checks 50,000 random inputs against the old loop.
diff_cleanup_merge called itself once per round of shifts. A hand-built
diff where each shift lines up the next one takes one round per piece and
overflowed a 1 MB stack at 16,000 rounds. Loop instead; the rounds and the
output are the same.

The new test runs 1,000 rounds on a 64 KiB stack, which the recursive
form overflowed.
diff_cleanup_semantic_lossless removed each equality a slide used up with
Vec::remove. Compact in place instead and drop the leftover slots once.

20,000 / 40,000 / 80,000 pieces where every slide empties an equality,
hand-built diff: before 110 / 644 / 2,832 ms, after 4 / 8 / 18 ms. Output
is unchanged; the test checks 50,000 random inputs against the old loop.
The last step of diff_cleanup_semantic put the shared text of each
delete/insert pair back with Vec::insert, and cloned both edits to look
for it. Build the result in a new vector instead and split the edits it
already owns.

20,000 / 40,000 / 80,000 overlapping pairs, hand-built diff:
before 424 / 2,093 / 8,884 ms, after 10 / 22 / 47 ms. Output is unchanged;
the test checks 50,000 random inputs against the old loop.
diff_cleanup_efficiency inserted into the list for every equality it
turned, then went back and rescanned, to the previous candidate or to
the start. Both are linear in the list, so a hand-built diff with many
cheap equalities took quadratic time.

Keep the candidates on a stack with the number of edit kinds before
each. Turning one only adds edit kinds to the runs beside it, so only
the candidate under it needs another look. Build the list once at the
end.

Same output: checked against the old loop on 50,000 random lists in
the test, and on 12 million more while developing.

80,000 pieces, edit_cost 4: 10.5 s -> 27 ms. A list where every split
sent the old loop back to the start: 52.7 s -> 52 ms.
patch_splitmax removed each big patch from the list, shifted its diffs
down one at a time, re-collected the diff it was cutting for every piece
and rebuilt the whole remaining text up to three times per piece. It now
reads the big patch front to back with an index and writes the pieces to
a new list. Output is unchanged: the old loop stays in the tests as the
reference for 3,000 random patch lists.

Splitting one patch of 40,000 small replacements drops from 8.9 s to
20 ms, a 400,000-char equality from 8.7 s to 7 ms, and 40,000 patches
that each split in two from 1.6 s to 38 ms.
patch_make4 kept a copy of the whole text and spliced each insertion and
deletion into it, moving everything after the edit every time. The text
with the edits applied is now two parts: the chars already passed, which
only grow at the end, and the untouched remainder of the source. Output
is unchanged, including the panic when a diff runs past the text: the
old loop stays in the tests as the reference for 3,000 random diff
lists, 302 of which panic.

Building one patch from 40,000 small replacements drops from 694 ms to
7 ms and now doubles with the input. Texts that produce many patches
still pay for one whole-text copy and one whole-text uniqueness scan per
patch: 20,000 patches take 15.0 s, down from 18.0 s.
patch_make4 copied the whole edited text every time it closed a patch,
only so the next patch could read its context from the text as it was
before that patch's edits. That text is already there: the chars passed
so far, which are never rewritten, followed by a tail of the source. The
context search and the uniqueness scan now read those two parts.

The scan starts with the tail, where the patch being built sits, so a
pattern that repeats is settled within a few chars instead of after a
scan from the start of the text. A unique pattern still costs one scan
of the whole text per patch.

Output is unchanged: the context search over one contiguous text stays
in the tests as the reference for 4,000 random cases, and the scan is
checked at every split of every text of up to 8 chars.

Building 20,000 patches drops from 13.0 s to 2.5 s; 3,495 patches over
20,000 words from 789 ms to 669 ms.
rfind_sub scanned from the start of the text to its bound and kept the
last hit, so every fuzzy match paid for the whole text before it even
when the hit sat right at the bound. It now tries the possible starts in
blocks from the bound backwards, each block twice as long as the one
before, and stops at the first block with a hit. A hit costs about twice
its distance from the bound; a miss still reads the text once.

Output is unchanged: the scan from the front stays in the tests as the
reference for every text of up to 11 bytes, every needle of up to 4 and
every bound.

Applying 3,495 patches to 20,000 words with one char added in front
drops from 209 ms to 16 ms.
bitap allocated and zeroed a bit array per error level that ran from the
start of the text to the end of the search window, although a level only
reads and writes the window around the expected location. The arrays now
start at the lowest index any level can reach, fixed at the first level,
so a level costs its window instead of the text before it.

Output is unchanged: the loop over whole arrays stays in the tests as the
reference for 6,000 random searches, including locations before and far
past the text and 719 searches that panic.

Applying 5,000/10,000/20,000 words of patches to the text with one char
added in front drops from 1.6/5.1/16.5 ms to 0.9/1.9/3.6 ms; with 10% of
the words added in front, from 90/255/990 ms to 76/219/715 ms.
patch_apply spliced every replacement into the whole text, so each
patch whose replacement changed length moved the rest of the text.

While each patch matches exactly where expected and changes nothing
before the previous patch's change ends, the text is now kept as the
output so far plus the unread rest of the source. The first patch that
breaks that rule (not exact, oversized, behind) turns it back into one
text, and it and all later patches run through the existing loop.

Output is unchanged: in_order_apply_matches_splicing checks results and
text against the splicing loop on 17,512 seeded applies, with path
counts pinned on the old code, and asserts the fast run covers exactly
the patches that loop applies in order.

Measured, ms at n/2n/4n:
  many sparse patches, clean   22.42/83.34/483.65 -> 5.30/10.75/22.34
  one dense patch, clean       10.19/31.26/91.44  -> 6.19/13.19/25.69
  longer words, clean           0.98/3.45/14.30   -> 0.36/0.81/4.98
  word edits, clean             0.35/0.69/1.53    -> 0.35/0.80/1.84
@distill-ai-dev distill-ai-dev changed the title Speed up the word diff: one-pass cleanup and cheaper word packing Make word diff, cleanup and patching linear with the same output Nov 12, 2026
@ajitk
ajitk added this pull request to stack #20 November 12, 2026 05:32
@ajitk
ajitk merged commit b548c30 into master Nov 12, 2026
4 checks passed
@ajitk
ajitk deleted the faster-word-diff branch November 12, 2026 12:13
ajitk added a commit that referenced this pull request Nov 12, 2026
Stacked on #17. Adds `Dmp::diff_step_budget`, a limit on diff work that
doesn't depend on a clock.

## Change

- `diff_step_budget: Option<u64>`, default `None` (no limit, as before).
One step is one diagonal visited or one token walked along a snake; the
budget is shared across one `diff_main` call.
- When it runs out, the search runs on until it has a matched run of 20+
tokens or has looked 1,024 edits ahead, splits there, and diffs the
parts in a loop with a second allowance the size of the budget. Whatever
is still unsolved comes back as delete plus insert.
- Half-match is skipped whenever a budget is set, since its work isn't
counted in steps. `diff_timeout` can still be set alongside; whichever
runs out first stops the search.

## Why

`diff_timeout` is wall-clock, so the same two texts can give different
diffs on a fast and a busy machine. A step budget gives the same output
every time. One step is about 2.4 ns native, so 400M steps is about 1 s.

Giving up on the whole region loses every match in it. On 18 real page
pairs at 10% of the steps they need, edits were 3.34× the exact diff
with plain delete plus insert and 1.49× with the split.

## Tests

- `a_spent_budget_keeps_what_it_found` and
`an_over_budget_diff_keeps_long_matches` pin the output at exact
budgets.
- 900 random runs: both texts rebuild, reruns are equal, no empty
pieces, merge is a fixed point.
- Work stays within 2 × budget plus one snake; 200,000 unrelated chars
finish on a 256 KB stack.
- No budget, a sufficient budget, and timeout-only give the same output
as before.
- One over-budget case each for budget + timeout, word mode, grapheme
mode, `diff_bisect` and line mode.
- `"ab"×20,000` vs `"ba"×20,000 + "c"` at budget 0 with the default
timeout returns delete plus insert without the half-match scan.

## Not covered

- Total work is up to twice the budget, and two unrelated texts pay that
for no gain.
- A larger budget usually gives a shorter diff, not always.
- A diff with a budget searches about 13% slower than one without,
measured on 43 real page pairs (counting steps plus tracking matched
runs). Diffs without a budget run the plain copy.
- Budgets under roughly half a million steps on texts with little in
common return delete plus insert, same as budget 0.
- `diff_step_budget` is a new public field: a full `Dmp { .. }` literal
without `..Dmp::new()` needs it.

---------

Co-authored-by: ajit <ajit@distill.io>
ajitk added a commit that referenced this pull request Nov 12, 2026
Stacked on #18. Bumps `diff_match_patch` to 0.3.2.

## In this release

- #16: `diff_words_tochars` no longer panics on the 55,296th distinct
word.
- #17: the word diff is faster with the same output (one-pass semantic
cleanup, cheaper word packing).
- #18: `Dmp::diff_step_budget`, a limit on diff work that gives the same
output on every machine.

## Upgrade note

`diff_step_budget` is a new public field on `Dmp`. Code that builds
`Dmp` with a full struct literal and no `..Dmp::new()` needs to add it.
With it set, `diff_main` skips the half-match shortcut, so the budget
bounds the search on its own.

Not published to crates.io yet; that happens after this merges.

---------

Co-authored-by: ajit <ajit@distill.io>
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