Skip to main content
Back to Community & Earn Hub

The sneaky git diff bug that made our coding agent re-apply the same patch twice

@chloe_martinez1 day ago·1 min read 2229 views
The sneaky git diff bug that made our coding agent re-apply the same patch twice

If you've ever built an edit_file tool for a coding agent, you've probably seen this happen: the agent reads routes.py, spots two things to fix, and either emits two edits back-to-back or retries after a linter warning using line numbers from three turns ago.

Line-number patching (replace lines 42-50) is brittle because the moment edit #1 inserts 6 lines at line 20, line 42 is no longer line 42. Worse, if the agent retries a patch blindly, it can duplicate an entire if block or chop a function in half.

Require an exact target block + file ETag

We swapped our line-range editor for two boring checks:

  1. Unique exact-text match: The agent passes target and replacement. If target appears 0 times or >1 time in the file, reject the edit immediately and tell it to include more surrounding lines.
  2. Stale-read ETag: Return a short sha256 prefix on every read_file call and check it before writing so parallel edits can't silently overwrite each other.
python
import hashlib
from pathlib import Path

def safe_replace(path: Path, target: str, replacement: str, expected_sha: str) -> str:
    content = path.read_text(encoding="utf-8")
    current_sha = hashlib.sha256(content.encode()).hexdigest()[:10]
    if current_sha != expected_sha:
        raise ValueError(f"File changed since last read ({current_sha} != {expected_sha}); re-read first.")

    count = content.count(target)
    if count != 1:
        raise ValueError(f"Target matched {count} times; must match exactly once.")

    updated = content.replace(target, replacement, 1)
    path.write_text(updated, encoding="utf-8")
    return hashlib.sha256(updated.encode()).hexdigest()[:10]

Mangled edits disappeared almost immediately after adding those 10 lines.

2 Comments

Discussion

@marcus_chen1 day ago

Requiring content.count(target) == 1 plus a file hash check is so much safer than line-number patching. Models lose track of line offsets constantly.

@aarav_sharma1 day ago

Stale-read ETag checks also catch the case where a pre-commit formatter modified the file between two agent turns.

Join the developer discussion

Sign in or create a free account to comment (+10 pts) and tag helpful AIStoreHub repositories.