Skip to content
Merged
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 @@ -1862,7 +1862,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 +1887,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 @@ -1138,13 +1138,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")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: An empty run list is treated as proof that no dispatch happened, but it may only mean the run isn't visible yet

since comes from the local clock, and the lookup runs only 5 s after the failed POST. If the POST actually went through, two things can hide that run: (1) the local clock is ahead of GitHub's clock by more than the dispatch latency, so created>=since filters the run out; (2) GitHub creates workflow_dispatch runs asynchronously, and listing can lag. That lag is most likely during the same 5xx incidents that trigger this path. In either case _eligibility_dispatched returns False and a second dispatch goes out. The duplicate is mostly harmless because the source job's concurrency group queues it with cancel-in-progress: false. Still, it contradicts the note that an observation you can't trust should not authorize a duplicate. Smallest fix: before treating an empty list as absence, either take since from a server-side timestamp (for example the Date header of the PR read), or subtract a small margin and keep only same-PR runs whose created_at is after the resolution. At minimum, document the residual risk.

try:
_gh(*args)
try:
_gh(*args)
except (GhUnavailable, ProcTimeout) as exc:
if isinstance(exc, GhUnavailable) and not _transient_error(exc.tail, False):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: The transient check repeats a decision _gh already made

_gh raises GhUnavailable for a non-read request only when the error was rate limited or transient. Re-running _transient_error(exc.tail, False) is only there to drop the rate-limit case, and nothing says so. Add a short comment, or have _gh mark rate-limit failures explicitly, so the two classifications can't silently drift apart.

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",),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: The final error repeats "refresh Loop-zero Eligibility failed"

The head-changed, findings-appeared and could-not-identify errors are raised as GhError(("refresh Loop-zero Eligibility",), ...). The outer handler wraps them again with the same command tuple, so the user sees refresh Loop-zero Eligibility failed: Finding on PR #7 is resolved. refresh Loop-zero Eligibility failed: .... Fix: raise the inner errors with a plain message (for example a ValueError caught by the outer handler), or use exc.tail when exc already carries this command.

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
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