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
from functools import partial, wraps
from pathlib import Path

Expand Down Expand Up @@ -218,11 +218,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]:

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: Untyped kwargs passthrough in _rest_rows/_pr_reviews

_rest_rows and _pr_reviews forward bare **kwargs to github.api_get. The only option they actually forward is response_headers, and the bare **kwargs hides that from type checkers and readers. Smallest fix: declare the parameter explicitly as *, response_headers: dict[str, str] | None = None in both functions. That is the same signature api_get and _gh_json use.

"""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 @@ -231,8 +231,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 @@ -286,6 +286,17 @@ 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,
Expand All @@ -294,25 +305,26 @@ def _readiness(
reason = f"PR #{pr.number} {github.MERGE_HOLD_MESSAGE}"
return github.Readiness(ready=False, reasons=(reason,))
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: Header dict setup split across if/else

headers is assigned in both branches, and the first branch then passes headers if workflow_wait else None. It is simpler to write headers: dict[str, str] = {} once before the if reviews is None: check and keep the conditional pass-through. Behaviour stays the same and the block loses three lines.

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 = _current_check_report(wt, config, head)
Expand Down
47 changes: 38 additions & 9 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,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 @@ -298,8 +299,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 @@ -355,6 +363,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 @@ -431,8 +440,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 @@ -464,11 +473,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:

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: api_get branches on response_headers when it could just pass it through

api_get only passes response_headers to _gh_json when it is not None. _gh already treats None as "don't capture", via _capture_headers. That makes the branch redundant, and it adds a second call path to keep in sync. Smallest fix: replace both lines with a single return _gh_json("api", endpoint, response_headers=response_headers).

"""`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 @@ -1110,15 +1130,24 @@ def _review_threads(repo: str, number: int, *, include_resolved: bool = False) -
raise _not_found(number, exc) from exc


def readiness_timestamp(value: object) -> datetime | None:
if isinstance(value, str):
with suppress(OverflowError, ValueError):
stamp = datetime.fromisoformat(value)
if stamp.tzinfo is not None:
return stamp.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]]] = {}
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:
Expand All @@ -1129,15 +1158,15 @@ def _check_signals(
signals[name] = [
(
cr.get("conclusion") or cr.get("status") or "unknown",
cr.get("completed_at") or cr.get("started_at"),
readiness_timestamp(cr.get("completed_at") or cr.get("started_at")),
)
]
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])
Expand Down Expand Up @@ -1248,7 +1277,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
103 changes: 51 additions & 52 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import subprocess
import sys
from dataclasses import replace
from email.utils import formatdate
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import Mock
Expand Down Expand Up @@ -2719,63 +2720,64 @@ def test_ready_transition_immediate_green_is_best_effort(wt, gh, capsys, head, w
(False, 300, "tie", True, 1, False),
(False, 300, False, False, 1, False),
(False, 300, "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-newer": "2026-09-23T12:00:00.250Z",

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: Refactor drops the only sub-second staleness check

This delta removes "fractional-review": "2026-09-23T12:00:00.000Z" from failed_at. The parametrize row (False, 5, "fractional-review", True, 0, True) at line 2723 is still there, so its failure time now falls back to 2026-09-23T11:59:59Z. That is a full second before the review at 12:00:00.125Z.

Before this change, the case checked that a failure 125 ms before the review counts as stale. An implementation that drops the fractional part would see 12:00:00 vs 12:00:00, treat it as a tie, return exit 1, and fail the test. With the fallback value, that implementation now passes.

fractional-newer (review 12:00:00Z, failure 12:00:00.250Z) does not cover this either: truncation also gives the expected not-stale result there. After this change, no case in the matrix detects lost sub-second precision, even though the task's acceptance and problem statement cover fractional and same-second instants.

The commit is described as a fixture reuse, so the lost coverage is easy to miss. Smallest fix: restore the "fractional-review": "2026-09-23T12:00:00.000Z" entry in failed_at. The other changes in this delta keep behavior the same: the runs/statuses rewrite matches the old conditional expressions, and formatdate(server_now, usegmt=True) gives the same output as the old format_datetime call.

"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": "bad",
}.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}]
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 @@ -2787,14 +2789,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