Skip to content

fix(ext): reject stale hunks in TextCanvas.apply_patch with context validation - #8195

Open
Manohar Paturi (ManoharPaturi) wants to merge 1 commit into
microsoft:mainfrom
ManoharPaturi:fix/text-canvas-stale-hunks
Open

Manohar Paturi (ManoharPaturi) wants to merge 1 commit into
microsoft:mainfrom
ManoharPaturi:fix/text-canvas-stale-hunks

Conversation

@ManoharPaturi

Copy link
Copy Markdown

Fixes #8193

Summary

TextCanvas.apply_patch() documented context-line validation, but the hunk loop performed a blind working_lines[start:end] = replacement slice assignment — so a unified diff prepared against an older revision was silently applied to the latest revision, returning PATCH APPLIED and making stale content the newest revision (reproduced exactly as in the issue: stale edit landed, region=Tokyo).

Changes

  • Each hunk's expected source block (removed + context lines, in order) is now built alongside the replacement and compared exactly against the current content slice. Mismatch or out-of-bounds hunks raise ValueError, matching the class's existing error convention and propagating through ApplyPatchTool like its other validation errors. The check runs before add_or_update_file(), so rejected patches leave the canvas untouched.
  • Related correctness fix required by the above: the insertion index for zero-length source hunks is now source_start (not source_start - 1), which fixes silent one-line misplacement of n=0 difflib patches while keeping file-creation patches working.

Tests

python/packages/autogen-ext/tests/memory/test_text_canvas_memory.py (+100):

  • test_apply_patch_rejects_stale_hunks — the issue's repro now raises ValueError, revision 2 stays latest, and a control patch built from the real revision-2 content then applies cleanly (revision 3)
  • test_apply_patch_rejects_near_miss_context — one-char context drift is rejected (no fuzzy matching)
  • valid-patch coverage via the pre-existing test_apply_patch_increments_revision

pytest tests/memory/test_text_canvas_memory.py → 6/6 passed; ruff check + ruff format --check clean on both files. Multi-hunk, deletions, EOF appends, prepends, create-empty, zero-context insert, and chained applies manually verified unaffected.

Copilot AI lite review requested due to automatic review settings September 5, 2026 02:09

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

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.

TextCanvas.apply_patch accepts stale hunks without validating context lines

2 participants