Repository navigation
Compare readiness using GitHub timestamps #1198
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
3a241dc
3ca6df4
159b375
da40f81
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 |
|---|---|---|
|
|
@@ -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 | ||
|
|
||
|
|
@@ -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]: | ||
| """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 | ||
|
|
@@ -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) | ||
|
|
@@ -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, | ||
|
|
@@ -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: | ||
|
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: Refactor duplicates the headers initialisation without changing behaviour Behaviour is the same before and after this change. In both versions |
||
| 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) | ||
|
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: Server Date comes from the last reviews page, and only on the wait path Headers are captured only when |
||
| 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) | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
|
@@ -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" | ||
|
|
@@ -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 | ||
|
|
||
|
|
||
|
|
@@ -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: | ||
|
|
@@ -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: | ||
|
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: api_get duplicates the _gh_json call just to avoid passing response_headers=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() | ||
|
|
@@ -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: | ||
|
|
@@ -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]) | ||
|
|
@@ -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, | ||
|
|
||
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: 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**kwargsjust to passresponse_headersthrough. This drops type checking, so a typo such asresponse_header=reaches_ghand only fails at runtime there. Smallest fix: declare an explicit keyword-only parameterresponse_headers: dict[str, str] | None = Noneon each of these functions.