The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(kanban): host-level cap accounting, daemon cap resolution, review-lane reservation (OOF-30 review)
Shannon Sandse1e472d299b7
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 3281f41dea5..fa710b6d211 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -2530,8 +2530,11 @@ DEFAULT_CONFIG = {# default profile. A task never ends up with assignee=None."default_assignee": "",# Global concurrency cap (#33488): when set to a positive int, the- # board never has more than N tasks in 'running' at once, across- # both the ready and review dispatch lanes. Unset (None) means+ # HOST never has more than N tasks in 'running' at once — counted+ # across every active board and across both the ready and review+ # dispatch lanes (workers are OS processes sharing one machine's+ # memory, so the cap bounds the machine, not each board; OOF-30).+ # Unset (None) means# "derive from system memory" (OOF-30/OOF-77): the dispatcher caps# concurrency at roughly MemTotal / 512 MiB, clamped to [2, 8] —# e.g. 2 workers on a 1 GiB VM. On hosts where total memory can'tdiff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.pyindex 06f511d1771..79398b7d688 100644--- a/hermes_cli/kanban_db.py+++ b/hermes_cli/kanban_db.py@@ -9694,6 +9694,95 @@ def resolve_max_in_progress(configured: Optional[int]) -> Optional[int]:return derive_default_max_in_progress()+def configured_max_in_progress() -> Optional[int]:+ """Read ``kanban.max_in_progress`` from config, or None when unset/invalid.++ Small shared parser so every dispatch entry point (gateway watcher, CLI+ dispatch, standalone daemon) agrees on what "explicitly configured"+ means: a positive integer wins, anything else falls through to the+ memory-derived default via :func:`resolve_max_in_progress`.+ """+ try:+ from hermes_cli.config import load_config_readonly+ raw = (load_config_readonly() or {}).get("kanban", {}).get(+ "max_in_progress"+ )+ except Exception:+ return None+ if raw is None:+ return None+ try:+ ival = int(raw)+ except (TypeError, ValueError):+ return None+ return ival if ival >= 1 else None+++def count_running_tasks(conn: sqlite3.Connection) -> int:+ """Return the number of tasks currently in ``status='running'``.++ Used by the gateway's multi-board sweep to account for workers on+ OTHER boards against the host-level concurrency budget (OOF-30): the+ memory-derived cap bounds the machine, so each board's tick must see+ the machine's total, not just its own. Fails open to 0 — a broken+ board must not brick dispatch on healthy ones (corruption is handled+ separately by the watcher's quarantine logic).+ """+ try:+ return int(+ conn.execute(+ "SELECT COUNT(*) FROM tasks WHERE status = 'running'"+ ).fetchone()[0]+ )+ except Exception:+ return 0+++def count_running_tasks_other_boards(board: Optional[str] = None) -> int:+ """Total ``running`` tasks across every board EXCEPT ``board``.++ The concurrency caps bound the HOST (workers are OS processes sharing+ one machine's memory), but each board's dispatch tick only sees its own+ DB. Without this, a memory-derived cap of N gets multiplied by the+ number of active boards — reproduced in review of OOF-30: two boards+ each spawned N workers on a derived N-worker host budget.++ Boards are matched by resolved DB path, so the ``HERMES_KANBAN_DB``+ override (which pins every board to one file) naturally yields 0.+ Fails open per board: one broken/corrupt board must not brick dispatch+ on the healthy ones.+ """+ try:+ current_path = str(kanban_db_path(board=board).expanduser().resolve())+ except Exception:+ current_path = None+ try:+ boards = list_boards(include_archived=False)+ except Exception:+ return 0+ total = 0+ for meta in boards:+ slug = meta.get("slug") or DEFAULT_BOARD+ try:+ path = kanban_db_path(board=slug).expanduser()+ resolved = str(path.resolve())+ if current_path is not None and resolved == current_path:+ continue+ if not path.exists():+ continue+ other = connect(board=slug)+ try:+ total += count_running_tasks(other)+ finally:+ try:+ other.close()+ except Exception:+ pass+ except Exception:+ continue+ return total++def _memory_pressure_level(sample: Optional[Mapping[str, Any]] = None) -> str:"""Classify current system memory pressure: ok/elevated/critical/unknown.@@ -9837,6 +9926,13 @@ def _dispatch_once_locked(a 60-second tick interval could grow concurrency by N every minute on abusy board and accumulate without bound.+ ``max_in_progress`` is a **host-level** concurrency cap (OOF-30): it+ counts running tasks on every active board — not just this one — plus+ this tick's spawns. Workers are OS processes sharing one machine's+ memory, so a per-board interpretation would multiply the cap by the+ number of active boards. ``max_spawn`` retains 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 specificboard. When omitted, the current-board resolution chain is used.@@ -9885,11 +9981,7 @@ def _dispatch_once_locked(running_count = 0spawn_budget: Optional[int] = Noneif max_spawn is not None or max_in_progress is not None:- running_count = int(- conn.execute(- "SELECT COUNT(*) FROM tasks WHERE status = 'running'"- ).fetchone()[0]- )+ running_count = count_running_tasks(conn)# Convert any concurrency caps into a shared additional-spawns budget# for this tick. Both ready and review loops consume from the same@@ -9903,10 +9995,17 @@ def _dispatch_once_locked(# the board already has enough running tasks, skip this tick entirely.# When there is room left, intersect the remaining in-progress budget# with any explicit max_spawn cap above.+ #+ # max_in_progress is a HOST-level cap, not a per-board one (OOF-30):+ # workers are OS processes sharing one machine's memory, so running+ # workers on every other board count against the same budget. Without+ # this, N active boards multiply the cap by N — exactly the fan-out+ # the memory-derived default exists to prevent.if max_in_progress is not None:- if running_count >= max_in_progress:+ total_running = running_count + count_running_tasks_other_boards(board)+ if total_running >= max_in_progress:return result- remaining = max_in_progress - running_count+ remaining = max_in_progress - total_runningif spawn_budget is None or spawn_budget > remaining:spawn_budget = remaining@@ -9939,6 +10038,42 @@ def _dispatch_once_locked("WHERE status = 'ready' AND claim_lock IS NULL ""ORDER BY priority DESC, created_at ASC").fetchall()+ # Review rows are enumerated up front (not after the ready loop) so the+ # budget split below can see whether review work exists at all.+ review_rows = []+ if review_dispatch_enabled():+ review_rows = conn.execute(+ "SELECT id, assignee FROM tasks "+ "WHERE status = 'review' AND claim_lock IS NULL "+ "ORDER BY priority DESC, created_at ASC"+ ).fetchall()+ # Review-lane reservation (OOF-30 review finding): the ready loop runs+ # first and used to consume the ENTIRE shared budget, so a sustained+ # ready backlog permanently starved autonomous reviews — completed work+ # sat in 'review' forever while new work kept spawning. When spawnable+ # review work exists and the tick has any budget, hold one slot back+ # from the ready loop so the review lane always gets a spawn+ # opportunity. The reservation is per-tick and self-releasing: with no+ # spawnable review work (or no cap at all) the ready loop keeps the+ # full budget. "Spawnable" mirrors the review loop's own gate+ # (assigned + real profile) so a review column full of human-pulled+ # control-plane lanes doesn't permanently tax ready throughput.+ def _any_spawnable_review() -> bool:+ if not review_rows:+ return False+ try:+ from hermes_cli.profiles import profile_exists as _rpe+ except Exception:+ # Profiles module unavailable (test stubs, exotic envs) —+ # assume spawnable, matching the review loop's own fallback.+ return any(row["assignee"] for row in review_rows)+ return any(+ row["assignee"] and _rpe(row["assignee"]) for row in review_rows+ )++ ready_budget = spawn_budget+ if spawn_budget is not None and spawn_budget > 0 and _any_spawnable_review():+ ready_budget = max(spawn_budget - 1, 0)spawned = 0# Per-profile concurrency cap (#21582): when set, track how many# workers each assignee already has in flight, and refuse to spawn@@ -9977,7 +10112,7 @@ def _dispatch_once_locked(# there, with the existing diagnostic._default_assignee_resolved = Truefor row in ready_rows:- if spawn_budget is not None and spawned >= spawn_budget:+ if ready_budget is not None and spawned >= ready_budget:breakrow_assignee = row["assignee"]if not row_assignee:@@ -10174,13 +10309,13 @@ def _dispatch_once_locked(# ``sdlc-review`` skill and reviewer workers can now approve, request# changes without block-loop accounting, or escalate a genuine blocker.# Human-only boards can disable it with ``kanban.review_dispatch``.- review_rows = []- if review_dispatch_enabled():- review_rows = conn.execute(- "SELECT id, assignee FROM tasks "- "WHERE status = 'review' AND claim_lock IS NULL "- "ORDER BY priority DESC, created_at ASC"- ).fetchall()+ #+ # ``review_rows`` was enumerated before the ready loop; when it is+ # non-empty the ready loop ran against ``ready_budget`` (one slot held+ # back) so this lane cannot be permanently starved by a sustained+ # ready backlog. The review loop itself still checks the FULL shared+ # ``spawn_budget`` — the reservation caps the ready lane, it does not+ # grant the review lane extra capacity.for row in review_rows:if spawn_budget is not None and spawned >= spawn_budget:break@@ -10804,6 +10939,11 @@ def run_daemon(on SIGINT / SIGTERM so ``hermes kanban daemon`` is systemd-friendly.``stop_event`` (a :class:`threading.Event`) and ``on_tick`` (acallable receiving the :class:`DispatchResult`) are test hooks.++ Each tick resolves ``kanban.max_in_progress`` (explicit config, else+ the memory-derived default) exactly like the gateway-embedded+ dispatcher and ``hermes kanban dispatch`` — the standalone daemon must+ not be the one uncapped entry point (OOF-30)."""import signalimport threading@@ -10827,10 +10967,22 @@ def run_daemon(while not stop_event.is_set():try:+ # Resolve the global concurrency cap the same way the gateway+ # dispatcher and `hermes kanban dispatch` do (OOF-30): explicit+ # kanban.max_in_progress wins, otherwise the memory-derived+ # default applies. The standalone daemon previously passed no+ # cap at all — the shipped systemd path could still fan out an+ # entire backlog in one tick even with the derived default in+ # place everywhere else. Re-resolved every tick (config load is+ # mtime-cached) so operator edits apply without a restart.+ max_in_progress = resolve_max_in_progress(+ configured_max_in_progress()+ )with contextlib.closing(connect()) as conn:res = dispatch_once(conn,max_spawn=max_spawn,+ max_in_progress=max_in_progress,failure_limit=failure_limit,)if on_tick is not None:diff --git a/tests/hermes_cli/test_kanban_host_cap.py b/tests/hermes_cli/test_kanban_host_cap.pynew file mode 100644index 00000000000..61de23da9e2--- /dev/null+++ b/tests/hermes_cli/test_kanban_host_cap.py@@ -0,0 +1,313 @@+"""Host-level concurrency accounting + review-lane fairness (OOF-30 review).++Three gaps found in review of the original memory-guard PR:++1. The standalone daemon path (``hermes kanban daemon --force`` /+ :func:`hermes_cli.kanban_db.run_daemon`) never resolved+ ``kanban.max_in_progress`` at all — the one shipped entry point that+ could still fan out an entire backlog in a single tick.+2. ``max_in_progress`` was enforced per-board while the gateway dispatcher+ ticks every active board — N boards multiplied the host budget by N.+3. The ready loop consumed the entire shared spawn budget before the+ review loop ran, so a sustained ready backlog starved autonomous+ reviews indefinitely.+"""++from __future__ import annotations++import sqlite3+import threading+from pathlib import Path++import pytest++from hermes_cli import kanban_db as kb+++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+++def _set_task_status(conn: sqlite3.Connection, task_id: str, status: str) -> None:+ conn.execute("UPDATE tasks SET status = ? WHERE id = ?", (status, task_id))+++def _fake_spawn_factory(spawns: list):+ def fake_spawn(task, workspace, board=None):+ spawns.append(task.id)+ return 42+ return fake_spawn+++# ---------------------------------------------------------------------------+# 1. Standalone daemon resolves max_in_progress (P1a)+# ---------------------------------------------------------------------------+++def test_run_daemon_resolves_and_passes_max_in_progress(+ kanban_home, monkeypatch,+):+ """The daemon tick must pass a resolved cap into dispatch_once.++ Regression guard for the OOF-30 review finding: ``run_daemon`` only+ forwarded ``max_spawn`` — with no explicit ``--max`` (the shipped+ systemd shape) nothing capped the tick even though the gateway and+ ``hermes kanban dispatch`` paths both resolved the memory-derived+ default.+ """+ captured: dict = {}+ stop = threading.Event()++ def fake_dispatch_once(conn, **kwargs):+ captured.update(kwargs)+ return kb.DispatchResult()++ monkeypatch.setattr(kb, "dispatch_once", fake_dispatch_once)+ # No explicit config → the derived default must flow through.+ monkeypatch.setattr(kb, "configured_max_in_progress", lambda: None)+ monkeypatch.setattr(kb, "derive_default_max_in_progress", lambda sample=None: 3)++ def on_tick(res):+ stop.set()++ kb.run_daemon(interval=0.01, stop_event=stop, on_tick=on_tick)++ assert captured.get("max_in_progress") == 3+++def test_run_daemon_explicit_config_wins(kanban_home, monkeypatch):+ captured: dict = {}+ stop = threading.Event()++ def fake_dispatch_once(conn, **kwargs):+ captured.update(kwargs)+ return kb.DispatchResult()++ monkeypatch.setattr(kb, "dispatch_once", fake_dispatch_once)+ monkeypatch.setattr(kb, "configured_max_in_progress", lambda: 7)+ monkeypatch.setattr(+ kb, "derive_default_max_in_progress",+ lambda sample=None: pytest.fail("derived default must not be consulted"),+ )++ def on_tick(res):+ stop.set()++ kb.run_daemon(interval=0.01, stop_event=stop, on_tick=on_tick)++ assert captured.get("max_in_progress") == 7+++def test_configured_max_in_progress_parsing(monkeypatch):+ import hermes_cli.config as cfgmod++ cases = [+ ({"kanban": {"max_in_progress": 4}}, 4),+ ({"kanban": {"max_in_progress": "5"}}, 5),+ ({"kanban": {"max_in_progress": 0}}, None),+ ({"kanban": {"max_in_progress": -2}}, None),+ ({"kanban": {"max_in_progress": "lots"}}, None),+ ({"kanban": {}}, None),+ ({}, None),+ ]+ for config, expected in cases:+ monkeypatch.setattr(+ cfgmod, "load_config_readonly", lambda c=config: c+ )+ assert kb.configured_max_in_progress() == expected, config+++# ---------------------------------------------------------------------------+# 2. max_in_progress counts running work on ALL boards (P1b)+# ---------------------------------------------------------------------------+++def test_max_in_progress_counts_other_boards(+ kanban_home, all_assignees_spawnable,+):+ """Workers running on another board consume the same host budget."""+ kb.create_board("second")++ # Two workers already running on the second board.+ with kb.connect(board="second") as conn:+ for title in ("busy-1", "busy-2"):+ tid = kb.create_task(conn, title=title, assignee="alice")+ assert kb.claim_task(conn, tid) is not None++ spawns: list = []+ with kb.connect() as conn:+ kb.create_task(conn, title="wants-to-run", assignee="alice")+ res = kb.dispatch_once(+ conn, spawn_fn=_fake_spawn_factory(spawns), max_in_progress=2,+ )++ # Host budget (2) already consumed by the second board → nothing spawns.+ assert not spawns+ assert not res.spawned+++def test_max_in_progress_partial_budget_across_boards(+ kanban_home, all_assignees_spawnable,+):+ kb.create_board("second")++ with kb.connect(board="second") as conn:+ tid = kb.create_task(conn, title="busy", assignee="alice")+ assert kb.claim_task(conn, tid) is not None++ spawns: list = []+ with kb.connect() as conn:+ for title in ("a", "b", "c"):+ kb.create_task(conn, title=title, assignee="alice")+ res = kb.dispatch_once(+ conn, spawn_fn=_fake_spawn_factory(spawns), max_in_progress=2,+ )++ # 1 running elsewhere + budget 2 → exactly one new spawn here.+ assert len(spawns) == 1+ assert len(res.spawned) == 1+++def test_count_running_tasks_other_boards_fails_open(+ kanban_home, monkeypatch,+):+ """A broken board enumeration must not brick dispatch (returns 0)."""+ monkeypatch.setattr(+ kb, "list_boards",+ lambda **k: (_ for _ in ()).throw(RuntimeError("boom")),+ )+ assert kb.count_running_tasks_other_boards() == 0+++def test_max_spawn_stays_per_board(kanban_home, all_assignees_spawnable):+ """``max_spawn`` keeps its historical per-board semantics."""+ kb.create_board("second")+ with kb.connect(board="second") as conn:+ tid = kb.create_task(conn, title="busy", assignee="alice")+ assert kb.claim_task(conn, tid) is not None++ spawns: list = []+ with kb.connect() as conn:+ kb.create_task(conn, title="a", assignee="alice")+ res = kb.dispatch_once(+ conn, spawn_fn=_fake_spawn_factory(spawns), max_spawn=1,+ )++ # The other board's worker does NOT count against max_spawn.+ assert len(spawns) == 1+ assert len(res.spawned) == 1+++# ---------------------------------------------------------------------------+# 3. Review lane cannot be starved by a sustained ready backlog (P2)+# ---------------------------------------------------------------------------+++def _park_in_review(conn: sqlite3.Connection, title: str, assignee: str) -> str:+ tid = kb.create_task(conn, title=title, assignee=assignee)+ _set_task_status(conn, tid, "review")+ return tid+++def test_review_lane_gets_reserved_slot_under_ready_backlog(+ kanban_home, all_assignees_spawnable, monkeypatch,+):+ import hermes_cli.config as cfgmod+ monkeypatch.setattr(+ cfgmod, "load_config",+ lambda *a, **k: {"kanban": {"review_dispatch": True}},+ )++ spawns: list = []+ with kb.connect() as conn:+ for title in ("ready-1", "ready-2", "ready-3"):+ kb.create_task(conn, title=title, assignee="alice")+ review_id = _park_in_review(conn, "review-me", "reviewer")+ res = kb.dispatch_once(+ conn, spawn_fn=_fake_spawn_factory(spawns), max_in_progress=2,+ )++ spawned_ids = [s[0] for s in res.spawned]+ # Budget 2: one ready + the reserved review slot — never 2×ready.+ assert len(spawned_ids) == 2+ assert review_id in spawned_ids+++def test_review_reservation_released_when_no_review_work(+ kanban_home, all_assignees_spawnable, monkeypatch,+):+ import hermes_cli.config as cfgmod+ monkeypatch.setattr(+ cfgmod, "load_config",+ lambda *a, **k: {"kanban": {"review_dispatch": True}},+ )++ spawns: list = []+ with kb.connect() as conn:+ for title in ("ready-1", "ready-2", "ready-3"):+ kb.create_task(conn, title=title, assignee="alice")+ res = kb.dispatch_once(+ conn, spawn_fn=_fake_spawn_factory(spawns), max_in_progress=2,+ )++ # No review work → ready lane keeps the full budget.+ assert len(res.spawned) == 2+++def test_nonspawnable_review_does_not_tax_ready_budget(+ kanban_home, monkeypatch,+):+ """Review tasks parked for humans (no real profile) release the slot."""+ import hermes_cli.config as cfgmod+ import hermes_cli.profiles as profmod++ monkeypatch.setattr(+ cfgmod, "load_config",+ lambda *a, **k: {"kanban": {"review_dispatch": True}},+ )+ # Only 'alice' is a real profile; the review assignee is a human lane.+ monkeypatch.setattr(+ profmod, "profile_exists", lambda name: name == "alice"+ )++ spawns: list = []+ with kb.connect() as conn:+ for title in ("ready-1", "ready-2"):+ kb.create_task(conn, title=title, assignee="alice")+ _park_in_review(conn, "human-review", "some-human")+ res = kb.dispatch_once(+ conn, spawn_fn=_fake_spawn_factory(spawns), max_in_progress=2,+ )++ # Human-lane review is not spawnable → no reservation, ready gets both.+ assert len(res.spawned) == 2+++def test_review_budget_still_bounded_by_shared_cap(+ kanban_home, all_assignees_spawnable, monkeypatch,+):+ """The reservation caps the ready lane; it grants review no extra slots."""+ import hermes_cli.config as cfgmod+ monkeypatch.setattr(+ cfgmod, "load_config",+ lambda *a, **k: {"kanban": {"review_dispatch": True}},+ )++ spawns: list = []+ with kb.connect() as conn:+ kb.create_task(conn, title="ready-1", assignee="alice")+ for i in range(3):+ _park_in_review(conn, f"review-{i}", "reviewer")+ res = kb.dispatch_once(+ conn, spawn_fn=_fake_spawn_factory(spawns), max_in_progress=2,+ )++ # Budget 2 total across both lanes, reservation notwithstanding.+ assert len(res.spawned) == 2