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
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
35 changes: 29 additions & 6 deletions src/loopzero/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,16 +89,39 @@ def base_revision(worktree: Path, base_branch: str) -> str:
raise ConfigError(f"git rev-parse origin/{base_branch} failed: {message}")


def _remote_workflow(worktree: Path, branch: str) -> tuple[Config, str]:
def _has_replacement_refs(common_dir: Path) -> bool:
# A replacement can change what Git reads at a fixed object name.
for entry in ("refs/replace", "reftable"):
try:
(common_dir / entry).lstat()
except FileNotFoundError:
continue
except OSError:
return True
return True
try:
packed = (common_dir / "packed-refs").read_bytes()
except FileNotFoundError:
return False
except OSError:
return True
return b" refs/replace/" in packed


def _remote_workflow(worktree: Path, branch: str, previous: Config | None) -> tuple[Config, str]:
source = f"origin/{branch}:workflow.toml"
hint = "Fetch the trusted base workflow, or supply --config for bootstrap or an override."
directory_args = ["--path-format=absolute", "--git-common-dir"] if previous is not None else []
resolved = _proc.run(
["git", "rev-parse", "--verify", f"refs/remotes/origin/{branch}^{{commit}}"],
["git", "rev-parse", *directory_args, "--verify", f"refs/remotes/origin/{branch}^{{commit}}"],
cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60,
)
if resolved.exit_code != 0:
raise ConfigError(f"{source} has no remote-tracking base commit. {hint}")
revision = resolved.stdout.strip()
common_dir, _, revision = resolved.stdout.rstrip("\n").rpartition("\n")
if (previous is not None and previous.base_branch == branch and previous.trusted_base_revision == revision
and common_dir and not _has_replacement_refs(Path(common_dir))):
return previous, revision
shown = _proc.run(
["git", "show", f"{revision}:workflow.toml"],
cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60,
Expand All @@ -115,7 +138,7 @@ def _remote_workflow(worktree: Path, branch: str) -> tuple[Config, str]:
raise ConfigError(f"{source}: {exc}. {hint}") from None


def load_trusted(worktree: Path) -> Config:
def load_trusted(worktree: Path, *, previous: Config | None = None) -> Config:
"""Select delivery policy using Git's origin default and its trusted workflow."""
prefix = "refs/remotes/origin/"
default = _proc.run(
Expand All @@ -129,10 +152,10 @@ def load_trusted(worktree: Path) -> Config:
"or supply --config for bootstrap or an override."
)
branch = ref.removeprefix(prefix)
policy, revision = _remote_workflow(worktree, branch)
policy, revision = _remote_workflow(worktree, branch, previous)
if policy.base_branch == branch:
return replace(policy, trusted_base_revision=revision)
base, revision = _remote_workflow(worktree, policy.base_branch)
base, revision = _remote_workflow(worktree, policy.base_branch, previous)
if base.base_branch != policy.base_branch:
raise ConfigError("trusted origin workflows disagree on repo.base; align them or supply --config")
return replace(base, trusted_base_revision=revision)
Expand Down
28 changes: 14 additions & 14 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@

REPO = "acme/widgets"
URL = f"https://github.com/{REPO}/pull/7"
FAILED_CHECK_HINT = f". Inspect {URL}/checks. Fix reproducible failures before retrying. Rerun the failed job only for a transient failure. Once green, run `loopzero ready --wait`."
MERGIFY_QUEUE_FIXTURE = json.loads((Path(__file__).with_name("fixtures") / "mergify-queue.json").read_text())
BRANCH_READ = branch_head_key().split()
PR_LIST_READ = pr_list_key().split()
Expand Down Expand Up @@ -2319,6 +2320,7 @@ def test_ready_not_ready_lists_reasons(wt: Path, gh: FakeGh, capsys, head) -> No
arm_check_runs(gh, head, [{"name": "checks", "status": "completed", "conclusion": "failure",
"check_suite": {"id": 10}}])
code, out, _ = run(capsys, "ready")
out = out.replace(FAILED_CHECK_HINT, "")
assert code == 1
assert without_accepted_receipt(out).splitlines() == [
f"not ready: Both review rounds are spent (primary + delta) and {head[:12]} has no eligible review. Open a replacement PR for changes that need review. Another `loopzero review` on this PR will be refused.",
Expand All @@ -2330,7 +2332,7 @@ def test_ready_not_ready_lists_reasons(wt: Path, gh: FakeGh, capsys, head) -> No

@pytest.mark.parametrize("retargeted,reason", [
(True, "PR targets release, configured base is main"),
(False, "required check 'checks' is failure"),
(False, f"required check 'checks' is failure{FAILED_CHECK_HINT}"),
], ids=["retargeted", "trust-base-required-ci"])
def test_ready_explains_trusted_policy_blocker(wt, gh, capsys, head, retargeted, reason):
if retargeted:
Expand All @@ -2341,8 +2343,7 @@ def test_ready_explains_trusted_policy_blocker(wt, gh, capsys, head, retargeted,

code, out, err = run(capsys, "ready")

assert (code, err) == (1, "")
assert without_accepted_receipt(out) == f"not ready: {reason}\n"
assert (code, err, without_accepted_receipt(out)) == (1, "", f"not ready: {reason}\n")


def test_pending_required_check_names_the_wait(wt: Path, gh: FakeGh, capsys, head) -> None:
Expand Down Expand Up @@ -2391,14 +2392,14 @@ def test_skipped_required_check_activates_only_on_ready(wt, gh, capsys, head, dr
assert all(c["argv"][:2] != ["pr", "ready"] for c in gh.calls)


def test_ready_wait_reports_initial_draft_blocker_once(wt, gh, capsys, monkeypatch, head):
def test_ready_wait_reports_initial_draft_blocker_once(wt, gh, capsys, monkeypatch, head, git_calls):
arm_approved_pr_with_check_result(gh, head, wt, "skipped", isDraft=True)
arm_check_progress(gh, head, "skipped", "skipped", "pending", "success")
gh.respond("pr ready", "")

git_calls.clear()
monkeypatch.setattr(cli, "_sleep", lambda _: None)
code, out, err = run(capsys, "ready", "--wait")

assert sum(call[0] == "show" and call[-1].endswith(":workflow.toml") for call in git_calls) == 1
assert (code, err) == (0, "")
assert out.count("receipt accepted:") == 1
assert without_accepted_receipt(out).splitlines() == [
Expand Down Expand Up @@ -2645,7 +2646,7 @@ def sleep(seconds):

assert (code, err) == (expected, "")
assert out.endswith({
0: f"ready: {URL}\n", 1: "not ready: required check 'checks' is failure\n",
0: f"ready: {URL}\n", 1: f"not ready: required check 'checks' is failure{FAILED_CHECK_HINT}\n",
3: f"timed out waiting for required checks on {head[:12]}\n",
}[expected])

Expand Down Expand Up @@ -2682,7 +2683,7 @@ def sleep(seconds: float) -> None:
assert "timed out waiting for required checks" in out
else:
assert out.endswith(f"ready: {URL}\n" if expected == 0 else
"not ready: required check 'checks' is failure\n")
f"not ready: required check 'checks' is failure{FAILED_CHECK_HINT}\n")


@pytest.mark.usefixtures("replay_gh")
Expand Down Expand Up @@ -2730,7 +2731,7 @@ def advance(seconds):
assert sleeps == ([30.0, 5.0, 5.0] if replacement == "pending" else
[30.0, 5.0] if initial_pending else [30.0])
assert out.endswith(f"ready: {URL}\n" if expected == 0 else
"not ready: required check 'checks' is failure\n" if expected == 1 else
f"not ready: required check 'checks' is failure{FAILED_CHECK_HINT}\n" if expected == 1 else
f"timed out waiting for required checks on {head[:12]}\n")
assert sum(c["argv"][:2] == ["pr", "ready"] for c in gh.calls) == 1

Expand Down Expand Up @@ -2928,7 +2929,7 @@ def advance(seconds):
)
assert (code, err, bool(sleeps)) == (expected, "", waited)
assert out.endswith(f"ready: {URL}\n" if expected == 0 else
f"not ready: required check '{name}' is failure\n")
f"not ready: required check '{name}' is failure{FAILED_CHECK_HINT}\n")
assert (f"waiting: required check '{name}' is failure" in out) == waited
assert out.count("predates the review; awaiting refresh") == int(
waited and (age < 0 or age >= 120) and not pending
Expand Down Expand Up @@ -3196,14 +3197,13 @@ def test_ready_respects_latest_review_state(wt: Path, gh: FakeGh, capsys, state,
def test_merge_refuses_when_not_ready(wt: Path, gh: FakeGh, capsys, head) -> None:
arm_pr(gh, head, isDraft=False)
gh.respond(reviews_key(), [rev(head, "primary")])
arm_readiness(gh, head, wt, threads=(
arm_readiness(gh, head, wt, conclusion="failure", threads=(
{"isResolved": False, "isOutdated": False, "path": "feature.py", "line": 1,
"comments": {"nodes": [{"body": f"<!-- loopzero:finding severity=critical head={head} -->"
"\n**critical: Bad**"}]}},))
code, out, err = run(capsys, "merge")
out = without_accepted_receipt(out)
assert code == 1 and out == ""
assert "not ready to merge: open critical finding at feature.py:1: Bad" in err
assert code == 1 and without_accepted_receipt(out) == ""
assert f"not ready to merge: open critical finding at feature.py:1: Bad; required check 'checks' is failure{FAILED_CHECK_HINT}" in err
assert wt.exists()


Expand Down
Loading