Skip to content

The agent that grows with you

test(kanban-e2e): dispatcher SIGKILL/restart row integrity; artifact + pinned-skill worker contracts (#120647 #119619 strict-xfail)

teknium1c2383217aefc
diff --git a/tests/e2e/core/kanban/test_kanban_dispatcher_restart.py b/tests/e2e/core/kanban/test_kanban_dispatcher_restart.py
new file mode 100644
index 00000000000..0dc66af54f1
--- /dev/null
+++ b/tests/e2e/core/kanban/test_kanban_dispatcher_restart.py
@@ -0,0 +1,125 @@
+"""Dispatcher SIGKILLed mid-tick and restarted: the board keeps every real task row (#119003 class).
+
+A real ``hermes kanban dispatch`` process is SIGKILLed at three points of a tick — right after it
+claimed a card (before the spawn), right after it spawned a worker, and immediately after launch —
+then plain ticks run until the board drains. Workers are real ``hermes chat -q`` processes (they
+survive the dispatcher: own session) and the model is the recording fake.
+
+Invariants, read from kanban.db and the provider's request log:
+
+* the ``tasks`` table holds exactly the created ids with their titles and bodies — no row
+ destroyed, replaced or invented (no status-word placeholder id);
+* every card ends ``done`` with exactly one ``completed`` run and one ``completed`` event;
+* each card's ``kanban_complete`` was billed exactly once (no duplicate worker ran a card);
+* no card ever had two runs open at the same time.
+"""
+
+from __future__ import annotations
+
+import re
+import signal
+import subprocess
+import sys
+import threading
+import time
+from collections import Counter
+
+import pytest
+
+from tests.e2e.core.kanban._helpers import PY, Board, pid_alive, wait_until
+from tests.fakes.fake_llm_provider import FakeLLMServer, Text, ToolCall
+
+pytestmark = [
+ pytest.mark.skipif(not sys.platform.startswith("linux"), reason="SIGKILL + /proc liveness"),
+ pytest.mark.live_system_guard_bypass, # teardown SIGKILLs this board's reparented workers
+]
+
+N_CARDS = 5
+_TASK_RE = re.compile(r"work kanban task (t_[0-9a-f]+)")
+
+
+class Completer:
+ """Every worker completes its own card; billing is counted per card id."""
+
+ def __init__(self) -> None:
+ self.completes: Counter[str] = Counter()
+ self._lock = threading.Lock()
+
+ def __call__(self, rec: dict):
+ msgs = rec["body"]["messages"]
+ if msgs[-1].get("role") == "tool":
+ return Text("card closed")
+ tid = next((m for m in (_TASK_RE.search(str(x.get("content"))) for x in msgs) if m), None)
+ assert tid, "worker prompt did not name its task"
+ with self._lock:
+ self.completes[tid.group(1)] += 1
+ return ToolCall("kanban_complete", {"summary": f"done {tid.group(1)}"})
+
+
+def _event_count(board: Board, kind: str) -> int:
+ if not board.db_path.exists():
+ return 0
+ return board._q("SELECT COUNT(*) AS n FROM task_events WHERE kind = ?", (kind,))[0]["n"]
+
+
+def _kill_dispatcher_after(board: Board, kind: str | None) -> None:
+ """Launch one real dispatch tick and SIGKILL it once a new ``kind`` event lands (None: at once)."""
+ before = _event_count(board, kind) if kind else 0
+ proc = subprocess.Popen(
+ [PY, "-m", "hermes_cli.main", "kanban", "dispatch", "--json"], cwd=str(board.root),
+ env=board.env(), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ )
+ try:
+ if kind:
+ wait_until(lambda: _event_count(board, kind) > before or proc.poll() is not None, 60,
+ f"dispatcher to write a {kind} event", interval=0.01)
+ finally:
+ proc.send_signal(signal.SIGKILL)
+ proc.wait(timeout=30)
+ for row in board.tasks():
+ if row["worker_pid"]:
+ board.spawned_pids.add(int(row["worker_pid"]))
+
+
+def _overlapping_runs(runs: list[dict]) -> list[tuple[int, int]]:
+ spans = [(r["id"], r["started_at"], r["ended_at"] or time.time()) for r in runs]
+ return [(a[0], b[0]) for i, a in enumerate(spans) for b in spans[i + 1:]
+ if a[1] < b[2] and b[1] < a[2] and a[2] > a[1] and b[2] > b[1]]
+
+
+def test_dispatcher_sigkill_mid_tick_never_destroys_or_duplicates_cards(tmp_path) -> None:
+ completer = Completer()
+ with FakeLLMServer(completer) as srv:
+ board = Board(tmp_path, srv.base_url, env_extra={"HERMES_KANBAN_CLAIM_TTL_SECONDS": "3"})
+ try:
+ created = {}
+ for i in range(N_CARDS):
+ title, body = f"chaos card {i}", f"body of chaos card {i}: keep me intact"
+ created[board.create(title, "--body", body)] = (title, body)
+ for kind in ("claimed", "spawned", None):
+ _kill_dispatcher_after(board, kind)
+ # Plain restarts until the board drains (stranded claims expire after the 3 s TTL).
+ def drained() -> bool:
+ if all(board.task(t)["status"] == "done" for t in created):
+ return True
+ board.dispatch()
+ return False
+ wait_until(drained, 150, "every card to finish after the dispatcher restarts", interval=0.5)
+ for pid in list(board.spawned_pids):
+ wait_until(lambda p=pid: not pid_alive(p), 60, f"worker {pid} to exit")
+
+ rows = board.tasks()
+ assert {r["id"]: (r["title"], r["body"]) for r in rows} == created, rows
+ for tid in created:
+ runs = board.runs(tid)
+ done = [r for r in runs if r["outcome"] == "completed"]
+ assert len(done) == 1 and done[0]["summary"] == f"done {tid}", board.diag(tid)
+ assert len(board.events(tid, "completed")) == 1, board.diag(tid)
+ assert not _overlapping_runs(runs), board.diag(tid)
+ assert dict(completer.completes) == {t: 1 for t in created}, completer.completes
+ # Vacuity guard: the claim-then-kill round really stranded a claim that the restarted
+ # dispatcher had to recover (a kill that always landed between ticks proves nothing).
+ outcomes = Counter(r["outcome"] for t in created for r in board.runs(t))
+ assert outcomes["reclaimed"] >= 1, outcomes
+ finally:
+ board.kill_workers()
diff --git a/tests/e2e/core/kanban/test_kanban_worker_contract.py b/tests/e2e/core/kanban/test_kanban_worker_contract.py
new file mode 100644
index 00000000000..a2039112225
--- /dev/null
+++ b/tests/e2e/core/kanban/test_kanban_worker_contract.py
@@ -0,0 +1,152 @@
+"""Worker-side board contracts through the real dispatcher and a real ``hermes chat -q`` worker.
+
+* ``kanban_complete(artifacts=[...])``: a declared file inside the task workspace is staged as a
+ ``task_attachments`` row; a declared file OUTSIDE the workspace must be reported (attached or the
+ completion refused), never silently dropped while the card reads as delivered (#120647).
+* ``--skill`` pins: a pin that resolves reaches the model on the worker's first request; a pin that
+ no longer resolves must not kill the dispatcher-owned worker before its session starts (#119619).
+
+Verdicts come from kanban.db rows, files on disk and the provider's request log.
+"""
+
+from __future__ import annotations
+
+import re
+import shutil
+import sys
+from pathlib import Path
+
+import pytest
+
+from tests.e2e.core.kanban._helpers import Board, wait_until
+from tests.fakes.fake_llm_provider import FakeLLMServer, Text, ToolCall
+
+pytestmark = [
+ pytest.mark.skipif(not sys.platform.startswith("linux"), reason="/proc worker liveness"),
+ pytest.mark.live_system_guard_bypass, # teardown SIGKILLs this board's reparented workers
+]
+
+KNOWN: dict[str, str] = {
+ "outside": "#120647 kanban_complete artifact outside the workspace is silently never attached",
+ "test_worker_with_unresolvable_pinned_skill_still_starts_its_session":
+ "#119619 dispatcher-owned worker with a stale --skill pin exits rc=1 before its session",
+}
+
+_TASK_RE = re.compile(r"work kanban task (t_[0-9a-f]+)")
+SKILL_MARK = "E2E_PINNED_SKILL_BODY_7f3a"
+
+
+class KnownGap(AssertionError):
+ """The tracked bug's own assertion. Only this is xfailed; any harness failure stays red."""
+
+
+def _task_id(rec: dict) -> str:
+ for m in rec["body"]["messages"]:
+ hit = _TASK_RE.search(str(m.get("content")))
+ if hit:
+ return hit.group(1)
+ raise AssertionError("worker prompt did not name its task")
+
+
+def _run_one_card(board: Board, tid: str) -> None:
+ board.dispatch()
+ pid = board.task(tid)["worker_pid"]
+ assert pid, board.diag(tid)
+ board.wait_worker_exit(tid, int(pid))
+
+
+# artifacts ------------------------------------------------------------------------------------
+
+
+def _artifact_location(board: Board, tid: str, where: str) -> Path:
+ workspace = board.hermes_home / "kanban" / "workspaces" / tid
+ return {"inside": workspace / "report.md",
+ "outside": board.hermes_home / "scripts" / f"{tid}-deliverable.md"}[where]
+
+
+ pytest.param(w, marks=pytest.mark.xfail(strict=True, raises=KnownGap, reason=KNOWN[w])) if w in KNOWN else w
+ for w in ("inside", "outside")
+])
+def test_declared_artifact_is_attached_or_reported(tmp_path, where: str) -> None:
+ board_ref: dict[str, Board] = {}
+ payload = f"DELIVERABLE_{where.upper()}_c0ffee\n"
+
+ def responder(rec: dict):
+ if rec["body"]["messages"][-1].get("role") == "tool":
+ return Text("delivered")
+ tid = _task_id(rec)
+ path = _artifact_location(board_ref["b"], tid, where)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(payload, encoding="utf-8") # the file exists before the call declares it
+ return ToolCall("kanban_complete", {"summary": "report written", "artifacts": [str(path)]})
+
+ with FakeLLMServer(responder) as srv:
+ board = board_ref["b"] = Board(tmp_path, srv.base_url)
+ try:
+ tid = board.create(f"artifact card ({where})")
+ _run_one_card(board, tid)
+ status = board.task(tid)["status"]
+ attached = board._q("SELECT * FROM task_attachments WHERE task_id = ?", (tid,))
+ stored = [Path(a["stored_path"]) for a in attached]
+ if status == "done" and not attached:
+ raise KnownGap(f"card done with its declared {where}-workspace artifact never attached\n"
+ f"{board.diag(tid)}")
+ assert status == "done" or where == "outside", board.diag(tid)
+ if attached:
+ assert len(attached) == 1 and stored[0].read_text(encoding="utf-8") == payload, attached
+ assert not stored[0].is_relative_to(board.hermes_home / "kanban" / "workspaces"), stored
+ finally:
+ board.kill_workers()
+
+
+# pinned skills --------------------------------------------------------------------------------
+
+
+def _seed_skill(board: Board, name: str) -> None:
+ skill = board.hermes_home / "skills" / name
+ skill.mkdir(parents=True, exist_ok=True)
+ (skill / "SKILL.md").write_text(
+ f"---\nname: {name}\ndescription: Use when running the kanban e2e pin probe.\n---\n\n"
+ f"# {name}\n\nAlways follow {SKILL_MARK}.\n", encoding="utf-8")
+
+
+def _completing_responder(rec: dict):
+ if rec["body"]["messages"][-1].get("role") == "tool":
+ return Text("pinned run done")
+ return ToolCall("kanban_complete", {"summary": "pinned skill run"})
+
+
+def test_worker_with_resolvable_pinned_skill_sees_it_on_first_request(tmp_path) -> None:
+ with FakeLLMServer(_completing_responder) as srv:
+ board = Board(tmp_path, srv.base_url)
+ try:
+ _seed_skill(board, "e2e-pinned")
+ tid = board.create("pinned skill card", "--skill", "e2e-pinned")
+ _run_one_card(board, tid)
+ first = srv.main_requests()[0]
+ assert SKILL_MARK in str(first["messages"]), "pinned skill body never reached the model"
+ assert board.task(tid)["status"] == "done", board.diag(tid)
+ assert len(srv.main_requests()) == 2
+ finally:
+ board.kill_workers()
+
+
[email protected](strict=True, raises=KnownGap,
+ reason=KNOWN["test_worker_with_unresolvable_pinned_skill_still_starts_its_session"])
+def test_worker_with_unresolvable_pinned_skill_still_starts_its_session(tmp_path) -> None:
+ with FakeLLMServer(_completing_responder) as srv:
+ board = Board(tmp_path, srv.base_url)
+ try:
+ _seed_skill(board, "e2e-archived")
+ tid = board.create("stale pin card", "--skill", "e2e-archived")
+ # The operator removes the skill after the pin was written.
+ shutil.rmtree(board.hermes_home / "skills" / "e2e-archived")
+ _run_one_card(board, tid)
+ wait_until(lambda: board.worker_log(tid), 10, "worker log")
+ if not srv.main_requests():
+ raise KnownGap(f"worker died before its session; board:\n{board.diag(tid)}")
+ assert SKILL_MARK not in str(srv.main_requests()[0]["messages"]), "removed skill still loaded"
+ assert board.task(tid)["status"] == "done", board.diag(tid)
+ finally:
+ board.kill_workers()