From 1ff46e1e835e933e8b3acf4006ffdb3b55021f52 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Mon, 9 Nov 2026 21:54:40 -0600 Subject: [PATCH] test(pm-stack/claimant): port Slice-1 suite to live API, add held-label gate (#7670) --- .github/workflows/pm-stack-tests.yml | 5 +- pm-stack/opencode-claimant/claimant.py | 76 +++- pm-stack/opencode-claimant/test/__init__.py | 1 + .../opencode-claimant/test/test_claimant.py | 328 ++++++++++-------- 4 files changed, 264 insertions(+), 146 deletions(-) create mode 100644 pm-stack/opencode-claimant/test/__init__.py diff --git a/.github/workflows/pm-stack-tests.yml b/.github/workflows/pm-stack-tests.yml index aefa6e5be7..e1186041e1 100644 --- a/.github/workflows/pm-stack-tests.yml +++ b/.github/workflows/pm-stack-tests.yml @@ -85,7 +85,7 @@ jobs: - name: Test claimant and grist Python suites run: | fail=0 - for t in pm-stack/opencode-claimant/test_poll.py pm-stack/opencode-claimant/test_claimant.py pm-stack/grist/test_update_choice_options.py; do + for t in pm-stack/opencode-claimant/test_poll.py pm-stack/opencode-claimant/test_claimant.py pm-stack/opencode-claimant/test/test_claimant.py pm-stack/grist/test_update_choice_options.py; do if [ ! -f "$t" ]; then echo "::error::Missing suite file $t — the pm-stack Python suites were not run in full." fail=1 @@ -96,12 +96,13 @@ jobs: fi python3 -m unittest pm-stack/opencode-claimant/test_poll.py || fail=1 python3 -m unittest pm-stack/opencode-claimant/test_claimant.py || fail=1 + python3 -m unittest pm-stack/opencode-claimant/test/test_claimant.py || fail=1 python3 -m unittest discover -s pm-stack/grist -p 'test_*.py' || fail=1 if [ "$fail" -ne 0 ]; then echo "::error::pm-stack Python suites: at least one suite failed (see above)." exit 1 fi - echo "pm-stack Python suites: test_poll.py + test_claimant.py + grist discovery passed." + echo "pm-stack Python suites: test_poll.py + test_claimant.py + test/test_claimant.py (#7670) + grist discovery passed." # Python suite for #6217: pm-stack/external-comms/ # test_push_quarantine.py (6 tests, the pinning suite for the diff --git a/pm-stack/opencode-claimant/claimant.py b/pm-stack/opencode-claimant/claimant.py index f6150f3fcc..473ed6c4df 100755 --- a/pm-stack/opencode-claimant/claimant.py +++ b/pm-stack/opencode-claimant/claimant.py @@ -493,6 +493,49 @@ def _collect_parked_handoffs(queue: str, want: int) -> Dict[int, Dict]: return collected + +HELD_ISSUE_LABELS = {"held", "user/owned", "do-not-merge", "do-not-auto-edit"} + +_CREDENTIAL_KEY_PARTS = ("password", "secret", "token", "credential", + "api_key", "apikey", "private_key") + + +def _github_issue_labels(repo: str, issue_number: int) -> set: + """Live label names on an issue, read through the gh CLI. + Raises on any failure so the caller can fail closed (#7670).""" + result = subprocess.run( + ["gh", "issue", "view", str(issue_number), "--repo", repo, + "--json", "labels", "--jq", "[.labels[].name]"], + capture_output=True, text=True, timeout=15, + ) + if result.returncode != 0: + raise RuntimeError( + f"gh issue view failed: {result.stderr.strip()[:200]}") + names = json.loads(result.stdout) + if not isinstance(names, list): + raise RuntimeError("gh issue view returned a non-list label set") + return {str(n) for n in names} + + +def _prompt_safe_packet(packet): + """Deep-copy a packet for the execution prompt with any + credential-shaped values redacted (#7670): a credential must + never enter a prompt, log, or payload surface, and packets are + assembled by many hands - strip by key name, recursively.""" + if isinstance(packet, dict): + safe = {} + for key, value in packet.items(): + lowered = str(key).lower() + if any(part in lowered for part in _CREDENTIAL_KEY_PARTS): + safe[key] = "[redacted]" + continue + safe[key] = _prompt_safe_packet(value) + return safe + if isinstance(packet, list): + return [_prompt_safe_packet(v) for v in packet] + return packet + + def launch_step(mode: str, cap_room: int) -> List[Dict]: """ Step 4: Launch - create sessions and bind tasks. @@ -613,6 +656,37 @@ def launch_step(mode: str, cap_room: int) -> List[Dict]: }) continue + # Step 4a2: Held-label gate (#7670). A candidate whose + # issue carries a held label (held, user/owned, + # do-not-merge, do-not-auto-edit) must never be launched: + # the queue-side hard stop is label-based, and the + # claimant is the last line of defense before a session + # exists. The check fails closed: an unreadable label set + # is a skip, never a launch. Candidates without a + # repo/issue reference have nothing to check. + _packet = packet if isinstance(packet, dict) else {} + _repo = _packet.get("repo") or "" + _issue_no = candidate.get("issue_number") + if _issue_no is None and isinstance(_packet.get("issue"), dict): + _issue_no = _packet["issue"].get("number") + if _repo and _issue_no: + try: + _labels = _github_issue_labels( + str(_repo), int(str(_issue_no).lstrip("#"))) + except Exception as e: + skips.append({ + "task_id": task_id, + "reason": f"held_label_check_failed: {str(e)}" + }) + continue + _held = sorted(_labels & HELD_ISSUE_LABELS) + if _held: + skips.append({ + "task_id": task_id, + "reason": f"held_issue_labels: {','.join(_held)}" + }) + continue + # Step 4b: Create worker session session_create_body = { "location": { @@ -705,7 +779,7 @@ def launch_step(mode: str, cap_room: int) -> List[Dict]: prompt = f""" Execute queue task {task_id} Issue: {issue} -Packet: {json.dumps(packet, indent=2)} +Packet: {json.dumps(_prompt_safe_packet(packet), indent=2)} You are a build agent working on this opencode-lane task. Use --worker {worker_id} for all queue CLI operations. diff --git a/pm-stack/opencode-claimant/test/__init__.py b/pm-stack/opencode-claimant/test/__init__.py new file mode 100644 index 0000000000..078e1e821b --- /dev/null +++ b/pm-stack/opencode-claimant/test/__init__.py @@ -0,0 +1 @@ +# Package marker so unittest discovery descends into this suite directory (#7670). diff --git a/pm-stack/opencode-claimant/test/test_claimant.py b/pm-stack/opencode-claimant/test/test_claimant.py index 0f7d51b131..3c98950327 100644 --- a/pm-stack/opencode-claimant/test/test_claimant.py +++ b/pm-stack/opencode-claimant/test/test_claimant.py @@ -1,167 +1,209 @@ #!/usr/bin/env python3 -"""Offline tests for claimant ordering and fail-closed behavior.""" - +"""Offline tests for claimant ordering and fail-closed behavior. + +Ported to the live claimant API for #7670 (task 14501). The Slice-1 +suite at this path patched a claimant API that no longer exists +(prepare_candidate / launch_one / _POLL / _current_bound_row / +_poll-shaped supervision_step(data, mode)) and errored 4/4 while no +workflow ran it. This port pins the surviving behaviors against the +live surface - launch_step(mode, cap_room) and supervision_step(mode): + +- bind precedes prompt: a session is created, then bound to the task, + then prompted (the Slice-1 checkpoint-between-bind-and-prompt pin is + superseded: the live flow has no checkpoint step; prompt delivery is + verified by _send_prompt's reconcile-before-resend instead); +- a credential-shaped packet value never enters the prompt text (the + live claimant redacts credential-shaped keys when it dumps the + packet into the prompt); +- a held issue label (held / user/owned / do-not-merge / + do-not-auto-edit) prevents launch, and an unreadable label set + fails closed the same way - this gate was genuinely missing in the + live claimant and is implemented in launch_step for this issue; +- session-create failure binds nothing and is a recorded skip; +- supervision: a confirmed zero-message read precedes the session + DELETE, which precedes the atomic recovery bind carrying + LAUNCHED_BY_RECOVERY_ZERO_MESSAGE. + +The Slice-1 per-packet route/model pin is superseded: the live +claimant launches every session on the fixed workhorse route. +""" + +import copy import importlib.util import json -import tempfile import unittest from pathlib import Path -from types import SimpleNamespace from unittest.mock import patch ROOT = Path(__file__).resolve().parents[1] spec = importlib.util.spec_from_file_location("claimant", ROOT / "claimant.py") claimant = importlib.util.module_from_spec(spec) spec.loader.exec_module(claimant) -poll_spec = importlib.util.spec_from_file_location("claimant_poll_test", ROOT / "poll.py") -poll_module = importlib.util.module_from_spec(poll_spec) -poll_spec.loader.exec_module(poll_module) + + +class Result: + """Minimal subprocess.run stand-in.""" + + def __init__(self, returncode=0, stdout="", stderr=""): + self.returncode = returncode + self.stdout = stdout + self.stderr = stderr + + +def make_fake_run(events, *, create_rc=0, messages="[]"): + """subprocess.run stub dispatching on argv shape, recording an + ordered event log: ("create",) / ("bind", argv) / ("prompt", argv) + / ("messages",) / ("delete",) / ("session_get",).""" + + def fake_run(cmd, **kwargs): + argv = [str(part) for part in cmd] + joined = " ".join(argv) + if "repo-queue" in argv[0] and "bind" in argv: + events.append(("bind", argv)) + return Result(0, "{}") + if argv[0] == "curl" and "-X" in argv and "DELETE" in argv: + events.append(("delete",)) + return Result(0, "") + if argv[0] == "curl" and joined.rstrip().endswith("/message"): + events.append(("messages",)) + return Result(0, messages) + if argv[0] == "curl" and joined.rstrip().endswith("/prompt"): + events.append(("prompt", argv)) + return Result(0, "") + if argv[0] == "curl" and "-X" in argv and "POST" in argv: + events.append(("create",)) + if create_rc != 0: + return Result(create_rc, "", "server unavailable") + return Result(0, json.dumps({ + "id": "ses_new1", + "location": {"directory": str(claimant.PRIMARY_CLONE)}, + })) + if argv[0] == "curl" and "/api/session/" in joined: + events.append(("session_get",)) + return Result(0, json.dumps({"error": "session not found"})) + return Result(0, "") + + return fake_run + + +CANDIDATE = { + "id": 73001, + "queue": "repo-health-code-pilot", + "status": "claimed", + "priority": 1, + "worker_id": "repo-worker-code", + "lane_id": "code-a", + "lease_until": "2999-01-01T00:00:00Z", + "lane": "opencode", + "stage": "handed_off", + "session_id": None, + "issue": 3026, + "issue_number": 3026, + "packet": { + "repo": "developing-today/code", + "issue": {"number": 3026}, + "route": {"providerID": "opencode-route", "modelID": "summit"}, + "password": "must-not-enter-prompt", + "nested": {"api_token": "must-not-enter-prompt-either"}, + }, + "attempts": 0, + "max_attempts": 3, + "title": "Queue task 73001", + "dedupe_key": "test", +} + + +def run_launch(events, *, labels=set(), create_rc=0): + with patch.object(claimant, "run_poll", + side_effect=lambda: {"candidates": [copy.deepcopy(CANDIDATE)]}), \ + patch.object(claimant, "_github_issue_labels", return_value=set(labels)), \ + patch.object(claimant.subprocess, "run", make_fake_run(events, create_rc=create_rc)): + return claimant.launch_step("live", 3) class TestLaunch(unittest.TestCase): - def candidate(self): - return { - "id": 73001, - "queue": "repo-health-code-pilot", - "priority": 1, - "worker_id": "repo-worker-code", - "lane": "opencode", - "stage": "handed_off", - "session_id": None, - "issue_number": 3026, - "packet": { - "payload": { - "repo": "developing-today/code", - "issue": {"number": 3026}, - "route": {"providerID": "opencode-route", "modelID": "summit"}, - "password": "must-not-enter-prompt", - } - }, - } - - def test_session_is_bound_before_checkpoint_and_prompt(self): - candidate = self.candidate() - calls = [] - - def api(method, path, body=None, timeout=15): - calls.append(("api", method, path, body)) - if method == "POST" and path == "/api/session": - self.assertEqual(body["location"]["directory"], str(Path.home() / "git/code")) - self.assertEqual(body["model"], {"id": "summit", "providerID": "opencode-route"}) - return {"id": "ses_test", "location": body["location"]} - return None - - def cli(args, timeout=30): - calls.append(("cli", args)) - return "{}" - - with patch.object(claimant, "_verify_candidate_is_current", return_value=True), \ - patch.object(claimant, "_github_issue_labels", return_value=set()), \ - patch.object(claimant, "_load_runbook", return_value="runbook body"), \ - patch.object(claimant, "_api_request", side_effect=api), \ - patch.object(claimant, "_run_cli", side_effect=cli), \ - patch.object(claimant, "_post_launch_note", side_effect=lambda *args: calls.append(("note",))): - prepared = claimant.prepare_candidate(candidate) - result = claimant.launch_one(prepared) - - self.assertEqual(result["status"], "prompted") - bind_at = next(i for i, call in enumerate(calls) if call[0] == "cli" and call[1][0] == "bind") - checkpoint_at = next(i for i, call in enumerate(calls) if call[0] == "cli" and call[1][0] == "checkpoint") - prompt_at = next(i for i, call in enumerate(calls) if call[0] == "api" and call[1] == "POST" and call[2].endswith("/prompt")) - note_at = next(i for i, call in enumerate(calls) if call[0] == "note") - self.assertLess(bind_at, checkpoint_at) - self.assertLess(checkpoint_at, prompt_at) - self.assertLess(prompt_at, note_at) - prompt = calls[prompt_at][3]["text"] + def test_session_is_bound_before_prompt_and_password_stays_out(self): + events = [] + launched, skips = run_launch(events) + self.assertEqual(skips, []) + self.assertEqual(len(launched), 1) + self.assertEqual(launched[0]["session_id"], "ses_new1") + kinds = [e[0] for e in events] + self.assertLess(kinds.index("create"), kinds.index("bind")) + self.assertLess(kinds.index("bind"), kinds.index("prompt")) + prompt_argv = next(e[1] for e in events if e[0] == "prompt") + body = json.loads(next(a for a in prompt_argv if a.startswith("{"))) + prompt = body["text"] self.assertIn("73001", prompt) self.assertIn("repo-worker-code", prompt) - self.assertIn('"session_id":"ses_test"', prompt) + self.assertIn("ses_new1", prompt) self.assertNotIn("must-not-enter-prompt", prompt) - - def test_create_failure_checkpoints_without_binding(self): - candidate = self.candidate() - calls = [] - - def cli(args, timeout=30): - calls.append(args) - return "{}" - - with patch.object(claimant, "_verify_candidate_is_current", return_value=True), \ - patch.object(claimant, "_api_request", side_effect=RuntimeError("server unavailable")), \ - patch.object(claimant, "_run_cli", side_effect=cli): - result = claimant.launch_one({"candidate": candidate, "packet": candidate["packet"], "payload": candidate["packet"]["payload"], "repo": "developing-today/code", "directory": str(Path.home() / "git/code"), "issue_number": 3026, "route": claimant._route(candidate["packet"], candidate["packet"]["payload"]), "runbook": "runbook"}) - - self.assertEqual(result["reason"], "session_create_failed") - self.assertEqual(len(calls), 1) - self.assertEqual(calls[0][0], "checkpoint") - self.assertIn("--stage", calls[0]) - self.assertIn("launch_failed", calls[0]) - - def test_held_issue_label_prevents_preflight(self): - candidate = self.candidate() - with patch.object(claimant, "_github_issue_labels", return_value={"do-not-merge"}): - with self.assertRaisesRegex(claimant.ClaimantError, "held issue labels"): - claimant.prepare_candidate(candidate) + self.assertIn("[redacted]", prompt) + + def test_create_failure_binds_nothing(self): + events = [] + launched, skips = run_launch(events, create_rc=1) + self.assertEqual(launched, []) + self.assertEqual(len(skips), 1) + self.assertEqual(skips[0]["task_id"], 73001) + self.assertTrue(skips[0]["reason"].startswith("launch_error")) + self.assertNotIn("bind", [e[0] for e in events]) + + def test_held_issue_label_prevents_launch(self): + events = [] + launched, skips = run_launch(events, labels={"do-not-merge"}) + self.assertEqual(launched, []) + self.assertEqual(len(skips), 1) + self.assertTrue(skips[0]["reason"].startswith("held_issue_labels")) + self.assertIn("do-not-merge", skips[0]["reason"]) + self.assertNotIn("create", [e[0] for e in events]) + self.assertNotIn("bind", [e[0] for e in events]) + + def test_unreadable_labels_fail_closed(self): + events = [] + with patch.object(claimant, "run_poll", + side_effect=lambda: {"candidates": [copy.deepcopy(CANDIDATE)]}), \ + patch.object(claimant, "_github_issue_labels", + side_effect=RuntimeError("gh down")), \ + patch.object(claimant.subprocess, "run", make_fake_run(events)): + launched, skips = claimant.launch_step("live", 3) + self.assertEqual(launched, []) + self.assertEqual(len(skips), 1) + self.assertTrue(skips[0]["reason"].startswith("held_label_check_failed")) + self.assertNotIn("create", [e[0] for e in events]) + + +BOUND_ROW = { + "id": 4242, + "attempts": 0, + "max_attempts": 5, + "lease_until": "2020-01-01T00:00:00Z", + "progress": {"lane": "opencode", "session_id": "ses_gone"}, +} class TestSupervision(unittest.TestCase): def test_zero_message_delete_precedes_atomic_recovery(self): - session = {"id": "ses_old", "time": {"created": 1, "updated": 1}} - row = { - "id": 73001, - "queue": "repo-health-code-pilot", - "worker_id": "repo-worker-code", - "lane_id": "code-a", - "lease_until": "2020-01-01T00:00:00Z", - "lane": "opencode", - "stage": "launched", - "session_id": "ses_old", - "attempts": 0, - "max_attempts": 3, - } - data = {"bound": [row], "stuck_bound": [row]} - actions = [] - session_reads = {"count": 0} - - def fetch_sessions(): - session_reads["count"] += 1 - return [session] if session_reads["count"] <= 3 else [] - - poll = type("Poll", (), { - "AUTH_FILE": "/unread", - "parse_lease_ms": staticmethod(lambda _: 0), - "is_active_root": staticmethod(lambda *_: False), - "is_stuck_bound": staticmethod(lambda *_: True), - "fetch_sessions": staticmethod(fetch_sessions), - "fetch_active_ids": staticmethod(lambda: set()), - }) - - def api(method, path, body=None, timeout=15): - actions.append(("api", method)) - return None - - def cli(args, timeout=30): - actions.append(("cli", args)) - return "{}" - - with patch.object(claimant, "_POLL", poll), \ - patch.object(claimant, "_current_bound_row", return_value=row), \ - patch.object(claimant, "_read_messages", side_effect=lambda _: (actions.append(("messages",)) or [])), \ - patch.object(claimant, "_api_request", side_effect=api), \ - patch.object(claimant, "_run_cli", side_effect=cli): - report, skips = claimant.supervision_step(data, "live") - - self.assertEqual(skips, []) - self.assertEqual(report[0]["status"], "reclaimed") - message_at = next(i for i, item in enumerate(actions) if item[0] == "messages") - delete_at = next(i for i, item in enumerate(actions) if item[:2] == ("api", "DELETE")) - recovery_at = next(i for i, item in enumerate(actions) if item[0] == "cli") - self.assertLess(message_at, delete_at) - self.assertLess(delete_at, recovery_at) - self.assertIn(claimant.LAUNCHED_BY_RECOVERY_ZERO_MESSAGE, actions[recovery_at][1]) - - - + events = [] + poll_mod = claimant._load_poll_module() + + def fake_fetch(queue): + return [dict(BOUND_ROW)] if queue == claimant.QUEUES[0] else [] + + with patch.object(poll_mod, "fetch_claimed_rows", side_effect=fake_fetch), \ + patch.object(claimant.subprocess, "run", make_fake_run(events)): + recovered = claimant.supervision_step("live") + + self.assertEqual(recovered, [{ + "task_id": 4242, + "session_id": "ses_gone", + "reason": "zero_message", + }]) + kinds = [e[0] for e in events] + self.assertLess(kinds.index("messages"), kinds.index("delete")) + self.assertLess(kinds.index("delete"), kinds.index("bind")) + bind_argv = next(e[1] for e in events if e[0] == "bind") + self.assertIn(claimant.LAUNCHED_BY_RECOVERY_ZERO_MESSAGE, bind_argv) if __name__ == "__main__":