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
5 changes: 3 additions & 2 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1868,7 +1868,8 @@ def _delete_tracking_ref(wt: Path, branch: str, expected_head: str) -> None:
def cmd_resolve(args: argparse.Namespace) -> int:
"""List open blocking findings, or reply to one with what changed and resolve its thread."""
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 @@ -1892,7 +1893,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
39 changes: 35 additions & 4 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -1139,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
38 changes: 19 additions & 19 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4073,34 +4073,34 @@ 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:
listing = threads_json(finding_pr)
remaining = listing if outcome == "remaining" else threads_json()
gh.respond("api graphql", listing, listing, REPLY_ACCEPTED, THREAD_RESOLVED, remaining)
gh.respond("api -X", "", exit=int(outcome == "dispatch failed"), stderr="HTTP 403")

@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):
listing, backoffs = threads_json(finding_pr), []
gh.respond("api graphql", listing, listing, REPLY_ACCEPTED, THREAD_RESOLVED, listing if outcome == "remaining" else threads_json())
endpoint = f"repos/{REPO}/actions/workflows/eligibility.yml"
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)
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)})
expect_cli(capsys, 0, "resolve", stderr="", stdout="0b9b59e7 important src/a.py:3 Off by one\n")
assert not any("eligibility.yml/dispatches" in " ".join(c["argv"]) for c in gh.calls)

code, out, err = run(capsys, "resolve", "0b9b59e7", "Fixed in abc1234: loop bound corrected.")
assert out.splitlines()[0] == "resolved 0b9b59e7: Off by one"
calls = [c["argv"] for c in gh.calls
if c["argv"][:2] == ["api", "graphql"] and "viewer {" not in c["argv"][3]][2:]
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]
endpoint = f"repos/{REPO}/actions/workflows/eligibility.yml/dispatches"
dispatches = [c["argv"] for c in gh.calls if endpoint in c["argv"]]
if outcome == "remaining":
assert (code, err, dispatches) == (0, "", [])
assert len(out.splitlines()) == 1
dispatches = [c["argv"] for c in gh.calls if f"{endpoint}/dispatches" in c["argv"]]
assert dispatches == [["api", "-X", "POST", f"{endpoint}/dispatches", "-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 {endpoint}/dispatches -f ref=main -f 'inputs[pr]=7'" in err
else:
assert dispatches == [["api", "-X", "POST", endpoint, "-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 {endpoint} -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