From 6fbacdaf73115b07c654f8be801b780406e6f3ca Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:39:23 +0100 Subject: [PATCH 1/3] Document and test the hosted ancestor-review pin rollout Co-Authored-By: Codex --- SETUP.md | 6 +++++ tests/test_hosted.py | 55 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/SETUP.md b/SETUP.md index d2153ef9..79d04e41 100644 --- a/SETUP.md +++ b/SETUP.md @@ -466,6 +466,12 @@ the consumer CI pin that supplies `loopzero.hosted` or `loopzero.eligibility` eligibility workflow for the existing PR, or run the command below with its unchanged source SHA. The refreshed reader can use the approval already on GitHub. +For inherited review coverage, advance both source and candidate workflow pins to +a revision containing [23219dd3 (#1081)](https://github.com/feder-positronics/loop-zero/commit/23219dd39e641549164c346e137f4e09718115f6). +The updated reader accepts an ancestor approval only across verified clean merges +from the configured base. After deploying both pins, refresh eligibility for open +sources judged by the older reader so their statuses reflect the updated policy. + From a trusted base checkout, run: ```sh diff --git a/tests/test_hosted.py b/tests/test_hosted.py index e15e7912..28dfd14c 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -2,6 +2,8 @@ import json import subprocess import sys +from contextlib import nullcontext +from functools import partial from pathlib import Path from types import SimpleNamespace @@ -10,6 +12,7 @@ from loopzero import github, hosted from loopzero.candidate import CandidateError, CandidateRaceError from tests import test_github as fixtures +from tests.conftest import git from tests.test_candidate import event as candidate_event from tests.test_candidate import payloads as candidate_payloads from tests.test_candidate import status as candidate_status @@ -97,6 +100,58 @@ def test_source_publication_is_bound_to_live_review(publisher, case, blocker, st assert status != "pending" or statuses[-1]["description"] == "Awaiting trusted review of current source head" +@pytest.mark.parametrize("candidate", [False, True]) +@pytest.mark.parametrize("change", ["exact", "ordinary", "clean merge"]) +def test_hosted_review_coverage_after_source_head_changes( + publisher, git_repo, monkeypatch, candidate, change, +): + git(git_repo, "switch", "-qc", "source") + git(git_repo, "commit", "-qm", "reviewed source", "--allow-empty") + reviewed = git(git_repo, "rev-parse", "HEAD").strip() + git(git_repo, "switch", "-q", "main") + git(git_repo, "commit", "-qm", "base advance", "--allow-empty") + base = git(git_repo, "rev-parse", "HEAD").strip() + git(git_repo, "switch", "-q", "source") + if change == "ordinary": + git(git_repo, "commit", "-qm", "unreviewed source", "--allow-empty") + elif change == "clean merge": + git(git_repo, "merge", "-q", "--no-edit", "main") + head = git(git_repo, "rev-parse", "HEAD").strip() + source = fixtures.rest_pr_json(pr_json(headRefOid=head)) + source["base"]["sha"] = base + publisher.respond(f"api repos/{REPO}/pulls/7", source) + publisher.respond(f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1", [{ + "state": "COMMENTED", "commit_id": reviewed, "user": {"login": "trusted-publisher"}, + "body": f"\n" + "loopzero primary review by claude: **approve** (0 critical, 0 important, 0 suggestion)", + }]) + publisher.respond(f"api repos/{REPO}/compare/{reviewed}...{head}", {"status": "ahead"}) + monkeypatch.setattr(hosted.candidate_mod, "fetched_git", + lambda *_: nullcontext(partial(git, git_repo))) + + target = head + if candidate: + target = HEAD + Path("event.json").write_text(json.dumps({ + "action": "opened", "pull_request": {"number": 9, "head": {"sha": target}}, + })) + publisher.respond(f"api repos/{REPO}/pulls/9", fixtures.rest_pr_json( + pr_json(number=9, headRefOid=target), branch="mergify/merge-queue/main", + )) + monkeypatch.setattr(hosted.candidate_mod, "attest_candidate", + lambda _event, *, source_policy, **_: source_policy(7, source)) + publisher.respond(f"api repos/{REPO}/statuses/{target}", {}) + + if change == "ordinary" and candidate: + with pytest.raises(hosted.LoopZeroError, match="no review recorded"): + hosted.main() + else: + assert hosted.main() == 0 + states = [json.loads(call["--input"])["state"] for call in publisher.calls if "--input" in call] + assert states == ["pending", ("failure" if candidate else "pending") + if change == "ordinary" else "success"] + + def test_merged_source_refresh_publishes_nothing(publisher): body = json.dumps({"head": {"sha": HEAD, "ref": "lz/task"}, "user": {"login": "author"}, "merged": True, "title": "before\u2028after"}, ensure_ascii=False) From 6f83c8a0f0e5e51687715c098cde6a2c87e4d66b Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:37:25 +0100 Subject: [PATCH 2/3] Reduce duplicated check and review handling Share sandbox failures and review publication identity checks. Simplify check receipt and subprocess result construction without changing interfaces. Architecture-Review: unchanged; command output, receipt schema, subprocess setup, and sandbox boundaries stay the same. Co-Authored-By: Codex --- src/loopzero/_proc.py | 34 +++-------- src/loopzero/cli.py | 130 ++++++++++++++++------------------------ src/loopzero/sandbox.py | 22 ++----- 3 files changed, 68 insertions(+), 118 deletions(-) diff --git a/src/loopzero/_proc.py b/src/loopzero/_proc.py index 1d70e76f..a7db463d 100644 --- a/src/loopzero/_proc.py +++ b/src/loopzero/_proc.py @@ -188,22 +188,15 @@ def run( stdin = input.encode(raw_encoding) if preserve_newlines and input is not None else input try: with subprocess.Popen( - argv, - cwd=str(cwd), - env=build_env(env_allowlist, extra_env), - stdin=subprocess.PIPE if input is not None else subprocess.DEVNULL, - stdout=subprocess.PIPE, + argv, cwd=str(cwd), env=build_env(env_allowlist, extra_env), + stdin=subprocess.PIPE if input is not None else subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT if merge_output else subprocess.PIPE, - encoding=None if preserve_newlines else encoding, - errors=None if preserve_newlines else "replace", - pass_fds=pass_fds, - start_new_session=os.name == "posix", + encoding=None if preserve_newlines else encoding, errors=None if preserve_newlines else "replace", + pass_fds=pass_fds, start_new_session=os.name == "posix", ) as proc: try: - if tail_chars is None: - stdout, stderr = proc.communicate(stdin, timeout=timeout) - else: - stdout, stderr = _read_output_tail(proc, tail_chars, timeout), "" + stdout, stderr = (proc.communicate(stdin, timeout=timeout) if tail_chars is None + else (_read_output_tail(proc, tail_chars, timeout), "")) except BaseException: if os.name == "posix": with suppress(ProcessLookupError): @@ -221,19 +214,10 @@ def run( out = exc.stdout.decode(errors="replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "") err = exc.stderr.decode(errors="replace") if isinstance(exc.stderr, bytes) else exc.stderr elapsed = time.monotonic() - started - raise ProcTimeout( - f"{' '.join(argv)}: timed out after {timeout:g}s\n{tail(out)}", - out, - stderr=err or "", - duration_s=elapsed, - ) from exc + message = f"{' '.join(argv)}: timed out after {timeout:g}s\n{tail(out)}" + raise ProcTimeout(message, out, stderr=err or "", duration_s=elapsed) from exc if isinstance(stdout, bytes): stdout = stdout.decode(raw_encoding, errors="surrogateescape") if isinstance(stderr, bytes): stderr = stderr.decode(raw_encoding, errors="replace") - return Completed( - exit_code=proc.returncode, - stdout=stdout or "", - stderr=stderr or "", - duration_s=time.monotonic() - started, - ) + return Completed(proc.returncode, stdout or "", stderr or "", time.monotonic() - started) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 6495aaf9..44868423 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -409,13 +409,12 @@ def _print_receipt(wt: Path, report: CheckReport, action: str) -> None: def _save_report(wt: Path, report: CheckReport) -> str | None: """Publish the receipt or return the current HEAD if the result is stale.""" - payload = { - "head": report.head, - "dirty": report.dirty, - "results": [{k: v for k, v in dataclasses.asdict(result).items() - if k not in {"input_key", "reused_from"} or v is not None} - for result in report.results], - } + results = [ + {k: v for k, v in dataclasses.asdict(result).items() + if k not in {"input_key", "reused_from"} or v is not None} + for result in report.results + ] + payload = {"head": report.head, "dirty": report.dirty, "results": results} if report.settings_sha256 is not None: payload["settings_sha256"] = report.settings_sha256 return worktree.write_local_state( @@ -550,15 +549,13 @@ def _require_pr_details(wt: Path) -> None: def _append_review(body: str, result: ReviewResult) -> str: """Append one compact review record under Review, replacing its placeholder.""" line = f"- {result.kind}, {result.family}, {result.head[:12]}, {result.verdict}" - pattern = re.compile(r"(^## Review\n)(.*?)(?=^## |\Z)", re.DOTALL | re.MULTILINE) - match = pattern.search(body) + match = re.search(r"^## Review\n(.*?)(?=^## |\Z)", body, re.DOTALL | re.MULTILINE) if not match: return f"{body.rstrip()}\n\n## Review\n{line}\n" - existing = match.group(2).rstrip() - if existing.startswith("(filled by `loopzero review`)"): - existing = "" - replacement = match.group(1) + (f"{existing}\n" if existing else "") + line + "\n\n" - return pattern.sub(lambda _: replacement, body, count=1).rstrip() + "\n" + existing = match[1].rstrip() + if existing and not existing.startswith("(filled by `loopzero review`)"): + line = f"{existing}\n{line}" + return (body[:match.start(1)] + line + "\n\n" + body[match.end():]).rstrip() + "\n" def _refresh_pr_checks(wt: Path, config: Config) -> None: @@ -589,9 +586,6 @@ def _pr_title(wt: Path, branch: str) -> str: return next((t for t in headings if t and t.lower() not in _SECTIONS), branch) -# --------------------------------------------------------------------------- commands - - def cmd_start(args: argparse.Namespace) -> int: root = _toplevel() current = config_mod.run_git(root, "symbolic-ref", "--quiet", "--short", "HEAD") @@ -623,15 +617,11 @@ def cmd_check(args: argparse.Namespace) -> int: worktree.local_state_files(wt, CHECKS_FILE.name) if not config.checks: raise config_mod.ConfigError("checks.commands must list at least one command to run checks") - try: - report = sandbox.run_checks(config, wt, progress=lambda command: print( - f"running: {github.redact_credentials(command)}", flush=True), - status=lambda message: print(message, flush=True), - checkpoint=lambda partial: _save_report(wt, partial), - workflow=args.config or f"origin/{config.base_branch}:workflow.toml") - except sandbox.SandboxUnavailable as exc: - print(f"sandbox unavailable: {exc}", file=sys.stderr) - return 2 + report = sandbox.run_checks( + config, wt, progress=lambda command: print(f"running: {github.redact_credentials(command)}", flush=True), + status=lambda message: print(message, flush=True), checkpoint=lambda partial: _save_report(wt, partial), + workflow=args.config or f"origin/{config.base_branch}:workflow.toml", + ) shortened = False for result in report.results: if result.exit_code != 0: @@ -657,16 +647,16 @@ def cmd_check(args: argparse.Namespace) -> int: return 1 if shortened: print(f"Full diagnostic tail: {CHECKS_FILE} (head {report.head})", file=sys.stderr) - if report.ok and report.settings_sha256 is None: + verified = not report.ok or report.settings_sha256 is not None + if not verified: print("check stages passed but the receipt is unverified; rerun loopzero check from the task " "worktree with a stable, readable configured runner before running ready", file=sys.stderr) - _refresh_pr_checks(wt, config) - return 1 - if report.ok and not report.dirty: + elif report.ok and not report.dirty: _print_receipt(wt, report, "produced") _refresh_pr_checks(wt, config) - print("PASS" if report.ok else "FAIL") - return 0 if report.ok else 1 + if verified: + print("PASS" if report.ok else "FAIL") + return 0 if report.ok and verified else 1 def cmd_pr(args: argparse.Namespace) -> int: @@ -688,8 +678,7 @@ def cmd_pr(args: argparse.Namespace) -> int: force_lease = False push = ["push", "-u", "origin"] if pr is not None and pr.state == "OPEN": - known = _proc.run(["git", "cat-file", "-e", f"{pr.head_sha}^{{commit}}"], cwd=wt, - env_allowlist=worktree.GIT_ENV, timeout=GIT_TIMEOUT) + known = config_mod.run_git(wt, "cat-file", "-e", f"{pr.head_sha}^{{commit}}") if known.exit_code != 0: raise CliError( f"PR head {pr.head_sha[:12]} is not in this worktree; fetch and integrate it first" @@ -776,10 +765,10 @@ def locked(args: argparse.Namespace) -> int: @_lock_review def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: - if args.config: - runtime_source = "reviewer paths are unpinned because --config was provided" - else: - runtime_source = f"reviewer paths pinned to origin/{config.base_branch}@{config.trusted_base_revision}" + runtime_source = ( + "reviewer paths are unpinned because --config was provided" if args.config + else f"reviewer paths pinned to origin/{config.base_branch}@{config.trusted_base_revision}" + ) branch, head = worktree.branch(wt), worktree.head(wt) _require_task_branch(config, branch) kinds = ("primary", "delta") @@ -801,10 +790,7 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: if len(saved) > 1: raise CliError("multiple saved reviews for HEAD; publication is ambiguous") reviews = [] if saved else _pr_reviews(config.repo, pr.number) - if saved: - kind = saved[0] - else: - kind, reviewed = _select_review_round(config, pr, head, reviews) + kind, reviewed = (saved[0], None) if saved else _select_review_round(config, pr, head, reviews) publication_context = {"repo": config.repo, "number": pr.number, "publisher": publisher} if args.repost: result, publication = _load_review(wt, head, kind) @@ -833,28 +819,21 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: wt, config, head, kind, publication_context, ): raise CliError(f"saved {kind} review for {head[:12]}; run `loopzero review --repost`") - try: - result = _run_review(wt, config, head, kind, reviewed, args.model, args.effort, - runtime_source=runtime_source, publication=(config.repo, pr.number, publisher)) - except sandbox.SandboxUnavailable as exc: - print(f"sandbox unavailable: {exc}", file=sys.stderr) - return 2 + result = _run_review(wt, config, head, kind, reviewed, args.model, args.effort, + runtime_source=runtime_source, publication=(config.repo, pr.number, publisher)) final_head, final_dirty = worktree.head(wt), worktree.is_dirty(wt) if final_head != head or final_dirty: raise CliError( f"worktree changed during review: HEAD before {head}, HEAD after {final_head}; " f"dirty before False, dirty after {final_dirty}" ) - prefix = review_marker(head, kind, "model") try: - evidence = runners.codex_evidence(result) + if not _matches_publication(result, publication_context): + raise CliError("native publication context changed; HOLD") except runners.RunnerBadOutput: _save_review(wt, result) raise - if evidence is not None and (evidence["repo"], evidence["pr"], evidence["publisher"]) != (config.repo, pr.number, publisher): - raise CliError("native publication context changed; HOLD") - if args.repost: - prefix = _repost_prefix(result) + prefix = _repost_prefix(result) if args.repost else review_marker(head, kind, "model") _save_review(wt, result, publication_context) token = _refresh_publisher_token(token, publisher) try: @@ -905,22 +884,28 @@ def _repost_reviewer_families( wt: Path, config: Config, head: str, result: ReviewResult, ) -> tuple[list[str], list[str]]: authors = runners.author_families(wt, head, _primary_base(wt, config)) + candidates = [family for family in config.reviewers if family not in authors] excluded = [family for family in config.reviewers if family in authors] if result.fallback and result.family not in excluded: raise CliError( f"saved review claims a same-family fallback, but {result.family} is not a configured " "reviewer family that contributed to this PR lineage; run without --repost" ) - if not result.fallback and not any(family not in authors for family in config.reviewers): - raise IndependentReviewerUnavailable( - _independence_message(authors, excluded, []) - ) + if not result.fallback and not candidates: + raise IndependentReviewerUnavailable(_independence_message(authors, excluded, [])) if result.family in authors and not result.fallback: raise IndependentReviewerUnavailable( f"saved reviewer family {result.family} contributed to this PR lineage; " "run without --repost to obtain an independent review" ) - return [family for family in config.reviewers if family not in authors], excluded + return candidates, excluded + + +def _matches_publication(result: ReviewResult, publication: dict) -> bool: + evidence = runners.codex_evidence(result) + return evidence is None or (evidence["repo"], evidence["pr"], evidence["publisher"]) == ( + publication["repo"], publication["number"], publication["publisher"] + ) def _has_recoverable_review( @@ -934,12 +919,9 @@ def _has_recoverable_review( candidates, excluded = _repost_reviewer_families(wt, config, head, result) if result.fallback and not _published_fallback(result.fallback, candidates, excluded): return False - evidence = runners.codex_evidence(result) + return _matches_publication(result, publication) except (CliError, runners.RunnerBadOutput): return False - return evidence is None or (evidence["repo"], evidence["pr"], evidence["publisher"]) == ( - publication["repo"], publication["number"], publication["publisher"], - ) def _repost_prefix(result: ReviewResult) -> str: @@ -1104,10 +1086,7 @@ def select(family: str) -> Callable[..., ReviewResult]: result = selected[family](diff=diff) except runners.RunnerPromptTooLong: chunks = runners.split_diff(diff, config.review_chunk_bytes) - print( - f"reviewer {family} rejected the full diff; reviewing {len(chunks)} chunks", - file=sys.stderr, - ) + print(f"reviewer {family} rejected the full diff; reviewing {len(chunks)} chunks", file=sys.stderr) chunk_results = [selected[family](diff=chunk, chunk=(index, len(chunks))) for index, chunk in enumerate(chunks, 1)] result = runners.merge_reviews(chunk_results) @@ -1580,16 +1559,13 @@ def _wait_for_merge(config: Config, pr: github.PR, timeout: float) -> str | None closed: list[github.GhError] = [] print(f"PR #{pr.number} is queued for merge into {config.base_branch}; waiting") for _ in _poll_until(started, timeout): - sha = _landed(config, pr, closed) - if sha: + if sha := _landed(config, pr, closed): return sha if not github.merge_pending(config.repo, pr.number): - sha = _landed(config, pr, closed) - if sha: + if sha := _landed(config, pr, closed): return sha - if closed: - continue - raise CliError(f"PR #{pr.number} left the merge queue unmerged") + if not closed: + raise CliError(f"PR #{pr.number} left the merge queue unmerged") if closed: raise closed[0] return None @@ -1916,9 +1892,6 @@ def _print_mergify_status(config: Config, pr: github.PR, readiness: github.Readi print(f" Mergify report: {report}") -# --------------------------------------------------------------------------- entry point - - def main(argv: list[str] | None = None) -> int: return _run(parse_args(build_parser(), argv)) @@ -1931,6 +1904,9 @@ def _run(args: argparse.Namespace) -> int: print(f"loopzero {args.command}: {exc}", file=sys.stderr) return 4 except HANDLED as exc: + if isinstance(exc, sandbox.SandboxUnavailable) and args.command in {"check", "review"}: + print(f"sandbox unavailable: {exc}", file=sys.stderr) + return 2 message = str(exc) if isinstance(exc, ReviewersUnavailable) else _one_line(exc) print(f"loopzero {args.command}: {message}", file=sys.stderr) return 1 diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index 16f64df7..4f1f20b7 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -82,11 +82,7 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO status: Callable[[str], None] | None = None, checkpoint: Callable[[CheckReport], None] | None = None, workflow: str | Path = "workflow.toml", _resolved: bool = False) -> CheckReport: - """Run checks, stopping at the first failure; status emits only stage metadata. - - progress receives each command before launch, as before. Optional status receives - heartbeats from a reporting thread and completion from the calling thread. - """ + """Run until a check fails, reporting commands via progress and stage metadata via status.""" worktree = worktree.resolve() if not config.check_runner and shutil.which("bwrap") is None: raise SandboxUnavailable( @@ -147,11 +143,8 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO if checkpoint is not None and result.input_key and result.exit_code == 0: # The receipt stays nonpassing until final validation. incomplete = CheckResult(INCOMPLETE_CHECK_COMMAND, 1, 0.0, "") - unvisited = ( - previous[stage] for stage in commands[ordinal:] if stage in previous - ) - checkpoint(CheckReport(head, dirty, (*results, *unvisited, incomplete), - settings_sha256)) + unvisited = (previous[stage] for stage in commands[ordinal:] if stage in previous) + checkpoint(CheckReport(head, dirty, (*results, *unvisited, incomplete), settings_sha256)) if status: status(f"stage {ordinal}/{len(commands)}: exit {result.exit_code} " f"({result.duration_s:.1f}s)") @@ -189,10 +182,8 @@ def _previous(worktree: Path, settings_sha256: str) -> dict[str, CheckResult]: if (isinstance(command, str) and isinstance(key, str) and key and is_check_exit_code(code) and code == 0 and isinstance(tail, str)): source = result.get("reused_from") - previous[command] = CheckResult( - command, 0, 0.0, _check_tail(tail), key, - source if isinstance(source, str) else data["head"], - ) + reused_from = source if isinstance(source, str) else data["head"] + previous[command] = CheckResult(command, 0, 0.0, _check_tail(tail), key, reused_from) return previous except (OSError, WorktreeError, ValueError, KeyError, TypeError, AttributeError): return {} @@ -249,8 +240,7 @@ def settings_fingerprint(config: Config, worktree: Path, *, base: str | None = N host_env = {"PATH", "LANG", "LC_ALL", "TERM", "HEAVY_SLOT_GRANTED_CORES"} for name in host_env - dict(config.env).keys(): settings["environment"].pop(name, None) - payload = [settings, config.inputs] - return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest() + return hashlib.sha256(json.dumps([settings, config.inputs], sort_keys=True).encode()).hexdigest() def _input_blobs(config: Config, worktree: Path, paths: tuple[str, ...]) -> str | None: From 4cd3faa32247cbcec55eb23a980f4cd245ffe28d Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:43:19 +0100 Subject: [PATCH 3/3] Use exclusive staging and safe lock opens for account files Architecture-Review: unchanged; the account helper retains its state format and lock order. Co-Authored-By: Codex --- scripts/ai-accounts/ai-accounts | 20 ++++++++++++++------ tests/test_ai_accounts.py | 23 +++++++++++++++++++++++ 2 files changed, 37 insertions(+), 6 deletions(-) diff --git a/scripts/ai-accounts/ai-accounts b/scripts/ai-accounts/ai-accounts index bf9d96d1..5c4c901d 100755 --- a/scripts/ai-accounts/ai-accounts +++ b/scripts/ai-accounts/ai-accounts @@ -56,8 +56,10 @@ import os import re import shutil import signal +import stat import subprocess import sys +import tempfile import threading import time import urllib.error @@ -115,11 +117,14 @@ def notify(msg: str) -> None: def write_private(path: Path, text: str) -> None: path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) - tmp = path.with_name(f"{path.name}.{os.getpid()}.{threading.get_ident()}.tmp") - fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) - with os.fdopen(fd, "w", encoding="utf-8") as fh: - fh.write(text) - os.replace(tmp, path) + fd, staged = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) + try: + with os.fdopen(fd, "w", encoding="utf-8") as fh: + fh.write(text) + os.replace(staged, path) + except BaseException: + Path(staged).unlink(missing_ok=True) + raise # ----------------------------------------------------------------- accounts @@ -171,7 +176,10 @@ class AccountLockTimeout(TimeoutError): @contextmanager def _locked(name: str): - with (STATE / name).open("a") as lock: + fd = os.open(STATE / name, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600) + with os.fdopen(fd, "rb") as lock: + if not stat.S_ISREG(os.fstat(lock.fileno()).st_mode): + raise ValueError(f"{name} is not a regular lock file") deadline = time.monotonic() + 60 while (remaining := deadline - time.monotonic()) > 0: try: diff --git a/tests/test_ai_accounts.py b/tests/test_ai_accounts.py index 82041ff8..c161c052 100644 --- a/tests/test_ai_accounts.py +++ b/tests/test_ai_accounts.py @@ -570,3 +570,26 @@ def open_(*args, **kwargs): monkeypatch.setattr(helper.urllib.request, "urlopen", open_) with pytest.raises(TimeoutError, match="provider HTTP request timed out"): helper._http(request, timeout=1) + + +@pytest.mark.parametrize("symlink", [False, True]) +def test_account_staging_preserves_colliding_path(helper, tmp_path, symlink): + path = helper.STATE / "status.json" + staged = path.with_name(f"{path.name}.{helper.os.getpid()}.{helper.threading.get_ident()}.tmp") + target = tmp_path / "unrelated" if symlink else staged + target.write_text("preserve") + if symlink: + staged.symlink_to(target) + helper.write_private(path, "{}") + assert path.read_text() == "{}" and target.read_text() == "preserve" + + +def test_account_lock_preserves_existing_file_and_rejects_symlink(helper): + lock = helper.STATE / ".lock" + lock.write_text("preserve") + with helper._locked(lock.name): + assert lock.read_text() == "preserve" + (helper.STATE / ".codex-sync.lock").symlink_to(lock) + with pytest.raises(OSError), helper._locked(".codex-sync.lock"): + pytest.fail("redirected lock opened") + assert lock.read_text() == "preserve"