Repository navigation
fix(tools): refuse str_replace when old_str matches at overlapping offsets - #6429
Conversation
VascoSch92
left a comment
There was a problem hiding this comment.
Thanks for this, the overlap check itself is right and the new test pins it down nicely.
One thing I ran into while testing: wrapping the pattern in a lookahead (here and here) stops Python's regex engine from using its fast literal search, so it tries a full match at every offset. On a 9 MB file that is mostly one repeated character, with an old_str of about 1000 characters, str_replace goes from 0.013 s on main to roughly 14 s on this branch. Ordinary code files are less extreme but still slower; an old_str that isn't in a 9 MB file went from about 0.05 s to 0.2 s.
A plain str.find loop gives exactly the same overlapping positions and is actually faster than main (0.007 s on the same input):
starts = []
i = file_content.find(old_str)
while i != -1:
starts.append(i)
i = file_content.find(old_str, i + 1)Could you switch both scans to that? Everything else in the PR looks good to me.
|
Good catch on the lookahead — switched both scans to the One data point from re-running your pathological input (9 MB of one repeated character,
|
HUMAN:
Fixed the overlapping-match check from #6348. I reviewed the diff and the test; an ambiguous old_str must be refused, not silently applied to the first match.
AGENT:
Why
str_replacecounted occurrences withre.finditer, which only reports non-overlapping matches. Inaaa,old_str="aa"matches at offsets 0 and 1, but the scan saw one occurrence and replaced the first one — the uniqueness check passed on an ambiguous string, contradicting its own contract.Summary
(?=pattern)), which reports every start position including overlapping ones, so an ambiguousold_strraises the "Multiple occurrences"ToolErrorand leaves the file unchanged.test_str_replace_rejects_overlapping_occurrencesfrom theworktree-test-edge-casesbranch (commit f2fcf6e) without itsxfail(strict=True)marker, per the [Bug]: Edge-case tests expose ~70 bugs across the SDK, agent server, tools and workspaces #6348 menu's acceptance criteria.Issue Number
Part of #6348 (menu sub-item: "str_replace uniqueness check misses overlapping occurrences")
How to Test
Before this change the replacement goes through; after, it raises
ToolErrormentioning multiple occurrences andaaa\nis untouched. The fulltests/tools/file_editor/suite is 170 passed, including the empty-old_strand multi-occurrence cases, whose messages are unchanged.ruff check/formaton the touched files are clean.Type
Notes
The line numbers in the error come from the same lookahead matches, so they stay accurate for ordinary (non-overlapping) inputs.