Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
3eca5fd
Keep hosted eligibility pending during GitHub outages
eowca Nov 26, 2026
d26ca8b
Keep hosted eligibility pending during GitHub outages
eowca Nov 26, 2026
9d9d15f
Retry safe GitHub observations once within their budget
eowca Nov 26, 2026
ffd6ed9
Merge branch 'lean178/1502-safe-observation-retry' into lean178/1509-…
eowca Nov 26, 2026
44e7683
Expect one retry for idempotent finding resolution
eowca Nov 26, 2026
9b2fdeb
Keep hosted refresh failures observable before pending publication
eowca Nov 26, 2026
71a4432
Merge remote-tracking branch 'origin/main' into lean178/1497-eligibil…
eowca Nov 26, 2026
71a8ff7
Preserve genuine missing-object failures during candidate fetch
eowca Nov 26, 2026
67df7d4
Merge branch 'lean178/1497-eligibility-outages' into lean178/1502-saf…
eowca Nov 26, 2026
da45c03
Merge remote-tracking branch 'origin/main' into lean178/1502-safe-obs…
eowca Nov 26, 2026
2fb45fa
Reconcile eligibility dispatch after finding resolution
eowca Nov 26, 2026
9d0988c
Merge branch 'lean178/1502-safe-observation-retry' into lean178/1509-…
eowca Nov 26, 2026
0234af9
Recognize HTTP outages in Git fetch diagnostics
eowca Nov 26, 2026
2cd175e
Merge branch 'lean178/1497-eligibility-outages' into lean178/1502-saf…
eowca Nov 26, 2026
c3de7fd
Merge branch 'lean178/1502-safe-observation-retry' into lean178/1509-…
eowca Nov 26, 2026
1aae039
Keep hosted eligibility pending during GitHub outages
eowca Nov 26, 2026
0c68daf
Keep hosted refresh failures observable before pending publication
eowca Nov 26, 2026
b945542
Preserve genuine missing-object failures during candidate fetch
eowca Nov 26, 2026
db8a695
Recognize HTTP outages in Git fetch diagnostics
eowca Nov 26, 2026
6c65b6a
Keep retry timing scoped to its follow-up change
eowca Nov 26, 2026
251719a
Merge branch 'lean178/1497-eligibility-outages-v2' into lean178/1502-…
eowca Nov 26, 2026
e780406
Merge remote-tracking branch 'origin/main' into lean178/1502-safe-obs…
eowca Nov 26, 2026
98d04b1
Merge branch 'lean178/1502-safe-observation-retry' into lean178/1509-…
eowca Nov 26, 2026
1e7cd89
Merge remote-tracking branch 'origin/main' into lean178/1502-safe-obs…
eowca Nov 26, 2026
c1d8bb7
Preserve the trusted-publisher fixture on the retry branch
eowca Nov 26, 2026
6ac05fd
Keep GitHub write timeouts outside read deadlines
eowca Nov 26, 2026
edccfe5
Merge branch 'lean178/1502-safe-observation-retry' into lean178/1509-…
eowca Nov 26, 2026
97aafaa
Merge remote-tracking branch 'origin/main' into lean178/1509-recover-…
eowca Nov 26, 2026
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 @@ -1726,7 +1726,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 @@ -1750,7 +1751,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 @@ -1129,13 +1129,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 after one 5 s wait still allows a duplicate dispatch

since comes from the local clock, and _eligibility_dispatched returns False whenever the filtered list is empty. That can be wrong in two cases: (a) the local clock runs ahead of GitHub's, so a run that was accepted has created_at < since and is filtered out; (b) GitHub creates the run asynchronously after the dispatch is accepted, and it can take longer than RETRY_DELAY during the same incident that caused the 5xx or timeout. Either way the code dispatches a second time. The run uses a non-cancelling concurrency group, so the duplicate is mostly harmless. Still, the acceptance asks that observations which cannot rule out an accepted refresh do not authorize another one. Smallest fix: move since back by a small skew margin (e.g. 30–60 s). Any extra runs this picks up are refreshes of the same PR, which count as success anyway. Also state in a comment that an empty list is treated as best-effort evidence.

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: Second transient check repeats _gh classification

_gh raises GhUnavailable only for a transient failure or a rate limit. Running _transient_error(exc.tail, False) again re-parses the tail text to tell those apart, and it ignores the HTTP status that _gh used. If a 5xx response has stderr without an HTTP 5xx line, it gets misclassified as non-transient. This also means two copies of the classification can drift apart. Prefer one signal: for example, have _gh raise a distinct rate-limit subclass, or check for rate limiting here directly, rather than re-deriving transience from the text.

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
40 changes: 20 additions & 20 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4016,35 +4016,35 @@ 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)

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: Test patches the global time.time

monkeypatch.setattr(github.time, "time", ...) replaces time.time on the shared time module, not just in github. Every caller during the test sees the frozen value, including app-token aging, _rate_limit_delay and _graphql_reset. monkeypatch restores it afterwards, but this can hide clock-dependent behaviour inside the test. Freezing a module-level clock seam in github (like _retry_sleep) would keep the effect scoped.

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)})
code, out, err = run(capsys, "resolve")
assert (code, err) == (0, "") and out == "0b9b59e7 important src/a.py:3 Off by one\n"
assert (code, err, out) == (0, "", "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