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
1 change: 1 addition & 0 deletions .github/workflows/eligibility.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
name: review eligibility
run-name: "${{ inputs.pr && format('Refresh eligibility for PR #{0}', inputs.pr) || '' }}"
on:
pull_request_target:
types: [opened, synchronize, reopened, edited, ready_for_review, converted_to_draft, labeled, unlabeled]
Expand Down
3 changes: 3 additions & 0 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,9 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con
delegated or input-keyed checks binds the configured base branch. Only the
stage reuse key binds the exact base revision. Source-check waiters check for policy
changes on every poll.
Local readiness and hosted eligibility share the mergeability verdict.
Hosted source refresh retries an unknown result on the same head before
leaving it pending.
Local readiness and hosted eligibility carry a review forward only across
a first-parent chain of verified merges from the configured PR base. They
reconstruct each merge in an isolated Git repository and compare its tree
Expand Down
9 changes: 4 additions & 5 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ def _review_cap_reason(config: Config, pr: github.PR, head: str, reviews: list[d
)


MERGEABILITY_PENDING = "GitHub is computing mergeability"
MERGEABILITY_PENDING = github.MERGEABILITY_PENDING


def _readiness_precheck(wt: Path, config: Config, pr: github.PR, head: str, diagnostics: bool) -> str | None:
Expand Down Expand Up @@ -355,8 +355,6 @@ def _readiness(
result = dataclasses.replace(result, reasons=tuple(
exhausted if reason == github.MISSING_REVIEW_REASON else reason for reason in result.reasons
))
if pr.state == "OPEN" and pr.mergeable == "UNKNOWN":
result = dataclasses.replace(result, ready=False, reasons=(*result.reasons, MERGEABILITY_PENDING))
report = _load_report(wt)
receipt_problem = _check_report_problem(report, config, head)
if receipt_problem:
Expand Down Expand Up @@ -1862,7 +1860,8 @@ def _delete_tracking_ref(wt: Path, branch: str, expected_head: str) -> None:
def cmd_resolve(args: argparse.Namespace) -> int:
encoding = getattr(sys.stdout, "encoding", None) or "utf-8"
wt, config = _context(args, pin_checks=True) # publishers come from the base, not the PR
pr = _require_pr(config, worktree.branch(wt))
branch = worktree.branch(wt)
pr = _require_pr(config, branch)
if pr.base_ref != config.base_branch: # trusted publishers belong to the configured base
raise CliError(f"PR #{pr.number} targets {pr.base_ref}, configured base is {config.base_branch}")
publishers = config.review_publishers or (github.login(),)
Expand All @@ -1886,7 +1885,7 @@ def cmd_resolve(args: argparse.Namespace) -> int:
f"Then, if no findings remain, run `{retry}`."
) from exc
if not remaining:
github.refresh_eligibility(config.repo, pr.number, config.base_branch)
github.refresh_eligibility(config.repo, pr, branch, config.base_branch, publishers)
print(f"refreshed Loop-zero Eligibility for PR #{pr.number}")
return 0

Expand Down
18 changes: 16 additions & 2 deletions src/loopzero/eligibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import sys
from collections.abc import Callable
from pathlib import Path
from time import sleep

from loopzero import candidate, config, github, runners
from loopzero.types import LoopZeroError
Expand Down Expand Up @@ -197,12 +198,22 @@ def source_fingerprint(pr: github.PR) -> tuple[object, ...]:
github.merge_hold(pr.number, pr.labels))


def source_snapshot(repo: str, number: int, head: str, pr: github.PR | None = None) -> github.PR:
pr = pr if pr is not None else github.pr_view(repo, number)
for delay in (2, 4, 8):
if pr.head_sha != head or github.mergeability_blocker(pr) != github.MERGEABILITY_PENDING:
break
sleep(delay)
pr = github.pr_view(repo, number)
return pr


def evaluate(repo: str, number: int, head: str, base: str,
publishers: tuple[str, ...], *, snapshot: github.PR | None = None) -> github.Readiness:
"""Evaluate live review evidence. Callers supplying a snapshot own the final source check."""
if not publishers or not re.fullmatch(r"[0-9a-f]{40}", head):
raise LoopZeroError("eligibility requires trusted publishers and a full source SHA")
pr = snapshot if snapshot is not None else github.pr_view(repo, number)
pr = snapshot if snapshot is not None else source_snapshot(repo, number, head)
if pr.number != number or pr.head_sha != head:
return github.Readiness(False, ("source head changed; refresh eligibility",))
if hold := github.merge_hold(pr.number, pr.labels):
Expand All @@ -224,8 +235,11 @@ def evaluate(repo: str, number: int, head: str, base: str,
result = github.readiness(repo, pr, base, (), head if review else None, allow_behind=True,
ancestor_review=review is not None and review["commit_id"] != head,
publishers=publishers)
if snapshot is None and source_fingerprint(github.pr_view(repo, number)) != source_fingerprint(pr):
current = github.pr_view(repo, number) if snapshot is None else pr
if snapshot is None and source_fingerprint(current) != source_fingerprint(pr):
return github.Readiness(False, ("source changed during eligibility refresh",))
if snapshot is None and result.ready and (blocker := github.mergeability_blocker(current)):
return github.Readiness(False, (blocker,))
return result


Expand Down
52 changes: 46 additions & 6 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
PR_LOCK_DIR = Path.home() / ".cache/loopzero/pr-locks"
_app_token_cache = ("", 0.0)
MISSING_REVIEW_REASON = "no review recorded for the current head"
MERGEABILITY_PENDING = "GitHub is computing mergeability"
MARKER_RE = re.compile(
r"<!-- loopzero:finding v=1 severity=(?P<severity>\w+) "
r"head=(?P<head>[0-9a-f]{40}) id=(?P<id>[0-9a-f]{8}) -->"
Expand Down Expand Up @@ -1138,13 +1139,44 @@ def eligibility_dispatch_args(repo: str, number: int, base: str) -> tuple[str, .
"-f", f"ref={base}", "-f", f"inputs[pr]={number}")


def refresh_eligibility(repo: str, number: int, base: str) -> None:
args = eligibility_dispatch_args(repo, number, base)
def _eligibility_dispatched(repo: str, number: int, base: str, since: str) -> bool:
query = f"event=workflow_dispatch&branch={quote(base, safe='')}&created={quote('>=' + since, safe='')}&per_page=100"
data = api_get(f"repos/{repo}/actions/workflows/eligibility.yml/runs?{query}")
runs = data.get("workflow_runs") if isinstance(data, dict) else None
complete = isinstance(runs, list) and data.get("total_count") == len(runs)
identified = [run.get("display_title") if isinstance(run, dict) else None for run in runs] if complete else []
if f"Refresh eligibility for PR #{number}" in identified:
return True
if not complete or any(not isinstance(name, str) or not re.fullmatch(r"Refresh eligibility for PR #[0-9]+", name) for name in identified):
raise GhError(("refresh Loop-zero Eligibility",), "could not identify all recent refresh runs")
return False


def refresh_eligibility(repo: str, pr: PR, branch: str, base: str, publishers: tuple[str, ...]) -> None:
args = eligibility_dispatch_args(repo, pr.number, base)
since = datetime.fromtimestamp(time.time(), UTC).isoformat(timespec="seconds")
try:
_gh(*args)
try:
_gh(*args)
except (GhUnavailable, ProcTimeout) as exc:
if isinstance(exc, GhUnavailable) and not _transient_error(exc.tail, False):
raise
_retry_sleep(RETRY_DELAY)
current = pr_for_branch(repo, branch, open_only=True)
if current is None or (current.number, current.head_sha, current.base_ref) != (
pr.number, pr.head_sha, pr.base_ref,
):
raise GhError(("refresh Loop-zero Eligibility",), "the PR or head changed after resolution") from exc
if _eligibility_dispatched(repo, pr.number, base, since):
return
if open_blocking_findings(repo, pr.number, None, publishers):
raise GhError(("refresh Loop-zero Eligibility",), "blocking findings appeared after resolution") from exc
_gh(*args)
except (GhError, ProcTimeout, OSError) as exc:
retry = shlex.join(("gh", *args))
raise GhError(("refresh Loop-zero Eligibility",), f"{exc}\nRun manually: {retry}") from exc
raise GhError(("refresh Loop-zero Eligibility",),
f"Finding on PR #{pr.number} is resolved. {exc}\n"
f"Verify the PR head, remaining findings and recent runs before retrying: {retry}") from exc


def open_blocking_findings(
Expand Down Expand Up @@ -1323,6 +1355,14 @@ def behind_reason(pr: PR, reviewed_head: str | None) -> str:
)


def mergeability_blocker(pr: PR) -> str | None:
if pr.mergeable == "CONFLICTING":
return f"PR #{pr.number} has merge conflicts with {pr.base_ref}"
if pr.state == "OPEN" and pr.mergeable == "UNKNOWN":
return MERGEABILITY_PENDING
return None


def readiness(
repo: str,
pr: PR,
Expand All @@ -1342,8 +1382,8 @@ def readiness(
reasons.append(f"PR #{pr.number} is {pr.state}, not open")
if pr.base_ref != base_branch:
reasons.append(f"PR targets {pr.base_ref}, configured base is {base_branch}")
if pr.mergeable == "CONFLICTING":
reasons.append(f"PR #{pr.number} has merge conflicts with {pr.base_ref}")
if blocker := mergeability_blocker(pr):
reasons.append(blocker)
if pr.merge_state == "BEHIND" and not allow_behind:
reasons.append(behind_reason(pr, reviewed_head))
if not reviewed_head:
Expand Down
43 changes: 28 additions & 15 deletions src/loopzero/hosted.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,19 @@ def _candidate_event(event: dict, head: str) -> bool:
return True


def _source_status(result: github.Readiness, current: github.PR) -> tuple[str, str]:
reasons = result.reasons
if result.ready:
if not (blocker := github.mergeability_blocker(current)):
return "success", "Reviewed source head"
reasons = (blocker,)
if reasons and set(reasons) <= {github.MISSING_REVIEW_REASON, github.MERGEABILITY_PENDING}:
if github.MISSING_REVIEW_REASON in reasons:
return "pending", "Awaiting trusted review of current source head"
return "pending", github.MERGEABILITY_PENDING
return "failure", "; ".join(reasons)


def _run(cfg: Config) -> int:
if cfg.repo != os.environ.get("GITHUB_REPOSITORY") or not cfg.review_publishers:
raise LoopZeroError("trusted repository configuration or review publishers missing")
Expand Down Expand Up @@ -94,18 +107,15 @@ def policy(source_number: int, source: dict) -> None:
f"{owner}/{repo}", f"/merge-queue/status?branch={quote(branch, safe='')}"),
source_policy=policy,
)
ready, message = True, "All attested candidate sources are reviewed"
else:
snapshot = github.pr_from_rest(pr)
snapshot = eligibility.source_snapshot(cfg.repo, number, head, github.pr_from_rest(pr))
result = eligibility.evaluate(cfg.repo, number, head, cfg.base_branch, cfg.review_publishers,
snapshot=snapshot)
ready, message = result.ready, "; ".join(result.reasons) or "Reviewed source head"
if _landed_before_publication(cfg.repo, number, head, snapshot):
current = _publication_snapshot(cfg.repo, number, head, snapshot)
if current is None:
return 0
state = "success" if ready else "failure"
if not candidate and not ready and result.reasons == (github.MISSING_REVIEW_REASON,):
message = "Awaiting trusted review of current source head"
state = "pending"
state, message = (("success", "All attested candidate sources are reviewed") if candidate
else _source_status(result, current))
except (github.GhUnavailable, github.ProcTimeout) as exc:
print(f"Eligibility pending: evidence unavailable ({exc})", file=sys.stderr)
return 0
Expand All @@ -114,18 +124,21 @@ def policy(source_number: int, source: dict) -> None:
raise
_publish_verdict(cfg.repo, head, state, message[:140])
print(message)
return 0 if ready or state == "pending" else 1
return int(state == "failure")


def _landed_before_publication(repo: str, number: int, head: str, snapshot: github.PR | None) -> bool:
def _publication_snapshot(
repo: str, number: int, head: str, snapshot: github.PR | None,
) -> github.PR | None:
current = github.pr_view(repo, number)
if current.head_sha != head:
raise LoopZeroError("head changed before publication; refresh eligibility")
if snapshot is None or current.state == "MERGED":
return snapshot is not None
if eligibility.source_fingerprint(current) != eligibility.source_fingerprint(snapshot):
raise LoopZeroError("source metadata changed before publication; refresh eligibility")
return False
if snapshot is not None:
if current.state == "MERGED":
return None
if eligibility.source_fingerprint(current) != eligibility.source_fingerprint(snapshot):
raise LoopZeroError("source metadata changed before publication; refresh eligibility")
return current


def _publish_verdict(repo: str, head: str, state: str, description: str) -> None:
Expand Down
29 changes: 17 additions & 12 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4022,14 +4022,20 @@ def finding_pr(wt, gh, head):
THREAD_RESOLVED = {"data": {"resolveReviewThread": {"thread": {"isResolved": True}}}}


@pytest.mark.parametrize("outcome", ["refreshed", "remaining", "dispatch failed"])
def test_resolve_lists_then_replies_and_resolves_one_finding(finding_pr, gh: FakeGh, capsys, outcome) -> None:
@pytest.mark.parametrize("outcome", ["refreshed", "remaining", "denied", "applied", "retry", "unknown"])
def test_resolve_lists_then_replies_and_resolves_one_finding(finding_pr, gh: FakeGh, capsys, monkeypatch, outcome) -> None:
sys.stdout.reconfigure(encoding="ascii" if outcome == "refreshed" else "utf-8", errors="strict")
finding_pr["comments"]["nodes"][0]["body"] = finding_pr["comments"]["nodes"][0]["body"].replace("Off by one", "Łódź")
listing = threads_json({**finding_pr, "path": "src/Łódź.py"})
listing, backoffs = threads_json({**finding_pr, "path": "src/Łódź.py"}), []
gh.respond("api graphql", listing, listing, REPLY_ACCEPTED, THREAD_RESOLVED,
listing if outcome == "remaining" else threads_json())
gh.respond("api -X", "", exit=int(outcome == "dispatch failed"), stderr="HTTP 403")
transient = outcome in {"applied", "retry", "unknown"}
gh.respond("api -X", {"stdout": "", "exit": 1, "stderr": "HTTP 503" if transient else "HTTP 403"} if transient or outcome == "denied" else "", "")
monkeypatch.setattr(github, "_retry_sleep", backoffs.append)
runs = [] if outcome == "retry" else [{"display_title": "Refresh eligibility for PR #7" if outcome == "applied" else "unknown"}]
monkeypatch.setattr(github.time, "time", lambda: 1795640554)
endpoint = ELIGIBILITY_DISPATCH.removesuffix("/dispatches")
gh.respond(f"api {endpoint}/runs?event=workflow_dispatch&branch=main&created=%3E%3D2026-11-25T21%3A02%3A34%2B00%3A00&per_page=100", {"workflow_runs": runs, "total_count": len(runs)})
title = r"\u0141\xf3d\u017a" if outcome == "refreshed" else "Łódź"
expect_cli(capsys, 0, "resolve", stderr="", stdout=f"0b9b59e7 important src/{title}.py:3 {title}\n")
assert not any("eligibility.yml/dispatches" in " ".join(c["argv"]) for c in gh.calls)
Expand All @@ -4040,15 +4046,14 @@ def test_resolve_lists_then_replies_and_resolves_one_finding(finding_pr, gh: Fak
assert "addPullRequestReviewThreadReply" in calls[0][3] and "resolveReviewThread" in calls[1][3]
assert "body=Fixed in abc1234: loop bound corrected." in calls[0] and "thread=THREAD_1" in calls[1]
dispatches = [c["argv"] for c in gh.calls if ELIGIBILITY_DISPATCH in c["argv"]]
if outcome == "remaining":
assert (code, err, dispatches, len(out.splitlines())) == (0, "", [], 1)
assert dispatches == [["api", "-X", "POST", ELIGIBILITY_DISPATCH, "-f", "ref=main", "-f", "inputs[pr]=7", "--include"]] * {"remaining": 0, "retry": 2}.get(outcome, 1)
assert backoffs == ([5] if transient else [])
if outcome in {"denied", "unknown"}:
assert code == 1 and "is resolved." in err and ("HTTP 403" if outcome == "denied" else "identify all recent refresh runs") in err
assert f"gh api -X POST {ELIGIBILITY_DISPATCH} -f ref=main -f 'inputs[pr]=7'" in err
else:
assert dispatches == [["api", "-X", "POST", ELIGIBILITY_DISPATCH, "-f", "ref=main", "-f", "inputs[pr]=7", "--include"]]
if outcome == "refreshed":
assert (code, err) == (0, "") and out.splitlines()[-1] == "refreshed Loop-zero Eligibility for PR #7"
else:
assert code == 1 and "HTTP 403" in err
assert f"gh api -X POST {ELIGIBILITY_DISPATCH} -f ref=main -f 'inputs[pr]=7'" in err
assert (code, err) == (0, "")
assert out.splitlines()[1:] == ([] if outcome == "remaining" else ["refreshed Loop-zero Eligibility for PR #7"])


@pytest.mark.parametrize("cut", ["reply", "resolution"])
Expand Down
Loading
Loading