diff --git a/scripts/ai-accounts/ai-accounts b/scripts/ai-accounts/ai-accounts index cdc7a1fd..1530d06a 100755 --- a/scripts/ai-accounts/ai-accounts +++ b/scripts/ai-accounts/ai-accounts @@ -46,6 +46,7 @@ from __future__ import annotations import argparse import base64 +import ctypes import datetime as dt import errno from email.utils import parsedate_to_datetime @@ -201,9 +202,20 @@ def sync_codex_home(home: Path, *, create: bool = False) -> None: _sync_codex_home(home) -def _copy_across_devices(entry: Path, target: Path) -> None: - import ctypes +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") + 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() + raise OSError(error, os.strerror(error), source, None, target) + +def _copy_across_devices(entry: Path, target: Path) -> None: # The private staging directory is also excluded from future mirroring # by shared() if the process is interrupted before cleanup. with tempfile.TemporaryDirectory(dir=target.parent, prefix=".codex-sync-", suffix=".lock") as directory: @@ -214,16 +226,7 @@ def _copy_across_devices(entry: Path, target: Path) -> None: else: shutil.copy2(entry, staged, follow_symlinks=False) - # Linux/WSL renameat2 with RENAME_NOREPLACE publishes the complete - # entry in one operation without replacing a competing destination. - rename = getattr(ctypes.CDLL(None, use_errno=True), "renameat2", None) - if rename is None: - raise OSError(errno.ENOSYS, "Atomic cross-device publication is unavailable", target) - if rename(-100, os.fsencode(staged), -100, os.fsencode(target), 1): - error = ctypes.get_errno() - if error == errno.EEXIST: - return - raise OSError(error, os.strerror(error), target) + _rename_noreplace(staged, target) if is_directory: shutil.rmtree(entry) else: @@ -237,13 +240,16 @@ 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: - pass + try: + _rename_noreplace(entry, target) + except OSError as exc: + if exc.errno != errno.EXDEV: + raise + _copy_across_devices(entry, target) except OSError as exc: - if exc.errno != errno.EXDEV: + if exc.errno not in {errno.EEXIST, errno.ENOENT, errno.ENOSYS, errno.EINVAL, + errno.EOPNOTSUPP}: raise - _copy_across_devices(entry, target) for src in CODEX_MAIN.iterdir(): dst = home / src.name if shared(src) and not dst.exists() and not dst.is_symlink(): @@ -607,10 +613,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/src/loopzero/worktree.py b/src/loopzero/worktree.py index 4d38c4de..08abf343 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -8,6 +8,7 @@ import re import stat import subprocess +import time from collections.abc import Iterator from collections.abc import Callable from contextlib import contextmanager, suppress @@ -112,7 +113,15 @@ def _local_state_directory(wt: Path, *, create: bool = False, lock: bool = False raise WorktreeError(f"local state directory is not a directory or is a symbolic link: {path}") from exc try: if lock: - fcntl.flock(fd, fcntl.LOCK_EX) + deadline = time.monotonic() + 60 + while (remaining := deadline - time.monotonic()) > 0: + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + break + except BlockingIOError: + time.sleep(min(0.1, remaining)) + else: + raise TimeoutError(f"task state is busy in {wt}; retry when the other command finishes") yield fd finally: os.close(fd) diff --git a/tests/test_ai_accounts.py b/tests/test_ai_accounts.py index cba117bd..679e03dc 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}}) @@ -618,3 +632,28 @@ def stage(src, dst, **kwargs): helper.account_env("codex", "extra") assert entry.read_text() == "original" and entry.is_symlink() == (outcome == "published") assert list(Path(main).iterdir()) == ([] if outcome == "copy failed" else [Path(main) / entry.name]) + + +@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() + 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() + 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() and (home / "notes").read_text() == "promote" diff --git a/tests/test_cli.py b/tests/test_cli.py index ab708699..77942cd8 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4719,6 +4719,25 @@ 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(git_repo, monkeypatch): + now = 0.0 + + def advance(seconds): + nonlocal now + now += seconds + + 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"), + cli.worktree.lock_local_state(git_repo), + ): + pytest.fail("contender acquired a held directory lock") + assert now == 60 + with cli.worktree.lock_local_state(git_repo): + assert now == 60 + + @pytest.mark.parametrize("redirected", [False, True]) def test_checks_report_survives_failed_publication(git_repo, tmp_path, monkeypatch, redirected): path = git_repo / cli.CHECKS_FILE