Skip to content

fix(filesystem): refuse an edit_file oldText that matches more than once - #5078

Open
vishalhabib99 wants to merge 3 commits into
docker:mainfrom
vishalhabib99:fix/edit-file-ambiguous-oldtext
Open

vishalhabib99 wants to merge 3 commits into
docker:mainfrom
vishalhabib99:fix/edit-file-ambiguous-oldtext

Conversation

@vishalhabib99

Copy link
Copy Markdown

Fixes #3929

This picks up #3929 after #3930 closed as stale on merge conflicts. #3930's approach was reviewed and approved there. The edit logic has since moved into types.ApplyEdits and gained CRLF retry, so this is a new change against current main. Credit to @dwin-gharibi for the report and the original design.

Problem

edit_file checks that oldText occurs at least once, then calls strings.Replace(content, oldText, newText, 1). When oldText occurs more than once, the first occurrence is rewritten and the tool still reports File edited successfully. The model can't tell whether it edited the place it meant. If it meant a later occurrence, the wrong code changes and nothing prompts the model to read the file again.

On main (51f04e7):

file:  def dev():\n    debug = True\ndef prod():\n    debug = True\n
edit:  oldText="    debug = True"  newText="    debug = False"

result: "File edited successfully. Replaced 16 characters"
file:   def dev():\n    debug = False\ndef prod():\n    debug = True\n

The ACP transport (pkg/acp/filesystem.go) serves the same edit_file tool and has the same check.

Fix

  • types.ApplyEdits counts matches with strings.Count and doesn't use strings.Contains. Zero matches still return old text not found. More than one match now returns Edit N failed: old text appears K times; include more surrounding context so it matches exactly once, and nothing is written.
  • Matches are counted against the content as it stands after the earlier edits in the same call, the same way edits are applied. An earlier edit can therefore make a later oldText unique.
  • The CRLF retry counts the converted text, so an ambiguous LF oldText in a CRLF file is refused too.
  • The ACP edit_file handler gets the same check, with the same message.

Tool descriptions are unchanged, so the e2e cassettes don't change.

Three existing tests used a repeated oldText only as fixture data. I gave them unique matches and kept what they check: TestApplyEdits and TestEditFileRecordsAggregateDiff keep the same before/after content (same\nsame\n to same\n), and TestEditDiffCapturesWholeFile still chains a second edit onto the first one's output.

Tests

New: TestFilesystemTool_EditFileRejectsAmbiguousOldText (built-in toolset, 5 cases) and TestEditRefusesAmbiguousOldText (ACP). TestApplyEdits also asserts the new error.

Before the fix, the three refusal cases fail:

--- FAIL: TestFilesystemTool_EditFileRejectsAmbiguousOldText/oldText_matching_twice_is_refused
    "File edited successfully. Replaced 16 characters" does not contain "Edit 1 failed: old text appears 2 times"
    actual: "def dev():\n    debug = False\ndef prod():\n    debug = True\n"
--- FAIL: .../ambiguous_edit_after_a_valid_one_leaves_the_file_untouched
    "File edited successfully. Changes:\nEdit 1: Replaced 10 characters\nEdit 2: Replaced 16 characters" ...
--- FAIL: .../ambiguous_LF_edit_in_a_CRLF_file_is_refused
    actual: "x\r\na\r\nb\r\n"
--- FAIL: TestEditRefusesAmbiguousOldText (ACP)

After the fix, all of them pass.

Commands run:

  • go test ./... with .env.test (same as task test): passes
  • golangci-lint run (v2.14.0) on pkg/acp/... and pkg/tools/builtin/filesystem/...: 0 issues
  • golangci-lint fmt --diff: clean
  • go run ./lint .: no offenses
  • go mod tidy --diff: clean

AI disclosure

I used Claude Code to find the issue, write the regression tests and draft the change and this description. I reproduced the bug on main, reviewed every line and ran the checks above myself.

edit_file only checked that oldText occurred at least once, then replaced
the first occurrence. An oldText that occurred more than once silently
rewrote the first match and still reported success, so the model could not
tell whether it edited the site it meant.

Count matches instead. Zero matches still fail with "old text not found";
more than one now fails with the count and a hint to add context, and the
file is left untouched. Matches are counted against the content as it
stands after earlier edits in the same call, and the CRLF retry counts the
converted text. The ACP edit_file handler gets the same check.

Fixes docker#3929

Signed-off-by: Vishal Habib <vishalhabib99@gmail.com>
@vishalhabib99
vishalhabib99 requested a review from a team as a code owner November 30, 2026 18:47
@aheritier aheritier added area/tools For features/issues/fixes related to the usage of built-in and MCP tools kind/fix PR fixes a bug (maps to fix:). Use on PRs only. labels Nov 30, 2026
@aheritier

Copy link
Copy Markdown
Collaborator

👋 Thanks for the update. This PR has merge conflicts with the base branch. Please rebase or merge the latest base branch and resolve them. It has been moved to draft and marked status/needs-rebase; it will be picked back up automatically once the conflicts are cleared.

@aheritier aheritier 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.

One blocking issue: overlapping matches can still silently edit the wrong occurrence.

[should-fix] Update the validation section in docs/tools/filesystem/index.md:51 to say that oldText must match exactly once in the content produced by any earlier edits in the same call, and that an ambiguous match leaves the file unchanged.

}
oldText, newText := edit.OldText, edit.NewText
if !strings.Contains(content, oldText) {
n := strings.Count(content, oldText)

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.

[blocking] strings.Count skips overlapping matches. In header\nsame\nsame\nfooter\n, oldText: "\nsame\n" can match either same line because the two matches share the middle newline. The count is 1, so the edit rewrites the first line and reports success—the wrong-site edit #3929 is meant to prevent. Reject matches at distinct start offsets even when they overlap, including in the CRLF retry at line 37 and in the ACP handler at pkg/acp/filesystem.go:457. Add regression cases that assert an error and no write.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks, good catch. Fixed in b010bd4:

  • Added types.CountMatches, which counts every start offset (advancing by one byte, so overlapping matches count), and used it at all three sites: the direct match and the CRLF retry in ApplyEdits, and the ACP edit_file handler.
  • Regression cases for header\nsame\nsame\nfooter\n with oldText: "\nsame\n" (LF, CRLF retry, and ACP), each asserting the error and that nothing is written. They fail on the previous commit and pass now.
  • Docs: the validation section now says oldText must match exactly once in the content produced by earlier edits in the same call, and that an ambiguous match leaves the file unchanged.

@aheritier
aheritier marked this pull request as draft December 1, 2026 11:03
@aheritier

Copy link
Copy Markdown
Collaborator

Please move this PR back to ready for review once the requested changes are addressed.

strings.Count skips overlapping matches, so an oldText such as "\nsame\n"
in "header\nsame\nsame\nfooter\n" counted once although it matches at two
start offsets, and edit_file rewrote the first one and reported success.

Add types.CountMatches, which counts every start offset including overlaps,
and use it for the direct match, the CRLF retry, and the ACP edit_file
handler. Add regression cases that assert an error and no write, and note
in the docs that oldText must match exactly once in the content produced by
earlier edits in the same call, and that an ambiguous match leaves the file
unchanged.

Signed-off-by: Vishal Habib <vishalhabib99@gmail.com>
@vishalhabib99
vishalhabib99 marked this pull request as ready for review December 1, 2026 14:16

@aheritier aheritier 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.

One blocking performance regression: rejecting an ambiguous edit can require millions of redundant comparisons. The overlapping-match and documentation feedback is addressed.

func CountMatches(s, substr string) int {
n := 0
for {
i := strings.Index(s, substr)

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.

[blocking] Both the built-in and ACP edit_file paths keep counting after the second match has already made the edit invalid. Advancing by one byte makes strings.Index recompare the entire oldText at each overlapping match. For a 16 MiB file of repeated abc\n lines and a 32 KiB oldText from that block, this means about 4.2 million full comparisons—roughly 128 GiB of cumulative comparison work before returning an error. That's a source-derived estimate, not a wall-clock measurement. Stop at the second match, starting the second search one byte after the first match's start so overlaps are still rejected, and report that the text matches more than once. Keep the no-write regression tests and add a benchmark for densely overlapping matches.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in 70eb3c6. Both edit_file paths now call CountMatchesUpTo(content, oldText, 2), which stops at the second match. It still starts the next search one byte after the previous match start, so overlapping matches are still rejected. The error now says the old text "matches more than once" instead of giving a count.

I added a benchmark (BenchmarkApplyEditsDenselyOverlapping) and a regression test that use your case: a 32 KiB oldText in a 16 MiB file of repeated abc\n lines. On my machine, rejecting it took ~1.52 s before this change and ~18 µs after. The no-write regression tests are unchanged apart from the new message, and go test ./pkg/tools/builtin/filesystem/... ./pkg/acp/... passes.

@aheritier
aheritier marked this pull request as draft December 1, 2026 16:31
Both edit_file paths only need to know whether oldText matches zero,
one, or more than one time. Counting every overlapping match made a
rejected edit scan the whole file, recomparing oldText at each offset:
a 32 KiB oldText in a 16 MiB file of repeated lines took ~1.5 s to
reject. Stop at the second match (still advancing one byte, so
overlapping matches are rejected) and report that the text matches
more than once. Adds a regression test and a benchmark for densely
overlapping matches.

Signed-off-by: Vishal Habib <vishalhabib99@gmail.com>
@vishalhabib99
vishalhabib99 marked this pull request as ready for review December 1, 2026 21:43

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/tools For features/issues/fixes related to the usage of built-in and MCP tools kind/fix PR fixes a bug (maps to fix:). Use on PRs only.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

edit_file silently edits the first match when oldText occurs more than once

2 participants