From 0c52688ff881c7eaf548c0e1361021cf0f2f11b4 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Thu, 19 Nov 2026 23:30:30 +0100 Subject: [PATCH] =?UTF-8?q?Answer=20stability=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=203=20=F0=9F=9F=A1=20(0=20misread);=20bound=20the?= =?UTF-8?q?=20forge's=20CLI=20with=20a=20timeout=20in=20one=20runner,=20an?= =?UTF-8?q?d=20read=20a=20pull=20request=20from=20a=20deleted=20fork?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/chunk_preflight/main.py | 14 ++---------- bin/chunk_preflight/test_chunk_preflight.py | 8 +++---- bin/forge/commands.py | 7 ++++-- bin/forge/pulls.py | 6 +++--- bin/forge/test_forge.py | 24 +++++++++++++++------ bin/loop_effects/effects.py | 4 +++- bin/release_plan/test_release_standing.py | 2 +- 7 files changed, 35 insertions(+), 30 deletions(-) diff --git a/bin/chunk_preflight/main.py b/bin/chunk_preflight/main.py index 86e00ba6..567c9e7d 100644 --- a/bin/chunk_preflight/main.py +++ b/bin/chunk_preflight/main.py @@ -83,7 +83,7 @@ import typing from git_cli.git_repo import commit_exists, default_branch, file_at, git, top from failure import Failure -from forge.commands import Forge, forge_of, Run +from forge.commands import Forge, forge_of, Run, runner from chunk_preflight.gathered import Gathered, ItemFacts, LeftWorktree, NamedPath, Ran, Worktree from chunk_preflight.facts import JOINING_DETAILS, render from project_config.main import located @@ -149,7 +149,7 @@ def preflight(root: pathlib.Path, timeout: float, make: bool, item_id: int | Non if isinstance(config, Failure): return config outside = None if config.tracked("plan") else config.plan_label - forge_run = forge_runner(root, timeout) + forge_run = runner(str(root), timeout) held = project_plan(config, ref, str(root), forge_run=forge_run) plan = planned(held.plan, held.cut, ref, config.branch, outside, item_id) item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout, make) @@ -189,16 +189,6 @@ def left_worktrees(root: pathlib.Path, forge_run: Run) -> tuple[LeftWorktree, .. return tuple(LeftWorktree(path, branch, pull) for path, branch, pull in merged if isinstance(pull, str)) -def forge_runner(root: pathlib.Path, timeout: float) -> Run: - """Runs the forge's CLI at root, stopped after timeout seconds: what it printed, or a Failure with why it failed.""" - def run(command: list[str]) -> str | Failure: - done = ran(command, root, timeout) - if isinstance(done, Failure): - return Failure(f"`{' '.join(command[:3])}` {done.reason}") - return Failure(f"`{' '.join(command[:3])}` exited {done.code}: {done.stderr.strip()}") if done.code else done.stdout - return run - - def pull_listing(root: pathlib.Path, branch: str, timeout: float) -> tuple[Forge, Ran | Failure] | None: url = git("remote", "get-url", "origin") if isinstance(url, Failure): diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index f93753cb..e017fdc7 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -161,7 +161,7 @@ elif args[:6] == ["pr", "list", "--head", "item-2", "--state", "merged"]: self.assertIn("No plan item: every item of release 0.2.0 in origin/main's todo.md waits. Under `merge = \"human\"`, these pull requests await a person's merge: #12 https://github.com/o/r/pull/12, which finishes item 3. The working loop stops here. Once a person has merged one, or turned one back into a draft, run loop-claude again.", done.stdout) (repo.fake / "gh").write_text("#!/bin/sh\necho 'not logged in' >&2\nexit 1\n") unread = repo.preflight() - self.assertIn("- The pull requests that await a person's merge cannot be read, so no item is passed over for one: `gh pr list` exited 1: not logged in\n", unread.stdout) + self.assertIn("- The pull requests that await a person's merge cannot be read, so no item is passed over for one: gh pr list: not logged in\n", unread.stdout) self.assertIn("Its first item that does not wait: item 3,", unread.stdout) def test_reads_a_plan_outside_the_checkout_as_it_stands_and_names_where_the_config_puts_each_file(self): @@ -438,9 +438,9 @@ def rendered(item, release=CUT, note=None): class Render(unittest.TestCase): def test_reads_each_worktree_on_a_branch_from_gits_listing(self): - porcelain = "worktree /c/proj\nHEAD aaa\nbranch refs/heads/main\n\nworktree /c/proj-item-2\nHEAD bbb\nbranch refs/heads/item-2\n\nworktree /c/detached\nHEAD ccc\ndetached\n" - self.assertEqual(worktrees(porcelain), [(pathlib.Path("/c/proj"), "main", "aaa"), (pathlib.Path("/c/proj-item-2"), "item-2", "bbb")]) - self.assertEqual((worktree_on(porcelain, "item-2"), worktree_on(porcelain, "item-3")), (pathlib.Path("/c/proj-item-2"), None)) + porcelain = "worktree /c/proj\nHEAD aaa\nbranch refs/heads/main\n\nworktree /c/my proj-item-2\nHEAD bbb\nbranch refs/heads/item-2\n\nworktree /c/detached\nHEAD ccc\ndetached\n" + self.assertEqual(worktrees(porcelain), [(pathlib.Path("/c/proj"), "main", "aaa"), (pathlib.Path("/c/my proj-item-2"), "item-2", "bbb")]) + self.assertEqual((worktree_on(porcelain, "item-2"), worktree_on(porcelain, "item-3")), (pathlib.Path("/c/my proj-item-2"), None)) def test_states_what_a_persons_merge_leaves_only_where_there_is_something(self): self.assertNotIn("merge", rendered(item_facts())) diff --git a/bin/forge/commands.py b/bin/forge/commands.py index 762461ac..88ec0ac2 100644 --- a/bin/forge/commands.py +++ b/bin/forge/commands.py @@ -24,12 +24,15 @@ def url_beside(origin_url: str, name: str) -> str | None: return place.group(1) + name if place and not place.group(1).endswith("//") else None -def runner(cwd: str) -> Run: +def runner(cwd: str, timeout: float | None = None) -> Run: + """Runs a command in cwd, stopped after timeout seconds where one is given.""" def run(command: list[str]) -> str | Failure: try: - done = subprocess.run(command, capture_output=True, cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL) + done = subprocess.run(command, capture_output=True, cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, timeout=timeout) except OSError as failure: return Failure(f"{command[0]} could not start: {failure}") + except subprocess.TimeoutExpired: + return Failure(f"{' '.join(command[:3])}: stopped after {timeout} s") if done.returncode: return Failure(f"{' '.join(command[:3])}: {(done.stderr or done.stdout).strip()}") return done.stdout diff --git a/bin/forge/pulls.py b/bin/forge/pulls.py index 2c641471..aea166a3 100644 --- a/bin/forge/pulls.py +++ b/bin/forge/pulls.py @@ -56,9 +56,9 @@ class ReadyPull: def ready_pulls(forge: Forge, run: Run) -> list[ReadyPull] | Failure: - """Each open pull request from origin's own branches that is no draft, which Gitea tells by its title (GITEA_DRAFT). A row is left out where its head is no commit ID, since the caller passes the head to git, or where its number is not all digits, since the caller prints it.""" + """Each open pull request from origin's own branches that is no draft, which Gitea tells by its title (GITEA_DRAFT); Gitea names no head repo for a fork that was deleted. A row is left out where its head is no commit ID, since the caller passes the head to git, or where its number is not all digits, since the caller prints it.""" if forge == "gh": - # 100 is the most GitHub's API lists a page; gh lists 30 unless told. + # A limit: an awaited pull request past the first 100 open ones, drafts and forks counted, is not seen. `--draft=false` would make gh search, and GitHub's search index lags a pull request just marked ready. listed = run(["gh", "pr", "list", "--limit", "100", "--json", "number,url,headRefOid,isDraft,isCrossRepository", "--template", "{{range .}}{{.number}}\t{{.url}}\t{{.headRefOid}}\t{{.isDraft}}\t{{.isCrossRepository}}\n{{end}}"]) if isinstance(listed, Failure): return listed @@ -69,7 +69,7 @@ def ready_pulls(forge: Forge, run: Run) -> list[ReadyPull] | Failure: if isinstance(pulls, Failure): return pulls try: - found = [ReadyPull(str(pull["number"]), pull["html_url"], pull["head"]["sha"]) for pull in pulls if pull["head"]["repo"]["full_name"] == pull["base"]["repo"]["full_name"] and not pull["title"].upper().startswith(GITEA_DRAFT)] + found = [ReadyPull(str(pull["number"]), pull["html_url"], pull["head"]["sha"]) for pull in pulls if (pull["head"]["repo"] or {}).get("full_name") == pull["base"]["repo"]["full_name"] and not pull["title"].upper().startswith(GITEA_DRAFT)] except (AttributeError, KeyError, TypeError): return Failure(f"tea api listed pull requests in a shape that can't be read: {str(pulls)[:200]}") return [pull for pull in found if pull.number.isascii() and pull.number.isdigit() and isinstance(pull.head, str) and re.fullmatch(r"[0-9a-f]{40,64}", pull.head)] diff --git a/bin/forge/test_forge.py b/bin/forge/test_forge.py index e2a4ee68..a026343f 100644 --- a/bin/forge/test_forge.py +++ b/bin/forge/test_forge.py @@ -9,7 +9,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from forge.pulls import CheckFailed, checks_now, checks_passed, open_pull, Pending, POLL_SECONDS, ready_pulls, ReadyPull, required_checks, WAIT_SECONDS from failure import Failure -from forge.commands import forge_of, gitea, url_beside +from forge.commands import forge_of, gitea, runner, url_beside class ForgeOf(unittest.TestCase): @@ -136,11 +136,6 @@ class ChecksPassed(unittest.TestCase): self.assertEqual(checks_passed("tea", "1", "abc", set(), tea([LONG]), self.fail).reason, f"tea api printed no commit status for abc: {LONG[:200]}") - -if __name__ == "__main__": - unittest.main() - - SHA = "a" * 40 GITEA_PULL = {"number": 7, "html_url": "https://gitea.example/o/r/pulls/7", "title": "Do 7", "head": {"sha": SHA, "repo": {"full_name": "o/r"}}, "base": {"repo": {"full_name": "o/r"}}} @@ -158,10 +153,25 @@ class ReadyPulls(unittest.TestCase): def test_lists_on_tea_each_open_pull_request_from_origins_own_branches_whose_title_marks_no_draft(self): fork = {**GITEA_PULL, "number": 8, "head": {"sha": SHA, "repo": {"full_name": "other/r"}}} draft = {**GITEA_PULL, "number": 9, "title": "wip: Do 9"} + deleted_fork = {**GITEA_PULL, "number": 10, "head": {"sha": SHA, "repo": None}} commands: list[list[str]] = [] - self.assertEqual(ready_pulls("tea", lambda command: commands.append(command) or json.dumps([GITEA_PULL, fork, draft])), [ReadyPull("7", "https://gitea.example/o/r/pulls/7", SHA)]) + self.assertEqual(ready_pulls("tea", lambda command: commands.append(command) or json.dumps([GITEA_PULL, fork, draft, deleted_fork])), [ReadyPull("7", "https://gitea.example/o/r/pulls/7", SHA)]) self.assertEqual(commands, [["tea", "api", "repos/{owner}/{repo}/pulls?state=open&limit=50"]]) def test_fails_where_the_forge_cannot_list_them(self): self.assertEqual(ready_pulls("gh", lambda command: Failure("gh: no network")).reason, "gh: no network") self.assertEqual(ready_pulls("tea", lambda command: LONG).reason, f"tea api listed pull requests in a shape that can't be read: {LONG[:200]}") + + +class Runner(unittest.TestCase): + def test_prints_what_a_command_printed_and_fails_where_it_exits_nonzero_cannot_start_or_outlasts_its_timeout(self): + self.assertEqual(runner("/")(["echo", "hello"]), "hello\n") + self.assertEqual(runner("/")(["sh", "-c", "echo no >&2; exit 3"]), Failure("sh -c echo no >&2; exit 3: no")) + failed = runner("/")(["no-such-forge-cli", "pr", "list"]) + self.assertIsInstance(failed, Failure) + self.assertTrue(failed.reason.startswith("no-such-forge-cli could not start: "), failed.reason) + self.assertEqual(runner("/", 0.05)(["sleep", "5"]), Failure("sleep 5: stopped after 0.05 s")) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/loop_effects/effects.py b/bin/loop_effects/effects.py index d0d9481d..6d58130c 100644 --- a/bin/loop_effects/effects.py +++ b/bin/loop_effects/effects.py @@ -26,6 +26,8 @@ from machine_load.slots import slot_folder # Seconds before a Python script loop-claude runs is stopped, so a hung one, such as chunk-preflight, cannot hold the loop. PYTHON_TIMEOUT = 600 +# Seconds a command of the forge's CLI may take, so a stalled one cannot hold the loop. +FORGE_TIMEOUT = 60 class Streaming(typing.Protocol): @@ -123,7 +125,7 @@ def system_effects(home: pathlib.Path, env: typing.Mapping[str, str], backends: discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH), dm=lambda text, directory: notify(text, directory, home, backends), execv=os.execv, - forge=runner, + forge=lambda cwd: runner(cwd, FORGE_TIMEOUT), git=git_repo.git, input=input, local_time=lambda seconds: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(seconds)), diff --git a/bin/release_plan/test_release_standing.py b/bin/release_plan/test_release_standing.py index 3be9fc38..faefb665 100644 --- a/bin/release_plan/test_release_standing.py +++ b/bin/release_plan/test_release_standing.py @@ -423,7 +423,7 @@ class AwaitingMerge(unittest.TestCase): def test_names_the_items_a_ready_pull_request_finished_on_its_branch(self): self.assertEqual(awaiting_merge.awaiting("main", plan_in(self.repo), self.repo, "gh", lambda command: self.listed), {1: "#7 https://github.com/o/r/pull/7"}, "item 4, filed after the branch left main, is not finished on it") - def test_names_none_for_a_pull_request_whose_head_the_checkout_lacks_and_fails_where_the_forge_does(self): + def test_names_none_for_a_pull_request_whose_head_the_checkout_lacks(self): unfetched = f"7\thttps://github.com/o/r/pull/7\t{'b' * 40}\tfalse\tfalse\n" self.assertEqual(awaiting_merge.awaiting("main", plan_in(self.repo), self.repo, "gh", lambda command: unfetched), {}) self.assertEqual(awaiting_merge.awaiting("main", plan_in(self.repo), self.repo, "gh", lambda command: unfetched + self.listed), {1: "#7 https://github.com/o/r/pull/7"}, "the pull request listed after it still counts")