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 on _rest_rows, _pr_reviews and _gh_json hides the only option they forward

_rest_rows, _pr_reviews (cli.py:234) and _gh_json (github.py:442) now take **kwargs just to pass response_headers through. This drops type checking, so a typo such as response_header= reaches _gh and only fails at runtime there. Smallest fix: declare an explicit keyword-only parameter response_headers: dict[str, str] | None = None on each of these functions.

"""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: Refactor duplicates the headers initialisation without changing behaviour

Behaviour is the same before and after this change. In both versions headers starts as an empty dict and is filled only when _pr_reviews runs with workflow_wait. When the caller passes reviews, _review_age(review_at, headers) still receives an empty dict, so it falls back to local time as before. The only change is that headers = {} is now written in two branches, one in the if and one in the new else. That adds a line and an extra branch without making anything clearer. Smallest fix: go back to a single headers: dict[str, str] = {} before the if, or drop the commit. If the aim is to show that caller-supplied reviews have no server Date, a short comment would say that without the extra branch.

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)

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: Server Date comes from the last reviews page, and only on the wait path

Headers are captured only when workflow_wait is true, and each page overwrites the previous one, so the Date used is from the last page fetched. That is the right instant for computing age. However, review_grace on the non-wait path (ready without --wait, and cli.py:1681 where reviews are passed in) still uses local time.time(). A host clock that is behind can still make review_age negative there and withhold review_grace. If this is intended (the task scopes server time to the wait decision), a short comment at _readiness would make it explicit. Otherwise, always capture headers when reviews is 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:
"""`gh api <endpoint>` parsed as JSON (None on an empty body)."""
if response_headers is not 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: api_get duplicates the _gh_json call just to avoid passing response_headers=None

api_get has two branches that differ only in whether response_headers is forwarded. _gh already ignores None through _capture_headers. The branch seems to exist only so test doubles of _gh_json that don't accept keyword arguments (e.g. tests/test_cli.py:3681) keep working. That ties production code to test mocks. Smallest fix: always call _gh_json("api", endpoint, response_headers=response_headers) and update the mock's signature to accept **kwargs.

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 @@ -1238,7 +1267,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
58 changes: 46 additions & 12 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import shutil
import subprocess
import sys
from datetime import UTC, datetime
from email.utils import format_datetime
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import Mock
Expand Down Expand Up @@ -2569,6 +2571,20 @@ 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,
Expand All @@ -2585,24 +2601,39 @@ def test_ready_wait_review_failure_freshness(
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
format_datetime(datetime.fromtimestamp(server_now, UTC), 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": "bad",
}.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",
)
runs = (
[{"name": name, "status": "completed", "conclusion": "failure", "completed_at": failed_at}]
Expand Down Expand Up @@ -2637,14 +2668,17 @@ def advance(seconds):
gh.respond(f"api repos/{REPO}/commits/{head}/statuses",
[{"context": name, "state": "success"}])
monkeypatch.setattr(cli, "_sleep", advance)
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=60" if age < 0 else "--wait"] if wait else []),
*([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