diff --git a/.github/workflows/eligibility.yml b/.github/workflows/eligibility.yml index a85b85ba..d2673492 100644 --- a/.github/workflows/eligibility.yml +++ b/.github/workflows/eligibility.yml @@ -1,4 +1,5 @@ name: review eligibility +run-name: "${{ inputs.pr && format('Refresh eligibility for PR #{0}', inputs.pr) || '' }}" on: pull_request_target: types: [opened, synchronize, reopened, edited, ready_for_review, converted_to_draft, labeled, unlabeled] diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 7476ad50..cb219532 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1860,7 +1860,8 @@ def _delete_tracking_ref(wt: Path, branch: str, expected_head: str) -> None: def cmd_resolve(args: argparse.Namespace) -> int: encoding = getattr(sys.stdout, "encoding", None) or "utf-8" wt, config = _context(args, pin_checks=True) # publishers come from the base, not the PR - pr = _require_pr(config, worktree.branch(wt)) + branch = worktree.branch(wt) + pr = _require_pr(config, branch) if pr.base_ref != config.base_branch: # trusted publishers belong to the configured base raise CliError(f"PR #{pr.number} targets {pr.base_ref}, configured base is {config.base_branch}") publishers = config.review_publishers or (github.login(),) @@ -1884,7 +1885,7 @@ def cmd_resolve(args: argparse.Namespace) -> int: f"Then, if no findings remain, run `{retry}`." ) from exc if not remaining: - github.refresh_eligibility(config.repo, pr.number, config.base_branch) + github.refresh_eligibility(config.repo, pr, branch, config.base_branch, publishers) print(f"refreshed Loop-zero Eligibility for PR #{pr.number}") return 0 diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 3f535c3e..80d1b365 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -1139,13 +1139,44 @@ def eligibility_dispatch_args(repo: str, number: int, base: str) -> tuple[str, . "-f", f"ref={base}", "-f", f"inputs[pr]={number}") -def refresh_eligibility(repo: str, number: int, base: str) -> None: - args = eligibility_dispatch_args(repo, number, base) +def _eligibility_dispatched(repo: str, number: int, base: str, since: str) -> bool: + query = f"event=workflow_dispatch&branch={quote(base, safe='')}&created={quote('>=' + since, safe='')}&per_page=100" + data = api_get(f"repos/{repo}/actions/workflows/eligibility.yml/runs?{query}") + runs = data.get("workflow_runs") if isinstance(data, dict) else None + complete = isinstance(runs, list) and data.get("total_count") == len(runs) + identified = [run.get("display_title") if isinstance(run, dict) else None for run in runs] if complete else [] + if f"Refresh eligibility for PR #{number}" in identified: + return True + if not complete or any(not isinstance(name, str) or not re.fullmatch(r"Refresh eligibility for PR #[0-9]+", name) for name in identified): + raise GhError(("refresh Loop-zero Eligibility",), "could not identify all recent refresh runs") + return False + + +def refresh_eligibility(repo: str, pr: PR, branch: str, base: str, publishers: tuple[str, ...]) -> None: + args = eligibility_dispatch_args(repo, pr.number, base) + since = datetime.fromtimestamp(time.time(), UTC).isoformat(timespec="seconds") try: - _gh(*args) + try: + _gh(*args) + except (GhUnavailable, ProcTimeout) as exc: + if isinstance(exc, GhUnavailable) and not _transient_error(exc.tail, False): + raise + _retry_sleep(RETRY_DELAY) + current = pr_for_branch(repo, branch, open_only=True) + if current is None or (current.number, current.head_sha, current.base_ref) != ( + pr.number, pr.head_sha, pr.base_ref, + ): + raise GhError(("refresh Loop-zero Eligibility",), "the PR or head changed after resolution") from exc + if _eligibility_dispatched(repo, pr.number, base, since): + return + if open_blocking_findings(repo, pr.number, None, publishers): + raise GhError(("refresh Loop-zero Eligibility",), "blocking findings appeared after resolution") from exc + _gh(*args) except (GhError, ProcTimeout, OSError) as exc: retry = shlex.join(("gh", *args)) - raise GhError(("refresh Loop-zero Eligibility",), f"{exc}\nRun manually: {retry}") from exc + raise GhError(("refresh Loop-zero Eligibility",), + f"Finding on PR #{pr.number} is resolved. {exc}\n" + f"Verify the PR head, remaining findings and recent runs before retrying: {retry}") from exc def open_blocking_findings( diff --git a/tests/test_cli.py b/tests/test_cli.py index f06bb890..d9122117 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4022,14 +4022,20 @@ def finding_pr(wt, gh, head): THREAD_RESOLVED = {"data": {"resolveReviewThread": {"thread": {"isResolved": True}}}} -@pytest.mark.parametrize("outcome", ["refreshed", "remaining", "dispatch failed"]) -def test_resolve_lists_then_replies_and_resolves_one_finding(finding_pr, gh: FakeGh, capsys, outcome) -> None: +@pytest.mark.parametrize("outcome", ["refreshed", "remaining", "denied", "applied", "retry", "unknown"]) +def test_resolve_lists_then_replies_and_resolves_one_finding(finding_pr, gh: FakeGh, capsys, monkeypatch, outcome) -> None: sys.stdout.reconfigure(encoding="ascii" if outcome == "refreshed" else "utf-8", errors="strict") finding_pr["comments"]["nodes"][0]["body"] = finding_pr["comments"]["nodes"][0]["body"].replace("Off by one", "Łódź") - listing = threads_json({**finding_pr, "path": "src/Łódź.py"}) + listing, backoffs = threads_json({**finding_pr, "path": "src/Łódź.py"}), [] gh.respond("api graphql", listing, listing, REPLY_ACCEPTED, THREAD_RESOLVED, listing if outcome == "remaining" else threads_json()) - gh.respond("api -X", "", exit=int(outcome == "dispatch failed"), stderr="HTTP 403") + transient = outcome in {"applied", "retry", "unknown"} + gh.respond("api -X", {"stdout": "", "exit": 1, "stderr": "HTTP 503" if transient else "HTTP 403"} if transient or outcome == "denied" else "", "") + monkeypatch.setattr(github, "_retry_sleep", backoffs.append) + runs = [] if outcome == "retry" else [{"display_title": "Refresh eligibility for PR #7" if outcome == "applied" else "unknown"}] + monkeypatch.setattr(github.time, "time", lambda: 1795640554) + endpoint = ELIGIBILITY_DISPATCH.removesuffix("/dispatches") + gh.respond(f"api {endpoint}/runs?event=workflow_dispatch&branch=main&created=%3E%3D2026-11-25T21%3A02%3A34%2B00%3A00&per_page=100", {"workflow_runs": runs, "total_count": len(runs)}) title = r"\u0141\xf3d\u017a" if outcome == "refreshed" else "Łódź" expect_cli(capsys, 0, "resolve", stderr="", stdout=f"0b9b59e7 important src/{title}.py:3 {title}\n") assert not any("eligibility.yml/dispatches" in " ".join(c["argv"]) for c in gh.calls) @@ -4040,15 +4046,14 @@ def test_resolve_lists_then_replies_and_resolves_one_finding(finding_pr, gh: Fak assert "addPullRequestReviewThreadReply" in calls[0][3] and "resolveReviewThread" in calls[1][3] assert "body=Fixed in abc1234: loop bound corrected." in calls[0] and "thread=THREAD_1" in calls[1] dispatches = [c["argv"] for c in gh.calls if ELIGIBILITY_DISPATCH in c["argv"]] - if outcome == "remaining": - assert (code, err, dispatches, len(out.splitlines())) == (0, "", [], 1) + assert dispatches == [["api", "-X", "POST", ELIGIBILITY_DISPATCH, "-f", "ref=main", "-f", "inputs[pr]=7", "--include"]] * {"remaining": 0, "retry": 2}.get(outcome, 1) + assert backoffs == ([5] if transient else []) + if outcome in {"denied", "unknown"}: + assert code == 1 and "is resolved." in err and ("HTTP 403" if outcome == "denied" else "identify all recent refresh runs") in err + assert f"gh api -X POST {ELIGIBILITY_DISPATCH} -f ref=main -f 'inputs[pr]=7'" in err else: - assert dispatches == [["api", "-X", "POST", ELIGIBILITY_DISPATCH, "-f", "ref=main", "-f", "inputs[pr]=7", "--include"]] - if outcome == "refreshed": - assert (code, err) == (0, "") and out.splitlines()[-1] == "refreshed Loop-zero Eligibility for PR #7" - else: - assert code == 1 and "HTTP 403" in err - assert f"gh api -X POST {ELIGIBILITY_DISPATCH} -f ref=main -f 'inputs[pr]=7'" in err + assert (code, err) == (0, "") + assert out.splitlines()[1:] == ([] if outcome == "remaining" else ["refreshed Loop-zero Eligibility for PR #7"]) @pytest.mark.parametrize("cut", ["reply", "resolution"]) diff --git a/tests/test_config.py b/tests/test_config.py index 3aa91cea..37aaa373 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -65,7 +65,8 @@ def test_missing_file(tmp_path): config.load(tmp_path / "nope.toml") -MINIMAL = '[repo]\nname = "o/n"\n' +FORBIDDEN = ["/", "/home", "/root", "/run", "/var/run", "/run/user/1000", "/proc/1", "/dev", + "/var/run/docker.sock", "/sys/fs", "/tmp/../run"] @pytest.mark.parametrize("text,message", [ @@ -102,6 +103,7 @@ def test_missing_file(tmp_path): (MINIMAL + '[delivery.review.codex]\nallowed_efforts = "medium"\n', "allowed_efforts must be a list"), (MINIMAL + '[checks]\nro_paths = ["rel/path"]\n', "must be absolute"), + *((MINIMAL + table("checks", ro_paths=[path]), "must not expose") for path in FORBIDDEN), (MINIMAL + '[checks]\nwritable = ["/run/x"]\n', "writable must not expose"), *((MINIMAL + f'[checks]\nscratch = ["{path}"]\n', "scratch entries must be relative") for path in ("../x", "/abs")), @@ -127,24 +129,12 @@ def test_invalid_content(tmp_path, text, message): assert str(info.value).startswith(str(tmp_path / "workflow.toml")) -FORBIDDEN = ["/", "/home", "/root", "/run", "/var/run", "/run/user/1000", "/proc/1", "/dev"] -FORBIDDEN += ["/var/run/docker.sock", "/sys/fs", "/tmp/../run"] - - @pytest.mark.parametrize("runner", [("dispatch", "--stage"), ("python3", "tools/run_stage.py"), ("dispatch", "--opt=/operator/run.py")]) def test_runner_prefix(tmp_path, runner): assert config.load(write(tmp_path, MINIMAL + f"[checks]\nrunner = {list(runner)!r}")).check_runner == runner -@pytest.mark.parametrize("path,allowed", [ - *((path, False) for path in FORBIDDEN), - *((path, True) for path in ("/home/me/.local/bin", "/opt/tool", "/tmp/x")), -]) -def test_ro_path_boundary(tmp_path, path, allowed): - cfg = write(tmp_path, f'[repo]\nname = "o/n"\n[checks]\nro_paths = ["{path}"]\n') - if allowed: - assert config.load(cfg).sandbox_ro == (path,) - else: - with pytest.raises(config.ConfigError, match="must not expose"): - config.load(cfg) +@pytest.mark.parametrize("path", ["/home/me/.local/bin", "/opt/tool", "/tmp/x"]) +def test_ro_path_boundary(tmp_path, path): + assert config.load(write(tmp_path, MINIMAL + table("checks", ro_paths=[path]))).sandbox_ro == (path,) diff --git a/tests/test_proc.py b/tests/test_proc.py index 65b5a209..d0a04713 100644 --- a/tests/test_proc.py +++ b/tests/test_proc.py @@ -44,15 +44,6 @@ def run(script, *, timeout=30, env_allowlist=("PATH",), unbuffered=False, args=( return run -def test_run_strips_environment_to_allowlist(run_python, monkeypatch): - monkeypatch.delenv("LZ_ABSENT", raising=False) - monkeypatch.setenv("LZ_SECRET", "nope") - monkeypatch.setenv("LZ_KEEP", "yes") - done = run_python("import os; print(sorted(k for k in os.environ if k.startswith('LZ_')))", - env_allowlist=("PATH", "LZ_KEEP", "LZ_ABSENT"), extra_env={"LZ_EXTRA": "1"}) - assert done.stdout.strip() == "['LZ_EXTRA', 'LZ_KEEP']" - - def test_run_raises_tool_missing(tmp_path): with pytest.raises(_proc.ToolMissing, match="definitely-not-a-tool"): _proc.run(["definitely-not-a-tool"], cwd=tmp_path, env_allowlist=("PATH",), timeout=30) @@ -122,14 +113,21 @@ def communicate(self, input=None, timeout=None): @pytest.mark.parametrize("merge,stderr", [(True, ""), (False, "b\n")]) -def test_run_captures_exit_duration_cwd_and_streams(tmp_path, run_python, merge, stderr): +def test_run_captures_streams_and_allowlisted_environment(tmp_path, run_python, monkeypatch, merge, stderr): + monkeypatch.delenv("LZ_ABSENT", raising=False) + monkeypatch.setenv("LZ_SECRET", "nope") + monkeypatch.setenv("LZ_KEEP", "yes") done = run_python( - "import os,sys; print(os.getcwd()); print('b', file=sys.stderr); print(sys.argv[1]); sys.exit(3)", - unbuffered=True, merge_output=merge, env_allowlist=(), args=("argument with spaces",), + "import os,sys; print(os.getcwd()); print('b', file=sys.stderr); print(sys.argv[1]); " + "print(sorted(k for k in os.environ if k.startswith('LZ_'))); sys.exit(3)", + unbuffered=True, merge_output=merge, args=("argument with spaces",), + env_allowlist=("PATH", "LZ_KEEP", "LZ_ABSENT"), extra_env={"LZ_EXTRA": "1"}, ) assert (done.exit_code, done.stderr) == (3, stderr) assert done.duration_s >= 0 - assert done.stdout.splitlines() == [str(tmp_path.resolve()), *(["b"] if merge else []), "argument with spaces"] + assert done.stdout.splitlines() == [ + str(tmp_path.resolve()), *(["b"] if merge else []), "argument with spaces", "['LZ_EXTRA', 'LZ_KEEP']", + ] def test_tail_keeps_last_lines(): @@ -138,7 +136,7 @@ def test_tail_keeps_last_lines(): assert _proc.tail("", 3) == "" -def test_explicit_utf8_input_under_ascii_parent_locale(tmp_path): +def test_explicit_utf8_input_under_ascii_parent_locale(run_python): source = str(Path(_proc.__file__).resolve().parents[1]) script = r""" import locale, sys @@ -150,10 +148,8 @@ def test_explicit_utf8_input_under_ascii_parent_locale(tmp_path): assert _proc.run(argv, input='\u03a9', **options).stdout.strip() == '3f' print(_proc.run(argv, input='\u03a9\r\n\u2028\r', encoding='utf-8', **options).stdout.strip()) """ - done = _proc.run( - [sys.executable, "-c", script], cwd=tmp_path, env_allowlist=(), timeout=30, - extra_env={"PYTHONPATH": source, "LC_ALL": "C", "PYTHONUTF8": "0", - "PYTHONCOERCECLOCALE": "0"}, - ) + done = run_python(script, env_allowlist=(), extra_env={ + "PYTHONPATH": source, "LC_ALL": "C", "PYTHONUTF8": "0", "PYTHONCOERCECLOCALE": "0", + }) assert done.exit_code == 0, done.stderr assert done.stdout.strip() == "Ω\r\n\u2028\r".encode("utf-8").hex() diff --git a/tests/test_size_budget.py b/tests/test_size_budget.py index 0acf66dc..64ce0033 100644 --- a/tests/test_size_budget.py +++ b/tests/test_size_budget.py @@ -45,16 +45,13 @@ def test_size_budget_counts_unicode_and_propagates_read_errors(git_repo, fake_to source.parent.mkdir(parents=True) source.write_text("one\ntwo\n") source.with_name("z.py").write_text("three\n") - git(git_repo, "add", ".") - base = git(git_repo, "write-tree").strip() + base = stage_tree(git_repo) if failure == "deleted": # unstaged deletion: skipped, not an error source.unlink() elif failure == "show": fake_tool("git", 'if [ "$1" = show ]; then case "$2" in */a.py) exit 1;; esac; fi\n' f'exec {shutil.which("git")} "$@"\n') - done = subprocess.run(["bash", str(SCRIPT), base], cwd=git_repo, - env={**os.environ, "PYTHON": sys.executable}, - capture_output=True, text=True, check=False) + done = run_budget(git_repo, base) assert bool(done.returncode) is (failure == "show") if failure != "show": assert done.stdout.startswith("src=1 (base 3," if failure else "src=3 (base 3, delta 0,") @@ -82,38 +79,29 @@ def module_path(git_repo): _HOT_FUNCTION = _branchy("hot", 11) -@pytest.mark.parametrize("before,after,expected_rc", [ - pytest.param(_SIMPLE_FUNCTION, _branchy("new_hot", 10), 1, id="new_over_cap"), - pytest.param(_HOT_FUNCTION, _HOT_FUNCTION, 0, id="existing_hold"), - pytest.param(_HOT_FUNCTION, _branchy("hot", 10), 0, id="existing_shrink"), - pytest.param(_HOT_FUNCTION, _branchy("hot", 12), 1, id="existing_grow"), +_CONTEXT_MANAGERS = "".join(f" with contextlib.suppress(ValueError):\n y = {i}\n" + for i in range(11)) +_PEP758 = "import contextlib\ndef pep758(x):\n" + _CONTEXT_MANAGERS + ( + " try:\n return int(x) + y\n except KeyError, TypeError:\n return 0\n" +) + + +@pytest.mark.parametrize("before,after,over_cap,regressions", [ + pytest.param(_SIMPLE_FUNCTION, _branchy("new_hot", 10), 1, 1, id="new_over_cap"), + pytest.param(_HOT_FUNCTION, _HOT_FUNCTION, 1, 0, id="existing_hold"), + pytest.param(_HOT_FUNCTION, _branchy("hot", 10), 1, 0, id="existing_shrink"), + pytest.param(_HOT_FUNCTION, _branchy("hot", 12), 1, 1, id="existing_grow"), + pytest.param(_PEP758, _PEP758, 0, 0, id="pep758_with_blocks"), ]) -def test_complexity_ratchet(git_repo, module_path, before, after, expected_rc): +def test_complexity_ratchet(git_repo, module_path, before, after, over_cap, regressions): module_path.write_text(before) base = stage_tree(git_repo) if after != before: module_path.write_text(after) done = run_budget(git_repo, base) - assert done.returncode == expected_rc, done.stdout + done.stderr - assert ("complexity=FAIL" if expected_rc else "complexity=PASS") in done.stdout - - -def test_complexity_parses_pep758_and_ignores_with_blocks(git_repo, module_path): - with_blocks = "".join(f" with contextlib.suppress(ValueError):\n y = {i}\n" - for i in range(11)) - module_path.write_text( - "import contextlib\n" - "def pep758(x):\n" - f"{with_blocks}" - " try:\n" - " return int(x) + y\n" - " except KeyError, TypeError:\n" - " return 0\n" - ) - base = stage_tree(git_repo) - done = run_budget(git_repo, base) - assert done.returncode == 0, done.stdout + done.stderr - assert "complexity=PASS (cap 10, over_cap 0, regressions 0)" in done.stdout + assert done.returncode == int(bool(regressions)), done.stdout + done.stderr + result = "FAIL" if regressions else "PASS" + assert f"complexity={result} (cap 10, over_cap {over_cap}, regressions {regressions})" in done.stdout def test_complexity_rejects_old_python(git_repo, module_path, tmp_path): @@ -133,13 +121,9 @@ def test_complexity_rejects_old_python(git_repo, module_path, tmp_path): assert "requires Python 3.14+" in done.stderr -@pytest.mark.parametrize("path,cap,grew,expected_rc", [ - ("core/CONTRACT.md", 1500, True, 1), - ("core/CONTRACT.md", 1500, False, 0), - ("docs/DELEGATION.md", 660, True, 1), - ("docs/DELEGATION.md", 660, False, 0), -]) -def test_markdown_doc_budgets(git_repo, path, cap, grew, expected_rc): +@pytest.mark.parametrize("path,cap", [("core/CONTRACT.md", 1500), ("docs/DELEGATION.md", 660)]) +@pytest.mark.parametrize("grew", [True, False]) +def test_markdown_doc_budgets(git_repo, path, cap, grew): doc = git_repo / path doc.parent.mkdir(parents=True) doc.write_text("line\n" * (cap + 5)) @@ -147,4 +131,4 @@ def test_markdown_doc_budgets(git_repo, path, cap, grew, expected_rc): if grew: doc.write_text("line\n" * (cap + 6)) done = run_budget(git_repo, base) - assert done.returncode == expected_rc, done.stdout + done.stderr + assert done.returncode == int(grew), done.stdout + done.stderr