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
148 changes: 46 additions & 102 deletions src/loopzero/candidate.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,7 @@ def _require(condition: bool, message: str, error: type[CandidateError] = Candid
def _identity(actor: object) -> tuple[object, object, object, object]:
if not isinstance(actor, dict):
return (None, None, None, None)
return (
actor.get("id"),
actor.get("login"),
actor.get("type"),
actor.get("html_url"),
)
return actor.get("id"), actor.get("login"), actor.get("type"), actor.get("html_url")


def _object(value: JsonValue, message: str) -> JsonObject:
Expand All @@ -106,10 +101,7 @@ def visit(items: list[object]) -> None:
_require(isinstance(item, dict), "Mergify status contains an invalid batch")
batch_id = item.get("id")
_require(isinstance(batch_id, str) and batch_id, "Mergify batch has no id")
_require(
batch_id not in indexed,
f"Mergify batch id is duplicated: {batch_id}",
)
_require(batch_id not in indexed, f"Mergify batch id is duplicated: {batch_id}")
indexed[batch_id] = item
children = item.get("sub_batches")
if children is not None:
Expand All @@ -136,10 +128,8 @@ def _candidate_lineage(status: JsonObject, candidate_number: int) -> tuple[str,
CandidateBatchError,
)
candidate_id = matches[0]["id"]
pending = [candidate_id]
visited: set[str] = set()
source_numbers: list[int] = []
missing: list[str] = []
pending, visited = [candidate_id], set()
source_numbers, missing = [], []
while pending:
batch_id = pending.pop()
if batch_id in visited:
Expand Down Expand Up @@ -170,10 +160,8 @@ def _candidate_lineage(status: JsonObject, candidate_number: int) -> tuple[str,
)
pending.extend(parent_ids)
_require(source_numbers, f"Mergify batch for PR #{candidate_number} has no sources")
_require(
len(source_numbers) == len(set(source_numbers)),
f"Mergify batch for PR #{candidate_number} repeats a source pull request",
)
_require(len(source_numbers) == len(set(source_numbers)),
f"Mergify batch for PR #{candidate_number} repeats a source pull request")
return candidate_id, sorted(source_numbers), sorted(missing)


Expand Down Expand Up @@ -239,6 +227,11 @@ def _source_fingerprint(source: JsonObject) -> tuple[object, ...]:
)


def _lookup_source(github_get: GitHubGet, repo: str, number: int) -> JsonObject:
return _object(github_get(f"/repos/{repo}/pulls/{number}"),
f"GitHub source PR #{number} lookup returned an invalid payload")


def _attest_source(
source: JsonObject,
*,
Expand All @@ -247,10 +240,7 @@ def _attest_source(
candidate_sha: str,
github_get: GitHubGet,
) -> str:
_require(
source.get("number") == number,
f"GitHub returned the wrong source PR for #{number}",
)
_require(source.get("number") == number, f"GitHub returned the wrong source PR for #{number}")
_require(
source.get("state") == "open",
f"source PR #{number} is not open",
Expand Down Expand Up @@ -280,12 +270,9 @@ def _attest_source(
"GitHub compare returned an invalid payload",
)
merge_base = comparison.get("merge_base_commit")
_require(
comparison.get("status") in {"ahead", "identical"}
and isinstance(merge_base, dict)
and merge_base.get("sha") == source_sha,
f"source PR #{number} head {source_sha} is not an ancestor of the candidate",
)
_require(comparison.get("status") in {"ahead", "identical"}
and isinstance(merge_base, dict) and merge_base.get("sha") == source_sha,
f"source PR #{number} head {source_sha} is not an ancestor of the candidate")
return source_sha


Expand Down Expand Up @@ -374,14 +361,11 @@ def _verify_tree(repo: str, main: str, candidate: str, sources: list[str]) -> No
cursor = candidate
while cursor in graph and pending:
parents = graph[cursor]
if cursor in pending:
pending.remove(cursor)
reverse_order.append(cursor)
if len(parents) > 1:
_require(len(parents) == 2, "ambiguous candidate integration topology")
if parents[1] in pending:
pending.remove(parents[1])
reverse_order.append(parents[1])
_require(len(parents) <= 2, "ambiguous candidate integration topology")
for source in (cursor, *parents[1:]):
if source in pending:
pending.remove(source)
reverse_order.append(source)
cursor = parents[0] if parents else ""
_require(not pending, "ambiguous source order in candidate topology")
integrated = main
Expand Down Expand Up @@ -435,26 +419,19 @@ def _attest_candidate_once(
batch_wait: list[float],
) -> list[dict[str, object]]:
"""Return stable source evidence after every source passes `source_policy`."""
repository = event.get("repository")
event_pr = event.get("pull_request")
_require(isinstance(repository, dict), "GitHub event repository is missing")
_require(isinstance(event_pr, dict), "GitHub event pull request is missing")
repository = _object(event.get("repository"), "GitHub event repository is missing")
event_pr = _object(event.get("pull_request"), "GitHub event pull request is missing")
_require(
event.get("action") in {"opened", "synchronize"},
"Candidate attestation requires its creation or head-update event",
)
full_name = repository.get("full_name")
_require(
isinstance(full_name, str) and _REPOSITORY.fullmatch(full_name) is not None,
"GitHub event repository name is invalid",
)
event_head = event_pr.get("head")
_require(isinstance(event_head, dict), "GitHub event candidate head is missing")
_require(isinstance(full_name, str) and _REPOSITORY.fullmatch(full_name) is not None,
"GitHub event repository name is invalid")
event_head = _object(event_pr.get("head"), "GitHub event candidate head is missing")
event_ref = event_head.get("ref")
_require(
isinstance(event_ref, str) and event_ref.startswith(QUEUE_BRANCH_PREFIX),
"Mergify candidate has an unexpected head ref",
)
_require(isinstance(event_ref, str) and event_ref.startswith(QUEUE_BRANCH_PREFIX),
"Mergify candidate has an unexpected head ref")
owner, repo = full_name.split("/", 1)

app = _object(github_get("/apps/mergify"), "GitHub App lookup is invalid")
Expand All @@ -475,56 +452,41 @@ def _attest_candidate_once(
expected_identity == (MERGIFY_BOT_ID, MERGIFY_BOT_LOGIN, "Bot", MERGIFY_APP_URL),
"Could not resolve the Mergify GitHub App identity",
)
_require(
_identity(event_pr.get("user")) == expected_identity,
"Candidate author is not the verified Mergify GitHub App",
)
_require(
_identity(event.get("sender")) == expected_identity,
"Candidate head event was not sent by the verified Mergify GitHub App",
)
_require(_identity(event_pr.get("user")) == expected_identity,
"Candidate author is not the verified Mergify GitHub App")
_require(_identity(event.get("sender")) == expected_identity,
"Candidate head event was not sent by the verified Mergify GitHub App")

candidate_number = event_pr.get("number")
candidate_sha = event_head.get("sha")
_require(
isinstance(candidate_number, int) and candidate_number > 0,
"Candidate PR number is invalid",
)
_require(
isinstance(candidate_sha, str) and _SHA.fullmatch(candidate_sha) is not None,
"Candidate head SHA is invalid",
)
_require(isinstance(candidate_sha, str) and _SHA.fullmatch(candidate_sha) is not None,
"Candidate head SHA is invalid")
candidate_path = f"/repos/{full_name}/pulls/{candidate_number}"
candidate_before = _object(
github_get(candidate_path),
"GitHub candidate lookup returned an invalid payload",
)
_candidate_snapshot(
candidate_before,
event_pr=event_pr,
repository=repository,
expected_identity=expected_identity,
)
def recheck_candidate(message: str = "GitHub candidate lookup returned an invalid payload") -> None:

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: Nested recheck_candidate has no blank line before it and a loose message parameter

def recheck_candidate(message=...) comes straight after the candidate_path assignment with no blank line, and its message changes between call sites (the default versus "Invalid candidate lookup"). The behavior is the same as before, but splitting one diagnostic across a default argument is easy to get wrong in later edits. Consider adding a blank line before the def, and either use one message everywhere if the tests allow it, or pass the message explicitly at every call site.

candidate = _object(github_get(candidate_path), message)
_candidate_snapshot(candidate, event_pr=event_pr, repository=repository,
expected_identity=expected_identity)

recheck_candidate()

def live_lineage() -> tuple[str, list[int], list[str]]:
delay = 2
while True:
try:
return _candidate_lineage(mergify_status(owner, repo, "main"), candidate_number)
except CandidateBatchError:
def recheck_candidate() -> None:
current = _object(github_get(candidate_path), "Invalid candidate lookup")
_candidate_snapshot(current, event_pr=event_pr, repository=repository,
expected_identity=expected_identity)

recheck_candidate()
recheck_candidate("Invalid candidate lookup")
remaining = batch_deadline - _retry_clock()
if remaining <= 0:
raise
started = _retry_clock()
_retry_sleep(min(delay, remaining))
batch_wait[0] += _retry_clock() - started
recheck_candidate()
recheck_candidate("Invalid candidate lookup")
if _retry_clock() >= batch_deadline:
raise
delay = min(delay * 2, 30)
Expand All @@ -534,10 +496,7 @@ def recheck_candidate() -> None:
main_before = github_get(main_path) if first_lineage[2] else None
source_snapshots: dict[int, tuple[str, tuple[object, ...]]] = {}
for number in first_lineage[1]:
source = _object(
github_get(f"/repos/{full_name}/pulls/{number}"),
f"GitHub source PR #{number} lookup returned an invalid payload",
)
source = _lookup_source(github_get, full_name, number)
source_sha = _attest_source(
source,
number=number,
Expand All @@ -551,7 +510,7 @@ def recheck_candidate() -> None:
except Exception as exc:
current = None
with contextlib.suppress(Exception):
current = github_get(f"/repos/{full_name}/pulls/{number}")
current = _lookup_source(github_get, full_name, number)
if (isinstance(current, dict) and current.get("merged") is True
and isinstance(current.get("head"), dict)
and current["head"].get("sha") == source_sha):
Expand All @@ -562,10 +521,7 @@ def recheck_candidate() -> None:
try:
main_ref = _object(main_before, "main ref unavailable")
main_sha = _object(main_ref.get("object"), "main object unavailable").get("sha")
_require(
isinstance(main_sha, str) and _SHA.fullmatch(main_sha) is not None,
"invalid main head",
)
_require(isinstance(main_sha, str) and _SHA.fullmatch(main_sha) is not None, "invalid main head")
_verify_tree(full_name, main_sha, candidate_sha,
[snapshot[0] for snapshot in source_snapshots.values()])
_require(
Expand All @@ -586,21 +542,9 @@ def recheck_candidate() -> None:
"Mergify candidate membership changed during attestation",
CandidateRaceError,
)
candidate_after = _object(
github_get(candidate_path),
"GitHub candidate lookup returned an invalid payload",
)
_candidate_snapshot(
candidate_after,
event_pr=event_pr,
repository=repository,
expected_identity=expected_identity,
)
recheck_candidate()
for number, (expected_sha, expected_fingerprint) in source_snapshots.items():
current = _object(
github_get(f"/repos/{full_name}/pulls/{number}"),
f"GitHub source PR #{number} lookup returned an invalid payload",
)
current = _lookup_source(github_get, full_name, number)
current_head = current.get("head")
_require(
isinstance(current_head, dict) and current_head.get("sha") == expected_sha,
Expand Down
Loading
Loading