Repository navigation
Compare readiness using GitHub timestamps #1841
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -128,6 +128,9 @@ class Readiness: | |
| _read_scope: ContextVar[tuple[float, str | None, bool] | None] = ContextVar("github_reads", default=None) | ||
| _api_error_diagnostics: ContextVar[bool] = ContextVar("github_api_error_diagnostics", default=False) | ||
| _HTTP_STATUS_RE = re.compile(r"^HTTP/\S+\s+(\d{3})(?:\s+(.*))?$", re.IGNORECASE) | ||
| _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])") | ||
| _HTTP_DATE = re.compile(r"[A-Za-z]{3}, [0-9]{2} [A-Za-z]{3} [0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2} GMT") | ||
| _CREDENTIAL_TOKEN_RE = re.compile( | ||
| r"\b(?:github_pat_[A-Za-z0-9_]+\b|gh[pousr]_[A-Za-z0-9_]{10,}\b|sk-[A-Za-z0-9_-]{8,})" | ||
| ) | ||
|
|
@@ -354,7 +357,8 @@ 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 | ||
| api = args[:1] == ("api",) | ||
| diagnostic_api = api and _api_error_diagnostics.get() | ||
| rest_api = api and args[:2] != ("api", "graphql") | ||
|
|
@@ -387,6 +391,7 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, | |
| status, headers, body = response | ||
| tail = "\n".join(part for part in (done.stderr, body) if part) | ||
| if done.exit_code == 0: | ||
| dates[:] = [headers.get("date", "")] | ||
| return body | ||
| rate_limited = _rate_limited(status, headers, tail) | ||
| transient = rate_limited or _transient_error(tail, retry_idempotent, status) | ||
|
|
@@ -416,9 +421,7 @@ def _rest_rate_limit(headers: dict[str, str]) -> str: | |
| remaining = int(remaining_value) if re.fullmatch(r"[0-9]{1,18}", remaining_value) else None | ||
| retry_after = headers.get("retry-after", "") | ||
| retry_seconds = re.fullmatch(r"[0-9]{1,18}", retry_after) | ||
| retry_date = re.fullmatch( | ||
| r"[A-Za-z]{3}, [0-9]{2} [A-Za-z]{3} [0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2} GMT", retry_after, | ||
| ) | ||
| retry_date = _HTTP_DATE.fullmatch(retry_after) | ||
| reset = "" | ||
| try: | ||
| if epoch := headers.get("x-ratelimit-reset"): | ||
|
|
@@ -479,8 +482,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: | ||
|
|
@@ -518,9 +521,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: | ||
| if _HTTP_DATE.fullmatch(value): | ||
| with suppress(OverflowError, ValueError): | ||
| return parsedate_to_datetime(value) | ||
| return None | ||
|
|
||
|
|
||
| def auth_token() -> str: | ||
|
|
@@ -1171,34 +1181,41 @@ def _review_threads(repo: str, number: int, *, include_resolved: bool = False) - | |
| _FAILED_VERDICTS = {"failure", "error", "cancelled", "timed_out"} | ||
|
|
||
|
|
||
| ReadinessTimestamp = tuple[datetime, str] | ||
|
|
||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. suggestion: ReadinessTimestamp's string part needs a comment
|
||
|
|
||
| def readiness_timestamp(value: object) -> ReadinessTimestamp | None: | ||
| if isinstance(value, str) and (match := _READINESS_TIMESTAMP.fullmatch(value)): | ||
| with suppress(OverflowError, ValueError): | ||
| return datetime.fromisoformat(value).astimezone(UTC), (match[1] or "")[6:].rstrip("0") | ||
| return None | ||
|
|
||
|
|
||
| def _check_signals( | ||
| repo: str, | ||
| head_sha: str, | ||
| review_at: str | None = None, | ||
| review_at: ReadinessTimestamp | 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, ReadinessTimestamp | 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 | ||
| signals = { | ||
| name: [(cr.get("conclusion") or cr.get("status") or "unknown", | ||
| cr.get("completed_at") or cr.get("started_at"))] | ||
| for name, cr in latest_runs.items() | ||
| } | ||
| for name, cr in latest_runs.items(): | ||
| state = cr.get("conclusion") or cr.get("status") or "unknown" | ||
| timestamp = cr.get("started_at" if state in _PENDING_CHECKS else "completed_at") | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. suggestion: A completed run without completed_at no longer falls back to started_at Before this change the timestamp was |
||
| 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"))) | ||
| states = { | ||
| name: _aggregate_signal([state for state, _ in values]) | ||
| for name, values in signals.items() | ||
| } | ||
| signals.setdefault(name, []).append((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()} | ||
| stale = tuple(name for name, values in signals.items() if review_at | ||
| and states[name] not in _NONFAILING_CHECKS | ||
| and all(at and at < review_at for state, at in values if state not in _NONFAILING_CHECKS) | ||
|
|
@@ -1302,7 +1319,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: ReadinessTimestamp | None = None, | ||
| review_grace: bool = False, | ||
| workflow_wait: bool = False, | ||
| stale_verdict_grace: bool = False, | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
|
@@ -2501,26 +2502,17 @@ def test_ready_explains_trusted_policy_blocker(wt, gh, capsys, head, retargeted, | |
| assert without_accepted_receipt(out) == f"not ready: {reason}\n" | ||
|
|
||
|
|
||
| def test_pending_required_check_names_the_wait(wt: Path, gh: FakeGh, capsys, head) -> None: | ||
| @pytest.mark.parametrize("command", ["ready", "merge"]) | ||
| def test_pending_required_check_names_the_wait(wt, gh, capsys, head, command): | ||
| arm_approved_ready_pr(gh, head, wt, isDraft=False) | ||
| arm_check_runs(gh, head, [{"name": "checks", "status": "in_progress"}]) | ||
|
|
||
| code, out, err = run(capsys, "ready") | ||
|
|
||
| out, err = expect_cli(capsys, 1, command) | ||
| out = without_accepted_receipt(out) | ||
| assert (code, err) == (1, "") | ||
| assert out.splitlines() == [ | ||
| "not ready: required check 'checks' is pending", | ||
| "next: loopzero ready --wait", | ||
| ] | ||
|
|
||
| arm_pr(gh, head, isDraft=False) | ||
| arm_readiness(gh, head, wt) | ||
| arm_check_runs(gh, head, [{"name": "checks", "status": "in_progress"}]) | ||
| code, out, err = run(capsys, "merge") | ||
|
|
||
| assert (code, without_accepted_receipt(out)) == (1, "") | ||
| assert "required check 'checks' is pending; next: loopzero merge --wait" in err | ||
| reason = "required check 'checks' is pending" | ||
| if command == "ready": | ||
| assert out == f"not ready: {reason}\nnext: loopzero ready --wait\n" and err == "" | ||
| else: | ||
| assert out == "" and f"{reason}; next: loopzero merge --wait" in err | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("draft", [True, False]) | ||
|
|
@@ -2939,33 +2931,48 @@ def test_ready_transition_immediate_green_is_best_effort(wt, gh, capsys, head, w | |
| (False, True), (True, True), (False, "tie"), (False, "missing"), | ||
| )), | ||
| (False, 300, False, False, 1, False), | ||
| *[(False, 180, failure, True, 1, False) for failure in | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. suggestion: Merged parametrize rows mix generator and list splats The merge kept main's rows, which splat generators ( |
||
| ("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 | ||
| failed_at = { | ||
| "tie": "2026-09-23T12:00:00Z", | ||
| "missing": None, | ||
| }.get( | ||
| new_failure, | ||
| "2026-09-23T12:00:10Z" if new_failure else "2026-09-23T11:59:00Z", | ||
| ) | ||
| active_at = "2026-09-23T12:00:20Z" | ||
| current, earlier = "12:00:00Z", "11:59:59Z" | ||
| review_time, failure_time = { | ||
| True: (current, "12:00:10Z"), "tie": (current, current), "missing": (current, None), | ||
| "fractional-review": ("12:00:00.1234569Z", "12:00:00.1234561Z"), | ||
| "fractional-newer": (current, "12:00:00.250Z"), | ||
| "offset-tie": ("12:00:00+00:00", "11:00:00-01:00"), | ||
| "offset-older": ("13:00:00+01:00", "13:59:59+02:00"), | ||
| "naive-check": (current, "11:59:00"), "malformed-check": (current, "12:00:00+00:60"), | ||
| "naive-review": ("12:00:00", earlier), "malformed-review": ("bad", earlier), | ||
| "missing-review": (None, earlier), | ||
| }.get(new_failure, (current, earlier)) | ||
| review_at, failed_at = (f"2026-09-23T{value}" if value else None for value in (review_time, failure_time)) | ||
| 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 = (formatdate(server_now, usegmt=True) if server_timeline | ||
| else "Wed, 23 Sep 2026 12:00:05 +0060") | ||
| gh.respond(reviews_key(), f"HTTP/2 200 OK\nDate: {date}\n\n{json.dumps(reviews)}") | ||
| offsets = {"server-host-behind": -40, "server-host-ahead": 1000, "server-old-review": -40} | ||
| start = server_now + offsets.get(new_failure, 0) | ||
| 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" | ||
|
|
@@ -2977,10 +2984,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 == [9.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 | ||
|
|
@@ -2989,20 +2999,15 @@ def advance(): | |
| ) | ||
|
|
||
|
|
||
| def test_ready_wait_stops_if_pr_head_moves(wt: Path, gh: FakeGh, capsys, monkeypatch, head) -> None: | ||
| body = "# T1\n\n## Review\n" | ||
| gh.respond_pr_list([pr_json(headRefOid=head, body=body, isDraft=False)], | ||
| [pr_json(headRefOid="f" * 40, body=body, isDraft=False)]) | ||
| gh.respond_pr_view( pr_json(headRefOid="f" * 40, body=body, isDraft=False)) | ||
| def test_ready_wait_stops_if_pr_head_moves(wt, gh, capsys, monkeypatch, head): | ||
| moved = "f" * 40 | ||
| gh.respond_pr_list([pr_json(headRefOid=head, isDraft=False)], [pr_json(headRefOid=moved, isDraft=False)]) | ||
| gh.respond_pr_view(pr_json(headRefOid=moved, isDraft=False)) | ||
| gh.respond(reviews_key(), [rev(head, "primary")]) | ||
| arm_readiness(gh, head, wt, conclusion="pending") | ||
|
|
||
| monkeypatch.setattr(cli, "_sleep", lambda _: None) | ||
| code, out, err = run(capsys, "ready", "--wait") | ||
|
|
||
| out = without_accepted_receipt(out) | ||
| assert code == 1 and "waiting:" in out | ||
| assert f"PR head changed while waiting: {head[:12]} to {'f' * 12}" in err | ||
| expect_cli(capsys, 1, "ready", "--wait", stdout_contains=("waiting:",), | ||
| stderr_contains=(f"PR head changed while waiting: {head[:12]} to {moved[:12]}",)) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("running", [False, True], ids=["missing-ci", "late-required-job"]) | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
**suggestion: Response Date reaches the caller through untyped kwargs and an output list
To get the HTTP Date to
_readiness, the change adds**kwargsto_rest_rows,_pr_reviews,api_getand_gh_json, and adds adatesoutput list to_gh._readinessthen builds the call with**({"dates": dates} if workflow_wait else {}). Type checking can no longer see these keyword arguments, so a misspelled keyword would only fail at runtime inside_gh. Every page also overwrites the list as a side effect. The behaviour is correct today. A smaller fix: give_rest_rows,_pr_reviews,api_getand_gh_jsonan explicitdates: list[str] \| None = Noneparameter and passdates=datesunconditionally. Collecting the Date outside waits costs nothing, so the conditional dict-splat can go.