Skip to content
Closed
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 @@ -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
47 changes: 38 additions & 9 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,15 +1153,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 @@ -1152,15 +1181,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 @@ -1275,7 +1304,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
7 changes: 3 additions & 4 deletions tests/test_candidate.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
from loopzero.candidate import CandidateError, CandidateRaceError, attest_candidate
from loopzero.types import LoopZeroError

from .conftest import git as isolated_git


@pytest.fixture(autouse=True)
def no_retry_delay(monkeypatch):
Expand Down Expand Up @@ -211,12 +213,9 @@ def tree_candidate(tmp_path, monkeypatch):
remote.mkdir()

def git(*args):
return subprocess.run(["git", *args], cwd=remote, check=True, capture_output=True,
text=True).stdout.strip()
return isolated_git(remote, *args).strip()

git("init", "-b", "main")
git("config", "user.name", "Test")
git("config", "user.email", "test@example.org")

def commit(name, content):
(remote / name).write_text(content)
Expand Down
58 changes: 46 additions & 12 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
import sys
from contextlib import suppress
from dataclasses import replace
from datetime import UTC, datetime
from email.utils import format_datetime
from pathlib import Path
from select import select
from types import SimpleNamespace
Expand Down Expand Up @@ -2894,6 +2896,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 @@ -2910,24 +2926,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 @@ -2962,14 +2993,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
24 changes: 17 additions & 7 deletions tests/test_sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -488,19 +488,29 @@ def test_real_sandbox_tmp_subpath_bind_stays_visible(git_repo, tmp_path):
@pytest.mark.skipif(
not _real_bwrap_works() or shutil.which("uv") is None, reason="needs real bwrap and uv"
)
def test_real_sandbox_uv_run_offline(git_repo):
home = Path.home() # the sandbox home inside `loopzero check`: bind the real toolchain
uv_cache = os.environ.get("UV_CACHE_DIR", f"{home}/.cache/uv")
uv_pythons = os.environ.get("UV_PYTHON_INSTALL_DIR", f"{home}/.local/share/uv/python")
def test_real_sandbox_uv_run_offline(git_repo, tmp_path):
uv_cache = tmp_path / "uv-cache"
uv_cache.mkdir()
uv = shutil.which("uv")
assert uv is not None
env = {
"UV_CACHE_DIR": str(uv_cache),
"UV_NO_CONFIG": "1",
"UV_OFFLINE": "1",
"UV_PYTHON": str(Path(sys._base_executable).resolve()),
"UV_PYTHON_DOWNLOADS": "never",
}
pyproject = '[project]\nname = "t"\nversion = "0"\nrequires-python = ">=3.12"\n'
(git_repo / "pyproject.toml").write_text(pyproject + "[dependency-groups]\ndev = []\n")
subprocess.run(["uv", "lock", "-q"], cwd=git_repo, check=True) # projects commit uv.lock
lock_env = {"HOME": str(tmp_path), "PATH": os.defpath, **env}
subprocess.run([uv, "lock", "-q"], cwd=git_repo, env=lock_env, check=True)
git(git_repo, "add", "-A")
git(git_repo, "commit", "-q", "-m", "uv project")
cfg = make_config(
checks=("uv run --group dev python -c 1", ".venv/bin/python -c 1", "test ! -w ."),
env=(("UV_CACHE_DIR", uv_cache), ("UV_PYTHON_INSTALL_DIR", uv_pythons)),
sandbox_ro=(str(Path(shutil.which("uv")).parent), uv_pythons), writable=(uv_cache,),
env=tuple(env.items()),
sandbox_ro=(str(Path(uv).parent), sys.base_prefix),
writable=(str(uv_cache),),
)
report = sandbox.run_checks(cfg, git_repo)
assert report.ok, report
Expand Down
Loading