fix(task-5): a rollback that fails after a cancellation no longer kills the session, and the COM rollback goes back to an UNDO Mark instead of prompting

Two review findings on 32821c6.

1. Once the shielded rollback body runs after a real client cancellation it
   can fail (the COM hard timeout, _safe_send_command's own deadline, an
   ezdxf quarantine refusal). That RuntimeError escaped run_spec as an
   ordinary error and the mcp lowlevel server, which had already answered
   the cancelled request, tried to respond a second time: `assert not
   self._completed` in mcp/shared/session.py escaped the server task group
   and the whole session died (measured through the real transport: the next
   system_status was never answered and Client.__aexit__ re-raised the
   AssertionError). run_spec now decides by the exception it is handling:
   after a cancellation the rollback error is logged and the cancellation is
   what propagates, so the SDK's cancellation suppression applies; after any
   other error the rollback error propagates as before, with the original
   chained as its context.

2. The docstring promised the rollback on both engines, but on the live
   AutoCAD 2026 ComBackend.transaction_rollback sent `_UNDO B` with no UNDO
   Mark in the stack (StartUndoMark/EndUndoMark form an undo *group*, not a
   Mark), AutoCAD answered "This will undo everything. OK? <Y>", SendCommand
   blocked at that prompt, _run gave up after 60 s, the entities stayed and
   every COM client was rejected until a human pressed ESC. transaction_begin
   now types `_.UNDO _M` before StartUndoMark (refused with ok:false while
   CMDACTIVE, where the Mark would be swallowed as input), and
   transaction_rollback ends the group and sends `_.UNDO _B`, which returns
   exactly to that Mark - also on an empty transaction, where `_UNDO 1` would
   be one step too many. A rollback with no transaction is refused the way the
   headless engine refuses it, because an unmarked Back is that prompt.
   Measured with the real ComBackend in a scratch Documents.Add() document on
   the running AutoCAD 2026 (closed with Close(False)): begin 31 ms ->
   entity_create_line + circle -> rollback 63 ms -> 3 entities back to 1,
   CMDACTIVE 0, no prompt; an empty begin/rollback leaves the older line;
   begin/commit unchanged.

Tests: the two failure modes on run_spec (anyio scope cancellation with a
raising rollback completes the task group and logs; a ValueError with a
raising rollback still raises the rollback error with the ValueError as
context), the real-transport case (client.cancel mid-run, rollback raises,
the next request is answered, cleanup through the real rollback), the COM
shape now pins `_.UNDO _M, StartUndoMark, EndUndoMark, _.UNDO _B`, and
test_com_sprint3 grows a Mark-keeping fake document whose unmarked Back
fails the way the prompt does: begin before the group, rollback consumes the
Mark, rollback without a transaction sends nothing, begin refuses on
CMDACTIVE.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FKFStjEFzpGyLq5bMpWxTd
This commit is contained in:
Umut CAN
2026-09-21 21:46:08 +03:00
co-authored by Claude Opus 5
parent 32821c6410
commit 2e101b95e2
7 changed files with 304 additions and 21 deletions
+29 -2
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
import copy
import logging
import math
from typing import TYPE_CHECKING
@@ -18,6 +19,8 @@ from .symbols import resolve, transform_port
if TYPE_CHECKING:
from backends.base import AutoCADBackend
log = logging.getLogger(__name__)
EXAMPLE_SPEC: dict = {
"sheet": {
"layer_set": "pid",
@@ -440,7 +443,7 @@ async def run_spec(backend: AutoCADBackend, spec: dict, dry_run: bool = False) -
except ValueError as exc:
raise ValueError(f"{where}: {exc}") from exc
crossings_total += drawn["crossings"]
except BaseException:
except BaseException as exc:
# ``Exception`` alone let a client cancellation (``CancelledError`` is
# a ``BaseException``) leave the placed symbols in the drawing inside
# an open transaction — on COM with the undo mark still open, so every
@@ -455,8 +458,32 @@ async def run_spec(backend: AutoCADBackend, spec: dict, dry_run: bool = False) -
# transaction, and on COM the undo mark left open while the backend's
# flag already said "no transaction". A native ``Task.cancel()`` is
# delivered once and clears, so it was never the case that mattered.
#
# Once the rollback body runs after a cancellation it can also *fail*
# (the COM hard timeout, ``_safe_send_command``'s own deadline, an
# ezdxf quarantine refusal). That failure must not replace the
# cancellation: the SDK has already answered the cancelled request,
# and only a cancellation exception is suppressed by its handler — an
# ordinary error makes it respond a second time, which trips
# ``assert not self._completed`` in ``mcp.shared.session`` and kills
# the whole session (measured through the real transport). So after a
# cancellation the rollback error is logged and the cancellation is
# what propagates; after any other error the rollback error propagates
# as before, with the original chained as its context.
cancelled = isinstance(exc, anyio.get_cancelled_exc_class())
with anyio.CancelScope(shield=True):
await backend.transaction_rollback()
try:
await backend.transaction_rollback()
except Exception as rollback_exc:
if not cancelled:
raise
log.error(
"pid_from_spec: rollback after a cancelled request failed (%s: %s); "
"the sheet may be half-drawn - check system_status and "
"transaction_rollback before retrying",
type(rollback_exc).__name__,
rollback_exc,
)
raise
await backend.transaction_commit()
graph = await build_graph(backend)