tickets: run: on Windows, a rollback's plan delete has no sharing-violation retry, so a briefly held plan pauses the run

未关闭
#967 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
3/5
预计耗时
1-2 天
新手友好度
56/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
python
领域
backend

调研方向

Start in src/bmad_loop/tickettree.py at discard_unbuilt_plan and restore_preimage, then read platform_util.retrying_unlink in src/bmad_loop/platform_util.py for the existing Windows sharing-violation retry behavior. Check how restore_preimage handles missing files and how tickets_engine.py pauses when re-arming fails. Done means both deletion paths retry while preserving missing-file behavior, and a held plan no longer prevents the next attempt from dispatching.

由索引模型根据 Issue 内容生成。

描述

Summary

After a failed attempt is rolled back, the tickets run deletes a plan that holds only frontmatter (TicketTree.discard_unbuilt_plan), and TicketTree.restore_preimage(plan, None) deletes one the same way. Both call Path.unlink() directly. bmad-loop's own platform_util.retrying_unlink exists for exactly this case ("an AV/indexer scanning the just-written source file fails the unlink") and is used by the other staged moves. On Windows, a process that holds the plan for a few seconds with read-share but not delete-share makes the delete fail at once with WinError 32. The run then pauses at ticket-tree with "re-arming 1.1's plan after its rollback failed (tickets.py plan-io: … cannot delete …)", instead of riding out the hold and dispatching attempt 2.

The measured holder is a separate pwsh process holding the plan open with read sharing and no delete sharing. A scanner, an indexer or an editor preview is a plausible source of that handle pattern; none of those products was tested. The run pauses visibly and loses no data; the defect is the missing bounded retry, not the fail-loud pause itself.

Environment

bmad-loop a5a8f097, Windows 11 (10.0.26200, NTFS), PowerShell 7.6.6 (SHELL unset), Python 3.13.2; mock adapter (TicketsEngine, real TicketTree), [scm] isolation = "none", rollback_on_failure = true, two dev attempts; Linux oracle: n/a (no sharing violation on POSIX)

Steps to reproduce

The repro is complete and runs from PowerShell 7 with SHELL removed. From a bmad-loop checkout at a5a8f097 (uv sync --all-extras done once):

Remove-Item Env:SHELL -ErrorAction SilentlyContinue
$env:PYTHONUTF8 = '1'
# save the script below as repro_unlink.py in the checkout root, then:
uv run python repro_unlink.py 0   # positive control: no holder
uv run python repro_unlink.py 3   # trigger: the plan is held for 3 s right after attempt 1 ends

The script builds the test suite's v7 sandbox (tests/conftest.py helpers) under $env:TEMP\unlink-repro. Attempt 1's mock session writes src.txt and a frontmatter-only plan at status: in-progress, then starts the holder and crashes. The holder is pwsh -Command "$f=[IO.File]::Open('<plan>','Open','Read','Read'); …; Start-Sleep …; $f.Close()", which shares read and denies delete. The script prints when the rollback ticket-mark was journaled relative to the moment the holder opened its handle. A trigger run is valid only if that falls inside the hold (on a slow machine, raise HOLD). Finally it runs platform_util.retrying_unlink against the same kind of holder (2 s; no holder in the control) for comparison.

"""Standalone repro (Windows): a plan held open for HOLD seconds by another process that
shares read but not delete (as a scanner/indexer does) while a rolled-back attempt's
frontmatter-only plan is discarded. In place, rollback_on_failure = true, two attempts.
Run from a bmad-loop checkout: uv run python repro_unlink.py <HOLD seconds, 0 = control>"""
import json, os, shutil, subprocess, sys, time
from pathlib import Path

hold_s = float(sys.argv[1])
base = Path(os.environ["TEMP"]).resolve() / "unlink-repro"
os.environ["BMAD_LOOP_STATE_DIR"] = str(base / "state")
sys.path.insert(0, "tests")
import conftest as C
from bmad_loop import platform_util
from bmad_loop.adapters.base import SessionResult
from bmad_loop.adapters.mock import MockAdapter
from bmad_loop.bmadconfig import load_paths
from bmad_loop.journal import Journal, load_state
from bmad_loop.model import RunState
from bmad_loop.policy import GatesPolicy, NotifyPolicy, Policy, ReviewPolicy, ScmPolicy
from bmad_loop.tickets_engine import TicketsEngine

root = base / f"hold-{hold_s:g}"
if root.exists():
    C.remove_tree(root)
root.mkdir(parents=True)
(root / "src.txt").write_text("original\n", encoding="utf-8")
(root / ".gitignore").write_text(C.V7_GITIGNORE, encoding="utf-8")
lay = C.install_bmad_v7(root)
C.write_ticket_tree(lay, (C.EpicSpec(1, "epic-cart", "Cart", (C.EntrySpec(1, "Cart model"),)),))
C._commit_template(root)
plan = Path(C.run_tickets(lay, "find", "1.1")["plan"])
holders = []
window: list[float] = []


def hold(path, seconds):
    lit = str(path).replace("'", "''")
    p = subprocess.Popen([shutil.which("pwsh"), "-NoProfile", "-Command",
                          f"$f=[IO.File]::Open('{lit}','Open','Read','Read'); 'held'; "
                          f"Start-Sleep -Milliseconds {int(seconds * 1000)}; $f.Close()"],
                         stdout=subprocess.PIPE, text=True)
    assert p.stdout.readline().strip() == "held"
    window.append(time.time())  # handle open from here for `seconds`
    return p


def crash(spec):  # attempt 1 writes a frontmatter-only plan, then crashes
    (Path(spec.cwd) / "src.txt").write_bytes(b"half done\n")
    plan.write_bytes(b"---\nticket: 1\nstatus: in-progress\n---\n")
    if hold_s:
        holders.append(hold(plan, hold_s))
    return SessionResult(status="crashed")


def second(spec):
    print(f"attempt 2 dispatched ({spec.task_id}); plan exists: {plan.exists()}")
    return SessionResult(status="crashed")


run_dir = root / ".bmad-loop" / "runs" / "r1"
state = RunState(run_id="r1", project=str(root), started_at="now",
                 initiative=lay.initiative, initiative_folder=str(lay.initiative_folder))
state.max_stories = 1
policy = Policy(gates=GatesPolicy(mode="none"), notify=NotifyPolicy(desktop=False, file=True),
                review=ReviewPolicy(enabled=False), scm=ScmPolicy(isolation="none", rollback_on_failure=True))
adapter = MockAdapter([crash, second])
TicketsEngine(paths=load_paths(root, want_tickets=True), policy=policy, adapter=adapter,
              run_dir=run_dir, journal=Journal(run_dir), state=state).run()
for h in holders:
    h.wait()
st = load_state(run_dir)
print(f"sessions={len(adapter.sessions)} paused_stage={st.paused_stage} reason={(st.paused_reason or '')[:260]}")
for line in (run_dir / "journal.jsonl").read_text(encoding="utf-8").splitlines():
    e = json.loads(line)
    if e["kind"] == "ticket-mark":
        print("ticket-mark", {k: e[k] for k in ("reason", "before", "after", "outcome")})
        if window:  # the mark is journaled after the delete; it must land inside the holder's window
            print(f"rollback ticket-mark recorded at +{e['ts'] - window[0]:.2f}s after the holder opened (holder: {hold_s:g}s)")
# the codebase's own retrying delete, same holder, for comparison
plan.write_bytes(b"x")
h = hold(plan, 2.0) if hold_s else None
platform_util.retrying_unlink(plan)
print(f"platform_util.retrying_unlink (holder={'2 s' if h else 'none'}): deleted =", not plan.exists())
if h:
    h.wait()

Observed with the script exactly as above (Windows, PowerShell 7.6.6, rc 0 for both; the generated plan pathname is shown as <plan>, and the reason's tail is cut where the script's own 260-character truncation fell on the full path):

### uv run python repro_unlink.py 0
attempt 2 dispatched (1.1-dev-2); plan exists: False
sessions=2 paused_stage=None reason=
ticket-mark {'reason': 'rollback', 'before': 'in-progress', 'after': '', 'outcome': 'discarded'}
platform_util.retrying_unlink (holder=none): deleted = True
### uv run python repro_unlink.py 3
sessions=1 paused_stage=ticket-tree reason=re-arming 1.1's plan after its rollback failed (tickets.py plan-io: 1.1: cannot delete <plan>: [WinError 32] The process canno
ticket-mark {'reason': 'rollback', 'before': 'in-progress', 'after': 'in-progress', 'outcome': 'failed'}
rollback ticket-mark recorded at +2.05s after the holder opened (holder: 3s)
platform_util.retrying_unlink (holder=2 s): deleted = True

All runs on the same machine, each with the no-holder control; every trigger run's ticket-mark lands inside the 3 s hold. The first three sets printed these results under earlier output labels:

runs control (0) trigger (3) rollback ticket-mark offset into the hold
first set, 2 runs 2/2 attempt 2 dispatched, outcome: discarded 2/2 sessions=1 paused_stage=ticket-tree, outcome: failed +0.92 s, +1.31 s
second set, 3 runs 3/3 same 3/3 same +1.48 s, +1.22 s, +0.90 s
third set, 3 runs 3/3 same 3/3 same +1.65 s, +1.76 s, +0.99 s
script as above, 1 run 1/1 same 1/1 same +2.05 s

platform_util.retrying_unlink deleted the plan under a real 2 s holder in every trigger run.

At symbol level (a separate script, the same holder for 2 s): discard_unbuilt_plan fails in 0.20 s with TicketsPlanIOError: 1.1: cannot delete … [WinError 32]. restore_preimage(plan, None, journal) fails in about 0.01 s with TicketsPlanIOError: cannot restore … [WinError 32] (journal ticket-plan-restored outcome=failed). platform_util.retrying_unlink succeeds after 2 to 3 s.

Ablation: with tickettree.py:562 changed to platform_util.retrying_unlink(plan) in a scratch copy of the package (first on PYTHONPATH), the 3 s run discards the plan and dispatches attempt 2, like the control. In that run the successful ticket-mark is journaled at about +3.3 s, after the holder released, because the delete was retried past the hold.

Expected vs actual

actual expected
plan held for 3 s (read-share, no delete-share) during the rollback re-arm delete fails at once, run pauses at ticket-tree, operator told to "fix the ticket tree" the delete retried as retrying_unlink does (a bounded backoff of about 5 s, source-derived), plan discarded, attempt 2 dispatched (the no-holder control)

Linux

No oracle applies: the failure is a Windows sharing violation (WinError 32). On POSIX, unlink of a file another process holds open succeeds, so this handle-sharing trigger cannot fail there.

Source

At a5a8f097, src/bmad_loop/tickettree.py:

# :561-564 (discard_unbuilt_plan)
                    try:
                        plan.unlink()
                    except OSError as e:
                        raise TicketsPlanIOError(f"{ref}: cannot delete {plan}: {e}") from e
# :602-604 (restore_preimage)
                    if data is None:
                        plan.unlink(missing_ok=True)
                        restored = not plan.exists()

The retrying delete they skip, src/bmad_loop/platform_util.py:2219-2226:

def retrying_unlink(path: Path) -> None:
    """``path.unlink()`` with the same win32 retry as :func:`atomic_replace`.

    Windows denies a *delete* against an open handle exactly as it denies a
    rename-over, ... an AV/indexer scanning the just-written source file fails the unlink."""
    _retry_on_sharing_violation(path.unlink)

The re-arm caller that turns the error into the pause (observed in the run above): tickets_engine.py:2055-2067 (_after_code_rollback → _pause_rearm). restore_preimage(…, None) is reached when a terminal mark is undone for a plan that did not exist before (tickets_engine.py:1653). That caller is source-derived here; I did not drive it through the engine, only the symbol.

Suggested fix

Not validated beyond the ablation above (which changed only the discard_unbuilt_plan site): use platform_util.retrying_unlink(plan) at both sites, keeping missing_ok behaviour at the restore_preimage site. A failure after the retries are exhausted should still pause as today.

主要语言
Python
星标
196
派生
78
平均合并
9 小时 24 分钟
30 天内合并 PR
44

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

bmad-code-org/bmad-loop 的其他 Issue

查看 bmad-code-org/bmad-loop 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。