diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 6af2e8b0..c22c54d7 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -121,7 +121,8 @@ 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 + target branch and required CI. Readiness compares parsed instants for verdict + freshness and uses a valid GitHub response Date during waits. The receipt must record a clean passing run at that head with the current commands and check settings digest. Ready and merge validate the PR, head and hold before checking the local receipt. An invalid receipt stops the command before it fetches remote readiness @@ -540,8 +541,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_args.py b/src/loopzero/_cli_args.py index ce9af047..c154e28d 100644 --- a/src/loopzero/_cli_args.py +++ b/src/loopzero/_cli_args.py @@ -5,6 +5,7 @@ import argparse import io import sys +from pathlib import Path WAIT_TIMEOUT = 1800.0 @@ -21,18 +22,12 @@ def _wait_seconds(value: str) -> float: raise argparse.ArgumentTypeError("expected a finite, nonnegative number of seconds") -def _config_path(value: str): - from pathlib import Path - - return Path(value) - - def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog="loopzero", description="One task, one branch, one draft PR, one review, one merge." ) parser.add_argument( - "--config", type=_config_path, default=None, help="path to workflow.toml (default: repo root)" + "--config", type=Path, help="path to workflow.toml (default: repo root)" ) parser.add_argument("--version", action=_VersionAction, nargs=0, help="show program's version number and exit") sub = parser.add_subparsers(dest="command", required=True) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 3ac7a1c5..2ae035b3 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) @@ -316,26 +315,29 @@ def _readiness( ) -> github.Readiness: if problem := _readiness_precheck(wt, config, pr, head, diagnostics): return github.Readiness(False, (problem,)) - 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, ) @@ -418,7 +420,7 @@ def _print_receipt(wt: Path, report: CheckReport, action: str) -> None: return -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.""" results = [ {k: v for k, v in dataclasses.asdict(result).items() @@ -428,8 +430,15 @@ def _save_report(wt: Path, report: CheckReport) -> str | None: payload = {"head": report.head, "dirty": report.dirty, "results": results} if report.settings_sha256 is not None: payload["settings_sha256"] = report.settings_sha256 + def preserve_pass() -> bool: + saved = _load_report(wt) + return (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 worktree.write_local_state( wt, CHECKS_FILE.name, json.dumps(payload, indent=2) + "\n", expected_head=report.head, + preserve=preserve_pass if checkpoint_checks is not None else None, ) @@ -630,7 +639,8 @@ def cmd_check(args: argparse.Namespace) -> int: raise config_mod.ConfigError("checks.commands must list at least one command to run checks") 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), + status=lambda message: print(message, flush=True), + checkpoint=lambda partial: _save_report(wt, partial, checkpoint_checks=config.checks), workflow=args.config or f"origin/{config.base_branch}:workflow.toml", ) shortened = False diff --git a/src/loopzero/config.py b/src/loopzero/config.py index 97db3d8f..6fd5279d 100644 --- a/src/loopzero/config.py +++ b/src/loopzero/config.py @@ -18,7 +18,6 @@ # Host locations that must never be exposed to the sandbox, even read-only, because they # hold credentials or live sockets (docker, ssh-agent, gpg-agent, dbus). Subpaths of /home # are allowed so tool caches such as ~/.local/bin can be listed explicitly. -FORBIDDEN_RO = ("/", "/home", "/root", "/run", "/var/run", "/proc", "/dev", "/sys") _ENV_NAME = re.compile(r"[A-Z_][A-Z0-9_]*\Z") FORBIDDEN_RO_TREES = ("/run", "/var/run", "/proc", "/dev", "/sys", "/root") @@ -45,8 +44,7 @@ def load(path: Path | str) -> Config: """Load and validate a workflow file.""" path = Path(path) try: - with path.open("rb") as handle: - data = tomllib.load(handle) + raw = path.read_bytes() except FileNotFoundError as exc: raise ConfigError( f"{path}: config file not found. Check out the intended repository, " @@ -54,14 +52,18 @@ def load(path: Path | str) -> Config: "(https://github.com/feder-positronics/loop-zero/blob/main/SETUP.md#configure), " "or follow this repository's review process if it has one." ) from exc - except UnicodeDecodeError as exc: - raise ConfigError(f"{path}: {exc}") from exc - except tomllib.TOMLDecodeError as exc: - raise ConfigError(f"{path}: invalid TOML: {exc}") from exc + return _parse_workflow(raw, path) + + +def _parse_workflow(raw: bytes, source: Path | str, hint: str = "") -> Config: try: - return _build(data) - except ConfigError as exc: - raise ConfigError(f"{path}: {exc}") from None + return _build(tomllib.loads(raw.decode("utf-8"))) + except UnicodeDecodeError as exc: + raise ConfigError(f"{source}: {exc}") from exc + except (tomllib.TOMLDecodeError, ConfigError) as exc: + invalid_toml = isinstance(exc, tomllib.TOMLDecodeError) + message = f"invalid TOML: {exc}" if invalid_toml else str(exc) + raise ConfigError(f"{source}: {message}{hint}") from (exc if invalid_toml and not hint else None) def run_git(worktree: Path, *args: str, timeout: float = 60) -> _proc.Completed: @@ -124,15 +126,7 @@ def _remote_workflow(worktree: Path, branch: str, previous: Config | None, *, ) if shown.exit_code != 0: raise ConfigError(f"cannot read {source}. {hint}") - try: - text = shown.stdout.encode("utf-8", errors="surrogateescape").decode("utf-8") - return _build(tomllib.loads(text)), revision - except UnicodeDecodeError as exc: - raise ConfigError(f"{source}: {exc}") from exc - except tomllib.TOMLDecodeError as exc: - raise ConfigError(f"{source}: invalid TOML: {exc}. {hint}") from None - except ConfigError as exc: - raise ConfigError(f"{source}: {exc}. {hint}") from None + return _parse_workflow(shown.stdout.encode("utf-8", "surrogateescape"), source, f". {hint}"), revision def load_trusted(worktree: Path, *, previous: Config | None = None, refresh: bool = False, @@ -147,13 +141,12 @@ def load_trusted(worktree: Path, *, previous: Config | None = None, refresh: boo "or supply --config for bootstrap or an override." ) branch = ref.removeprefix(prefix) - policy, revision = _remote_workflow(worktree, branch, previous, refresh=refresh, read_timeout=read_timeout) - if policy.base_branch != branch: - branch = policy.base_branch + for _ in range(2): policy, revision = _remote_workflow(worktree, branch, previous, refresh=refresh, read_timeout=read_timeout) - if policy.base_branch != branch: - raise ConfigError("trusted origin workflows disagree on repo.base; align them or supply --config") - return replace(policy, trusted_base_revision=revision) + if policy.base_branch == branch: + return replace(policy, trusted_base_revision=revision) + branch = policy.base_branch + raise ConfigError("trusted origin workflows disagree on repo.base; align them or supply --config") def _build(data: dict[str, Any]) -> Config: @@ -269,14 +262,13 @@ def _merge_settings(delivery: dict[str, Any]) -> tuple[str, str | None]: if merge not in MERGE_STRATEGIES: raise ConfigError(f"delivery.merge must be one of {MERGE_STRATEGIES}, got {merge!r}") mergify_queue = delivery.get("mergify_queue") - if merge == "mergify" and not mergify_queue: - raise ConfigError("delivery.mergify_queue is required when delivery.merge = 'mergify'") - if mergify_queue is not None and merge != "mergify": - raise ConfigError( - f"delivery.mergify_queue requires delivery.merge = 'mergify', got {merge!r}" - ) - if mergify_queue is not None and not re.fullmatch(r"[A-Za-z0-9_-]+", mergify_queue): - raise ConfigError("delivery.mergify_queue must be a non-empty command-safe name") + if merge == "mergify": + if not mergify_queue: + raise ConfigError("delivery.mergify_queue is required when delivery.merge = 'mergify'") + if not re.fullmatch(r"[A-Za-z0-9_-]+", mergify_queue): + raise ConfigError("delivery.mergify_queue must be a non-empty command-safe name") + elif mergify_queue is not None: + raise ConfigError(f"delivery.mergify_queue requires delivery.merge = 'mergify', got {merge!r}") return merge, mergify_queue @@ -298,7 +290,7 @@ def _host_paths(label: str, value: list[Any]) -> tuple[str, ...]: if not raw.startswith("/"): raise ConfigError(f"{label} entries must be absolute, got {raw!r}") path = Path(raw).resolve() - if str(path) in FORBIDDEN_RO or any( + if str(path) in ("/", "/home") or any( path.is_relative_to(tree) for tree in FORBIDDEN_RO_TREES ): raise ConfigError(f"{label} must not expose {raw!r} (host sockets or secrets)") @@ -319,8 +311,7 @@ def _env_table(table: dict[str, Any]) -> tuple[tuple[str, str], ...]: def _limits(table: dict[str, Any]) -> ResourceLimits: defaults = ResourceLimits() _reject_unknown("checks.limits", table, defaults.__dict__) - values = defaults.__dict__ | table - for name, value in values.items(): + for name, value in (defaults.__dict__ | table).items(): if isinstance(value, bool) or not isinstance(value, int) or value <= 0: raise ConfigError(f"checks.limits.{name} must be a positive int") - return ResourceLimits(**values) + return ResourceLimits(**table) diff --git a/src/loopzero/eligibility.py b/src/loopzero/eligibility.py index 7857a18b..c003125d 100644 --- a/src/loopzero/eligibility.py +++ b/src/loopzero/eligibility.py @@ -54,10 +54,9 @@ def review_projection(review: dict, head: str, repo: str, number: int): if not positions: return False, None try: - if positions != [1] or len(span.encode("utf-8")) > runners.CODEX_HEADER_LIMIT: - return True, None - if len(block) > 2 and (len(block) != 3 or not re.fullmatch( - r"", block[2])): + if (positions != [1] or len(span.encode("utf-8")) > runners.CODEX_HEADER_LIMIT + or (len(block) > 2 and (len(block) != 3 or not re.fullmatch( + r"", block[2])))): return True, None marker = REVIEW_MARKER_RE.fullmatch(block[0]) evidence = runners.decode_codex_evidence(block[1]) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 115c6179..ba49032d 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: @@ -1171,34 +1181,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) @@ -1302,7 +1319,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/src/loopzero/worktree.py b/src/loopzero/worktree.py index 8916bc2a..4d38c4de 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -9,6 +9,7 @@ import stat import subprocess from collections.abc import Iterator +from collections.abc import Callable from contextlib import contextmanager, suppress from pathlib import Path from select import select @@ -147,12 +148,15 @@ def read_local_state(wt: Path, name: str) -> str: def write_local_state( wt: Path, name: str, text: str, *, private: bool = False, exclusive: bool = False, - expected_head: str | None = None, + expected_head: str | None = None, preserve: Callable[[], bool] | None = None, ) -> str | None: - with _local_state_directory(wt, create=True, lock=private or expected_head is not None) as fd: + lock = private or expected_head is not None or preserve is not None + with _local_state_directory(wt, create=True, lock=lock) as fd: if expected_head is not None and (current_head := head(wt)) != expected_head: return current_head _regular_state(wt, fd, name) + if preserve is not None and preserve(): + return None if private: os.fchmod(fd, 0o700) temp = f".{name}-{uuid4().hex}" diff --git a/tests/test_cli.py b/tests/test_cli.py index e790e384..aab7989a 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 @@ -2501,26 +2502,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]) @@ -2939,33 +2931,48 @@ def test_ready_transition_immediate_green_is_best_effort(wt, gh, capsys, head, w (False, True), (True, True), (False, "tie"), (False, "missing"), )), (False, 300, False, False, 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" @@ -2977,10 +2984,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 @@ -2989,20 +2999,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"]) @@ -4814,3 +4819,26 @@ def test_pr_marks_legacy_same_head_check_unverified(wt, gh, capsys, refresh): draft = json.loads(gh.calls[-1]["--input"])["body"] assert "unverified" not in draft assert_contains(draft, f"Recorded for `{head[:12]}`\n- `echo ok`: exit 0", "Manual validation evidence.") + + +def test_late_checkpoint_preserves_completed_pass(wt, gh, capsys, head, monkeypatch): + def run_checks(cfg, path, *, progress, status, checkpoint, workflow): + results = tuple(CheckResult(c, 0, 0, "", input_key="key") for c in cfg.checks) + passed = CheckReport(head, False, results, cli.sandbox.settings_fingerprint(cfg)) + incomplete = CheckResult(cli.sandbox.INCOMPLETE_CHECK_COMMAND, 1, 0.0, "") + partial = replace(passed, results=(results[0], incomplete)) + checkpoint(partial) + assert cli._load_report(wt) == partial + cli._save_report(wt, passed) + checkpoint(partial) + assert cli._current_check_report(wt, cfg, head) == passed + cli._save_report(wt, replace(passed, results=results[:1])) + checkpoint(partial) + assert cli._load_report(wt) == partial + cli._save_report(wt, passed) + return replace(passed, results=(replace(results[0], exit_code=1),)) + + monkeypatch.setattr(cli.sandbox, "run_checks", run_checks) + code, _, err = run(capsys, "check") + assert code == 1 and "(exit 1)" in err, err + assert cli._load_report(wt).results[0].exit_code == 1