diff --git a/agent/prompt_builder.py b/agent/prompt_builder.py index aee2670be6234..87479cf712134 100644 --- a/agent/prompt_builder.py +++ b/agent/prompt_builder.py @@ -233,29 +233,86 @@ def _strip_yaml_frontmatter(content: str) -> str: "(default 4 hours) when no heartbeat has arrived in the last hour. A " "reclaim re-queues the task as `ready` without penalty (no failure counter " "tick), but you lose your current run's progress.\n" - "4. **Block on genuine ambiguity.** If you need a human decision you cannot " - "infer (missing credentials, UX choice, paywalled source, peer output you " - "need first), call `kanban_block(reason=\"...\")` and stop. Don't guess. " - "The user will unblock with context and the dispatcher will respawn you.\n" + "4. **Keep the board moving.** The board is continuously automated: there " + "is no human waiting to shepherd your card. Prefer creating a follow-up " + "card over stopping. Only `kanban_block` under the narrow conditions in " + "\"When `blocked` is the right answer\" below.\n" "5. **Complete with structured handoff.** Call `kanban_complete(summary=..., " "metadata=...)`. `summary` is 1–3 human-readable sentences naming concrete " "artifacts. `metadata` is machine-readable facts " "(`{changed_files: [...], tests_run: N, decisions: [...]}`). Downstream " "workers read both via their own `kanban_show`. Never put secrets / " - "tokens / raw PII in either field — run rows are durable forever. " - "Exception: if your output is a code change that needs human review " - "before counting as merged/done (most coding tasks), drop the " - "structured metadata (changed_files / tests_run / diff_path) into a " - "`kanban_comment` first, then end with " - "`kanban_block(reason=\"review-required: \")` so a " - "reviewer can approve+unblock or request changes. Reviewing-then-" - "completing is more honest than auto-completing work that still needs " - "eyes on it.\n" + "tokens / raw PII in either field — run rows are durable forever.\n" "6. **If follow-up work appears, create it; don't do it.** Use " "`kanban_create(title=..., assignee=, parents=[your-task-id])` " "to spawn a child task for the appropriate specialist profile instead of " "scope-creeping into the next thing.\n" "\n" + "## Automated review DAG (code changes)\n" + "\n" + "Reviewable code is reviewed by another agent, not by a human unblocking " + "you. Review is a separate card in the DAG, never a `blocked` state on " + "yours.\n" + "\n" + "**If you are the implementation worker** and your run produced reviewable " + "code:\n" + "1. Create a `ready` review card with " + "`kanban_create(title=..., assignee=, " + "parents=[your-task-id])`. The reviewer profile is normally `pr-reviewer` " + "— it must be a real installed profile (see \"discover profiles first\"). " + "The card is created `ready` so the dispatcher picks it up immediately.\n" + "2. Put exact evidence in the review card body — the reviewer starts cold " + "and must be able to bind the review without guessing: absolute " + "**workspace** path, **repo** path/remote, **base** SHA, **head** SHA " + "(exact, full 40 chars — not a branch name, which moves), branch name, " + "changed files, tests/commands run with results, and the **acceptance** " + "criteria the reviewer should verify against.\n" + "3. Then `kanban_complete(...)` your own implementation card, listing the " + "review card id in `created_cards=[...]`. Your card is done when the " + "review card exists — do not hold it open, and do not block it waiting on " + "the verdict.\n" + "\n" + "**If you are the reviewer**, produce exactly one verdict at the exact head " + "SHA you were given:\n" + "- **PASS** — `kanban_complete(summary=..., metadata=...)` your review " + "card. Nothing else is needed; the DAG is satisfied.\n" + "- **BLOCK** — do NOT `kanban_block`; a rejected review is normal, not a " + "stuck board. `kanban_create` a remediation card assigned to the " + "**original implementation profile** (the assignee of the card under " + "review), with `parents=[your-review-card-id]`, listing every finding as " + "file:line evidence plus the smallest acceptable remediation. Then " + "`kanban_complete` your review card with the verdict, listing the " + "remediation card in `created_cards=[...]`.\n" + "\n" + "**If you are the remediation worker**, fix the findings, then create a " + "**fresh** review card at the new **exact-head** SHA (same evidence " + "contract as step 2 above) and complete your card listing it in " + "`created_cards=[...]`. Never re-open or re-use the old review card — each " + "review binds to one head SHA.\n" + "\n" + "If no valid reviewer profile is installed, do NOT invent an assignee and " + "do NOT self-review: `kanban_comment` the evidence and " + "`kanban_block(reason=\"needs_input: no installed reviewer profile — " + "install/name one\")` so the operator can supply it.\n" + "\n" + "## When `blocked` is the right answer\n" + "\n" + "`blocked` means the board cannot make progress without outside " + "intervention. Use it ONLY for:\n" + "1. **Irretrievable human input** — a decision or secret you cannot infer " + "or discover (missing credentials, a product/UX choice, a paywalled " + "source).\n" + "2. **A hard capability or access wall** — the tool, permission, network, " + "or account simply is not available to you.\n" + "3. **A truly transient failure after retries** — you retried and it still " + "fails for reasons outside the task.\n" + "\n" + "Never use `blocked` as: a dispatcher fence (to stop other work running), " + "a status update (use `kanban_comment`), a review queue (create a review " + "card), an ordinary dependency wait (express it with `parents=[...]`, " + "not `blocked`), or a substitute for child tasks (use `kanban_create`). " + "Dependencies are DAG edges, not blocked state.\n" + "\n" "## Orchestrator mode\n" "\n" "If your task is itself a decomposition task (e.g. a planner profile given " diff --git a/gateway/kanban_watchers.py b/gateway/kanban_watchers.py index dc2c5efd9011a..fdd72cacb132c 100644 --- a/gateway/kanban_watchers.py +++ b/gateway/kanban_watchers.py @@ -465,12 +465,13 @@ def _collect(): msg = f"🔄 {board_tag}{tag}Kanban {sub['task_id']} → {new_status}" elif kind == "block_loop_detected": # A task re-blocked for the same cause past the - # recurrence limit and was routed to `triage` for a - # human decision. This is the ONE transition that - # exists to force human attention, yet it emits no - # `blocked`/`status` event — so before adding it to - # TERMINAL_KINDS it produced zero notification and - # the task stalled in triage silently. Ping loudly. + # recurrence limit; the block is now sticky and only + # an explicit unblock resumes it. This is the ONE + # transition that exists to force human attention, + # yet it emits no `blocked`/`status` event — so + # before adding it to TERMINAL_KINDS it produced zero + # notification and the task stalled silently. Ping + # loudly. reason = "" recurrences = None if ev.payload: @@ -479,8 +480,8 @@ def _collect(): recurrences = ev.payload.get("recurrences") rc = f" (blocked {recurrences}x for the same cause)" if recurrences else "" msg = ( - f"🛑 {board_tag}{tag}Kanban {sub['task_id']} routed to TRIAGE" - f" — needs a human decision{rc}{reason}" + f"🛑 {board_tag}{tag}Kanban {sub['task_id']} STUCK BLOCKED" + f" — needs a human decision, unblock to resume{rc}{reason}" ) else: # archived / unblocked are claimed by TERMINAL_KINDS diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.py index 113e34842ec54..2be2dc57b2985 100644 --- a/hermes_cli/kanban_db.py +++ b/hermes_cli/kanban_db.py @@ -119,16 +119,21 @@ # # ``needs_input`` and ``capability`` are "truly blocked": they go to ``blocked`` # for a human, and the unblock-loop breaker (see ``block_task`` / -# ``BLOCK_RECURRENCE_LIMIT``) escalates them to ``triage`` if a cron keeps +# ``BLOCK_RECURRENCE_LIMIT``) escalates them to a *sticky* block if a cron keeps # unblocking them only to have the worker re-block for the same reason. # ``None`` = legacy/un-typed block (treated as a generic human blocker). VALID_BLOCK_KINDS = {"dependency", "needs_input", "capability", "transient"} # After a task has been blocked, unblocked, and re-blocked this many times for # the same (truly-blocked) reason, the unblock-loop breaker stops trusting the -# unblocker (usually a cron) and routes the task to ``triage`` instead of back -# to ``blocked`` — breaking the infinite unblock↔re-block loop and forcing a -# human-in-the-loop decision. Mirrors the dispatcher's ``DEFAULT_FAILURE_LIMIT`` +# unblocker (usually a cron): the task stays ``blocked`` and the emitted +# ``block_loop_detected`` event makes that block *sticky* (see +# ``_has_sticky_block``), so nothing short of an explicit operator ``unblock`` +# advances it — breaking the infinite unblock↔re-block loop and forcing a +# human-in-the-loop decision. It is deliberately NOT parked in ``triage``: that +# column is the auto-decomposer's input queue, which promoted escalated cards +# straight back into the work pool. +# Mirrors the dispatcher's ``DEFAULT_FAILURE_LIMIT`` # spirit (default 2) but counts a different signal: manual unblock recurrences, # not dispatcher spawn/crash/timeout failures. BLOCK_RECURRENCE_LIMIT = 2 @@ -238,6 +243,22 @@ def _fire_kanban_lifecycle_hook(event: str, task_id: str, **fields: Any) -> None # signal lands, and the following tick reclaims cleanly. RECLAIM_DEFER_GRACE_SECONDS = 120 +# Wall-clock budget for confirming a SIGKILLed worker process group is gone. +# Signal delivery is asynchronous, so a single post-SIGKILL probe would +# report a group that dies milliseconds later as a survivor and defer the +# requeue for a whole tick. Bounded so a genuinely unkillable group (D state) +# still falls through to the deferral path instead of blocking the tick. +WORKER_TERMINATION_VERIFY_SECONDS = 2.0 +WORKER_TERMINATION_VERIFY_PROBES = 40 + +# Upper bound on how long a worker fence may hold a task nonclaimable when +# the only thing keeping it alive is the process GROUP (the leader itself is +# gone, so we cannot prove the group is still the worker's rather than a +# recycled pgid). A fence whose leader is verifiably alive never expires — +# that one is a real duplicate-writer risk. This bound exists so an +# unverifiable hold degrades into a retry instead of stranding the task. +WORKER_FENCE_MAX_SECONDS = 60 * 60 + def _resolve_claim_ttl_seconds(ttl_seconds: Optional[int] = None) -> int: """Return the effective claim TTL, honoring the kanban env override. @@ -932,7 +953,17 @@ class Task: # ``_record_task_failure`` for the circuit-breaker trip rule. # (Pre-rename column: ``spawn_failures``.) consecutive_failures: int = 0 + # Effective limit the circuit breaker decided against on its last trip. + # See the column comment in SCHEMA_SQL: this is what makes the trip + # binding for every later promotion caller. + breaker_limit: Optional[int] = None worker_pid: Optional[int] = None + # Process-group id of the live worker (== worker_pid for workers we + # spawned, which get their own session). None on legacy rows. + worker_pgid: Optional[int] = None + # Identity token (start time) of the worker leader, captured at spawn. + # None on legacy rows / platforms without a probe. + worker_identity: Optional[str] = None # Short excerpt of the last failure's error text (any outcome, not # just spawn). Pre-rename column: ``last_spawn_error``. last_failure_error: Optional[str] = None @@ -1034,7 +1065,12 @@ def from_row(cls, row: sqlite3.Row) -> "Task": # belt-and-suspenders safety; in practice it is dead code post-migration. else (row["spawn_failures"] if "spawn_failures" in keys else 0) ), + breaker_limit=row["breaker_limit"] if "breaker_limit" in keys else None, worker_pid=row["worker_pid"] if "worker_pid" in keys else None, + worker_pgid=row["worker_pgid"] if "worker_pgid" in keys else None, + worker_identity=( + row["worker_identity"] if "worker_identity" in keys else None + ), last_failure_error=( row["last_failure_error"] if "last_failure_error" in keys # Same belt-and-suspenders fallback as consecutive_failures above. @@ -1210,7 +1246,30 @@ class Event: -- The circuit breaker in _record_task_failure trips when this -- exceeds DEFAULT_FAILURE_LIMIT consecutive non-successes. consecutive_failures INTEGER NOT NULL DEFAULT 0, + -- The effective limit the circuit breaker actually decided against when + -- it last tripped (mirrors the ``gave_up`` event's ``effective_limit``). + -- Set on trip, cleared on every deliberate fresh start (unblock, manual + -- promote, operator reclaim, successful completion). ``recompute_ready`` + -- honours THIS value rather than re-resolving a limit from its own + -- caller, so a restart / config change / caller mismatch can no longer + -- re-promote a task the breaker already gave up on. + breaker_limit INTEGER, worker_pid INTEGER, + -- Process-group id of the live worker (workers are spawned with + -- ``start_new_session=True``, so this is the whole tree: the worker plus + -- every tool subprocess it forked). Termination targets the group; the + -- PID alone leaves reparented children writing to the workspace. + worker_pgid INTEGER, + -- Identity token (process start time) of the live worker leader, taken + -- at spawn. PIDs and PGIDs are recycled numbers; this is what lets a + -- later tick tell "still our worker" from "the OS reused the number", + -- before signalling a process group or holding a task nonclaimable. + worker_identity TEXT, + -- JSON fence describing a previous worker that may still be running when + -- the task left ``running``. While the fenced process group is alive the + -- task is NOT claimable, so no second writer is spawned beside it. NULL + -- in the common case (termination confirmed / clean completion). + worker_fence TEXT, -- Short excerpt of the most recent failure's error text. last_failure_error TEXT, max_runtime_seconds INTEGER, @@ -1270,8 +1329,8 @@ class Event: block_kind TEXT, -- Unblock-loop counter. Incremented each time a task is re-blocked for the -- same truly-blocked reason after having been unblocked. When it reaches - -- BLOCK_RECURRENCE_LIMIT the task is routed to ``triage`` instead of - -- ``blocked`` so a cron can't spin it forever. Reset to 0 only on a + -- BLOCK_RECURRENCE_LIMIT the block becomes sticky (``block_loop_detected``) + -- so a cron can't spin it forever. Reset to 0 only on a -- successful completion — NOT on unblock (resetting on unblock is exactly -- the amnesia that let the loop run unbounded). block_recurrences INTEGER NOT NULL DEFAULT 0 @@ -2323,6 +2382,45 @@ def init_db( return path +# Events that end a breaker decision. Each one corresponds exactly to a code +# path that clears ``tasks.breaker_limit``: ``unblock_task`` ("unblocked"), +# ``promote_task`` ("promoted_manual") and ``complete_task`` ("completed", via +# ``_clear_failure_counter``). The legacy event-log fallback reads this list, +# so the two representations of "the trip was reset" cannot drift apart. +# +# A plain ``claimed`` is NOT a reset — claiming is not an operator decision +# about the retry budget. Neither is ``"reclaimed"``: a reclaim recovers a +# *worker*, and ``reclaim_task`` keeps the recorded limit for a task that is +# staying blocked. Listing it here would undo that one tick later on exactly +# the boards this fallback exists for — a trip recorded only in the event log +# would be cleared by the reclaim's own event, and the next +# ``recompute_ready`` would promote the task. +_BREAKER_RESET_KINDS = ( + "unblocked", "promoted_manual", "completed", +) + + +def _backfill_breaker_limit(conn: sqlite3.Connection) -> None: + """Lift the breaker decision from the event log onto ``tasks``. + + Boards written before the column existed recorded the trip only in the + ``gave_up`` event payload, which is why a later ``recompute_ready`` with + a different caller limit could re-promote them (the ``t_27263082`` + incident). Copy the recorded ``effective_limit`` onto every still-blocked + task whose most recent lifecycle event is that ``gave_up``. + """ + rows = conn.execute( + "SELECT id FROM tasks WHERE status = 'blocked' AND breaker_limit IS NULL" + ).fetchall() + for row in rows: + limit = _breaker_limit_from_events(conn, row["id"]) + if limit is not None: + conn.execute( + "UPDATE tasks SET breaker_limit = ? WHERE id = ?", + (limit, row["id"]), + ) + + def _migrate_add_optional_columns(conn: sqlite3.Connection) -> None: """Add columns that were introduced after v1 release to legacy DBs. @@ -2377,6 +2475,26 @@ def _migrate_add_optional_columns(conn: sqlite3.Connection) -> None: ) if "worker_pid" not in cols: _add_column_if_missing(conn, "tasks", "worker_pid", "worker_pid INTEGER") + if "worker_pgid" not in cols: + # Process-group id of the live worker. NULL on legacy rows and on + # any worker spawned before this column existed — termination then + # falls back to the PID, which is exactly the old behaviour. + _add_column_if_missing(conn, "tasks", "worker_pgid", "worker_pgid INTEGER") + if "worker_identity" not in cols: + # Identity token for the live worker leader. NULL on legacy rows and + # on any platform without a cheap probe (Windows) — callers fail + # closed on NULL: pid-only signalling, no fence held. + _add_column_if_missing( + conn, "tasks", "worker_identity", "worker_identity TEXT", + ) + if "worker_fence" not in cols: + # Nonclaimable fence for a worker that may still be running after the + # task left ``running``. NULL = no fence (legacy rows included). + _add_column_if_missing(conn, "tasks", "worker_fence", "worker_fence TEXT") + if "breaker_limit" not in cols: + _add_column_if_missing(conn, "tasks", "breaker_limit", "breaker_limit INTEGER") + if "status" in cols: + _backfill_breaker_limit(conn) if "last_failure_error" not in cols: added = _add_column_if_missing( conn, "tasks", "last_failure_error", "last_failure_error TEXT" @@ -2593,8 +2711,67 @@ def _migrate_add_optional_columns(conn: sqlite3.Connection) -> None: (new, old), ) + # Order matters: the escalation migration decides which rows are still + # escalated by reading the NEWEST block-lifecycle event (``ORDER BY id + # DESC``). On a pre-#35096 board ``task_events.id`` is still TEXT, so that + # ordering is lexicographic — ``ev-9`` outranks ``ev-10`` — and a history + # ending ``block_loop_detected (ev-9), unblocked (ev-10)`` reads backwards. + # ``_rebuild_drifted_tables`` renumbers those ids to chronological + # INTEGERs, so it has to run FIRST or the migration converts an + # already-unblocked triage card to ``blocked``, the rebuild then makes it + # nonsticky again, and the next ``recompute_ready`` promotes it to + # ``ready`` for a worker to claim. _rebuild_drifted_tables(conn) + _migrate_block_loop_escalations_out_of_triage(conn) + + +def _migrate_block_loop_escalations_out_of_triage( + conn: sqlite3.Connection, +) -> None: + """Move pre-fix unblock-loop escalations from ``triage`` to ``blocked``. + + Until this fix ``block_task`` routed a loop escalation to ``triage``. With + ``kanban.auto_decompose`` on (the default) the dispatcher then treated that + card as a decompose candidate and walked it ``triage -> todo -> ready`` + without a lifecycle event, handing a task that needs a human straight back + to a worker. Boards written before the fix still have those rows, so + activation must lift them into the sticky ``blocked`` state the escalation + always meant — otherwise the first tick after upgrading resurrects them. + + Deliberately narrow: only rows sitting in ``triage`` that carry a + ``block_kind`` *and* whose most recent block-lifecycle event is + ``block_loop_detected``. An ordinary triage card (no block history) and an + escalation an operator already unblocked (latest event ``unblocked``) are + both left exactly where they are. + """ + cols = {row["name"] for row in conn.execute("PRAGMA table_info(tasks)")} + if "block_kind" not in cols or "status" not in cols: + return + candidates = [ + row["id"] for row in conn.execute( + "SELECT id FROM tasks WHERE status = 'triage' AND block_kind IS NOT NULL" + ) + ] + stuck = [tid for tid in candidates if has_block_loop_escalation(conn, tid)] + if not stuck: + return + with write_txn(conn): + for tid in stuck: + # Re-check status inside the txn: a racing operator may have moved + # the card out of triage between the scan and here. + conn.execute( + "UPDATE tasks SET status = 'blocked', claim_lock = NULL, " + "claim_expires = NULL, worker_pid = NULL, worker_pgid = NULL, " + "worker_identity = NULL " + "WHERE id = ? AND status = 'triage'", + (tid,), + ) + _log.info( + "kanban: moved %d block-loop escalation(s) out of triage into the " + "sticky blocked state", len(stuck), + ) + # Legacy DBs defined these tables with a ``TEXT PRIMARY KEY`` id (or, for # ``kanban_notify_subs``, a nullable ``TEXT last_event_id``). The current @@ -4122,14 +4299,197 @@ def _has_sticky_block(conn: sqlite3.Connection, task_id: str) -> bool: was set to ``status='blocked'`` by the circuit breaker or by direct DB manipulation) — preserves the pre-#28712 auto-recover semantics for that path. + + ``block_loop_detected`` counts as sticky too: it is the unblock-loop + breaker's escalation, i.e. the *strongest* possible "stop automating + this, a human must decide" signal. It used to park the task in + ``triage`` where the auto-decomposer promoted it straight back into + the work pool; now it stays ``blocked`` and this predicate is what + keeps it there. + + Two events end it, both deliberate operator acts: ``unblock_task`` + (``"unblocked"``) and ``promote_task`` (``"promoted_manual"``). A + ``reclaim`` is NOT one of them — reclaim recovers a *worker*, and + reading it as a release is what let an operator poke at a stuck row and + silently resurrect a task nobody had decided to resume. + """ + return _latest_block_event_kind(conn, task_id) in ( + "blocked", "block_loop_detected", + ) + + +_BLOCK_LIFECYCLE_KINDS = ( + "blocked", "unblocked", "block_loop_detected", "promoted_manual", +) + + +def _latest_block_event_kind( + conn: sqlite3.Connection, task_id: str, +) -> Optional[str]: + """Return the most recent block-lifecycle event kind for ``task_id``. + + One of :data:`_BLOCK_LIFECYCLE_KINDS`, or ``None`` when the task has + never been blocked, unblocked or manually promoted. """ + placeholders = ", ".join("?" for _ in _BLOCK_LIFECYCLE_KINDS) row = conn.execute( - "SELECT kind FROM task_events " - "WHERE task_id = ? AND kind IN ('blocked', 'unblocked') " - "ORDER BY id DESC LIMIT 1", - (task_id,), + f"SELECT kind FROM task_events " + f"WHERE task_id = ? AND kind IN ({placeholders}) " + f"ORDER BY id DESC LIMIT 1", + (task_id, *_BLOCK_LIFECYCLE_KINDS), ).fetchone() - return bool(row) and row["kind"] == "blocked" + return str(row["kind"]) if row else None + + +def has_block_loop_escalation( + conn: sqlite3.Connection, task_id: str, +) -> bool: + """Return True when ``task_id`` currently carries an unescaped + unblock-loop escalation. + + Defense in depth for the orchestration paths: a row whose latest + block-lifecycle event is ``block_loop_detected`` is waiting on a human, + no matter which column it happens to sit in — including a legacy row + still parked in ``triage`` by the pre-fix routing, or one an operator + dragged there by hand. Auto-decompose / specify must never advance it. + An explicit ``unblock_task`` or ``promote_task`` clears this. + + Most callers want the broader :func:`terminal_hold_reason`, which covers + the plain sticky block and the breaker trip as well. This one stays for + code that needs to distinguish the escalation specifically. + """ + return _latest_block_event_kind(conn, task_id) == "block_loop_detected" + + +def _breaker_limit_from_events( + conn: sqlite3.Connection, task_id: str, +) -> Optional[int]: + """Recover the recorded breaker decision from the event log. + + Fallback for rows written before ``tasks.breaker_limit`` existed (the + migration backfills them, but a board can also be restored from an old + dump). Only the most recent lifecycle event counts: a ``gave_up`` + followed by an ``unblocked`` / manual promote / completion has already + been cleared by an operator and must NOT bind. A ``reclaimed`` is not on + that list — see :data:`_BREAKER_RESET_KINDS`. + """ + kinds = ("gave_up",) + _BREAKER_RESET_KINDS + placeholders = ", ".join("?" for _ in kinds) + row = conn.execute( + f"SELECT kind, payload FROM task_events " + f"WHERE task_id = ? AND kind IN ({placeholders}) " + f"ORDER BY id DESC LIMIT 1", + (task_id, *kinds), + ).fetchone() + if not row or row["kind"] != "gave_up" or not row["payload"]: + return None + try: + limit = json.loads(row["payload"]).get("effective_limit") + except (ValueError, TypeError): + return None + return int(limit) if isinstance(limit, int) else None + + +def recorded_breaker_limit( + conn: sqlite3.Connection, task_id: str, +) -> Optional[int]: + """Return the effective limit the breaker last tripped against, or None. + + ``None`` means "no binding decision on record" — either the task never + tripped, or an operator cleared it (unblock / manual promote) or it + completed successfully. A reclaim is NOT one of those: it recovers a + worker, not the task. Callers that promote tasks must honour a + non-None value instead of resolving a limit of their own: the limit that + tripped the breaker is the one the task actually exhausted, and a + gateway restart, a changed ``kanban.failure_limit``, or a caller that + forgets to thread the config through must not quietly hand the task + another retry (incident ``t_27263082``). + """ + row = conn.execute( + "SELECT breaker_limit FROM tasks WHERE id = ?", (task_id,), + ).fetchone() + if row is None: + return None + if row["breaker_limit"] is not None: + return int(row["breaker_limit"]) + return _breaker_limit_from_events(conn, task_id) + + +def _clear_breaker_limit(conn: sqlite3.Connection, task_id: str) -> None: + """Drop the recorded breaker decision (deliberate fresh start).""" + conn.execute( + "UPDATE tasks SET breaker_limit = NULL WHERE id = ?", (task_id,), + ) + + +def _breaker_trip_is_active( + conn: sqlite3.Connection, + task_id: str, + column_value: Any = None, +) -> bool: + """True when a recorded give-up decision still binds this task. + + Presence is the whole test. The counter is deliberately NOT compared + against the recorded limit: ``force_trip`` callers record ``gave_up`` + with fewer failures than the limit (a systemic error fingerprint, or the + protocol-violation streak reaching its own bound), and comparing would + read those as "still under budget" and promote them. + + ``column_value`` lets callers that already selected ``breaker_limit`` + pass it in rather than re-reading the row. + """ + if column_value is not None: + return True + return _breaker_limit_from_events(conn, task_id) is not None + + +_UNREAD = object() + + +def terminal_hold_reason( + conn: sqlite3.Connection, + task_id: str, + breaker_limit: Any = _UNREAD, +) -> Optional[str]: + """Why ``task_id`` may not be advanced by automation, or ``None``. + + A terminal hold is a decision *about the task*, not a property of the + column it happens to sit in. Two produce one: + + * ``"sticky_block"`` / ``"block_loop_escalation"`` — a worker or + operator called ``kanban_block``, or the unblock-loop breaker + escalated (see :func:`_has_sticky_block`). + * ``"breaker_trip"`` — the circuit breaker recorded ``gave_up`` and + persisted the limit it tripped against (see + :func:`recorded_breaker_limit`). + + Both were already understood — but only by ``recompute_ready``, and + only for rows it found in ``blocked``. Every other door into the work + pool re-derived a narrower rule of its own, so a held row that reached + another column by any route was advanced anyway: ``claim_task`` had no + check at all, the triage promoters gated on the escalation alone, and + ``reclaim_task`` flipped ``blocked -> ready`` outright. This is the one + predicate all of them share, so a new promotion path cannot quietly + disagree with the others about what "blocked" means. + + ``breaker_limit`` lets a caller that already selected the column pass + it in; omit it and the row is read (falling back to the event log for + boards written before the column existed). + + Released only by the explicit operator escapes — ``unblock_task`` and + ``promote_task`` — or by a successful completion, which clears the + breaker decision outright. + """ + kind = _latest_block_event_kind(conn, task_id) + if kind == "block_loop_detected": + return "block_loop_escalation" + if kind == "blocked": + return "sticky_block" + if breaker_limit is _UNREAD: + tripped = recorded_breaker_limit(conn, task_id) is not None + else: + tripped = _breaker_trip_is_active(conn, task_id, breaker_limit) + return "breaker_trip" if tripped else None def recompute_ready( @@ -4144,9 +4504,12 @@ def recompute_ready( blocked purely by a parent dependency unblocks itself when the parent completes), *except* in two cases: - 1. The most recent block event was a worker-initiated - ``kanban_block`` — those stay blocked until an explicit - ``kanban_unblock`` (#28712). + 1. The row is on a terminal hold — a worker-initiated + ``kanban_block`` (#28712), the unblock-loop escalation, or a + recorded breaker trip. :func:`terminal_hold_reason` is the single + predicate, and it is checked for ``todo`` candidates too: the hold + is a decision about the task, so it cannot be something a row + escapes by being in a different column. 2. The task's ``consecutive_failures`` has reached the effective failure limit. This prevents infinite retry loops when a task @@ -4158,27 +4521,45 @@ def recompute_ready( circuit breaker in ``_record_task_failure`` so the two never disagree about when a task is permanently blocked: + 0. the limit the breaker ACTUALLY tripped against, when it has + already tripped (``tasks.breaker_limit``) — nothing a caller + passes can widen a decision the task already exhausted 1. per-task ``max_retries`` if set 2. caller-supplied ``failure_limit`` (the dispatcher passes the ``kanban.failure_limit`` config value through ``dispatch_once``) 3. ``DEFAULT_FAILURE_LIMIT`` + + Step 0 is what closes the ``t_27263082`` hole: the breaker gave up at + ``effective_limit=2`` and a later recompute — run from a restarted + gateway, a caller that didn't thread the config through, or after + ``kanban.failure_limit`` was raised — resolved a laxer limit, decided + the task was still under budget, and handed it back to the dispatcher. + Steps 1-3 still apply to tasks that never tripped (a task blocked on a + dependency, or parked at ``blocked`` by hand), preserving #35072's + lenient-config recovery. """ if failure_limit is None: failure_limit = DEFAULT_FAILURE_LIMIT promoted = 0 with write_txn(conn): todo_rows = conn.execute( - "SELECT id, status, consecutive_failures, max_retries " + "SELECT id, status, consecutive_failures, max_retries, breaker_limit " "FROM tasks WHERE status IN ('todo', 'blocked')" ).fetchall() for row in todo_rows: task_id = row["id"] cur_status = row["status"] - if cur_status == "blocked" and _has_sticky_block(conn, task_id): - # Worker / operator asked for human review — do not - # silently auto-recover. ``unblock_task`` is the only - # legitimate exit (it emits ``"unblocked"`` which flips - # this predicate back). + # A terminal hold binds in EVERY column, not just ``blocked``. + # Checking it only on the blocked branch meant anything that + # moved a held row to ``todo`` — a re-specify, an operator drag, + # a restored dump — got it promoted on the very next tick. A + # ``dependency`` block routes to ``todo`` deliberately and emits + # ``dependency_wait`` (not ``blocked``), so it is untouched by + # this and still frees itself when its parents finish. + if terminal_hold_reason(conn, task_id, row["breaker_limit"]): + # Worker / operator asked for human review, or the breaker + # gave up — do not silently auto-recover. ``unblock_task`` + # and ``promote_task`` are the legitimate exits. continue parents = conn.execute( "SELECT t.status FROM tasks t " @@ -4196,6 +4577,12 @@ def recompute_ready( # exhausted → block → … The counter must also # be preserved so the breaker can accumulate # across recovery cycles. + # A recorded trip binds on its OWN, not on a counter + # comparison — that is ``terminal_hold_reason``'s job + # above, and it has already run for this row. What is + # left here is #35072's lenient path: a task that never + # tripped (blocked by hand, or on a dependency) whose + # counter has nonetheless reached the limit. failures = int(row["consecutive_failures"] or 0) task_limit = row["max_retries"] effective_limit = ( @@ -4238,7 +4625,45 @@ def claim_task( now = int(time.time()) lock = claimer or _claimer_id() expires = now + _resolve_claim_ttl_seconds(ttl_seconds) + # Process fence (outside the txn — it probes the OS and may write its own + # clear). A task whose previous worker process group can still write is + # not claimable at any price: claiming would put two writers on the same + # task + workspace, which is the duplicate-run incident ``t_80a3542a``. + fence = _fence_blocks_claim(conn, task_id) + if fence is not None: + with write_txn(conn): + _append_event( + conn, task_id, "claim_rejected", + { + "reason": "prior_worker_alive", + "fence_pid": fence.get("pid"), + "fence_pgid": fence.get("pgid"), + "fence_run_id": fence.get("run_id"), + "fence_reason": fence.get("reason"), + }, + ) + return None with write_txn(conn): + # Structural invariant, same shape as the parent gate below: a + # terminal hold binds no matter which writer put this row in + # 'ready'. ``recompute_ready`` refuses to promote a held task, but + # it is not the only writer of status='ready' — a racy promote, a + # stale-claim release, a restored dump or an operator's manual SQL + # all reach here, and this is the only door into 'running'. Demote + # to 'blocked' (where a held task belongs) so the next tick doesn't + # re-litigate the same decision. + hold = terminal_hold_reason(conn, task_id) + if hold: + conn.execute( + "UPDATE tasks SET status = 'blocked' " + "WHERE id = ? AND status = 'ready'", + (task_id,), + ) + _append_event( + conn, task_id, "claim_rejected", + {"reason": "terminal_hold", "hold": hold}, + ) + return None # Structural invariant: never transition ready -> running while any # parent is not yet 'done'. This is the single enforcement point # regardless of which writer (create_task, link_tasks, unblock_task, @@ -4284,6 +4709,12 @@ def claim_task( """, (now, int(stale["current_run_id"])), ) + # ``worker_fence IS NULL`` belongs INSIDE the CAS, not just in the + # gate above. The gate probes the OS, so it cannot run under the + # write lock — which leaves a window where a reaper tick commits + # ``ready`` + a fresh fence while this claimer is between gate and + # CAS. Guarding only status/claim_lock, the stale claimer still wins + # and lands a second writer next to the live orphan group. cur = conn.execute( """ UPDATE tasks @@ -4294,6 +4725,7 @@ def claim_task( WHERE id = ? AND status = 'ready' AND claim_lock IS NULL + AND worker_fence IS NULL """, (lock, expires, now, task_id), ) @@ -4367,7 +4799,48 @@ def claim_review_task( now = int(time.time()) lock = claimer or _claimer_id() expires = now + _resolve_claim_ttl_seconds(ttl_seconds) + # ``review -> running`` spawns a worker just like ``ready -> running``, + # so it takes the same process fence and the same atomic guard. A review + # task is not fenced today (fences are recorded on requeue paths that + # land in ``ready``), but the gate is cheap and the invariant — no claim + # while a previous process group can still write — should hold at every + # entrance, not just the one that happens to be reachable. + fence = _fence_blocks_claim(conn, task_id) + if fence is not None: + with write_txn(conn): + _append_event( + conn, task_id, "claim_rejected", + { + "reason": "prior_worker_alive", + "gate": "review", + "fence_pid": fence.get("pid"), + "fence_pgid": fence.get("pgid"), + "fence_run_id": fence.get("run_id"), + "fence_reason": fence.get("reason"), + }, + ) + return None with write_txn(conn): + # Same terminal-hold gate as ``claim_task``: the review column is a + # second door into 'running', and a held card must not walk through + # it either. + # + # Refuse WITHOUT demoting, unlike the ``ready`` gate. ``ready`` is the + # active work pool that ``recompute_ready`` keeps re-examining, so + # parking a held row at 'blocked' settles it; ``review`` is neither — + # recompute only ever promotes out of 'todo'/'blocked', so refusing + # the claim already binds the hold. Demoting would be a one-way door: + # ``unblock_task`` restores 'ready' (or 'todo' behind open parents) + # and never 'review', so the card would come back as ordinary + # implementation work with its PR already open — the very failure + # ``_claim_source_status`` exists to prevent. + hold = terminal_hold_reason(conn, task_id) + if hold: + _append_event( + conn, task_id, "claim_rejected", + {"reason": "terminal_hold", "hold": hold, "gate": "review"}, + ) + return None cur = conn.execute( """ UPDATE tasks @@ -4378,6 +4851,7 @@ def claim_review_task( WHERE id = ? AND status = 'review' AND claim_lock IS NULL + AND worker_fence IS NULL """, (lock, expires, now, task_id), ) @@ -4485,7 +4959,8 @@ def release_stale_claims( reclaimed = 0 host_prefix = f"{_claimer_id().split(':', 1)[0]}:" stale = conn.execute( - "SELECT id, claim_lock, worker_pid, claim_expires, last_heartbeat_at " + "SELECT id, claim_lock, worker_pid, worker_pgid, worker_identity, " + " claim_expires, last_heartbeat_at, current_run_id " "FROM tasks " "WHERE status = 'running' AND claim_expires IS NOT NULL " " AND claim_expires < ?", @@ -4506,7 +4981,7 @@ def release_stale_claims( if ( host_local and row["worker_pid"] - and _pid_alive(row["worker_pid"]) + and _worker_leader_alive(row["worker_pid"], row["worker_identity"]) and not heartbeat_stale ): new_expires = now + _resolve_claim_ttl_seconds() @@ -4547,6 +5022,7 @@ def release_stale_claims( termination = _terminate_reclaimed_worker( row["worker_pid"], row["claim_lock"], signal_fn=signal_fn, + pgid=row["worker_pgid"], identity=row["worker_identity"], ) # Never release a claim while our own worker is still alive: that would # spawn a duplicate beside it. Hold the claim and retry next tick. @@ -4556,10 +5032,26 @@ def release_stale_claims( reason="ttl_expired_worker_alive", ) continue + if termination.get("still_alive"): + # Requeuing a worker we could not confirm dead — its children + # still hold the process group. Fence the task so the claim gate + # keeps it out of a second worker's hands until the group exits. + # ``still_alive`` is only ever set for host-local claims, so this + # never fences on another host's pid numbers. + record_worker_fence( + conn, row["id"], + pid=row["worker_pid"], + pgid=row["worker_pgid"], + run_id=row["current_run_id"], + claim_lock=row["claim_lock"], + reason="stale_claim_unconfirmed_termination", + identity=row["worker_identity"], + ) with write_txn(conn): cur = conn.execute( "UPDATE tasks SET status = 'ready', claim_lock = NULL, " - "claim_expires = NULL, worker_pid = NULL " + "claim_expires = NULL, worker_pid = NULL, worker_pgid = NULL, " + "worker_identity = NULL " "WHERE id = ? AND status = 'running' AND claim_lock IS ? " "AND claim_expires IS NOT NULL AND claim_expires < ?", (row["id"], row["claim_lock"], now), @@ -4616,28 +5108,139 @@ def reclaim_task( reclaimable state (not running, or doesn't exist). """ row = conn.execute( - "SELECT status, claim_lock, worker_pid FROM tasks WHERE id = ?", + "SELECT status, claim_lock, worker_pid, worker_pgid, worker_identity, " + " current_run_id FROM tasks WHERE id = ?", (task_id,), ).fetchone() if not row: return False - if row["status"] != "running" and row["claim_lock"] is None: - # Nothing to reclaim — already ready / blocked / done. + fence_raw, fence = _read_worker_fence(conn, task_id) + if ( + row["status"] != "running" + and row["claim_lock"] is None + and fence is None + ): + # Nothing to reclaim — already ready / blocked / done, and nothing + # holding it back. A task that is merely FENCED is still reclaimable + # so the operator can re-drive the release check, but note that a + # reclaim does NOT override a valid fence: it releases one only on + # the same evidence the claim gate would accept. ``promote`` and + # ``unblock`` are the documented overrides. return False prev_lock = row["claim_lock"] + # A reclaim recovers a *worker*; it is not a decision to resume the + # *task*. A held row can still reach here — a blocked task that kept a + # fence from an unconfirmed termination passes the gate above — and + # unconditionally writing 'ready' resurrected it, breaker decision + # cleared and all. Release the claim, kill the group, resolve the fence, + # and leave it blocked: ``promote`` / ``unblock`` remain the overrides. + hold = terminal_hold_reason(conn, task_id) + new_status = "blocked" if hold else "ready" + + # Which process do we probe? A task that still owns a worker has it on + # the row. A task that was already requeued behind a fence does NOT: the + # requeue NULLs worker_pid / worker_pgid / worker_identity, so the fence + # payload is the only surviving record of the group that can still write. + # Probing the empty columns would ask "is nothing alive?", get "no", and + # release the task straight into the duplicate-writer state the fence + # exists to prevent. + if row["worker_pid"]: + probe_pid = row["worker_pid"] + probe_pgid = row["worker_pgid"] + probe_identity = row["worker_identity"] + probe_lock = prev_lock + probe_run_id = row["current_run_id"] + else: + probe_pid = fence.get("pid") if fence else None + probe_pgid = fence.get("pgid") if fence else None + probe_identity = fence.get("identity") if fence else None + probe_lock = (fence.get("claim_lock") if fence else None) or prev_lock + probe_run_id = ( + (fence.get("run_id") if fence else None) or row["current_run_id"] + ) + + # Probe and terminate BEFORE writing anything. Every decision below is + # then committed in one transaction, so there is no instant where the + # row is unfenced-but-undecided for a concurrent dispatcher tick to + # claim through. termination = _terminate_reclaimed_worker( - row["worker_pid"], prev_lock, signal_fn=signal_fn, + probe_pid, probe_lock, signal_fn=signal_fn, + pgid=probe_pgid, identity=probe_identity, ) + now = int(time.time()) + if fence is not None: + # The fence's own release rules are the authority for a fence: same + # predicate the claim gate uses, so an operator reclaim can never be + # more permissive than an ordinary claim would have been. It clears + # for a group that is gone, a recycled identity, another host's + # fence, or one that outlived its bound — and holds otherwise. + release_reason = _fence_release_reason(fence, now) + keep_fence = release_reason is None + new_fence = None + else: + keep_fence = bool(termination.get("still_alive")) + release_reason = None + # The operator wants the task back now, but the old group can still + # write. Release the claim (their call) yet record a fence so the + # recovery doesn't create the duplicate-writer state it was meant + # to fix. + new_fence = _build_worker_fence( + pid=probe_pid, + pgid=probe_pgid, + run_id=probe_run_id, + claim_lock=probe_lock, + # An unidentified row whose leader survived the kill is the one + # case that would otherwise be fenced on a bare number, and the + # bound on that weak evidence would expire under a worker that + # never stopped writing. The termination probe saw the live + # process; pin what it saw. The automatic reclaims never reach + # here with a live leader — they hold the claim instead — so + # this is the only site where the fallback can be non-None. + identity=probe_identity or termination.get("observed_identity"), + reason="manual_reclaim_unconfirmed_termination", + ) if keep_fence else None + + # One CAS for the whole decision. ``worker_fence IS ?`` binds the exact + # fence this call read BEFORE probing the OS, so a fence recorded in the + # meantime (a live worker we never looked at) makes the statement match + # nothing — and because the fence write rides the same UPDATE, a refusal + # cannot leave the task half-reclaimed: released but with no ``reclaimed`` + # event, no finalized run, and ``current_run_id`` pointing at a run row + # that stays open forever. + if new_fence is not None: + fence_set_sql = ", worker_fence = ?" + fence_param: tuple = (json.dumps(new_fence, ensure_ascii=False),) + elif fence is not None and not keep_fence: + fence_set_sql = ", worker_fence = NULL" + fence_param = () + else: + fence_set_sql = "" + fence_param = () + with write_txn(conn): cur = conn.execute( - "UPDATE tasks SET status = 'ready', claim_lock = NULL, " - "claim_expires = NULL, worker_pid = NULL " + "UPDATE tasks SET status = ?, claim_lock = NULL, " + "claim_expires = NULL, worker_pid = NULL, worker_pgid = NULL, " + "worker_identity = NULL" + fence_set_sql + " " "WHERE id = ? AND status IN ('running', 'ready', 'blocked') " - "AND claim_lock IS ?", - (task_id, prev_lock), + "AND claim_lock IS ? AND worker_fence IS ?", + (new_status, *fence_param, task_id, prev_lock, fence_raw), ) if cur.rowcount != 1: + # Nothing was written: the task moved on, or a newer fence + # appeared. Both mean "not this reclaim's call to make". return False + if new_fence is not None: + _append_event(conn, task_id, "worker_fenced", new_fence) + elif fence is not None and not keep_fence: + _append_event( + conn, task_id, "worker_fence_cleared", + { + **fence, + "cleared_reason": release_reason, + "on": "operator_reclaim", + }, + ) run_id = _end_run( conn, task_id, outcome="reclaimed", status="reclaimed", @@ -4651,6 +5254,8 @@ def reclaim_task( "manual": True, "reason": reason, "prev_lock": prev_lock, + "fence_held": keep_fence, + "terminal_hold": hold, } payload.update(termination) _append_event( @@ -4661,8 +5266,11 @@ def reclaim_task( # Operator intervention — they've looked at the task, so the # consecutive-failures counter is now stale. Give the next retry # a fresh budget. (_clear_failure_counter opens its own write_txn, - # so it runs after the enclosing one commits.) - _clear_failure_counter(conn, task_id) + # so it runs after the enclosing one commits.) The breaker's give-up + # decision survives when it is what is holding the task: clearing it + # here would leave the row blocked but freely promotable by the next + # ``recompute_ready``, which is the same resurrection by a slower route. + _clear_failure_counter(conn, task_id, keep_breaker_limit=hold is not None) return True @@ -4909,11 +5517,14 @@ def complete_task( """ UPDATE tasks SET status = 'done', + worker_fence = NULL, result = ?, completed_at = ?, claim_lock = NULL, claim_expires= NULL, worker_pid = NULL, + worker_pgid = NULL, + worker_identity = NULL, block_kind = NULL, block_recurrences = 0 WHERE id = ? @@ -4926,11 +5537,14 @@ def complete_task( """ UPDATE tasks SET status = 'done', + worker_fence = NULL, result = ?, completed_at = ?, claim_lock = NULL, claim_expires= NULL, worker_pid = NULL, + worker_pgid = NULL, + worker_identity = NULL, block_kind = NULL, block_recurrences = 0 WHERE id = ? @@ -5639,16 +6253,19 @@ def block_task( "Type 1"). Lands in ``blocked`` for a human. BUT: each time such a task is re-blocked for the SAME kind after having been unblocked, the unblock-loop counter (``block_recurrences``) increments. When it reaches - :data:`BLOCK_RECURRENCE_LIMIT`, the task is routed to ``triage`` instead - of ``blocked`` — breaking the cron-unblock ↔ worker-re-block loop and - forcing a human-in-the-loop triage decision. + :data:`BLOCK_RECURRENCE_LIMIT`, the block is escalated: the task stays in + ``blocked`` but a ``block_loop_detected`` event makes it *sticky*, so + ``recompute_ready`` / claim / auto-decompose / a dispatcher tick can no + longer advance it and only an explicit ``unblock_task`` resumes it — + breaking the cron-unblock ↔ worker-re-block loop and forcing a + human-in-the-loop decision. * ``transient`` — treated like a generic block for routing, but a worker can use it to signal "this might clear on its own"; it still participates in the loop breaker so a forever-flaky task eventually escalates. - Returns True on any successful transition (to ``blocked``, ``todo``, or - ``triage``), False when the task wasn't in a blockable state. + Returns True on any successful transition (to ``blocked`` — plain or + sticky — or ``todo``), False when the task wasn't in a blockable state. """ if kind is not None and kind not in VALID_BLOCK_KINDS: raise ValueError( @@ -5682,6 +6299,8 @@ def block_task( claim_lock = NULL, claim_expires = NULL, worker_pid = NULL, + worker_pgid = NULL, + worker_identity = NULL, block_kind = ? WHERE id = ? AND status IN ('running', 'ready') @@ -5725,15 +6344,28 @@ def block_task( recurrences = prev_recurrences + 1 if same_cause else 1 if recurrences >= BLOCK_RECURRENCE_LIMIT: - # Loop detected — stop letting the unblocker spin this task. Route - # to triage for a human-in-the-loop decision instead of blocked. + # Loop detected — stop letting the unblocker spin this task. It + # stays in ``blocked``, but the ``block_loop_detected`` event makes + # that block *sticky* (see ``_has_sticky_block``): recompute_ready, + # claim, restart/migration and the dispatcher tick all refuse to + # advance it, and only an explicit ``unblock_task`` resumes it. + # + # This deliberately does NOT route to ``triage`` any more. Triage + # is an automation queue, not a human hold: with the default + # ``kanban.auto_decompose: true`` the dispatcher treats every + # triage row as a decompose/specify candidate and silently walked + # escalated cards triage -> todo -> ready on the next tick + # (observed live on ``t_bdf1001a`` and ``t_80a3542a``), which is + # exactly the blocked-task resurrection the breaker exists to stop. cur = conn.execute( """ UPDATE tasks - SET status = 'triage', + SET status = 'blocked', claim_lock = NULL, claim_expires = NULL, worker_pid = NULL, + worker_pgid = NULL, + worker_identity = NULL, block_kind = ?, block_recurrences = ? WHERE id = ? @@ -5772,6 +6404,8 @@ def block_task( claim_lock = NULL, claim_expires = NULL, worker_pid = NULL, + worker_pgid = NULL, + worker_identity = NULL, block_kind = ?, block_recurrences = ? WHERE id = ? @@ -5787,6 +6421,8 @@ def block_task( claim_lock = NULL, claim_expires = NULL, worker_pid = NULL, + worker_pgid = NULL, + worker_identity = NULL, block_kind = ?, block_recurrences = ? WHERE id = ? @@ -5888,6 +6524,13 @@ def promote_task( ) if upd.rowcount != 1: return False, f"task {task_id} status changed during promotion" + # A deliberate operator promote overrides a recorded breaker trip — + # otherwise the task would land in ``ready`` but be re-blocked (and + # never re-promoted) by the next automatic recompute. It is also one + # of the explicit escapes from a worker fence: the operator has + # looked at the task and wants it dispatched. + _clear_breaker_limit(conn, task_id) + clear_worker_fence(conn, task_id) _append_event( conn, task_id, @@ -5943,15 +6586,20 @@ def unblock_task(conn: sqlite3.Connection, task_id: str) -> bool: # ``block_kind``. Resetting the recurrence counter on unblock is exactly # the amnesia that let a cron unblock → worker re-block loop run # unbounded (Dale's report). The counter survives the unblock so that a - # subsequent same-cause ``block_task`` can detect the loop and route to - # triage at ``BLOCK_RECURRENCE_LIMIT``. It is reset to 0 only on a + # subsequent same-cause ``block_task`` can detect the loop and escalate + # to a sticky block at ``BLOCK_RECURRENCE_LIMIT``. It is reset to 0 only on a # successful completion (see ``complete_task``). ``consecutive_failures`` # (the *dispatcher* spawn/crash/timeout counter — a different signal) is # still reset here, which is correct: a deliberate unblock is a fresh # start for the dispatcher's retry budget. + # ``breaker_limit`` is cleared alongside ``consecutive_failures`` for + # the same reason: an explicit unblock is the operator saying "try + # again", so the recorded trip must stop binding ``recompute_ready``. cur = conn.execute( "UPDATE tasks SET status = ?, current_run_id = NULL, " - "consecutive_failures = 0, last_failure_error = NULL " + "consecutive_failures = 0, last_failure_error = NULL, " + "breaker_limit = NULL, worker_fence = NULL, worker_pgid = NULL, " + "worker_identity = NULL " "WHERE id = ? AND status IN ('blocked', 'scheduled')", (new_status, task_id), ) @@ -5999,6 +6647,13 @@ def specify_triage_task( ).fetchone() if existing is None: return False + if terminal_hold_reason(conn, task_id): + # A row on a terminal hold is a human hold, even if something + # parked it in ``triage``. Promoting it here is the resurrection + # path the breaker exists to prevent. The escalation was already + # caught; a plain sticky block and a recorded give-up are the + # same class of decision and were not. + return False sets: list[str] = ["status = 'todo'"] params: list[Any] = [] changed_fields: list[str] = [] @@ -6156,6 +6811,10 @@ def decompose_triage_task( return None if root_row["status"] != "triage": return None + if terminal_hold_reason(conn, task_id): + # Same human-hold guard as ``specify_triage_task``: never fan out + # a card that a worker blocked or the breaker gave up on. + return None tenant = root_row["tenant"] # Children inherit the root's workspace by default so a fan-out # of a code-gen task lands in the parent's project dir/worktree @@ -6292,7 +6951,9 @@ def archive_task(conn: sqlite3.Connection, task_id: str) -> bool: with write_txn(conn): cur = conn.execute( "UPDATE tasks SET status = 'archived', " - " claim_lock = NULL, claim_expires = NULL, worker_pid = NULL " + " claim_lock = NULL, claim_expires = NULL, worker_pid = NULL, " + " worker_pgid = NULL, worker_identity = NULL, " + " worker_fence = NULL " "WHERE id = ? AND status != 'archived'", (task_id,), ) @@ -6707,7 +7368,9 @@ def schedule_task( SET status = 'scheduled', claim_lock = NULL, claim_expires= NULL, - worker_pid = NULL + worker_pid = NULL, + worker_pgid = NULL, + worker_identity = NULL WHERE id = ? AND status IN ('todo', 'ready', 'running', 'blocked') """ @@ -7014,80 +7677,421 @@ def _pid_alive(pid: Optional[int]) -> bool: return True +def _identity_probe_supported() -> bool: + """True when this platform can identify a process beyond its PID number. + + Linux (``/proc//stat`` starttime) and macOS (``ps -o lstart=``) can. + Where it is supported, a recorded PID with NO identity token is a legacy + row we must treat as unverifiable — never signal it, because the number + may since have been recycled. Where it is not supported (Windows), the + PID is all we ever had, so the pre-existing behaviour stands: that is the + documented boundary of the fail-closed rule. + """ + return sys.platform in ("linux", "darwin") + + +def _process_identity(pid: Optional[int]) -> Optional[str]: + """Return a stable identity token for ``pid``, or None if unknowable. + + A PID is a recycled number: on its own it cannot tell "our worker" from + "whatever the OS handed the number to next". Pairing it with the + process's start time makes it identifying for as long as we need it. We + record the token at spawn and re-derive it before doing anything + destructive (group signals) or binding (fences). + + Returns None when the process is gone or the platform gives us no cheap + probe (Windows). Callers must fail CLOSED on None: no group signal, no + fence held on an unverifiable process. + """ + if not pid or int(pid) <= 0: + return None + if sys.platform == "linux": + try: + with open(f"/proc/{int(pid)}/stat", "r", encoding="utf-8") as f: + fields = f.read().rsplit(") ", 1)[-1].split() + # Post-comm field 20 is starttime (clock ticks since boot). + return f"starttime:{fields[19]}" + except (OSError, ValueError, IndexError): + return None + if sys.platform == "darwin": + try: + proc = subprocess.run( + ["ps", "-o", "lstart=", "-p", str(int(pid))], + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True, encoding="utf-8", errors="replace", + timeout=5, + check=False, + ) + if proc.returncode != 0: + return None + started = (proc.stdout or "").strip() + return f"lstart:{started}" if started else None + except (OSError, subprocess.SubprocessError, TimeoutError): + return None + return None + + +def _identity_matches(pid: Optional[int], identity: Optional[str]) -> bool: + """True when ``pid`` is still the process ``identity`` was taken from. + + False when the identity was never recorded (legacy rows, Windows) or the + number has been recycled — both mean "we cannot claim this process is + ours", which every caller treats as fail-closed. + """ + if not identity: + return False + return _process_identity(pid) == identity + + +def _group_has_live_member(pgid: int) -> bool: + """True when the process group has at least one NON-zombie member. + + ``killpg(pgid, 0)`` succeeds against a group whose only remaining member + is an unreaped zombie, which would make a dead worker look like a live + writer forever. Same zombie caveat (and the same per-platform probes) as + :func:`_pid_alive`, applied group-wide. Probe failures answer "alive": + deferring a requeue for one tick is recoverable, spawning a second + writer beside a live worker is not. + """ + if sys.platform == "linux": + try: + for entry in os.listdir("/proc"): + if not entry.isdigit(): + continue + try: + with open(f"/proc/{entry}/stat", "r", encoding="utf-8") as f: + fields = f.read().rsplit(") ", 1)[-1].split() + # Post-comm fields: state, ppid, pgrp, ... + if int(fields[2]) == pgid and fields[0] not in ("Z", "X"): + return True + except (OSError, ValueError, IndexError): + continue + except OSError: + return True + return False + try: + proc = subprocess.run( + ["ps", "-A", "-o", "pgid=,stat="], + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True, encoding="utf-8", errors="replace", + timeout=5, + check=False, + ) + if proc.returncode != 0: + return True + except (OSError, subprocess.SubprocessError, TimeoutError): + return True + for line in (proc.stdout or "").splitlines(): + parts = line.split() + if len(parts) < 2: + continue + try: + if int(parts[0]) != pgid: + continue + except ValueError: + continue + if "Z" not in parts[1]: + return True + return False + + +def _process_group_alive(pgid: Optional[int]) -> bool: + """True when any process in ``pgid`` can still run on this host. + + ``killpg(pgid, 0)`` is the only cheap probe that sees the *children* a + worker forked: those reparent to PID 1 when the worker dies but keep the + process group (and keep writing to the task's workspace), so a PID-only + liveness check reports "gone" while real writers are still live. + """ + if not pgid or int(pgid) <= 0: + return False + killpg = getattr(os, "killpg", None) + if killpg is None: # Windows: no process groups to probe. + return False + try: + killpg(int(pgid), 0) + except ProcessLookupError: + return False + except PermissionError: + # The group exists but we may not signal it. That is also what a + # group whose only member is an unreaped zombie looks like on + # macOS, so this must NOT short-circuit to "alive" — fall through + # to the member scan, which distinguishes the two. + pass + except OSError: + return False + return _group_has_live_member(int(pgid)) + + +def _worker_leader_alive( + pid: Optional[int], identity: Optional[str] = None, +) -> bool: + """True while the worker process ITSELF is running (not just its group). + + Identity-gated: a live pid whose recorded identity no longer matches is + a recycled number, not our worker. A *missing* identity is not a pass + either where the platform could have produced one — an unverifiable pid + is treated as "not our worker", which routes the task onto the bounded + fence path instead of an unbounded hold on a number. + + That is the right answer for a decision made ABOUT a process we are only + observing. It is not the right answer for the process we are actively + killing: :func:`_terminate_reclaimed_worker` signals an identity-less + pid and therefore judges its survival on the bare pid, because a live + worker that fell through to a bounded fence would age out of it. + """ + if not _pid_alive(pid): + return False + if identity is not None: + return _identity_matches(pid, identity) + return not _identity_probe_supported() + + +def _worker_tree_alive( + pid: Optional[int], + pgid: Optional[int], + identity: Optional[str] = None, +) -> bool: + """True while the worker OR anything it forked can still write. + + When ``identity`` is recorded it gates the PID half: a live number whose + identity no longer matches is a recycled pid, not our worker. The group + half stays number-based (individual members carry no recorded identity), + which is why fences that rest on it alone are bounded in time. + """ + if _worker_leader_alive(pid, identity): + return True + return _process_group_alive(pgid) + + def _terminate_reclaimed_worker( pid: Optional[int], claim_lock: Optional[str], *, signal_fn=None, + pgid: Optional[int] = None, + killpg_fn=None, + identity: Optional[str] = None, ) -> dict[str, Any]: - """Best-effort host-local worker termination for reclaim paths.""" + """Best-effort host-local worker termination for reclaim paths. + + Signals the worker's whole **process group** — workers are spawned with + ``start_new_session=True``, so the group is the worker plus every tool + subprocess it forked — but ONLY while the leader's recorded ``identity`` + still matches the live process. PIDs and PGIDs are recycled numbers, and + a group signal is the widest blast radius we have. + + Without that proof the blast radius narrows to the bare PID, which is + the pre-existing behaviour and the only one that keeps the duplicate- + writer invariant. The two unproven cases are NOT the same: + + * **No recorded identity** (legacy row, or a row written before the + token landed): the PID is all we have, so we signal it. Declining + would leave a live worker to be carried by a fence — and a fence with + no identity token is bounded by ``WORKER_FENCE_MAX_SECONDS``, so the + worker would age out of its own fence and a second writer would claim + beside it. ``observed_identity`` reports the token of whatever is + still alive afterwards, so a caller that must fence rather than hold + (operator reclaim) can pin it instead of resting on the number. + * **Recorded identity that no longer matches** a live PID: the OS + recycled the number. Our worker is already gone, so we signal nothing + — killing here would kill a stranger. + + ``terminated`` is only True once nothing we are allowed to attribute to + this worker answers a liveness probe; ``still_alive`` is its complement + for callers deciding whether to fence, and ``leader_alive`` narrows that + to the worker process itself (the signal to HOLD the claim rather than + fence). All are host-local judgements: for a claim held by another host + we return without probing anything, since a local PID number says + nothing about a remote process. + """ import signal + pgid = int(pgid) if pgid else None info: dict[str, Any] = { "prev_pid": int(pid) if pid else None, + "prev_pgid": pgid, + "prev_identity": identity, "host_local": False, + "identity_verified": False, "termination_attempted": False, + "group_signaled": False, "terminated": False, "sigkill": False, + "still_alive": False, + "leader_alive": False, + "observed_identity": None, } if not pid or pid <= 0 or not claim_lock: return info host_prefix = f"{_claimer_id().split(':', 1)[0]}:" if not str(claim_lock).startswith(host_prefix): + # Another host's claim. Its pid/pgid are numbers in a namespace we + # cannot see; probing them locally would read some unrelated local + # process as "the worker" and fence the task on a collision that can + # never resolve. Report nothing and let the caller requeue. return info info["host_local"] = True + identity_ok = _identity_matches(pid, identity) + info["identity_verified"] = identity_ok + # A recorded identity that does NOT match is proof the number was + # recycled, and the only case where signalling is forbidden outright: + # blind-signalling it is how a stranger's process gets killed. With no + # identity recorded at all there is nothing to contradict — the PID is + # the only handle we have ever had, and the pre-existing behaviour of + # signalling it is what keeps a live worker from aging out of a bounded + # fence into a duplicate-writer state. + may_signal = ( + identity_ok or identity is None or not _identity_probe_supported() + ) + info["may_signal"] = may_signal + if identity and _pid_alive(pid) and not identity_ok: + # The number is live but it is NOT our worker any more — the OS + # recycled it. Our worker is therefore gone: nothing to signal, + # nothing to fence, and certainly nothing to kill. + info["terminated"] = True + return info + kill = signal_fn if signal_fn is not None else ( os.kill if hasattr(os, "kill") else None ) - if kill is None: + if killpg_fn is not None: + killpg = killpg_fn + elif signal_fn is not None: + # An injected ``signal_fn`` replaces OS signalling entirely (callers + # pass one precisely so nothing real gets killed). Sending the group + # a real signal behind that hook would be a nasty surprise, so the + # group channel is off and the pid is the unit of both signalling + # and liveness for this call. + killpg = None + else: + killpg = getattr(os, "killpg", None) + # Fail closed: no verified identity (legacy row, Windows, leader already + # exited) means no group signal. The fence still keeps the task + # nonclaimable while the group has live members, so children we decline + # to kill cannot produce a second writer. + group_enabled = bool(pgid) and killpg is not None and identity_ok + info["group_enabled"] = group_enabled + if kill is None or not may_signal: + info["still_alive"] = ( + _worker_tree_alive(pid, pgid) if pgid else _pid_alive(pid) + ) return info + def _leader_alive() -> bool: + """The worker process itself — not the group it left behind. + + With no recorded identity the bare PID is the answer: we just + signalled that number, so reporting it dead while it is visibly + alive would send the caller down the bounded-fence path and let the + survivor age out. ``_worker_leader_alive`` deliberately answers + "not ours" for an unverifiable pid — right for a fence decision it + did not signal, wrong for the process we are killing right here. + """ + if identity is None: + return _pid_alive(pid) + return _worker_leader_alive(pid, identity) + + def _alive() -> bool: + if _leader_alive(): + return True + return _process_group_alive(pgid) if pgid else False + + def _signal(sig) -> bool: + """Send ``sig`` to the group (when proven ours) and the pid.""" + delivered = False + if group_enabled: + try: + killpg(pgid, sig) + info["group_signaled"] = True + delivered = True + except ProcessLookupError: + pass + except OSError: + pass + try: + kill(int(pid), sig) + delivered = True + except ProcessLookupError: + pass + except OSError: + return delivered + return delivered + info["termination_attempted"] = True - try: - kill(int(pid), signal.SIGTERM) - except ProcessLookupError: - # Process is already gone — that's a successful termination, not a - # survival. Leaving terminated=False here would make the reclaim guard - # misread a dead worker as still-alive and defer forever. + if not _signal(signal.SIGTERM) and not _alive(): + # Nothing left to signal — already gone. That's a successful + # termination, not a survival: leaving terminated=False here would + # make the reclaim guard misread a dead worker as still-alive and + # defer forever. info["terminated"] = True return info - except OSError: - return info for _ in range(10): - if not _pid_alive(pid): + if not _alive(): info["terminated"] = True return info time.sleep(0.5) - if _pid_alive(pid): - try: - # signal.SIGKILL doesn't exist on Windows; fall back to SIGTERM - # (which maps to TerminateProcess via the stdlib shim). - _sigkill = getattr(signal, "SIGKILL", signal.SIGTERM) - kill(int(pid), _sigkill) - info["sigkill"] = True - except (ProcessLookupError, OSError): - return info - - info["terminated"] = not _pid_alive(pid) + if _alive(): + # signal.SIGKILL doesn't exist on Windows; fall back to SIGTERM + # (which maps to TerminateProcess via the stdlib shim). + _sigkill = getattr(signal, "SIGKILL", signal.SIGTERM) + _signal(_sigkill) + info["sigkill"] = True + # SIGKILL is delivered asynchronously: verify on a wall-clock + # deadline rather than a single probe, so a group that dies a few + # milliseconds later isn't misreported as a survivor (which would + # defer the requeue for a whole tick). + deadline = time.monotonic() + WORKER_TERMINATION_VERIFY_SECONDS + # Bounded on BOTH wall-clock and probe count: each probe may shell + # out to ``ps``, and a caller that stubs ``time.sleep`` (tests) would + # otherwise spin the deadline out in hundreds of process scans. + for _ in range(WORKER_TERMINATION_VERIFY_PROBES): + if not _alive() or time.monotonic() >= deadline: + break + time.sleep(0.05) + + info["leader_alive"] = _leader_alive() + info["still_alive"] = _alive() + info["terminated"] = not info["still_alive"] + if identity is None and info["leader_alive"]: + # Nothing was recorded at spawn, but the leader is alive NOW, so a + # token can be derived now. A caller that must fence instead of + # holding the claim (operator reclaim) pins this, turning a hold on + # a recyclable number into a provable one: unbounded while it + # matches, self-releasing the moment the pid is recycled. + info["observed_identity"] = _process_identity(pid) return info def _worker_survived_termination(termination: dict) -> bool: - """True when we tried to kill our own host-local worker and it is still alive. + """True when the worker PROCESS itself shrugged off our termination. Reclaiming in this state would release the claim and let the dispatcher spawn a second worker while the first is still running — the duplication - loop. Only host-local workers we actually signalled count: a non-local - claim lock or a no-op attempt (no ``os.kill`` available) must fall through - to the normal release path, since we cannot manage that worker anyway. + loop. Holding the claim is right here because the situation is expected + to resolve: the worker is throttled or wedged in a syscall, and the next + tick retries the kill. + + Deliberately NOT true when only the worker's *children* survive: the + leader is gone, so no later tick will ever kill anything, and holding a + claim for a worker that no longer exists just parks the task in + ``running`` forever. Those callers requeue and record a bounded fence + instead, which keeps the task nonclaimable while being honest about the + state. Only host-local workers we actually signalled count: a non-local + claim lock or a no-op attempt (no ``os.kill`` available) must fall + through to the normal release path, since we cannot manage that worker + anyway. """ return bool( termination.get("termination_attempted") and termination.get("host_local") + and termination.get("leader_alive") and not termination.get("terminated") ) @@ -7133,6 +8137,231 @@ def _defer_reclaim_for_live_worker( _append_event(conn, task_id, "reclaim_deferred", payload, run_id=run_id) +# --------------------------------------------------------------------------- +# Worker fence — a task is not claimable while its previous process group +# can still write. +# --------------------------------------------------------------------------- + +def _read_worker_fence( + conn: sqlite3.Connection, task_id: str, +) -> tuple[Optional[str], Optional[dict]]: + """Return ``(raw, parsed)`` for the recorded fence — raw is the CAS key. + + Anything that decides a fence is releasable does so against a snapshot. + The stored JSON text is that snapshot's version stamp: clearing keys off + it so a decision about one fence can never delete a different one. + """ + row = conn.execute( + "SELECT worker_fence FROM tasks WHERE id = ?", (task_id,), + ).fetchone() + if row is None or not row["worker_fence"]: + return None, None + raw = row["worker_fence"] + try: + fence = json.loads(raw) + except (ValueError, TypeError): + return raw, None + return raw, (fence if isinstance(fence, dict) else None) + + +def worker_fence(conn: sqlite3.Connection, task_id: str) -> Optional[dict]: + """Return the recorded fence for ``task_id``, or None when unfenced.""" + return _read_worker_fence(conn, task_id)[1] + + +def record_worker_fence( + conn: sqlite3.Connection, + task_id: str, + *, + pid: Optional[int], + pgid: Optional[int], + run_id: Optional[int], + claim_lock: Optional[str], + reason: str, + identity: Optional[str] = None, +) -> None: + """Mark ``task_id`` nonclaimable until the given worker group is gone. + + Recorded on the task row (not in memory) so the fence survives a gateway + restart: the incident that motivated it (``t_80a3542a``) had the + dispatcher claim a fresh run against a task whose previous worker — PID + 98725, reparented to PID 1 with live children — was still writing to the + same workspace. Carries the PID, the process group, the leader identity + token, and the run that owned them so the rejection is auditable and so + a recycled PID cannot impersonate the fenced worker. + + A fence is only ever meaningful on the host that recorded it, so the + fence pins ``host`` too and callers only record one for host-local + claims (see :func:`_fence_blocks_claim`). + """ + with write_txn(conn): + _write_worker_fence( + conn, task_id, pid=pid, pgid=pgid, run_id=run_id, + claim_lock=claim_lock, reason=reason, identity=identity, + ) + + +def _build_worker_fence( + *, + pid: Optional[int], + pgid: Optional[int], + run_id: Optional[int], + claim_lock: Optional[str], + reason: str, + identity: Optional[str] = None, +) -> dict: + """The fence payload. Split out so a caller that folds the write into + another statement (see ``reclaim_task``) builds the identical value.""" + return { + "pid": int(pid) if pid else None, + "pgid": int(pgid) if pgid else None, + "identity": identity, + "host": _claimer_id().split(":", 1)[0], + "run_id": int(run_id) if run_id else None, + "claim_lock": claim_lock, + "reason": reason, + "since": int(time.time()), + } + + +def _write_worker_fence( + conn: sqlite3.Connection, + task_id: str, + *, + pid: Optional[int], + pgid: Optional[int], + run_id: Optional[int], + claim_lock: Optional[str], + reason: str, + identity: Optional[str] = None, +) -> None: + """``record_worker_fence`` body for callers already inside a write txn.""" + fence = _build_worker_fence( + pid=pid, pgid=pgid, run_id=run_id, claim_lock=claim_lock, + reason=reason, identity=identity, + ) + conn.execute( + "UPDATE tasks SET worker_fence = ? WHERE id = ?", + (json.dumps(fence, ensure_ascii=False), task_id), + ) + _append_event(conn, task_id, "worker_fenced", fence) + + +def clear_worker_fence( + conn: sqlite3.Connection, + task_id: str, + *, + expected: Optional[str] = None, +) -> bool: + """Drop the fence (worker confirmed gone, or a new worker took over). + + ``expected`` is the exact serialized fence the caller evaluated. Pass it + from any path that decided "this fence may go" against a snapshot: if a + reaper recorded a DIFFERENT fence in the meantime — a live worker this + caller never looked at — the CAS matches nothing and the newer fence + survives. Omit it only where the intent is unconditional ("whatever is + fencing this task, an operator/new worker has superseded it"). + + Returns True when a fence was actually cleared. + """ + if expected is None: + cur = conn.execute( + "UPDATE tasks SET worker_fence = NULL " + "WHERE id = ? AND worker_fence IS NOT NULL", + (task_id,), + ) + else: + cur = conn.execute( + "UPDATE tasks SET worker_fence = NULL " + "WHERE id = ? AND worker_fence = ?", + (task_id, expected), + ) + return cur.rowcount == 1 + + +def _fence_release_reason(fence: dict, now: int) -> Optional[str]: + """Why this fence no longer blocks a claim, or None while it still does. + + A fence must fail open in every case where it can no longer be trusted + to describe a live writer, because a fence that can never resolve is a + task stranded with no automatic exit: + + * ``foreign_host`` — recorded by (or for) another host. Local PID/PGID + numbers say nothing about a remote process, and we would never observe + the remote worker exiting, so we must not hold on one. + * ``worker_identity_changed`` — the PID is live but is no longer the + process we fenced. The OS recycled the number; our worker is gone. + * ``worker_group_gone`` — nothing answers: the normal happy exit. + * ``fence_expired`` — the leader is unverifiable and only the process + GROUP is holding the fence. That is the one case we cannot prove + (members carry no identity token and a pgid can be recycled too), so + it is bounded by ``WORKER_FENCE_MAX_SECONDS``. A fence whose leader is + verifiably alive never expires. + """ + if fence.get("host") and fence["host"] != _claimer_id().split(":", 1)[0]: + return "foreign_host" + pid, pgid = fence.get("pid"), fence.get("pgid") + identity = fence.get("identity") + if identity is not None: + if _pid_alive(pid): + if _identity_matches(pid, identity): + # Provably the worker we fenced, still running. This is the + # only evidence strong enough for an unbounded hold. + return None + return "worker_identity_changed" + elif _pid_alive(pid): + # No identity token: a live PID is *evidence*, not proof — it may be + # our worker or whatever inherited its number. Hold on it, but let + # the bound below apply, or a recycled pid strands the task forever. + return _fence_expiry_reason(fence, now) + if not _process_group_alive(pgid): + return "worker_group_gone" + # The group is alive but the leader is not verifiable (gone, or never + # identified). Members carry no identity of their own and a pgid can be + # recycled too, so this evidence is bounded in time. + return _fence_expiry_reason(fence, now) + + +def _fence_expiry_reason(fence: dict, now: int) -> Optional[str]: + """``"fence_expired"`` once a weakly-evidenced hold outlives its bound.""" + since = fence.get("since") + if isinstance(since, int) and now - since > WORKER_FENCE_MAX_SECONDS: + return "fence_expired" + return None + + +def _fence_blocks_claim( + conn: sqlite3.Connection, task_id: str, +) -> Optional[dict]: + """Return the fence when it still blocks a claim, else clear it. + + Called at the claim gate — the single choke point every spawn path goes + through — so no requeue path can hand a task to a second worker while the + first process group is alive, regardless of which code path (or which + gateway process) requeued it. + """ + raw, fence = _read_worker_fence(conn, task_id) + if fence is None: + return None + release = _fence_release_reason(fence, int(time.time())) + if release is None: + return fence + kind = ( + "worker_fence_expired" if release == "fence_expired" + else "worker_fence_cleared" + ) + with write_txn(conn): + # CAS on the fence we evaluated: a reaper may have replaced it while + # we were probing the OS, and that newer fence describes a worker we + # know nothing about. + if not clear_worker_fence(conn, task_id, expected=raw): + return worker_fence(conn, task_id) + _append_event( + conn, task_id, kind, {**fence, "cleared_reason": release}, + ) + return None + + def heartbeat_worker( conn: sqlite3.Connection, task_id: str, @@ -7188,28 +8417,42 @@ def enforce_max_runtime( conn: sqlite3.Connection, *, signal_fn=None, + killpg_fn=None, ) -> list[str]: """Terminate workers whose per-task ``max_runtime_seconds`` has elapsed. - Sends SIGTERM, waits a short grace window, then SIGKILL. Emits a - ``timed_out`` event and drops the task back to ``ready`` so the next - dispatcher tick re-spawns it — unless the spawn-failure circuit - breaker has already given up, in which case the task stays blocked - where ``_record_spawn_failure`` parked it. + Signals the worker's whole process group (SIGTERM, grace window, then + SIGKILL), and only once nothing in that group answers a liveness probe + does it emit ``timed_out`` and drop the task back to ``ready`` for the + next dispatcher tick — unless the circuit breaker has already given up, + in which case the task stays blocked where ``_record_task_failure`` + parked it. + + **A blown budget is not permission to requeue.** In incident + ``t_80a3542a`` the runtime cap fired on run 141, the worker (PID 98725, + reparented to PID 1, with live Claude children) ignored the signal, and + the task was flipped to ``ready`` anyway: the dispatcher claimed run 152 + and spawned PID 57286 against the same task and workspace. Two writers. + When the group survives termination the task stays ``running`` with its + run open, the claim is held via ``reclaim_deferred``, and the next tick + retries the kill — the same self-correcting hold ``release_stale_claims`` + already uses. When we requeue a worker we could *not* confirm dead (a + non-host-local claim, no signalling primitive), a durable + ``worker_fence`` keeps the task nonclaimable until the group is gone. Runs host-local: only tasks claimed by this host are candidates - (same reasoning as ``detect_crashed_workers``). ``signal_fn`` is a - test hook; defaults to ``os.kill`` on POSIX. + (same reasoning as ``detect_crashed_workers``). ``signal_fn`` / + ``killpg_fn`` are test hooks; they default to ``os.kill`` / + ``os.killpg`` on POSIX. """ - import signal timed_out: list[str] = [] now = int(time.time()) host_prefix = f"{_claimer_id().split(':', 1)[0]}:" rows = conn.execute( - "SELECT t.id, t.worker_pid, " + "SELECT t.id, t.worker_pid, t.worker_pgid, t.worker_identity, " " COALESCE(r.started_at, t.started_at) AS active_started_at, " - " t.max_runtime_seconds, t.claim_lock " + " t.max_runtime_seconds, t.claim_lock, t.current_run_id " "FROM tasks t " "LEFT JOIN task_runs r ON r.id = t.current_run_id " "WHERE t.status = 'running' AND t.max_runtime_seconds IS NOT NULL " @@ -7228,38 +8471,46 @@ def enforce_max_runtime( continue pid = int(row["worker_pid"]) + pgid = row["worker_pgid"] tid = row["id"] - # SIGTERM then SIGKILL. Keep it simple: 5 s grace. Workers that - # want a cleaner shutdown can install their own SIGTERM handler - # before the grace expires. - killed = False - kill = signal_fn if signal_fn is not None else ( - os.kill if hasattr(os, "kill") else None - ) - if kill is not None: - try: - kill(pid, signal.SIGTERM) - except (ProcessLookupError, OSError): - pass - # Short polling wait — no time.sleep on the write txn. - for _ in range(10): - if not _pid_alive(pid): - break - time.sleep(0.5) - if _pid_alive(pid): - try: - # signal.SIGKILL doesn't exist on Windows. - _sigkill = getattr(signal, "SIGKILL", signal.SIGTERM) - kill(pid, _sigkill) - killed = True - except (ProcessLookupError, OSError): - pass + termination = _terminate_reclaimed_worker( + pid, row["claim_lock"], + signal_fn=signal_fn, + pgid=pgid, + killpg_fn=killpg_fn, + identity=row["worker_identity"], + ) + if _worker_survived_termination(termination): + # Still writable → hold the claim. No requeue, no run + # finalization, no failure counted: the attempt is not over. + _defer_reclaim_for_live_worker( + conn, tid, row["claim_lock"], now, termination, + reason="max_runtime_worker_alive", + ) + continue + killed = bool(termination.get("sigkill")) + if termination.get("still_alive"): + # We are requeuing a worker we could not confirm dead: its + # children still hold the process group, or we had no signalling + # primitive at all. Never the leader itself — a live leader is + # held by the branch above, not fenced. + # ``still_alive`` is only ever set for host-local claims. Fence + # the task so no replacement claim lands until the group is gone. + record_worker_fence( + conn, tid, + pid=pid, + pgid=pgid, + run_id=row["current_run_id"], + claim_lock=row["claim_lock"], + reason="max_runtime_unconfirmed_termination", + identity=row["worker_identity"], + ) with write_txn(conn): cur = conn.execute( "UPDATE tasks SET status = 'ready', claim_lock = NULL, " - "claim_expires = NULL, worker_pid = NULL, " - "last_heartbeat_at = NULL " + "claim_expires = NULL, worker_pid = NULL, worker_pgid = NULL, " + "worker_identity = NULL, last_heartbeat_at = NULL " "WHERE id = ? AND status = 'running' " " AND worker_pid = ? AND claim_lock IS ?", (tid, pid, row["claim_lock"]), @@ -7267,6 +8518,7 @@ def enforce_max_runtime( if cur.rowcount == 1: payload = { "pid": pid, + "pgid": int(pgid) if pgid else None, "elapsed_seconds": int(elapsed), "limit_seconds": int(row["max_runtime_seconds"]), "sigkill": killed, @@ -7341,7 +8593,8 @@ def detect_stale_running( reclaimed: list[str] = [] rows = conn.execute( - "SELECT t.id, t.worker_pid, t.last_heartbeat_at, t.claim_lock, " + "SELECT t.id, t.worker_pid, t.worker_pgid, t.worker_identity, " + " t.last_heartbeat_at, t.claim_lock, t.current_run_id, " " COALESCE(r.started_at, t.started_at) AS active_started_at " "FROM tasks t " "LEFT JOIN task_runs r ON r.id = t.current_run_id " @@ -7366,9 +8619,10 @@ def detect_stale_running( tid = row["id"] lock = row["claim_lock"] or "" - # Terminate the worker if it's still host-local. + # Terminate the worker (whole process group) if it's still host-local. termination = _terminate_reclaimed_worker( pid, lock, signal_fn=signal_fn, + pgid=row["worker_pgid"], identity=row["worker_identity"], ) # Never release a claim while our own worker is still alive: that would @@ -7379,12 +8633,27 @@ def detect_stale_running( reason="heartbeat_stale_worker_alive", ) continue + if termination.get("still_alive"): + # Same contract as the TTL and runtime-cap reclaims: a silent + # heartbeat does not mean the worker's children stopped writing. + # They keep the process group after the leader exits, so fence + # the task until that group is empty rather than letting the + # next tick spawn a second writer into the same workspace. + record_worker_fence( + conn, tid, + pid=pid, + pgid=row["worker_pgid"], + run_id=row["current_run_id"], + claim_lock=lock, + reason="heartbeat_stale_unconfirmed_termination", + identity=row["worker_identity"], + ) with write_txn(conn): cur = conn.execute( "UPDATE tasks SET status = 'ready', claim_lock = NULL, " - "claim_expires = NULL, worker_pid = NULL, " - "last_heartbeat_at = NULL " + "claim_expires = NULL, worker_pid = NULL, worker_pgid = NULL, " + "worker_identity = NULL, last_heartbeat_at = NULL " "WHERE id = ? AND status = 'running' " " AND claim_lock IS ?", (tid, row["claim_lock"]), @@ -7553,26 +8822,54 @@ def detect_crashed_workers(conn: sqlite3.Connection) -> list[str]: # counter (see the post-txn loop below). crash_details: list[tuple[str, int, str, bool, str]] = [] # (task_id, pid, claimer, protocol_violation, error_text) - with write_txn(conn): - rows = conn.execute( - "SELECT id, worker_pid, claim_lock, started_at FROM tasks " - "WHERE status = 'running' AND worker_pid IS NOT NULL" - ).fetchall() - host_prefix = f"{_claimer_id().split(':', 1)[0]}:" - for row in rows: - # Only check liveness for claims owned by this host. - lock = row["claim_lock"] or "" - if not lock.startswith(host_prefix): + # Probe the OS BEFORE taking the board's write lock. ``_pid_alive`` and + # ``_process_group_alive`` read /proc or shell out to ``ps``; doing that + # inside BEGIN IMMEDIATE stalls every other writer on the board — workers + # completing, heartbeats, sibling dispatch ticks — for the length of a + # subprocess call. Everything decided here is re-checked against the row + # under the lock below, so a worker that dies (or is replaced) in between + # cannot be acted on with stale evidence. + candidates: list[tuple[sqlite3.Row, bool]] = [] + host_prefix = f"{_claimer_id().split(':', 1)[0]}:" + for row in conn.execute( + "SELECT id, worker_pid, worker_pgid, worker_identity, claim_lock, " + " started_at, current_run_id FROM tasks " + "WHERE status = 'running' AND worker_pid IS NOT NULL" + ).fetchall(): + # Only check liveness for claims owned by this host. + lock = row["claim_lock"] or "" + if not lock.startswith(host_prefix): + continue + # Skip liveness check inside the launch-window grace period + # so a freshly-spawned worker isn't reclaimed before its PID + # is visible on /proc. + started_at = row["started_at"] if "started_at" in row.keys() else None + if started_at is not None: + grace = _resolve_crash_grace_seconds() + if time.time() - started_at < grace: continue - # Skip liveness check inside the launch-window grace period - # so a freshly-spawned worker isn't reclaimed before its PID - # is visible on /proc. - started_at = row["started_at"] if "started_at" in row.keys() else None - if started_at is not None: - grace = _resolve_crash_grace_seconds() - if time.time() - started_at < grace: - continue - if _pid_alive(row["worker_pid"]): + # Identity-aware: a live PID that is no longer OUR worker (the number + # was recycled) must not suppress crash detection, or the task sits + # in ``running`` forever with nothing behind it. + if _worker_leader_alive(row["worker_pid"], row["worker_identity"]): + continue + candidates.append((row, _process_group_alive(row["worker_pgid"]))) + + with write_txn(conn): + for row, group_alive in candidates: + # Re-read under the lock: the row may have moved on while we were + # probing (worker completed, task was reclaimed, a new worker was + # spawned). Only act when it is still the same claim and worker. + fresh = conn.execute( + "SELECT status, worker_pid, claim_lock FROM tasks WHERE id = ?", + (row["id"],), + ).fetchone() + if ( + fresh is None + or fresh["status"] != "running" + or fresh["worker_pid"] != row["worker_pid"] + or fresh["claim_lock"] != row["claim_lock"] + ): continue pid = int(row["worker_pid"]) @@ -7639,9 +8936,25 @@ def detect_crashed_workers(conn: sqlite3.Connection) -> list[str]: event_payload["exit_kind"] = kind event_payload["exit_code"] = code + # The worker process is gone, but the children it forked are + # not: they reparent to PID 1 and keep the worker's process + # group — and keep writing to the task's workspace. Requeuing + # in that state is how a "crashed" task ends up with two live + # writers, so fence the task until the group is empty. + if group_alive: + _write_worker_fence( + conn, row["id"], + pid=pid, + pgid=row["worker_pgid"], + run_id=row["current_run_id"], + claim_lock=row["claim_lock"], + reason="crashed_worker_children_alive", + identity=row["worker_identity"], + ) cur = conn.execute( "UPDATE tasks SET status = 'ready', claim_lock = NULL, " - "claim_expires = NULL, worker_pid = NULL " + "claim_expires = NULL, worker_pid = NULL, worker_pgid = NULL, " + "worker_identity = NULL " "WHERE id = ? AND status = 'running' " " AND worker_pid = ? AND claim_lock IS ?", (row["id"], pid, row["claim_lock"]), @@ -7785,6 +9098,29 @@ def detect_crashed_workers(conn: sqlite3.Connection) -> list[str]: return crashed +def _claim_source_status(conn: sqlite3.Connection, task_id: str) -> str: + """Which column the task's current run was claimed out of. + + ``"review"`` when ``claim_review_task`` made the claim (it stamps + ``source_status`` on the ``claimed`` event), ``"ready"`` otherwise — + including for every pre-existing event that predates the stamp. Read + from the event rather than threaded through the callers so a requeue + lands in the right column no matter which failure path reached it. + """ + row = conn.execute( + "SELECT payload FROM task_events " + "WHERE task_id = ? AND kind = 'claimed' ORDER BY id DESC LIMIT 1", + (task_id,), + ).fetchone() + if not row or not row["payload"]: + return "ready" + try: + source = json.loads(row["payload"]).get("source_status") + except (ValueError, TypeError): + return "ready" + return "review" if source == "review" else "ready" + + def _record_task_failure( conn: sqlite3.Connection, task_id: str, @@ -7812,8 +9148,10 @@ def _record_task_failure( * ``release_claim=True, end_run=True`` — spawn-failure path. Caller has a running task with an open run; this transitions - it back to ``ready`` (or ``blocked`` when the breaker trips), - releases the claim, and closes the run with ``outcome=``. + it back to the column the claim came from — ``ready``, or + ``review`` for a claim made by :func:`claim_review_task` (or + ``blocked`` when the breaker trips) — releases the claim, and + closes the run with ``outcome=``. * ``release_claim=False, end_run=False`` — timeout/crash path. Caller has ALREADY flipped the task to ``ready`` and closed the @@ -7865,26 +9203,41 @@ def _record_task_failure( limit_source = "dispatcher" if force_trip or failures >= effective_limit: - # Trip the breaker. + # Trip the breaker. The limit we decided against is persisted so + # no later promotion caller can resolve a laxer one and hand the + # task back to the dispatcher (incident ``t_27263082``) — but the + # stamp rides the SAME status-guarded UPDATE as the transition. + # If the worker completed the task while we were accounting this + # failure, that UPDATE matches nothing and the finished task must + # not be left carrying a binding give-up decision either. if release_claim: # Spawn path: still running, also clear claim state. - conn.execute( + tripped_rows = conn.execute( "UPDATE tasks SET status = 'blocked', claim_lock = NULL, " "claim_expires = NULL, worker_pid = NULL, " - "consecutive_failures = ?, last_failure_error = ? " + "worker_pgid = NULL, worker_identity = NULL, " + "consecutive_failures = ?, last_failure_error = ?, " + "breaker_limit = ? " "WHERE id = ? AND status IN ('running', 'ready')", - (failures, error[:500], task_id), - ) + (failures, error[:500], int(effective_limit), task_id), + ).rowcount else: # Timeout/crash path: task is already at ``ready`` # with claim cleared; just flip to blocked + update # counter fields. - conn.execute( + tripped_rows = conn.execute( "UPDATE tasks SET status = 'blocked', " - "consecutive_failures = ?, last_failure_error = ? " + "consecutive_failures = ?, last_failure_error = ?, " + "breaker_limit = ? " "WHERE id = ? AND status IN ('ready', 'running')", - (failures, error[:500], task_id), - ) + (failures, error[:500], int(effective_limit), task_id), + ).rowcount + if tripped_rows != 1: + # The task reached a terminal state under us (completed, + # archived, deleted). Nothing was transitioned and nothing + # was stamped; do not emit a give-up for a task that isn't + # blocked. + return False run_id = None if end_run: # Only the spawn path has an open run to close. @@ -7915,22 +9268,39 @@ def _record_task_failure( else: # Below threshold. if release_claim: - # Spawn path: transition running → ready + clear claim. - conn.execute( - "UPDATE tasks SET status = 'ready', claim_lock = NULL, " + # Spawn path: transition running → back to the column this + # run was claimed out of, and clear the claim. A review claim + # must land in ``review``, not ``ready``: the dispatcher + # force-loads the ``sdlc-review`` skill for review claims, so + # requeueing to ``ready`` hands the card to the next tick as + # ordinary work and spawns a plain implementation worker + # against a task whose PR is already open. + counted_rows = conn.execute( + "UPDATE tasks SET status = ?, claim_lock = NULL, " "claim_expires = NULL, worker_pid = NULL, " + "worker_pgid = NULL, worker_identity = NULL, " "consecutive_failures = ?, last_failure_error = ? " "WHERE id = ? AND status = 'running'", - (failures, error[:500], task_id), - ) + ( + _claim_source_status(conn, task_id), + failures, error[:500], task_id, + ), + ).rowcount else: - # Timeout/crash path: task is already at ``ready`` via - # its own UPDATE. Just bookkeep the counter + last error. - conn.execute( + # Timeout/crash path: task is already at ``ready`` via its + # own UPDATE. Bookkeep the counter + last error — but under + # the same status guard as the trip branch above, or a task + # the worker completed while we were accounting this failure + # comes out of it ``done`` with a failure counted against it. + counted_rows = conn.execute( "UPDATE tasks SET consecutive_failures = ?, " - "last_failure_error = ? WHERE id = ?", + "last_failure_error = ? " + "WHERE id = ? AND status IN ('ready', 'running')", (failures, error[:500], task_id), - ) + ).rowcount + if counted_rows != 1: + # Terminal race: nothing to account against. + return False if end_run: # Spawn path: close the open run with outcome. run_id = _end_run( @@ -7966,28 +9336,85 @@ def _record_spawn_failure( ) -def _set_worker_pid(conn: sqlite3.Connection, task_id: str, pid: int) -> None: - """Record the spawned child's pid + emit a ``spawned`` event. +def _set_worker_pid( + conn: sqlite3.Connection, + task_id: str, + pid: int, + *, + pgid: Optional[int] = None, +) -> None: + """Record the spawned child's pid + process group, emit ``spawned``. The event's payload carries the pid so a human reading ``hermes kanban tail`` can correlate log lines with OS-level traces without opening the drawer. + + ``pgid`` defaults to the child's own process group. Workers are spawned + with ``start_new_session=True``, so that group is the whole worker tree + (agent + every tool subprocess). Termination and liveness checks target + the group, because the children outlive the worker and keep writing. """ + if pgid is None: + getpgid = getattr(os, "getpgid", None) + if getpgid is not None: + try: + pgid = getpgid(int(pid)) + except (ProcessLookupError, OSError): + # The process is already gone, or the platform will not tell + # us. Record nothing: synthesizing ``pgid = pid`` would sail + # through the leadership check below on no evidence at all, + # which is precisely what that check exists to prevent. + pgid = None + # Only persist a group id the worker LEADS. ``_default_spawn`` uses + # start_new_session=True, so a real worker is its own group leader and + # pgid == pid. Any other value is a group the worker merely joined — + # in practice the gateway's own — and signalling that would take down + # the dispatcher and every sibling worker with it. Store nothing and + # degrade to pid-only safety instead. + if pgid is not None and int(pgid) != int(pid): + _log.warning( + "kanban: worker pid %s is not its own process-group leader " + "(pgid=%s); not recording a group id for it", + pid, pgid, + ) + pgid = None + # Identity token for the leader, captured as close to the spawn as we + # can get it. Everything destructive (group signals) and everything + # binding (fences) is gated on this still matching later, so a recycled + # PID can neither be killed by us nor hold a task hostage. + identity = _process_identity(pid) with write_txn(conn): conn.execute( - "UPDATE tasks SET worker_pid = ? WHERE id = ?", - (int(pid), task_id), + "UPDATE tasks SET worker_pid = ?, worker_pgid = ?, " + "worker_identity = ? WHERE id = ?", + (int(pid), int(pgid) if pgid else None, identity, task_id), ) + # A live worker of our own supersedes any fence recorded for a + # previous one — we just proved the task was claimable. + clear_worker_fence(conn, task_id) run_id = _current_run_id(conn, task_id) if run_id is not None: conn.execute( "UPDATE task_runs SET worker_pid = ? WHERE id = ?", (int(pid), run_id), ) - _append_event(conn, task_id, "spawned", {"pid": int(pid)}, run_id=run_id) + _append_event( + conn, task_id, "spawned", + { + "pid": int(pid), + "pgid": int(pgid) if pgid else None, + "identity": identity, + }, + run_id=run_id, + ) -def _clear_failure_counter(conn: sqlite3.Connection, task_id: str) -> None: +def _clear_failure_counter( + conn: sqlite3.Connection, + task_id: str, + *, + keep_breaker_limit: bool = False, +) -> None: """Reset the unified consecutive-failures counter. Called from ``complete_task`` on successful completion — a fresh @@ -7996,11 +9423,16 @@ def _clear_failure_counter(conn: sqlite3.Connection, task_id: str) -> None: a successful spawn proves the worker could start but says nothing about whether the run will succeed, so we need to let timeouts and crashes accumulate across spawn boundaries. + + ``keep_breaker_limit`` preserves the recorded give-up decision while + still zeroing the counter. ``reclaim_task`` uses it for a task that is + staying blocked: the operator freed the worker, not the task. """ + breaker_sql = "" if keep_breaker_limit else ", breaker_limit = NULL" with write_txn(conn): conn.execute( "UPDATE tasks SET consecutive_failures = 0, " - "last_failure_error = NULL WHERE id = ?", + "last_failure_error = NULL" + breaker_sql + " WHERE id = ?", (task_id,), ) diff --git a/hermes_cli/kanban_decompose.py b/hermes_cli/kanban_decompose.py index d6c248c658a6d..16e61d398217b 100644 --- a/hermes_cli/kanban_decompose.py +++ b/hermes_cli/kanban_decompose.py @@ -283,12 +283,22 @@ def decompose_task( """ with kb.connect_closing() as conn: task = kb.get_task(conn, task_id) + hold = ( + kb.terminal_hold_reason(conn, task_id) if task is not None else None + ) if task is None: return DecomposeOutcome(task_id, False, "unknown task id") if task.status != "triage": return DecomposeOutcome( task_id, False, f"task is not in triage (status={task.status!r})" ) + if hold: + # A worker blocked this, or the breaker gave up on it; it needs an + # operator decision, not another LLM fan-out. ``hermes kanban + # unblock`` (or ``promote``) resumes it. + return DecomposeOutcome( + task_id, False, f"task is on a terminal hold ({hold}) — unblock it first", + ) cfg = _load_config() orchestrator = _resolve_orchestrator_profile(cfg) @@ -457,7 +467,15 @@ def decompose_task( def list_triage_ids(*, tenant: Optional[str] = None) -> list[str]: - """Return task ids currently in the triage column.""" + """Return task ids currently in the triage column that are safe to + auto-decompose. + + Rows on a terminal hold are excluded — an unblock-loop escalation, a + worker's ``kanban_block``, or a recorded breaker trip. All three are a + human hold that only ``kanban unblock`` / ``promote`` clears. Before + this filter the gateway's auto-decompose tick picked such a card up and + silently promoted it back into the work pool. + """ with kb.connect_closing() as conn: rows = kb.list_tasks( conn, @@ -465,4 +483,7 @@ def list_triage_ids(*, tenant: Optional[str] = None) -> list[str]: tenant=tenant, limit=1000, ) - return [row.id for row in rows] + return [ + row.id for row in rows + if not kb.terminal_hold_reason(conn, row.id) + ] diff --git a/tests/agent/test_kanban_review_dag_guidance.py b/tests/agent/test_kanban_review_dag_guidance.py new file mode 100644 index 0000000000000..04839b90cd243 --- /dev/null +++ b/tests/agent/test_kanban_review_dag_guidance.py @@ -0,0 +1,122 @@ +"""Prompt contract: Kanban workers run a continuously automated review DAG. + +Policy (operator-mandated): the board must keep moving without a human in the +loop. A coding worker no longer parks its own card in ``blocked`` with a +``review-required:`` reason and waits for a person — it creates a *ready* +review card for a real installed reviewer profile and completes its own card. +Review outcomes fan out as more cards (remediation → fresh review), so the +dependency graph is expressed with ``parents``/DAG edges rather than blocked +state. + +``blocked`` keeps its narrow, genuine meaning (irretrievable human input, hard +capability/access wall, truly transient failure after retries) — these tests +must not be "fixed" by deleting the block guidance, only by removing the +*mandatory review block* workflow. +""" + +from agent.prompt_builder import KANBAN_GUIDANCE + + +def _g() -> str: + return KANBAN_GUIDANCE.lower() + + +# --- the old human-gated review block is gone ------------------------------- + + +def test_no_mandatory_review_required_block_instruction(): + """The `kanban_block(reason="review-required: ...")` handoff is retired.""" + assert "review-required" not in _g() + + +def test_completion_step_does_not_route_code_changes_into_blocked(): + guidance = _g() + # The old text told coding workers to "end with kanban_block(...)". + assert "end with `kanban_block" not in guidance + # ...and justified it as more honest than completing. Both must be gone. + assert "auto-completing" not in guidance + + +# --- the automated review DAG is present ------------------------------------ + + +def test_reviewable_code_creates_a_ready_review_card(): + guidance = _g() + assert "review card" in guidance + assert "ready" in guidance + # Assigned to a real installed reviewer profile, normally pr-reviewer. + assert "pr-reviewer" in guidance + + +def test_review_card_carries_exact_evidence(): + guidance = _g() + for token in ("workspace", "repo", "base", "head", "acceptance"): + assert token in guidance, token + + +def test_implementation_card_completes_and_lists_created_cards(): + guidance = _g() + assert "created_cards" in guidance + # Completion of the implementation card is explicit, not implied. + assert "kanban_complete" in guidance + + +def test_reviewer_pass_completes_and_block_creates_remediation(): + guidance = _g() + assert "pass" in guidance + assert "remediation" in guidance + # BLOCK verdict routes back to the original implementation profile. + assert "original implementation profile" in guidance + + +def test_remediation_creates_a_fresh_exact_head_review_card(): + guidance = _g() + assert "fresh" in guidance and "exact-head" in guidance + + +def test_dependencies_use_parents_dag_not_blocked(): + guidance = _g() + assert "parents=" in guidance + assert "not `blocked`" in guidance or "not blocked" in guidance + + +# --- blocked stays narrow --------------------------------------------------- + + +def test_blocked_is_reserved_for_three_named_conditions(): + guidance = _g() + assert "irretrievable human input" in guidance + assert "capability" in guidance and "access wall" in guidance + assert "transient failure after retries" in guidance + + +def test_blocked_anti_uses_are_enumerated(): + guidance = _g() + for anti in ( + "dispatcher fence", + "status update", + "review queue", + "ordinary dependency wait", + "substitute for child tasks", + ): + assert anti in guidance, anti + + +def test_missing_reviewer_profile_surfaces_needs_input_not_an_invented_assignee(): + guidance = _g() + assert "needs_input" in guidance + assert "invent" in guidance + + +# --- preserved invariants --------------------------------------------------- + + +def test_unknown_assignees_must_still_be_discovered_and_validated(): + guidance = _g() + assert "hermes profile list" in guidance + assert "silently" in guidance + + +def test_genuine_block_path_is_retained(): + """Do not weaken true safety blocks: kanban_block still exists.""" + assert "kanban_block" in _g() diff --git a/tests/gateway/test_kanban_notifier.py b/tests/gateway/test_kanban_notifier.py index 7400efd7263d9..977721eb9aa2e 100644 --- a/tests/gateway/test_kanban_notifier.py +++ b/tests/gateway/test_kanban_notifier.py @@ -469,16 +469,15 @@ def bad_first(conn, task_id=None, **kwargs): assert tid_good in adapter.sent[0]["text"] -def test_notifier_delivers_block_loop_detected_triage_ping(tmp_path, monkeypatch): - """A `block_loop_detected` event must reach the subscriber as a triage ping. - - Regression for the silent-triage gap (PR #62712): kanban_db routes a task - to `triage` after BLOCK_RECURRENCE_LIMIT re-blocks for the same cause and - emits ONLY a `block_loop_detected` event — no `blocked`/`status` event. - Before `block_loop_detected` joined TERMINAL_KINDS with its own message - branch, that one transition (the whole point of which is to force human - attention) produced zero notification and the task stalled in triage - silently. +def test_notifier_delivers_block_loop_detected_stuck_ping(tmp_path, monkeypatch): + """A `block_loop_detected` event must reach the subscriber as a stuck-block ping. + + Regression for the silent-escalation gap (PR #62712): kanban_db escalates a + task to a sticky block after BLOCK_RECURRENCE_LIMIT re-blocks for the same + cause and emits ONLY a `block_loop_detected` event — no `blocked`/`status` + event. Before `block_loop_detected` joined TERMINAL_KINDS with its own + message branch, that one transition (the whole point of which is to force + human attention) produced zero notification and the task stalled silently. """ db_path = tmp_path / "block-loop.db" monkeypatch.setenv("HERMES_KANBAN_DB", str(db_path)) @@ -503,7 +502,8 @@ def test_notifier_delivers_block_loop_detected_triage_ping(tmp_path, monkeypatch assert len(adapter.sent) == 1, "block_loop_detected must produce a notification" text = adapter.sent[0]["text"] - assert "TRIAGE" in text + assert "STUCK BLOCKED" in text + assert "unblock to resume" in text assert tid in text assert "needs credentials" in text # Cursor advanced: the event is claimed and not re-delivered. diff --git a/tests/hermes_cli/test_kanban_block_kinds.py b/tests/hermes_cli/test_kanban_block_kinds.py index d562d436db676..05c69a02cf55e 100644 --- a/tests/hermes_cli/test_kanban_block_kinds.py +++ b/tests/hermes_cli/test_kanban_block_kinds.py @@ -9,7 +9,9 @@ never enter the human ``blocked`` bucket a cron would keep unblocking. * ``needs_input`` / ``capability`` / un-typed blocks land in ``blocked``; each same-cause re-block after an unblock increments ``block_recurrences``, - and at ``BLOCK_RECURRENCE_LIMIT`` the task routes to ``triage`` for a human. + and at ``BLOCK_RECURRENCE_LIMIT`` the block becomes sticky (``blocked`` + + ``block_loop_detected``) so only an explicit unblock resumes it. See + ``test_kanban_block_loop_sticky.py`` for the escalation invariants. * ``unblock_task`` deliberately does NOT reset ``block_recurrences`` (the amnesia that let the loop run unbounded). * A successful ``complete_task`` resets the loop memory. diff --git a/tests/hermes_cli/test_kanban_block_loop_sticky.py b/tests/hermes_cli/test_kanban_block_loop_sticky.py new file mode 100644 index 0000000000000..245773eec8922 --- /dev/null +++ b/tests/hermes_cli/test_kanban_block_loop_sticky.py @@ -0,0 +1,356 @@ +"""Regression: a block-loop escalation must not be resurrected by the +dispatcher's auto-decomposer. + +Live defect (board default, event 2955 / run 233, task ``t_bdf1001a``; +``t_80a3542a`` showed the same class): ``block_task`` routed a repeated +``needs_input`` block (``block_recurrences >= BLOCK_RECURRENCE_LIMIT``) to +``status='triage'`` and emitted ``block_loop_detected``. But ``triage`` is an +*automation* queue, not a human hold: with ``kanban.auto_decompose`` enabled +(the default) the dispatcher treats every triage row as a decompose/specify +candidate. On the next tick it silently advanced the escalated card +``triage -> todo`` (no lifecycle event) and ``recompute_ready`` would then make +it ``ready`` — exactly the blocked-task-resurrection class this branch fixes. + +The invariant pinned here: a block-loop escalation lands in a *sticky* +``blocked`` state that auto-decompose, ``recompute_ready``, ``claim_task`` and +dispatcher ticks cannot advance. Only an explicit ``unblock_task`` resumes it. +Ordinary triage cards keep auto-decomposing. +""" + +from __future__ import annotations + +import json +import sqlite3 +import time +from pathlib import Path + +import pytest + +from hermes_cli import kanban_db as kb +from hermes_cli import kanban_decompose as kd + + +@pytest.fixture +def kanban_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + home = tmp_path / ".hermes" + home.mkdir() + monkeypatch.setenv("HERMES_HOME", str(home)) + monkeypatch.setattr(Path, "home", lambda: tmp_path) + kb.init_db() + return home + + +def _running_task(conn: sqlite3.Connection, title: str = "t") -> str: + tid = kb.create_task(conn, title=title, assignee="worker") + with kb.write_txn(conn): + conn.execute("UPDATE tasks SET status='ready' WHERE id=?", (tid,)) + assert kb.claim_task(conn, tid, claimer="worker") is not None + return tid + + +def _escalate_block_loop(conn: sqlite3.Connection, kind: str = "needs_input") -> str: + """Drive a task through the real block -> unblock -> re-block loop until + ``block_task`` trips the recurrence breaker.""" + tid = _running_task(conn, title="worker keeps asking the same question") + assert kb.block_task(conn, tid, reason="need creds", kind=kind) + assert kb.unblock_task(conn, tid) # the cron that keeps spinning it + with kb.write_txn(conn): + conn.execute("UPDATE tasks SET status='ready' WHERE id=?", (tid,)) + assert kb.claim_task(conn, tid, claimer="worker") is not None + assert kb.block_task(conn, tid, reason="need creds", kind=kind) + row = conn.execute( + "SELECT block_recurrences FROM tasks WHERE id=?", (tid,) + ).fetchone() + assert int(row["block_recurrences"]) >= kb.BLOCK_RECURRENCE_LIMIT + kinds = [ + r["kind"] for r in conn.execute( + "SELECT kind FROM task_events WHERE task_id=? ORDER BY id", (tid,) + ) + ] + assert "block_loop_detected" in kinds + return tid + + +# --------------------------------------------------------------------------- +# The escalation itself +# --------------------------------------------------------------------------- + + +def test_block_loop_escalation_is_sticky_blocked_not_triage(kanban_home: Path) -> None: + with kb.connect_closing() as conn: + tid = _escalate_block_loop(conn) + task = kb.get_task(conn, tid) + assert task.status == "blocked", ( + "block-loop escalation must land in a sticky blocked state, not in " + "the triage automation queue" + ) + assert task.block_kind == "needs_input" + assert kb._has_sticky_block(conn, tid) is True + + +def test_block_loop_escalation_is_invisible_to_auto_decompose(kanban_home: Path) -> None: + """The real dispatcher path: ``list_triage_ids`` feeds the auto-decomposer + every tick. An escalated card must never appear in it.""" + with kb.connect_closing() as conn: + tid = _escalate_block_loop(conn) + ordinary = kb.create_task(conn, title="rough idea", triage=True) + + assert kd.list_triage_ids() == [ordinary], ( + "auto-decompose must not see a block-loop escalation as a triage " + "candidate" + ) + + outcome = kd.decompose_task(tid) + assert outcome.ok is False + + +def test_block_loop_escalation_survives_dispatcher_ticks(kanban_home: Path) -> None: + with kb.connect_closing() as conn: + tid = _escalate_block_loop(conn) + for _ in range(5): + assert kb.recompute_ready(conn) == 0 + assert kb.get_task(conn, tid).status == "blocked" + assert kb.claim_task(conn, tid, claimer="worker") is None + + +def test_block_loop_escalation_rejects_specify_and_decompose(kanban_home: Path) -> None: + """Defense in depth: even if something parks an escalated row back in + ``triage``, the two production promotion helpers must refuse it.""" + with kb.connect_closing() as conn: + tid = _escalate_block_loop(conn) + with kb.write_txn(conn): + conn.execute("UPDATE tasks SET status='triage' WHERE id=?", (tid,)) + assert kb.specify_triage_task(conn, tid, body="spec") is False + assert kb.decompose_triage_task( + conn, tid, root_assignee="worker", + children=[{"title": "child"}], + ) is None + assert kb.get_task(conn, tid).status == "triage" + + +def test_explicit_unblock_resumes_a_block_loop_escalation(kanban_home: Path) -> None: + with kb.connect_closing() as conn: + tid = _escalate_block_loop(conn) + assert kb.unblock_task(conn, tid) is True + assert kb.get_task(conn, tid).status == "ready" + assert kb._has_sticky_block(conn, tid) is False + assert kb.claim_task(conn, tid, claimer="worker") is not None + + +# --------------------------------------------------------------------------- +# Legacy rows already parked in triage by the old routing +# --------------------------------------------------------------------------- + + +def _legacy_escalated_row(conn: sqlite3.Connection, title: str) -> str: + """Write a row shaped exactly like the pre-fix escalation: parked in + ``triage`` with ``block_kind`` set and a trailing ``block_loop_detected`` + event.""" + tid = kb.create_task(conn, title=title) + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET status='triage', block_kind='needs_input', " + "block_recurrences=? WHERE id=?", + (kb.BLOCK_RECURRENCE_LIMIT, tid), + ) + conn.execute( + "INSERT INTO task_events (task_id, kind, payload, created_at) " + "VALUES (?, 'block_loop_detected', ?, ?)", + ( + tid, + json.dumps({ + "reason": "need creds", + "kind": "needs_input", + "recurrences": kb.BLOCK_RECURRENCE_LIMIT, + "limit": kb.BLOCK_RECURRENCE_LIMIT, + }), + int(time.time()), + ), + ) + return tid + + +def test_migration_lifts_legacy_triage_escalations_out_of_triage( + kanban_home: Path, +) -> None: + with kb.connect_closing() as conn: + escalated = _legacy_escalated_row(conn, "legacy escalation") + ordinary = kb.create_task(conn, title="ordinary idea", triage=True) + # An escalation an operator already unblocked and re-parked in triage + # by hand is NOT ours to move. + cleared = _legacy_escalated_row(conn, "already handled") + with kb.write_txn(conn): + conn.execute( + "INSERT INTO task_events (task_id, kind, payload, created_at) " + "VALUES (?, 'unblocked', NULL, ?)", + (cleared, int(time.time())), + ) + + kb.init_db() # activation re-runs the migration pass + + with kb.connect_closing() as conn: + assert kb.get_task(conn, escalated).status == "blocked" + assert kb._has_sticky_block(conn, escalated) is True + assert kb.get_task(conn, ordinary).status == "triage" + assert kb.get_task(conn, cleared).status == "triage" + + assert sorted(kd.list_triage_ids()) == sorted([ordinary, cleared]) + + +def test_migration_leaves_ordinary_triage_auto_decomposable(kanban_home: Path) -> None: + """The legitimate flow must keep working: a plain triage card is still a + decompose candidate and still promotes to ``todo``.""" + with kb.connect_closing() as conn: + tid = kb.create_task(conn, title="build me a thing", triage=True) + + kb.init_db() + + assert kd.list_triage_ids() == [tid] + with kb.connect_closing() as conn: + assert kb.specify_triage_task(conn, tid, body="spec") is True + assert kb.get_task(conn, tid).status in ("todo", "ready") + + +# --------------------------------------------------------------------------- +# Legacy DBs whose ``task_events`` still carries drifted TEXT ids (#35096) +# --------------------------------------------------------------------------- + + +_LEGACY_EVENTS_SQL = """ +CREATE TABLE task_events ( + id TEXT PRIMARY KEY, + task_id TEXT NOT NULL, + run_id INTEGER, + kind TEXT NOT NULL, + payload TEXT, + created_at INTEGER NOT NULL +) +""" + + +def _drift_task_events_to_text_ids(conn: sqlite3.Connection) -> None: + """Rewrite ``task_events`` into the pre-#35096 TEXT-id shape. + + Rows keep their chronological order but get ``ev-1 … ev-N`` string ids — + which sort *lexicographically*, so ``ev-9`` compares greater than + ``ev-10``. ``_rebuild_drifted_tables`` is what repairs this on init. + """ + rows = conn.execute( + "SELECT task_id, run_id, kind, payload, created_at " + "FROM task_events ORDER BY id" + ).fetchall() + conn.execute("DROP TABLE task_events") + conn.execute(_LEGACY_EVENTS_SQL) + for idx, row in enumerate(rows, start=1): + conn.execute( + "INSERT INTO task_events (id, task_id, run_id, kind, payload, created_at) " + "VALUES (?, ?, ?, ?, ?, ?)", + (f"ev-{idx}", row["task_id"], row["run_id"], row["kind"], + row["payload"], row["created_at"]), + ) + conn.commit() + assert kb._table_has_drifted(conn, "task_events") + + +def _legacy_triage_row_with_history( + conn: sqlite3.Connection, title: str, *, tail_kinds: list[str], + filler: int, +) -> str: + """A triage row with a realistic (>= 10 event) history whose final + chronological events are ``tail_kinds``. + + ``filler`` pads the history so the caller can place ``tail_kinds`` at exact + positions in the *global* event sequence — which is what decides whether + the legacy TEXT ids (``ev-9`` vs ``ev-10``) sort the wrong way round. + ``create_task`` already emits one ``created`` event, so the row carries + ``1 + filler + len(tail_kinds)`` events in total. + """ + tid = kb.create_task(conn, title=title) + now = int(time.time()) + kinds = ["claimed", "heartbeat", "comment", "claimed", "reclaimed", + "claimed", "comment", "heartbeat", "comment", "claimed"] + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET status='triage', block_kind='needs_input', " + "block_recurrences=? WHERE id=?", + (kb.BLOCK_RECURRENCE_LIMIT, tid), + ) + for offset, kind in enumerate(kinds[:filler] + tail_kinds): + payload = None + if kind == "block_loop_detected": + payload = json.dumps({ + "reason": "need creds", "kind": "needs_input", + "recurrences": kb.BLOCK_RECURRENCE_LIMIT, + "limit": kb.BLOCK_RECURRENCE_LIMIT, + }) + conn.execute( + "INSERT INTO task_events (task_id, kind, payload, created_at) " + "VALUES (?, ?, ?, ?)", + (tid, kind, payload, now + offset), + ) + return tid + + +def test_migration_reads_event_order_after_text_id_drift_is_repaired( + kanban_home: Path, +) -> None: + """A legacy drifted board must not have its escalation migration decided by + lexicographic TEXT ids. + + On a pre-#35096 board ``task_events.id`` is TEXT, so ``ORDER BY id DESC`` + picks ``ev-9`` over ``ev-10``. A task whose real history ends + ``… block_loop_detected (ev-9), unblocked (ev-10)`` — i.e. an operator + already cleared the escalation — then looks *still escalated*. If the + escalation migration runs before ``_rebuild_drifted_tables`` repairs the + ids, init converts that triage card to ``blocked``; the rebuild then + renumbers the events, ``_has_sticky_block`` reads the true tail + (``unblocked``) and returns False, and the very next ``recompute_ready`` + promotes the card to ``ready`` for a worker to claim. That is the + resurrection this branch exists to prevent, reached by a different door. + """ + with kb.connect_closing() as conn: + # Built first so its events own global ids 1-10: the escalation lands + # at ev-9 and the operator's unblock at ev-10, which TEXT ids sort + # backwards ('ev-9' > 'ev-10'). + cleared = _legacy_triage_row_with_history( + conn, "operator already unblocked", filler=7, + tail_kinds=["block_loop_detected", "unblocked"], + ) + still_escalated = _legacy_triage_row_with_history( + conn, "still waiting on a human", filler=8, + tail_kinds=["unblocked", "block_loop_detected"], + ) + ordinary = kb.create_task(conn, title="ordinary idea", triage=True) + for tid in (cleared, still_escalated): + n = conn.execute( + "SELECT COUNT(*) AS n FROM task_events WHERE task_id=?", (tid,) + ).fetchone()["n"] + assert n >= 10, n + _drift_task_events_to_text_ids(conn) + # Pin the hazard itself: on the drifted table the event log reads + # backwards for the cleared row. + assert kb._latest_block_event_kind(conn, cleared) == "block_loop_detected" + + kb.init_db() # activation: rebuild + escalation migration + + with kb.connect_closing() as conn: + assert kb._table_has_drifted(conn, "task_events") is False + # The cleared row was never ours to touch — it must stay exactly where + # the operator left it, and must not be silently made claimable. + assert kb.get_task(conn, cleared).status == "triage", ( + "a legacy row whose newest event is 'unblocked' must not be " + "migrated out of triage on the strength of lexicographic id order" + ) + assert kb.has_block_loop_escalation(conn, cleared) is False + # The genuinely-escalated row still becomes a sticky block. + assert kb.get_task(conn, still_escalated).status == "blocked" + assert kb._has_sticky_block(conn, still_escalated) is True + assert kb.get_task(conn, ordinary).status == "triage" + + # No dispatcher tick may hand either card back to a worker. + for _ in range(3): + kb.recompute_ready(conn) + assert kb.get_task(conn, cleared).status == "triage" + assert kb.get_task(conn, still_escalated).status == "blocked" + assert kb.claim_task(conn, cleared, claimer="worker") is None + assert kb.claim_task(conn, still_escalated, claimer="worker") is None diff --git a/tests/hermes_cli/test_kanban_core_functionality.py b/tests/hermes_cli/test_kanban_core_functionality.py index 0a47445ec1108..4139813f338cd 100644 --- a/tests/hermes_cli/test_kanban_core_functionality.py +++ b/tests/hermes_cli/test_kanban_core_functionality.py @@ -266,7 +266,13 @@ def _signal_fn(pid, sig): killed.append((pid, sig)) # We bypass _pid_alive by stubbing it so the grace-poll exits fast. - import hermes_cli.kanban_db as _kb + # Stub the module object this test actually calls into (``kb``): an + # earlier test in the same session may have evicted hermes_cli from + # sys.modules, in which case a fresh ``import hermes_cli.kanban_db`` + # here would patch a *different* module and leave the real liveness + # probe running against pytest's own pid — which now (correctly) + # refuses to requeue a task whose worker is still alive. + _kb = kb original_alive = _kb._pid_alive _kb._pid_alive = lambda pid: False # pretend SIGTERM worked immediately @@ -1204,7 +1210,11 @@ def test_reclaim_task_resets_running_to_ready(kanban_home, monkeypatch): import signal import time import secrets - import hermes_cli.kanban_db as _kb + # Patch the module object this test actually calls into. A fresh + # ``import hermes_cli.kanban_db`` can hand back a DIFFERENT module when an + # earlier test in the session evicted hermes_cli from sys.modules, and the + # stubs below would then silently miss. + _kb = kb conn = kb.connect() try: t = kb.create_task(conn, title="stuck", assignee="broken") @@ -1220,9 +1230,15 @@ def _signal(pid, sig): state["alive"] = False monkeypatch.setattr(_kb, "_pid_alive", lambda _pid: state["alive"]) + # A worker row carries an identity token alongside its pid: signalling + # is only allowed while that token still verifies, so a fabricated row + # has to carry one too (a pid with no identity is a legacy row, which + # is deliberately never signalled — see + # test_kanban_process_retry_safety.py). + monkeypatch.setattr(_kb, "_process_identity", lambda _pid: "test-identity") conn.execute( "UPDATE tasks SET status='running', claim_lock=?, claim_expires=?, " - "worker_pid=? WHERE id=?", + "worker_pid=?, worker_identity='test-identity' WHERE id=?", (lock, future, 12345, t), ) conn.execute( diff --git a/tests/hermes_cli/test_kanban_process_retry_safety.py b/tests/hermes_cli/test_kanban_process_retry_safety.py new file mode 100644 index 0000000000000..7cafbf76c8c8e --- /dev/null +++ b/tests/hermes_cli/test_kanban_process_retry_safety.py @@ -0,0 +1,1790 @@ +"""Kanban lifecycle process-safety regressions. + +Two production incidents, one coherent lifecycle contract: a task must not +be handed to a new worker while the *previous* decision about it is still +binding. + +**Bug A — the breaker decision was not binding.** +``t_27263082`` recorded ``gave_up`` after two spawn failures with payload +``effective_limit=2 / limit_source=dispatcher``. A later ``recompute_ready`` +call resolved a *different* effective limit (its own default / a differently +configured caller), decided the task was still under budget, promoted it back +to ``ready``, and the dispatcher retried it. The limit that actually tripped +the breaker must be persisted and honoured by every later caller — restart, +config change, or default mismatch included. The only legitimate exits stay +explicit: ``kanban_unblock``, operator reclaim/promote, or a success. + +**Bug B — the requeue decision outran the OS.** +``t_80a3542a`` run 141 hit its iteration/runtime budget. The dispatcher +signalled the worker PID, did not confirm the process group was gone (PID +98725 was still alive, reparented to PID 1, with live Claude children), +flipped the task to ``ready`` anyway, and immediately claimed run 152 with a +second worker (PID 57286) against the same task and workspace: two live +writers. A timeout/reclaim must either bound the termination of the whole +process group or leave a durable fence that keeps the task nonclaimable +until that group is provably gone. +""" + +from __future__ import annotations + +import json +import os +import signal +import subprocess +import sys +import time +from pathlib import Path + +import pytest + +from hermes_cli import kanban_db as kb + + +@pytest.fixture +def kanban_home(tmp_path, monkeypatch): + """Isolated HERMES_HOME with an empty kanban DB.""" + home = tmp_path / ".hermes" + home.mkdir() + monkeypatch.setenv("HERMES_HOME", str(home)) + monkeypatch.setattr(Path, "home", lambda: tmp_path) + kb.init_db() + return home + + +@pytest.fixture +def no_sleep(monkeypatch): + """Collapse the termination grace polling so tests stay fast.""" + monkeypatch.setattr(kb.time, "sleep", lambda *_a, **_k: None) + + +@pytest.fixture +def live_worker(): + """A real, session-leading child process (pgid == pid), reaped on exit.""" + procs = [] + + def _spawn(): + proc = subprocess.Popen( # noqa: S603 - fixed argv + [sys.executable, "-c", "import time; time.sleep(120)"], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + start_new_session=True, + ) + procs.append(proc) + return proc + + yield _spawn + + for proc in procs: + try: + # getattr: a test may have removed killpg to exercise the + # no-process-groups (Windows-shaped) degradation path. + killpg = getattr(os, "killpg", None) + if killpg is not None: + killpg(os.getpgid(proc.pid), signal.SIGKILL) + else: + os.kill(proc.pid, signal.SIGKILL) + except (ProcessLookupError, OSError, AttributeError): + pass + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: # pragma: no cover - defensive + pass + + +@pytest.fixture +def orphaned_group(): + """A process group whose LEADER has exited but whose child is still alive. + + This is the ``t_80a3542a`` shape: the worker dies, its Claude children + reparent to PID 1, keep the worker's process group, and keep writing. + Returns ``(leader_pid, pgid, child_pid)`` with the leader already reaped. + """ + state = {} + + def _spawn(): + leader = subprocess.Popen( # noqa: S603 - fixed argv + [ + sys.executable, "-c", + "import os, subprocess, sys, time\n" + "child = subprocess.Popen([sys.executable, '-c'," + " 'import time; time.sleep(120)'])\n" + "print(os.getpid(), os.getpgid(0), child.pid, flush=True)\n", + ], + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True, + start_new_session=True, + ) + line = leader.stdout.readline().split() + leader.wait(timeout=10) # leader exits and is reaped: truly gone + leader_pid, pgid, child_pid = (int(x) for x in line) + state["pgid"] = pgid + state["child"] = child_pid + return leader_pid, pgid, child_pid + + yield _spawn + + if state: + try: + os.killpg(state["pgid"], signal.SIGKILL) + except (ProcessLookupError, OSError): + pass + + +def _kill_and_reap(pid): + """SIGKILL ``pid`` and wait until it is really gone (not just a zombie).""" + try: + os.kill(pid, signal.SIGKILL) + except (ProcessLookupError, OSError): + pass + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + try: + os.kill(pid, 0) + except ProcessLookupError: + return + except PermissionError: + return + time.sleep(0.02) + + +# --------------------------------------------------------------------------- +# helpers +# --------------------------------------------------------------------------- + + +def _events(conn, task_id, kind=None): + sql = "SELECT kind, payload FROM task_events WHERE task_id = ?" + args = [task_id] + if kind is not None: + sql += " AND kind = ?" + args.append(kind) + sql += " ORDER BY id" + return [ + (r["kind"], json.loads(r["payload"]) if r["payload"] else {}) + for r in conn.execute(sql, args).fetchall() + ] + + +def _trip_breaker(conn, task_id, *, failure_limit, attempts=None): + """Drive the real spawn-failure path until the breaker trips.""" + attempts = attempts if attempts is not None else failure_limit + tripped = False + for i in range(attempts): + assert kb.claim_task(conn, task_id) is not None, f"claim {i} failed" + tripped = kb._record_task_failure( + conn, task_id, + error="spawn failed: profile not found", + outcome="spawn_failed", + failure_limit=failure_limit, + release_claim=True, + end_run=True, + ) + return tripped + + +def _make_running_with_worker(conn, task_id, pid, *, pgid=None, elapsed=600): + """Claim ``task_id`` and attach a worker pid whose runtime cap is blown.""" + claimed = kb.claim_task(conn, task_id) + assert claimed is not None + kb._set_worker_pid(conn, task_id, int(pid), pgid=pgid) + now = int(time.time()) + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET max_runtime_seconds = 1, started_at = ? WHERE id = ?", + (now - elapsed, task_id), + ) + conn.execute( + "UPDATE task_runs SET started_at = ? WHERE id = ?", + (now - elapsed, kb.get_task(conn, task_id).current_run_id), + ) + return kb.get_task(conn, task_id) + + +# =========================================================================== +# Bug A — the recorded breaker decision binds every later caller +# =========================================================================== + + +def test_gave_up_records_the_effective_limit_that_tripped(kanban_home): + """The trip must persist *which* limit it decided against.""" + with kb.connect() as conn: + tid = kb.create_task(conn, title="breaker", assignee="a") + assert _trip_breaker(conn, tid, failure_limit=2) is True + + task = kb.get_task(conn, tid) + assert task.status == "blocked" + assert task.consecutive_failures == 2 + + gave_up = _events(conn, tid, "gave_up") + assert len(gave_up) == 1 + assert gave_up[0][1]["effective_limit"] == 2 + assert gave_up[0][1]["limit_source"] == "dispatcher" + + # And it is readable from the task row, not just the event log, so + # every promotion caller can honour it without replaying events. + assert kb.recorded_breaker_limit(conn, tid) == 2 + + +def test_recompute_with_a_lenient_caller_limit_cannot_repromote(kanban_home): + """The exact t_27263082 bug. + + Breaker tripped at effective_limit=2 (limit_source=dispatcher). A later + ``recompute_ready`` from a caller carrying a larger limit must not + promote the task: 2 failures already exhausted the limit the breaker + actually decided against. + """ + with kb.connect() as conn: + tid = kb.create_task(conn, title="t_27263082 shape", assignee="a") + _trip_breaker(conn, tid, failure_limit=2) + + for caller_limit in (None, 3, 4, 10): + promoted = ( + kb.recompute_ready(conn) + if caller_limit is None + else kb.recompute_ready(conn, failure_limit=caller_limit) + ) + assert promoted == 0, f"caller_limit={caller_limit} re-promoted" + assert kb.get_task(conn, tid).status == "blocked" + + +def test_recorded_limit_survives_restart_and_dispatcher_config_drift( + kanban_home, +): + """Gateway restart + a raised ``kanban.failure_limit`` must not resurrect + a task the breaker already gave up on.""" + spawned = [] + + with kb.connect() as conn: + tid = kb.create_task(conn, title="restart", assignee="a") + _trip_breaker(conn, tid, failure_limit=1, attempts=1) + assert kb.get_task(conn, tid).status == "blocked" + + # Fresh process/connection, dispatcher now configured far more leniently. + with kb.connect() as conn: + res = kb.dispatch_once( + conn, + spawn_fn=lambda *a, **k: spawned.append(a) or 4321, + failure_limit=9, + ) + assert res.promoted == 0, "gave_up task promoted after restart" + assert spawned == [], "dispatcher respawned a gave_up task" + assert kb.get_task(conn, tid).status == "blocked" + + +def test_task_max_retries_trip_is_also_binding(kanban_home): + """A per-task ``max_retries`` trip (limit_source=task) is just as sticky + when a later caller passes a larger dispatcher limit.""" + with kb.connect() as conn: + tid = kb.create_task(conn, title="task-limit", assignee="a") + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET max_retries = 1 WHERE id = ?", (tid,), + ) + _trip_breaker(conn, tid, failure_limit=5, attempts=1) + assert kb.get_task(conn, tid).status == "blocked" + assert _events(conn, tid, "gave_up")[0][1]["limit_source"] == "task" + + assert kb.recompute_ready(conn, failure_limit=9) == 0 + assert kb.get_task(conn, tid).status == "blocked" + + +def test_explicit_unblock_clears_the_recorded_breaker_decision(kanban_home): + """``kanban_unblock`` is the operator's deliberate fresh start: the + recorded trip must not survive it.""" + with kb.connect() as conn: + tid = kb.create_task(conn, title="unblock me", assignee="a") + _trip_breaker(conn, tid, failure_limit=2) + assert kb.get_task(conn, tid).status == "blocked" + + assert kb.unblock_task(conn, tid) is True + task = kb.get_task(conn, tid) + assert task.status == "ready" + assert task.consecutive_failures == 0 + assert kb.recorded_breaker_limit(conn, tid) is None + + # A later blocked-with-failures state resolves against the caller's + # limit again (the #35072 contract), because nothing is recorded. + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET status='blocked', consecutive_failures=1 " + "WHERE id = ?", + (tid,), + ) + assert kb.recompute_ready(conn, failure_limit=5) == 1 + assert kb.get_task(conn, tid).status == "ready" + + +def test_legacy_gave_up_rows_are_backfilled_on_migration(kanban_home): + """Boards written before this fix carry the decision only in the event + payload. Migration must lift it onto the task row so the historical + ``t_27263082`` shape is fenced too.""" + with kb.connect() as conn: + tid = kb.create_task(conn, title="legacy", assignee="a") + _trip_breaker(conn, tid, failure_limit=2) + # Simulate a row written by the pre-fix code: event payload only. + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET breaker_limit = NULL WHERE id = ?", (tid,), + ) + + with kb.connect() as conn: # re-open → migration/backfill runs + assert kb.recorded_breaker_limit(conn, tid) == 2 + assert kb.recompute_ready(conn, failure_limit=9) == 0 + assert kb.get_task(conn, tid).status == "blocked" + + +def test_parent_gated_todo_promotion_still_works(kanban_home): + """The breaker fence must not touch ordinary dependency promotion.""" + with kb.connect() as conn: + parent = kb.create_task(conn, title="parent", assignee="a") + child = kb.create_task(conn, title="child", assignee="a", parents=[parent]) + assert kb.get_task(conn, child).status == "todo" + + kb.claim_task(conn, parent) + kb.complete_task(conn, parent, result="done") + # complete_task recomputes inline; the child is promoted there. + assert kb.get_task(conn, child).status == "ready" + + # A blocked-on-dependency child (no breaker trip on record) is still + # promoted by a later recompute once its parent is done. + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET status='blocked' WHERE id = ?", (child,), + ) + assert kb.recompute_ready(conn) == 1 + assert kb.get_task(conn, child).status == "ready" + + +def test_worker_initiated_block_stays_sticky(kanban_home): + """#28712 contract is untouched: an explicit worker block never + auto-promotes, with or without a recorded breaker limit.""" + with kb.connect() as conn: + tid = kb.create_task(conn, title="review please", assignee="a") + kb.claim_task(conn, tid) + kb.block_task( + conn, tid, + reason="review-required: verify ACL change", + expected_run_id=kb.get_task(conn, tid).current_run_id, + ) + for _ in range(3): + assert kb.recompute_ready(conn, failure_limit=9) == 0 + assert kb.get_task(conn, tid).status == "blocked" + + +def test_completed_task_is_terminal(kanban_home): + """A done task is never re-promoted or re-claimed, even with a stale + ``gave_up`` in its history.""" + with kb.connect() as conn: + tid = kb.create_task(conn, title="finished", assignee="a") + _trip_breaker(conn, tid, failure_limit=2) + assert kb.unblock_task(conn, tid) is True + kb.claim_task(conn, tid) + kb.complete_task(conn, tid, result="shipped") + assert kb.get_task(conn, tid).status == "done" + + assert kb.recompute_ready(conn, failure_limit=9) == 0 + assert kb.claim_task(conn, tid) is None + assert kb.get_task(conn, tid).status == "done" + + +# =========================================================================== +# Bug B — no replacement worker while the old process group can still write +# =========================================================================== + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_timeout_does_not_requeue_while_worker_group_is_alive( + kanban_home, live_worker, no_sleep, monkeypatch, +): + """The exact t_80a3542a bug: budget exhausted, worker still alive. + + ``enforce_max_runtime`` must not flip the task to ``ready`` (which is + what let the dispatcher claim run 152 beside live run 141). The task + stays ``running``, the run stays open, and the hold is visible. + """ + proc = live_worker() + with kb.connect() as conn: + tid = kb.create_task(conn, title="t_80a3542a shape", assignee="a") + task = _make_running_with_worker(conn, tid, proc.pid) + run_id = task.current_run_id + + # signal_fn/killpg_fn are no-ops: the worker ignores our signals, + # exactly like a process wedged in an uninterruptible syscall. + timed_out = kb.enforce_max_runtime( + conn, + signal_fn=lambda *a, **k: None, + killpg_fn=lambda *a, **k: None, + ) + + assert timed_out == [] + task = kb.get_task(conn, tid) + assert task.status == "running", "requeued while worker still alive" + assert task.current_run_id == run_id, "run finalized under a live worker" + assert task.consecutive_failures == 0 + assert [k for k, _ in _events(conn, tid)].count("timed_out") == 0 + deferred = _events(conn, tid, "reclaim_deferred") + assert deferred, "the hold must be recorded for operators" + assert deferred[-1][1]["prev_pid"] == proc.pid + + # Same through a full dispatcher tick, with the worker still + # ignoring signals (a D-state / throttled worker): no requeue, no + # second spawn — this is the tick that produced run 152. + spawned = [] + with monkeypatch.context() as m: + m.setattr(kb.os, "kill", lambda *a, **k: None) + m.setattr(kb.os, "killpg", lambda *a, **k: None) + kb.dispatch_once(conn, spawn_fn=lambda *a, **k: spawned.append(a) or 1) + assert spawned == [] + assert kb.get_task(conn, tid).status == "running" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_timeout_termination_targets_the_whole_process_group( + kanban_home, live_worker, no_sleep, +): + """Signalling only the worker PID leaves its Claude children alive (they + reparent to PID 1 and keep writing). Terminate the group.""" + proc = live_worker() + pgid = os.getpgid(proc.pid) + calls = [] + + with kb.connect() as conn: + tid = kb.create_task(conn, title="group kill", assignee="a") + _make_running_with_worker(conn, tid, proc.pid) + assert kb.get_task(conn, tid).worker_pgid == pgid + + kb.enforce_max_runtime( + conn, + signal_fn=lambda *a, **k: None, + killpg_fn=lambda *a, **k: calls.append(a), + ) + + assert calls, "no process-group signal was sent" + assert {c[0] for c in calls} == {pgid} + assert signal.SIGTERM in {c[1] for c in calls} + assert signal.SIGKILL in {c[1] for c in calls}, "no bounded escalation" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_timeout_requeues_once_the_group_is_gone(kanban_home, live_worker, no_sleep): + """Normal path preserved: when termination is confirmed, the task is + requeued exactly once with a ``timed_out`` run and a counted failure.""" + proc = live_worker() + with kb.connect() as conn: + tid = kb.create_task(conn, title="clean timeout", assignee="a") + task = _make_running_with_worker(conn, tid, proc.pid) + run_id = task.current_run_id + + timed_out = kb.enforce_max_runtime(conn) # real signals: group dies + + assert timed_out == [tid] + task = kb.get_task(conn, tid) + assert task.status == "ready" + assert task.current_run_id is None + assert task.consecutive_failures == 1 + run = kb.get_run(conn, run_id) + assert run.outcome == "timed_out" + assert [k for k, _ in _events(conn, tid)].count("timed_out") == 1 + + # And nothing fences the (now dead) worker: the retry can claim. + assert kb.claim_task(conn, tid) is not None + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_claim_is_fenced_until_the_prior_process_group_exits( + kanban_home, live_worker, no_sleep, +): + """Durable nonclaimable reconciliation: a task that reached ``ready`` + while its previous worker group was still alive must not be claimed — + across restarts, since the fence lives on the row.""" + proc = live_worker() + with kb.connect() as conn: + tid = kb.create_task(conn, title="fenced", assignee="a") + task = _make_running_with_worker(conn, tid, proc.pid) + run_id = task.current_run_id + # A path outside our control (crash reaper, manual SQL, an older + # gateway) requeued the task while the group was still alive. + kb.record_worker_fence( + conn, tid, + pid=proc.pid, + pgid=os.getpgid(proc.pid), + run_id=run_id, + claim_lock=task.claim_lock, + reason="requeued_worker_alive", + ) + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET status='ready', claim_lock=NULL, " + "claim_expires=NULL, worker_pid=NULL, current_run_id=NULL " + "WHERE id = ?", + (tid,), + ) + + with kb.connect() as conn: # restart + assert kb.claim_task(conn, tid) is None, "claimed beside a live worker" + rejected = _events(conn, tid, "claim_rejected") + assert rejected and rejected[-1][1]["reason"] == "prior_worker_alive" + assert rejected[-1][1]["fence_run_id"] == run_id + assert kb.get_task(conn, tid).status == "ready" + + spawned = [] + kb.dispatch_once(conn, spawn_fn=lambda *a, **k: spawned.append(a) or 1) + assert spawned == [], "dispatcher spawned a duplicate writer" + + # Once the group is gone the fence clears itself and work resumes. + os.killpg(os.getpgid(proc.pid), signal.SIGKILL) + proc.wait(timeout=5) + assert kb.claim_task(conn, tid) is not None + assert kb.get_task(conn, tid).status == "running" + assert kb.worker_fence(conn, tid) is None + + +@pytest.mark.live_system_guard_bypass # signals only our own orphaned group +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_crashed_worker_with_live_children_is_fenced( + kanban_home, orphaned_group, no_sleep, +): + """The worker PID is gone but the children it forked are not. + + They reparent to PID 1, keep the worker's process group, and keep + writing to the workspace — the ``t_80a3542a`` shape. The crash reaper + may requeue the task, but it must not become claimable. Real processes + throughout: a group-leading worker that has exited and been reaped, with + a live child still holding its group. + """ + leader_pid, pgid, _child_pid = orphaned_group() + + with kb.connect() as conn: + tid = kb.create_task(conn, title="orphaned children", assignee="a") + claimed = kb.claim_task(conn, tid) + kb._set_worker_pid(conn, tid, leader_pid, pgid=pgid) + run_id = kb.get_task(conn, tid).current_run_id + assert kb.get_task(conn, tid).worker_pgid == pgid + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET started_at = ? WHERE id = ?", + (int(time.time()) - 3600, tid), + ) + + crashed = kb.detect_crashed_workers(conn) + assert tid in crashed + + fence = kb.worker_fence(conn, tid) + assert fence is not None, "requeued with live children and no fence" + assert fence["pgid"] == pgid + assert fence["run_id"] == run_id + assert fence["claim_lock"] == claimed.claim_lock + + assert kb.claim_task(conn, tid) is None + rejected = _events(conn, tid, "claim_rejected") + assert rejected[-1][1]["reason"] == "prior_worker_alive" + + +def test_run_finalization_is_exactly_once(kanban_home): + """A run may be finalized once. A second finalization (racing reaper vs + worker completion) must not reopen it, rewrite its outcome, or emit a + second terminal row.""" + with kb.connect() as conn: + tid = kb.create_task(conn, title="one finalize", assignee="a") + kb.claim_task(conn, tid) + run_id = kb.get_task(conn, tid).current_run_id + + with kb.write_txn(conn): + first = kb._end_run(conn, tid, outcome="timed_out", status="timed_out") + assert first == run_id + + with kb.write_txn(conn): + second = kb._end_run(conn, tid, outcome="completed", status="done") + assert second is None, "second finalization must be a no-op" + + run = kb.get_run(conn, run_id) + assert run.outcome == "timed_out" + assert run.ended_at is not None + open_runs = conn.execute( + "SELECT COUNT(*) FROM task_runs WHERE task_id = ? AND ended_at IS NULL", + (tid,), + ).fetchone()[0] + assert open_runs == 0 + + +# =========================================================================== +# Review round 2 — every reclaim path fences, and the fence is identity-safe +# =========================================================================== + + +@pytest.mark.live_system_guard_bypass # signals only our own orphaned group +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_stale_running_reclaim_fences_orphaned_children( + kanban_home, orphaned_group, no_sleep, +): + """``detect_stale_running`` is a third requeue path and must fence too. + + Dead leader, live child holding the worker's process group: the + heartbeat reaper may requeue the task, but a replacement worker must + not be claimable until those children are gone. + """ + leader_pid, pgid, child_pid = orphaned_group() + with kb.connect() as conn: + tid = kb.create_task(conn, title="stale with children", assignee="a") + claimed = kb.claim_task(conn, tid) + kb._set_worker_pid(conn, tid, leader_pid, pgid=pgid) + run_id = kb.get_task(conn, tid).current_run_id + old = int(time.time()) - 100_000 + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET started_at = ?, last_heartbeat_at = NULL " + "WHERE id = ?", + (old, tid), + ) + conn.execute( + "UPDATE task_runs SET started_at = ? WHERE id = ?", (old, run_id), + ) + + assert kb.detect_stale_running(conn, stale_timeout_seconds=60) == [tid] + + task = kb.get_task(conn, tid) + assert task.status == "ready" + assert task.worker_pgid is None, "stale worker_pgid residue" + fence = kb.worker_fence(conn, tid) + assert fence is not None, "requeued with live children and no fence" + assert fence["pgid"] == pgid + assert fence["run_id"] == run_id + assert fence["claim_lock"] == claimed.claim_lock + + assert kb.claim_task(conn, tid) is None + assert _events(conn, tid, "claim_rejected")[-1][1]["reason"] == ( + "prior_worker_alive" + ) + + _kill_and_reap(child_pid) + assert kb.claim_task(conn, tid) is not None + assert kb.worker_fence(conn, tid) is None + + +@pytest.mark.live_system_guard_bypass # signals only our own orphaned group +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_release_stale_claims_fences_orphaned_children( + kanban_home, orphaned_group, no_sleep, +): + """Same contract on the TTL-expiry path, exercised end to end.""" + leader_pid, pgid, child_pid = orphaned_group() + with kb.connect() as conn: + tid = kb.create_task(conn, title="ttl with children", assignee="a") + kb.claim_task(conn, tid) + kb._set_worker_pid(conn, tid, leader_pid, pgid=pgid) + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET claim_expires = ? WHERE id = ?", + (int(time.time()) - 60, tid), + ) + + assert kb.release_stale_claims(conn) == 1 + task = kb.get_task(conn, tid) + assert task.status == "ready" + assert task.worker_pgid is None + assert kb.worker_fence(conn, tid) is not None + assert kb.claim_task(conn, tid) is None + + _kill_and_reap(child_pid) + assert kb.claim_task(conn, tid) is not None + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_foreign_host_claim_is_never_fenced_from_local_pids( + kanban_home, live_worker, no_sleep, +): + """A claim held by ANOTHER host says nothing about local PIDs. + + Its pid/pgid numbers are meaningful only on that host; a local process + that happens to share the number must not fence the task forever — we + have no way to ever observe the remote worker exiting. + """ + proc = live_worker() # local process colliding with the remote pid number + with kb.connect() as conn: + tid = kb.create_task(conn, title="foreign claim", assignee="a") + kb.claim_task(conn, tid) + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET claim_lock = ?, claim_expires = ?, " + "worker_pid = ?, worker_pgid = ?, worker_identity = NULL " + "WHERE id = ?", + ( + "some-other-host:4242", int(time.time()) - 60, + proc.pid, os.getpgid(proc.pid), tid, + ), + ) + + assert kb.release_stale_claims(conn) == 1 + assert kb.get_task(conn, tid).status == "ready" + assert kb.worker_fence(conn, tid) is None, ( + "fenced a foreign-host claim from a local pid collision" + ) + assert kb.claim_task(conn, tid) is not None + assert proc.poll() is None, "signalled a process we do not own" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_fence_does_not_survive_pid_reuse(kanban_home, live_worker, no_sleep): + """A fence pins process *identity*, not a recycled number. + + The recorded worker is long gone; the OS handed its pid to something + unrelated. Holding the task hostage to a stranger's lifetime would strand + it forever. + """ + proc = live_worker() + with kb.connect() as conn: + tid = kb.create_task(conn, title="reused pid", assignee="a") + with kb.write_txn(conn): + conn.execute("UPDATE tasks SET status = 'ready' WHERE id = ?", (tid,)) + kb.record_worker_fence( + conn, tid, + pid=proc.pid, + pgid=os.getpgid(proc.pid), + run_id=1, + claim_lock=kb._claimer_id(), + reason="unit", + identity="definitely-not-this-process", + ) + + assert kb.claim_task(conn, tid) is not None, "fenced by a recycled pid" + assert kb.worker_fence(conn, tid) is None + cleared = _events(conn, tid, "worker_fence_cleared") + assert cleared and cleared[-1][1]["cleared_reason"] == "worker_identity_changed" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_fence_held_by_children_only_is_bounded( + kanban_home, orphaned_group, no_sleep, +): + """A fence with no verifiable leader is bounded in time. + + Children can hold a process group for a very long time (or a recycled + pgid can look like they do). While the leader itself is verifiably + alive the fence never expires, but a group-only hold gives up after + ``WORKER_FENCE_MAX_SECONDS`` rather than stranding the task. + """ + _leader_pid, pgid, _child = orphaned_group() + with kb.connect() as conn: + tid = kb.create_task(conn, title="bounded fence", assignee="a") + with kb.write_txn(conn): + conn.execute("UPDATE tasks SET status = 'ready' WHERE id = ?", (tid,)) + kb.record_worker_fence( + conn, tid, + pid=_leader_pid, pgid=pgid, run_id=1, + claim_lock=kb._claimer_id(), reason="unit", + identity="leader-is-gone", + ) + # Fresh fence: children hold it. + assert kb.claim_task(conn, tid) is None + + # Age it past the bound. + fence = kb.worker_fence(conn, tid) + fence["since"] = int(time.time()) - kb.WORKER_FENCE_MAX_SECONDS - 1 + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET worker_fence = ? WHERE id = ?", + (json.dumps(fence), tid), + ) + assert kb.claim_task(conn, tid) is not None + expired = _events(conn, tid, "worker_fence_expired") + assert expired, "expiry must be auditable" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_operator_recovery_clears_a_fence(kanban_home, live_worker, no_sleep): + """Explicit operator actions are the escape hatch for a stuck fence.""" + for action in ("unblock", "promote"): + proc = live_worker() + with kb.connect() as conn: + tid = kb.create_task(conn, title=f"escape-{action}", assignee="a") + kb.record_worker_fence( + conn, tid, + pid=proc.pid, pgid=os.getpgid(proc.pid), run_id=1, + claim_lock=kb._claimer_id(), reason="unit", + identity=kb._process_identity(proc.pid), + ) + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET status = 'blocked' WHERE id = ?", (tid,), + ) + # Still fenced by a genuinely live worker... + assert kb.worker_fence(conn, tid) is not None + + if action == "unblock": + assert kb.unblock_task(conn, tid) is True + else: + ok, _err = kb.promote_task(conn, tid, actor="operator") + assert ok + + assert kb.worker_fence(conn, tid) is None, ( + f"{action} left the task fenced with no operator escape" + ) + assert kb.claim_task(conn, tid) is not None + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_group_signal_requires_verified_leader_identity( + kanban_home, live_worker, no_sleep, +): + """Never blast a process group we cannot prove is still ours. + + PIDs and PGIDs are recycled. Signalling a group whose leader identity no + longer matches (or was never recorded) would kill an unrelated group. + """ + proc = live_worker() + pgid = os.getpgid(proc.pid) + + # Identity matches → the group is ours, group signalling is allowed. + group_calls = [] + kb._terminate_reclaimed_worker( + proc.pid, kb._claimer_id(), + signal_fn=lambda *a: None, + killpg_fn=lambda *a: group_calls.append(a), + pgid=pgid, + identity=kb._process_identity(proc.pid), + ) + assert group_calls and group_calls[0][0] == pgid + + # Identity mismatch (pid was recycled) → no group signal at all. + stale_calls = [] + pid_calls = [] + info = kb._terminate_reclaimed_worker( + proc.pid, kb._claimer_id(), + signal_fn=lambda *a: pid_calls.append(a), + killpg_fn=lambda *a: stale_calls.append(a), + pgid=pgid, + identity="not-the-recorded-process", + ) + assert stale_calls == [], "blasted a recycled process group" + assert info["terminated"] is True, "a recycled pid means our worker is gone" + assert info["still_alive"] is False + + # No recorded identity (legacy row) → fail closed on the group too. + legacy_calls = [] + kb._terminate_reclaimed_worker( + proc.pid, kb._claimer_id(), + signal_fn=lambda *a: None, + killpg_fn=lambda *a: legacy_calls.append(a), + pgid=pgid, + identity=None, + ) + assert legacy_calls == [], "group-signalled an unverifiable process group" + + +def test_force_trip_gave_up_is_binding_below_the_limit(kanban_home): + """A recorded trip binds on its own, not on a counter comparison. + + ``force_trip`` (protocol-violation streak, systemic-error trip) records + ``gave_up`` with ``failures`` BELOW ``effective_limit``. Comparing the + counter against the limit let those tasks auto-promote on the very next + recompute — the give-up decision has to bind until something explicitly + resets it. + """ + with kb.connect() as conn: + tid = kb.create_task(conn, title="force tripped", assignee="a") + kb.claim_task(conn, tid) + assert kb._record_task_failure( + conn, tid, + error="clean exit without terminal tool call", + outcome="crashed", + failure_limit=5, + force_trip=True, + release_claim=True, + end_run=True, + ) is True + + task = kb.get_task(conn, tid) + assert task.status == "blocked" + assert task.consecutive_failures < 5, "precondition: below the limit" + assert kb.recorded_breaker_limit(conn, tid) is not None + + for caller_limit in (None, 5, 99): + promoted = ( + kb.recompute_ready(conn) if caller_limit is None + else kb.recompute_ready(conn, failure_limit=caller_limit) + ) + assert promoted == 0, f"force-tripped task promoted ({caller_limit})" + assert kb.get_task(conn, tid).status == "blocked" + + # Explicit operator recovery still works. + assert kb.unblock_task(conn, tid) is True + assert kb.get_task(conn, tid).status == "ready" + assert kb.recorded_breaker_limit(conn, tid) is None + + +def test_breaker_limit_is_not_stamped_on_a_terminal_race(kanban_home): + """The trip stamp rides the status-guarded transition. + + If the worker completes the task while the dispatcher is accounting a + failure, the guarded UPDATE matches nothing — and the breaker stamp must + not land either, or a finished task carries a binding give-up decision. + """ + with kb.connect() as conn: + tid = kb.create_task(conn, title="racy completion", assignee="a") + kb.claim_task(conn, tid) + kb.complete_task(conn, tid, result="done before the reaper looked") + assert kb.get_task(conn, tid).status == "done" + + kb._record_task_failure( + conn, tid, + error="reaper thought this crashed", + outcome="crashed", + failure_limit=1, + release_claim=False, + end_run=False, + ) + + task = kb.get_task(conn, tid) + assert task.status == "done", "terminal task reopened" + assert task.breaker_limit is None, "stamped a completed task" + assert kb.recompute_ready(conn) == 0 + + +def test_terminal_transitions_clear_worker_process_state(kanban_home, live_worker): + """No stale pgid residue: whatever clears worker_pid clears worker_pgid.""" + proc = live_worker() + with kb.connect() as conn: + for finisher in ("complete", "block"): + tid = kb.create_task(conn, title=f"residue-{finisher}", assignee="a") + kb.claim_task(conn, tid) + kb._set_worker_pid(conn, tid, proc.pid) + assert kb.get_task(conn, tid).worker_pgid is not None + run_id = kb.get_task(conn, tid).current_run_id + if finisher == "complete": + kb.complete_task(conn, tid, result="ok") + else: + kb.block_task( + conn, tid, reason="review-required: x", + expected_run_id=run_id, + ) + task = kb.get_task(conn, tid) + assert task.worker_pid is None + assert task.worker_pgid is None, f"{finisher} left a stale pgid" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def _fence_via_stale_reclaim(conn, title, leader_pid, pgid): + """Produce a real fenced-``ready`` row through the production path. + + ``detect_stale_running`` requeues the task and NULLs worker_pid / + worker_pgid / worker_identity, so the fence payload is the only record + of which process group is still writing. Anything that later re-probes + the worker has to read it from there. + """ + tid = kb.create_task(conn, title=title, assignee="a") + kb.claim_task(conn, tid) + kb._set_worker_pid(conn, tid, leader_pid, pgid=pgid) + old = int(time.time()) - 100_000 + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET started_at = ?, last_heartbeat_at = NULL " + "WHERE id = ?", + (old, tid), + ) + conn.execute( + "UPDATE task_runs SET started_at = ? WHERE id = ?", + (old, kb.get_task(conn, tid).current_run_id), + ) + assert kb.detect_stale_running(conn, stale_timeout_seconds=60) == [tid] + task = kb.get_task(conn, tid) + assert task.status == "ready" + assert (task.worker_pid, task.worker_pgid, task.worker_identity) == ( + None, None, None, + ), "fenced-ready rows carry the worker only in the fence payload" + assert kb.worker_fence(conn, tid) is not None + return tid + + +@pytest.mark.live_system_guard_bypass # signals only our own orphaned group +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_operator_reclaim_keeps_a_fence_over_a_live_orphan_group( + kanban_home, orphaned_group, no_sleep, +): + """Reclaim is an operator escape, not an override of physics. + + The fenced ``ready`` row has NULL worker columns by construction, so a + reclaim that probes those columns probes nothing, finds "no worker", and + hands the task to a second writer beside the live orphan group. The + fence payload is the source of truth for that probe. + """ + leader_pid, pgid, child_pid = orphaned_group() + with kb.connect() as conn: + tid = _fence_via_stale_reclaim(conn, "reclaim vs orphans", leader_pid, pgid) + assert kb.claim_task(conn, tid) is None + + kb.reclaim_task(conn, tid, reason="operator wants it back") + + assert kb.worker_fence(conn, tid) is not None, ( + "reclaim released a task next to a live orphan group" + ) + assert kb.claim_task(conn, tid) is None + spawned = [] + kb.dispatch_once(conn, spawn_fn=lambda *a, **k: spawned.append(a) or 1) + assert spawned == [] + + # Once the group really is gone, the same call releases it. + _kill_and_reap(child_pid) + kb.reclaim_task(conn, tid, reason="operator wants it back") + assert kb.worker_fence(conn, tid) is None + assert kb.claim_task(conn, tid) is not None + + +@pytest.mark.live_system_guard_bypass # signals only our own orphaned group +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_reclaim_opens_no_claim_window(kanban_home, orphaned_group, no_sleep): + """The fence must never be momentarily absent mid-reclaim. + + A dispatcher tick that lands between "clear the fence" and "decide + whether to re-record it" claims the task — the very duplicate-writer + state the fence exists to prevent. Probe first, then commit one + decision: this test claims from inside the probe. + """ + leader_pid, pgid, _child = orphaned_group() + mid_reclaim_claims = [] + real_terminate = kb._terminate_reclaimed_worker + + with kb.connect() as conn: + tid = _fence_via_stale_reclaim(conn, "no window", leader_pid, pgid) + + def _claim_during_probe(*args, **kwargs): + # Stands in for a concurrent dispatcher tick. + mid_reclaim_claims.append(kb.claim_task(conn, tid)) + return real_terminate(*args, **kwargs) + + try: + kb._terminate_reclaimed_worker = _claim_during_probe + kb.reclaim_task(conn, tid, reason="operator") + finally: + kb._terminate_reclaimed_worker = real_terminate + + assert mid_reclaim_claims, "probe never ran — test would prove nothing" + assert all(c is None for c in mid_reclaim_claims), ( + "a dispatcher could claim mid-reclaim" + ) + assert kb.worker_fence(conn, tid) is not None + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_operator_reclaim_releases_a_confirmed_dead_fence( + kanban_home, live_worker, no_sleep, +): + """The other half: nothing alive behind the fence → reclaim releases.""" + proc = live_worker() + pid, pgid = proc.pid, os.getpgid(proc.pid) + with kb.connect() as conn: + tid = kb.create_task(conn, title="dead fence", assignee="a") + kb.record_worker_fence( + conn, tid, + pid=pid, pgid=pgid, run_id=1, + claim_lock=kb._claimer_id(), reason="unit", + identity=kb._process_identity(pid), + ) + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET status = 'ready', claim_lock = NULL " + "WHERE id = ?", (tid,), + ) + assert kb.claim_task(conn, tid) is None # fenced by a live worker + + _kill_and_reap(pid) + assert kb.reclaim_task(conn, tid, reason="operator says go") is True + assert kb.worker_fence(conn, tid) is None + assert kb.claim_task(conn, tid) is not None + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_identity_null_fence_is_bounded_even_with_a_live_pid( + kanban_home, live_worker, no_sleep, +): + """Only a POSITIVE identity match earns an unbounded hold. + + A fence with no identity token (legacy row, or a platform without a + probe) cannot tell "our worker" from "the process that inherited its + number". Treating a live PID as proof made the TTL unreachable and let a + recycled pid strand the task forever. + """ + proc = live_worker() + pid, pgid = proc.pid, os.getpgid(proc.pid) + with kb.connect() as conn: + tid = kb.create_task(conn, title="unverifiable fence", assignee="a") + with kb.write_txn(conn): + conn.execute("UPDATE tasks SET status = 'ready' WHERE id = ?", (tid,)) + kb.record_worker_fence( + conn, tid, + pid=pid, pgid=pgid, run_id=1, + claim_lock=kb._claimer_id(), reason="unit", + identity=None, + ) + # Fresh: the evidence is weak but recent — still held. + assert kb.claim_task(conn, tid) is None + + fence = kb.worker_fence(conn, tid) + fence["since"] = int(time.time()) - kb.WORKER_FENCE_MAX_SECONDS - 1 + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET worker_fence = ? WHERE id = ?", + (json.dumps(fence), tid), + ) + + assert kb.claim_task(conn, tid) is not None, ( + "identity-NULL fence never reached its bound" + ) + assert _events(conn, tid, "worker_fence_expired") + + +def test_completion_clears_a_worker_fence(kanban_home, live_worker): + """A completed task is terminal: no fence rides along into ``done``.""" + proc = live_worker() + with kb.connect() as conn: + tid = kb.create_task(conn, title="completed with fence", assignee="a") + kb.claim_task(conn, tid) + kb._set_worker_pid(conn, tid, proc.pid) + kb.record_worker_fence( + conn, tid, + pid=proc.pid, pgid=os.getpgid(proc.pid), run_id=1, + claim_lock=kb._claimer_id(), reason="unit", + identity=kb._process_identity(proc.pid), + ) + kb.complete_task(conn, tid, result="shipped") + + task = kb.get_task(conn, tid) + assert task.status == "done" + assert kb.worker_fence(conn, tid) is None, "fence survived completion" + + +def test_degrades_safely_without_process_group_primitives( + kanban_home, live_worker, no_sleep, monkeypatch, +): + """Windows (and any platform without groups/identity) must fail closed. + + No ``os.killpg`` and no identity probe means: no group signalling, no + group-based liveness, and the pre-existing PID-only behaviour — never a + wider blast radius and never a fence we cannot resolve. + """ + proc = live_worker() + monkeypatch.delattr(kb.os, "killpg", raising=False) + monkeypatch.setattr(kb, "_process_identity", lambda pid: None) + # No identity probe at all — the documented boundary where a bare PID + # remains the only handle we have ever had on a worker. + monkeypatch.setattr(kb, "_identity_probe_supported", lambda: False) + + assert kb._process_group_alive(os.getpgid(proc.pid)) is False + + sent = [] + info = kb._terminate_reclaimed_worker( + proc.pid, kb._claimer_id(), + signal_fn=lambda *a: sent.append(a), + pgid=os.getpgid(proc.pid), + ) + assert info["group_signaled"] is False + assert {s[0] for s in sent} == {proc.pid}, "signalled beyond the pid" + + # A fence recorded on this platform still resolves: the pid probe alone + # decides, exactly as the pre-group behaviour did. + with kb.connect() as conn: + tid = kb.create_task(conn, title="no groups here", assignee="a") + with kb.write_txn(conn): + conn.execute("UPDATE tasks SET status = 'ready' WHERE id = ?", (tid,)) + kb.record_worker_fence( + conn, tid, + pid=proc.pid, pgid=os.getpgid(proc.pid), run_id=1, + claim_lock=kb._claimer_id(), reason="unit", + ) + assert kb.claim_task(conn, tid) is None # live pid holds it + _kill_and_reap(proc.pid) + assert kb.claim_task(conn, tid) is not None + + +# =========================================================================== +# Review round 3 — the fence must be part of the claim CAS, and no OS probe +# may run while the board's write lock is held +# =========================================================================== + + +@pytest.mark.live_system_guard_bypass # signals only our own orphaned group +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_claim_loses_to_a_fence_committed_after_its_gate( + kanban_home, orphaned_group, no_sleep, +): + """The fence check and the claim must be ONE atomic decision. + + Real ordering, two connections: the dispatcher reads an unfenced task + and starts claiming; before its CAS lands, the reaper commits + ``ready + worker_fence`` for a worker whose children are still writing. + A CAS that only guards ``status`` and ``claim_lock`` still wins — and the + task is claimed beside the live orphan group. + """ + leader_pid, pgid, child_pid = orphaned_group() + with kb.connect() as claimer_conn, kb.connect() as reaper_conn: + tid = kb.create_task(conn := claimer_conn, title="cas race", assignee="a") + kb.claim_task(conn, tid) + kb._set_worker_pid(conn, tid, leader_pid, pgid=pgid) + run_id = kb.get_task(conn, tid).current_run_id + lock = kb.get_task(conn, tid).claim_lock + + real_gate = kb._fence_blocks_claim + + def _gate_then_reaper_commits(gate_conn, gate_tid): + verdict = real_gate(gate_conn, gate_tid) + # The reaper tick lands here — on its own connection, fully + # committed — while this claimer is between gate and CAS. + kb.record_worker_fence( + reaper_conn, gate_tid, + pid=leader_pid, pgid=pgid, run_id=run_id, + claim_lock=lock, reason="requeued_worker_alive", + identity=None, + ) + with kb.write_txn(reaper_conn): + reaper_conn.execute( + "UPDATE tasks SET status = 'ready', claim_lock = NULL, " + "claim_expires = NULL, worker_pid = NULL, " + "worker_pgid = NULL, worker_identity = NULL, " + "current_run_id = NULL WHERE id = ?", + (gate_tid,), + ) + return verdict + + try: + kb._fence_blocks_claim = _gate_then_reaper_commits + claimed = kb.claim_task(conn, tid) + finally: + kb._fence_blocks_claim = real_gate + + assert claimed is None, "claimed beside a live orphan group" + assert kb.worker_fence(conn, tid) is not None + assert kb.get_task(conn, tid).status == "ready" + assert kb._process_group_alive(pgid), "precondition: orphans still live" + + # And the fence still resolves normally once the group is gone. + _kill_and_reap(child_pid) + assert kb.claim_task(conn, tid) is not None + + +def test_review_claim_is_fenced_too(kanban_home, live_worker, no_sleep): + """``review -> running`` is a claim as well, and needs the same gate.""" + proc = live_worker() + with kb.connect() as conn: + tid = kb.create_task(conn, title="review me", assignee="a") + with kb.write_txn(conn): + conn.execute("UPDATE tasks SET status = 'review' WHERE id = ?", (tid,)) + kb.record_worker_fence( + conn, tid, + pid=proc.pid, pgid=os.getpgid(proc.pid), run_id=1, + claim_lock=kb._claimer_id(), reason="unit", + identity=kb._process_identity(proc.pid), + ) + + assert kb.claim_review_task(conn, tid) is None + assert kb.get_task(conn, tid).status == "review" + + _kill_and_reap(proc.pid) + assert kb.claim_review_task(conn, tid) is not None + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_crash_detection_probes_outside_the_write_lock( + kanban_home, live_worker, no_sleep, +): + """``ps``/``/proc`` scans must not run while the board write lock is held. + + ``detect_crashed_workers`` opens a BEGIN IMMEDIATE over the whole board; + a process-group scan inside it blocks every other writer (workers + completing, heartbeats, other boards' ticks) for the duration of a + subprocess call. + """ + proc = live_worker() + probed_in_txn = [] + real_group_alive = kb._process_group_alive + real_leader_alive = kb._worker_leader_alive + + with kb.connect() as conn: + tid = kb.create_task(conn, title="probe placement", assignee="a") + kb.claim_task(conn, tid) + kb._set_worker_pid(conn, tid, proc.pid, pgid=os.getpgid(proc.pid)) + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET started_at = ? WHERE id = ?", + (int(time.time()) - 3600, tid), + ) + + def _watch(fn): + def _wrapped(*a, **k): + probed_in_txn.append(bool(conn.in_transaction)) + return fn(*a, **k) + return _wrapped + + try: + kb._process_group_alive = _watch(real_group_alive) + kb._worker_leader_alive = _watch(real_leader_alive) + kb.detect_crashed_workers(conn) + finally: + kb._process_group_alive = real_group_alive + kb._worker_leader_alive = real_leader_alive + + assert probed_in_txn, "no probe ran — the test would prove nothing" + assert not any(probed_in_txn), ( + "OS probe ran while the board write transaction was held" + ) + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_crash_detection_is_not_fooled_by_a_recycled_pid( + kanban_home, live_worker, no_sleep, +): + """A live PID that is no longer our worker must not suppress the crash. + + ``_pid_alive`` alone says "still running" and the task sits in + ``running`` forever with nothing behind it. + """ + proc = live_worker() # unrelated process now holding the recorded number + with kb.connect() as conn: + tid = kb.create_task(conn, title="recycled pid", assignee="a") + kb.claim_task(conn, tid) + kb._set_worker_pid(conn, tid, proc.pid, pgid=os.getpgid(proc.pid)) + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET started_at = ?, worker_identity = ? " + "WHERE id = ?", + (int(time.time()) - 3600, "some-older-process", tid), + ) + + assert kb.detect_crashed_workers(conn) == [tid] + assert kb.get_task(conn, tid).status in ("ready", "blocked") + assert proc.poll() is None, "signalled a process that is not ours" + + +def test_below_threshold_failure_does_not_stamp_a_completed_task(kanban_home): + """N4: the counter branch needs the same status guard as the trip branch. + + A worker that completes while the reaper is accounting a (below-limit) + failure must not come out of it with a failure counted against a task + that is already ``done``. + """ + with kb.connect() as conn: + tid = kb.create_task(conn, title="racy below-threshold", assignee="a") + kb.claim_task(conn, tid) + kb.complete_task(conn, tid, result="finished first") + + assert kb._record_task_failure( + conn, tid, + error="reaper thought this timed out", + outcome="timed_out", + failure_limit=5, # well below the trip threshold + release_claim=False, + end_run=False, + ) is False + + task = kb.get_task(conn, tid) + assert task.status == "done" + assert task.consecutive_failures == 0, "counted a failure on a done task" + assert task.last_failure_error is None + + +def test_archive_clears_a_worker_fence(kanban_home, live_worker): + """N5: archiving is terminal — no fence rides along.""" + proc = live_worker() + with kb.connect() as conn: + tid = kb.create_task(conn, title="archived with fence", assignee="a") + kb.record_worker_fence( + conn, tid, + pid=proc.pid, pgid=os.getpgid(proc.pid), run_id=1, + claim_lock=kb._claimer_id(), reason="unit", + identity=kb._process_identity(proc.pid), + ) + assert kb.archive_task(conn, tid) is True + assert kb.worker_fence(conn, tid) is None + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_unverifiable_pid_widens_to_nothing_beyond_itself( + kanban_home, live_worker, no_sleep, +): + """Legacy rows carry a PID and no identity. On a platform that CAN + identify processes, that number is not evidence of *which* process is + there — so the blast radius stays exactly that one number. No process + group (the widest radius we have, and the one that needs proof), and no + unbounded fence. + + Signalling the pid itself is still right: it is the only handle we ever + had on that worker, and declining leaves a live writer to be carried by + a fence that expires. A recorded identity that MISMATCHES is the case + where we signal nothing at all — see + ``test_group_signal_requires_verified_leader_identity``. + """ + proc = live_worker() + pgid = os.getpgid(proc.pid) + + sent = [] + group_calls = [] + info = kb._terminate_reclaimed_worker( + proc.pid, kb._claimer_id(), + signal_fn=lambda *a: sent.append(a), + killpg_fn=lambda *a: group_calls.append(a), + pgid=pgid, + identity=None, + ) + assert group_calls == [], "blasted a group we cannot prove is ours" + assert info["group_signaled"] is False + assert {s[0] for s in sent} == {proc.pid}, "signalled beyond the pid" + assert info["still_alive"] is True + assert info["leader_alive"] is True, ( + "a live worker we could not kill must hold, not fall to a bounded fence" + ) + assert proc.poll() is None + + +# =========================================================================== +# Review round 4 — clearing a fence is a compare-and-swap, and a pgid is +# only recorded when it identifies the worker's own group +# =========================================================================== + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_releasing_a_fence_cannot_delete_a_newer_one( + kanban_home, live_worker, no_sleep, +): + """Clearing must CAS against the exact fence that was evaluated. + + The claim gate decides "this fence is releasable" against a snapshot, + then writes. If a reaper records a NEW fence in between — a different + worker, still alive — a blind ``worker_fence = NULL`` by task id deletes + it, and the task is claimable beside that live worker. + """ + replacement = live_worker() + with kb.connect() as conn, kb.connect() as reaper_conn: + tid = kb.create_task(conn, title="fence swap", assignee="a") + with kb.write_txn(conn): + conn.execute("UPDATE tasks SET status = 'ready' WHERE id = ?", (tid,)) + # F1: describes a worker that is already gone, so it is releasable. + kb.record_worker_fence( + conn, tid, + pid=999_999_000, pgid=999_999_000, run_id=1, + claim_lock=kb._claimer_id(), reason="f1", + identity="long-gone", + ) + f1 = kb.worker_fence(conn, tid) + + real_reason = kb._fence_release_reason + + def _release_then_swap(fence, now): + verdict = real_reason(fence, now) + if fence.get("reason") == "f1": + # A reaper fences the task again — for a worker that IS alive. + kb.record_worker_fence( + reaper_conn, tid, + pid=replacement.pid, + pgid=os.getpgid(replacement.pid), + run_id=2, + claim_lock=kb._claimer_id(), reason="f2", + identity=kb._process_identity(replacement.pid), + ) + return verdict + + try: + kb._fence_release_reason = _release_then_swap + claimed = kb.claim_task(conn, tid) + finally: + kb._fence_release_reason = real_reason + + surviving = kb.worker_fence(conn, tid) + assert surviving is not None, "a stale release deleted the newer fence" + assert surviving["reason"] == "f2" + assert surviving != f1 + assert claimed is None, "claimed beside the newly fenced live worker" + assert kb.claim_task(conn, tid) is None + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_pgid_is_recorded_only_for_a_group_leading_worker(kanban_home, no_sleep): + """A pgid is worth persisting only when it IS the worker's own group. + + Production spawns with ``start_new_session=True``, so the worker leads + its group and pgid == pid. Anything else (a worker started without a new + session, an inherited group) means the recorded id names the *gateway's* + group — signalling it would take down the dispatcher and every sibling + worker. Store nothing rather than that. + """ + shared = subprocess.Popen( # noqa: S603 - fixed argv + [sys.executable, "-c", "import time; time.sleep(120)"], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) # deliberately NO start_new_session: shares our process group + try: + assert os.getpgid(shared.pid) != shared.pid, "precondition: not a leader" + with kb.connect() as conn: + tid = kb.create_task(conn, title="shared group", assignee="a") + kb.claim_task(conn, tid) + kb._set_worker_pid(conn, tid, shared.pid) + + task = kb.get_task(conn, tid) + assert task.worker_pid == shared.pid + assert task.worker_pgid is None, ( + "persisted the gateway's own process group id" + ) + + # And nothing downstream can target that shared group. + group_calls = [] + kb._terminate_reclaimed_worker( + task.worker_pid, task.claim_lock, + signal_fn=lambda *a: None, + killpg_fn=lambda *a: group_calls.append(a), + pgid=task.worker_pgid, + identity=task.worker_identity, + ) + assert group_calls == [], "signalled a shared process group" + finally: + try: + os.kill(shared.pid, signal.SIGKILL) + shared.wait(timeout=5) + except (ProcessLookupError, OSError, subprocess.TimeoutExpired): + pass + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_session_leading_worker_still_records_its_pgid(kanban_home, live_worker): + """The production shape is unaffected: a session leader keeps its pgid.""" + proc = live_worker() + with kb.connect() as conn: + tid = kb.create_task(conn, title="normal spawn", assignee="a") + kb.claim_task(conn, tid) + kb._set_worker_pid(conn, tid, proc.pid) + task = kb.get_task(conn, tid) + assert task.worker_pgid == os.getpgid(proc.pid) == proc.pid + assert task.worker_identity is not None + + +# =========================================================================== +# Review round 5 — a refused reclaim must mutate nothing, and group +# leadership is never assumed +# =========================================================================== + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_reclaim_refused_by_a_newer_fence_mutates_nothing( + kanban_home, live_worker, no_sleep, +): + """A reclaim that cannot complete must not half-complete. + + The fence is read before the OS probe and the writes happen after it. If + a reaper records a different fence in between, bailing out *after* the + status/claim/worker columns have already been reset commits a partial + reclaim: the task is released, no ``reclaimed`` event is emitted, the run + is never finalized, and ``current_run_id`` points at a run row that stays + open forever. Either the whole reclaim lands or none of it does. + """ + replacement = live_worker() + with kb.connect() as conn, kb.connect() as reaper_conn: + tid = kb.create_task(conn, title="atomic reclaim", assignee="a") + claimed = kb.claim_task(conn, tid) + kb._set_worker_pid(conn, tid, 999_999_001) + before = kb.get_task(conn, tid) + run_id = before.current_run_id + # F1: a fence for a worker that is long gone (releasable). + kb.record_worker_fence( + conn, tid, + pid=999_999_000, pgid=999_999_000, run_id=run_id, + claim_lock=claimed.claim_lock, reason="f1", identity="long-gone", + ) + + real_terminate = kb._terminate_reclaimed_worker + + def _swap_fence_mid_probe(*args, **kwargs): + # A reaper tick lands between reclaim's pre-read and its writes, + # fencing the task for a worker that IS alive. + kb.record_worker_fence( + reaper_conn, tid, + pid=replacement.pid, pgid=os.getpgid(replacement.pid), + run_id=run_id, claim_lock=claimed.claim_lock, reason="f2", + identity=kb._process_identity(replacement.pid), + ) + return real_terminate(*args, **kwargs) + + try: + kb._terminate_reclaimed_worker = _swap_fence_mid_probe + result = kb.reclaim_task(conn, tid, reason="operator") + finally: + kb._terminate_reclaimed_worker = real_terminate + + assert result is False + after = kb.get_task(conn, tid) + assert after.status == before.status == "running", "partial reclaim" + assert after.claim_lock == before.claim_lock + assert after.worker_pid == before.worker_pid + assert after.current_run_id == run_id, "stranded the run pointer" + run = kb.get_run(conn, run_id) + assert run.ended_at is None and run.outcome is None, "run left half-closed" + assert _events(conn, tid, "reclaimed") == [], ( + "claimed a reclaim happened when nothing did" + ) + + surviving = kb.worker_fence(conn, tid) + assert surviving is not None and surviving["reason"] == "f2" + assert kb.claim_task(conn, tid) is None + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_unknown_process_group_is_never_invented(kanban_home, no_sleep, monkeypatch): + """If we cannot ask the OS for the group, we do not guess one. + + Synthesizing ``pgid = pid`` on a failed ``getpgid`` passes the + "worker leads its group" check without any proof that it does — the + exact assumption that check exists to stop. + """ + def _boom(_pid): + raise ProcessLookupError("gone before we looked") + + monkeypatch.setattr(kb.os, "getpgid", _boom) + + with kb.connect() as conn: + tid = kb.create_task(conn, title="unknowable group", assignee="a") + claimed = kb.claim_task(conn, tid) + kb._set_worker_pid(conn, tid, 999_999_002) + + task = kb.get_task(conn, tid) + assert task.worker_pid == 999_999_002 + assert task.worker_pgid is None, "invented a process group" + + group_calls = [] + kb._terminate_reclaimed_worker( + task.worker_pid, claimed.claim_lock, + signal_fn=lambda *a: None, + killpg_fn=lambda *a: group_calls.append(a), + pgid=task.worker_pgid, + identity=task.worker_identity, + ) + assert group_calls == [] + + +# =========================================================================== +# Review round 5 — an identity-less LIVE worker must be killed, not fenced +# +# Failing closed on the *group* (never blast a pgid we cannot prove is ours) +# had been over-applied to the *pid*: a legacy or transiently-unidentified +# row whose worker was still running got no signal at all, only a fence — +# and a fence with no identity token is bounded by WORKER_FENCE_MAX_SECONDS. +# The live worker therefore aged out of its own fence and a replacement +# claim landed beside it: exactly the ``t_80a3542a`` duplicate-writer state. +# =========================================================================== + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_identityless_live_worker_is_terminated_not_left_to_age_out( + kanban_home, live_worker, no_sleep, +): + """No identity token is not a reason to leave a live worker running. + + A bare PID we recorded ourselves is weak evidence of *which* process is + there, but the pre-existing behaviour — signal the pid — stays the right + call while the number is still alive: the alternative is a fence that + expires under a worker that never stopped writing. The blast radius stays + the single pid; the process GROUP still requires a proven identity. + """ + proc = live_worker() + pgid = os.getpgid(proc.pid) + + group_calls = [] + info = kb._terminate_reclaimed_worker( + proc.pid, kb._claimer_id(), + killpg_fn=lambda *a: group_calls.append(a), + pgid=pgid, + identity=None, + ) + + assert info["may_signal"] is True, "declined to signal a live worker" + assert info["termination_attempted"] is True + assert group_calls == [], "blasted a group we cannot prove is ours" + assert info["group_signaled"] is False + assert info["terminated"] is True + assert info["still_alive"] is False + proc.wait(timeout=5) + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_identityless_survivor_holds_the_claim_instead_of_fencing( + kanban_home, live_worker, no_sleep, +): + """A live identity-less leader that shrugs off the kill is a HOLD. + + ``_worker_survived_termination`` is what keeps the claim (and so keeps + the dispatcher from spawning a second writer). Reporting an unsignalled, + unverifiable-but-live leader as "not alive" routed this state onto the + bounded fence path, which resolves itself after an hour regardless of + the process. Holding is correct and self-correcting: the next tick + retries the kill. + """ + proc = live_worker() + sent = [] + info = kb._terminate_reclaimed_worker( + proc.pid, kb._claimer_id(), + signal_fn=lambda *a: sent.append(a), + pgid=os.getpgid(proc.pid), + identity=None, + ) + + assert {s[0] for s in sent} == {proc.pid}, "signalled beyond the pid" + assert info["sigkill"] is True, "never escalated past SIGTERM" + assert info["leader_alive"] is True + assert info["still_alive"] is True + assert info["terminated"] is False + assert kb._worker_survived_termination(info) is True, ( + "a live worker we could not kill must hold its claim, not age out" + ) + assert proc.poll() is None + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups") +def test_operator_reclaim_pins_a_live_identityless_leader( + kanban_home, live_worker, no_sleep, +): + """The operator path fences rather than holds — so the fence must bind. + + ``reclaim_task`` honours the operator's release even for a worker that + survived termination, and records a fence to stop the duplicate writer. + With no identity on the row that fence was weakly evidenced and expired + after ``WORKER_FENCE_MAX_SECONDS`` while the worker was still running. + Pinning the identity observed at termination time makes the hold provable + (so it cannot age out under a live worker) and still self-releasing (a + recycled pid reads as ``worker_identity_changed``). + """ + proc = live_worker() + pgid = os.getpgid(proc.pid) + with kb.connect() as conn: + tid = kb.create_task(conn, title="legacy live worker", assignee="a") + kb.claim_task(conn, tid) + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET worker_pid = ?, worker_pgid = ?, " + "worker_identity = NULL WHERE id = ?", + (proc.pid, pgid, tid), + ) + + # Signals swallowed: the worker outlives the operator's reclaim. + assert kb.reclaim_task( + conn, tid, reason="operator", signal_fn=lambda *a: None, + ) is True + + fence = kb.worker_fence(conn, tid) + assert fence is not None, "released a live worker with no fence" + assert fence["identity"] == kb._process_identity(proc.pid), ( + "fenced a live leader on nothing but a recyclable number" + ) + + # Age it far past the weak-evidence bound: a PROVEN live leader is + # not on a clock. + fence["since"] = int(time.time()) - kb.WORKER_FENCE_MAX_SECONDS * 10 + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET worker_fence = ? WHERE id = ?", + (json.dumps(fence), tid), + ) + assert kb._fence_release_reason(fence, int(time.time())) is None + assert kb.claim_task(conn, tid) is None, ( + "a live worker aged out of its own fence: duplicate writers" + ) + + # And it still resolves on its own once the worker is really gone. + _kill_and_reap(proc.pid) + assert kb.claim_task(conn, tid) is not None diff --git a/tests/hermes_cli/test_kanban_terminal_hold.py b/tests/hermes_cli/test_kanban_terminal_hold.py new file mode 100644 index 0000000000000..aac06d87e74a1 --- /dev/null +++ b/tests/hermes_cli/test_kanban_terminal_hold.py @@ -0,0 +1,549 @@ +"""A terminal hold on a kanban task must bind at every promotion door. + +Two holds are *status-independent* decisions about a task, not properties of +the column it happens to sit in: + +* **sticky block** — a worker/operator ``kanban_block`` (or the unblock-loop + breaker's ``block_loop_detected`` escalation) said "a human decides next". +* **breaker trip** — ``_record_task_failure`` recorded ``gave_up`` and + persisted the limit it tripped against. + +``recompute_ready`` honoured both, but only for rows it found in ``blocked``. +Every other door into the work pool re-derived its own, narrower rule: + +* ``claim_task`` had no hold check at all, so any writer that put a held row + in ``ready`` (a racy promote, a stale-claim release, an old dump, a + dependency refresh) got a worker spawned on the next tick. +* ``specify_triage_task`` / ``decompose_triage_task`` gated only on the + ``block_loop_detected`` escalation, so a sticky-blocked or gave-up card + parked in ``triage`` was promoted straight back to ``todo``. +* ``reclaim_task`` flipped ``blocked -> ready`` and cleared the breaker + decision, reviving a task nobody had unblocked. + +The hold is released by exactly two explicit operator acts — ``unblock_task`` +and ``promote_task`` — and by a successful completion. Everything else +(recompute, restart, reclaim, dependency refresh, re-specify) leaves it +standing. + +Separately: a spawn failure on a task claimed out of the ``review`` column +requeued it to ``ready``, dropping it out of review and back into the +implementation pool where the next dispatcher tick spawns an ordinary worker +instead of the forced ``sdlc-review`` agent. +""" + +from __future__ import annotations + +import json +import time +from pathlib import Path + +import pytest + +from hermes_cli import kanban_db as kb + + +@pytest.fixture +def kanban_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """Isolated HERMES_HOME with an empty kanban DB.""" + home = tmp_path / ".hermes" + home.mkdir() + monkeypatch.setenv("HERMES_HOME", str(home)) + monkeypatch.setattr(Path, "home", lambda: tmp_path) + kb.init_db() + return home + + +# --------------------------------------------------------------------------- +# helpers — build the two hold shapes through the real code paths +# --------------------------------------------------------------------------- + + +def _sticky_blocked(conn, *, title: str = "needs a human", **kwargs) -> str: + """A task a worker explicitly blocked for review.""" + tid = kb.create_task(conn, title=title, **kwargs) + kb.claim_task(conn, tid) + assert kb.block_task( + conn, tid, + reason="review-required: verify before continuing", + kind="needs_input", + expected_run_id=kb.get_task(conn, tid).current_run_id, + ) + assert kb.get_task(conn, tid).status == "blocked" + return tid + + +def _gave_up(conn, *, title: str = "keeps failing", **kwargs) -> str: + """A task the circuit breaker gave up on (spawn failures).""" + tid = kb.create_task(conn, title=title, **kwargs) + kb.claim_task(conn, tid) + assert kb._record_spawn_failure(conn, tid, "boom", failure_limit=1) is True + assert kb.get_task(conn, tid).status == "blocked" + assert kb.recorded_breaker_limit(conn, tid) is not None + return tid + + +def _force_status(conn, task_id: str, status: str) -> None: + """Put a row in ``status`` behind the API's back. + + Stands in for every writer that can land a held row somewhere it does + not belong: a racy promote, a restored dump, a dependency refresh, an + operator's manual SQL. + """ + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET status = ? WHERE id = ?", (status, task_id), + ) + + +# --------------------------------------------------------------------------- +# claim_task — the last gate before a worker is spawned +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("make_held", [_sticky_blocked, _gave_up]) +def test_claim_task_refuses_a_held_task_parked_in_ready(kanban_home, make_held): + """A held row that reaches ``ready`` must not be claimable. + + ``recompute_ready`` is not the only writer of ``status='ready'``, so it + cannot be the only place the hold is enforced. ``claim_task`` is the + single door into ``running`` — it must re-check, exactly as it already + re-checks parent completion. + """ + with kb.connect() as conn: + tid = make_held(conn) + _force_status(conn, tid, "ready") + + assert kb.claim_task(conn, tid) is None + # And it is demoted back to where a held task belongs, so the next + # tick doesn't re-litigate the same decision. + assert kb.get_task(conn, tid).status == "blocked" + + +@pytest.mark.parametrize("make_held", [_sticky_blocked, _gave_up]) +def test_claim_review_task_refuses_a_held_task(kanban_home, make_held): + """Same gate on the review column's claim door — but no demotion. + + ``claim_task`` demotes a held row out of ``ready`` because ``ready`` is + the active work pool and ``recompute_ready`` would keep re-examining it. + ``review`` is neither: ``recompute_ready`` only ever promotes out of + ``todo``/``blocked``, so refusing the claim already binds the hold. + + Demoting here would be a one-way door. ``unblock_task`` restores + ``ready`` (or ``todo`` behind open parents) and never ``review``, so the + card would come back as ordinary implementation work with its PR already + open — the exact failure ``_claim_source_status`` exists to prevent. + """ + with kb.connect() as conn: + tid = make_held(conn) + _force_status(conn, tid, "review") + + assert kb.claim_review_task(conn, tid) is None + assert kb.get_task(conn, tid).status == "review" + # Still not promotable by any automatic door, and still not claimable. + assert kb.recompute_ready(conn) == 0 + assert kb.claim_review_task(conn, tid) is None + assert kb.get_task(conn, tid).status == "review" + + +def test_claim_task_still_works_for_an_unheld_ready_task(kanban_home): + """The gate must not cost an ordinary task its claim.""" + with kb.connect() as conn: + tid = kb.create_task(conn, title="ordinary work") + _force_status(conn, tid, "ready") + + claimed = kb.claim_task(conn, tid) + assert claimed is not None + assert kb.get_task(conn, tid).status == "running" + + +def test_below_limit_spawn_failure_stays_claimable(kanban_home): + """A failure that did NOT trip the breaker is not a hold. + + ``_record_task_failure`` requeues to ``ready`` with the counter bumped + and no ``gave_up``; that task must still be retried. + """ + with kb.connect() as conn: + tid = kb.create_task(conn, title="transient failure") + kb.claim_task(conn, tid) + assert kb._record_spawn_failure(conn, tid, "flaky", failure_limit=3) is False + assert kb.get_task(conn, tid).status == "ready" + assert kb.recorded_breaker_limit(conn, tid) is None + + assert kb.claim_task(conn, tid) is not None + + +# --------------------------------------------------------------------------- +# recompute_ready — restart / dependency refresh +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("make_held", [_sticky_blocked, _gave_up]) +def test_recompute_ready_holds_a_held_todo_row(kanban_home, make_held): + """A held row parked in ``todo`` must not be promoted either. + + ``recompute_ready`` selects ``todo`` and ``blocked`` and only checked + the hold on the ``blocked`` branch — so anything that moved a held card + to ``todo`` (specify, a dependency-flavoured re-block, manual SQL) got + it promoted on the very next tick. + """ + with kb.connect() as conn: + tid = make_held(conn) + _force_status(conn, tid, "todo") + + assert kb.recompute_ready(conn) == 0 + assert kb.get_task(conn, tid).status != "ready" + + +def test_held_task_survives_a_restart_with_a_laxer_limit(kanban_home): + """A fresh connection + a laxer configured limit must not free it.""" + with kb.connect() as conn: + tid = _gave_up(conn) + + # "Restart": new connection, dispatcher configured with a bigger budget. + with kb.connect() as conn: + for _ in range(3): + assert kb.recompute_ready(conn, failure_limit=99) == 0 + assert kb.get_task(conn, tid).status == "blocked" + + +def test_dependency_refresh_does_not_free_a_held_child(kanban_home): + """Parents completing is not an unblock. + + The dependency-refresh path exists so a task blocked purely on a parent + frees itself. A task with its own terminal hold must stay put even when + every parent lands ``done``. + """ + with kb.connect() as conn: + parent = kb.create_task(conn, title="parent") + child = _sticky_blocked(conn, title="held child") + kb.link_tasks(conn, parent, child) + _force_status(conn, parent, "done") + + assert kb.recompute_ready(conn) == 0 + assert kb.get_task(conn, child).status == "blocked" + + +# --------------------------------------------------------------------------- +# triage promotion doors +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("make_held", [_sticky_blocked, _gave_up]) +def test_specify_triage_task_refuses_a_held_card(kanban_home, make_held): + """``specify`` must not launder a held card into ``todo``. + + It already refuses the ``block_loop_detected`` escalation; a plain + sticky block and a recorded give-up are the same class of human hold. + """ + with kb.connect() as conn: + tid = make_held(conn) + _force_status(conn, tid, "triage") + + assert kb.specify_triage_task( + conn, tid, title="rescoped", author="operator", + ) is False + assert kb.get_task(conn, tid).status == "triage" + + +@pytest.mark.parametrize("make_held", [_sticky_blocked, _gave_up]) +def test_decompose_triage_task_refuses_a_held_card(kanban_home, make_held): + """Neither may auto-decompose fan a held card out into the work pool.""" + with kb.connect() as conn: + tid = make_held(conn) + _force_status(conn, tid, "triage") + + assert kb.decompose_triage_task( + conn, tid, + root_assignee=None, + children=[{"title": "step one"}, {"title": "step two"}], + ) is None + assert kb.get_task(conn, tid).status == "triage" + assert kb.list_tasks(conn, limit=100) and len( + [t for t in kb.list_tasks(conn, limit=100)] + ) == 1 + + +def test_specify_triage_task_still_promotes_an_unheld_card(kanban_home): + """Ordinary triage flow is untouched.""" + with kb.connect() as conn: + tid = kb.create_task(conn, title="fresh idea", triage=True) + assert kb.get_task(conn, tid).status == "triage" + + assert kb.specify_triage_task( + conn, tid, title="scoped idea", author="operator", + ) is True + # No open parents, and specify runs a promotion pass on the way out. + assert kb.get_task(conn, tid).status == "ready" + + +# --------------------------------------------------------------------------- +# reclaim — an operator recovery, not an unblock +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("make_held", [_sticky_blocked, _gave_up]) +def test_reclaim_does_not_revive_a_held_task(kanban_home, make_held): + """Reclaim releases a worker; it does not overrule a terminal hold. + + A held row that still carries a fence (the requeue path records one + when a process group outlived its kill) passes reclaim's "is there + anything to release?" gate — and the reclaim then flipped it to + ``ready`` and cleared the breaker decision on the way out. + """ + with kb.connect() as conn: + tid = make_held(conn) + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET worker_fence = ? WHERE id = ?", + ( + json.dumps({ + "pid": 999999, "pgid": 999999, "run_id": 1, + "claim_lock": "gone", "identity": None, + "recorded_at": int(time.time()), + "reason": "unconfirmed_termination", + }), + tid, + ), + ) + + kb.reclaim_task(conn, tid, reason="operator poke", signal_fn=lambda *a: None) + + assert kb.get_task(conn, tid).status == "blocked" + assert kb.claim_task(conn, tid) is None + assert kb.recompute_ready(conn) == 0 + + +def test_reclaim_does_not_clear_a_trip_recorded_only_in_the_event_log( + kanban_home, +): + """The two representations of "the trip was reset" must agree. + + ``recorded_breaker_limit`` reads ``tasks.breaker_limit`` and falls back + to the event log for boards written before that column existed (or + restored from such a dump). Keeping the *column* across a reclaim is + therefore only half the decision: if ``"reclaimed"`` still counts as a + reset in the event-log fallback, the reclaim's own event clears the trip + a tick later and the task promotes itself — the same resurrection by a + slower route, on exactly the boards the fallback exists for. + + A reclaim recovers a worker. It is not an operator decision about the + retry budget in either representation. + """ + with kb.connect() as conn: + tid = _gave_up(conn) + # A board whose trip survives only as the ``gave_up`` event. + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET breaker_limit = NULL, worker_fence = ? " + "WHERE id = ?", + ( + json.dumps({ + "pid": 999999, "pgid": 999999, "run_id": 1, + "claim_lock": "gone", "identity": None, + "recorded_at": int(time.time()), + "reason": "unconfirmed_termination", + }), + tid, + ), + ) + assert kb.recorded_breaker_limit(conn, tid) is not None + assert kb.terminal_hold_reason(conn, tid) == "breaker_trip" + + kb.reclaim_task(conn, tid, reason="operator poke", signal_fn=lambda *a: None) + + assert kb.terminal_hold_reason(conn, tid) == "breaker_trip" + assert kb.recompute_ready(conn) == 0 + assert kb.get_task(conn, tid).status == "blocked" + assert kb.claim_task(conn, tid) is None + + +def test_unblock_still_clears_a_trip_recorded_only_in_the_event_log( + kanban_home, +): + """The operator escapes must keep working on those same boards.""" + with kb.connect() as conn: + tid = _gave_up(conn) + with kb.write_txn(conn): + conn.execute( + "UPDATE tasks SET breaker_limit = NULL WHERE id = ?", (tid,), + ) + assert kb.terminal_hold_reason(conn, tid) == "breaker_trip" + + assert kb.unblock_task(conn, tid) is True + assert kb.terminal_hold_reason(conn, tid) is None + assert kb.claim_task(conn, tid) is not None + + +def test_reclaim_still_releases_a_running_worker(kanban_home): + """The recovery path itself keeps working for an unheld task.""" + with kb.connect() as conn: + tid = kb.create_task(conn, title="stuck worker") + kb.claim_task(conn, tid) + + assert kb.reclaim_task( + conn, tid, reason="hallucinating", signal_fn=lambda *a: None, + ) is True + assert kb.get_task(conn, tid).status == "ready" + + +# --------------------------------------------------------------------------- +# the two explicit operator escapes still work +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("make_held", [_sticky_blocked, _gave_up]) +def test_unblock_frees_a_held_task(kanban_home, make_held): + with kb.connect() as conn: + tid = make_held(conn) + + assert kb.unblock_task(conn, tid) is True + assert kb.get_task(conn, tid).status == "ready" + assert kb.claim_task(conn, tid) is not None + + +@pytest.mark.parametrize("make_held", [_sticky_blocked, _gave_up]) +def test_manual_promote_frees_a_held_task(kanban_home, make_held): + """``hermes kanban promote`` is a deliberate operator override. + + It already clears the breaker decision and the worker fence; the claim + gate must read it as a release too, or a promoted card would be demoted + straight back to ``blocked`` by the very next tick and never dispatch. + """ + with kb.connect() as conn: + tid = make_held(conn) + + ok, err = kb.promote_task(conn, tid, actor="operator", reason="looked at it") + assert (ok, err) == (True, None) + assert kb.get_task(conn, tid).status == "ready" + + assert kb.recompute_ready(conn) == 0 # already ready, nothing to do + assert kb.get_task(conn, tid).status == "ready" + assert kb.claim_task(conn, tid) is not None + + +def test_parent_gated_todo_still_promotes(kanban_home): + """The ordinary dependency promotion is untouched.""" + with kb.connect() as conn: + parent = kb.create_task(conn, title="parent") + child = kb.create_task(conn, title="child", parents=(parent,)) + assert kb.get_task(conn, child).status == "todo" + + assert kb.recompute_ready(conn) == 0 + assert kb.get_task(conn, child).status == "todo" + + _force_status(conn, parent, "done") + assert kb.recompute_ready(conn) == 1 + assert kb.get_task(conn, child).status == "ready" + assert kb.claim_task(conn, child) is not None + + +# --------------------------------------------------------------------------- +# goal_mode +# --------------------------------------------------------------------------- + + +def test_goal_mode_budget_block_is_terminal(kanban_home): + """A goal-loop worker that exhausts its turn budget sticky-blocks. + + That card must not come back through any automatic door — the goal loop + would otherwise re-spawn against the same exhausted budget forever. + """ + with kb.connect() as conn: + tid = _sticky_blocked( + conn, title="ralph loop", goal_mode=True, goal_max_turns=3, + ) + assert kb.get_task(conn, tid).goal_mode is True + + for _ in range(3): + assert kb.recompute_ready(conn) == 0 + _force_status(conn, tid, "ready") + assert kb.claim_task(conn, tid) is None + assert kb.get_task(conn, tid).status == "blocked" + + # The operator escape still resumes it. + assert kb.unblock_task(conn, tid) is True + assert kb.claim_task(conn, tid) is not None + + +# --------------------------------------------------------------------------- +# terminal columns stay terminal +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("terminal_status", ["done", "archived"]) +def test_completed_and_superseded_tasks_stay_unclaimable( + kanban_home, terminal_status, +): + """A finished or superseded card is never promoted or claimed.""" + with kb.connect() as conn: + tid = kb.create_task(conn, title="finished work") + _force_status(conn, tid, terminal_status) + + assert kb.recompute_ready(conn) == 0 + assert kb.claim_task(conn, tid) is None + assert kb.claim_review_task(conn, tid) is None + assert kb.get_task(conn, tid).status == terminal_status + + +def test_completion_clears_the_hold_for_a_later_rerun(kanban_home): + """A success is the third release: the decision it reversed is history.""" + with kb.connect() as conn: + tid = _gave_up(conn) + assert kb.unblock_task(conn, tid) is True + kb.claim_task(conn, tid) + kb.complete_task(conn, tid, summary="done at last") + + assert kb.recorded_breaker_limit(conn, tid) is None + _force_status(conn, tid, "ready") + assert kb.claim_task(conn, tid) is not None + + +# --------------------------------------------------------------------------- +# review column requeue +# --------------------------------------------------------------------------- + + +def test_review_spawn_failure_requeues_to_review(kanban_home): + """A spawn failure on a review claim belongs back in ``review``. + + The dispatcher force-loads the ``sdlc-review`` skill for tasks it claims + out of ``review``. Requeueing to ``ready`` drops that: the next tick + picks the card up as ordinary work and spawns a plain implementation + worker against a task whose PR is already open. + """ + with kb.connect() as conn: + tid = kb.create_task(conn, title="PR awaiting review", assignee="reviewer") + _force_status(conn, tid, "review") + claimed = kb.claim_review_task(conn, tid) + assert claimed is not None + + assert kb._record_spawn_failure( + conn, tid, "workspace: no such worktree", failure_limit=3, + ) is False + assert kb.get_task(conn, tid).status == "review" + + +def test_review_spawn_failure_still_trips_the_breaker(kanban_home): + """The requeue column must not cost the review card its breaker.""" + with kb.connect() as conn: + tid = kb.create_task(conn, title="PR awaiting review", assignee="reviewer") + _force_status(conn, tid, "review") + assert kb.claim_review_task(conn, tid) is not None + + assert kb._record_spawn_failure( + conn, tid, "boom", failure_limit=1, + ) is True + assert kb.get_task(conn, tid).status == "blocked" + assert kb.recorded_breaker_limit(conn, tid) is not None + + +def test_ready_spawn_failure_still_requeues_to_ready(kanban_home): + """The ordinary spawn-failure requeue is unchanged.""" + with kb.connect() as conn: + tid = kb.create_task(conn, title="ordinary work") + assert kb.claim_task(conn, tid) is not None + + assert kb._record_spawn_failure( + conn, tid, "transient", failure_limit=3, + ) is False + assert kb.get_task(conn, tid).status == "ready" diff --git a/tests/hermes_cli/test_stress_isolation_guard.py b/tests/hermes_cli/test_stress_isolation_guard.py new file mode 100644 index 0000000000000..ab641294491a2 --- /dev/null +++ b/tests/hermes_cli/test_stress_isolation_guard.py @@ -0,0 +1,463 @@ +"""The destructive kanban stress scripts must never reach a live board. + +Incident: a ``tests/stress/test_concurrency*.py`` run set a temporary +``HERMES_HOME`` but left the ambient ``HERMES_KANBAN_DB`` in place. That env +var outranks ``HERMES_HOME`` in :func:`kanban_db.kanban_db_path` (it is +resolution step 1, the home is step 3), so every "isolated" synthetic worker +claimed, failed and completed cards on the real default board. + +``HERMES_HOME`` alone is therefore not isolation. The shared guard under test +is fail-closed: a stress entry point must *prove* its resolved DB is a fresh +file inside a sandbox home it just created, or refuse to run. + +These tests exercise the guard entirely against ``tmp_path`` — with +``tempfile.tempdir`` repointed there, so even the guard's own ``mkdtemp`` +lands under pytest's cleanup. No real DB is opened and **no stress script is +executed**. +""" + +from __future__ import annotations + +import importlib.util +import os +import sys +import tempfile +from pathlib import Path +from types import ModuleType + +import pytest + +REPO_ROOT = Path(__file__).resolve().parents[2] +STRESS_DIR = REPO_ROOT / "tests" / "stress" +GUARD_PATH = STRESS_DIR / "_isolation.py" + +#: Every destructive concurrency entry point that must be wired to the guard. +CONCURRENCY_SCRIPTS = ( + "test_concurrency.py", + "test_concurrency_mixed.py", + "test_concurrency_parent_gate.py", + "test_concurrency_reclaim_race.py", +) + + +def _load_guard() -> ModuleType: + """Import ``tests/stress/_isolation.py`` by path. + + ``tests/stress`` is deliberately not a package (its conftest sets + ``collect_ignore_glob = ["*.py"]`` so pytest never collects the scripts), + so this cannot be a plain import. + """ + name = "hermes_stress_isolation_under_test" + spec = importlib.util.spec_from_file_location(name, GUARD_PATH) + assert spec and spec.loader, f"cannot load guard from {GUARD_PATH}" + module = importlib.util.module_from_spec(spec) + # @dataclass resolves annotations through sys.modules[cls.__module__], + # so the module has to be registered before it is executed. + sys.modules[name] = module + try: + spec.loader.exec_module(module) + except BaseException: + sys.modules.pop(name, None) + raise + return module + + +@pytest.fixture +def guard() -> ModuleType: + return _load_guard() + + +@pytest.fixture(autouse=True) +def _restore_environ(): + """Snapshot the whole environment. + + The guard mutates ``os.environ`` process-wide by design (the stress + scripts import ``kanban_db`` after it runs), so ``monkeypatch.setenv`` + is not enough — it only restores names it was told about. + """ + saved = dict(os.environ) + try: + yield + finally: + os.environ.clear() + os.environ.update(saved) + + +@pytest.fixture +def sandbox_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """Repoint the system temp root at a subdir of ``tmp_path``. + + A subdir, not ``tmp_path`` itself, so the tests still have somewhere + that is *outside* the temp root to use for the negative cases. + """ + root = tmp_path / "tmp" + root.mkdir() + monkeypatch.setattr(tempfile, "tempdir", str(root)) + return root + + +@pytest.fixture +def live_board(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """A stand-in for the operator's real ``~/.hermes`` board. + + Nothing in these tests may read or write it; it exists so the guard has + a concrete "live board" to refuse. + """ + real_home = tmp_path / "realhome" + hermes = real_home / ".hermes" + hermes.mkdir(parents=True) + db = hermes / "kanban.db" + db.write_bytes(b"SQLite format 3\x00") # a board that already exists + monkeypatch.setattr(Path, "home", classmethod(lambda cls: real_home)) + monkeypatch.setenv("HERMES_REAL_HOME", str(real_home)) + return db + + +# --------------------------------------------------------------------------- +# the happy path: an isolated sandbox, pinned explicitly +# --------------------------------------------------------------------------- + + +def test_isolate_pins_an_explicit_db_inside_the_new_temp_home( + guard, sandbox_root, live_board, +): + """The DB must be an explicit path inside the home the guard just made.""" + sandbox = guard.isolate_stress_home("unit_guard_") + + assert sandbox.home.parent.resolve() == sandbox_root.resolve() + assert sandbox.db.parent.resolve() == sandbox.home.resolve() + # Pinned explicitly, not left to HERMES_HOME resolution. + assert os.environ["HERMES_KANBAN_DB"] == str(sandbox.db) + assert os.environ["HERMES_HOME"] == str(sandbox.home) + # The guard isolates; creating the schema stays the script's job. + assert not sandbox.db.exists() + + +def test_isolated_db_is_what_kanban_db_actually_resolves( + guard, sandbox_root, live_board, +): + """End-to-end: the production resolver must agree with the sandbox. + + This is the check that would have caught the incident — the scripts' + ``HERMES_HOME`` looked isolated while ``kanban_db_path()`` returned the + live board. + """ + sandbox = guard.isolate_stress_home("unit_guard_") + + from hermes_cli import kanban_db as kb + + assert kb.kanban_db_path().resolve() == sandbox.db.resolve() + + +def test_isolate_overrides_an_ambient_live_kanban_db( + guard, sandbox_root, live_board, monkeypatch: pytest.MonkeyPatch, +): + """The incident, reproduced: a live ``HERMES_KANBAN_DB`` is inherited. + + Setting ``HERMES_HOME`` does not dislodge it — the guard must. + """ + monkeypatch.setenv("HERMES_KANBAN_DB", str(live_board)) + + sandbox = guard.isolate_stress_home("unit_guard_") + + from hermes_cli import kanban_db as kb + + assert os.environ["HERMES_KANBAN_DB"] != str(live_board) + assert kb.kanban_db_path().resolve() == sandbox.db.resolve() + assert kb.kanban_db_path().resolve() != live_board.resolve() + + +def test_isolate_scrubs_every_kanban_redirect_var( + guard, sandbox_root, live_board, monkeypatch: pytest.MonkeyPatch, +): + """No inherited kanban var may still point at the live tree. + + ``HERMES_KANBAN_WORKSPACES_ROOT`` and friends have the same + env-beats-home precedence as the DB, and the per-worker identity vars + (``HERMES_KANBAN_TASK`` / ``_RUN_ID`` / ``_CLAIM_LOCK``) name real rows + on the live board. + """ + live = live_board.parent + ambient = { + "HERMES_KANBAN_HOME": str(live), + "HERMES_KANBAN_BOARD": "default", + "HERMES_KANBAN_WORKSPACES_ROOT": str(live / "kanban" / "workspaces"), + "HERMES_KANBAN_ATTACHMENTS_ROOT": str(live / "kanban" / "attachments"), + "HERMES_KANBAN_TASK": "t_bdf1001a", + "HERMES_KANBAN_RUN_ID": "255", + "HERMES_KANBAN_CLAIM_LOCK": "some-host:80006", + "HERMES_KANBAN_WORKSPACE": str(live / "worktrees" / "t_bdf1001a"), + "HERMES_PROFILE": "backend", + } + for key, value in ambient.items(): + monkeypatch.setenv(key, value) + + sandbox = guard.isolate_stress_home("unit_guard_") + + home_str = str(sandbox.home.resolve()) + for key in ambient: + value = os.environ.get(key) + if value is None: + continue + assert str(Path(value).resolve()).startswith(home_str) or ( + not Path(value).is_absolute() + ), f"{key}={value!r} still escapes the sandbox" + for key in ("HERMES_KANBAN_TASK", "HERMES_KANBAN_RUN_ID", + "HERMES_KANBAN_CLAIM_LOCK"): + assert key not in os.environ, f"{key} still names a live-board row" + + +def test_child_env_carries_only_the_isolated_db( + guard, sandbox_root, live_board, monkeypatch: pytest.MonkeyPatch, +): + """Spawned workers must inherit the sandbox, never the live board.""" + monkeypatch.setenv("HERMES_KANBAN_DB", str(live_board)) + + sandbox = guard.isolate_stress_home("unit_guard_") + child = sandbox.child_env() + + assert child["HERMES_KANBAN_DB"] == str(sandbox.db) + assert child["HERMES_HOME"] == str(sandbox.home) + assert child["HOME"] == str(sandbox.home) + leaked = [ + f"{k}={v}" for k, v in child.items() + if k.startswith("HERMES_KANBAN") and str(live_board.parent) in str(v) + ] + assert leaked == [] + + +# --------------------------------------------------------------------------- +# the operator's real home must survive the HOME rewrite +# --------------------------------------------------------------------------- + + +def test_isolate_preserves_the_operator_real_home( + guard, sandbox_root, live_board, tmp_path: Path, +): + """``HERMES_REAL_HOME`` names the operator's home, not the sandbox. + + The guard rewrites ``HOME`` at the sandbox, which is precisely why + ``HERMES_REAL_HOME`` exists: it is the only surviving pointer at the + tree that must never be written. Overwriting it with the sandbox blinds + :func:`_live_roots` in every process downstream of isolation. + """ + real_home = tmp_path / "realhome" + + sandbox = guard.isolate_stress_home("unit_guard_") + + assert os.environ["HERMES_REAL_HOME"] == str(real_home) + assert sandbox.env["HERMES_REAL_HOME"] == str(real_home) + assert sandbox.child_env()["HERMES_REAL_HOME"] == str(real_home) + # ...while everything that actually resolves a board stays sandboxed. + assert os.environ["HOME"] == str(sandbox.home) + assert os.environ["HERMES_HOME"] == str(sandbox.home) + assert os.environ["HERMES_KANBAN_HOME"] == str(sandbox.home) + assert os.environ["HERMES_KANBAN_DB"] == str(sandbox.db) + + +def test_isolate_falls_back_to_the_actual_home_when_real_home_is_unset( + guard, sandbox_root, live_board, tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +): + """Un-dispatched runs have no ``HERMES_REAL_HOME`` to inherit. + + The value has to be captured *before* ``HOME`` is rewritten, or the + fallback records the sandbox and the live-board rule matches nothing. + """ + monkeypatch.delenv("HERMES_REAL_HOME", raising=False) + + sandbox = guard.isolate_stress_home("unit_guard_") + + assert os.environ["HERMES_REAL_HOME"] == str(tmp_path / "realhome") + assert sandbox.child_env()["HERMES_REAL_HOME"] == str(tmp_path / "realhome") + + +def test_a_child_of_the_sandbox_still_refuses_the_operator_live_board( + guard, sandbox_root, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +): + """The teeth: ``_live_roots`` must survive being inherited. + + A spawned worker sees the sandbox as its ``HOME``. If the parent also + handed it ``HERMES_REAL_HOME=``, both live-root candidates + collapse onto the sandbox and the "is this the real board?" rule can + never fire again — the one check aimed at the incident becomes a no-op + in exactly the processes that caused it. + + The stand-in real home lives *under* the temp root so the containment + and marker rules pass; the live-board rule is then the only thing left + that can refuse. + """ + real_home = sandbox_root / "realhome" + hermes = real_home / ".hermes" + hermes.mkdir(parents=True) + (hermes / guard.SANDBOX_MARKER).write_text("test") + monkeypatch.setattr( + Path, "home", classmethod(lambda cls: Path(os.environ["HOME"])), + ) + monkeypatch.setenv("HERMES_REAL_HOME", str(real_home)) + + sandbox = guard.isolate_stress_home("unit_guard_") + child = guard # a fresh interpreter re-reads the same module + os.environ.clear() + os.environ.update(sandbox.child_env()) + + with pytest.raises(child.StressIsolationError): + child.assert_disposable_sandbox(hermes, hermes / "kanban.db") + + +# --------------------------------------------------------------------------- +# fail-closed: it must refuse anything it cannot prove is disposable +# --------------------------------------------------------------------------- + + +def test_guard_refuses_a_home_outside_the_temp_root( + guard, sandbox_root, live_board, tmp_path: Path, +): + """A home that is not under the system temp root is not a sandbox. + + Marked and DB-free, so the temp-root rule is the only thing left to + refuse on. + """ + outside = tmp_path / "not_temp" + outside.mkdir() + (outside / guard.SANDBOX_MARKER).write_text("test") + + with pytest.raises(guard.StressIsolationError): + guard.assert_disposable_sandbox(outside, outside / "kanban.db") + + +def test_guard_refuses_the_live_default_board(guard, sandbox_root, live_board): + """``~/.hermes/kanban.db`` is the exact DB the incident wrote to.""" + with pytest.raises(guard.StressIsolationError): + guard.assert_disposable_sandbox(live_board.parent, live_board) + + +def test_guard_refuses_a_db_outside_its_home(guard, sandbox_root, live_board): + """Containment: the DB has to be inside the sandbox, not merely named.""" + home = Path(tempfile.mkdtemp(prefix="unit_guard_")) + (home / guard.SANDBOX_MARKER).write_text("test") + + with pytest.raises(guard.StressIsolationError): + guard.assert_disposable_sandbox(home, live_board) + + +def test_guard_refuses_an_already_existing_board( + guard, sandbox_root, live_board, +): + """A DB file that already exists is somebody's board, not a fresh one.""" + home = Path(tempfile.mkdtemp(prefix="unit_guard_")) + (home / guard.SANDBOX_MARKER).write_text("test") + db = home / "kanban.db" + db.write_bytes(b"SQLite format 3\x00") + + with pytest.raises(guard.StressIsolationError): + guard.assert_disposable_sandbox(home, db) + + +def test_guard_refuses_an_unmarked_home(guard, sandbox_root, live_board): + """Only a home this guard created carries the marker. + + Without it, a child process handed an arbitrary path would adopt it. + """ + home = Path(tempfile.mkdtemp(prefix="unit_guard_")) + + with pytest.raises(guard.StressIsolationError): + guard.assert_disposable_sandbox( + home, home / "kanban.db", require_marker=True, + ) + + +def test_guard_refuses_when_the_resolver_still_disagrees( + guard, sandbox_root, live_board, monkeypatch: pytest.MonkeyPatch, +): + """The post-set verification is what makes this future-proof. + + If a new env var, or a change to ``kanban_db_path``'s precedence, ever + out-votes the pin again, the guard must refuse rather than run. + """ + from hermes_cli import kanban_db as kb + + monkeypatch.setattr(kb, "kanban_db_path", lambda *a, **k: live_board) + + with pytest.raises(guard.StressIsolationError): + guard.isolate_stress_home("unit_guard_") + + +# --------------------------------------------------------------------------- +# the child half +# --------------------------------------------------------------------------- + + +def test_adopt_reasserts_the_sandbox_in_a_child( + guard, sandbox_root, live_board, monkeypatch: pytest.MonkeyPatch, +): + """A spawned worker re-pins rather than trusting what it inherited.""" + sandbox = guard.isolate_stress_home("unit_guard_") + sandbox.db.write_bytes(b"SQLite format 3\x00") # parent ran init_db + + # A child that inherited a hostile environment despite everything. + monkeypatch.setenv("HERMES_KANBAN_DB", str(live_board)) + monkeypatch.setenv("HERMES_KANBAN_BOARD", "default") + + adopted = guard.adopt_stress_home(str(sandbox.home)) + + from hermes_cli import kanban_db as kb + + assert adopted.db.resolve() == sandbox.db.resolve() + assert kb.kanban_db_path().resolve() == sandbox.db.resolve() + + +def test_adopt_refuses_a_non_sandbox_home(guard, sandbox_root, live_board): + """A child pointed at the live tree must die, not adopt it.""" + with pytest.raises(guard.StressIsolationError): + guard.adopt_stress_home(str(live_board.parent)) + + +# --------------------------------------------------------------------------- +# every entry point is wired — a new script cannot quietly skip the guard +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("script", CONCURRENCY_SCRIPTS) +def test_every_concurrency_script_uses_the_guard(script: str): + """All four destructive entry points must go through the helper.""" + source = (STRESS_DIR / script).read_text() + + assert "_isolation" in source, f"{script} does not import the guard" + assert "isolate_stress_home(" in source, ( + f"{script} does not create an isolated sandbox" + ) + + +@pytest.mark.parametrize("script", CONCURRENCY_SCRIPTS) +def test_no_concurrency_script_sets_hermes_home_by_hand(script: str): + """Bypass detector. + + Hand-rolled ``os.environ["HERMES_HOME"] = ...`` is exactly what looked + like isolation and was not. Every home/DB assignment goes through the + guard, in the parent and in every child loop. + """ + source = (STRESS_DIR / script).read_text() + + for name in ("HERMES_HOME", "HOME", "HERMES_KANBAN_DB"): + assert f'os.environ["{name}"] =' not in source, ( + f"{script} still assigns {name} by hand" + ) + assert f"os.environ['{name}'] =" not in source + + +@pytest.mark.parametrize("script", CONCURRENCY_SCRIPTS) +def test_every_spawned_child_entry_point_adopts_the_sandbox(script: str): + """Child *processes* re-assert; they never trust what they inherited. + + Thread-based scripts share the parent's ``os.environ`` and are covered + by the parent's ``isolate_stress_home`` alone — spawned processes get a + fresh interpreter, so each one re-runs the guard. + """ + source = (STRESS_DIR / script).read_text() + + if "Process(" not in source: + pytest.skip(f"{script} spawns no child processes") + assert "adopt_stress_home(" in source, ( + f"{script} spawns workers that never re-assert isolation" + ) diff --git a/tests/stress/_isolation.py b/tests/stress/_isolation.py new file mode 100644 index 0000000000000..2b7ad8c362509 --- /dev/null +++ b/tests/stress/_isolation.py @@ -0,0 +1,319 @@ +"""Fail-closed board isolation for the destructive kanban stress scripts. + +These scripts claim, fail, reclaim and complete tasks in tight loops. Pointed +at the wrong database they are indistinguishable from a fleet of malicious +workers, so "which DB am I on?" is a safety property, not a convenience. + +**Why ``HERMES_HOME`` was never enough.** ``kanban_db.kanban_db_path()`` +resolves in this order: + +1. ``HERMES_KANBAN_DB`` — pins the file directly, +2. the active board, +3. ``/kanban.db``, where ```` comes from ``HERMES_KANBAN_HOME`` + or ``HERMES_HOME``. + +The scripts set only ``HERMES_HOME`` (step 3). Anything that had already +exported ``HERMES_KANBAN_DB`` — most obviously the dispatcher, which injects +it into every worker's environment as defense in depth — therefore won at +step 1. A stress run launched from inside a worker printed a +``/var/folders/...`` home and drove the operator's real board: synthetic +workers marked live cards done. The same inheritance applies to +``HERMES_KANBAN_HOME``, ``HERMES_KANBAN_WORKSPACES_ROOT`` and friends. + +So this module does not *ask* for isolation, it *proves* it: + +* the home is a directory this module created under the system temp root, + stamped with :data:`SANDBOX_MARKER`; +* the DB is a file that does not exist yet, directly inside that home; +* neither is the live default board or anywhere under the real ``~/.hermes``; +* every ``HERMES_KANBAN_*`` variable is scrubbed and only the sandbox ones + are re-pinned — a *new* redirect var added upstream is scrubbed by default + rather than silently inherited; +* and finally ``kanban_db_path()`` is *called* and its answer compared to the + sandbox. That last check is what makes the guard survive a future change to + the resolution order: if anything still out-votes the pin, the script + refuses to start. + +Every entry point calls :func:`isolate_stress_home` before importing +``hermes_cli.kanban_db``; every spawned worker calls +:func:`adopt_stress_home` rather than trusting what it inherited. +:class:`StressIsolationError` is fatal by design — there is no fallback to +"probably fine". +""" + +from __future__ import annotations + +import os +import tempfile +from dataclasses import dataclass, field +from pathlib import Path +from typing import Iterable, Mapping + +__all__ = [ + "SANDBOX_MARKER", + "StressHome", + "StressIsolationError", + "adopt_stress_home", + "assert_disposable_sandbox", + "isolate_stress_home", +] + +#: Stamped into every sandbox home. A child process is handed a path, not a +#: promise; the marker is how it tells a sandbox from any other directory. +SANDBOX_MARKER = ".hermes_stress_sandbox" + +#: Board layout inside the sandbox. ``default`` resolves to ``/kanban.db``, +#: so the sandbox mirrors a real board exactly. +_DB_NAME = "kanban.db" +_BOARD = "default" + +#: Scrubbed wholesale before the sandbox values are pinned. Anything matching +#: this prefix either redirects path resolution or names a row on the live +#: board (``HERMES_KANBAN_TASK``, ``_RUN_ID``, ``_CLAIM_LOCK`` — a stress +#: worker inheriting those can complete somebody else's run). +_SCRUB_PREFIX = "HERMES_KANBAN" + +#: Scrubbed by name: profile selection re-anchors ``HERMES_HOME`` at +#: ``/profiles/``, which is not the sandbox. +_SCRUB_EXACT = ("HERMES_PROFILE", "HERMES_PROFILE_NAME", "HERMES_HOME_ENSURED") + + +class StressIsolationError(RuntimeError): + """The stress script could not prove its board is disposable. + + Always fatal. Catching this to continue would defeat the entire point. + """ + + +@dataclass(frozen=True) +class StressHome: + """A proven-disposable sandbox and the environment that pins it.""" + + home: Path + db: Path + env: Mapping[str, str] = field(default_factory=dict) + + def child_env(self) -> dict[str, str]: + """Environment for a spawned worker: scrubbed, then re-pinned. + + Built from the sandbox values rather than copied from ``os.environ`` + verbatim, so a variable that reappeared after isolation cannot ride + along into the child. + """ + env = { + key: value for key, value in os.environ.items() + if not _is_scrubbed(key) + } + env.update(self.env) + return env + + +def _is_scrubbed(key: str) -> bool: + return key.startswith(_SCRUB_PREFIX) or key in _SCRUB_EXACT + + +def _is_within(path: Path, root: Path) -> bool: + """True when ``path`` is strictly inside ``root`` (both resolved).""" + try: + resolved = path.resolve() + root = root.resolve() + except OSError: # pragma: no cover - unreadable path is not a sandbox + return False + return root != resolved and root in resolved.parents + + +def _real_home() -> Path | None: + """The operator's home, as it looks *before* ``HOME`` is rewritten. + + ``HERMES_REAL_HOME`` is what the dispatcher exports when it rewrites + ``HOME``, so it survives that indirection; without it the OS home is + still trustworthy. Resolved eagerly at isolation time and re-exported + verbatim, because after ``_apply`` runs ``HOME`` names the sandbox and + the answer would no longer be recoverable. + """ + raw = os.environ.get("HERMES_REAL_HOME") + if not raw: + return _ambient_home() + try: + return Path(raw).expanduser() + except (OSError, RuntimeError): # pragma: no cover - unusable value + return _ambient_home() + + +def _ambient_home() -> Path | None: + """``Path.home()``, or ``None`` where the process has no home at all.""" + try: + return Path.home() + except (OSError, RuntimeError): # pragma: no cover - no home at all + return None + + +def _live_roots() -> Iterable[Path]: + """Directories that certainly hold a real board. + + Both the exported real home and the ambient one, because before + isolation they can legitimately differ and either may hold the board. + Afterwards ``HOME`` is the sandbox, and the first candidate is the only + one still pointing anywhere real. + """ + seen: set[Path] = set() + for base in (_real_home(), _ambient_home()): + if base is None: + continue + root = base / ".hermes" + if root not in seen: + seen.add(root) + yield root + + +def assert_disposable_sandbox( + home: Path, + db: Path, + *, + require_marker: bool = True, + allow_existing_db: bool = False, +) -> None: + """Raise :class:`StressIsolationError` unless ``db`` is safe to destroy. + + ``allow_existing_db`` is for :func:`adopt_stress_home`: by the time a + spawned worker runs, the parent has already created the schema. Every + other rule still binds, so an existing *live* board is refused there too + — it fails the containment and marker checks first. + """ + home = Path(home) + db = Path(db) + tmp_root = Path(tempfile.gettempdir()) + + def refuse(why: str) -> None: + raise StressIsolationError( + f"refusing to run a destructive stress script: {why}\n" + f" home = {home}\n" + f" db = {db}\n" + f" temp root = {tmp_root}\n" + "This guard is fail-closed. It never falls back to the " + "ambient HERMES_KANBAN_DB / HERMES_HOME." + ) + + if not home.is_dir(): + refuse("the sandbox home does not exist or is not a directory") + if not _is_within(home, tmp_root): + refuse( + "the sandbox home is not under the system temp root, so it was " + "not created by this guard" + ) + if require_marker and not (home / SANDBOX_MARKER).is_file(): + refuse( + f"the sandbox home carries no {SANDBOX_MARKER} marker — it is " + "some other directory, not a home this guard created" + ) + if db.parent.resolve() != home.resolve(): + refuse("the database is not directly inside the sandbox home") + for live in _live_roots(): + if db.resolve() == (live / _DB_NAME).resolve() or _is_within(db, live): + refuse(f"the database is the live board under {live}") + if db.exists() and not allow_existing_db: + refuse( + "the database already exists — a fresh sandbox cannot contain a " + "board, so this is somebody else's" + ) + + +def _sandbox_env(home: Path, db: Path) -> dict[str, str]: + """The variables that pin every kanban path inside ``home``. + + ``HERMES_KANBAN_DB`` and ``HERMES_KANBAN_HOME`` are independent locks at + different steps of the resolution order: even if one were ignored, the + other still lands inside the sandbox. + + ``HERMES_REAL_HOME`` is the exception: it is not a redirect, it is the + label on the tree that must never be touched. Pinning it at the sandbox + would make every child agree that the operator's home *is* the sandbox, + and :func:`_live_roots` — the only rule that names the live board — + would then match nothing. It is carried through unchanged instead. + """ + real_home = _real_home() + return { + "HOME": str(home), + "HERMES_HOME": str(home), + **({"HERMES_REAL_HOME": str(real_home)} if real_home else {}), + "HERMES_KANBAN_HOME": str(home), + "HERMES_KANBAN_DB": str(db), + "HERMES_KANBAN_BOARD": _BOARD, + "HERMES_KANBAN_WORKSPACES_ROOT": str(home / "kanban" / "workspaces"), + "HERMES_KANBAN_ATTACHMENTS_ROOT": str(home / "kanban" / "attachments"), + } + + +def _apply(env: Mapping[str, str]) -> None: + """Scrub every inherited kanban variable, then pin the sandbox. + + Deliberately not restored on failure: leaving the process pointed at the + sandbox is the safe end state, and the caller is expected to die anyway. + """ + for key in [k for k in os.environ if _is_scrubbed(k)]: + del os.environ[key] + os.environ.update(env) + + +def _verify_resolver(db: Path) -> None: + """Ask production code where the board is and insist on the sandbox. + + Imported here, after the environment is pinned, so nothing caches a live + path on the way in. This is the check that does not depend on this + module's list of variables being complete. + """ + try: + from hermes_cli import kanban_db as kb + except Exception as exc: # pragma: no cover - import failure is fatal + raise StressIsolationError( + f"cannot import hermes_cli.kanban_db to verify isolation: {exc}" + ) from exc + + resolved = kb.kanban_db_path() + if Path(resolved).resolve() != db.resolve(): + raise StressIsolationError( + "kanban_db_path() does not agree with the sandbox — something " + "still out-votes the pin.\n" + f" pinned = {db}\n" + f" resolved = {resolved}\n" + "Refusing to run rather than risk a live board." + ) + + +def isolate_stress_home(prefix: str) -> StressHome: + """Create a sandbox board and pin the whole process to it. + + Call this **before** importing ``hermes_cli.kanban_db``, as the first + statement of a stress entry point. Creating the schema stays the + script's job; this only guarantees where it will land. + """ + home = Path(tempfile.mkdtemp(prefix=prefix)).resolve() + (home / SANDBOX_MARKER).write_text( + f"disposable kanban board for {prefix}* (pid {os.getpid()})\n", + encoding="utf-8", + ) + db = home / _DB_NAME + + assert_disposable_sandbox(home, db) + env = _sandbox_env(home, db) + _apply(env) + _verify_resolver(db) + return StressHome(home=home, db=db, env=env) + + +def adopt_stress_home(home: str | Path) -> StressHome: + """Re-assert the sandbox inside a spawned worker. + + A child inherits its parent's environment, so in practice it starts + clean — but "in practice" is what the incident already disproved once. + The child re-derives the DB from the path it was handed and re-runs + every check, so a worker pointed anywhere else dies instead of working. + """ + home = Path(home).resolve() + db = home / _DB_NAME + + assert_disposable_sandbox(home, db, allow_existing_db=True) + env = _sandbox_env(home, db) + _apply(env) + _verify_resolver(db) + return StressHome(home=home, db=db, env=env) diff --git a/tests/stress/test_concurrency.py b/tests/stress/test_concurrency.py index 80d9183003a52..56fc06b301a70 100644 --- a/tests/stress/test_concurrency.py +++ b/tests/stress/test_concurrency.py @@ -31,6 +31,10 @@ NUM_TASKS = 100 WORKER_TIMEOUT_S = 60 WT = str(Path(__file__).resolve().parents[2]) +sys.path.insert(0, WT) +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from _isolation import adopt_stress_home, isolate_stress_home # noqa: E402 def worker_loop(worker_id: int, hermes_home: str, result_file: str) -> None: @@ -40,9 +44,10 @@ def worker_loop(worker_id: int, hermes_home: str, result_file: str) -> None: repeats until the ready pool is empty. Records every claim + complete into its own JSON result file for later aggregation. """ - os.environ["HERMES_HOME"] = hermes_home - os.environ["HOME"] = hermes_home - sys.path.insert(0, WT) + # Re-assert the sandbox before touching the DB. This worker completes + # tasks; on the wrong board that is data loss, so it proves where it is + # rather than trusting the environment it was handed. + adopt_stress_home(hermes_home) from hermes_cli import kanban_db as kb @@ -117,13 +122,12 @@ def worker_loop(worker_id: int, hermes_home: str, result_file: str) -> None: def main(): - home = tempfile.mkdtemp(prefix="hermes_concurrency_") + sandbox = isolate_stress_home("hermes_concurrency_") + home = str(sandbox.home) print(f"HERMES_HOME = {home}") + print(f"kanban DB = {sandbox.db}") # Seed. - os.environ["HERMES_HOME"] = home - os.environ["HOME"] = home - sys.path.insert(0, WT) from hermes_cli import kanban_db as kb kb.init_db() diff --git a/tests/stress/test_concurrency_mixed.py b/tests/stress/test_concurrency_mixed.py index 8b6ef718667c6..3e042743cc234 100644 --- a/tests/stress/test_concurrency_mixed.py +++ b/tests/stress/test_concurrency_mixed.py @@ -28,12 +28,15 @@ NUM_TASKS = 500 RUN_DURATION_S = 30 WT = str(Path(__file__).resolve().parents[2]) +sys.path.insert(0, WT) +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from _isolation import adopt_stress_home, isolate_stress_home # noqa: E402 def worker_loop(worker_id: int, hermes_home: str, result_file: str) -> None: - os.environ["HERMES_HOME"] = hermes_home - os.environ["HOME"] = hermes_home - sys.path.insert(0, WT) + # Re-assert the sandbox before touching the DB (see _isolation). + adopt_stress_home(hermes_home) from hermes_cli import kanban_db as kb events = [] @@ -143,9 +146,9 @@ def worker_loop(worker_id: int, hermes_home: str, result_file: str) -> None: def reclaimer_loop(hermes_home: str, result_file: str) -> None: """Background dispatcher-like loop that reclaims stale tasks.""" - os.environ["HERMES_HOME"] = hermes_home - os.environ["HOME"] = hermes_home - sys.path.insert(0, WT) + # Re-assert the sandbox: this loop reclaims *every* stale claim it + # finds, so on a live board it would tear down real workers. + adopt_stress_home(hermes_home) from hermes_cli import kanban_db as kb events = [] @@ -170,12 +173,11 @@ def reclaimer_loop(hermes_home: str, result_file: str) -> None: def main(): - home = tempfile.mkdtemp(prefix="hermes_mixed_stress_") + sandbox = isolate_stress_home("hermes_mixed_stress_") + home = str(sandbox.home) print(f"HERMES_HOME = {home}") + print(f"kanban DB = {sandbox.db}") - os.environ["HERMES_HOME"] = home - os.environ["HOME"] = home - sys.path.insert(0, WT) from hermes_cli import kanban_db as kb kb.init_db() diff --git a/tests/stress/test_concurrency_parent_gate.py b/tests/stress/test_concurrency_parent_gate.py index 406774bad5b0a..2dbb5e8a1611b 100644 --- a/tests/stress/test_concurrency_parent_gate.py +++ b/tests/stress/test_concurrency_parent_gate.py @@ -28,15 +28,23 @@ WT = str(Path(__file__).resolve().parents[2]) sys.path.insert(0, WT) +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from _isolation import isolate_stress_home # noqa: E402 NUM_CREATE_ROUNDS = 200 WORKERS_RUN_DURATION_S = 8 def run() -> int: - home = tempfile.mkdtemp(prefix="hermes_parent_gate_stress_") - os.environ["HERMES_HOME"] = home - os.environ["HOME"] = home + # Workers here are threads, so they share this process's environment — + # the one sandbox pinned here covers all of them. There is no + # ``adopt_stress_home`` counterpart because there is no child process to + # re-assert in. + sandbox = isolate_stress_home("hermes_parent_gate_stress_") + home = str(sandbox.home) + print(f"HERMES_HOME = {home}") + print(f"kanban DB = {sandbox.db}") from hermes_cli import kanban_db as kb diff --git a/tests/stress/test_concurrency_reclaim_race.py b/tests/stress/test_concurrency_reclaim_race.py index 6a636de72efa6..e70a3f6a0358a 100644 --- a/tests/stress/test_concurrency_reclaim_race.py +++ b/tests/stress/test_concurrency_reclaim_race.py @@ -36,12 +36,15 @@ TTL = 1 WORK_DURATION_S = 2.0 # longer than TTL => reclaimer wins WT = str(Path(__file__).resolve().parents[2]) +sys.path.insert(0, WT) +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from _isolation import adopt_stress_home, isolate_stress_home # noqa: E402 def worker_loop(worker_id: int, hermes_home: str, result_file: str) -> None: - os.environ["HERMES_HOME"] = hermes_home - os.environ["HOME"] = hermes_home - sys.path.insert(0, WT) + # Re-assert the sandbox before touching the DB (see _isolation). + adopt_stress_home(hermes_home) from hermes_cli import kanban_db as kb events = [] @@ -96,9 +99,9 @@ def worker_loop(worker_id: int, hermes_home: str, result_file: str) -> None: def reclaimer_loop(hermes_home: str, result_file: str) -> None: - os.environ["HERMES_HOME"] = hermes_home - os.environ["HOME"] = hermes_home - sys.path.insert(0, WT) + # Re-assert the sandbox: this loop reclaims *every* stale claim it + # finds, so on a live board it would tear down real workers. + adopt_stress_home(hermes_home) from hermes_cli import kanban_db as kb events = [] @@ -121,10 +124,10 @@ def reclaimer_loop(hermes_home: str, result_file: str) -> None: def main(): - home = tempfile.mkdtemp(prefix="hermes_reclaim_race_") - os.environ["HERMES_HOME"] = home - os.environ["HOME"] = home - sys.path.insert(0, WT) + sandbox = isolate_stress_home("hermes_reclaim_race_") + home = str(sandbox.home) + print(f"HERMES_HOME = {home}") + print(f"kanban DB = {sandbox.db}") from hermes_cli import kanban_db as kb kb.init_db() diff --git a/website/docs/user-guide/features/kanban.md b/website/docs/user-guide/features/kanban.md index 18bef83fed189..7e60fe26c70b8 100644 --- a/website/docs/user-guide/features/kanban.md +++ b/website/docs/user-guide/features/kanban.md @@ -271,17 +271,23 @@ hermes kanban block t_abc "need input" --ids t_def t_hij dispatcher auto-promotes it once the parent finishes). It never routes to `triage`. -If you unblock a task and it later shows up in **`triage`**, the unblock is not -what put it there. A subsequent *re-block for the same reason* did: after a task -is blocked → unblocked → re-blocked for the same cause `BLOCK_RECURRENCE_LIMIT` -times (default `2`), the unblock-loop breaker stops sending it back to `blocked` -— where a cron would just keep unblocking it — and routes it to `triage` for a -human decision. This is a deterministic DB guard, not an LLM judgment call, and -a task's body text cannot opt out of it: the recurrence counter deliberately -survives each unblock (it resets only on a successful `complete`). To keep an -unblocked task in the work pool, resolve *why it keeps re-blocking* (unfinished -parent, missing input, unmet capability) before unblocking, or raise -`BLOCK_RECURRENCE_LIMIT` if the loop is expected. +If an unblocked task keeps coming back to **`blocked`** and stops responding to +`unblock`-by-cron, the unblock-loop breaker has escalated it. After a task is +blocked → unblocked → re-blocked for the same cause `BLOCK_RECURRENCE_LIMIT` +times (default `2`), the breaker emits `block_loop_detected` and makes the block +**sticky**: `recompute_ready`, `claim`, restart/migration and the dispatcher +tick all refuse to advance it, and the auto-decomposer will not touch it. Only +an explicit `hermes kanban unblock` (a human decision) resumes it. The +escalation deliberately does *not* park the card in `triage` — `triage` is the +auto-decomposer's input queue, so a card left there gets promoted straight back +into the work pool. + +This is a deterministic DB guard, not an LLM judgment call, and a task's body +text cannot opt out of it: the recurrence counter deliberately survives each +unblock (it resets only on a successful `complete`). To keep an unblocked task +in the work pool, resolve *why it keeps re-blocking* (unfinished parent, missing +input, unmet capability) before unblocking, or raise `BLOCK_RECURRENCE_LIMIT` if +the loop is expected. ::: ## How workers interact with the board @@ -293,7 +299,7 @@ parent, missing input, unmet capability) before unblocking, or raise | `kanban_show` | Read the current task (title, body, prior attempts, parent handoffs, comments, full pre-formatted `worker_context`). Defaults to the env's task id. | — | | `kanban_list` | List task summaries with filters for `assignee`, `status`, `tenant`, archived visibility, and limit. Intended for orchestrators discovering board work. | — | | `kanban_complete` | Finish with `summary` + `metadata` structured handoff. | at least one of `summary` / `result` | -| `kanban_block` | Stop work and route by why: `kind=dependency` (waits in `todo`, auto-resumes), `needs_input`/`capability`/`transient` (surface to a human). Repeated same-kind re-blocks auto-escalate to `triage`. | `reason` | +| `kanban_block` | Stop work and route by why: `kind=dependency` (waits in `todo`, auto-resumes), `needs_input`/`capability`/`transient` (surface to a human). Repeated same-kind re-blocks escalate to a sticky block only an explicit `unblock` clears. | `reason` | | `kanban_heartbeat` | Signal liveness during long operations. Pure side-effect. | — | | `kanban_comment` | Append a durable note to the task thread. | `task_id`, `body` | | `kanban_attach` | Attach a file to a task by passing its bytes inline (base64); stored under the task's attachments dir (25 MB cap). | file bytes + name | @@ -996,7 +1002,7 @@ Every transition appends a row to `task_events`. Each row carries an optional `r | `completed` | `{result_len, summary?}` | Worker wrote `--result` / `--summary` and task hit `done`. `summary` is the first-line handoff (400-char cap); full version lives on the run row. If `complete_task` is called on a never-claimed task with handoff fields, a zero-duration run is synthesized so `run_id` still points at something. | | `blocked` | `{reason, kind, recurrences}` | Worker or human flipped the task to `blocked`. `kind` is the typed block reason (`needs_input`, `capability`, `transient`, or `null` for a generic block); `recurrences` is the unblock-loop counter. Synthesizes a zero-duration run when called on a never-claimed task with `--reason`. | | `dependency_wait` | `{reason, kind}` | Worker blocked with `kind=dependency` — the task is only waiting on another task, so it routes to `todo` (parent-gated, auto-promoted) instead of `blocked`. No human needed. | -| `block_loop_detected` | `{reason, kind, recurrences, limit}` | A task was unblocked and re-blocked for the same reason `BLOCK_RECURRENCE_LIMIT` times (default 2). Instead of landing in `blocked` again — where a cron would keep unblocking it — it routes to `triage` for a human decision, breaking the unblock↔re-block loop. | +| `block_loop_detected` | `{reason, kind, recurrences, limit}` | A task was unblocked and re-blocked for the same reason `BLOCK_RECURRENCE_LIMIT` times (default 2). The task stays `blocked` and this event makes that block **sticky**: `recompute_ready`, `claim`, the dispatcher tick and the auto-decomposer all leave it alone, so only an explicit `unblock` resumes it. Breaks the unblock↔re-block loop. | | `unblocked` | — | `blocked → ready` (or `todo` if parents are still open), either manually or via `/unblock`. Resets the dispatcher's `consecutive_failures` but deliberately preserves `block_recurrences` so the loop breaker keeps its memory. `run_id` is `NULL`. | | `archived` | — | Hidden from the default board. If the task was still running, carries the `run_id` of the run that was reclaimed as a side effect. |