Skip to content

Make the half-match search honor DiffTimeout - #163

Draft
flostadler wants to merge 1 commit into
sergi:masterfrom
flostadler:fix-half-match-deadline
Draft

flostadler wants to merge 1 commit into
sergi:masterfrom
flostadler:fix-half-match-deadline

Conversation

@flostadler

Copy link
Copy Markdown

Fixes #162

Problem

When DiffTimeout is more than zero, DiffMain can use much more time than DiffTimeout. diffHalfMatchI does not examine the deadline. On repetitive text, its loop and its seed search (runesIndexOf, a simple search) take quadratic time.

Change

  • diffCompute gives its deadline to diffHalfMatch and diffHalfMatchI.
  • A new unexported function, runesIndexOfDeadline, does the seed search. It examines the deadline at the first position and after each 1024 positions. If the deadline is past, it returns -1.
  • After the loop, diffHalfMatchI examines the deadline. If the deadline is past, it returns no half-match. Then diffCompute uses diffBisect, which also stops at the deadline.
  • The exported functions do not change. DiffHalfMatch uses a zero deadline, thus its results do not change.
  • runesIndex and runesIndexOf do not change.

Results

DiffTimeout = 100ms. macOS arm64.

Input Before After
"b" + "a"×100,000 + "c" vs "d" + "a"×100,000 + "e" 7.4 s 0.1 s
Seed-search case in the test (100,000 characters) 0.5 s (8.1 s at 400,000) 0.1 s

Tests

TestDiffMainHalfMatchHonorsDeadline does the two cases above. It makes sure that DiffMain stops in less than 2 s and that the diff gives the two original texts again. Without the change, the test fails. go test ./..., go test -race ./diffmatchpatch/, go vet ./... and gofmt pass.

🤖 Generated with Claude Code

diffHalfMatchI did not check the deadline, and its seed search and loop
are quadratic on repetitive text. Pass the deadline into the half-match
search, check it during the seed search, and return no half-match when
it has passed, so DiffMain falls back to bisect.

Fixes sergi#162

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@flostadler
flostadler marked this pull request as draft October 13, 2026 14:07
@sergi

sergi commented Nov 16, 2026

Copy link
Copy Markdown
Owner

Thanks for this. I tested it on top of current master and it fixes #162: the repro now stops at the timeout (about 200ms instead of 5.7s), and the full suite passes with -race. It's still marked as a draft, so I didn't merge it. Mark it ready for review when you're happy with it and I'll merge it for the next release.

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.

DiffMain ignores DiffTimeout in diffHalfMatch (quadratic on repetitive text)

2 participants