Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions doc/architecture/SPEC/app/run_service.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# app/run_service.py —— 规范

<!-- verified-against: 2026-10-30 -->
<!-- verified-against: 2026-12-01 -->

`RunService` is the durable application boundary shared by the embedded
Strict SDK and MCP transport. It owns policy-checked reserve/start, a queue
Expand Down Expand Up @@ -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:
Expand Down
14 changes: 7 additions & 7 deletions doc/architecture/SPEC/engine/lifecycle.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# engine/lifecycle.py —— 规范

<!-- verified-against: 2026-10-28 -->
<!-- verified-against: 2026-12-01 -->

`LOC ~396 · 引擎底座(run 生命周期原语 + 优雅停机) · refactor-status: ok`

Expand All @@ -12,7 +12,7 @@ GPU 调度器 `--timeout` 发出的 SIGINT 被整个忽略,随后 reservation
杀掉其下的测试进程)。

## 功能
`RunLock` 对 `<run_dir>/.lock` 取排他 advisory `flock`(第二个并发
`RunLock` 对 `<run_dir>/.lock` 取操作系统排他 advisory 锁(第二个并发
`--resume` fail fast,而不是交错写进度、共享 checkout);
`register_finalizer`/`finalize` 维护逐 run 的异步 finalizer 表;
`run_guarded` 包住 executor 协程,在完成/失败/抛异常的**每条**退出路径上、
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 时跑钩子即返回、
Expand Down
8 changes: 4 additions & 4 deletions doc/architecture/SPEC/engine/worktrees.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# engine/worktrees.py —— 规范

<!-- verified-against: 2026-09-30 -->
<!-- verified-against: 2026-12-01 -->

`LOC ~294 · PR-time worktree:身份、物化、持有 · refactor-status: ok`

Expand All @@ -9,7 +9,7 @@ PR 快照 worktree 的三条性质,每条都对应一个修掉的真实事故
**身份**(旧键 `<repo>-pr<N>` 在不同 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` 只有前者才有)。

Expand Down Expand Up @@ -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 仓库分键、
Expand Down
12 changes: 12 additions & 0 deletions doc/architecture/SPEC/file_locking.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# file_locking.py —— 规范

<!-- verified-against: 2026-12-01 -->

Strict 的预约、状态和 worktree 使用同一组操作系统文件锁原语。POSIX 使用 `flock`,Windows 使用 `LockFileEx` 锁定从偏移 0 开始的一个字节,支持空锁文件。

- `try_lock` 支持共享和排他模式,只在锁被占用时返回 `False`,其余错误由调用者处理。
- `lock` 等待排他锁,可指定超时。`unlock` 在同一个描述符上释放锁。描述符关闭或进程退出后,由操作系统释放剩余锁。
- 持有者和等待者必须竞争同一个锁文件。调用者不得在释放锁时删除该文件。
- 无系统锁的平台保留旧的单进程 CLI 降级。Strict 在预约和创建 worktree 前调用 `require_file_locking` 拒绝不受保护的执行。

`test_run_lifecycle.py` 验证跨进程排他、进程退出后的释放,以及共享持有者和排他持有者之间的互斥。
2 changes: 1 addition & 1 deletion doc/architecture/SPEC/idempotency.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# idempotency.py —— 规范

<!-- verified-against: 2026-09-30 -->
<!-- verified-against: 2026-12-01 -->

`LOC ~293 · 持久 idempotency 索引:每键一个 run、一次执行 · refactor-status: ok`

Expand Down
2 changes: 1 addition & 1 deletion doc/architecture/SPEC/providers/base.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# providers/base.py —— 规范

<!-- verified-against: 2026-10-28 -->
<!-- verified-against: 2026-12-01 -->

`LOC ~234 · provider 层契约 + 子进程环境白名单 + 受管 CLI 子进程 · refactor-status: ok`

Expand Down
2 changes: 1 addition & 1 deletion doc/architecture/SPEC/providers/codex.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# providers/codex.py —— 规范

<!-- verified-against: 2026-10-28 -->
<!-- verified-against: 2026-12-01 -->

`LOC ~197 · harness transport(ChatGPT 订阅) · refactor-status: ok`

Expand Down
6 changes: 3 additions & 3 deletions doc/architecture/SPEC/run_status.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# run_status.py —— 规范

<!-- verified-against: 2026-10-28 -->
<!-- verified-against: 2026-12-01 -->

`LOC ~345 · 持久化的单写者 run 生命周期记录 · refactor-status: ok`

Expand Down Expand Up @@ -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 去抢另一个
Expand All @@ -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`
Expand Down
4 changes: 2 additions & 2 deletions doc/architecture/SPEC/tool_bridge.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# tool_bridge.py —— 规范

<!-- verified-against: 2026-10-28 -->
<!-- verified-against: 2026-12-01 -->

`LOC ~783 · 面向 harness 会话的 scoped 工具 MCP server · refactor-status: ok`

Expand Down Expand Up @@ -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 是唯一正常退出。
Expand Down
4 changes: 2 additions & 2 deletions src/infermatrix_copilot/app/run_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down
48 changes: 15 additions & 33 deletions src/infermatrix_copilot/engine/lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand All @@ -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()
Expand Down
44 changes: 14 additions & 30 deletions src/infermatrix_copilot/engine/worktrees.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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,
Expand All @@ -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:
Expand All @@ -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():
Expand All @@ -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:
Expand All @@ -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)
Expand All @@ -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)

Expand Down
Loading
Loading