Skip to content
8 changes: 5 additions & 3 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,8 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con
5. `ready` derives readiness from the current head, its check receipt, an eligible review at that
head or an eligible review covering an ancestor, blocking findings
(unresolved threads a review publisher opened with a head-bound marker line),
target branch and required CI. The receipt must record a clean passing run
target branch and required CI. Readiness compares parsed instants for verdict
freshness and uses a valid GitHub response Date during waits. The receipt must record a clean passing run
at that head with the current commands and check settings digest. Ready and
merge validate the PR, head and hold before checking the local receipt.
An invalid receipt stops the command before it fetches remote readiness
Expand Down Expand Up @@ -540,8 +541,9 @@ stage is retried after success or uncertain launch. Only the coordinator writes
the authoritative `checks.json` receipt. Writers lock the task state directory
while rechecking HEAD and atomically replacing the receipt from a synced sibling
temporary file. Successful keyed stages are checkpointed in the same receipt
for reuse. The checkpoint cannot satisfy readiness before final worktree
validation. Runners cannot select stages or mint receipts. Stage admission
for reuse. A checkpoint cannot replace a clean pass for the same head and
settings or satisfy readiness before final worktree validation. Completed
failures still replace passes. Runners cannot select stages or mint receipts. Stage admission
belongs to the runner: the outer `loopzero check`
must not hold a heavy slot when a runner is configured. Without a runner, the
existing local execution path is unchanged.
Expand Down
82 changes: 26 additions & 56 deletions src/loopzero/candidate.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,30 +86,26 @@ def _identity(actor: object) -> tuple[object, object, object, object]:
return actor.get("id"), actor.get("login"), actor.get("type"), actor.get("html_url")


def _object(value: JsonValue, message: str) -> JsonObject:
def _object(value: object, message: str) -> JsonObject:
_require(isinstance(value, dict), message)
return value


def flatten_batches(status: object) -> dict[str, JsonObject]:
_require(isinstance(status, dict), "Mergify status is not an object")
batches = status.get("batches")
batches = _object(status, "Mergify status is not an object").get("batches")
_require(isinstance(batches, list), "Mergify status has no batches list")
indexed: dict[str, JsonObject] = {}

def visit(items: list[object]) -> None:
for item in items:
_require(isinstance(item, dict), "Mergify status contains an invalid batch")
item = _object(item, "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}")
indexed[batch_id] = item
children = item.get("sub_batches")
if children is not None:
_require(
isinstance(children, list),
f"Mergify batch {batch_id} has invalid sub_batches",
)
_require(isinstance(children, list), f"Mergify batch {batch_id} has invalid sub_batches")
visit(children)

visit(batches)
Expand All @@ -118,17 +114,11 @@ def visit(items: list[object]) -> None:

def _candidate_lineage(status: JsonObject, candidate_number: int) -> tuple[str, list[int], list[str]]:
indexed = flatten_batches(status)
matches = [
batch
for batch in indexed.values()
if batch.get("queue_pull_request_number") == candidate_number
]
_require(
len(matches) == 1,
f"PR #{candidate_number} is not exactly one live Mergify batch",
CandidateBatchError,
)
candidate_id = matches[0]["id"]
matches = [batch_id for batch_id, batch in indexed.items()
if batch.get("queue_pull_request_number") == candidate_number]
_require(len(matches) == 1, f"PR #{candidate_number} is not exactly one live Mergify batch",
CandidateBatchError)
candidate_id = matches[0]
pending, visited = [candidate_id], set()
source_numbers, missing = [], []
while pending:
Expand All @@ -141,10 +131,7 @@ def _candidate_lineage(status: JsonObject, candidate_number: int) -> tuple[str,
missing.append(batch_id)
continue
pull_requests = batch.get("pull_requests")
_require(
isinstance(pull_requests, list),
f"Mergify batch {batch_id} has no pull_requests list",
)
_require(isinstance(pull_requests, list), f"Mergify batch {batch_id} has no pull_requests list")
for pull_request in pull_requests:
_require(
isinstance(pull_request, dict)
Expand All @@ -154,11 +141,9 @@ def _candidate_lineage(status: JsonObject, candidate_number: int) -> tuple[str,
)
source_numbers.append(pull_request["number"])
parent_ids = batch.get("parent_ids", [])
_require(
isinstance(parent_ids, list)
and all(isinstance(parent_id, str) and parent_id for parent_id in parent_ids),
f"Mergify batch {batch_id} has invalid parent_ids",
)
_require(isinstance(parent_ids, list)
and all(isinstance(parent, str) and parent for parent in parent_ids),
f"Mergify batch {batch_id} has invalid parent_ids")
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)),
Expand Down Expand Up @@ -196,7 +181,8 @@ def _candidate_snapshot(
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
base = base if isinstance(base, dict) else {}
base_repo = base.get("repo")
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")
Expand All @@ -209,9 +195,8 @@ def _source_fingerprint(source: JsonObject) -> tuple[object, ...]:
source.get("draft"),
source.get("body"),
head.get("sha") if isinstance(head, dict) else None,
base.get("ref") if isinstance(base, dict) else None,
base_repo.get("id") if isinstance(base_repo, dict) else None,
base_repo.get("full_name") if isinstance(base_repo, dict) else None,
base.get("ref"),
*_repo_identity(base_repo if isinstance(base_repo, dict) else {}),
)


Expand Down Expand Up @@ -438,10 +423,8 @@ def _attest_candidate_once(
"""Return stable source evidence after every source passes `source_policy`."""
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",
)
_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")
Expand All @@ -453,33 +436,20 @@ def _attest_candidate_once(

app = _object(github_get("/apps/mergify"), "GitHub App lookup is invalid")
app_owner = app.get("owner")
_require(
app.get("id") == MERGIFY_APP_ID
and app.get("slug") == "mergify"
and isinstance(app_owner, dict)
and app_owner.get("login") == MERGIFY_APP_OWNER,
"Could not resolve the official Mergify GitHub App",
)
expected_actor = _object(
github_get("/users/mergify%5Bbot%5D"),
"GitHub bot lookup is invalid",
)
expected_identity = _identity(expected_actor)
_require(
expected_identity == (MERGIFY_BOT_ID, MERGIFY_BOT_LOGIN, "Bot", MERGIFY_APP_URL),
"Could not resolve the Mergify GitHub App identity",
)
_require(app.get("id") == MERGIFY_APP_ID and app.get("slug") == "mergify"
and isinstance(app_owner, dict) and app_owner.get("login") == MERGIFY_APP_OWNER,
"Could not resolve the official Mergify GitHub App")
expected_identity = _identity(_object(github_get("/users/mergify%5Bbot%5D"), "GitHub bot lookup is invalid"))
_require(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")

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_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")
candidate_path = f"/repos/{full_name}/pulls/{candidate_number}"
Expand Down
40 changes: 25 additions & 15 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import tempfile
import time
from collections.abc import Callable, Iterator
from datetime import UTC, datetime
from functools import partial, wraps
from pathlib import Path

Expand Down Expand Up @@ -198,11 +197,11 @@ def _require_pushed(pr: github.PR, head: str) -> None:
# --------------------------------------------------------------------------- review markers


def _rest_rows(endpoint: str, what: str) -> list[dict]:
def _rest_rows(endpoint: str, what: str, **kwargs) -> list[dict]:
"""Every row of a REST list, oldest first, following pages until a short one."""
rows: list[dict] = []
for page in range(1, 101):
batch = github.api_get(f"{endpoint}?per_page={github.PAGE}&page={page}")
batch = github.api_get(f"{endpoint}?per_page={github.PAGE}&page={page}", **kwargs)
if not isinstance(batch, list) or not all(isinstance(row, dict) for row in batch):
raise CliError(f"invalid GitHub {what} response")
rows += batch
Expand All @@ -211,8 +210,8 @@ def _rest_rows(endpoint: str, what: str) -> list[dict]:
raise CliError(f"GitHub {what} pagination limit exceeded")


def _pr_reviews(repo: str, number: int) -> list[dict]:
return _rest_rows(f"repos/{repo}/pulls/{number}/reviews", "reviews")
def _pr_reviews(repo: str, number: int, **kwargs) -> list[dict]:
return _rest_rows(f"repos/{repo}/pulls/{number}/reviews", "reviews", **kwargs)


@dataclasses.dataclass(frozen=True)
Expand Down Expand Up @@ -316,26 +315,29 @@ def _readiness(
) -> github.Readiness:
if problem := _readiness_precheck(wt, config, pr, head, diagnostics):
return github.Readiness(False, (problem,))
if reviews is None:
reviews = _pr_reviews(config.repo, pr.number)
dates: list[str] = []
reviews = (_pr_reviews(config.repo, pr.number, **({"dates": dates} if workflow_wait else {}))
if reviews is None else reviews)
publishers = config.review_publishers or (github.login(),)
review = eligibility.readiness_review(
reviews, head, publishers, repo=config.repo, number=pr.number, base_branch=config.base_branch,
)
review_at = review.get("submitted_at") if review else None
# GitHub's review timestamp is in UTC and predates this process.
review_age = (time.time() - datetime.strptime(review_at, "%Y-%m-%dT%H:%M:%SZ")
.replace(tzinfo=UTC).timestamp()) if review_at else None
review_at = github.readiness_timestamp(review.get("submitted_at")) if review else None
server = github.response_date(dates[-1]) if dates else None
now = server.timestamp() if server else time.time()
review_age = now - review_at[0].timestamp() if review_at else None
if server and review_age is not None and -1 < review_age < 0:
review_age = 0 # HTTP Date rounds down to the second.
result = github.readiness(
config.repo, pr, config.base_branch, config.required_ci,
head if review else None, review_at=review_at,
ancestor_review=review is not None and review["commit_id"] != head,
review_grace=review_age is not None and 0 <= review_age < MISSING_RUN_GRACE,
workflow_wait=workflow_wait,
# Allow skew only for verdicts GitHub timestamps establish are stale.
# Allow host clock skew only when GitHub did not supply a usable Date.
stale_verdict_grace=(
workflow_wait and review_age is not None
and -MAX_REVIEW_CLOCK_SKEW <= review_age < STALE_VERDICT_GRACE
and (0 if server else -MAX_REVIEW_CLOCK_SKEW) <= review_age < STALE_VERDICT_GRACE
),
publishers=publishers,
)
Expand Down Expand Up @@ -418,7 +420,7 @@ def _print_receipt(wt: Path, report: CheckReport, action: str) -> None:
return


def _save_report(wt: Path, report: CheckReport) -> str | None:
def _save_report(wt: Path, report: CheckReport, *, checkpoint_checks: tuple[str, ...] | None = None) -> str | None:
"""Publish the receipt or return the current HEAD if the result is stale."""
results = [
{k: v for k, v in dataclasses.asdict(result).items()
Expand All @@ -428,8 +430,15 @@ def _save_report(wt: Path, report: CheckReport) -> str | None:
payload = {"head": report.head, "dirty": report.dirty, "results": results}
if report.settings_sha256 is not None:
payload["settings_sha256"] = report.settings_sha256
def preserve_pass() -> bool:
saved = _load_report(wt)
return (saved is not None and saved.ok and not saved.dirty and saved.head == report.head
and saved.settings_sha256 == report.settings_sha256
and tuple(result.command for result in saved.results) == checkpoint_checks)

return worktree.write_local_state(
wt, CHECKS_FILE.name, json.dumps(payload, indent=2) + "\n", expected_head=report.head,
preserve=preserve_pass if checkpoint_checks is not None else None,
)


Expand Down Expand Up @@ -630,7 +639,8 @@ def cmd_check(args: argparse.Namespace) -> int:
raise config_mod.ConfigError("checks.commands must list at least one command to run checks")
report = sandbox.run_checks(
config, wt, progress=lambda command: print(f"running: {github.redact_credentials(command)}", flush=True),
status=lambda message: print(message, flush=True), checkpoint=lambda partial: _save_report(wt, partial),
status=lambda message: print(message, flush=True),
checkpoint=lambda partial: _save_report(wt, partial, checkpoint_checks=config.checks),
workflow=args.config or f"origin/{config.base_branch}:workflow.toml",
)
shortened = False
Expand Down
Loading
Loading