From 4e168286ccee164ca8b424b3f97c23715e482eaa Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sat, 8 Aug 2026 14:56:46 +0200 Subject: [PATCH] fix(ci-trigger): read the priority input from the job log GitHub cuts display_title at 512 UTF-8 bytes and closes it with a literal '...'. The run-name template renders priority second-to-last and whitelist last, and on the --failed path the whitelist is empty, so the cut always lands inside the priority list: 21 of 69 roles survived the source run's title, the 21st a half-token. untriggered_priority parsed that title and passed undecodable names through verbatim, so the fragment reached the dispatched priority input, became the orchestrator's whitelist, and hit the complexity filter's lexer, whose word class has no rule for CJK. Sequencing died with argparse exit 2 and took the run with it. The retrigger that is supposed to repair a red run was breaking its successor. Read the priority from the ##[group] Inputs block a called job's log records instead: it carries all 69 roles. Depth-1 jobs only -- a deeper one echoes its own workflow's inputs, which have no priority. Drop the decode passthrough now that the source is lossless. The loud failure is only affordable once a whole value exists; before, it would have aborted every large retrigger. dispatched_priority cross-checks against the title: it still proves a priority line existed even when truncation mangled it, so an empty log read is a broken reader -- expired logs, a moved block -- and not a run without priority. Without that check the carry-over would vanish silently, which is what the rest of this change exists to prevent. Co-Authored-By: Claude Opus 5 (1M context) --- cli/administration/deploy/ci/runs.py | 102 ++++++++++++++++-- .../deploy/ci/trigger/__main__.py | 4 +- .../cli/administration/deploy/ci/test_runs.py | 56 +++++++++- .../administration/deploy/ci/test_trigger.py | 47 ++++++-- 4 files changed, 186 insertions(+), 23 deletions(-) diff --git a/cli/administration/deploy/ci/runs.py b/cli/administration/deploy/ci/runs.py index 1ee58f7a1f..d02ec27a87 100644 --- a/cli/administration/deploy/ci/runs.py +++ b/cli/administration/deploy/ci/runs.py @@ -243,27 +243,115 @@ def fetch_jobs(run_id: str, repo: str | None = None) -> list[dict]: def fetch_run(run_id: str, repo: str | None = None) -> dict: """Jobs plus the run title, in one ``gh`` call. - The title is the only place a dispatched run records its inputs: the - REST API answers ``inputs: null`` for a finished workflow_dispatch. + The REST API answers ``inputs: null`` for a finished workflow_dispatch, so + the inputs are recovered from the run itself: short ones from the title + (:func:`config_from_title`), the long ones from a called job's log + (:func:`inputs_from_jobs`), which the title truncates. """ return json.loads( _gh(["run", "view", run_id, "--json", "jobs,displayTitle"], repo=repo) ) -def untriggered_priority(title: str, statuses: dict[str, dict[str, str]]) -> list[str]: +_INPUT_RE = re.compile(r"^\S+\s+(?P[A-Za-z_][A-Za-z0-9_]*): ?(?P.*)$") + + +def inputs_from_jobs(jobs: list[dict], repo: str) -> dict[str, str]: + """The dispatch inputs a called job's log records verbatim. + + GitHub cuts ``display_title`` at 512 UTF-8 bytes (measured on two runs, + both exactly 512) and closes it with a literal ``...``. The run-name + template renders ``priority`` second-to-last and ``whitelist`` last, and + on the ``--failed`` path the whitelist is empty, so the cut always lands + inside the priority list: measured 21 of 69 roles survived, the 21st a + half-token. A CJK display name costs 3 bytes per character, so the budget + is ~22 display names against ~28 bare role ids. Every job of the *called* + workflow opens its log with an ``##[group] Inputs`` block holding the full + values, so that is the SPOT for anything the title cannot hold. + + Args: + jobs: the run's jobs. Only depth-1 jobs are read: a deeper one echoes + its own workflow's inputs, which carry no ``priority``. + repo: ``owner/repo`` the run lives in. + + Returns: + input name -> value, empty when the run has no called job. + """ + called = next( + ( + job + for job in jobs + if str(job.get("name", "")).count(" / ") == 1 and job.get("databaseId") + ), + None, + ) + if called is None: + return {} + log = _gh(["api", f"repos/{repo}/actions/jobs/{called['databaseId']}/logs"]) + inputs: dict[str, str] = {} + inside = False + for line in log.splitlines(): + if line.endswith("##[group] Inputs"): + inside = True + continue + if inside: + if line.endswith("##[endgroup]"): + break + match = _INPUT_RE.match(line) + if match: + inputs[match["name"]] = match["value"].strip() + return inputs + + +def dispatched_priority(source: dict, repo: str) -> str: + """The source run's ``priority`` input, whole. + + The title's priority segment is the cross-check, not the source: it proves + a priority line existed even when truncation mangled it, so an empty log + read is a broken reader -- expired logs, a moved Inputs block, an inlined + orchestrator -- rather than a run dispatched without one. + + Args: + source: the run as :func:`fetch_run` returns it. + repo: ``owner/repo`` the run lives in. + """ + priority = inputs_from_jobs(source["jobs"], repo).get("priority", "") + if not priority and run_name.value_from_title(source["displayTitle"], "priority"): + raise SystemExit( + "Source run has a priority line but its job log records no inputs; " + "the Inputs block moved or the log expired. Retriggering now would " + "silently drop every priority role." + ) + return priority + + +def untriggered_priority( + priority: str, statuses: dict[str, dict[str, str]] +) -> list[str]: """Roles the source run's priority line named but never deployed at all. A priority role can fall behind the discovery budget cut in every mode, so the run holds no job for it and :func:`failed_roles` cannot see it — it is neither green nor red, it simply never ran. Carrying it into the retrigger is the only way it ever gets deployed. + + Args: + priority: the raw ``priority`` input, as :func:`inputs_from_jobs` reads + it back. A truncated value would smuggle a half-token into the + retrigger's role set, so an undecodable name raises instead. + statuses: role -> mode -> state, from :func:`parse_role_statuses`. """ codec = display_names() - named = [ - codec.decode(name) or name - for name in run_name.value_from_title(title, "priority").split() - ] + named = [] + for name in priority.split(): + role = codec.decode(name) + if role is None: + raise SystemExit( + f"Cannot resolve priority entry {name!r} to a role. The source " + f"run's priority input is corrupt or truncated; retriggering " + f"with it would deploy a role set that is silently incomplete." + ) + named.append(role) return sorted(role for role in named if role not in statuses) diff --git a/cli/administration/deploy/ci/trigger/__main__.py b/cli/administration/deploy/ci/trigger/__main__.py index 969cf485a6..1ac5ab9d33 100644 --- a/cli/administration/deploy/ci/trigger/__main__.py +++ b/cli/administration/deploy/ci/trigger/__main__.py @@ -109,7 +109,9 @@ def main(argv: list[str] | None = None) -> int: scope = "docker" if args.failed == "compose" else args.failed statuses = runs.parse_role_statuses(source["jobs"]) failed = runs.failed_roles(statuses, scope, strict=args.strict) - untriggered = runs.untriggered_priority(source["displayTitle"], statuses) + untriggered = runs.untriggered_priority( + runs.dispatched_priority(source, repo), statuses + ) if not failed and not untriggered: print(f"Nothing failed ({args.failed}) in that run; not triggering.") return 0 diff --git a/tests/unit/cli/administration/deploy/ci/test_runs.py b/tests/unit/cli/administration/deploy/ci/test_runs.py index 485effd4a7..8c59bc1599 100644 --- a/tests/unit/cli/administration/deploy/ci/test_runs.py +++ b/tests/unit/cli/administration/deploy/ci/test_runs.py @@ -220,6 +220,51 @@ class TestSlugFromUrl(unittest.TestCase): runs.slug_from_url("https://example.com/x/y") +class TestInputsFromJobs(unittest.TestCase): + """The title truncates; a called job's log does not.""" + + LOG: ClassVar[str] = "\n".join( + [ + "2026-08-08T10:22:59.5Z ##[group] Inputs", + "2026-08-08T10:22:59.5Z distros: arch", + "2026-08-08T10:22:59.5Z whitelist: ", + "2026-08-08T10:22:59.5Z priority: " + + " ".join(f"web-app-{n}" for n in range(69)), + "2026-08-08T10:22:59.5Z mode_fail_fast: true", + "2026-08-08T10:22:59.5Z ##[endgroup]", + "2026-08-08T10:22:59.6Z ##[group]Run echo hi", + "2026-08-08T10:22:59.6Z priority: not-an-input", + ] + ) + + def test_reads_the_full_priority_from_the_first_called_job(self) -> None: + jobs = [ + {"name": "🎲 Pick distro(s)", "databaseId": 1}, + {"name": "🎛️ Orchestrate CI (manual) / 🏁 Finish pipeline", "databaseId": 2}, + ] + seen: list[list[str]] = [] + + def fake_gh(args: list[str], repo: str | None = None) -> str: + seen.append(args) + return self.LOG + + original = runs._gh + runs._gh = fake_gh + try: + inputs = runs.inputs_from_jobs(jobs, "o/r") + finally: + runs._gh = original + + self.assertEqual(seen, [["api", "repos/o/r/actions/jobs/2/logs"]]) + self.assertEqual(len(inputs["priority"].split()), 69) + self.assertEqual(inputs["distros"], "arch") + self.assertEqual(inputs["whitelist"], "") + self.assertEqual(inputs["mode_fail_fast"], "true") + + def test_a_run_without_a_called_job_reads_nothing(self) -> None: + self.assertEqual(runs.inputs_from_jobs([{"name": "🎲 Pick"}], "o/r"), {}) + + class TestConfigFromTitle(unittest.TestCase): """A retrigger has to reproduce the source run's configuration. @@ -277,15 +322,18 @@ class TestConfigFromTitle(unittest.TestCase): ) def test_priority_roles_without_any_job_are_reported(self) -> None: - title = render({"priority": "web-app-a web-app-b web-app-c"}) statuses = {"web-app-a": {"swarm": "failure"}} self.assertEqual( - runs.untriggered_priority(title, statuses), ["web-app-b", "web-app-c"] + runs.untriggered_priority("web-app-a web-app-b web-app-c", statuses), + ["web-app-b", "web-app-c"], ) def test_a_run_without_a_priority_line_reports_nothing(self) -> None: - title = render({"distros": "debian"}) - self.assertEqual(runs.untriggered_priority(title, {}), []) + self.assertEqual(runs.untriggered_priority("", {}), []) + + def test_a_truncated_priority_entry_aborts_instead_of_passing_through(self) -> None: + with self.assertRaises(SystemExit): + runs.untriggered_priority("web-app-a 网络应用·Funkwha...", {}) def test_a_job_list_without_a_distro_group_adds_nothing(self) -> None: title = render({"sequencing": "serial"}) diff --git a/tests/unit/cli/administration/deploy/ci/test_trigger.py b/tests/unit/cli/administration/deploy/ci/test_trigger.py index 28897c3007..7276188c48 100644 --- a/tests/unit/cli/administration/deploy/ci/test_trigger.py +++ b/tests/unit/cli/administration/deploy/ci/test_trigger.py @@ -40,13 +40,19 @@ _SOURCE_RUN = {"jobs": _JOBS, "displayTitle": render(_SOURCE_CONFIG)} class TestTriggerMain(unittest.TestCase): - def _run(self, argv: list[str], run: dict | None = None) -> tuple[int, list]: + def _run( + self, + argv: list[str], + run: dict | None = None, + inputs: dict[str, str] | None = None, + ) -> tuple[int, list]: calls: list[tuple] = [] buf = io.StringIO() with ( mock.patch.object(runs, "current_branch", return_value="feature/x"), mock.patch.object(runs, "resolve_repo", return_value="o/r"), mock.patch.object(runs, "find_last_deploy_run", return_value=run), + mock.patch.object(runs, "inputs_from_jobs", return_value=inputs or {}), mock.patch.object( runs, "dispatch_workflow", @@ -87,17 +93,17 @@ class TestTriggerMain(unittest.TestCase): self.assertEqual(calls[0][3], "web-app-y") def test_never_deployed_priority_roles_join_the_retrigger(self) -> None: - source = { - "jobs": _JOBS, - "displayTitle": render( - {**_SOURCE_CONFIG, "priority": "web-app-x web-app-never"} - ), - } + source = {"jobs": _JOBS, "displayTitle": render(_SOURCE_CONFIG)} calls: list = [] with ( mock.patch.object(runs, "current_branch", return_value="feature/x"), mock.patch.object(runs, "resolve_repo", return_value="o/r"), mock.patch.object(runs, "fetch_run", return_value=source), + mock.patch.object( + runs, + "inputs_from_jobs", + return_value={"priority": "web-app-x web-app-never"}, + ), mock.patch.object( runs, "dispatch_workflow", @@ -111,20 +117,39 @@ class TestTriggerMain(unittest.TestCase): self.assertEqual(rc, 0) self.assertEqual(calls[0], "web-app-never web-app-x web-app-y") + def test_an_unreadable_job_log_aborts_instead_of_dropping_the_priority( + self, + ) -> None: + source = { + "jobs": _JOBS, + "displayTitle": render({**_SOURCE_CONFIG, "priority": "web-app-x"}), + } + with ( + mock.patch.object(runs, "current_branch", return_value="feature/x"), + mock.patch.object(runs, "resolve_repo", return_value="o/r"), + mock.patch.object(runs, "fetch_run", return_value=source), + mock.patch.object(runs, "inputs_from_jobs", return_value={}), + redirect_stdout(io.StringIO()), + self.assertRaises(SystemExit), + ): + trigger.main(["--failed", "--run", _RUN_URL]) + def test_a_never_deployed_priority_role_alone_still_dispatches(self) -> None: green = [ _job("docker", "web-app-x", "success"), _job("swarm", "web-app-x", "success"), ] - source = { - "jobs": green, - "displayTitle": render({"priority": "web-app-x web-app-never"}), - } + source = {"jobs": green, "displayTitle": render({})} calls: list = [] with ( mock.patch.object(runs, "current_branch", return_value="feature/x"), mock.patch.object(runs, "resolve_repo", return_value="o/r"), mock.patch.object(runs, "fetch_run", return_value=source), + mock.patch.object( + runs, + "inputs_from_jobs", + return_value={"priority": "web-app-x web-app-never"}, + ), mock.patch.object( runs, "dispatch_workflow",