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
2 changes: 2 additions & 0 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,8 @@ candidate attestation. The caller rechecks the source fields that affect the
verdict before publication. Standalone evaluation performs its own PR reads.
[Mergify](MERGIFY.md) describes optional source-preserving queue integration;
[candidate validation](../src/loopzero/candidate.py) belongs at that boundary.
Hosted attestation uses the trusted workflow's base branch for candidate and
source targets, queue status and integration tree verification.
When delivery uses the existing size checker, local readiness and new Mergify
requests evaluate a temporary integration with the freshly fetched target. The
target supplies the checker and baseline. Existing requests continue to the
Expand Down
34 changes: 34 additions & 0 deletions scripts/ai-accounts/ai-accounts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ from __future__ import annotations
import argparse
import base64
import datetime as dt
import errno
from email.utils import parsedate_to_datetime
import fcntl
import hashlib
Expand Down Expand Up @@ -200,6 +201,35 @@ 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

# 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:
staged = Path(directory) / entry.name
is_directory = entry.is_dir()
if is_directory:
shutil.copytree(entry, staged, symlinks=True)
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)
if is_directory:
shutil.rmtree(entry)
else:
entry.unlink()


def _sync_codex_home(home: Path) -> None:
"""Mirror shared Codex files while holding the home lock."""
for entry in home.iterdir():
Expand All @@ -210,6 +240,10 @@ def _sync_codex_home(home: Path) -> None:
os.rename(entry, target)
except FileNotFoundError:
pass
except OSError as exc:
if exc.errno != errno.EXDEV:
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
36 changes: 20 additions & 16 deletions src/loopzero/candidate.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from collections.abc import Callable, Iterator
from pathlib import Path
from typing import Any, BinaryIO
from urllib.parse import quote

MERGIFY_APP_ID = 10562
MERGIFY_APP_OWNER = "Mergifyio"
Expand Down Expand Up @@ -172,6 +173,7 @@ def _repo_identity(repo: JsonObject) -> tuple[object, object]:
def _candidate_snapshot(
candidate: JsonObject, number: int, event_head: JsonObject, repository: JsonObject,
expected_identity: tuple[object, object, object, object],
base_branch: str,
) -> None:
_require(candidate.get("number") == number, "GitHub returned the wrong candidate PR")
state = candidate.get("state")
Expand All @@ -184,7 +186,7 @@ def _candidate_snapshot(
_require(isinstance(head, dict) and isinstance(base, dict), "Candidate refs are missing")
_require(head.get("sha") == event_head.get("sha"), "Candidate head changed after the workflow event")
_require(head.get("ref") == event_head.get("ref"), "Mergify candidate has an unexpected head ref")
_require(base.get("ref") == "main", "Mergify candidate must target the real main branch")
_require(base.get("ref") == base_branch, f"Mergify candidate must target the real {base_branch} branch")
expected_repo = _repo_identity(repository)
for label, repo in (("head", head.get("repo")), ("base", base.get("repo"))):
_require(isinstance(repo, dict) and _repo_identity(repo) == expected_repo,
Expand Down Expand Up @@ -225,6 +227,7 @@ def _attest_source(
repository: JsonObject,
candidate_sha: str,
github_get: GitHubGet,
base_branch: str,
) -> str:
_require(source.get("number") == number, f"GitHub returned the wrong source PR for #{number}")
_require(
Expand All @@ -240,10 +243,10 @@ def _attest_source(
)
base_repo = base.get("repo")
_require(
base.get("ref") == "main"
base.get("ref") == base_branch
and isinstance(base_repo, dict)
and _repo_identity(base_repo) == _repo_identity(repository),
f"source PR #{number} does not target this repository's main branch",
f"source PR #{number} does not target this repository's {base_branch} branch",
)
source_sha = head.get("sha")
_require(
Expand Down Expand Up @@ -391,6 +394,7 @@ def _verify_tree(repo: str, main: str, candidate: str, sources: list[str]) -> No
def attest_candidate(
event: JsonObject,
*,
base_branch: str = "main",
github_get: GitHubGet,
mergify_status: MergifyStatus,
source_policy: SourcePolicy,
Expand All @@ -405,7 +409,7 @@ def attest_candidate(
for attempt in range(_ATTEST_ATTEMPTS):
try:
return _attest_candidate_once(
event,
event, base_branch,
github_get=github_get,
mergify_status=mergify_status,
source_policy=source_policy,
Expand All @@ -423,7 +427,7 @@ def attest_candidate(


def _attest_candidate_once(
event: JsonObject,
event: JsonObject, base_branch: str,
*,
github_get: GitHubGet,
mergify_status: MergifyStatus,
Expand Down Expand Up @@ -481,15 +485,15 @@ def _attest_candidate_once(
candidate_path = f"/repos/{full_name}/pulls/{candidate_number}"
def recheck_candidate(message: str = "GitHub candidate lookup returned an invalid payload") -> None:
candidate = _object(github_get(candidate_path), message)
_candidate_snapshot(candidate, candidate_number, event_head, repository, expected_identity)
_candidate_snapshot(candidate, candidate_number, event_head, repository, expected_identity, base_branch)

recheck_candidate()

def live_lineage() -> tuple[str, list[int], list[str]]:
delay = 2
while True:
try:
return _candidate_lineage(mergify_status(owner, repo, "main"), candidate_number)
return _candidate_lineage(mergify_status(owner, repo, base_branch), candidate_number)
except CandidateBatchError:
recheck_candidate("Invalid candidate lookup")
remaining = batch_deadline - _retry_clock()
Expand All @@ -504,8 +508,8 @@ def live_lineage() -> tuple[str, list[int], list[str]]:
delay = min(delay * 2, 30)

first_lineage = live_lineage()
main_path = f"/repos/{full_name}/git/ref/heads/main"
main_before = github_get(main_path) if first_lineage[2] else None
base_path = f"/repos/{full_name}/git/ref/heads/{quote(base_branch)}"
base_before = github_get(base_path) if first_lineage[2] else None
source_snapshots: dict[int, tuple[str, tuple[object, ...]]] = {}
for number in first_lineage[1]:
source = _lookup_source(github_get, full_name, number)
Expand All @@ -514,7 +518,7 @@ def live_lineage() -> tuple[str, list[int], list[str]]:
number=number,
repository=repository,
candidate_sha=candidate_sha,
github_get=github_get,
github_get=github_get, base_branch=base_branch,
)
source_snapshots[number] = (source_sha, _source_fingerprint(source))
try:
Expand All @@ -531,14 +535,14 @@ def live_lineage() -> tuple[str, list[int], list[str]]:

if first_lineage[2]:
try:
main_ref = _object(main_before, "main ref unavailable")
main_sha = _object(main_ref.get("object"), "main object unavailable").get("sha")
_require(isinstance(main_sha, str) and _SHA.fullmatch(main_sha) is not None, "invalid main head")
_verify_tree(full_name, main_sha, candidate_sha,
base_ref = _object(base_before, f"{base_branch} ref unavailable")
base_sha = _object(base_ref.get("object"), f"{base_branch} object unavailable").get("sha")
_require(isinstance(base_sha, str) and _SHA.fullmatch(base_sha) is not None, f"invalid {base_branch} head")
_verify_tree(full_name, base_sha, candidate_sha,
[snapshot[0] for snapshot in source_snapshots.values()])
_require(
github_get(main_path) == main_before,
"main changed during attestation",
github_get(base_path) == base_before,
f"{base_branch} changed during attestation",
CandidateRaceError,
)
except CandidateRaceError:
Expand Down
5 changes: 3 additions & 2 deletions src/loopzero/hosted.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import sys
from contextlib import suppress
from pathlib import Path
from urllib.parse import quote

from loopzero import candidate as candidate_mod
from loopzero import config, eligibility, github, mergify
Expand Down Expand Up @@ -86,10 +87,10 @@ def policy(source_number: int, source: dict) -> None:
if not result.ready:
raise _SourcePolicyRejection(f"source #{source_number}: " + "; ".join(result.reasons))
candidate_mod.attest_candidate(
event,
event, base_branch=cfg.base_branch,
github_get=lambda path: github.api_get(path.lstrip("/")),
mergify_status=lambda owner, repo, branch: mergify.api_get(
f"{owner}/{repo}", f"/merge-queue/status?branch={branch}"),
f"{owner}/{repo}", f"/merge-queue/status?branch={quote(branch, safe='')}"),
source_policy=policy,
)
ready, message = True, "All attested candidate sources are reviewed"
Expand Down
25 changes: 25 additions & 0 deletions tests/test_ai_accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import importlib.machinery
import importlib.util
import json
import tempfile
from concurrent.futures import ThreadPoolExecutor
from io import BytesIO
from pathlib import Path
Expand Down Expand Up @@ -593,3 +594,27 @@ 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"


@pytest.mark.parametrize("outcome", ["published", "copy failed"])
def test_account_env_moves_shared_entry_across_devices(helper, monkeypatch, outcome):
if not Path("/dev/shm").is_dir() or Path("/dev/shm").stat().st_dev == helper.STATE.stat().st_dev:
pytest.skip("requires two filesystems")
entry = helper.codex_home("extra") / "session-index.jsonl"
helper.write_private(entry, "original")
helper.write_private(entry.with_name("auth.json"), "{}")
copy = helper.shutil.copy2
with tempfile.TemporaryDirectory(dir="/dev/shm") as main:
monkeypatch.setattr(helper, "CODEX_MAIN", Path(main))
def stage(src, dst, **kwargs):
copy(src, dst, **kwargs)
if outcome == "copy failed":
raise OSError("copy interrupted")
monkeypatch.setattr(helper.shutil, "copy2", stage)
if outcome == "copy failed":
with pytest.raises(OSError, match="copy interrupted"):
helper.account_env("codex", "extra")
else:
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])
14 changes: 10 additions & 4 deletions tests/test_candidate.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ def isolated_fetch(argv, **kwargs):
def attest(
*, head=candidate_sha, main_head=main, policy=lambda _n, _s: None,
main_after=None, extra_source=None, lineage="vanished", run=attest_candidate,
held_source=None,
held_source=None, base_branch="main",
):
candidate_event = event(head)
values = payloads(candidate_event)
Expand All @@ -286,23 +286,29 @@ def attest(
)
for endpoint in ("commits", "files"):
values[f"/repos/owner/repo/pulls/{number}/{endpoint}?per_page=100&page=1"] = []
if base_branch != "main":
for number in (102, 900):
values[f"/repos/owner/repo/pulls/{number}"]["base"]["ref"] = base_branch
reads = cycle([main_head, main_after or main_head])

def get(path):
if not path.endswith("/git/ref/heads/main"):
if not path.endswith(f"/git/ref/heads/{base_branch}"):
return deepcopy(values[path])
return {"object": {"sha": sha}} if (sha := next(reads)) else {}

if base_branch != "main":
run = partial(run, base_branch=base_branch)
return run_attestation(candidate_event, github_get=get, status_reads=[queue],
source_policy=policy, run=run)

return attest, git, commit, base, parent, source, candidate_sha


def test_vanished_squash_parent_passes_real_tree_attestation(tree_candidate):
@pytest.mark.parametrize("base_branch", ["main", "trunk"])
def test_vanished_squash_parent_passes_real_tree_attestation(tree_candidate, base_branch):
attest, _, _, _, _, source, _ = tree_candidate
seen = []
assert attest(policy=lambda n, _: seen.append(n)) == expected_sources((102, source))
assert attest(base_branch=base_branch, policy=lambda n, _: seen.append(n)) == expected_sources((102, source))
assert seen == [102]


Expand Down
17 changes: 11 additions & 6 deletions tests/test_hosted.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, ca


@pytest.mark.parametrize("case,error,message", [
("valid", None, ""), ("policy", hosted.LoopZeroError, "no review recorded"),
("valid", None, ""), ("trunk", None, ""), ("policy", hosted.LoopZeroError, "no review recorded"),
("hold", hosted.LoopZeroError, "source #101: PR #101 has a merge-authority hold"),
("race", CandidateRaceError, "metadata changed"),
("malformed", CandidateError, "invalid payload"),
Expand All @@ -263,8 +263,9 @@ def test_candidate_publication_and_event_controls(tmp_path, fake_bin, monkeypatc
event = candidate_event()
event["action"], event["sender"]["id"] = (
"edited" if case == "metadata" else event["action"], 1 if case == "untrusted" else event["sender"]["id"])
branch = "trunk" if case == "trunk" else "main"
values = candidate_payloads(event)
if case in {"valid", "hold"}:
if case in {"valid", "trunk", "hold"}:
gh = FakeGh(fake_bin, tmp_path)
gh.respond("api graphql", threads_json())
for number, sha in [(101, "1" * 40), (102, "2" * 40), (900, "c" * 40)]:
Expand All @@ -273,12 +274,16 @@ def test_candidate_publication_and_event_controls(tmp_path, fake_bin, monkeypatc
number=number, headRefOid=sha, isDraft=False,
labels=[{"name": "hold"}] if case == "hold" and number == 101 else [],
)) | values[path]
values[path]["base"]["ref"] = branch
values[f"{path}/reviews?per_page=100&page=1"] = [approval(sha)]
if case == "stale":
values["/repos/owner/repo/pulls/900"]["head"]["sha"] = "d" * 40
if case == "malformed":
values["/repos/owner/repo/pulls/101"] = []
prepare_event(tmp_path, monkeypatch, "owner/repo", {"inputs": {"pr": "900"}} if case == "manual" else event)
if case == "trunk":
workflow = Path("workflow.toml")
workflow.write_text(workflow.read_text().replace('base="main"', 'base="trunk"'))
rest_calls, sleeps = [], []

def api_get(path):
Expand All @@ -300,23 +305,23 @@ def publish(*args):

def evaluate(repo, number, head, base, publishers, *, snapshot):
evaluated.append((repo, number, head, base, publishers))
if case in {"valid", "hold"}:
if case in {"valid", "trunk", "hold"}:
return real_evaluate(repo, number, head, base, publishers, snapshot=snapshot)
if fault := {"interrupt": KeyboardInterrupt(), "api": github.GhUnavailable(("gh",), "HTTP 503")}.get(case):
raise fault
reasons = (github.MISSING_REVIEW_REASON,) if case == "policy" else ()
return github.Readiness(not reasons, reasons)
if case not in {"valid", "hold"}:
if case not in {"valid", "trunk", "hold"}:
monkeypatch.setattr(github, "pr_view", lambda *_: SimpleNamespace(head_sha=("d" if case == "head" else "c") * 40))
monkeypatch.setattr(hosted.eligibility, "evaluate", evaluate)
monkeypatch.setattr("loopzero.mergify.api_get", lambda repo, suffix: candidate_status()
if (repo, suffix) == ("owner/repo", "/merge-queue/status?branch=main") else None)
if (repo, suffix) == ("owner/repo", f"/merge-queue/status?branch={branch}") else None)
if error:
with pytest.raises(error, match=message or None):
hosted.main()
else:
assert hosted.main() == 0
states = {"valid": ["pending", "success"], "interrupt": ["pending"], "api": ["pending"],
states = {"valid": ["pending", "success"], "trunk": ["pending", "success"], "interrupt": ["pending"], "api": ["pending"],
"manual": [], "metadata": [], "stale": []}
assert [call[3] for call in published] == states.get(case, ["pending", "failure"])
assert all(call[:3] == ("owner/repo", "c" * 40, "Loop-zero Eligibility") for call in published)
Expand Down
Loading