Skip to content
Merged
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 @@ -114,6 +114,8 @@ The [CLI](../src/loopzero/cli.py) implements the contract's
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
18 changes: 11 additions & 7 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,14 +104,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 @@ -1313,17 +1315,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 @@ -1341,13 +1344,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
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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Replacement-ref guard and cache-miss paths have no automated coverage

_has_replacement_refs is a new hand-written probe of Git's on-disk layout: the loose refs/replace directory, reftable, and packed-refs. The only evidence for it is the manual check described in the task. No test runs the loose or packed replacement case, a ref move between polls, or the two-branch setup where origin/HEAD differs from repo.base. If this guard regresses, the waiter could quietly keep using a stale parsed policy, and nothing would catch it. Two cheap tests would close the gap: one that writes a refs/replace/<sha> line to packed-refs, and one that moves origin/<base> between polls, each asserting that the workflow blob is read again. Those tests would add lines, which conflicts with the no-net-test-lines goal, so this is non-blocking.

# 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Split default/base configuration still rereads the default branch workflow every poll

previous holds the policy from the base branch. When origin/HEAD points at a different branch than repo.base, the first _remote_workflow(worktree, branch, previous) call fails previous.base_branch == branch, so it runs git show and parses the default branch's workflow on every poll. That is correct, just not cached. In this setup the wait still makes one blob read per poll instead of one in total. If that setup matters, the cache would need to key on the default branch's revision as well. Otherwise, note in ARCHITECTURE.md that reuse only covers the base workflow.

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
6 changes: 3 additions & 3 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2391,14 +2391,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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Inline workflow-read count duplicates existing assert_git_cost helper

The new assertion reimplements the show ... :workflow.toml counting predicate already defined in assert_git_cost (tests/test_cli.py:306-308). If the predicate ever changes (for example, the blob read moves to cat-file), the two copies will drift apart. Factor the predicate into a small shared helper that both call sites use, or use assert_git_cost(git_calls, <total>, 1). Pinning the total would also lock in the claimed reduction from 41 to 30 Git commands, which the current test does not check.

assert (code, err) == (0, "")
assert out.count("receipt accepted:") == 1
assert without_accepted_receipt(out).splitlines() == [
Expand Down
Loading