Skip to content
Closed
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
51 changes: 30 additions & 21 deletions scripts/ai-accounts/ai-accounts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand All @@ -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():
Expand Down Expand Up @@ -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

Expand Down
6 changes: 3 additions & 3 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1851,18 +1851,18 @@ def _delete_tracking_ref(wt: Path, branch: str, expected_head: str) -> None:


def cmd_resolve(args: argparse.Namespace) -> int:
"""List open blocking findings, or reply to one with what changed and resolve its thread."""
encoding = getattr(sys.stdout, "encoding", None) or "utf-8"
wt, config = _context(args, pin_checks=True) # publishers come from the base, not the PR
pr = _require_pr(config, worktree.branch(wt))
if pr.base_ref != config.base_branch: # trusted publishers belong to the configured base
raise CliError(f"PR #{pr.number} targets {pr.base_ref}, configured base is {config.base_branch}")
publishers = config.review_publishers or (github.login(),)
if not args.finding:
for marker_id, _thread, f in github.open_findings(config.repo, pr.number, publishers):
print(f"{marker_id} {f.severity} {f.path or '-'}:{f.line or '-'} {f.title}")
print(f"{marker_id} {f.severity} {f.path or '-'}:{f.line or '-'} {f.title}".encode(encoding, "backslashreplace").decode(encoding))
return 0
finding = github.resolve_finding(config.repo, pr.number, args.finding, args.reply, publishers)
print(f"resolved {args.finding}: {finding.title}")
print(f"resolved {args.finding}: {finding.title}".encode(encoding, "backslashreplace").decode(encoding))
try:
with github.api_error_diagnostics():
remaining = github.open_blocking_findings(config.repo, pr.number, None, publishers)
Expand Down
11 changes: 10 additions & 1 deletion src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
43 changes: 41 additions & 2 deletions tests/test_ai_accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}})
Expand Down Expand Up @@ -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"
37 changes: 28 additions & 9 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4061,25 +4061,25 @@ def finding_pr(wt, gh, head):

@pytest.mark.parametrize("outcome", ["refreshed", "remaining", "dispatch failed"])
def test_resolve_lists_then_replies_and_resolves_one_finding(finding_pr, gh: FakeGh, capsys, outcome) -> None:
listing = threads_json(finding_pr)
remaining = listing if outcome == "remaining" else threads_json()
gh.respond("api graphql", listing, listing, REPLY_ACCEPTED, THREAD_RESOLVED, remaining)
sys.stdout.reconfigure(encoding="ascii" if outcome == "refreshed" else "utf-8", errors="strict")
finding_pr["comments"]["nodes"][0]["body"] = finding_pr["comments"]["nodes"][0]["body"].replace("Off by one", "Łódź")
listing = threads_json({**finding_pr, "path": "src/Łódź.py"})
gh.respond("api graphql", listing, listing, REPLY_ACCEPTED, THREAD_RESOLVED,
listing if outcome == "remaining" else threads_json())
gh.respond("api -X", "", exit=int(outcome == "dispatch failed"), stderr="HTTP 403")

expect_cli(capsys, 0, "resolve", stderr="", stdout="0b9b59e7 important src/a.py:3 Off by one\n")
title = r"\u0141\xf3d\u017a" if outcome == "refreshed" else "Łódź"
expect_cli(capsys, 0, "resolve", stderr="", stdout=f"0b9b59e7 important src/{title}.py:3 {title}\n")
assert not any("eligibility.yml/dispatches" in " ".join(c["argv"]) for c in gh.calls)

code, out, err = run(capsys, "resolve", "0b9b59e7", "Fixed in abc1234: loop bound corrected.")
assert out.splitlines()[0] == "resolved 0b9b59e7: Off by one"
assert out.splitlines()[0] == f"resolved 0b9b59e7: {title}"
calls = [c["argv"] for c in gh.calls
if c["argv"][:2] == ["api", "graphql"] and "viewer {" not in c["argv"][3]][2:]
assert "addPullRequestReviewThreadReply" in calls[0][3] and "resolveReviewThread" in calls[1][3]
assert "body=Fixed in abc1234: loop bound corrected." in calls[0] and "thread=THREAD_1" in calls[1]
endpoint = f"repos/{REPO}/actions/workflows/eligibility.yml/dispatches"
dispatches = [c["argv"] for c in gh.calls if endpoint in c["argv"]]
if outcome == "remaining":
assert (code, err, dispatches) == (0, "", [])
assert len(out.splitlines()) == 1
assert (code, err, dispatches, len(out.splitlines())) == (0, "", [], 1)
else:
assert dispatches == [["api", "-X", "POST", endpoint, "-f", "ref=main", "-f", "inputs[pr]=7", "--include"]]
if outcome == "refreshed":
Expand Down Expand Up @@ -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
Expand Down
Loading