Skip to content
Closed
15 changes: 10 additions & 5 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,11 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con
at that head with the current commands and check settings digest. A settings
change or an older receipt without the digest requires a fresh check. The
digest covers execution and stage reuse settings without recording raw
environment values. It excludes only inherited `HEAVY_SLOT_GRANTED_CORES`
for local sandbox receipts. Explicit settings, delegated runner environments
and stage reuse keys still bind the grant. Waiters check for policy changes
on every poll.
environment values. For local sandbox receipts it omits inherited `PATH`,
`LANG`, `LC_ALL`, `TERM`, and `HEAVY_SLOT_GRANTED_CORES` so readiness can
run in a different host environment. Explicit settings, delegated runner
environments, and stage reuse keys still bind these values. Waiters check
for policy changes on every poll.
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 Expand Up @@ -318,12 +319,16 @@ 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
requests evaluate a temporary integration with the freshly fetched target. The
target supplies the checker and baseline. Existing requests continue to the
queue wait path.
queue wait path. Readiness and new queue requests without an admission deadline can project an
advisory budget after a single known chain of queued predecessors.
Candidate lineage reads wait on zero or multiple live batch matches with exponential
backoff capped at 30 seconds and a shared 90-second retry-admission deadline across
both reads and all attestation attempts. Each wait revalidates the candidate before
Expand Down
11 changes: 9 additions & 2 deletions src/loopzero/candidate.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def _object(value: JsonValue, message: str) -> JsonObject:
return value


def _flatten_batches(status: object) -> dict[str, JsonObject]:
def flatten_batches(status: object) -> dict[str, JsonObject]:
_require(isinstance(status, dict), "Mergify status is not an object")
batches = status.get("batches")
_require(isinstance(batches, list), "Mergify status has no batches list")
Expand All @@ -116,7 +116,7 @@ def visit(items: list[object]) -> None:


def _candidate_lineage(status: JsonObject, candidate_number: int) -> tuple[str, list[int], list[str]]:
indexed = _flatten_batches(status)
indexed = flatten_batches(status)
matches = [
batch
for batch in indexed.values()
Expand Down 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
49 changes: 41 additions & 8 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1277,7 +1277,7 @@ def _cleanup(wt: Path, pr: github.PR) -> None:


def _prequeue_size_budget(
wt: Path, config: Config, pr: github.PR, readiness: github.Readiness,
wt: Path, config: Config, pr: github.PR, readiness: github.Readiness, *, project: bool = True,
) -> None:
if not readiness.ready or config.merge_strategy != "mergify" or _SIZE_BUDGET not in config.checks:
return
Expand All @@ -1299,14 +1299,47 @@ def _prequeue_size_budget(
raise CliError(f"could not fetch {config.base_branch} from origin for the size budget check")
base = git("rev-parse", "FETCH_HEAD^{commit}")
script = git("show", f"{base}:{_SIZE_BUDGET}")
tree = git("merge-tree", "--write-tree", base, pr.head_sha)
# A candidate symlink must not read files outside the temporary checkout.
git("-c", "core.symlinks=false", "read-tree", "--reset", "-u", tree)
result = _proc.run(["bash", "-s", "--", base], input=script + "\n", cwd=root,
env_allowlist=("PATH",), extra_env=env, timeout=GIT_TIMEOUT,
merge_output=True)

def evaluate(target: str) -> _proc.Completed:
tree = git("merge-tree", "--write-tree", target, pr.head_sha)
# A candidate symlink must not read files outside the temporary checkout.
git("-c", "core.symlinks=false", "read-tree", "--reset", "-u", tree)
return _proc.run(["bash", "-s", "--", base], input=script + "\n", cwd=root,
env_allowlist=("PATH",), extra_env=env, timeout=GIT_TIMEOUT,
merge_output=True)

result = evaluate(base)
if result.exit_code:
raise CliError("current target size budget failed:\n" + result.stdout.rstrip())
if project:
_warn_queue_size(config, pr, root, origin, base, git, evaluate)


def _warn_queue_size(
config: Config, pr: github.PR, root: Path, origin: str, base: str,
git: Callable[..., str], evaluate: Callable[[str], _proc.Completed],
) -> None:
assert config.mergify_queue is not None
try:
numbers = mergify.queue_predecessors(config.repo, config.base_branch, config.mergify_queue, pr.number)
if not numbers:
return
refs = [f"refs/pull/{number}/head:refs/loopzero/{number}" for number in numbers]
_git(root, "fetch", "--no-tags", "--no-recurse-submodules", "--", origin, *refs)
integrated = base
for number in numbers:
source = git("rev-parse", f"refs/loopzero/{number}^{{commit}}")
if git("merge-base", integrated, source) == source:
return # A queued PR may already have landed or be represented by another head.
tree = git("merge-tree", "--write-tree", integrated, source)
integrated = git("-c", "user.name=loopzero", "-c", "user.email=loopzero@localhost",
"commit-tree", tree, "-p", integrated, "-p", source, "-m", "Queue size projection")
result = evaluate(integrated)
except (LoopZeroError, OSError):
return
if result.exit_code and "size budget: FAIL" in result.stdout:
predecessors = ", ".join(f"#{number}" for number in numbers)
print(f"warning: projected size budget after {predecessors}:\n{result.stdout.rstrip()}")


def cmd_ready(args: argparse.Namespace) -> int:
Expand Down Expand Up @@ -1723,7 +1756,7 @@ def _merge_with_mergify(
return sha
raise closed[0]
if not confirmed and not requested:
_prequeue_size_budget(wt, config, pr, readiness)
_prequeue_size_budget(wt, config, pr, readiness, project=admit_by is None)
if admit_by is not None and time.monotonic() > admit_by:
raise _AdmissionDeadline
mergify.request(config.repo, pr.number, pr.head_sha, queue)
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
39 changes: 38 additions & 1 deletion src/loopzero/mergify.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from pathlib import Path
from urllib.parse import quote

from . import github
from . import candidate, github
from .types import LoopZeroError

API = "https://api.mergify.com/v1"
Expand Down Expand Up @@ -147,6 +147,43 @@ def membership(repo: str, number: int, queue: str) -> Membership | None:
raise MergifyError("invalid Mergify queue membership response") from exc


def queue_predecessors(repo: str, branch: str, queue: str, number: int) -> tuple[int, ...]:
"""Identify a single chain of one-PR batches ahead of a new request."""
status = api_get(repo, f"/merge-queue/status?branch={quote(branch, safe='')}")
if (not isinstance(status, dict) or status.get("mode") != "serial"
or status.get("waiting_pull_requests") != [] or status.get("forming_batches") != []):
return ()
try:
batches = candidate.flatten_batches(status)
successors: dict[str | None, tuple[str, int]] = {}
for batch_id, batch in batches.items():
pulls, parents = batch["pull_requests"], batch["parent_ids"]
if pulls == [] and batch.get("sub_batches"):
continue # Container batches carry no direct source.
if (batch.get("queue_rule_name") != queue or not isinstance(pulls, list)
or len(pulls) != 1 or not isinstance(parents, list) or len(parents) > 1):
return ()
source = pulls[0]["number"]
parent = next(iter(parents), None)
if type(source) is not int or source <= 0 or source == number or parent in successors:
return ()
successors[parent] = batch_id, source
return _ordered_sources(successors)
except (candidate.CandidateError, KeyError, TypeError, RecursionError):
return ()


def _ordered_sources(successors: dict[str | None, tuple[str, int]]) -> tuple[int, ...]:
if len(successors) > 32:
return ()
sources = []
cursor = None
while cursor in successors:
cursor, source = successors.pop(cursor)
sources.append(source)
return tuple(sources) if not successors and len(sources) == len(set(sources)) else ()


def _preserves_source_heads(repo: str, branch: str, queue: str) -> bool:
"""Read the vendor's canonical input, not a deprecated raw queue-rule default."""
import yaml
Expand Down
8 changes: 5 additions & 3 deletions src/loopzero/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,9 +254,11 @@ def settings_fingerprint(config: Config, worktree: Path, *, base: str | None = N
settings = _execution_settings(config, base)
if config.check_runner and settings["runner_executable"] is None:
return None
if not config.check_runner and "HEAVY_SLOT_GRANTED_CORES" not in config.env:
# The inherited local worker limit is transient. Stage reuse still binds it.
settings["environment"].pop("HEAVY_SLOT_GRANTED_CORES", None)
if not config.check_runner:
# Inherited host settings can differ at readiness. Stage reuse still binds them.
host_env = {"PATH", "LANG", "LC_ALL", "TERM", "HEAVY_SLOT_GRANTED_CORES"}
for name in host_env - dict(config.env).keys():
settings["environment"].pop(name, None)
payload = [settings, config.inputs]
return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()

Expand Down
2 changes: 1 addition & 1 deletion tach.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ depends_on = ["loopzero._proc", "loopzero.runners", "loopzero.types"]

[[modules]]
path = "loopzero.mergify"
depends_on = ["loopzero.github", "loopzero.types"]
depends_on = ["loopzero.candidate", "loopzero.github", "loopzero.types"]

[[modules]]
path = "loopzero.candidate"
Expand Down
Loading
Loading