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
8 changes: 8 additions & 0 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -1451,6 +1451,14 @@ def commit_status(repo: str, head: str, context: str, state: str, description: s
raise


def status_matches(repo: str, head: str, context: str, state: str, description: str) -> bool:
statuses = _iter_paged(f"repos/{repo}/commits/{head}/statuses")
latest = next((row for row in statuses if row.get("context") == context), {})
creator = latest.get("creator")
return (isinstance(creator, dict) and creator.get("login") == "github-actions[bot]"
and (latest.get("state"), latest.get("description")) == (state, description))


def _status_limit_reached(repo: str, head: str, context: str) -> bool:
# A validation error alone does not prove exhaustion.
with suppress(GhError, ProcTimeout, OSError):
Expand Down
19 changes: 16 additions & 3 deletions src/loopzero/hosted.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,25 @@ def policy(source_number: int, source: dict) -> None:
if not candidate and not ready and result.reasons == (github.MISSING_REVIEW_REASON,):
message = "Awaiting trusted review of current source head"
state = "pending"
publish(state, message)
print(message)
return 0 if ready or state == "pending" else 1
except Exception as exc:
_mark_refresh_failed(publish, exc)
raise
_publish_verdict(cfg.repo, head, state, message[:140])

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: A failed verdict write that is definitely not accepted now leaves the stale 'Refreshing…' pending status

Before this change, any failed final write (e.g. HTTP 422 invalid description, 403, 5xx) went through _mark_refresh_failed, so the context ended as failure: Eligibility refresh failed. Now _publish_verdict runs outside the try block. When the read-back shows the verdict is not the latest status, it raises LoopZeroError without writing anything. The commit is left at pending: Refreshing live source review evidence (the updated publication test now expects ["pending", "pending"]). This is fail-closed, so it is not unsafe. However, the status claims a refresh is still running when the job has already failed. A read-back that proves the latest status is not our verdict is a safe point to write the refresh-failed marker, because there is no accepted verdict to overwrite. Smallest fix: have status_matches tell 'confirmed absent' apart from 'unreadable', and on 'confirmed absent' call _mark_refresh_failed before raising. Alternatively, record in the task or a comment that a stale pending is the intended outcome.

print(message)
return 0 if ready or state == "pending" else 1


def _publish_verdict(repo: str, head: str, state: str, description: str) -> None:
context = eligibility.CONTEXT
try:
github.commit_status(repo, head, context, state, description)
except github.StatusLimitReached:
raise
except (github.GhError, github.ProcTimeout, OSError) as exc:
with suppress(github.GhError, github.ProcTimeout, OSError):
if github.status_matches(repo, head, context, state, description):
return
raise LoopZeroError(f"Could not confirm eligibility status publication: {exc}") from exc


def _mark_refresh_failed(publish: Callable[[str, str], None], exc: Exception) -> None:
Expand Down
41 changes: 40 additions & 1 deletion tests/test_hosted.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,45 @@ def test_merged_source_refresh_publishes_nothing(publisher):
assert hosted.main() == 0 and not [c for c in publisher.calls if "--input" in c] and publisher.argv(0)[-1] == "--include"


@pytest.mark.parametrize("state,readback", [
("success", "match"), ("failure", "match"), ("success", "absent"),
("success", "publisher"), ("success", "description"), ("success", "state"),
("success", "unreadable"),
])
def test_final_status_lost_reply(publisher, monkeypatch, state, readback):
ready = state == "success"
monkeypatch.setattr(hosted.eligibility, "evaluate",
lambda *_: github.Readiness(ready, () if ready else ("Blocking finding",)))
post = github.commit_status
endpoint = f"api repos/{REPO}/commits/{HEAD}/statuses"
monkeypatch.setattr(github, "_retry_sleep", lambda _: None)

def lose_reply(repo, head, context, value, description):
post(repo, head, context, value, description)
if description.startswith(("Refreshing", "Eligibility refresh failed")):
return
accepted = {"context": context, "state": value, "description": description,
"creator": {"login": "github-actions[bot]"}}
assert value == state
observed = {
"absent": [],
"publisher": [accepted | {"creator": {"login": "other"}}, accepted],
"description": [accepted | {"description": "other"}, accepted],
"state": [accepted | {"state": "pending"}, accepted],
"unreadable": {"exit": 1, "stderr": "unavailable"},
}.get(readback, [accepted])
publisher.respond(endpoint, observed)
raise github.ProcTimeout("lost status reply", "")

monkeypatch.setattr(github, "commit_status", lose_reply)
if readback == "match":
assert hosted.main() == (0 if ready else 1)
else:
with pytest.raises(hosted.LoopZeroError, match="confirm eligibility status publication"):
hosted.main()
assert [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] == ["pending", state]


@pytest.mark.parametrize("error", ["api", "head", "publication", "config"])
def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, error):
monkeypatch.setattr(github, "_retry_sleep", lambda _: None)
Expand All @@ -124,7 +163,7 @@ def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, er
if error == "publication":
assert "invalid description (HTTP 422)" in str(raised.value)
statuses = [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c]
assert statuses == ([] if error == "config" else ["pending", "pending", "failure"]
assert statuses == ([] if error == "config" else ["pending", "pending"]
if error == "publication" else ["pending", "failure"])


Expand Down
Loading