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
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
4 changes: 1 addition & 3 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
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

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: Snapshot-less recheck uses a conditional assignment that both later guards repeat

current = github.pr_view(...) if snapshot is None else pr is followed by two separate if snapshot is None and ... checks. When a snapshot is supplied, current is never used, so the ternary branch does nothing and the same condition is checked three times. A single if snapshot is None: block that fetches current, compares fingerprints, and then applies mergeability_blocker(current) when result.ready would behave the same and be easier to read. Behaviour is correct as written: hosted callers that pass a snapshot get the same mergeability recheck in _publication_snapshot and _source_status.

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
13 changes: 11 additions & 2 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 @@ -1323,6 +1324,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 +1351,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 @@ -62,6 +62,19 @@ def _candidate_event(event: dict, head: str) -> bool:
return True


def _source_status(result: github.Readiness, current: github.PR) -> tuple[str, str]:

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: Mergeability re-check is duplicated between evaluate and _source_status

eligibility.evaluate already re-fetches the PR and turns a ready result into (blocker,) when mergeability_blocker(current) is set (eligibility.py:204-208). hosted._run then fetches the PR again and _source_status repeats the same check. The hosted re-fetch is needed for the head-change guard, but having the blocker check in two places invites drift. Consider keeping the mergeability check only in evaluate, so _source_status maps reasons to a state and does not need current.

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 @@ -93,18 +106,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 @@ -115,18 +125,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
39 changes: 20 additions & 19 deletions tests/test_hosted.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,7 @@ def test_eligibility_entry_points_report_malformed_config(tmp_path, module, args
({"workflow_run": {"pull_requests": [{"number": 7}, {"number": 8}]}}, None),
])
def test_event_selection(event, number):
if number is None:
with pytest.raises(hosted.LoopZeroError):
hosted.event_number(event)
else:
with pytest.raises(hosted.LoopZeroError) if number is None else nullcontext():
assert hosted.event_number(event) == number


Expand Down Expand Up @@ -90,38 +87,45 @@ def check_source(publisher, states, *, exit_code=0, error=None, match=None):
("stale", "", "pending"), ("malformed", "", "pending"),
("revoked", "", "pending"), ("absent", "important", "failure"),
("absent", "conflict", "failure"), ("COMMENTED", "important", "failure"),
("APPROVED", "unknown", "pending"), ("APPROVED", "settles", "success"),
])
def test_source_publication_is_bound_to_live_review(publisher, case, blocker, status):
def test_source_publication_is_bound_to_live_review(publisher, monkeypatch, case, blocker, status):
review = approval() | {"state": "COMMENTED"}
reviews = {
"absent": [], "APPROVED": [approval()], "revoked": [approval(), review | {"state": "DISMISSED"}],
"untrusted": [review | {"user": {"login": "attacker"}}], "stale": [approval("b" * 40)],
"malformed": [review | {"body": "<!-- loopzero:review invalid -->\n**approve**"}],
}.get(case, [review])
publisher.respond(f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1", reviews)
if blocker == "conflict":
publisher.respond(f"api repos/{REPO}/pulls/7", fixtures.rest_pr_json(pr_json(mergeable="CONFLICTING")))
delays = []
monkeypatch.setattr(hosted.eligibility, "sleep", delays.append)
if blocker in {"conflict", "unknown", "settles"}:
initial = pr_json(mergeable="CONFLICTING" if blocker == "conflict" else "UNKNOWN")
snapshots = [initial, pr_json()] if blocker == "settles" else [initial]
publisher.respond(f"api repos/{REPO}/pulls/7", *(fixtures.rest_pr_json(pr) for pr in snapshots))
if blocker == "important":
publisher.respond("api graphql", threads_json(fixtures.thread(fixtures.marker("important") + "\nFinding",
author="trusted-publisher")))
statuses = check_source(publisher, ["pending", status], exit_code=int(status == "failure"))
assert all(s["context"] == "Loop-zero Eligibility" for s in statuses)
assert status != "success" or sum(c["argv"][1] != "graphql" for c in publisher.calls) <= 5
assert status != "pending" or statuses[-1]["description"] == "Awaiting trusted review of current source head"
assert delays == {"unknown": [2, 4, 8], "settles": [2]}.get(blocker, [])
if status == "success":
assert sum(c["argv"][1] != "graphql" for c in publisher.calls) <= 5 + int(blocker == "settles")
if status == "pending":
expected = github.MERGEABILITY_PENDING if blocker == "unknown" else "Awaiting trusted review of current source head"
assert statuses[-1]["description"] == expected


@pytest.mark.parametrize("candidate", [False, True])
@pytest.mark.parametrize("change", ["exact", "ordinary", "clean merge"])
def test_hosted_review_coverage_after_source_head_changes(
publisher, git_repo, monkeypatch, candidate, change,
):
git(git_repo, "switch", "-qc", "source")
git(git_repo, "commit", "-qm", "reviewed source", "--allow-empty")
reviewed = git(git_repo, "rev-parse", "HEAD").strip()
git(git_repo, "switch", "-q", "main")
git(git_repo, "commit", "-qm", "base advance", "--allow-empty")
base = git(git_repo, "rev-parse", "HEAD").strip()
git(git_repo, "switch", "-q", "source")
git(git_repo, "switch", "-qc", "source", "HEAD^")
git(git_repo, "commit", "-qm", "reviewed source", "--allow-empty")
reviewed = git(git_repo, "rev-parse", "HEAD").strip()
if change == "ordinary":
git(git_repo, "commit", "-qm", "unreviewed source", "--allow-empty")
elif change == "clean merge":
Expand Down Expand Up @@ -365,7 +369,7 @@ def test_privileged_workflow_runs_only_the_trusted_default_branch_package():


@pytest.mark.parametrize("prior", [998, 999, 1000])
def test_source_status_limit(publisher, monkeypatch, capsys, prior):
def test_source_status_limit(publisher, capsys, prior):
context = hosted.eligibility.CONTEXT
endpoint = f"api repos/{REPO}/statuses/{HEAD}"
refused = {
Expand All @@ -383,10 +387,7 @@ def test_source_status_limit(publisher, monkeypatch, capsys, prior):
pages = [statuses[i:i + 100] for i in range(0, 1001, 100)]
publisher.respond(f"api repos/{REPO}/commits/{HEAD}/statuses", *pages, *pages)

monkeypatch.setattr(hosted.eligibility, "evaluate", lambda *args, **kwargs: SimpleNamespace(
ready=True, reasons=(),
))

publisher.respond(f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1", [approval()])
if prior == 998:
check_source(publisher, ["pending", "success"])
assert not any("/commits/" in " ".join(call["argv"]) for call in publisher.calls)
Expand Down
Loading