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
36 changes: 24 additions & 12 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import time
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from datetime import UTC, datetime
from datetime import datetime
Comment thread
eowca marked this conversation as resolved.
Resolved
from functools import partial, wraps
from pathlib import Path

Expand Down Expand Up @@ -186,11 +186,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 @@ -199,8 +199,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 @@ -254,32 +254,44 @@ 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, headers: dict[str, str]) -> tuple[float | None, float]:
server_time = github.response_date(headers)
now = server_time.timestamp() if server_time is not None else time.time()
age = now - review_at.timestamp() if review_at is not None else None
if server_time is None:
return age, -MAX_REVIEW_CLOCK_SKEW
if age is not None and -1 < age < 0:
age = 0.0 # HTTP Date rounds down to the second.
return age, 0.0


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,))
if reviews is None:
reviews = _pr_reviews(config.repo, pr.number)
headers: dict[str, str] = {}
reviews = _pr_reviews(config.repo, pr.number, response_headers=headers if workflow_wait else None)
else:
headers = {}
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, headers)
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
),
)
report = _load_report(wt)
Expand Down
60 changes: 45 additions & 15 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from contextvars import ContextVar
from dataclasses import dataclass
from datetime import UTC, datetime
from email.utils import parsedate_to_datetime
from pathlib import Path
from typing import Literal
from urllib.parse import quote
Expand Down Expand Up @@ -319,8 +320,15 @@ def _pr_list_error_guidance(args: tuple[str, ...], stderr: str, using_app: bool)
return ""


def _capture_headers(destination: dict[str, str] | None, headers: dict[str, str]) -> None:
if destination is not None:
destination.clear()
destination.update(headers)


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,
response_headers: dict[str, str] | None = None) -> str:
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 @@ -376,6 +384,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 GhError(error_command, error_tail, token=selected, guidance=guidance)
_capture_headers(response_headers, headers)
return body


Expand Down Expand Up @@ -452,8 +461,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 @@ -488,11 +497,22 @@ def _with_file(content: str) -> Path:
return Path(name)


def api_get(endpoint: str) -> object:
def api_get(endpoint: str, *, response_headers: dict[str, str] | None = None) -> object:
"""`gh api <endpoint>` parsed as JSON (None on an empty body)."""
if response_headers is not None:
return _gh_json("api", endpoint, response_headers=response_headers)
return _gh_json("api", endpoint)


def response_date(headers: dict[str, str]) -> datetime | None:
"""Return the HTTP response time when it identifies an instant."""
try:
stamp = parsedate_to_datetime(headers.get("date", ""))
return stamp.astimezone(UTC) if stamp.tzinfo is not None else None
except (OverflowError, ValueError):
return None


def auth_token() -> str:
"""Token of the authenticated `gh` host, for Git transports that cannot call gh."""
return _gh("auth", "token", "--hostname", "github.com").strip()
Expand Down Expand Up @@ -1133,40 +1153,50 @@ 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]+)?"
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"}
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
Expand Down Expand Up @@ -1285,7 +1315,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
108 changes: 55 additions & 53 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 replace
from email.utils import formatdate
from pathlib import Path
from select import select
from types import SimpleNamespace
Expand Down Expand Up @@ -2851,64 +2852,68 @@ def test_ready_transition_immediate_green_is_best_effort(wt, gh, capsys, head, w
(True, 300, True, True, 1, False),
(False, 300, "tie", True, 1, False),
(False, 300, False, False, 1, False),
(False, 300, "missing", True, 1, False),
(False, 180, "missing", True, 1, False),
(False, 5, "fractional-review", True, 0, True),
(False, 180, "fractional-newer", True, 1, False),
(False, 180, "offset-tie", True, 1, False),
(False, 180, "offset-older", True, 0, True),
(False, 180, "naive-check", True, 1, False),
(False, 180, "malformed-check", True, 1, False),
(False, 5, "naive-review", True, 1, False),
(False, 5, "malformed-review", True, 1, False),
(False, 5, "missing-review", True, 1, False),
(False, 5, "server-synced", True, 0, True),
(False, 5, "server-host-behind", True, 0, True),
(False, 5, "server-host-ahead", True, 0, True),
(False, 900, "server-old-review", True, 1, False),
(False, 5, "invalid-date", True, 0, True),
])
def test_ready_wait_review_failure_freshness(
wt: Path,
gh: FakeGh,
capsys,
monkeypatch,
name,
pending,
age,
new_failure,
wait,
expected,
waited,
head,
wt: Path, gh: FakeGh, capsys, monkeypatch, name, pending, age, new_failure, wait, expected, waited, head,
) -> 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,
)
clock = [1790164800 + age] # 2026-09-23T12:00:00Z plus review age
start = clock[0]
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)
clock = [start]
monkeypatch.setattr(cli.time, "time", lambda: clock[0])
monkeypatch.setattr(cli.time, "monotonic", lambda: clock[0] - start)
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",
)
runs = (
[{"name": name, "status": "completed", "conclusion": "failure", "completed_at": failed_at}]
if name == "checks"
else [
{
"name": name,
"status": "in_progress",
"started_at": "2026-09-23T12:00:20Z",
}
]
if pending
else []
)
statuses = (
[{"context": name, "state": "failure", "created_at": failed_at}]
if name != "checks"
else [
{"context": name, "state": "pending", "created_at": "2026-09-23T12:00:20Z"}
]
if pending
else []
"2026-09-23T12:00:10Z" if new_failure is True else "2026-09-23T11:59:59Z",
)
pending_at = "2026-09-23T12:00:20Z"
if name == "checks":
runs = [{"name": name, "conclusion": "failure", "status": "completed", "completed_at": failed_at}]
if new_failure == "missing":
runs[0]["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": pending_at}] if pending else []
statuses = [{"context": name, "state": "failure", "created_at": failed_at}]
arm_check_runs(gh, head, runs)
gh.respond(f"api repos/{REPO}/commits/{head}/statuses", statuses)
sleeps = []
Expand All @@ -2920,14 +2925,11 @@ def advance(seconds):
gh.respond(f"api repos/{REPO}/commits/{head}/statuses",
[{"context": name, "state": "success"}])
monkeypatch.setattr(cli, "_sleep", advance)
code, out, err = run(
capsys,
"--config",
"workflow.toml",
"ready",
*(["--wait=60" if age < 0 else "--wait"] if wait else []),
)
wait_flag = "--wait=10" if server_timeline else "--wait=60" if age < 0 else "--wait"
code, out, err = run(capsys, "--config", "workflow.toml", "ready", *([wait_flag] if wait else []))
assert (code, err, bool(sleeps)) == (expected, "", waited)
if server_timeline and waited:
assert sleeps == [5.0]
assert out.endswith(f"ready: {URL}\n" if expected == 0 else
f"not ready: required check '{name}' is failure\n")
assert (f"waiting: required check '{name}' is failure" in out) == waited
Expand Down
Loading