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
2 changes: 2 additions & 0 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,8 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con
that requested changes also requires resolved findings at the reviewed head.
After its own draft-to-ready write,
`ready --wait` revalidates through the same waiter and original deadline.
Each poll resolves the trusted workflow ref, reusing parsed policy when the
branch and immutable revision match the preceding observation.
This is best-effort observation: an immediate green read may precede
asynchronous CI scheduling, there is no unconditional delay, and merge
admission checks readiness again. Missing-run diagnosis keeps its two-minute
Expand Down
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:
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
35 changes: 25 additions & 10 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,14 +107,16 @@ def _repo_root(wt: Path) -> Path:
return root


def _load_config(args: argparse.Namespace, root: Path, *, pin_checks: bool = False) -> Config:
def _load_config(
args: argparse.Namespace, root: Path, *, pin_checks: bool = False, previous: Config | None = None,
) -> Config:
path = args.config or root / "workflow.toml"
if not pin_checks:
return config_mod.load(path)
if args.config:
print("checks are unpinned because --config was provided")
return config_mod.load(path)
config = config_mod.load_trusted(root)
config = config_mod.load_trusted(root, previous=previous)
if args.command == "check":
if not config.checks:
raise config_mod.ConfigError(
Expand Down Expand Up @@ -1213,7 +1215,7 @@ def cmd_ready(args: argparse.Namespace) -> int:
return 3
pr, readiness, kicked = waited
assert readiness is not None
for reason in readiness.reasons:
for reason in _readiness_messages(pr, readiness):
print(f"not ready: {reason}")
if not readiness.ready:
if args.wait is None and _pending_checks(config, pr, readiness):
Expand Down Expand Up @@ -1254,6 +1256,17 @@ def _pending_checks(
return reasons if reasons and all(r in waitable for r in reasons) else ()


def _readiness_messages(pr: github.PR, readiness: github.Readiness) -> Iterator[str]:
for reason in readiness.reasons:
check, separator, conclusion = reason.rpartition("' is ")
if (separator and check.startswith("required check '") and conclusion not in {"pending", "skipped"}
and reason not in readiness.waitable_failures):
yield (f"{reason}. Inspect {pr.url}/checks. Fix reproducible failures before retrying. "
"Rerun the failed job only for a transient failure. Once green, run `loopzero ready --wait`.")
else:
yield reason


def _merge_check_hint(config: Config, pr: github.PR, readiness: github.Readiness) -> str:
if _pending_checks(config, pr, readiness):
return "; next: loopzero merge --wait"
Expand Down Expand Up @@ -1319,17 +1332,18 @@ def _print_check_wait_timeout(pr: github.PR) -> None:

def _verify_wait_snapshot(
args: argparse.Namespace | None, wt: Path, config: Config, head: str, current_head: str,
) -> None:
previous: Config | None = None,
) -> Config:
if current_head != head:
raise CliError(f"PR head changed while waiting: {head[:12]} to {current_head[:12]}")
if args is None:
return
latest = _load_config(args, wt, pin_checks=True)
return config
latest = _load_config(args, wt, pin_checks=True, previous=previous or config)
changed = "workflow settings"
if latest == config:
if (latest.trusted_base_revision == config.trusted_base_revision
or not (config.check_runner or config.inputs)):
return
return latest
changed = "check base"
if _current_check_report(wt, latest, head) is None:
raise CliError(f"{changed} changed while waiting; run loopzero check and retry")
Expand All @@ -1347,13 +1361,14 @@ def _wait_for_checks(
started = grace_started if started is None else started
current = pr
stale_notice = False
previous = config
for _ in _poll_until(started, timeout, bounded=bounded):
if initial is not None:
readiness = initial
initial = None
else:
current = github.pr_view(config.repo, pr.number)
_verify_wait_snapshot(args, wt, config, pr.head_sha, current.head_sha)
previous = _verify_wait_snapshot(args, wt, config, pr.head_sha, current.head_sha, previous)
if allow_merged and current.state == "MERGED":
return current, None, kicked
readiness = _readiness(wt, config, current, pr.head_sha, workflow_wait=True)
Expand Down Expand Up @@ -1541,7 +1556,7 @@ def _merge_with_mergify(
"""Request Mergify after readiness verifies the source gates and queue configuration."""
if not readiness.ready:
hint = _merge_check_hint(config, pr, readiness)
raise CliError("not ready to request Mergify: " + "; ".join(readiness.reasons) + hint)
raise CliError("not ready to request Mergify: " + "; ".join(_readiness_messages(pr, readiness)) + hint)
queue = config.mergify_queue
assert queue is not None
requested, confirmed_marker = mergify.markers(
Expand Down Expand Up @@ -1622,7 +1637,7 @@ def cmd_merge(args: argparse.Namespace) -> int:
else:
if not readiness.ready:
hint = _merge_check_hint(config, pr, readiness)
raise CliError("not ready to merge: " + "; ".join(readiness.reasons) + hint)
raise CliError("not ready to merge: " + "; ".join(_readiness_messages(pr, readiness)) + hint)
if admit_by is not None and time.monotonic() > admit_by:
print(f"timed out before merging PR #{pr.number}")
return 3
Expand Down
Loading
Loading