Skip to content
6 changes: 5 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,11 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con
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
at that head with the current commands and check settings digest. A settings
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
evidence. Writes to advance readiness or merging recheck the receipt.
Status continues to collect all readiness diagnostics. 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. For local sandbox receipts it omits inherited `PATH`,
Expand Down
34 changes: 9 additions & 25 deletions src/loopzero/_proc.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,22 +188,15 @@ def run(
stdin = input.encode(raw_encoding) if preserve_newlines and input is not None else input
try:
with subprocess.Popen(
argv,
cwd=str(cwd),
env=build_env(env_allowlist, extra_env),
stdin=subprocess.PIPE if input is not None else subprocess.DEVNULL,
stdout=subprocess.PIPE,
argv, cwd=str(cwd), env=build_env(env_allowlist, extra_env),
stdin=subprocess.PIPE if input is not None else subprocess.DEVNULL, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT if merge_output else subprocess.PIPE,
encoding=None if preserve_newlines else encoding,
errors=None if preserve_newlines else "replace",
pass_fds=pass_fds,
start_new_session=os.name == "posix",
encoding=None if preserve_newlines else encoding, errors=None if preserve_newlines else "replace",
pass_fds=pass_fds, start_new_session=os.name == "posix",
) as proc:
try:
if tail_chars is None:
stdout, stderr = proc.communicate(stdin, timeout=timeout)
else:
stdout, stderr = _read_output_tail(proc, tail_chars, timeout), ""
stdout, stderr = (proc.communicate(stdin, timeout=timeout) if tail_chars is None
else (_read_output_tail(proc, tail_chars, timeout), ""))
except BaseException:
if os.name == "posix":
with suppress(ProcessLookupError):
Expand All @@ -221,19 +214,10 @@ def run(
out = exc.stdout.decode(errors="replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "")
err = exc.stderr.decode(errors="replace") if isinstance(exc.stderr, bytes) else exc.stderr
elapsed = time.monotonic() - started
raise ProcTimeout(
f"{' '.join(argv)}: timed out after {timeout:g}s\n{tail(out)}",
out,
stderr=err or "",
duration_s=elapsed,
) from exc
message = f"{' '.join(argv)}: timed out after {timeout:g}s\n{tail(out)}"
raise ProcTimeout(message, out, stderr=err or "", duration_s=elapsed) from exc
if isinstance(stdout, bytes):
stdout = stdout.decode(raw_encoding, errors="surrogateescape")
if isinstance(stderr, bytes):
stderr = stderr.decode(raw_encoding, errors="replace")
return Completed(
exit_code=proc.returncode,
stdout=stdout or "",
stderr=stderr or "",
duration_s=time.monotonic() - started,
)
return Completed(proc.returncode, stdout or "", stderr or "", time.monotonic() - started)
173 changes: 83 additions & 90 deletions src/loopzero/cli.py

Large diffs are not rendered by default.

15 changes: 8 additions & 7 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from loopzero.types import BLOCKING, Finding, ReviewResult

GH_BASE_ENV = ("PATH", "HOME", "LANG", "LC_ALL", "TERM", "GH_HOST")
GH_ENV = (*GH_BASE_ENV, "GH_TOKEN", "GITHUB_TOKEN")
GH_ENV = (*GH_BASE_ENV, "GH_TOKEN", "GITHUB_TOKEN", "GH_CONFIG_DIR", "XDG_CONFIG_HOME")
APP_TOKEN_HELPER = Path.home() / ".config/loopzero/app-token"
_app_token_cache = ("", 0.0)
MISSING_REVIEW_REASON = "no review recorded for the current head"
Expand Down Expand Up @@ -666,13 +666,14 @@ def _confirm_branch_pr(repo: str, branch: str, endpoint: str, number: int, state
return pr


def pr_for_branch(repo: str, branch: str, *, open_only: bool = False) -> PR | None:
def pr_for_branch(repo: str, branch: str, *, open_only: bool = False, list_only: bool = False) -> PR | None:
"""Return the open PR, falling back to the most recent closed PR unless open_only."""
endpoint, matches = _commit_branch_prs(repo, branch)
open_matches = [row for row in matches if row["state"] == "open"]
if open_matches:
newest = max(open_matches, key=lambda row: (row["created_at"], row["number"]))
return _confirm_branch_pr(repo, branch, endpoint, newest["number"], "OPEN")
if not list_only:
endpoint, matches = _commit_branch_prs(repo, branch)
open_matches = [row for row in matches if row["state"] == "open"]
if open_matches:
newest = max(open_matches, key=lambda row: (row["created_at"], row["number"]))
return _confirm_branch_pr(repo, branch, endpoint, newest["number"], "OPEN")

# A closed association cannot rule out an open PR or newer closed history.
owner = repo.split("/", 1)[0]
Expand Down
22 changes: 6 additions & 16 deletions src/loopzero/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,7 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO
status: Callable[[str], None] | None = None,
checkpoint: Callable[[CheckReport], None] | None = None,
workflow: str | Path = "workflow.toml", _resolved: bool = False) -> CheckReport:
"""Run checks, stopping at the first failure; status emits only stage metadata.

progress receives each command before launch, as before. Optional status receives
heartbeats from a reporting thread and completion from the calling thread.
"""
"""Run until a check fails, reporting commands via progress and stage metadata via status."""
worktree = worktree.resolve()
if not config.check_runner and shutil.which("bwrap") is None:
raise SandboxUnavailable(
Expand Down Expand Up @@ -147,11 +143,8 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO
if checkpoint is not None and result.input_key and result.exit_code == 0:
# The receipt stays nonpassing until final validation.
incomplete = CheckResult(INCOMPLETE_CHECK_COMMAND, 1, 0.0, "")
unvisited = (
previous[stage] for stage in commands[ordinal:] if stage in previous
)
checkpoint(CheckReport(head, dirty, (*results, *unvisited, incomplete),
settings_sha256))
unvisited = (previous[stage] for stage in commands[ordinal:] if stage in previous)
checkpoint(CheckReport(head, dirty, (*results, *unvisited, incomplete), settings_sha256))
if status:
status(f"stage {ordinal}/{len(commands)}: exit {result.exit_code} "
f"({result.duration_s:.1f}s)")
Expand Down Expand Up @@ -189,10 +182,8 @@ def _previous(worktree: Path, settings_sha256: str) -> dict[str, CheckResult]:
if (isinstance(command, str) and isinstance(key, str) and key
and is_check_exit_code(code) and code == 0 and isinstance(tail, str)):
source = result.get("reused_from")
previous[command] = CheckResult(
command, 0, 0.0, _check_tail(tail), key,
source if isinstance(source, str) else data["head"],
)
reused_from = source if isinstance(source, str) else data["head"]
previous[command] = CheckResult(command, 0, 0.0, _check_tail(tail), key, reused_from)
return previous
except (OSError, WorktreeError, ValueError, KeyError, TypeError, AttributeError):
return {}
Expand Down Expand Up @@ -247,8 +238,7 @@ def settings_fingerprint(config: Config) -> str | None:
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()
return hashlib.sha256(json.dumps([settings, config.inputs], sort_keys=True).encode()).hexdigest()


def _input_blobs(config: Config, worktree: Path, paths: tuple[str, ...]) -> str | None:
Expand Down
2 changes: 1 addition & 1 deletion tests/fake_gh.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
def replay(
argv: list[str], calls: str, scenario: str, cwd: str, token: str | None,
) -> tuple[int, str, str]:
record = {"argv": argv, "token": token}
record = dict(argv=argv, token=token, config=[os.getenv(k) for k in ("GH_CONFIG_DIR", "XDG_CONFIG_HOME")])
input_files = {}
for flag in ("--input", "--body-file"):
if flag in argv:
Expand Down
122 changes: 61 additions & 61 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2405,7 +2405,7 @@ def test_ready_marks_draft_ready(wt: Path, gh: FakeGh, capsys, head, branch, git
gh.respond("pr ready", "")
git_calls.clear()
code, out, err = run(capsys, "ready")
assert_git_cost(git_calls, 9, 1)
assert_git_cost(git_calls, 11, 1) # Receipt ownership is checked before gates, after them and before marking ready.
assert ["ls-files", "-z", "--", ".loopzero"] in git_calls
assert (code, err) == (0, "") and out.endswith(f"ready: {URL}\n")
assert ["pr", "ready", "7", "--repo", REPO] in [c["argv"] for c in gh.calls]
Expand Down Expand Up @@ -3060,54 +3060,52 @@ def test_ready_draft_with_open_blocking_finding_does_not_mark_ready(
assert all(c["argv"][:2] != ["pr", "ready"] for c in gh.calls)


@pytest.mark.parametrize("draft,condition,reason", [
(False, "missing", "run loopzero check at this head"),
*((False, condition, "check receipt") for condition in ("wrong-head", "failed", "dirty")),
(False, "wrong-commands", "check receipt's plan differs from the trusted workflow."),
(False, "legacy", "check receipt is missing its settings fingerprint."),
(False, "incompatible", "check receipt has an incompatible settings fingerprint."),
(False, "matching", None),
(True, "stale", "check receipt is for aaaaaaaaaaaa."),
(True, "red", "check receipt records a failed stage."),
(True, "dirty", "check receipt was recorded in a dirty worktree."),
(True, "commands", "check receipt's plan differs from the trusted workflow."),
*((True, condition, "check receipt is incomplete.") for condition in ("empty", "checkpoint")),
@pytest.mark.parametrize("command", ["ready", "merge"])
@pytest.mark.parametrize("condition,reason", [
*((case, "run loopzero check at this head") for case in ("missing", "during-gates", "transient")),
("head", "check receipt is for aaaaaaaaaaaa."),
("failed", "check receipt records a failed stage."), ("dirty", "check receipt was recorded in a dirty worktree."),
("plan", "check receipt's plan differs from the trusted workflow."),
("legacy", "check receipt is missing its settings fingerprint."),
("incompatible", "check receipt has an incompatible settings fingerprint."),
("empty", "check receipt is incomplete."), ("checkpoint", "check receipt is incomplete."),
])
def test_ready_requires_clean_successful_local_report_at_head(wt, gh, capsys, condition, head, draft, reason):
arm_approved_pr_with_check_result(gh, head, wt, "success", isDraft=draft, readiness={
"local_exit": int(condition == "failed"), "dirty": condition == "dirty",
})
def test_delivery_requires_current_receipt(wt, gh, capsys, head, monkeypatch, command, condition, reason):
head = commit_mergify_configuration(wt) if command == "merge" else head
monkeypatch.setattr(mergify, "configured", lambda *_: condition == "during-gates" or pytest.fail("remote gate read"))
arm_approved_pr_with_check_result(gh, head, wt, "success", isDraft=command == "ready")
gh.respond(" ".join(BRANCH_READ), {"object": {"sha": head}})
path = wt / ".loopzero/checks.json"
if condition == "missing":
report = json.loads(path.read_text())
if condition == "during-gates":
readiness = github.readiness

def replace_receipt(*args, **kwargs):
path.unlink()
return readiness(*args, **kwargs)

monkeypatch.setattr(github, "readiness", replace_receipt)
elif condition in {"missing", "transient"}:
path.unlink()
elif condition not in {"failed", "dirty", "matching"}:
report = json.loads(path.read_text())
if condition in {"wrong-head", "stale"}:
report["head"] = ("a" if draft else "0") * 40
elif condition == "wrong-commands":
report["results"].pop()
elif condition == "commands":
report["results"][0]["command"] = "changed"
elif condition == "empty":
report["results"] = []
elif condition == "checkpoint":
report["results"][1:] = [asdict(CheckResult("<checks incomplete>", 1, 0.0, ""))]
elif condition == "red":
report["results"][0]["exit_code"] = 1
elif condition == "legacy":
del report["settings_sha256"]
else:
report["settings_sha256"] = "0" * 64
if condition == "transient":
monkeypatch.setattr(github, "_retry_sleep", lambda _: None)
gh.respond(pr_list_key(), {"stdout": "", "exit_code": 1, "stderr": "HTTP 503"}, [{"number": 7}])
else:
results = report["results"]
report.update({
"head": {"head": "a" * 40}, "dirty": {"dirty": True},
"failed": {"results": [dict(results[0], exit_code=1), *results[1:]]},
"plan": {"results": results[:-1]}, "empty": {"results": []},
"legacy": {"settings_sha256": None}, "incompatible": {"settings_sha256": "0" * 64},
"checkpoint": {"results": [results[0], asdict(CheckResult("<checks incomplete>", 1, 0, ""))]},
}[condition])
path.write_text(json.dumps(report))

out, _ = expect_cli(capsys, int(reason is not None), "ready")
if reason:
assert f"not ready: {reason}" in out
if draft:
assert "receipt accepted:" not in out
if condition in {"legacy", "incompatible"}:
assert ("Run loopzero check in this worktree at this head with the same current CLI and effective "
"settings as ready, using a local coordinator for delegated stages." in out)
out, err = expect_cli(capsys, 1, command, *(["--wait"] if command == "merge" or condition == "during-gates" else []))
assert reason in out + err and "receipt accepted:" not in out
assert all(github._read_only(tuple(c["argv"])) for c in gh.calls)
if condition != "during-gates":
expected = [PR_LIST_READ, *LOOKUP_CALLS[1:]] if condition == "transient" else LOOKUP_CALLS[1:]
assert [c["argv"][:2] for c in gh.calls] == expected


@pytest.fixture
Expand All @@ -3118,8 +3116,8 @@ def check_environment(wt, gh, head, tmp_path):
return path, policy, ("--config", str(path))


@pytest.mark.parametrize("case", ["explicit", "ready", "merge", "inherited", "fixed"])
def test_ready_checks_effective_receipt_environment(gh, capsys, head, monkeypatch, case, check_environment):
@pytest.mark.parametrize("case", ["explicit", "ready", "merge", "fresh", "inherited", "fixed"])
def test_ready_checks_effective_receipt_environment(wt, gh, capsys, head, monkeypatch, case, check_environment):
config_path, config, args = check_environment
inherited = case in {"inherited", "fixed"}
if inherited:
Expand All @@ -3135,26 +3133,28 @@ def test_ready_checks_effective_receipt_environment(gh, capsys, head, monkeypatc
monkeypatch.setenv("CHECK_POLICY", "new")
else:
new_config = config.replace('CHECK_POLICY = "old"', 'CHECK_POLICY = "new"')
if case in {"ready", "merge"}:
arm_check_runs(gh, head, [{"name": "checks", "status": "in_progress"}])
if case in {"ready", "merge", "fresh"}:
arm_check_progress(gh, head, "pending")
command = "merge" if case == "fresh" else case

def change_policy(_seconds):
assert config_path.read_text() == config
config_path.write_text(new_config)
if case == "fresh":
cfg = cli._load_config(SimpleNamespace(config=config_path, command=command), wt, pin_checks=True)
cli._save_report(wt, cli.dataclasses.replace(cli._load_report(wt),
settings_sha256=cli.sandbox.settings_fingerprint(cfg)))

monkeypatch.setattr(cli, "_sleep", change_policy)
expect_cli(capsys, 1, *args, case, "--wait",
stderr_contains=("workflow settings changed while waiting; run loopzero check",))
arm_check_runs(gh, head, [{"name": "checks", "status": "completed", "conclusion": "success"}])
hint = "retry with the current settings" if case == "fresh" else "run loopzero check"
expect_cli(capsys, 1, *args, command, "--wait", stderr_contains=(f"workflow settings changed while waiting; {hint}",))
arm_check_progress(gh, head, "success")
else:
config_path.write_text(new_config)
if case == "fixed":
expect_cli(capsys, 0, *args, "ready")
else:
expect_cli(capsys, 1, *args, "ready",
stdout_contains=("not ready: check receipt has an incompatible settings fingerprint.",))
if not inherited:
expect_cli(capsys, 1, *args, "check")
passing = case in {"fixed", "fresh"}
out, _ = expect_cli(capsys, int(not passing), *args, "ready")
assert passing or "not ready: check receipt has an incompatible settings fingerprint." in out
if not (passing or inherited):
expect_cli(capsys, 1, *args, "check")


def test_check_refuses_unverified_receipt_after_runner_retarget(wt, gh, capsys, head, tmp_path):
Expand Down Expand Up @@ -3480,7 +3480,7 @@ def membership(*_):
code, out, err = run(capsys, "merge", *(["--wait=1"] if wait else []))

calls = [c["argv"][:2] for c in gh.calls]
assert calls.count(LOOKUP_CALLS[0]) == 1
assert calls.count(LOOKUP_CALLS[0]) == 0
assert calls.count(detail.split()) == 2
if outcome == "merged":
assert (code, err) == (0, "") and out.splitlines()[-1] == merged_sha
Expand Down
8 changes: 4 additions & 4 deletions tests/test_github.py
Original file line number Diff line number Diff line change
Expand Up @@ -739,6 +739,8 @@ def test_app_identity_selection_and_cache(gh: FakeGh, tmp_path: Path, monkeypatc
monkeypatch.setattr(github.time, "CLOCK_BOOTTIME", 7, raising=False)
monkeypatch.setattr(github.time, "clock_gettime", lambda _: boot_time)
monkeypatch.setattr(github.time, "monotonic", lambda: 100.0) # stopped during host suspend
monkeypatch.setenv("GH_CONFIG_DIR", "/fixture/gh")
monkeypatch.setenv("XDG_CONFIG_HOME", "/fixture/xdg")
monkeypatch.setenv("GH_TOKEN", "operator-token")
gh.respond("api repos/acme/widgets", {})
gh.respond("api graphql viewer", {"data": {"viewer": {"login": "app[bot]"}}})
Expand All @@ -752,10 +754,8 @@ def test_app_identity_selection_and_cache(gh: FakeGh, tmp_path: Path, monkeypatc
github._gh("api", "repos/acme/widgets/issues/7/comments", "--method", "POST")
github._gh("api", "graphql", "-f", "query=mutation { resolveReviewThread(input: {}) { clientMutationId } }")
assert github.auth_token() == "operator-token"
assert [c["token"] for c in gh.calls] == [
"synthetic-app-token", "synthetic-app-token", "synthetic-app-token",
"operator-token", "operator-token", "operator-token",
]
assert [c["token"] for c in gh.calls] == ["synthetic-app-token"] * 3 + ["operator-token"] * 3
assert all(call["config"] == ["/fixture/gh", "/fixture/xdg"] for call in gh.calls)
assert counter.read_text().splitlines() == ["called"]
boot_time += 3_620
wall_time += 2_620 # The wall clock stepped back by a thousand seconds.
Expand Down
Loading