Skip to content

The agent that grows with you

fix(kanban): capture worker exit codes on Windows so rate-limited exits requeue

teknium1984c12b98312
diff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.py
index 5590176f55c..419d653d146 100644
--- a/hermes_cli/kanban_db_dispatch.py
+++ b/hermes_cli/kanban_db_dispatch.py
@@ -184,6 +184,16 @@ _RECENT_WORKER_EXIT_TTL_SECONDS = 600
_RECENT_WORKER_EXITS_MAX = 4096
_recent_worker_exits: "dict[int, tuple[int, float]]" = {}
+# Windows has no ``waitpid(-1)``: a child's exit code is only recoverable
+# through a live handle, so ``_default_spawn`` parks each worker's ``Popen``
+# here (Windows only) and ``reap_worker_zombies`` polls it. Entry: ``pid -> Popen``.
+_live_worker_procs: "dict[int, subprocess.Popen]" = {}
+
+
+def _wait_status_from_returncode(returncode: int) -> int:
+ """Encode a ``Popen.returncode`` in the wait-status layout the registry stores."""
+ return (int(returncode) & 0xFF) << 8
+
def _record_worker_exit(pid: int, raw_status: int) -> None:
"""Record a reaped child's exit status; duplicate pids overwrite (latest wins)."""
@@ -231,21 +241,32 @@ def _classify_worker_exit(pid: int) -> "tuple[str, Optional[int]]":
def reap_worker_zombies() -> "list[int]":
- """Reap all zombie children without blocking; returns reaped PIDs. No-op on Windows."""
+ """Reap exited workers without blocking; returns reaped PIDs. POSIX reaps
+ every child via ``waitpid(-1)``; Windows polls the ``Popen`` handles
+ parked by ``_default_spawn`` (the only way to learn a child's exit code
+ there), so the rate-limit sentinel exit is classified on both hosts."""
reaped: "list[int]" = []
- if os.name != "nt":
- try:
- while True:
- try:
- pid, status = os.waitpid(-1, os.WNOHANG)
- except ChildProcessError:
- break
- if pid == 0:
- break
- _record_worker_exit(pid, status)
- reaped.append(pid)
- except Exception:
- pass
+ if _kb._IS_WINDOWS:
+ for pid, proc in list(_live_worker_procs.items()):
+ returncode = proc.poll()
+ if returncode is None:
+ continue
+ _record_worker_exit(pid, _wait_status_from_returncode(returncode))
+ _live_worker_procs.pop(pid, None)
+ reaped.append(pid)
+ return reaped
+ try:
+ while True:
+ try:
+ pid, status = os.waitpid(-1, os.WNOHANG)
+ except ChildProcessError:
+ break
+ if pid == 0:
+ break
+ _record_worker_exit(pid, status)
+ reaped.append(pid)
+ except Exception:
+ pass
return reaped
@@ -2748,6 +2769,8 @@ def _default_spawn(task: Task, workspace: str, *, board: Optional[str] = None) -
)
# Intentionally NOT closing log_f: the child keeps writing after return;
# the OS-level FD stays open in the child until it exits.
+ if _kb._IS_WINDOWS:
+ _live_worker_procs[proc.pid] = proc
return proc.pid
diff --git a/tests/hermes_cli/test_kanban_worker_exit_decode.py b/tests/hermes_cli/test_kanban_worker_exit_decode.py
new file mode 100644
index 00000000000..8d4e11cc617
--- /dev/null
+++ b/tests/hermes_cli/test_kanban_worker_exit_decode.py
@@ -0,0 +1,68 @@
+"""Worker exit classification must not depend on POSIX-only ``os.WIF*`` helpers.
+
+``_classify_worker_exit`` feeds the dead-worker reclaim: a ``rate_limited``
+verdict requeues the card without counting a failure, ``unknown`` counts as a
+crash. Windows has neither ``os.WIFEXITED`` nor ``waitpid(-1)``, so both the
+decode and the reaper's exit capture have a Windows-independent path.
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+
+import pytest
+
+from hermes_cli import kanban_db as kb
+from hermes_cli import kanban_db_dispatch as kbd
+
+
+def _spawn_exit(code: int) -> subprocess.Popen:
+ proc = subprocess.Popen([sys.executable, "-c", f"raise SystemExit({code})"]) # noqa: S603
+ proc.wait()
+ return proc
+
+
+def test_windows_reaper_classifies_parked_popen_exit(monkeypatch):
+ """With the Windows flag on, the reaper learns exit codes from the parked
+ ``Popen`` handles (no ``waitpid``) and the decode needs no ``os.WIF*``:
+ the rate-limit sentinel is ``rate_limited``, a crash ``nonzero_exit``,
+ and a still-running worker is left alone."""
+ monkeypatch.setattr(kb, "_IS_WINDOWS", True)
+ for name in ("WIFEXITED", "WEXITSTATUS", "WIFSIGNALED", "WTERMSIG"):
+ monkeypatch.delattr(os, name, raising=False)
+ monkeypatch.setattr(kbd, "_live_worker_procs", {})
+ monkeypatch.setattr(kbd, "_recent_worker_exits", {})
+
+ limited = _spawn_exit(kb.KANBAN_RATE_LIMIT_EXIT_CODE)
+ crashed = _spawn_exit(3)
+ alive = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"]) # noqa: S603
+ try:
+ for proc in (limited, crashed, alive):
+ kbd._live_worker_procs[proc.pid] = proc
+
+ reaped = kbd.reap_worker_zombies()
+
+ assert sorted(reaped) == sorted([limited.pid, crashed.pid])
+ assert kbd._classify_worker_exit(limited.pid) == ("rate_limited", kb.KANBAN_RATE_LIMIT_EXIT_CODE)
+ assert kbd._classify_worker_exit(crashed.pid) == ("nonzero_exit", 3)
+ assert kbd._classify_worker_exit(alive.pid) == ("unknown", None)
+ assert set(kbd._live_worker_procs) == {alive.pid}
+ finally:
+ alive.kill()
+ alive.wait()
+
+
+def test_native_windows_reaper_and_decode(monkeypatch):
+ """Native Windows, nothing patched: ``_IS_WINDOWS`` selects the Popen-poll
+ reaper and the decode runs where ``os.WIFEXITED`` does not exist, so the
+ rate-limit sentinel exit is a requeue, not a crash."""
+ monkeypatch.setattr(kbd, "_live_worker_procs", {})
+ monkeypatch.setattr(kbd, "_recent_worker_exits", {})
+ assert not hasattr(os, "WIFEXITED")
+ proc = _spawn_exit(kb.KANBAN_RATE_LIMIT_EXIT_CODE)
+ kbd._live_worker_procs[proc.pid] = proc
+ assert kbd.reap_worker_zombies() == [proc.pid]
+ assert kbd._classify_worker_exit(proc.pid) == ("rate_limited", kb.KANBAN_RATE_LIMIT_EXIT_CODE)