From 717403809eddedb679d9fc0063f2d514ab7cc5d3 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:39:34 +0100 Subject: [PATCH 1/3] Preserve passing receipts across late check checkpoints Architecture-Review: document which completed receipts a checkpoint may replace. Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 5 +++-- src/loopzero/cli.py | 9 +++++++-- tests/test_cli.py | 20 ++++++++++++++++++++ 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index bfe286f2..9e50b205 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -481,8 +481,9 @@ stage is retried after success or uncertain launch. Only the coordinator writes the authoritative `checks.json` receipt. Writers lock the task state directory while rechecking HEAD and atomically replacing the receipt from a synced sibling temporary file. Successful keyed stages are checkpointed in the same receipt -for reuse. The checkpoint cannot satisfy readiness before final worktree -validation. Runners cannot select stages or mint receipts. Stage admission +for reuse. A checkpoint cannot replace a clean pass for the same head and +settings or satisfy readiness before final worktree validation. Completed +failures still replace passes. Runners cannot select stages or mint receipts. Stage admission belongs to the runner: the outer `loopzero check` must not hold a heavy slot when a runner is configured. Without a runner, the existing local execution path is unchanged. diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 46a93e29..1cf1b68b 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -359,7 +359,7 @@ def _lock_task_state(wt: Path) -> Iterator[None]: os.close(fd) -def _save_report(wt: Path, report: CheckReport) -> str | None: +def _save_report(wt: Path, report: CheckReport, *, checkpoint_checks: tuple[str, ...] | None = None) -> str | None: """Publish the receipt or return the current HEAD if the result is stale.""" path = wt / CHECKS_FILE payload = { @@ -375,6 +375,11 @@ def _save_report(wt: Path, report: CheckReport) -> str | None: current_head = worktree.head(wt) if report.head != current_head: return current_head + saved = _load_report(wt) if checkpoint_checks is not None else None + if (saved is not None and saved.ok and not saved.dirty and saved.head == report.head + and saved.settings_sha256 == report.settings_sha256 + and tuple(result.command for result in saved.results) == checkpoint_checks): + return None _write_json_atomically(path, payload) return None @@ -598,7 +603,7 @@ def cmd_check(args: argparse.Namespace) -> int: report = sandbox.run_checks(config, wt, progress=lambda command: print( f"running: {command}", flush=True), status=lambda message: print(message, flush=True), - checkpoint=lambda partial: _save_report(wt, partial)) + checkpoint=lambda partial: _save_report(wt, partial, checkpoint_checks=config.checks)) except sandbox.SandboxUnavailable as exc: print(f"sandbox unavailable: {exc}", file=sys.stderr) return 2 diff --git a/tests/test_cli.py b/tests/test_cli.py index 3421662b..037c073b 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -10,6 +10,7 @@ import subprocess import sys from dataclasses import replace +from functools import partial from pathlib import Path from types import SimpleNamespace from unittest.mock import Mock @@ -4763,3 +4764,22 @@ def test_pr_marks_legacy_same_head_check_unverified(wt, gh, capsys): assert "unverified" not in draft assert f"Recorded for `{head[:12]}`\n- `echo ok`: exit 0" in draft assert "Manual validation evidence." in draft + + +def test_late_checkpoint_preserves_completed_pass(wt, head): + cfg = config.load(wt / "workflow.toml") + passed = CheckReport(head, False, tuple(CheckResult(c, 0, 0, "", input_key="key") for c in cfg.checks), + cli.sandbox.settings_fingerprint(cfg, wt)) + save = partial(cli._save_report, wt) + checkpoint = cli.sandbox._checkpoint_success + checkpoint(partial(save, checkpoint_checks=cfg.checks), passed, {}, ()) + assert cli._load_report(wt).results[0].input_key == "key" + save(passed) + checkpoint(partial(save, checkpoint_checks=cfg.checks), passed, {}, ()) + assert cli._current_check_report(wt, cfg, head) == passed + failed = replace(passed, results=(replace(passed.results[0], exit_code=1),)) + save(failed) + assert cli._load_report(wt) == failed + save(passed) + checkpoint(partial(save, checkpoint_checks=cfg.checks[:1]), replace(passed, results=passed.results[:1]), {}, ()) + assert not cli._load_report(wt).ok From ea129f83d3822317bfd277834f4385eab004bb58 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:26:44 +0100 Subject: [PATCH 2/3] Use GitHub timestamps for readiness waits Co-Authored-By: Codex Architecture-Review: unchanged; readiness still relies on GitHub evidence and its existing check gates. --- docs/ARCHITECTURE.md | 6 +- src/loopzero/cli.py | 28 ++++----- src/loopzero/github.py | 57 +++++++++++------- tests/test_cli.py | 130 ++++++++++++++++++++--------------------- 4 files changed, 119 insertions(+), 102 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 6d63539f..0f29e6f3 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -120,8 +120,10 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con 5. `ready` derives readiness from the current head, its check receipt, an eligible review at that head or an eligible review covering an ancestor, blocking findings (unresolved threads a review publisher opened with a head-bound marker line), - target branch and required CI. The receipt must record a clean passing run - at that head with the current commands and check settings digest. A settings + target branch and required CI. Readiness compares parsed instants for verdict + freshness and uses the GitHub review response Date during waits when valid. + The receipt must record a clean passing run at that head with the current + commands and check settings digest. A settings change or an older receipt without the digest requires a fresh check. The digest covers execution and stage reuse settings without recording raw environment values. For local sandbox receipts it omits inherited `PATH`, diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index ccf5cdd5..b2222b97 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -21,7 +21,6 @@ import tempfile import time from collections.abc import Callable, Iterator -from datetime import UTC, datetime from functools import partial, wraps from pathlib import Path @@ -198,11 +197,11 @@ def _require_pushed(pr: github.PR, head: str) -> None: # --------------------------------------------------------------------------- review markers -def _rest_rows(endpoint: str, what: str) -> list[dict]: +def _rest_rows(endpoint: str, what: str, **kwargs) -> list[dict]: """Every row of a REST list, oldest first, following pages until a short one.""" rows: list[dict] = [] for page in range(1, 101): - batch = github.api_get(f"{endpoint}?per_page={github.PAGE}&page={page}") + batch = github.api_get(f"{endpoint}?per_page={github.PAGE}&page={page}", **kwargs) if not isinstance(batch, list) or not all(isinstance(row, dict) for row in batch): raise CliError(f"invalid GitHub {what} response") rows += batch @@ -211,8 +210,8 @@ def _rest_rows(endpoint: str, what: str) -> list[dict]: raise CliError(f"GitHub {what} pagination limit exceeded") -def _pr_reviews(repo: str, number: int) -> list[dict]: - return _rest_rows(f"repos/{repo}/pulls/{number}/reviews", "reviews") +def _pr_reviews(repo: str, number: int, **kwargs) -> list[dict]: + return _rest_rows(f"repos/{repo}/pulls/{number}/reviews", "reviews", **kwargs) @dataclasses.dataclass(frozen=True) @@ -310,26 +309,29 @@ def _readiness( ) -> github.Readiness: if hold := github.merge_hold(pr.number, pr.labels): return github.Readiness(False, (hold,)) - if reviews is None: - reviews = _pr_reviews(config.repo, pr.number) + dates: list[str] = [] + reviews = (_pr_reviews(config.repo, pr.number, **({"dates": dates} if workflow_wait else {})) + if reviews is None else reviews) publishers = config.review_publishers or (github.login(),) review = eligibility.readiness_review( reviews, head, publishers, repo=config.repo, number=pr.number, base_branch=config.base_branch, ) - review_at = review.get("submitted_at") if review else None - # GitHub's review timestamp is in UTC and predates this process. - review_age = (time.time() - datetime.strptime(review_at, "%Y-%m-%dT%H:%M:%SZ") - .replace(tzinfo=UTC).timestamp()) if review_at else None + review_at = github.readiness_timestamp(review.get("submitted_at")) if review else None + server = github.response_date(dates[-1]) if dates else None + now = server.timestamp() if server else time.time() + review_age = now - review_at[0].timestamp() if review_at else None + if server and review_age is not None and -1 < review_age < 0: + review_age = 0 # HTTP Date rounds down to the second. result = github.readiness( config.repo, pr, config.base_branch, config.required_ci, head if review else None, review_at=review_at, ancestor_review=review is not None and review["commit_id"] != head, review_grace=review_age is not None and 0 <= review_age < MISSING_RUN_GRACE, workflow_wait=workflow_wait, - # Allow skew only for verdicts GitHub timestamps establish are stale. + # Allow host clock skew only when GitHub did not supply a usable Date. stale_verdict_grace=( workflow_wait and review_age is not None - and -MAX_REVIEW_CLOCK_SKEW <= review_age < STALE_VERDICT_GRACE + and (0 if server else -MAX_REVIEW_CLOCK_SKEW) <= review_age < STALE_VERDICT_GRACE ), publishers=publishers, ) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index b5489684..501b43a1 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -128,6 +128,9 @@ class Readiness: _read_scope: ContextVar[tuple[float, str | None, bool] | None] = ContextVar("github_reads", default=None) _api_error_diagnostics: ContextVar[bool] = ContextVar("github_api_error_diagnostics", default=False) _HTTP_STATUS_RE = re.compile(r"^HTTP/\S+\s+(\d{3})(?:\s+(.*))?$", re.IGNORECASE) +_READINESS_TIMESTAMP = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.([0-9]+))?" + r"(?:Z|[+-](?:[01][0-9]|2[0-3]):[0-5][0-9])") +_HTTP_DATE = re.compile(r"[A-Za-z]{3}, [0-9]{2} [A-Za-z]{3} [0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2} GMT") _CREDENTIAL_TOKEN_RE = re.compile( r"\b(?:github_pat_[A-Za-z0-9_]+\b|gh[pousr]_[A-Za-z0-9_]{10,}\b|sk-[A-Za-z0-9_-]{8,})" ) @@ -354,7 +357,8 @@ def _pr_list_error_guidance(args: tuple[str, ...], stderr: str, using_app: bool) def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, - token: str | None = None, retry_idempotent: bool = False) -> str: + token: str | None = None, retry_idempotent: bool = False, dates: list[str] | None = None) -> str: + dates = [] if dates is None else dates api = args[:1] == ("api",) diagnostic_api = api and _api_error_diagnostics.get() rest_api = api and args[:2] != ("api", "graphql") @@ -387,6 +391,7 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, status, headers, body = response tail = "\n".join(part for part in (done.stderr, body) if part) if done.exit_code == 0: + dates[:] = [headers.get("date", "")] return body rate_limited = _rate_limited(status, headers, tail) transient = rate_limited or _transient_error(tail, retry_idempotent, status) @@ -416,9 +421,7 @@ def _rest_rate_limit(headers: dict[str, str]) -> str: remaining = int(remaining_value) if re.fullmatch(r"[0-9]{1,18}", remaining_value) else None retry_after = headers.get("retry-after", "") retry_seconds = re.fullmatch(r"[0-9]{1,18}", retry_after) - retry_date = re.fullmatch( - r"[A-Za-z]{3}, [0-9]{2} [A-Za-z]{3} [0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2} GMT", retry_after, - ) + retry_date = _HTTP_DATE.fullmatch(retry_after) reset = "" try: if epoch := headers.get("x-ratelimit-reset"): @@ -479,8 +482,8 @@ def _graphql_reset(args: tuple[str, ...], tail: str, cwd: Path, token: str = "") return "" -def _gh_json(*args: str, token: str | None = None) -> object: - out = _gh(*args, token=token) +def _gh_json(*args: str, token: str | None = None, **kwargs) -> object: + out = _gh(*args, token=token, **kwargs) try: return json.loads(out) if out.strip() else None except json.JSONDecodeError as exc: @@ -518,9 +521,16 @@ def _paged(endpoint: str, key: str = "check_runs") -> list: return list(_iter_paged(endpoint, key)) -def api_get(endpoint: str) -> object: +def api_get(endpoint: str, **kwargs) -> object: """`gh api ` parsed as JSON (None on an empty body).""" - return _gh_json("api", endpoint) + return _gh_json("api", endpoint, **kwargs) + + +def response_date(value: str) -> datetime | None: + if _HTTP_DATE.fullmatch(value): + with suppress(OverflowError, ValueError): + return parsedate_to_datetime(value) + return None def auth_token() -> str: @@ -1179,34 +1189,41 @@ def _review_threads(repo: str, number: int, *, include_resolved: bool = False) - _FAILED_VERDICTS = {"failure", "error", "cancelled", "timed_out"} +ReadinessTimestamp = tuple[datetime, str] + + +def readiness_timestamp(value: object) -> ReadinessTimestamp | None: + if isinstance(value, str) and (match := _READINESS_TIMESTAMP.fullmatch(value)): + with suppress(OverflowError, ValueError): + return datetime.fromisoformat(value).astimezone(UTC), (match[1] or "")[6:].rstrip("0") + return None + + def _check_signals( repo: str, head_sha: str, - review_at: str | None = None, + review_at: ReadinessTimestamp | None = None, review_grace: bool = False, required_ci: tuple[str, ...] = (), stale_verdict_grace: bool = False, ) -> tuple[dict[str, str], tuple[str, ...], tuple[str, ...], bool]: + signals: dict[str, list[tuple[str, ReadinessTimestamp | None]]] = {} latest_runs: dict[str, dict] = {} runs = _paged(f"repos/{repo}/commits/{head_sha}/check-runs") for cr in runs: previous = latest_runs.get(cr["name"]) if previous is None or _check_run_order(cr) > _check_run_order(previous): latest_runs[cr["name"]] = cr - signals = { - name: [(cr.get("conclusion") or cr.get("status") or "unknown", - cr.get("completed_at") or cr.get("started_at"))] - for name, cr in latest_runs.items() - } + for name, cr in latest_runs.items(): + state = cr.get("conclusion") or cr.get("status") or "unknown" + timestamp = cr.get("started_at" if state in _PENDING_CHECKS else "completed_at") + signals[name] = [(state, readiness_timestamp(timestamp))] latest_status: dict[str, dict] = {} for status in _paged(f"repos/{repo}/commits/{head_sha}/statuses"): latest_status.setdefault(status["context"], status) for name, status in latest_status.items(): - signals.setdefault(name, []).append((status.get("state") or "unknown", status.get("created_at"))) - states = { - name: _aggregate_signal([state for state, _ in values]) - for name, values in signals.items() - } + signals.setdefault(name, []).append((status.get("state") or "unknown", readiness_timestamp(status.get("created_at")))) + states = {name: _aggregate_signal([state for state, _ in values]) for name, values in signals.items()} stale = tuple(name for name, values in signals.items() if review_at and states[name] not in _NONFAILING_CHECKS and all(at and at < review_at for state, at in values if state not in _NONFAILING_CHECKS) @@ -1310,7 +1327,7 @@ def readiness( required_ci: tuple[str, ...], reviewed_head: str | None, *, allow_behind: bool = False, ancestor_review: bool = False, - review_at: str | None = None, + review_at: ReadinessTimestamp | None = None, review_grace: bool = False, workflow_wait: bool = False, stale_verdict_grace: bool = False, diff --git a/tests/test_cli.py b/tests/test_cli.py index a0d4d6ee..5c011ea0 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -13,6 +13,7 @@ import sys from contextlib import suppress from dataclasses import asdict, replace +from email.utils import formatdate from pathlib import Path from select import select from types import SimpleNamespace @@ -2509,26 +2510,17 @@ def test_ready_explains_trusted_policy_blocker(wt, gh, capsys, head, retargeted, assert without_accepted_receipt(out) == f"not ready: {reason}\n" -def test_pending_required_check_names_the_wait(wt: Path, gh: FakeGh, capsys, head) -> None: +@pytest.mark.parametrize("command", ["ready", "merge"]) +def test_pending_required_check_names_the_wait(wt, gh, capsys, head, command): arm_approved_ready_pr(gh, head, wt, isDraft=False) arm_check_runs(gh, head, [{"name": "checks", "status": "in_progress"}]) - - code, out, err = run(capsys, "ready") - + out, err = expect_cli(capsys, 1, command) out = without_accepted_receipt(out) - assert (code, err) == (1, "") - assert out.splitlines() == [ - "not ready: required check 'checks' is pending", - "next: loopzero ready --wait", - ] - - arm_pr(gh, head, isDraft=False) - arm_readiness(gh, head, wt) - arm_check_runs(gh, head, [{"name": "checks", "status": "in_progress"}]) - code, out, err = run(capsys, "merge") - - assert (code, without_accepted_receipt(out)) == (1, "") - assert "required check 'checks' is pending; next: loopzero merge --wait" in err + reason = "required check 'checks' is pending" + if command == "ready": + assert out == f"not ready: {reason}\nnext: loopzero ready --wait\n" and err == "" + else: + assert out == "" and f"{reason}; next: loopzero merge --wait" in err @pytest.mark.parametrize("draft", [True, False]) @@ -2958,51 +2950,57 @@ def test_ready_transition_immediate_green_is_best_effort(wt, gh, capsys, head, w @pytest.mark.parametrize("name", ["checks", "Loop-zero Eligibility"]) @pytest.mark.parametrize("pending,age,new_failure,wait,expected,waited", [ (True, 180, False, True, 0, True), - (False, 30, False, True, 0, True), - (False, -30, False, True, 0, True), - (False, -3600, False, True, 1, False), + *[(False, age, False, True, 0, True) for age in (-30, 30, 119, 120, 300, 899)], + *[(False, age, False, True, 1, False) for age in (-3600, 900, 901)], (False, -30, True, True, 1, False), (False, -30, "tie", True, 1, False), (True, 30, True, True, 1, True), (False, 30, True, True, 0, True), - (False, 120, False, True, 0, True), - (False, 119, False, True, 0, True), - (False, 300, False, True, 0, True), - (False, 899, False, True, 0, True), - (False, 900, False, True, 1, False), - (False, 901, False, True, 1, False), - (False, 300, True, True, 1, False), - (True, 300, True, True, 1, False), - (False, 300, "tie", True, 1, False), + *[(pending, 300, True, True, 1, False) for pending in (False, True)], + *[(False, 300, failure, True, 1, False) for failure in ("tie", "missing")], (False, 300, False, False, 1, False), - (False, 300, "missing", True, 1, False), + *[(False, 180, failure, True, 1, False) for failure in + ("missing", "fractional-newer", "offset-tie", "naive-check", "malformed-check")], + (False, 180, "offset-older", True, 0, True), + *[(False, 5, failure, True, 1, False) for failure in ("naive-review", "malformed-review", "missing-review")], + *[(False, 5, sample, True, 0, True) for sample in + ("server-synced", "server-host-behind", "server-host-ahead", "invalid-date", "fractional-review")], + (False, 900, "server-old-review", True, 1, False), ]) def test_ready_wait_review_failure_freshness( - wt, gh, capsys, monkeypatch, name, pending, age, new_failure, wait, expected, waited, head, replay_gh, -): + wt: Path, gh: FakeGh, capsys, monkeypatch, name, pending, age, new_failure, wait, expected, waited, head, + replay_gh, +) -> None: (wt / "workflow.toml").write_text(WORKFLOW.replace('["checks"]', json.dumps([name]))) - arm_approved_pr_with_check_result( - gh, - head, - wt, - "success", - reviews=[rev(head, "primary") | {"submitted_at": "2026-09-23T12:00:00Z"}], - isDraft=False, - ) - epoch = 1790164800 + age # 2026-09-23T12:00:00Z plus review age - failed_at = { - "tie": "2026-09-23T12:00:00Z", - "missing": None, - }.get( - new_failure, - "2026-09-23T12:00:10Z" if new_failure else "2026-09-23T11:59:00Z", - ) - active_at = "2026-09-23T12:00:20Z" + current, earlier = "12:00:00Z", "11:59:59Z" + review_time, failure_time = { + True: (current, "12:00:10Z"), "tie": (current, current), "missing": (current, None), + "fractional-review": ("12:00:00.1234569Z", "12:00:00.1234561Z"), + "fractional-newer": (current, "12:00:00.250Z"), + "offset-tie": ("12:00:00+00:00", "11:00:00-01:00"), + "offset-older": ("13:00:00+01:00", "13:59:59+02:00"), + "naive-check": (current, "11:59:00"), "malformed-check": (current, "12:00:00+00:60"), + "naive-review": ("12:00:00", earlier), "malformed-review": ("bad", earlier), + "missing-review": (None, earlier), + }.get(new_failure, (current, earlier)) + review_at, failed_at = (f"2026-09-23T{value}" if value else None for value in (review_time, failure_time)) + reviews = [rev(head, "primary") | {"submitted_at": review_at}] + arm_approved_pr_with_check_result(gh, head, wt, "success", reviews=reviews, isDraft=False) + server_now = 1790164800 + age + server_timeline = str(new_failure).startswith("server-") + if server_timeline or new_failure == "invalid-date": + date = (formatdate(server_now, usegmt=True) if server_timeline + else "Wed, 23 Sep 2026 12:00:05 +0060") + gh.respond(reviews_key(), f"HTTP/2 200 OK\nDate: {date}\n\n{json.dumps(reviews)}") + offsets = {"server-host-behind": -40, "server-host-ahead": 1000, "server-old-review": -40} + start = server_now + offsets.get(new_failure, 0) + pending_at = "2026-09-23T12:00:20Z" if name == "checks": - runs = [{"name": name, "status": "completed", "conclusion": "failure", "completed_at": failed_at}] - statuses = [{"context": name, "state": "pending", "created_at": active_at}] if pending else [] + runs = [{"name": name, "conclusion": "failure", "status": "completed", + "completed_at": failed_at, "started_at": "2026-09-23T11:59:59Z"}] + statuses = [{"context": name, "state": "pending", "created_at": pending_at}] if pending else [] else: - runs = [{"name": name, "status": "in_progress", "started_at": active_at}] if pending else [] + runs = [{"name": name, "status": "in_progress", "started_at": pending_at}] if pending else [] statuses = [{"context": name, "state": "failure", "created_at": failed_at}] arm_check_runs(gh, head, runs) status_key = f"api repos/{REPO}/commits/{head}/statuses" @@ -3014,10 +3012,13 @@ def advance(): gh.respond(status_key, [{"context": name, "state": "success"}]) clock = poll_clock(monkeypatch, after_sleep=advance) - monkeypatch.setattr(cli.time, "time", lambda: epoch + clock.now) - wait_args = ["--wait=60" if age < 0 else "--wait"] if wait else [] - out, _ = expect_cli(capsys, expected, "--config", "workflow.toml", "ready", *wait_args, stderr="") - assert bool(clock.sleeps) == waited + monkeypatch.setattr(cli.time, "time", lambda: start + clock.now) + wait_flag = "--wait=10" if server_timeline else "--wait=60" if age < 0 else "--wait" + out, _ = expect_cli(capsys, expected, "--config", "workflow.toml", "ready", + *([wait_flag] if wait else []), stderr="") + assert bool(clock.sleeps) is waited + if server_timeline and waited: + assert clock.sleeps == [9.0] assert out.endswith(f"ready: {URL}\n" if expected == 0 else f"not ready: required check '{name}' is failure{FAILED_CHECK_HINT}\n") assert (f"waiting: required check '{name}' is failure" in out) == waited @@ -3026,20 +3027,15 @@ def advance(): ) -def test_ready_wait_stops_if_pr_head_moves(wt: Path, gh: FakeGh, capsys, monkeypatch, head) -> None: - body = "# T1\n\n## Review\n" - gh.respond_pr_list([pr_json(headRefOid=head, body=body, isDraft=False)], - [pr_json(headRefOid="f" * 40, body=body, isDraft=False)]) - gh.respond_pr_view( pr_json(headRefOid="f" * 40, body=body, isDraft=False)) +def test_ready_wait_stops_if_pr_head_moves(wt, gh, capsys, monkeypatch, head): + moved = "f" * 40 + gh.respond_pr_list([pr_json(headRefOid=head, isDraft=False)], [pr_json(headRefOid=moved, isDraft=False)]) + gh.respond_pr_view(pr_json(headRefOid=moved, isDraft=False)) gh.respond(reviews_key(), [rev(head, "primary")]) arm_readiness(gh, head, wt, conclusion="pending") - monkeypatch.setattr(cli, "_sleep", lambda _: None) - code, out, err = run(capsys, "ready", "--wait") - - out = without_accepted_receipt(out) - assert code == 1 and "waiting:" in out - assert f"PR head changed while waiting: {head[:12]} to {'f' * 12}" in err + expect_cli(capsys, 1, "ready", "--wait", stdout_contains=("waiting:",), + stderr_contains=(f"PR head changed while waiting: {head[:12]} to {moved[:12]}",)) @pytest.mark.parametrize("running", [False, True], ids=["missing-ci", "late-required-job"]) From 0661d58486e6f03368638348a87c6071ff28f767 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:59:26 +0100 Subject: [PATCH 3/3] Reuse candidate validation and simplify hosted publication guards Architecture-Review: unchanged; hosted dispatch and candidate attestation preserve their trust boundaries, checks, and call ordering. Co-Authored-By: Codex --- src/loopzero/candidate.py | 82 +++++++++++++-------------------------- src/loopzero/hosted.py | 15 ++++--- 2 files changed, 33 insertions(+), 64 deletions(-) diff --git a/src/loopzero/candidate.py b/src/loopzero/candidate.py index 38a68c8a..7df6024b 100644 --- a/src/loopzero/candidate.py +++ b/src/loopzero/candidate.py @@ -85,30 +85,26 @@ def _identity(actor: object) -> tuple[object, object, object, object]: return actor.get("id"), actor.get("login"), actor.get("type"), actor.get("html_url") -def _object(value: JsonValue, message: str) -> JsonObject: +def _object(value: object, message: str) -> JsonObject: _require(isinstance(value, dict), message) return value def flatten_batches(status: object) -> dict[str, JsonObject]: - _require(isinstance(status, dict), "Mergify status is not an object") - batches = status.get("batches") + batches = _object(status, "Mergify status is not an object").get("batches") _require(isinstance(batches, list), "Mergify status has no batches list") indexed: dict[str, JsonObject] = {} def visit(items: list[object]) -> None: for item in items: - _require(isinstance(item, dict), "Mergify status contains an invalid batch") + item = _object(item, "Mergify status contains an invalid batch") batch_id = item.get("id") _require(isinstance(batch_id, str) and batch_id, "Mergify batch has no id") _require(batch_id not in indexed, f"Mergify batch id is duplicated: {batch_id}") indexed[batch_id] = item children = item.get("sub_batches") if children is not None: - _require( - isinstance(children, list), - f"Mergify batch {batch_id} has invalid sub_batches", - ) + _require(isinstance(children, list), f"Mergify batch {batch_id} has invalid sub_batches") visit(children) visit(batches) @@ -117,17 +113,11 @@ def visit(items: list[object]) -> None: def _candidate_lineage(status: JsonObject, candidate_number: int) -> tuple[str, list[int], list[str]]: indexed = flatten_batches(status) - matches = [ - batch - for batch in indexed.values() - if batch.get("queue_pull_request_number") == candidate_number - ] - _require( - len(matches) == 1, - f"PR #{candidate_number} is not exactly one live Mergify batch", - CandidateBatchError, - ) - candidate_id = matches[0]["id"] + matches = [batch_id for batch_id, batch in indexed.items() + if batch.get("queue_pull_request_number") == candidate_number] + _require(len(matches) == 1, f"PR #{candidate_number} is not exactly one live Mergify batch", + CandidateBatchError) + candidate_id = matches[0] pending, visited = [candidate_id], set() source_numbers, missing = [], [] while pending: @@ -140,10 +130,7 @@ def _candidate_lineage(status: JsonObject, candidate_number: int) -> tuple[str, missing.append(batch_id) continue pull_requests = batch.get("pull_requests") - _require( - isinstance(pull_requests, list), - f"Mergify batch {batch_id} has no pull_requests list", - ) + _require(isinstance(pull_requests, list), f"Mergify batch {batch_id} has no pull_requests list") for pull_request in pull_requests: _require( isinstance(pull_request, dict) @@ -153,11 +140,9 @@ def _candidate_lineage(status: JsonObject, candidate_number: int) -> tuple[str, ) source_numbers.append(pull_request["number"]) parent_ids = batch.get("parent_ids", []) - _require( - isinstance(parent_ids, list) - and all(isinstance(parent_id, str) and parent_id for parent_id in parent_ids), - f"Mergify batch {batch_id} has invalid parent_ids", - ) + _require(isinstance(parent_ids, list) + and all(isinstance(parent, str) and parent for parent in parent_ids), + f"Mergify batch {batch_id} has invalid parent_ids") pending.extend(parent_ids) _require(source_numbers, f"Mergify batch for PR #{candidate_number} has no sources") _require(len(source_numbers) == len(set(source_numbers)), @@ -194,7 +179,8 @@ def _candidate_snapshot( def _source_fingerprint(source: JsonObject) -> tuple[object, ...]: head = source.get("head") base = source.get("base") - base_repo = base.get("repo") if isinstance(base, dict) else None + base = base if isinstance(base, dict) else {} + base_repo = base.get("repo") labels = source.get("labels", []) if not isinstance(labels, list) or any(not isinstance(label, dict) or not isinstance(label.get("name"), str) for label in labels): raise CandidateError("invalid source PR labels") @@ -207,9 +193,8 @@ def _source_fingerprint(source: JsonObject) -> tuple[object, ...]: source.get("draft"), source.get("body"), head.get("sha") if isinstance(head, dict) else None, - base.get("ref") if isinstance(base, dict) else None, - base_repo.get("id") if isinstance(base_repo, dict) else None, - base_repo.get("full_name") if isinstance(base_repo, dict) else None, + base.get("ref"), + *_repo_identity(base_repo if isinstance(base_repo, dict) else {}), ) @@ -434,10 +419,8 @@ def _attest_candidate_once( """Return stable source evidence after every source passes `source_policy`.""" repository = _object(event.get("repository"), "GitHub event repository is missing") event_pr = _object(event.get("pull_request"), "GitHub event pull request is missing") - _require( - event.get("action") in {"opened", "synchronize"}, - "Candidate attestation requires its creation or head-update event", - ) + _require(event.get("action") in {"opened", "synchronize"}, + "Candidate attestation requires its creation or head-update event") full_name = repository.get("full_name") _require(isinstance(full_name, str) and _REPOSITORY.fullmatch(full_name) is not None, "GitHub event repository name is invalid") @@ -449,22 +432,12 @@ def _attest_candidate_once( app = _object(github_get("/apps/mergify"), "GitHub App lookup is invalid") app_owner = app.get("owner") - _require( - app.get("id") == MERGIFY_APP_ID - and app.get("slug") == "mergify" - and isinstance(app_owner, dict) - and app_owner.get("login") == MERGIFY_APP_OWNER, - "Could not resolve the official Mergify GitHub App", - ) - expected_actor = _object( - github_get("/users/mergify%5Bbot%5D"), - "GitHub bot lookup is invalid", - ) - expected_identity = _identity(expected_actor) - _require( - expected_identity == (MERGIFY_BOT_ID, MERGIFY_BOT_LOGIN, "Bot", MERGIFY_APP_URL), - "Could not resolve the Mergify GitHub App identity", - ) + _require(app.get("id") == MERGIFY_APP_ID and app.get("slug") == "mergify" + and isinstance(app_owner, dict) and app_owner.get("login") == MERGIFY_APP_OWNER, + "Could not resolve the official Mergify GitHub App") + expected_identity = _identity(_object(github_get("/users/mergify%5Bbot%5D"), "GitHub bot lookup is invalid")) + _require(expected_identity == (MERGIFY_BOT_ID, MERGIFY_BOT_LOGIN, "Bot", MERGIFY_APP_URL), + "Could not resolve the Mergify GitHub App identity") _require(_identity(event_pr.get("user")) == expected_identity, "Candidate author is not the verified Mergify GitHub App") _require(_identity(event.get("sender")) == expected_identity, @@ -472,10 +445,7 @@ def _attest_candidate_once( candidate_number = event_pr.get("number") candidate_sha = event_head.get("sha") - _require( - isinstance(candidate_number, int) and candidate_number > 0, - "Candidate PR number is invalid", - ) + _require(isinstance(candidate_number, int) and candidate_number > 0, "Candidate PR number is invalid") _require(isinstance(candidate_sha, str) and _SHA.fullmatch(candidate_sha) is not None, "Candidate head SHA is invalid") candidate_path = f"/repos/{full_name}/pulls/{candidate_number}" diff --git a/src/loopzero/hosted.py b/src/loopzero/hosted.py index 8a9fdd12..4b3a58aa 100644 --- a/src/loopzero/hosted.py +++ b/src/loopzero/hosted.py @@ -27,9 +27,9 @@ def event_number(event: dict) -> int: value = prs[0].get("number") else: value = event.get("inputs", {}).get("pr", "") - if isinstance(value, bool) or not str(value).isdigit() or int(value) < 1: - raise LoopZeroError("refresh requires a positive PR number") - return int(value) + if not isinstance(value, bool) and str(value).isdigit() and (number := int(value)) > 0: + return number + raise LoopZeroError("refresh requires a positive PR number") def main() -> int: @@ -121,11 +121,10 @@ def _landed_before_publication(repo: str, number: int, head: str, snapshot: gith current = github.pr_view(repo, number) if current.head_sha != head: raise LoopZeroError("head changed before publication; refresh eligibility") - if snapshot is not None: - if current.state == "MERGED": - return True - if eligibility.source_fingerprint(current) != eligibility.source_fingerprint(snapshot): - raise LoopZeroError("source metadata changed before publication; refresh eligibility") + if snapshot is None or current.state == "MERGED": + return snapshot is not None + if eligibility.source_fingerprint(current) != eligibility.source_fingerprint(snapshot): + raise LoopZeroError("source metadata changed before publication; refresh eligibility") return False