Skip to content
33 changes: 24 additions & 9 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1311,6 +1311,7 @@ def _warn_queue_size(

def cmd_ready(args: argparse.Namespace) -> int:
wt, config = _context(args, pin_checks=True)
read_started = time.monotonic()
pr, readiness = _pr_readiness(wt, config, worktree.branch(wt), workflow_wait=args.wait is not None)
assert readiness is not None
waiting = _draft_checks_waiting(config, pr, readiness)
Expand All @@ -1328,7 +1329,8 @@ def cmd_ready(args: argparse.Namespace) -> int:
):
waited = _wait_with_deadline(wt, config, pr, args.wait, kicked=kicked, started=started,
shown=readiness.reasons if kicked else (), args=args,
allow_skipped=True, initial=None if kicked else readiness)
allow_skipped=True, initial=None if kicked else readiness,
initial_read_time=started - read_started)
if waited is None:
return 3
pr, readiness, kicked = waited
Expand All @@ -1338,7 +1340,8 @@ def cmd_ready(args: argparse.Namespace) -> int:
github.mark_ready(config.repo, pr.number)
if args.wait is not None:
waited = _wait_with_deadline(wt, config, pr, args.wait, kicked=True, started=started,
args=args, allow_skipped=True)
args=args, allow_skipped=True,
initial_read_time=started - read_started)
if waited is None:
return 3
pr, readiness, kicked = waited
Expand Down Expand Up @@ -1403,17 +1406,25 @@ def _merge_check_hint(config: Config, pr: github.PR, readiness: github.Readiness
return ""


def _poll_until(started: float, timeout: float, *, bounded: bool = False) -> Iterator[None]:
def _poll_until(
started: float, timeout: float, *, bounded: bool = False, initial_read_time: float = 0.0,
) -> Iterator[None]:
delay = WAIT_INTERVAL
longest_read = initial_read_time
while True:
read_started = time.monotonic()
yield # Observe immediately, including --wait=0.
remaining = timeout - (time.monotonic() - started)
now = time.monotonic()
longest_read = max(longest_read, now - read_started)
remaining = timeout - (now - started)
if remaining <= 0:
return
pause = delay * random.uniform(0.9, 1.0)
if bounded and remaining <= pause:
# Leave part of the final interval for the last observation to complete.
_sleep(remaining / 2)
# Poll late enough to see a settled check while reserving time to read it.
baseline = min(5.0, max(0.5, remaining / 10))
allowance = min(remaining / 2, max(baseline, 2 * longest_read))
_sleep(remaining - allowance)
yield
remaining = timeout - (time.monotonic() - started)
if remaining > 0:
Expand All @@ -1427,6 +1438,7 @@ def _wait_with_deadline(
wt: Path, config: Config, pr: github.PR, timeout: float, *, kicked: bool,
started: float | None = None, shown: tuple[str, ...] = (), args: argparse.Namespace,
allow_merged: bool = False, allow_skipped: bool = False, initial: github.Readiness | None = None,
initial_read_time: float = 0.0,
) -> tuple[github.PR, github.Readiness | None, bool] | None:
started = time.monotonic() if started is None else started
wait = partial(_wait_for_checks, wt, config, pr, timeout, kicked=kicked, started=started,
Expand All @@ -1441,7 +1453,7 @@ def _wait_with_deadline(
reported_timeout = False
try:
with github.bounded_reads(deadline, token=None, retry=True):
waited = wait(bounded=True)
waited = wait(bounded=True, initial_read_time=initial_read_time)
reported_timeout = waited is None
except github.ReadDeadline:
if not reported_timeout:
Expand Down Expand Up @@ -1495,14 +1507,15 @@ def _wait_for_checks(
started: float | None = None, shown: tuple[str, ...] = (),
args: argparse.Namespace | None = None, bounded: bool = False, allow_merged: bool = False,
allow_skipped: bool = False, initial: github.Readiness | None = None,
initial_read_time: float = 0.0,
) -> tuple[github.PR, github.Readiness | None, bool] | None:
"""Poll the same head until it settles, omitting readiness for an allowed merge."""
grace_started = time.monotonic()
started = grace_started if started is None else started
current = pr
stale_notice = False
previous = config
for _ in _poll_until(started, timeout, bounded=bounded):
for _ in _poll_until(started, timeout, bounded=bounded, initial_read_time=initial_read_time):
if initial is not None:
readiness = initial
initial = None
Expand Down Expand Up @@ -1747,6 +1760,7 @@ def cmd_merge(args: argparse.Namespace) -> int:
mergify.dequeue(config.repo, pr.number)
print(f"requested removal of PR #{pr.number} from Mergify")
return 0
read_started = time.monotonic()
pr, readiness = _pr_readiness(
wt, config, branch, allow_merged=True, workflow_wait=args.wait is not None
)
Expand All @@ -1758,7 +1772,8 @@ def cmd_merge(args: argparse.Namespace) -> int:
# One waiter and one deadline span source checks and landing: a check created
# by the ready transition must not end the turn between `ready` and the queue.
waited = _wait_with_deadline(wt, config, pr, args.wait, kicked=False, started=started,
args=args, allow_merged=True, initial=readiness)
args=args, allow_merged=True, initial=readiness,
initial_read_time=started - read_started)
if waited is None:
return 3
pr, readiness, _ = waited
Expand Down
7 changes: 4 additions & 3 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
from loopzero.runners import review_settings
from loopzero.types import BLOCKING, Finding, ReviewResult

GH_ENV = ("PATH", "HOME", "LANG", "LC_ALL", "TERM", "GH_TOKEN", "GITHUB_TOKEN", "GH_HOST")
GH_BASE_ENV = ("PATH", "HOME", "LANG", "LC_ALL", "TERM", "GH_HOST")
GH_ENV = (*GH_BASE_ENV, "GH_TOKEN", "GITHUB_TOKEN")
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 @@ -297,7 +298,7 @@ def app_token() -> str:
return ""
minted = _app_token_clock() # before minting so a suspend mid-call ages the token
try:
result = run([str(APP_TOKEN_HELPER)], cwd=Path("/"), env_allowlist=GH_ENV, timeout=_read_timeout(10))
result = run([str(APP_TOKEN_HELPER)], cwd=Path("/"), env_allowlist=GH_BASE_ENV, timeout=_read_timeout(10))
except (ToolMissing, ProcTimeout, ReadDeadline, OSError):
return ""
if result.exit_code or not result.stdout.strip():
Expand Down Expand Up @@ -1463,7 +1464,7 @@ def delete_remote_branch(repo: str, branch: str, expected_head: str) -> bool:
env = {"GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull, "GIT_TERMINAL_PROMPT": "0"}
with tempfile.TemporaryDirectory(prefix="loopzero-cleanup-") as scratch:
init = ("git", "init", "--bare", "--template=")
done = run(init, cwd=scratch, env_allowlist=GH_ENV, extra_env=env, timeout=120)
done = run(init, cwd=scratch, env_allowlist=GH_BASE_ENV, extra_env=env, timeout=120)
if done.exit_code != 0:
raise GhError(init, done.stderr or done.stdout)
done = run(argv, cwd=scratch, env_allowlist=GH_ENV, extra_env=env, timeout=120)
Expand Down
57 changes: 21 additions & 36 deletions tests/test_architecture_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,43 +13,35 @@
SCRIPT = Path(__file__).resolve().parents[1] / "scripts/check_architecture_docs.py"


def prepare(repo):
@pytest.fixture
def base(git_repo):
for name in ("docs/ARCHITECTURE.md", "docs/README.md", "README.md", "AGENTS.md",
"core/CONTRACT.md"):
path = repo / name
path = git_repo / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("# Current\n")
git(repo, "add", ".")
git(repo, "commit", "-m", "architecture base")
return git(repo, "rev-parse", "HEAD").strip()
git(git_repo, "add", ".")
git(git_repo, "commit", "-m", "architecture base")
return git(git_repo, "rev-parse", "HEAD").strip()


def run(repo, base, *args):
return subprocess.run([sys.executable, str(SCRIPT), base, *args], cwd=repo,
text=True, capture_output=True, check=False)


@pytest.mark.skipif(sys.platform != "linux", reason="requires raw pathname bytes")
@pytest.mark.parametrize("staged", [False, True])
def test_architecture_check_accepts_non_utf8_path(git_repo, staged):
base = prepare(git_repo)
path = os.fsdecode(b"caf\xe9.txt")
(git_repo / path).write_text("unrelated file\n")
if staged:
git(git_repo, "add", "--", path)

done = run(git_repo, base)
assert done.returncode == 0, done.stderr

(git_repo / "core/CONTRACT.md").write_text("# New authority\n")
done = run(git_repo, base)
assert done.returncode == 1
assert "without guide update or reasoned Architecture-Review trailer" in done.stderr


@pytest.mark.parametrize("sync", ["missing", "guide", "trailer", "empty", "squash"])
def test_architecture_change_requires_update_or_reasoned_review(git_repo, sync):
base = prepare(git_repo)
@pytest.mark.parametrize("sync", ["missing", "guide", "trailer", "empty", "squash",
"untracked-non-utf8", "staged-non-utf8"])
def test_architecture_change_requires_update_or_reasoned_review(git_repo, base, sync):
if sync.endswith("non-utf8"):
if sys.platform != "linux":
pytest.skip("requires raw pathname bytes")
path = os.fsdecode(b"caf\xe9.txt")
(git_repo / path).write_text("unrelated file\n")
if sync == "staged-non-utf8":
git(git_repo, "add", "--", path)
done = run(git_repo, base)
assert done.returncode == 0, done.stderr
git(git_repo, "checkout", "-b", "authored")
(git_repo / "core/CONTRACT.md").write_text("# New authority\n")
if sync == "guide":
Expand All @@ -73,16 +65,14 @@ def test_architecture_change_requires_update_or_reasoned_review(git_repo, sync):


@pytest.mark.parametrize("target", ["absent.md", "../README.md#absent"])
def test_broken_local_link_fails_even_with_guide_update(git_repo, target):
base = prepare(git_repo)
def test_broken_local_link_fails_even_with_guide_update(git_repo, base, target):
(git_repo / "docs/ARCHITECTURE.md").write_text(f"# Current\n[reference]({target})\n")
done = run(git_repo, base)
assert done.returncode == 1
assert "invalid local" in done.stderr


def test_private_code_fix_needs_no_pointless_documentation_edit(git_repo):
base = prepare(git_repo)
def test_private_code_fix_needs_no_pointless_documentation_edit(git_repo, base):
path = git_repo / "src/loopzero/_cli_args.py"
path.parent.mkdir(parents=True)
path.write_text("def build_parser():\n return 'public'\n\ndef _fix():\n return 1\n")
Expand All @@ -96,8 +86,7 @@ def test_private_code_fix_needs_no_pointless_documentation_edit(git_repo):
assert run(git_repo, base).returncode == 1


def test_missing_base_fails_closed(git_repo):
prepare(git_repo)
def test_missing_base_fails_closed(git_repo, base):
assert run(git_repo, "not-a-revision").returncode == 1


Expand Down Expand Up @@ -127,10 +116,6 @@ def test_tach_enforces_module_boundaries(tmp_path):
repo_root = Path(__file__).resolve().parents[1]
tach = Path(sys.executable).with_name("tach")
assert tach.exists(), f"tach not installed next to {sys.executable}"
clean = subprocess.run([str(tach), "check"], cwd=repo_root,
text=True, capture_output=True, check=False)
assert clean.returncode == 0, clean.stdout + clean.stderr

shutil.copy2(repo_root / "tach.toml", tmp_path / "tach.toml")
shutil.copytree(repo_root / "src", tmp_path / "src")
types_py = tmp_path / "src/loopzero/types.py"
Expand Down
30 changes: 15 additions & 15 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2611,9 +2611,7 @@ def get(_repo, path):


@pytest.mark.parametrize("command", ["ready", "merge"])
def test_source_wait_reads_once_before_first_interval(
wt, gh, capsys, monkeypatch, source_queue_api, command,
):
def test_source_wait_reads_once_before_first_interval(wt, gh, capsys, monkeypatch, source_queue_api, command):
head = commit_mergify_configuration(wt)
arm_approved_pr_with_check_result(gh, head, wt, "pending", isDraft=False)
repo, config_path, vendor_calls = source_queue_api
Expand All @@ -2622,15 +2620,16 @@ def test_source_wait_reads_once_before_first_interval(

def after_sleep():
observations.append(([call["argv"][1] for call in gh.calls], len(vendor_calls)))
arm_check_runs(gh, head, [{"name": "checks", "conclusion": "success"}])
if clock.now >= 6:
arm_check_runs(gh, head, [{"name": "checks", "conclusion": "success"}])

clock = poll_clock(monkeypatch, jitter=1.0, after_sleep=after_sleep)
monkeypatch.setattr(mergify, "markers", lambda *_: (True, False))
monkeypatch.setattr(mergify, "membership", lambda *_: None)
monkeypatch.setattr(cli, "_wait_for_mergify", lambda *_: "e" * 40)

_out, _err = expect_cli(capsys, 0, command, "--wait=90", stderr="")
assert clock.now == cli.WAIT_INTERVAL
_out, _err = expect_cli(capsys, 0, command, "--wait=8", stderr="")
assert clock.now == pytest.approx(7.2)
[(before_sleep, vendor_count)] = observations
assert before_sleep.count(f"{repo}/pulls/7") == 1
assert before_sleep.count(reviews_key().split(" ", 1)[1]) == 1
Expand Down Expand Up @@ -2815,8 +2814,8 @@ def advance():

out, _err = expect_cli(capsys, expected, "ready", "--wait=40", stderr="")
assert "waiting: required check 'checks' is cancelled" in out
assert clock.sleeps == ([30.0, 5.0, 5.0] if replacement == "pending" else
[30.0, 5.0] if initial_pending else [30.0])
assert clock.sleeps == ([30.0, 9.0, 1.0] if replacement == "pending" else
[30.0, 9.0] if initial_pending else [30.0])
assert out.endswith(f"ready: {URL}\n" if expected == 0 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]}. Run `loopzero ready --wait` to resume on this head.\n")
Expand Down Expand Up @@ -2855,7 +2854,7 @@ def late_read(*args, **kwargs):
code, out, err = run(capsys, "ready", "--wait=40")

assert code == (1 if after in {"head_move", "blocker", "cancelled"} else 3)
assert clock.sleeps == ([30.0, 5.0, 5.0] if after == "pending" else [30.0])
assert clock.sleeps == ([30.0, 9.0, 1.0] if after == "pending" else [30.0])
assert "ready: https" not in out
assert ("PR head changed while waiting" in err) == (after == "head_move")
if after == "cancelled":
Expand Down Expand Up @@ -2889,7 +2888,7 @@ def advance():

assert (code, err) == (0 if run_appears else 3, "")
assert marked_at == [210.0]
assert clock.sleeps == [30.0, 60.0, 120.0, 30.0] + ([] if run_appears else [30.0, 30.0])
assert clock.sleeps == [30.0, 60.0, 120.0, 30.0] + ([] if run_appears else [55.0, 5.0])
assert out.endswith(f"ready: {URL}\n" if run_appears else
f"timed out waiting for required checks on {head[:12]}. Run `loopzero ready --wait` to resume on this head.\n")
assert sum(c["argv"][:2] == ["pr", "ready"] for c in gh.calls) == 1
Expand Down Expand Up @@ -3359,14 +3358,14 @@ def test_merge_wait_times_out_on_pending_checks_with_exit_three(
assert wt.exists() and all(c["argv"][:2] != ["pr", "merge"] for c in gh.calls)


def test_merge_wait_bounds_slow_source_check_read(wt, gh, capsys, monkeypatch, head, replay_gh):
@pytest.mark.parametrize("command", ["ready", "merge"])
def test_source_wait_bounds_slow_check_read(wt, gh, capsys, monkeypatch, head, replay_gh, command):
arm_approved_pr_with_check_result(gh, head, wt, "pending", isDraft=False)
budgets = []
initial_check_seen = False
run_gh = github.run
clock = poll_clock(monkeypatch, start=1000.0)
monkeypatch.setattr(github, "_retry_sleep", lambda _: None)

def slow_check(argv, *, timeout, **kwargs):
nonlocal initial_check_seen
if len(argv) > 2 and argv[2].endswith("/check-runs"):
Expand All @@ -3375,12 +3374,13 @@ def slow_check(argv, *, timeout, **kwargs):
clock.now += timeout
raise cli._proc.ProcTimeout("gh api timed out", "")
initial_check_seen = True
clock.now += 2.0
return run_gh(argv, timeout=timeout, **kwargs)

monkeypatch.setattr(github, "run", slow_check)
out, _err = expect_cli(capsys, 3, "merge", "--wait=16", stderr="")
assert budgets == pytest.approx([8.0])
assert f"timed out waiting for required checks on {head[:12]}. Run `loopzero merge --wait` to resume on this head." in out
out, _err = expect_cli(capsys, 3, command, "--wait=16", stderr="")
assert budgets == pytest.approx([4.0])
assert f"timed out waiting for required checks on {head[:12]}. Run `loopzero {command} --wait` to resume on this head." in out
assert all(c["argv"][:2] != ["pr", "merge"] for c in gh.calls)


Expand Down
Loading
Loading