diff --git a/doc/architecture/SPEC/app/run_service.md b/doc/architecture/SPEC/app/run_service.md index 23a31c8f..e50df214 100644 --- a/doc/architecture/SPEC/app/run_service.md +++ b/doc/architecture/SPEC/app/run_service.md @@ -1,6 +1,6 @@ # app/run_service.py —— 规范 - + `RunService` is the durable application boundary shared by the embedded Strict SDK and MCP transport. It owns policy-checked reserve/start, a queue @@ -53,7 +53,7 @@ in for the custom bytes that the child consumes. ## 2026-09-30 Concurrent workers `Settings.strict_max_workers` (`STRICT_MAX_WORKERS`, 1–32, default 1; embedded hosts set it through `StrictRuntimeConfig.max_workers`) starts that many worker -threads, and `capabilities()` reports the same number as `max_strict_workers`. +threads, and `capabilities()` reports the same number as `max_strict_workers`. The handshake reports platform support for the file locks used by Strict reservations and worktrees. Each worker launches one child at a time, so at most N children run at once. `RunQueue` never hands out two runs with the same **conflict key** at once: diff --git a/doc/architecture/SPEC/engine/lifecycle.md b/doc/architecture/SPEC/engine/lifecycle.md index 2e19a534..3b0e817c 100644 --- a/doc/architecture/SPEC/engine/lifecycle.md +++ b/doc/architecture/SPEC/engine/lifecycle.md @@ -1,6 +1,6 @@ # engine/lifecycle.py —— 规范 - + `LOC ~396 · 引擎底座(run 生命周期原语 + 优雅停机) · refactor-status: ok` @@ -12,7 +12,7 @@ GPU 调度器 `--timeout` 发出的 SIGINT 被整个忽略,随后 reservation 杀掉其下的测试进程)。 ## 功能 -`RunLock` 对 `/.lock` 取排他 advisory `flock`(第二个并发 +`RunLock` 对 `/.lock` 取操作系统排他 advisory 锁(第二个并发 `--resume` fail fast,而不是交错写进度、共享 checkout); `register_finalizer`/`finalize` 维护逐 run 的异步 finalizer 表; `run_guarded` 包住 executor 协程,在完成/失败/抛异常的**每条**退出路径上、 @@ -59,10 +59,10 @@ run_harness_cli`);`register_shutdown_hook(fn)/unregister_shutdown_hook(fn)` `idempotency.py`(`key_lock`/`reap_stale`)消费。 ## 不变量 -- `flock` 争用按 open file description 计:同进程内对同一路径的第二次 - `acquire` 也失败 —— 抛 `RunLockHeld`,绝不静默共存。 -- 锁文件释放后**留在原地**:它的存在不携带语义,只有 flock 本身算数。 -- 非 POSIX(无 fcntl,与 `run_status.py` 同款守卫):无 advisory 锁, +- POSIX 使用 `flock`,Windows 使用 `LockFileEx`。同进程内对同一路径的第二次 + 排他 `acquire` 也失败,抛 `RunLockHeld`。 +- 锁文件释放后**留在原地**,后续调用者在同一个文件上竞争操作系统锁。 +- 缺少操作系统文件锁的平台仍为单进程 CLI 保留降级路径: `acquire` 直接成功 —— 注释声明的刻意降级(保住 run 可用;无 trace 事件)。 - **降级与 fail-closed 是两条刻意分开的路径**:`RunLock` 的静默降级只对 "单进程 CLI run 可用性"成立;对**正确性就是锁本身**的路径(worktree @@ -106,7 +106,7 @@ stdlib(asyncio/os/signal/subprocess/threading/pathlib/fcntl-守卫);停机 **进程级** run 保证才落在这里。 ## 测试 -`test_run_lifecycle.py`(同进程/跨进程锁争用、release 后可重取、无 fcntl +`test_run_lifecycle.py`(同进程/跨进程锁争用、release 后可重取、无系统锁 降级、finalizer 恰好一次 / 异常与取消隔离 / 失败路径也执行); `test_run_shutdown.py`(覆盖继承的 SIG_IGN 并恢复、请求幂等与 128+signum、 工作线程杀注册子进程整棵树后在硬截止 `exit_fn`、无绑定 task 时跑钩子即返回、 diff --git a/doc/architecture/SPEC/engine/worktrees.md b/doc/architecture/SPEC/engine/worktrees.md index 79d1c767..78e5a5e0 100644 --- a/doc/architecture/SPEC/engine/worktrees.md +++ b/doc/architecture/SPEC/engine/worktrees.md @@ -1,6 +1,6 @@ # engine/worktrees.py —— 规范 - + `LOC ~294 · PR-time worktree:身份、物化、持有 · refactor-status: ok` @@ -9,7 +9,7 @@ PR 快照 worktree 的三条性质,每条都对应一个修掉的真实事故 **身份**(旧键 `-pr` 在不同 head 的 run 之间、同名目录的不同 checkout 之间碰撞,force-remove 曾删掉一个活评审的树)、 **验证**(复用前确认这棵树属于请求方仓库且 HEAD == sha)、 -**存活**(run 期间的共享 flock 持有,让 reaper 的 `LOCK_EX|LOCK_NB` +**存活**(run 期间的共享文件锁持有,让 reaper 的 `LOCK_EX|LOCK_NB` 扫描跳过它 —— 这是对 MCP 预约 run 和 CLI run 都成立的唯一存活信号, `run_status.json` 只有前者才有)。 @@ -59,8 +59,8 @@ worktree,允许本地 rebase,又不会改配置的 checkout 或复用评审 `engine/steps/pr/fetch.py` 和 `engine/steps/pr/rebase.py` 的决定。 ## 依赖(允许) -stdlib(hashlib/os/re/time/pathlib)+ `.lifecycle` -(fcntl 守卫、register_finalizer、require_file_locking)。 +stdlib(hashlib/os/re/pathlib)、`file_locking` 的跨平台排他锁和共享锁, +以及 `.lifecycle.register_finalizer`。 ## 测试 `test_pr_steps.py`(materialize 创建与复用、同 basename 仓库分键、 diff --git a/doc/architecture/SPEC/file_locking.md b/doc/architecture/SPEC/file_locking.md new file mode 100644 index 00000000..cda9d644 --- /dev/null +++ b/doc/architecture/SPEC/file_locking.md @@ -0,0 +1,12 @@ +# file_locking.py —— 规范 + + + +Strict 的预约、状态和 worktree 使用同一组操作系统文件锁原语。POSIX 使用 `flock`,Windows 使用 `LockFileEx` 锁定从偏移 0 开始的一个字节,支持空锁文件。 + +- `try_lock` 支持共享和排他模式,只在锁被占用时返回 `False`,其余错误由调用者处理。 +- `lock` 等待排他锁,可指定超时。`unlock` 在同一个描述符上释放锁。描述符关闭或进程退出后,由操作系统释放剩余锁。 +- 持有者和等待者必须竞争同一个锁文件。调用者不得在释放锁时删除该文件。 +- 无系统锁的平台保留旧的单进程 CLI 降级。Strict 在预约和创建 worktree 前调用 `require_file_locking` 拒绝不受保护的执行。 + +`test_run_lifecycle.py` 验证跨进程排他、进程退出后的释放,以及共享持有者和排他持有者之间的互斥。 diff --git a/doc/architecture/SPEC/idempotency.md b/doc/architecture/SPEC/idempotency.md index 641b4cef..15de5035 100644 --- a/doc/architecture/SPEC/idempotency.md +++ b/doc/architecture/SPEC/idempotency.md @@ -1,6 +1,6 @@ # idempotency.py —— 规范 - + `LOC ~293 · 持久 idempotency 索引:每键一个 run、一次执行 · refactor-status: ok` diff --git a/doc/architecture/SPEC/providers/base.md b/doc/architecture/SPEC/providers/base.md index 8a3604fd..c14b6ac3 100644 --- a/doc/architecture/SPEC/providers/base.md +++ b/doc/architecture/SPEC/providers/base.md @@ -1,6 +1,6 @@ # providers/base.py —— 规范 - + `LOC ~234 · provider 层契约 + 子进程环境白名单 + 受管 CLI 子进程 · refactor-status: ok` diff --git a/doc/architecture/SPEC/providers/codex.md b/doc/architecture/SPEC/providers/codex.md index a1dace53..d709e37f 100644 --- a/doc/architecture/SPEC/providers/codex.md +++ b/doc/architecture/SPEC/providers/codex.md @@ -1,6 +1,6 @@ # providers/codex.py —— 规范 - + `LOC ~197 · harness transport(ChatGPT 订阅) · refactor-status: ok` diff --git a/doc/architecture/SPEC/run_status.md b/doc/architecture/SPEC/run_status.md index b69e6e4c..aa8c12fd 100644 --- a/doc/architecture/SPEC/run_status.md +++ b/doc/architecture/SPEC/run_status.md @@ -1,6 +1,6 @@ # run_status.py —— 规范 - + `LOC ~345 · 持久化的单写者 run 生命周期记录 · refactor-status: ok` @@ -33,7 +33,7 @@ owner_server_pid)`(`interrupted → queued` 重新武装)、 `claim_for_execution` 赢下 CAS 并写入自己的 pid(非预约 run 走 `mark_child_started`),然后 `planning → running → 终态`。父进程 **只在 `.wait()` 之后**对账 —— 也就是在子进程已确认死亡之后。 -- **跨进程对账只发生在写者被确认死亡之后**,持 `flock` 进行,并保留 owner 字段。 +- **跨进程对账只发生在写者被确认死亡之后**,持操作系统排他锁进行,并保留 owner 字段。 - **按属主对账**(`owner_server_id` / `owner_server_pid` / `child_pid`):只有**属主** server 被确认死亡,才可以把一个非终态 run 标记为 `interrupted`。在多 server 模型下 (Claude Code 和 Codex 各自拉起一个 server),正是这一条阻止了某个 server 去抢另一个 @@ -55,7 +55,7 @@ owner_server_pid)`(`interrupted → queued` 重新武装)、 不拉起进程(那是 `mcp_server`);不含策略;不渲染报告。 ## 依赖(允许) -仅 stdlib(`json`、`os`、`fcntl`/`flock`、`pathlib`)。 +依赖 stdlib 和 `file_locking`。Windows 用进程句柄检查存活状态,POSIX 使用 `kill(pid, 0)`。 ## 测试 `test_mcp.py`(单写者对账、属主判定);`test_idempotency.py` diff --git a/doc/architecture/SPEC/tool_bridge.md b/doc/architecture/SPEC/tool_bridge.md index a4423df1..dff2f3ea 100644 --- a/doc/architecture/SPEC/tool_bridge.md +++ b/doc/architecture/SPEC/tool_bridge.md @@ -1,6 +1,6 @@ # tool_bridge.py —— 规范 - + `LOC ~783 · 面向 harness 会话的 scoped 工具 MCP server · refactor-status: ok` @@ -98,7 +98,7 @@ client 把 server 判为失败,余下数小时不再路由到它。桥进程 (≥ `SLOW_TOOL_CALL_S` 的调用:tool/elapsed_s,是 client 截止切断的唯一旁证)、 `exit`(`reason` ∈ stdin_closed / signal / system_exit / exception / import_error / build_error,`rc`、`calls`、`parent_alive`)。写失败绝不抛。 -- 进程对 SIGINT/SIGHUP/SIGPIPE 置 `SIG_IGN`(`install_bridge_signal_dispositions`, +- 进程对当前平台支持的 SIGINT/SIGHUP/SIGPIPE 置 `SIG_IGN`(`install_bridge_signal_dispositions`, 在 `run_bridge` **最先**执行——SDK 导入在高负载宿主上要数秒,期间到达的信号 不得先杀掉还没开始的 server):stdio server 的寿命就是它的 stdin,终端 Ctrl-C 只应到引擎、由引擎按序停会话;harness 关闭 stdin 是唯一正常退出。 diff --git a/src/infermatrix_copilot/app/run_service.py b/src/infermatrix_copilot/app/run_service.py index 44185c6e..4a18e19b 100644 --- a/src/infermatrix_copilot/app/run_service.py +++ b/src/infermatrix_copilot/app/run_service.py @@ -148,11 +148,11 @@ def _reap(self) -> None: def capabilities(self) -> dict: """The version/capability handshake — see `contract.capabilities`.""" - from ..engine.lifecycle import fcntl as _fcntl + from ..file_locking import supports_file_locking return contract.capabilities( max_strict_workers=self.max_strict_workers, - supports_file_locking=_fcntl is not None) + supports_file_locking=supports_file_locking()) # -- workers: up to N runs at a time, each an isolated subprocess -------- def _conflict_key(self, run_id: str) -> tuple[str, Any]: diff --git a/src/infermatrix_copilot/engine/lifecycle.py b/src/infermatrix_copilot/engine/lifecycle.py index 7afdd85e..442e650c 100644 --- a/src/infermatrix_copilot/engine/lifecycle.py +++ b/src/infermatrix_copilot/engine/lifecycle.py @@ -36,36 +36,15 @@ from pathlib import Path from typing import Any, Awaitable, Callable -try: # same guard as run_status.py: fcntl is POSIX-only - import fcntl -except ImportError: # pragma: no cover - Windows - fcntl = None # type: ignore +from .. import file_locking +from ..file_locking import FileLockingUnavailable as FileLockingUnavailable +from ..file_locking import require_file_locking as require_file_locking Finalizer = Callable[[Any], Awaitable[None]] _finalizers: dict[str, list[Finalizer]] = {} -class FileLockingUnavailable(RuntimeError): - """This platform has no `fcntl`, so cross-process locking cannot be honored.""" - - -def require_file_locking() -> None: - """Raise unless POSIX advisory locking is available. - - The `fcntl = None` fallback above makes every lock in this file a silent - no-op. That is tolerable for a single-process CLI run, where no cross-process - lock was protecting anything anyway, but not for the paths whose *correctness* - is the lock — worktree materialization, and (later) the idempotency index and - its reaper. Those must fail closed rather than run unprotected and report a - guarantee they are not providing (invariant 7).""" - if fcntl is None: - raise FileLockingUnavailable( - "POSIX file locking (fcntl) is unavailable on this platform, so " - "concurrent-safe worktrees and run reservations cannot be " - "guaranteed; this surface refuses to run unprotected") - - class RunLockHeld(RuntimeError): """Another process already holds this run's lock.""" @@ -83,25 +62,28 @@ def __init__(self, run_dir: Path): self._fd: int | None = None def acquire(self) -> "RunLock": - if fcntl is None: # non-POSIX: no advisory locking; keep runs working + if not file_locking.supports_file_locking(): return self self.path.parent.mkdir(parents=True, exist_ok=True) fd = os.open(self.path, os.O_CREAT | os.O_RDWR, 0o644) try: - fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) - except OSError: + if not file_locking.try_lock(fd): + raise RunLockHeld( + f"run lock {self.path} is held by another process — " + "is this run already executing (a concurrent --resume)?") + except (OSError, RunLockHeld): os.close(fd) - raise RunLockHeld( - f"run lock {self.path} is held by another process — " - "is this run already executing (a concurrent --resume)?") + raise self._fd = fd return self def release(self) -> None: if self._fd is not None: - fcntl.flock(self._fd, fcntl.LOCK_UN) - os.close(self._fd) - self._fd = None + fd, self._fd = self._fd, None + try: + file_locking.unlock(fd) + finally: + os.close(fd) def __enter__(self) -> "RunLock": return self.acquire() diff --git a/src/infermatrix_copilot/engine/worktrees.py b/src/infermatrix_copilot/engine/worktrees.py index d4997c43..b07cddd7 100644 --- a/src/infermatrix_copilot/engine/worktrees.py +++ b/src/infermatrix_copilot/engine/worktrees.py @@ -36,11 +36,11 @@ import hashlib import os import re -import time from pathlib import Path from typing import Callable -from .lifecycle import fcntl, register_finalizer, require_file_locking +from .. import file_locking +from .lifecycle import register_finalizer def worktree_root() -> Path: """The tool's worktree scratch root (`~/.infermatrix-copilot/runs` is its @@ -124,25 +124,6 @@ def _open_lock(dest: Path | str) -> int: return os.open(str(path), os.O_RDWR | os.O_CREAT, 0o644) -def _flock_blocking(fd: int, flags: int, timeout: float) -> bool: - """Take `flags` on `fd`, retrying until `timeout` seconds elapse. - - `LOCK_EX` here must *block*, not fail: two runs at the same sha racing - inside `git worktree add` is the ordinary case, and its failure path - degrades silently to the live checkout — the exact wrong-tree outcome the - head gate exists to prevent. Polling rather than a blocking flock keeps the - timeout enforceable.""" - deadline = time.monotonic() + timeout - while True: - try: - fcntl.flock(fd, flags | fcntl.LOCK_NB) - return True - except OSError: - if time.monotonic() >= deadline: - return False - time.sleep(0.05) - - def touch(dest: Path) -> None: """Mark a reused tree as in use NOW, while the exclusive lock is held. @@ -201,10 +182,10 @@ def materialize_mutable(repo: Path, sha: str, dest: Path, git: GitRunner, *, checkout step itself is being retried. A completed checkout is replayed from the checkpoint on resume and keeps its in-progress work. """ - require_file_locking() + file_locking.require_file_locking() fd = _open_lock(dest) try: - if not _flock_blocking(fd, fcntl.LOCK_EX, timeout): + if not file_locking.lock(fd, timeout=timeout): return False, f"worktree lock busy for {timeout:.0f}s" try: # A symlink to the source checkout passes the common-git-dir check, @@ -224,7 +205,7 @@ def materialize_mutable(repo: Path, sha: str, dest: Path, git: GitRunner, *, return False, f"worktree add failed: {out[:300]}" return True, "created private worktree" finally: - fcntl.flock(fd, fcntl.LOCK_UN) + file_locking.unlock(fd) except OSError as exc: return False, f"worktree error: {exc}" finally: @@ -238,10 +219,10 @@ def materialize(repo: Path, sha: str, dest: Path, git: GitRunner, *, never raises for a git-level failure — callers decide whether to block or degrade — but a platform without file locking IS raised, because the serialization is the guarantee.""" - require_file_locking() + file_locking.require_file_locking() fd = _open_lock(dest) try: - if not _flock_blocking(fd, fcntl.LOCK_EX, timeout): + if not file_locking.lock(fd, timeout=timeout): return False, f"worktree lock busy for {timeout:.0f}s" try: if dest.exists(): @@ -260,7 +241,7 @@ def materialize(repo: Path, sha: str, dest: Path, git: GitRunner, *, return False, f"worktree add failed: {out[:300]}" return True, f"created worktree @ {sha[:12]}" finally: - fcntl.flock(fd, fcntl.LOCK_UN) + file_locking.unlock(fd) except OSError as exc: return False, f"worktree error: {exc}" finally: @@ -275,12 +256,15 @@ def hold(dest: Path | str, run_dir: Path) -> bool: is released by a run finalizer on every exit path, and by the kernel anyway if the process dies, so a crashed run never pins a tree forever.""" key = canonical(dest) - if key in _HELD or fcntl is None: + if key in _HELD or not file_locking.supports_file_locking(): return key in _HELD fd = _open_lock(dest) try: - fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB) + acquired = file_locking.try_lock(fd, shared=True) except OSError: + os.close(fd) + raise + if not acquired: # A reaper's exclusive sweep is in flight. Not fatal: the tree is either # about to go and the run will rebuild it, or the sweep will skip it. os.close(fd) @@ -298,7 +282,7 @@ async def _release(_outcome) -> None: if fd is None: return try: - fcntl.flock(fd, fcntl.LOCK_UN) + file_locking.unlock(fd) finally: os.close(fd) diff --git a/src/infermatrix_copilot/file_locking.py b/src/infermatrix_copilot/file_locking.py new file mode 100644 index 00000000..77ba57fa --- /dev/null +++ b/src/infermatrix_copilot/file_locking.py @@ -0,0 +1,94 @@ +"""OS-released advisory locks for Strict run and worktree coordination.""" + +from __future__ import annotations + +import errno +import os +import time + +if os.name == "nt": + import ctypes + import msvcrt + from ctypes import wintypes + + class _Overlapped(ctypes.Structure): + _fields_ = [ + ("internal", ctypes.c_size_t), + ("internal_high", ctypes.c_size_t), + ("offset", wintypes.DWORD), + ("offset_high", wintypes.DWORD), + ("event", wintypes.HANDLE), + ] + + _kernel = ctypes.WinDLL("kernel32", use_last_error=True) + _lock_file = _kernel.LockFileEx + _lock_file.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD, + wintypes.DWORD, wintypes.DWORD, ctypes.POINTER(_Overlapped)] + _lock_file.restype = wintypes.BOOL + _unlock_file = _kernel.UnlockFileEx + _unlock_file.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD, + wintypes.DWORD, ctypes.POINTER(_Overlapped)] + _unlock_file.restype = wintypes.BOOL + + _FAIL_IMMEDIATELY = 1 + _EXCLUSIVE_LOCK = 2 + _LOCK_VIOLATION = 33 + _fcntl = None +else: + try: + import fcntl as _fcntl + except ImportError: + _fcntl = None + + +class FileLockingUnavailable(RuntimeError): + """The platform cannot provide the process-wide locking Strict needs.""" + + +def supports_file_locking() -> bool: + return os.name == "nt" or _fcntl is not None + + +def require_file_locking() -> None: + if not supports_file_locking(): + raise FileLockingUnavailable("OS file locking is unavailable on this platform") + + +def try_lock(fd: int, *, shared: bool = False) -> bool: + """Return False for contention. Propagate filesystem and descriptor errors.""" + require_file_locking() + if os.name == "nt": + flags = _FAIL_IMMEDIATELY | (0 if shared else _EXCLUSIVE_LOCK) + # Windows permits locks beyond EOF, so even an empty lock file works. + if _lock_file(msvcrt.get_osfhandle(fd), flags, 0, 1, 0, ctypes.byref(_Overlapped())): + return True + error = ctypes.get_last_error() + if error == _LOCK_VIOLATION: + return False + raise ctypes.WinError(error) + mode = _fcntl.LOCK_SH if shared else _fcntl.LOCK_EX + try: + _fcntl.flock(fd, mode | _fcntl.LOCK_NB) + except OSError as exc: + if exc.errno in (errno.EACCES, errno.EAGAIN, errno.EWOULDBLOCK): + return False + raise + return True + + +def lock(fd: int, *, timeout: float | None = None) -> bool: + """Take an exclusive lock, waiting indefinitely by default.""" + deadline = None if timeout is None else time.monotonic() + timeout + while not try_lock(fd): + if deadline is not None and time.monotonic() >= deadline: + return False + time.sleep(0.05) + return True + + +def unlock(fd: int) -> None: + if os.name == "nt": + if not _unlock_file(msvcrt.get_osfhandle(fd), 0, 1, 0, ctypes.byref(_Overlapped())): + raise ctypes.WinError(ctypes.get_last_error()) + else: + _fcntl.flock(fd, _fcntl.LOCK_UN) diff --git a/src/infermatrix_copilot/idempotency.py b/src/infermatrix_copilot/idempotency.py index 902bd2e3..872824b7 100644 --- a/src/infermatrix_copilot/idempotency.py +++ b/src/infermatrix_copilot/idempotency.py @@ -41,7 +41,7 @@ from typing import Any, Optional from . import run_status as rs -from .engine.lifecycle import fcntl, require_file_locking +from . import file_locking INDEX_DIR = ".idem" # Long enough that no plausible retry window outlives it, short enough to bound @@ -97,25 +97,17 @@ def key_lock(run_root: Path | str, key: str, *, timeout: float = 30.0): Blocking, unlike `RunLock`: a concurrent duplicate start is the ordinary case this exists to absorb, so the loser must WAIT and then observe the winner's entry. Failing fast would turn a dedupe into an error.""" - require_file_locking() + file_locking.require_file_locking() path = _entry_path(run_root, key).with_suffix(".lock") path.parent.mkdir(parents=True, exist_ok=True) fd = os.open(str(path), os.O_RDWR | os.O_CREAT, 0o644) - deadline = time.monotonic() + timeout try: - while True: - try: - fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) - break - except OSError: - if time.monotonic() >= deadline: - raise IdempotencyError( - f"idempotency lock busy for {timeout:.0f}s") - time.sleep(0.05) + if not file_locking.lock(fd, timeout=timeout): + raise IdempotencyError(f"idempotency lock busy for {timeout:.0f}s") try: yield finally: - fcntl.flock(fd, fcntl.LOCK_UN) + file_locking.unlock(fd) finally: os.close(fd) @@ -180,7 +172,7 @@ def reap_stale(run_root: Path | str, *, retention_days: int = DEFAULT_RETENTION_ audit trail (`RUN_REPORT.md`, `run_trace.jsonl`, `DIAGNOSTICS.md`), nothing has ever pruned them, and deleting completed runs is a separate and much higher-consequence change than bounding an index this feature introduces.""" - require_file_locking() + file_locking.require_file_locking() counts = {"entries": 0, "worktrees": 0, "refs": 0} cutoff = time.time() - retention_days * 86_400 root = Path(run_root) @@ -243,9 +235,10 @@ def _reap_worktrees(cutoff: float, worktree_root: Path | None) -> int: fd = os.open(str(wt.lock_path(dest)), os.O_RDWR | os.O_CREAT, 0o644) try: try: - fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + if not file_locking.try_lock(fd): + continue # a run holds it except OSError: - continue # a run holds it + continue try: # Re-read under the lock: a run may have reused (and touched) # this tree after the unlocked check above, then released its @@ -265,11 +258,11 @@ def _reap_worktrees(cutoff: float, worktree_root: Path | None) -> int: str(dest), timeout=120) if not dest.exists(): removed += 1 - wt.lock_path(dest).unlink(missing_ok=True) + # Keep the lock file so waiters always share the same lock object. except (OSError, subprocess.SubprocessError): continue finally: - fcntl.flock(fd, fcntl.LOCK_UN) + file_locking.unlock(fd) finally: os.close(fd) return removed diff --git a/src/infermatrix_copilot/providers/base.py b/src/infermatrix_copilot/providers/base.py index fb03bd5b..386f56d2 100644 --- a/src/infermatrix_copilot/providers/base.py +++ b/src/infermatrix_copilot/providers/base.py @@ -21,6 +21,7 @@ import os import shutil +import subprocess from dataclasses import dataclass, field from pathlib import Path from typing import Any, Literal @@ -33,6 +34,10 @@ # this class of machine) would silently reroute a vendor CLI's traffic. _ENV_KEEP = {"PATH", "HOME", "TERM", "COLORTERM", "LANG", "USER", "LOGNAME", "SHELL", "TMPDIR"} +if os.name == "nt": + # Use the normal Windows profile, certificate store and temp directories. + _ENV_KEEP.update({"SYSTEMROOT", "WINDIR", "USERPROFILE", "APPDATA", "LOCALAPPDATA", + "PROGRAMDATA", "SYSTEMDRIVE", "TEMP", "TMP", "COMSPEC", "PATHEXT"}) _ENV_KEEP_PREFIXES = ("LC_", "XDG_") @@ -191,8 +196,6 @@ def run_harness_cli(cmd: list[str], *, input: str | None, cwd: str | None, The child gets its own session: a terminal Ctrl-C then reaches the engine only, whose handler stops the session in order. Timeout semantics match `subprocess.run`: `TimeoutExpired` carries the partial stdout.""" - import subprocess - from ..engine.lifecycle import register_child, unregister_child from ..testing.process_tree import kill_tree diff --git a/src/infermatrix_copilot/providers/codex.py b/src/infermatrix_copilot/providers/codex.py index 393e56e8..fe461ac5 100644 --- a/src/infermatrix_copilot/providers/codex.py +++ b/src/infermatrix_copilot/providers/codex.py @@ -97,12 +97,14 @@ def _mcp_overrides(self, spec_path: Path) -> list[str]: config-only, so nothing is written into the session tree.""" package_root = Path(__file__).resolve().parents[2] args = json.dumps(["-m", "infermatrix_copilot.tool_bridge", - "--spec", str(spec_path)]) + "--spec", str(spec_path)], ensure_ascii=False) + python = json.dumps(sys.executable, ensure_ascii=False) + pythonpath = json.dumps(str(package_root), ensure_ascii=False) return [ - "-c", f'mcp_servers.{_BRIDGE_SERVER}.command="{sys.executable}"', + "-c", f"mcp_servers.{_BRIDGE_SERVER}.command={python}", "-c", f"mcp_servers.{_BRIDGE_SERVER}.args={args}", "-c", (f"mcp_servers.{_BRIDGE_SERVER}.env=" - f'{{PYTHONPATH = "{package_root}"}}'), + f"{{PYTHONPATH = {pythonpath}}}"), ] def _run(self, text: str, *, cwd: str, timeout_s: float, model: str = "", diff --git a/src/infermatrix_copilot/run_status.py b/src/infermatrix_copilot/run_status.py index 5098070f..2243c40e 100644 --- a/src/infermatrix_copilot/run_status.py +++ b/src/infermatrix_copilot/run_status.py @@ -15,7 +15,7 @@ then drives `planning -> running -> {done|blocked|failed}`. The parent never writes while the child is alive; it only reconciles *after* `.wait()` (child dead). Cross-process reconcilers write only after confirming the writer is - dead. Every write takes an advisory `flock` and preserves the ownership fields, + dead. Every write takes an advisory lock and preserves the ownership fields, so there are never two concurrent writers and no lost updates. - **Ownership-aware reconciliation.** Each run stores the `owner_server_id` / @@ -33,10 +33,7 @@ from pathlib import Path from typing import Any, Callable, Optional -try: # POSIX advisory locking; the copilot targets Linux (H200 box) - import fcntl -except ImportError: # pragma: no cover - non-POSIX fallback (no cross-proc lock) - fcntl = None # type: ignore +from . import file_locking # lifecycle states; TERMINAL states never transition again QUEUED = "queued" @@ -82,9 +79,10 @@ def _locked_update(run_dir: str | Path, run_dir = Path(run_dir) run_dir.mkdir(parents=True, exist_ok=True) lock = run_dir / _LOCK_NAME - with open(lock, "w", encoding="utf-8") as lf: - if fcntl is not None: - fcntl.flock(lf, fcntl.LOCK_EX) + with lock.open("a+b") as lf: + locking = file_locking.supports_file_locking() + if locking: + file_locking.lock(lf.fileno()) try: cur = read_status(run_dir) or {} updates = fn(cur) @@ -98,8 +96,8 @@ def _locked_update(run_dir: str | Path, os.replace(tmp, status_path(run_dir)) return new finally: - if fcntl is not None: - fcntl.flock(lf, fcntl.LOCK_UN) + if locking: + file_locking.unlock(lf.fileno()) # ── writers ─────────────────────────────────────────────────────────────────── @@ -217,22 +215,35 @@ def _upd(cur: dict) -> dict: # ── liveness ────────────────────────────────────────────────────────────────── def pid_alive(pid: Optional[int]) -> bool: - """True if `pid` names a live process. `os.kill(pid, 0)` probes without - signalling; PermissionError means it exists but is owned by another user.""" - if not pid: + """Probe a process without signalling or terminating it.""" + try: + pid = int(pid) if pid is not None else 0 + except (OverflowError, ValueError, TypeError): + return False + if pid <= 0: return False + if os.name == "nt": + # On Windows os.kill(pid, 0) terminates the target. Waiting on a + # process handle with a zero timeout only inspects its current state. + import _winapi + + try: + handle = _winapi.OpenProcess(_winapi.SYNCHRONIZE, False, pid) + except PermissionError: + return True + except (OSError, OverflowError, ValueError): + return False + try: + return _winapi.WaitForSingleObject(handle, 0) == _winapi.WAIT_TIMEOUT + finally: + _winapi.CloseHandle(handle) try: - os.kill(int(pid), 0) + os.kill(pid, 0) except ProcessLookupError: return False except PermissionError: return True - except (OverflowError, ValueError): - return False - except OSError: - # Windows raises a plain OSError (for example WinError 87) when the - # probed PID no longer identifies a process. Treat that as dead so an - # orphaned MCP run can be reconciled instead of crashing server startup. + except (OSError, OverflowError, ValueError): return False return True diff --git a/src/infermatrix_copilot/tool_bridge.py b/src/infermatrix_copilot/tool_bridge.py index ba0d50db..ff880678 100644 --- a/src/infermatrix_copilot/tool_bridge.py +++ b/src/infermatrix_copilot/tool_bridge.py @@ -51,8 +51,9 @@ import time from pathlib import Path -from .run_trace import RunTrace from . import trace_store +from .run_status import pid_alive +from .run_trace import RunTrace from .scopes import PathScope, ToolScope from .tools import _PATH_ARGS, TOOLS, dispatch @@ -391,15 +392,7 @@ def read_lifecycle_events(spec_path: Path) -> list[dict]: def _parent_alive(ppid: int) -> bool: """True while the launching harness process exists (reparenting to init or a reaper means it is gone).""" - if ppid <= 1 or os.getppid() != ppid: - return False - try: - os.kill(ppid, 0) - except ProcessLookupError: - return False - except PermissionError: - return True - return True + return ppid > 1 and os.getppid() == ppid and pid_alive(ppid) def _offload(fn): @@ -722,7 +715,10 @@ def install_bridge_signal_dispositions() -> None: engine's handler stops the harness in order), on a hangup of a terminal it never used, or on a write to a closed pipe (surfaces as an exception the transport handles). The harness closing stdin is the one exit.""" - for signum in (signal.SIGINT, signal.SIGHUP, signal.SIGPIPE): + for name in ("SIGINT", "SIGHUP", "SIGPIPE"): + signum = getattr(signal, name, None) + if signum is None: + continue try: signal.signal(signum, signal.SIG_IGN) except (OSError, ValueError, AttributeError): diff --git a/test/test_contract.py b/test/test_contract.py index abdb9700..9074c4c2 100644 --- a/test/test_contract.py +++ b/test/test_contract.py @@ -140,6 +140,8 @@ def test_quality_result_has_its_own_typed_contract(tmp_path): def test_capabilities_reports_the_real_worker_count(): """The MCP server drains its queue with one worker, so Strict requests serialize; advertising anything else would invite a bot to fan out.""" + from infermatrix_copilot.knowledge_service.common import _apply_supported + caps = contract.capabilities(max_strict_workers=1) assert caps["max_strict_workers"] == 1 assert caps["strict_api_version"] == contract.STRICT_API_VERSION @@ -148,7 +150,8 @@ def test_capabilities_reports_the_real_worker_count(): assert caps["supports_quality_review"] is True assert caps["supports_expected_head"] is True assert caps["supports_structured_result"] is True - assert caps["supports_knowledge_curation"] is True + assert caps["supports_idempotent_strict_start"] is True + assert caps["supports_knowledge_curation"] is _apply_supported() assert contract.KNOWLEDGE_API_VERSION == "1.1.0" diff --git a/test/test_idempotency.py b/test/test_idempotency.py index 430558c2..bb48f726 100644 --- a/test/test_idempotency.py +++ b/test/test_idempotency.py @@ -411,13 +411,13 @@ def test_reaper_leaves_a_held_worktree_and_removes_an_unheld_one(settings, os.utime(dest, (0, 0)) # older than any retention window fd = os.open(str(wt.lock_path(held)), os.O_RDWR | os.O_CREAT, 0o644) - import fcntl as _fcntl + from infermatrix_copilot import file_locking - _fcntl.flock(fd, _fcntl.LOCK_SH | _fcntl.LOCK_NB) + assert file_locking.try_lock(fd, shared=True) try: counts = idem.reap_stale(settings.run_root, worktree_root=root) finally: - _fcntl.flock(fd, _fcntl.LOCK_UN) + file_locking.unlock(fd) os.close(fd) assert held.exists() # a run is using it diff --git a/test/test_provider_codex.py b/test/test_provider_codex.py index 95d59f1a..bf55c0fa 100644 --- a/test/test_provider_codex.py +++ b/test/test_provider_codex.py @@ -4,17 +4,45 @@ readiness check exercises).""" import json +import os import stat +import tomllib from pathlib import Path import pytest from infermatrix_copilot.config import Settings -from infermatrix_copilot.providers.base import AgentSessionRequest +from infermatrix_copilot.providers.base import AgentSessionRequest, sanitized_env from infermatrix_copilot.providers.codex import CodexTransport from infermatrix_copilot.scopes import read_only_scope from infermatrix_copilot.tool_bridge import write_bridge_spec + +def test_codex_bridge_config_round_trips_windows_paths(monkeypatch): + import infermatrix_copilot.providers.codex as codex + + executable = r"C:\Python Env\Scripts\python.exe" + spec = r"C:\review\路径\bridge.json" + monkeypatch.setattr(codex.sys, "executable", executable) + transport = CodexTransport(Settings(_env_file=None)) + overrides = transport._mcp_overrides(Path(spec)) + config = tomllib.loads("\n".join(overrides[1::2]))["mcp_servers"]["infermatrix-tools"] + assert config["command"] == executable + assert config["args"][-1] == spec + assert config["env"]["PYTHONPATH"] == str(Path(codex.__file__).resolve().parents[2]) + + +@pytest.mark.skipif(os.name != "nt", reason="Windows harness environment") +def test_codex_keeps_windows_runtime_environment_without_forwarding_keys(monkeypatch): + monkeypatch.setenv("SYSTEMROOT", r"C:\Windows") + monkeypatch.setenv("USERPROFILE", r"C:\Users\reviewer") + monkeypatch.setenv("OPENAI_API_KEY", "not-forwarded") + monkeypatch.setenv("OPENAI_BASE_URL", "https://example.invalid") + env = sanitized_env() + assert env["SYSTEMROOT"] == r"C:\Windows" + assert env["USERPROFILE"] == r"C:\Users\reviewer" + assert not ({"OPENAI_API_KEY", "OPENAI_BASE_URL"} & env.keys()) + _FAKE_CLI = """#!/usr/bin/env python3 import json, os, sys, time here = os.path.dirname(os.path.abspath(__file__)) diff --git a/test/test_run_lifecycle.py b/test/test_run_lifecycle.py index 38b38a18..0b324876 100644 --- a/test/test_run_lifecycle.py +++ b/test/test_run_lifecycle.py @@ -47,7 +47,6 @@ def boom(fd): # -- same-run lock ------------------------------------------------------------- def test_run_lock_excludes_second_holder(tmp_path): - pytest.importorskip("fcntl") # exclusion exists only where flock does run_dir = tmp_path / "run" with RunLock(run_dir): with pytest.raises(RunLockHeld): @@ -61,37 +60,55 @@ def test_run_lock_reacquirable_after_release(tmp_path): pass # no raise +def test_shared_worktree_locks_can_coexist_and_exclude_a_writer(tmp_path): + path = tmp_path / "worktree.lock" + locking = lifecycle.file_locking + with path.open("a+b") as first, path.open("a+b") as second, path.open("a+b") as writer: + assert locking.try_lock(first.fileno(), shared=True) + assert locking.try_lock(second.fileno(), shared=True) + assert not locking.try_lock(writer.fileno()) + locking.unlock(first.fileno()) + assert not locking.try_lock(writer.fileno()) + locking.unlock(second.fileno()) + assert locking.try_lock(writer.fileno()) + locking.unlock(writer.fileno()) + + def test_run_lock_excludes_across_processes(tmp_path): """The lock's whole point is cross-process exclusion (two --resume - invocations), so contend against a real second process holding the flock.""" - pytest.importorskip("fcntl") # POSIX-only; the lock degrades elsewhere + invocations), so contend against a real second process holding the lock.""" import subprocess import sys - import time + + from infermatrix_copilot.run_status import pid_alive run_dir = tmp_path / "run" run_dir.mkdir() holder = subprocess.Popen( [sys.executable, "-c", - "import fcntl,sys,time; f=open(sys.argv[1],'w'); " - "fcntl.flock(f, fcntl.LOCK_EX); print('held',flush=True); time.sleep(30)", - str(run_dir / ".lock")], + "import sys,time; from infermatrix_copilot.engine.lifecycle import RunLock; " + "lock=RunLock(sys.argv[1]).acquire(); print('held',flush=True); time.sleep(30)", + str(run_dir)], stdout=subprocess.PIPE, text=True) try: assert holder.stdout.readline().strip() == "held" + assert pid_alive(holder.pid) with pytest.raises(RunLockHeld): RunLock(run_dir).acquire() finally: holder.kill() - holder.wait() - time.sleep(0.05) # kernel releases the flock with the process + holder.wait(timeout=10) + assert not pid_alive(holder.pid) + # Windows can finish releasing a terminated process's locks after wait(). + with (run_dir / ".lock").open("a+b") as lock_file: + assert lifecycle.file_locking.lock(lock_file.fileno(), timeout=3) + lifecycle.file_locking.unlock(lock_file.fileno()) RunLock(run_dir).acquire().release() -def test_run_lock_degrades_without_fcntl(tmp_path, monkeypatch): - """Non-POSIX platforms have no fcntl (run_status.py precedent): the lock - becomes a no-op rather than an import error or a crash at acquire.""" - monkeypatch.setattr(lifecycle, "fcntl", None) +def test_run_lock_degrades_on_unsupported_platform(tmp_path, monkeypatch): + """The single-process CLI still runs on platforms without advisory locks.""" + monkeypatch.setattr(lifecycle.file_locking, "supports_file_locking", lambda: False) lock = RunLock(tmp_path / "run").acquire() # no raise, no lock file needed lock.release() @@ -225,7 +242,6 @@ def test_duplicate_execute_reserved_leaves_status_untouched(settings, tmp_path): """The reserved-run race: a duplicate child losing the lock must return BLOCKED_EXIT without rewriting child_pid or marking run_status.json — a poller must never observe a terminal state while the winner is running.""" - pytest.importorskip("fcntl") # exclusion exists only where flock does import json as _json from infermatrix_copilot import run_status as rs diff --git a/test/test_run_service_concurrency.py b/test/test_run_service_concurrency.py index 640f8250..dad8d8c6 100644 --- a/test/test_run_service_concurrency.py +++ b/test/test_run_service_concurrency.py @@ -327,14 +327,14 @@ def test_reaper_rechecks_age_under_its_lock(settings, tmp_path, git_repo, assert wt.materialize(git_repo, sha, dest, _git)[0] os.utime(dest, (0, 0)) - real_flock = idem.fcntl.flock + real_try_lock = idem.file_locking.try_lock - def flock(fd, flags): - if flags & idem.fcntl.LOCK_EX: + def try_lock(fd, *, shared=False): + if not shared: os.utime(dest) # a run reused the tree just before this lock - return real_flock(fd, flags) + return real_try_lock(fd, shared=shared) - monkeypatch.setattr(idem.fcntl, "flock", flock) + monkeypatch.setattr(idem.file_locking, "try_lock", try_lock) counts = idem.reap_stale(settings.run_root, worktree_root=root) assert dest.exists() assert counts["worktrees"] == 0 diff --git a/test/test_tool_bridge_lifecycle.py b/test/test_tool_bridge_lifecycle.py index d65cf123..c96cdd03 100644 --- a/test/test_tool_bridge_lifecycle.py +++ b/test/test_tool_bridge_lifecycle.py @@ -19,7 +19,6 @@ import asyncio import json -import os import signal import subprocess import sys @@ -149,15 +148,16 @@ def test_lifecycle_write_failure_never_raises(tmp_path): lifecycle.record("start") # must not raise -@pytest.mark.skipif(sys.platform == "win32", reason="POSIX signals") -def test_bridge_process_survives_sigint_sighup_and_exits_on_stdin_close(tmp_path): - """End-to-end on the real stdio server: SIGINT and SIGHUP are ignored - (the process stays alive), closing stdin ends it with rc 0, and the - lifecycle log carries start + exit(reason=stdin_closed).""" +def test_bridge_process_exits_on_stdin_close(tmp_path): + """The real stdio server exits when stdin closes and logs its lifecycle. + + On POSIX it also survives the terminal signals it explicitly ignores. + """ pytest.importorskip("mcp") spec, _worktree, run_dir = _spec(tmp_path) - env = {"PATH": os.environ.get("PATH", ""), "PYTHONPATH": str(ROOT / "src"), - "HOME": str(tmp_path)} + from infermatrix_copilot.providers.base import sanitized_env + + env = {**sanitized_env(), "PYTHONPATH": str(ROOT / "src"), "HOME": str(tmp_path)} proc = subprocess.Popen( [sys.executable, "-m", "infermatrix_copilot.tool_bridge", "--spec", str(spec)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, @@ -170,20 +170,25 @@ def test_bridge_process_survives_sigint_sighup_and_exits_on_stdin_close(tmp_path break time.sleep(0.1) else: - pytest.fail(f"bridge never logged start: {proc.stderr.read()!r}") + pytest.fail(f"bridge never logged start (exit code {proc.poll()})") # dispositions are installed before the start event is written, so # the signals may go out as soon as it appears - proc.send_signal(signal.SIGINT) - proc.send_signal(signal.SIGHUP) - time.sleep(1.0) - assert proc.poll() is None, f"bridge died on SIGINT/SIGHUP: rc={proc.returncode}" + if sys.platform != "win32": + proc.send_signal(signal.SIGINT) + proc.send_signal(signal.SIGHUP) + time.sleep(1.0) + assert proc.poll() is None, f"bridge died on SIGINT/SIGHUP: rc={proc.returncode}" proc.stdin.close() rc = proc.wait(timeout=30) assert rc == 0, proc.stderr.read() events = read_lifecycle_events(spec) kinds = [e["kind"] for e in events] assert kinds[0] == "start" and kinds[-1] == "exit" - assert events[0]["pid"] == proc.pid and events[0]["spec"] == str(spec) + # A Windows virtualenv launcher has a different PID from its Python child. + assert events[0]["pid"] == events[-1]["pid"] + assert events[0]["spec"] == str(spec) + if sys.platform != "win32": + assert events[0]["pid"] == proc.pid assert events[-1]["reason"] == "stdin_closed" assert events[-1]["parent_alive"] is True # we, the launcher, are alive assert log.parent == run_dir / "bridge"