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
3 changes: 3 additions & 0 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,9 @@ PR writes. [Hosted dispatch](../src/loopzero/hosted.py) and
Local readiness and hosted source and candidate eligibility reject PRs with
merge-authority holds. Adding or removing a hold refreshes source eligibility
even when the head stays the same. Merge admission rechecks the live hold.
Hosted evaluation uses the source snapshot already fetched by dispatch or
candidate attestation. The caller rechecks the source fields that affect the
verdict before publication. Standalone evaluation performs its own PR reads.
[Mergify](MERGIFY.md) describes optional source-preserving queue integration;
[candidate validation](../src/loopzero/candidate.py) belongs at that boundary.
When delivery uses the existing size checker, local readiness and new Mergify
Expand Down
7 changes: 7 additions & 0 deletions src/loopzero/candidate.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,14 @@ def _source_fingerprint(source: JsonObject) -> tuple[object, ...]:
head = source.get("head")
base = source.get("base")
base_repo = base.get("repo") if isinstance(base, dict) else None
labels = source.get("labels", [])
if not isinstance(labels, list) or any(not isinstance(label, dict) or not isinstance(label.get("name"), str) for label in labels):
raise CandidateError("invalid source PR labels")
return (
source.get("number"),
source.get("merged"),
source.get("mergeable") is False,
tuple(label["name"] for label in labels),
source.get("state"),
source.get("draft"),
source.get("body"),
Expand Down
17 changes: 11 additions & 6 deletions src/loopzero/eligibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,13 +180,18 @@ def readiness_review(reviews: list[dict], head: str, publishers: tuple[str, ...]
return latest


def source_fingerprint(pr: github.PR) -> tuple[object, ...]:
return (pr.number, pr.head_sha, pr.base_ref, pr.state, pr.mergeable == "CONFLICTING",
github.merge_hold(pr.number, pr.labels))


def evaluate(repo: str, number: int, head: str, base: str,
publishers: tuple[str, ...]) -> github.Readiness:
"""Re-fetch reviews and threads; no local receipts, CI identity or source execution."""
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 = github.pr_view(repo, number)
if pr.head_sha != head:
pr = snapshot if snapshot is not None else github.pr_view(repo, number)
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):
return github.Readiness(False, (hold,))
Expand All @@ -207,8 +212,8 @@ 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 github.pr_view(repo, number).head_sha != head:
return github.Readiness(False, ("source head changed during eligibility refresh",))
if snapshot is None and source_fingerprint(github.pr_view(repo, number)) != source_fingerprint(pr):
return github.Readiness(False, ("source changed during eligibility refresh",))
return result


Expand Down
6 changes: 3 additions & 3 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -570,7 +570,7 @@ def _pr_labels(data: dict) -> tuple[str, ...]:
return tuple(label["name"] for label in data.get("labels", []))


def _pr_from_rest(data: object) -> PR:
def pr_from_rest(data: object) -> PR:
"""Normalize one REST pull detail without treating absent merge evidence as clean."""
try:
if not isinstance(data, dict):
Expand Down Expand Up @@ -609,7 +609,7 @@ def _pr_from_rest(data: object) -> PR:

def _pr_detail(repo: str, number: int) -> tuple[PR, dict]:
data = api_get(f"repos/{repo}/pulls/{number}")
pr = _pr_from_rest(data)
pr = pr_from_rest(data)
if pr.number != number:
raise GhError(("gh", "api", f"repos/{repo}/pulls/{number}"),
f"PR detail number {pr.number} differs from requested {number}")
Expand Down Expand Up @@ -753,7 +753,7 @@ def create_draft_pr(repo: str, branch: str, base: str, title: str, body: str) ->
detail = _api(
f"repos/{repo}/pulls", {"head": branch, "base": base, "title": title,
"body": body, "draft": True})
pr = _pr_from_rest(detail)
pr = pr_from_rest(detail)
source_repo = detail["head"].get("repo") or {}
if (pr.state != "OPEN" or not pr.is_draft or pr.base_ref != base
or detail["head"].get("ref") != branch
Expand Down
24 changes: 20 additions & 4 deletions src/loopzero/hosted.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,13 @@ def _run(cfg: Config) -> int:
def publish(state: str, message: str) -> None:
github.commit_status(cfg.repo, head, eligibility.CONTEXT, state, message[:140])
publish("pending", "Refreshing live source review evidence")
snapshot = None
try:
if candidate:
def policy(source_number: int, source: dict) -> None:
result = eligibility.evaluate(cfg.repo, source_number, source["head"]["sha"],
cfg.base_branch, cfg.review_publishers)
cfg.base_branch, cfg.review_publishers,
snapshot=github.pr_from_rest(source))
if not result.ready:
raise _SourcePolicyRejection(f"source #{source_number}: " + "; ".join(result.reasons))
candidate_mod.attest_candidate(
Expand All @@ -94,10 +96,12 @@ def policy(source_number: int, source: dict) -> None:
)
ready, message = True, "All attested candidate sources are reviewed"
else:
result = eligibility.evaluate(cfg.repo, number, head, cfg.base_branch, cfg.review_publishers)
snapshot = 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 github.pr_view(cfg.repo, number).head_sha != head:
raise LoopZeroError("head changed before publication; refresh eligibility")
if _landed_before_publication(cfg.repo, number, head, snapshot):
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"
Expand All @@ -113,6 +117,18 @@ def policy(source_number: int, source: dict) -> None:
return 0 if ready or state == "pending" else 1


def _landed_before_publication(repo: str, number: int, head: str, snapshot: github.PR | None) -> bool:
current = github.pr_view(repo, number)
if current.head_sha != head:
raise LoopZeroError("head changed before publication; refresh eligibility")
if snapshot is not None:
if current.state == "MERGED":
return True
if eligibility.source_fingerprint(current) != eligibility.source_fingerprint(snapshot):
raise LoopZeroError("source metadata changed before publication; refresh eligibility")
return False


def _publish_verdict(repo: str, head: str, state: str, description: str) -> None:
context = eligibility.CONTEXT
try:
Expand Down
12 changes: 6 additions & 6 deletions tests/test_github.py
Original file line number Diff line number Diff line change
Expand Up @@ -636,7 +636,7 @@ def timeout(*args, **kwargs):
def test_post_review_posts_comment_directly_for_own_pr(gh: FakeGh, verdict: str, supplied: bool) -> None:
details = f"api repos/{REPO}/pulls/7"
arm_review(gh, author="someone-else" if supplied else "bot-user")
pr = github._pr_from_rest(rest_pr_json(pr_json(author={"login": "bot-user"}))) if supplied else None
pr = github.pr_from_rest(rest_pr_json(pr_json(author={"login": "bot-user"}))) if supplied else None
github.post_review(REPO, 7, HEAD, review(verdict=verdict, findings=FINDINGS[:1]), pr=pr)
(payload,) = review_payloads(gh)
assert payload["event"] == "COMMENT"
Expand Down Expand Up @@ -958,7 +958,7 @@ def arm_workflow_check(gh: FakeGh, *checks: dict, statuses=(), threads=()) -> No


def readiness(*, reviewed=HEAD, workflow_wait=False):
pr = github._pr_from_rest(rest_pr_json(pr_json()))
pr = github.pr_from_rest(rest_pr_json(pr_json()))
return github.readiness(REPO, pr, "main", ("checks",), reviewed, workflow_wait=workflow_wait,
publishers=PUBLISHERS)

Expand Down Expand Up @@ -1034,7 +1034,7 @@ def test_readiness_uses_head_or_non_outdated_rule_and_resolved_never_blocks(
def test_readiness_missing_and_failed_checks(gh: FakeGh, failure, wait, grace) -> None:
arm_readiness(gh, runs={"checks": failure})
r = github.readiness(
REPO, github._pr_from_rest(rest_pr_json(pr_json())), "main", ("checks", "e2e"), HEAD, workflow_wait=wait, review_grace=grace,
REPO, github.pr_from_rest(rest_pr_json(pr_json())), "main", ("checks", "e2e"), HEAD, workflow_wait=wait, review_grace=grace,
publishers=PUBLISHERS,
)
assert r.reasons == (
Expand Down Expand Up @@ -1155,14 +1155,14 @@ def test_readiness_rerun_attempt_requires_start_after_old_failure(
], ids=["behind-base", "merge-conflict", "merged-pr"])
def test_readiness_metadata_blocker(gh: FakeGh, metadata: dict, reason: str) -> None:
arm_readiness(gh)
pr = github._pr_from_rest(rest_pr_json(pr_json(**metadata)))
pr = github.pr_from_rest(rest_pr_json(pr_json(**metadata)))
r = github.readiness(REPO, pr, "main", ("checks",), HEAD, publishers=PUBLISHERS)
assert r.reasons == (reason,)


def test_readiness_without_required_ci_skips_check_lookup(gh: FakeGh) -> None:
gh.respond("api graphql", threads_json())
assert github.readiness(REPO, github._pr_from_rest(rest_pr_json(pr_json())), "main", (), HEAD,
assert github.readiness(REPO, github.pr_from_rest(rest_pr_json(pr_json())), "main", (), HEAD,
publishers=PUBLISHERS).ready
assert [c["argv"][:2] for c in gh.calls] == [["api", "graphql"]]

Expand Down Expand Up @@ -1467,7 +1467,7 @@ def test_readiness_at_check_suite_limit(gh: FakeGh, unrelated, legacy_success, c
runs.append({"name": "required-ci", "conclusion": "failure", "check_suite": {"id": 1}})
gh.respond(f"api repos/{REPO}/commits/{HEAD}/check-runs",
*({"check_runs": runs[i:i + 100]} for i in range(0, len(runs) + 1, 100)))
result = github.readiness(REPO, github._pr_from_rest(rest_pr_json(pr_json())),
result = github.readiness(REPO, github.pr_from_rest(rest_pr_json(pr_json())),
"main", ("required-ci",), HEAD, publishers=PUBLISHERS)

reasons = {
Expand Down
Loading
Loading