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
6 changes: 4 additions & 2 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,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`,
Expand Down
33 changes: 21 additions & 12 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import time
from collections.abc import Callable, Iterator
from contextlib import contextmanager, suppress
from datetime import UTC, datetime
from datetime import datetime
from functools import partial, wraps
from pathlib import Path
from uuid import uuid4
Expand Down Expand Up @@ -212,11 +212,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={PAGE}&page={page}")
batch = github.api_get(f"{endpoint}?per_page={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
Expand All @@ -225,8 +225,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)
Expand Down Expand Up @@ -280,32 +280,41 @@ def _decide_kind(markers: list[Marker], head: str) -> tuple[str, str | None]:
MERGEABILITY_PENDING = "GitHub is computing mergeability"


def _review_age(review_at: datetime | None, dates: list[str]) -> tuple[float | None, float]:
if review_at is None:
return None, 0
server = github.response_date(dates[-1]) if dates else None
if server is None:
return time.time() - review_at.timestamp(), -MAX_REVIEW_CLOCK_SKEW
age = (server - review_at).total_seconds()
return (0.0 if -1 < age < 0 else age), 0 # HTTP Date rounds down to the second.


def _readiness(
wt: Path, config: Config, pr: github.PR, head: str, reviews: list[dict] | None = None,
*, workflow_wait: bool = False, announce_receipt: bool = False,
) -> github.Readiness:
if hold := github.merge_hold(pr.number, pr.labels):
return github.Readiness(False, (hold,))
dates: list[str] = []
if reviews is None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: The headers setup in _readiness could be simpler

headers is declared in both arms of the if/else, and _rest_rows/_pr_reviews pass an untyped **kwargs through to api_get. Two smaller options: declare headers: dict[str, str] = {} once before the if reviews is None check, and give _rest_rows/_pr_reviews an explicit response_headers: dict[str, str] | None = None parameter instead of **kwargs. That keeps the plumbing type-checked and removes the duplicated else arm. Behaviour stays the same.

reviews = _pr_reviews(config.repo, pr.number)
reviews = _pr_reviews(config.repo, pr.number, **({"dates": dates} if workflow_wait else {}))
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
review_age, min_age = _review_age(review_at, dates)
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 min_age <= review_age < STALE_VERDICT_GRACE
),
publishers=publishers,
)
Expand Down
68 changes: 39 additions & 29 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,9 @@ 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
diagnostic_api = _api_error_diagnostics.get() and args[:1] == ("api",)
rest_api = args[:1] == ("api",) and args[:2] != ("api", "graphql")
patch_error = args[:1] == ("api",) and _api_method(args) == "PATCH"
Expand Down Expand Up @@ -410,6 +412,7 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120,
raise GhAuth(error_command, error_tail.rstrip(), token=selected, guidance=f"\n{GH_AUTH_REMEDY}")
guidance = _pr_list_error_guidance(args, done.stderr, bool(read_only and selected and token is None))
raise _request_error(transient)(error_command, error_tail, token=selected, guidance=guidance)
dates[:] = [headers.get("date", "")]
return body


Expand Down Expand Up @@ -486,8 +489,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:
Expand Down Expand Up @@ -525,9 +528,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 <endpoint>` 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:
with suppress(OverflowError, ValueError):
stamp = parsedate_to_datetime(value)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

important: Validate the HTTP Date before using it for review age

parsedate_to_datetime accepts malformed values such as Wed, 23 Sep 2026 12:00:05 +0060 and interprets the offset as one hour. For a review at 12:00:00Z, the computed age is −3595 seconds, so the wait exits immediately even when the local fallback would give an age of five seconds. Validate the complete HTTP Date value before trusting it and add this case to the existing invalid-Date test.

return stamp if stamp.tzinfo is not None else None
return None


def auth_token() -> str:
Expand Down Expand Up @@ -1192,55 +1202,55 @@ def _review_threads(repo: str, number: int, *, include_resolved: bool = False) -
raise _not_found(number, exc) from exc


_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]+)?"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

important: Preserve fractional precision when ordering verdicts

The pattern accepts arbitrary fractional precision, but datetime.fromisoformat truncates to six digits. A check failure at 12:00:00.1234561Z and a review at 12:00:00.1234569Z therefore compare equal, ending the wait even though the failure predates the review. Preserve the sub-microsecond remainder for ordering both check runs and commit statuses, and cover this pair in the freshness test.

r"(?:Z|[+-](?:[01][0-9]|2[0-3]):[0-5][0-9])")


def readiness_timestamp(value: object) -> datetime | None:
if isinstance(value, str) and _READINESS_TIMESTAMP.fullmatch(value):
with suppress(OverflowError, ValueError):
return datetime.fromisoformat(value).astimezone(UTC)
return None


def _check_signals(
repo: str,
head_sha: str,
review_at: str | None = None,
review_at: datetime | 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, str | None]]] = {}
pending = {"pending", "queued", "in_progress", "requested", "waiting", "expected"}
signals: dict[str, list[tuple[str, datetime | 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
for name, cr in latest_runs.items():
signals[name] = [
(
cr.get("conclusion") or cr.get("status") or "unknown",
cr.get("completed_at") or cr.get("started_at"),
)
]
state = cr.get("conclusion") or cr.get("status") or "unknown"
timestamp = cr.get("started_at" if state in pending 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"))
(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()
}
pending = {"pending", "queued", "in_progress", "requested", "waiting", "expected"}
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 pending and states[name] != "success"
and all(at and at < review_at for state, at in values
if state != "success" and state not in pending)
and (review_grace or any(at and at >= review_at
for state, at in values if state in pending)))
stale_verdicts = tuple(
name
for name, values in signals.items()
if review_at
and stale_verdict_grace
and name not in stale
and states[name] in {"failure", "error", "cancelled", "timed_out"}
and all(at and at < review_at for state, at in values if state != "success")
)
stale_verdicts = tuple(name for name, values in signals.items()
if review_at and stale_verdict_grace and name not in stale
and states[name] in {"failure", "error", "cancelled", "timed_out"}
and all(at and at < review_at for state, at in values if state != "success"))
stale = (*stale, *stale_verdicts)
superseded: list[str] = []
workflows: list[dict] | None = None
Expand Down Expand Up @@ -1344,7 +1354,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: datetime | None = None,
review_grace: bool = False,
workflow_wait: bool = False,
stale_verdict_grace: bool = False,
Expand Down
84 changes: 51 additions & 33 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -2912,51 +2913,65 @@ 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
review_at = {
"fractional-review": "2026-09-23T12:00:00.125Z",
"offset-tie": "2026-09-23T12:00:00+00:00",
"offset-older": "2026-09-23T13:00:00+01:00",
"naive-review": "2026-09-23T12:00:00",
"malformed-review": "bad",
"missing-review": None,
}.get(new_failure, "2026-09-23T12:00:00Z")
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 = "bad" if new_failure == "invalid-date" else formatdate(server_now, usegmt=True)
gh.respond(reviews_key(), f"HTTP/2 200 OK\nDate: {date}\n\n{json.dumps(reviews)}")
offset = {"server-host-behind": -40, "server-host-ahead": 1000, "server-old-review": -40}
start = server_now + offset.get(new_failure, 0)
failed_at = {
"tie": "2026-09-23T12:00:00Z",
"missing": None,
"fractional-review": "2026-09-23T12:00:00.000Z",
"fractional-newer": "2026-09-23T12:00:00.250Z",
"offset-tie": "2026-09-23T11:00:00-01:00",
"offset-older": "2026-09-23T13:59:59+02:00",
"naive-check": "2026-09-23T11:59:00",
"malformed-check": "2026-09-23T12:00:00+00:60",
}.get(
new_failure,
"2026-09-23T12:00:10Z" if new_failure else "2026-09-23T11:59:00Z",
"2026-09-23T12:00:10Z" if new_failure is True else "2026-09-23T11:59:59Z",
)
active_at = "2026-09-23T12:00:20Z"
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"
Expand All @@ -2968,10 +2983,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 == [5.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
Expand Down
Loading