From 8771095a742f0dc767b26fc275244cebb214f21e Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:40:14 +0100 Subject: [PATCH 1/5] Bound task-state lock acquisition Architecture-Review: unchanged; task writers keep their existing lock and fail closed if it stays occupied. Co-Authored-By: Codex --- src/loopzero/cli.py | 10 +++++++++- tests/test_cli.py | 20 ++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 29829078..4cc12c95 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -374,7 +374,15 @@ def _lock_task_state(wt: Path) -> Iterator[None]: directory.mkdir(parents=True, exist_ok=True) fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY) try: - fcntl.flock(fd, fcntl.LOCK_EX) + deadline = time.monotonic() + GIT_TIMEOUT + while (remaining := deadline - time.monotonic()) > 0: + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + break + except BlockingIOError: + _sleep(min(0.1, remaining)) + else: + raise TimeoutError(f"task state is busy in {wt}; retry when the other command finishes") yield finally: os.close(fd) diff --git a/tests/test_cli.py b/tests/test_cli.py index 53b0e0ba..fcdac4d5 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4735,6 +4735,26 @@ def test_wait_rechecks_closed_unmerged_pr(monkeypatch, final) -> None: assert _closed_unmerged_wait(monkeypatch, reads, steps=1) == final +def test_task_state_lock_times_out_with_a_live_holder(tmp_path, monkeypatch): + now = 0.0 + + def advance(seconds): + nonlocal now + now += seconds + + monkeypatch.setattr(cli.time, "monotonic", lambda: now) + monkeypatch.setattr(cli, "_sleep", advance) + with cli._lock_task_state(tmp_path): + with ( + pytest.raises(TimeoutError, match=r"task state is busy.*retry"), + cli._lock_task_state(tmp_path), + ): + pytest.fail("contender acquired a held directory lock") + assert now == cli.GIT_TIMEOUT + with cli._lock_task_state(tmp_path): + assert now == cli.GIT_TIMEOUT + + def test_checks_report_survives_failed_publication(tmp_path, monkeypatch): path = tmp_path / cli.CHECKS_FILE monkeypatch.setattr(cli.worktree, "head", lambda _: next(heads)) From 2caa6acaa6458180e1631a9594fee3903e50464b Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:56:38 +0100 Subject: [PATCH 2/5] Promote shared Codex entries without replacing the destination Architecture-Review: unchanged; account mirroring retains its lock and layout while refusing concurrent destination replacement. Co-Authored-By: Codex --- scripts/ai-accounts/ai-accounts | 18 ++++++++++++++++-- tests/test_ai_accounts.py | 23 +++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/scripts/ai-accounts/ai-accounts b/scripts/ai-accounts/ai-accounts index 5c4c901d..f2757abc 100755 --- a/scripts/ai-accounts/ai-accounts +++ b/scripts/ai-accounts/ai-accounts @@ -46,7 +46,9 @@ from __future__ import annotations import argparse import base64 +import ctypes import datetime as dt +import errno from email.utils import parsedate_to_datetime import fcntl import hashlib @@ -200,6 +202,18 @@ def sync_codex_home(home: Path, *, create: bool = False) -> None: _sync_codex_home(home) +def _rename_noreplace(source: Path, target: Path) -> None: + """Publish a shared entry atomically, including directories.""" + libc = ctypes.CDLL(None, use_errno=True) + renameat2 = getattr(libc, "renameat2", None) + if renameat2 is None: + raise OSError(errno.ENOSYS, "atomic no-replace promotion requires renameat2") + at_fdcwd, rename_noreplace = -100, 1 + if renameat2(at_fdcwd, os.fsencode(source), at_fdcwd, os.fsencode(target), rename_noreplace): + error = ctypes.get_errno() + raise OSError(error, os.strerror(error), source, None, target) + + def _sync_codex_home(home: Path) -> None: """Mirror shared Codex files while holding the home lock.""" for entry in home.iterdir(): @@ -207,8 +221,8 @@ def _sync_codex_home(home: Path) -> None: if shared(entry) and not entry.is_symlink() and not target.exists() \ and not target.is_symlink(): try: - os.rename(entry, target) - except FileNotFoundError: + _rename_noreplace(entry, target) + except (FileExistsError, FileNotFoundError): pass for src in CODEX_MAIN.iterdir(): dst = home / src.name diff --git a/tests/test_ai_accounts.py b/tests/test_ai_accounts.py index c161c052..e02de851 100644 --- a/tests/test_ai_accounts.py +++ b/tests/test_ai_accounts.py @@ -593,3 +593,26 @@ def test_account_lock_preserves_existing_file_and_rejects_symlink(helper): with pytest.raises(OSError), helper._locked(".codex-sync.lock"): pytest.fail("redirected lock opened") assert lock.read_text() == "preserve" + + +def test_sync_preserves_a_shared_directory_created_during_promotion(helper, monkeypatch): + home = helper.codex_home("extra") + home.mkdir(parents=True) + helper.CODEX_MAIN.mkdir() + source = home / "sessions" + source.mkdir() + (source / "old").write_text("keep local") + (home / "notes").write_text("promote") + rename = helper._rename_noreplace + + def create_destination(entry, target): + if entry == source: + target.mkdir() + rename(entry, target) + + monkeypatch.setattr(helper, "_rename_noreplace", create_destination) + helper.sync_codex_home(home) + assert (source / "old").read_text() == "keep local" + assert list((helper.CODEX_MAIN / "sessions").iterdir()) == [] + assert (home / "notes").is_symlink() + assert (home / "notes").read_text() == "promote" From a6a2a19b89ded73aac7d7b4ff3bf51a4c02661a5 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:58:57 +0100 Subject: [PATCH 3/5] Keep mirroring when no-replace promotion is unsupported Co-Authored-By: Codex --- scripts/ai-accounts/ai-accounts | 8 ++++++-- tests/test_ai_accounts.py | 8 +++++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/scripts/ai-accounts/ai-accounts b/scripts/ai-accounts/ai-accounts index f2757abc..f7702dc8 100755 --- a/scripts/ai-accounts/ai-accounts +++ b/scripts/ai-accounts/ai-accounts @@ -208,6 +208,7 @@ def _rename_noreplace(source: Path, target: Path) -> None: renameat2 = getattr(libc, "renameat2", None) if renameat2 is None: raise OSError(errno.ENOSYS, "atomic no-replace promotion requires renameat2") + renameat2.argtypes = (ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint) at_fdcwd, rename_noreplace = -100, 1 if renameat2(at_fdcwd, os.fsencode(source), at_fdcwd, os.fsencode(target), rename_noreplace): error = ctypes.get_errno() @@ -222,8 +223,11 @@ def _sync_codex_home(home: Path) -> None: and not target.is_symlink(): try: _rename_noreplace(entry, target) - except (FileExistsError, FileNotFoundError): - pass + except OSError as exc: + # A competing writer or unsupported no-replace operation leaves the source local. + if exc.errno not in {errno.EEXIST, errno.ENOENT, errno.ENOSYS, errno.EINVAL, + errno.EOPNOTSUPP, errno.EXDEV}: + raise for src in CODEX_MAIN.iterdir(): dst = home / src.name if shared(src) and not dst.exists() and not dst.is_symlink(): diff --git a/tests/test_ai_accounts.py b/tests/test_ai_accounts.py index e02de851..2464d7a2 100644 --- a/tests/test_ai_accounts.py +++ b/tests/test_ai_accounts.py @@ -595,7 +595,8 @@ def test_account_lock_preserves_existing_file_and_rejects_symlink(helper): assert lock.read_text() == "preserve" -def test_sync_preserves_a_shared_directory_created_during_promotion(helper, monkeypatch): +@pytest.mark.parametrize("unsupported", [None, "ENOSYS", "EINVAL"]) +def test_sync_preserves_a_shared_directory_created_during_promotion(helper, monkeypatch, unsupported): home = helper.codex_home("extra") home.mkdir(parents=True) helper.CODEX_MAIN.mkdir() @@ -608,11 +609,12 @@ def test_sync_preserves_a_shared_directory_created_during_promotion(helper, monk def create_destination(entry, target): if entry == source: target.mkdir() + if unsupported: + raise OSError(getattr(helper.errno, unsupported), "no-replace unsupported") rename(entry, target) monkeypatch.setattr(helper, "_rename_noreplace", create_destination) helper.sync_codex_home(home) assert (source / "old").read_text() == "keep local" assert list((helper.CODEX_MAIN / "sessions").iterdir()) == [] - assert (home / "notes").is_symlink() - assert (home / "notes").read_text() == "promote" + assert (home / "notes").is_symlink() and (home / "notes").read_text() == "promote" From 9d17de4361b71af47572e553e045d73a7658f2e0 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:10:43 +0100 Subject: [PATCH 4/5] Isolate the task-state timeout test clock Co-Authored-By: Codex --- tests/test_cli.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index df26cd91..f9f62e24 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4706,8 +4706,7 @@ def advance(seconds): nonlocal now now += seconds - monkeypatch.setattr(cli.worktree.time, "monotonic", lambda: now) - monkeypatch.setattr(cli.worktree.time, "sleep", advance) + monkeypatch.setattr(cli.worktree, "time", SimpleNamespace(monotonic=lambda: now, sleep=advance)) with cli.worktree.lock_local_state(git_repo): with ( pytest.raises(TimeoutError, match=r"task state is busy.*retry"), From 83dc6d9db9e27f0db0ea1d3b3472ce4a9823dbef Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:12:06 +0100 Subject: [PATCH 5/5] Keep shorter Codex auth refreshes valid on the bound inode Architecture-Review: unchanged; refresh preserves the existing auth inode, credential identity and token exchange. Co-Authored-By: Codex --- scripts/ai-accounts/ai-accounts | 11 +++++++---- tests/test_ai_accounts.py | 18 ++++++++++++++++-- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/scripts/ai-accounts/ai-accounts b/scripts/ai-accounts/ai-accounts index cdc7a1fd..5c5b183c 100755 --- a/scripts/ai-accounts/ai-accounts +++ b/scripts/ai-accounts/ai-accounts @@ -607,10 +607,13 @@ def refresh_codex(auth_file: Path, auth: dict) -> tuple[str, dict]: fresh = json.loads(raw) tokens.update({k: fresh[k] for k in ("id_token", "access_token", "refresh_token") if fresh.get(k)}) auth["last_refresh"] = dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z") - # Rewrite in place like Codex: reviewers bind-mount this inode, so os.replace would detach them. - with open(auth_file, "r+", encoding="utf-8") as fh: - fh.write(json.dumps(auth, indent=2) + "\n") - fh.truncate() + # Reviewers bind-mount this inode. Pad shorter JSON with whitespace so + # the completed write is readable without a second, interruptible truncate. + payload = (json.dumps(auth, indent=2) + "\n").encode("utf-8") + with auth_file.open("r+b", buffering=0) as fh: + payload = payload.ljust(os.fstat(fh.fileno()).st_size, b" ") + if os.pwrite(fh.fileno(), payload, 0) != len(payload): + raise OSError("incomplete Codex auth write") log(f"codex: refreshed {auth_file}") return tokens["access_token"], tokens diff --git a/tests/test_ai_accounts.py b/tests/test_ai_accounts.py index cba117bd..abcc5be5 100644 --- a/tests/test_ai_accounts.py +++ b/tests/test_ai_accounts.py @@ -183,11 +183,25 @@ def test_codex_select_reserves_current_at_85_without_churn(helper): def test_codex_refresh_keeps_managed_binding_and_exhaustion_selection(helper, monkeypatch): auth = helper.CODEX_MAIN / 'auth.json' principal = {'account_id': 'account-a', 'id_token': 'e30.eyJzdWIiOiJ1c2VyLWEiLCJpc3MiOiJpc3N1ZXIifQ.x'} - helper.write_private(auth, json.dumps({'tokens': {**principal, 'access_token': 'old'}})) + helper.write_private(auth, json.dumps({'tokens': {**principal, 'access_token': 'old' * 100, 'refresh_token': 'old-refresh'}})) helper.write_private(helper.STATE / 'codex/homes/b/auth.json', json.dumps({'tokens': {'account_id': 'account-b', 'access_token': 'other'}})) helper.set_active('codex', 'main') inherited = helper.with_accounts('codex', {}) - helper.write_private(auth, json.dumps({'tokens': {**principal, 'access_token': 'fresh', 'refresh_token': 'rotated'}})) + refreshed = {"access_token": "fresh", "refresh_token": "rotated"} + monkeypatch.setattr(helper, "_http", lambda _: (200, {}, json.dumps(refreshed))) + write = helper.os.pwrite + + def interrupt(fd, data, offset): + write(fd, data, offset) + raise KeyboardInterrupt + + with auth.open("rb") as pinned, monkeypatch.context() as patch: + patch.setattr(helper.os, "pwrite", interrupt) + patch.setattr(helper, "jwt_claims", lambda _: {"client_id": "test"}) + with pytest.raises(KeyboardInterrupt): + helper.refresh_codex(auth, json.loads(auth.read_text())) + assert json.load(pinned)["tokens"] == {**principal, **refreshed} + assert auth.stat().st_ino == helper.os.fstat(pinned.fileno()).st_ino revision = inherited['AI_ACCOUNTS_CODEX_IDENTITY'] assert helper.managed_name('codex', inherited) == 'main' monkeypatch.setattr(helper, 'check_codex', lambda name: {'tier': 2, 'util': 0, 'models': {'m': True}})