Skip to content

The agent that grows with you

refactor(kanban-db): drop dead _clear_spawn_failures alias, unify per-task row/link accessors, compact three docstrings

Tekniuma11464423a27
diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.py
index c5b73a24e4b..6a391fa2409 100644
--- a/hermes_cli/kanban_db.py
+++ b/hermes_cli/kanban_db.py
@@ -2260,20 +2260,19 @@ def unlink_tasks(conn: sqlite3.Connection, parent_id: str, child_id: str) -> boo
return removed
-def parent_ids(conn: sqlite3.Connection, task_id: str) -> list[str]:
+def _linked_ids(conn: sqlite3.Connection, want: str, where: str, task_id: str) -> list[str]:
rows = conn.execute(
- "SELECT parent_id FROM task_links WHERE child_id = ? ORDER BY parent_id",
- (task_id,),
+ f"SELECT {want} FROM task_links WHERE {where} = ? ORDER BY {want}", (task_id,)
).fetchall()
- return [r["parent_id"] for r in rows]
+ return [r[want] for r in rows]
+
+
+def parent_ids(conn: sqlite3.Connection, task_id: str) -> list[str]:
+ return _linked_ids(conn, "parent_id", "child_id", task_id)
def child_ids(conn: sqlite3.Connection, task_id: str) -> list[str]:
- rows = conn.execute(
- "SELECT child_id FROM task_links WHERE parent_id = ? ORDER BY child_id",
- (task_id,),
- ).fetchall()
- return [r["child_id"] for r in rows]
+ return _linked_ids(conn, "child_id", "parent_id", task_id)
def task_graph_contexts(
@@ -2347,12 +2346,14 @@ def add_comment(
return int(cur.lastrowid or 0)
-def list_comments(conn: sqlite3.Connection, task_id: str) -> list[Comment]:
- rows = conn.execute(
- "SELECT * FROM task_comments WHERE task_id = ? ORDER BY created_at ASC",
- (task_id,),
+def _task_rows(conn: sqlite3.Connection, table: str, task_id: str, order: str) -> list[sqlite3.Row]:
+ return conn.execute(
+ f"SELECT * FROM {table} WHERE task_id = ? ORDER BY {order}", (task_id,)
).fetchall()
- return [Comment.from_row(r) for r in rows]
+
+
+def list_comments(conn: sqlite3.Connection, task_id: str) -> list[Comment]:
+ return [Comment.from_row(r) for r in _task_rows(conn, "task_comments", task_id, "created_at ASC")]
def list_comments_after(
@@ -2538,11 +2539,7 @@ def add_attachment(
def list_attachments(conn: sqlite3.Connection, task_id: str) -> list[Attachment]:
- rows = conn.execute(
- "SELECT * FROM task_attachments WHERE task_id = ? ORDER BY created_at ASC, id ASC",
- (task_id,),
- ).fetchall()
- return [Attachment.from_row(r) for r in rows]
+ return [Attachment.from_row(r) for r in _task_rows(conn, "task_attachments", task_id, "created_at ASC, id ASC")]
def get_attachment(conn: sqlite3.Connection, attachment_id: int) -> Optional[Attachment]:
@@ -2577,11 +2574,7 @@ def delete_attachment(conn: sqlite3.Connection, attachment_id: int) -> Optional[
def list_events(conn: sqlite3.Connection, task_id: str) -> list[Event]:
- rows = conn.execute(
- "SELECT * FROM task_events WHERE task_id = ? ORDER BY created_at ASC, id ASC",
- (task_id,),
- ).fetchall()
- return [Event.from_row(r) for r in rows]
+ return [Event.from_row(r) for r in _task_rows(conn, "task_events", task_id, "created_at ASC, id ASC")]
def _insert_comment(
@@ -5940,7 +5933,6 @@ from hermes_cli.kanban_db_dispatch import ( # noqa: E402,F401
_apply_default_assignee,
_classify_worker_exit,
_clear_failure_counter,
- _clear_spawn_failures,
_default_spawn,
_defer_reclaim_for_live_worker,
_dispatch_lane_task,
diff --git a/hermes_cli/kanban_db_connect.py b/hermes_cli/kanban_db_connect.py
index e7e5a92e7c0..04f30403200 100644
--- a/hermes_cli/kanban_db_connect.py
+++ b/hermes_cli/kanban_db_connect.py
@@ -606,37 +606,21 @@ def _attempt_index_reindex_repair(
def _guard_existing_db_is_healthy(path: Path) -> None:
"""Run ``PRAGMA integrity_check`` on an existing non-empty DB file.
- Opens the probe in read/write mode so SQLite can recover or
- checkpoint a healthy WAL/hot-journal DB before we declare it
- corrupt.
-
- **Narrow auto-repair:** when the integrity failure consists *only* of
- index-scoped errors (``wrong # of entries in index <name>`` / ``row N
- missing from index <name>``), the table b-trees are intact and REINDEX
- rebuilds the damaged indexes losslessly. In that case we take the
- corrupt backup FIRST (same content-addressed quarantine as the
- fail-closed path), run REINDEX under the caller-held init flock,
- re-run ``integrity_check``, and proceed only if it comes back clean.
- Anything else — page corruption, ``malformed`` images, a REINDEX that
- does not produce a clean re-check — fails closed exactly as before:
- copy the file (and any WAL/SHM sidecars) to a backup and raise
- :class:`KanbanDbCorruptError` so callers cannot silently recreate the
- schema on top of a damaged DB.
-
- Transient lock/busy errors (``sqlite3.OperationalError``) are NOT
- treated as corruption; they propagate raw so the caller sees a
- normal lock failure and no spurious ``.corrupt`` backup is made.
-
- No-op for missing files, zero-byte files (treated as fresh), and
- paths already proven healthy this process (cache hit).
-
- Path-trust note: ``path`` arrives via :func:`connect`, which itself
- resolves it from an explicit ``db_path`` argument, the
- :func:`kanban_db_path` env-var chain, or the kanban-home default —
- all sources Hermes treats as user-controlled-but-trusted on the
- user's own machine. We additionally resolve the path here and
- confine all filesystem writes to its parent directory so any
- accidental ``..`` segments are collapsed before any I/O happens.
+ The probe opens read/write so SQLite can recover/checkpoint a healthy
+ WAL/hot-journal DB before we declare it corrupt. Narrow auto-repair: when
+ the failure is ONLY index-scoped (``wrong # of entries in index`` / ``row
+ N missing from index``) the table b-trees are intact and REINDEX rebuilds
+ losslessly — take the content-addressed corrupt backup FIRST, REINDEX
+ under the caller-held init flock, re-check, proceed only if clean. Any
+ other failure (page corruption, ``malformed``, unclean re-check) fails
+ closed: copy the file + WAL/SHM sidecars to a backup and raise
+ :class:`KanbanDbCorruptError` so callers never recreate the schema on top
+ of a damaged DB. ``sqlite3.OperationalError`` (lock/busy) is NOT
+ corruption and propagates raw (no spurious ``.corrupt`` backup). No-op for
+ missing / zero-byte (fresh) files and paths already proven healthy this
+ process. ``path`` comes from user-controlled-but-trusted sources; it is
+ resolved here and all writes are confined to its parent so stray ``..``
+ segments collapse before any I/O.
"""
# Resolve before any I/O. ``Path.resolve()`` normalizes ``..`` and
# symlinks, giving us a canonical path whose parent dir we can pin.
diff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.py
index 10847977758..9ff27b333f7 100644
--- a/hermes_cli/kanban_db_dispatch.py
+++ b/hermes_cli/kanban_db_dispatch.py
@@ -206,28 +206,17 @@ def _record_worker_exit(pid: int, raw_status: int) -> None:
def _classify_worker_exit(pid: int) -> "tuple[str, Optional[int]]":
- """Classify a recently-reaped worker by pid.
-
- Returns ``(kind, code)`` where ``kind`` is one of:
-
- * ``"clean_exit"`` — ``WIFEXITED`` with ``WEXITSTATUS == 0``. When the
- task is still ``running`` in the DB, this is a protocol violation
- (worker exited without calling ``kanban_complete`` / ``kanban_block``)
- and should be auto-blocked immediately — retrying will just loop.
- * ``"rate_limited"`` — ``WIFEXITED`` with status
- ``KANBAN_RATE_LIMIT_EXIT_CODE``. The worker bailed because the
- provider rate-limited / exhausted quota, NOT because the task failed.
- ``detect_crashed_workers`` releases the task back to ``ready`` without
- counting a failure, so a long quota window can't trip the breaker.
- * ``"nonzero_exit"`` — ``WIFEXITED`` with non-zero status. Real error.
- * ``"signaled"`` — ``WIFSIGNALED`` (OOM killer, SIGKILL, etc). Real crash.
- * ``"unknown"`` — pid was not in the reap registry (either reaped by
- something else, or died between reap tick and liveness check). Fall
- back to existing crashed-counter behavior.
-
- ``code`` is the exit status (for ``clean_exit`` / ``rate_limited`` /
- ``nonzero_exit``) or the signal number (for ``signaled``), or ``None``
- for ``unknown``.
+ """Return ``(kind, code)`` for a reaped worker PID.
+
+ ``clean_exit`` (status 0 — a still-``running`` task is a protocol
+ violation: worker exited without ``kanban_complete``/``kanban_block``, so
+ auto-block, retrying just loops); ``rate_limited`` (status
+ ``KANBAN_RATE_LIMIT_EXIT_CODE`` — provider quota wall, released back to
+ ``ready`` WITHOUT counting a failure so a long quota window can't trip the
+ breaker); ``nonzero_exit`` (real error); ``signaled`` (OOM/SIGKILL, real
+ crash; ``code`` is the signal); ``unknown`` (pid not in the reap registry
+ — reaped elsewhere or died between reap tick and liveness check — fall
+ back to the crashed-counter path; ``code`` is None).
"""
entry = _recent_worker_exits.get(int(pid))
if entry is None:
@@ -2012,35 +2001,23 @@ def _dispatch_once_locked(
max_in_progress_per_profile: Optional[int] = None,
reconcile_orphans: bool = True,
) -> DispatchResult:
- """Run one dispatcher tick.
-
- Steps:
- 1. Reclaim stale running tasks (TTL expired).
- 2. Reclaim stale running tasks (no recent heartbeat).
- 3. Reclaim crashed running tasks (host-local PID no longer alive).
- 3. Promote todo -> ready where all parents are done.
- 4. For each ready task with an assignee, atomically claim and call
- ``spawn_fn(task, workspace_path, board) -> Optional[int]``. The
- return value (if any) is recorded as ``worker_pid`` so subsequent
- ticks can detect crashes before the TTL expires.
-
- Spawn failures are counted per-task. After ``failure_limit`` consecutive
- failures the task is auto-blocked with the last error as its reason —
- prevents the dispatcher from thrashing forever on an unfixable task.
-
- ``max_spawn`` is a **live concurrency cap** (running + this tick's spawns
- across the board), not a per-tick budget — a per-tick reading would grow
- concurrency by N every tick on a busy board without bound.
-
- ``max_in_progress`` is a **host-level** cap: it counts running tasks on
- every active board plus this tick's spawns, because workers are OS
- processes sharing one machine's memory and a per-board reading would
- multiply the cap by the number of boards. ``max_spawn`` keeps its
- historical per-board semantics.
-
- ``spawn_fn`` defaults to ``_default_spawn``. Tests pass a stub.
- ``board`` pins workspace/log/db resolution for this tick to a specific
- board. When omitted, the current-board resolution chain is used.
+ """Run one dispatcher tick: reclaim stale (TTL / heartbeat) and crashed
+ (dead host-local PID) running tasks, promote todo -> ready where all
+ parents are done, then for each ready task with an assignee atomically
+ claim and call ``spawn_fn(task, workspace_path, board) -> Optional[int]``,
+ recording the returned PID as ``worker_pid`` so later ticks catch crashes
+ before the TTL expires.
+
+ After ``failure_limit`` consecutive per-task failures the task is
+ auto-blocked with the last error as reason (no thrashing on an unfixable
+ task). ``max_spawn`` is a live per-board concurrency cap (running + this
+ tick's spawns), not a per-tick budget — a per-tick reading would grow
+ concurrency by N every tick. ``max_in_progress`` is a host-level cap over
+ every active board plus this tick's spawns: workers are OS processes
+ sharing one machine's memory, so a per-board reading would multiply it by
+ the board count. ``spawn_fn`` defaults to ``_default_spawn`` (tests stub
+ it); ``board`` pins workspace/log/db resolution for this tick, else the
+ current-board chain is used.
"""
# Reap zombie children from previously spawned workers. See
# reap_worker_zombies() for the full rationale.