The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(kanban): respawn guards compare mixed int/ISO times by value
kshitijk4poor7cc3fb8cb558
diff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.pyindex bf6c75bc5e2..7ae9f4dcfcf 100644--- a/hermes_cli/kanban_db_dispatch.py+++ b/hermes_cli/kanban_db_dispatch.py@@ -21,6 +21,7 @@ from pathlib import Pathfrom typing import Anyfrom typing import Callablefrom typing import Iterable+from typing import Iteratorfrom typing import Mappingfrom typing import Optionalfrom typing import TYPE_CHECKING@@ -1600,24 +1601,11 @@ def check_respawn_guard(# AFTER that success (done→ready drag, re-promotion, unblock, reclaim) is# a deliberate "run it again" — otherwise a manual done→ready would sit# silently held until the window elapses.- cutoff = now - _RESPAWN_GUARD_SUCCESS_WINDOW- recent_completed = conn.execute(- "SELECT ended_at FROM task_runs "- "WHERE task_id = ? AND outcome = 'completed' AND ended_at >= ? "- "ORDER BY ended_at DESC LIMIT 1",- (task_id, cutoff),- ).fetchone()- if recent_completed:- completed_at = _kb._to_epoch(recent_completed["ended_at"]) or 0- requeued_after = conn.execute(- "SELECT 1 FROM task_events "- "WHERE task_id = ? AND created_at >= ? "- "AND kind IN ('status', 'promoted', 'unblocked', 'reclaimed') "- "LIMIT 1",- (task_id, completed_at),- ).fetchone()- if not requeued_after:- return "recent_success"+ success = max((t for t, _ in _rows_since(+ conn, "task_runs", task_id, now - _RESPAWN_GUARD_SUCCESS_WINDOW, "AND outcome = 'completed'")), default=None)+ if success is not None and not any(_rows_since(+ conn, "task_events", task_id, success, "AND kind IN ('status', 'promoted', 'unblocked', 'reclaimed')")):+ return "recent_success"# 4. GitHub PR URL in a recent comment — prior worker already opened a PR.# Exception: a handoff AFTER the newest PR comment (operator reassign,@@ -1625,29 +1613,38 @@ def check_respawn_guard(# now work on THAT PR — a closer or the implementer finishing it, not a# duplicate implementation (#111910). A crash/reclaim is not a handoff,# so the worker that opened the PR is still not re-spawned against it.- pr_cutoff = now - _RESPAWN_GUARD_PR_WINDOW- for c in conn.execute(- "SELECT body, created_at FROM task_comments "- "WHERE task_id = ? AND created_at >= ? ORDER BY created_at DESC",- (task_id, pr_cutoff),- ).fetchall():- body = _kb._lossy_text(c["body"])- if not (body and _RESPAWN_GUARD_PR_URL_RE.search(body)):- continue- events = conn.execute(- # Strictly after: a same-second tie stays guarded (fail closed).- "SELECT kind, payload FROM task_events "- "WHERE task_id = ? AND created_at > ? "- "AND kind IN ('assigned', 'changes_requested', 'review_reopened')",- (task_id, _kb._to_epoch(c["created_at"]) or now), # unreadable: guard stays on- ).fetchall()- if any(_is_handoff_event(e["kind"], e["payload"]) for e in events):+ pr_times = [t for t, c in _rows_since(conn, "task_comments", task_id, now - _RESPAWN_GUARD_PR_WINDOW,+ cols=", body", unreadable=now) # duplicate-PR risk: fail closed+ if _RESPAWN_GUARD_PR_URL_RE.search(_kb._lossy_text(c["body"]) or "")]+ if pr_times:+ # Strictly after: a same-second tie stays guarded (fail closed).+ if any(_is_handoff_event(e["kind"], e["payload"]) for _, e in _rows_since(+ conn, "task_events", task_id, max(pr_times),+ "AND kind IN ('assigned', 'changes_requested', 'review_reopened')", cols=", kind, payload", strict=True)):return Nonereturn "active_pr"return None+_GUARD_TIME_COLS = {"task_runs": "ended_at", "task_events": "created_at", "task_comments": "created_at"}+++def _rows_since(conn: sqlite3.Connection, table: str, task_id: str, since: int, where: str = "", *,+ cols: str = "", strict: bool = False, unreadable: Optional[int] = None) -> Iterator[tuple[int, Any]]:+ """``(epoch, row)`` for ``task_id``'s ``table`` rows timed at/after ``since`` (after, if ``strict``).+ SQLite sorts TEXT above every INTEGER, so the indexed range also returns every text stamp (written+ outside the mutators, #97455); those are decided on their parsed epoch. An unreadable time is+ dropped (never guards or lifts) unless the caller substitutes ``unreadable``."""+ col = _GUARD_TIME_COLS[table]+ sql = f"SELECT {col}{cols} FROM {table} WHERE task_id = ? {where} AND {col} {'>' if strict else '>='} ?"+ for row in conn.execute(sql, (task_id, since)):+ t = _kb._to_epoch(row[0])+ t = unreadable if t is None else t+ if t is not None and (t > since if strict else t >= since):+ yield t, row++def _is_handoff_event(kind: str, payload: Optional[str]) -> bool:"""Only an ``assigned`` event that moves the card to a DIFFERENT profile isa handoff. A no-op re-assign (dev→dev via CLI/dashboard/``reassigndiff --git a/tests/hermes_cli/test_kanban_review_lifecycle_complete.py b/tests/hermes_cli/test_kanban_review_lifecycle_complete.pyindex 826b07b3ae4..037adafc988 100644--- a/tests/hermes_cli/test_kanban_review_lifecycle_complete.py+++ b/tests/hermes_cli/test_kanban_review_lifecycle_complete.py@@ -383,25 +383,80 @@ def test_interrupted_review_runs_retry_in_review_phase(assert event.payload.get("retry_status") == "review"+def _iso(ago: int) -> str:+ return time.strftime("%Y-%m-%dT%H:%M:%S+00:00", time.gmtime(int(time.time()) - ago))++def test_dispatcher_sweeps_survive_iso_text_timestamps(conn, monkeypatch) -> None:"""ISO text in the start/heartbeat columns (written outside the mutators,- #97455) must not abort the per-tick dispatcher sweeps that read them as- ints (each raised before): the max-runtime sweep skips an unreadable- start instead of killing, and the dead-worker backstop still reclaims."""- task_id = kb.create_task(conn, title="text clocks", assignee="builder", max_runtime_seconds=60)- claimed = kb.claim_task(conn, task_id) # host-local claim lock: the crash sweep's scope- assert claimed is not None- kbd._set_worker_pid(conn, task_id, 98765)+ #97455) must not abort the per-tick dispatcher sweeps, and a READABLE stamp+ must still drive the decision: an unreadable start is skipped (never killed),+ a fresh ISO heartbeat spares a run, an old ISO start times out / goes stale,+ and the dead-worker backstop reclaims."""+ iso = _iso+ monkeypatch.setattr(kbd, "_terminate_reclaimed_worker", lambda *a, **k: {"terminated": True})+ monkeypatch.setattr(kbd, "_kill_fn", lambda signal_fn: None)++ def running(title, *, start, heartbeat=None):+ task_id = kb.create_task(conn, title=title, assignee="builder", max_runtime_seconds=60)+ claimed = kb.claim_task(conn, task_id) # host-local claim lock: the sweeps' scope+ assert claimed is not None+ kbd._set_worker_pid(conn, task_id, 98765)+ with kb.write_txn(conn):+ conn.execute("UPDATE tasks SET started_at = ?, last_heartbeat_at = ? WHERE id = ?",+ (start, heartbeat, task_id))+ conn.execute("UPDATE task_runs SET started_at = ? WHERE id = ?", (start, claimed.current_run_id))+ return task_id++ garbled = running("garbled", start="not-a-timestamp", heartbeat="2020-01-01T00:00:00+00:00")+ assert kb.get_task(conn, garbled).last_heartbeat_at == 1577836800 # Task coerces it too+ assert kbd.enforce_max_runtime(conn) == [] # eligible (running, pid, cap) but unreadable: not killed+ assert kbd.detect_stale_running(conn, stale_timeout_seconds=1) == []+ fresh = running("fresh heartbeat", start=iso(7200), heartbeat=iso(5))+ assert kbd.detect_stale_running(conn, stale_timeout_seconds=600) == [] # fresh ISO heartbeat spares it+ stale = running("stale", start=iso(7200), heartbeat=iso(7200))+ assert kbd.detect_stale_running(conn, stale_timeout_seconds=600) == [stale]+ assert kbd.enforce_max_runtime(conn) == [fresh] # readable ISO start 2h ago > 60s cap+ monkeypatch.setattr(kb, "_pid_alive", lambda pid: False) # garbled start: past the launch grace+ assert kbd.detect_crashed_workers(conn) == [garbled]+++def test_respawn_guards_compare_mixed_int_and_iso_times_by_value(conn) -> None:+ """SQLite sorts TEXT above every INTEGER, so ISO stamps (#97455) must not pass+ the guards' SQL windows by type: an old ISO success does not hold a card, an+ old ISO PR comment does not either, and an ISO handoff OLDER than an int PR+ comment does not lift ``active_pr``."""+ now, iso = int(time.time()), _iso++ def card(title):+ task_id = kb.create_task(conn, title=title, assignee="dev")+ conn.execute("DELETE FROM task_events WHERE task_id = ?", (task_id,))+ return task_id++ def comment(task_id, at):+ conn.execute("INSERT INTO task_comments (task_id, author, body, created_at) VALUES (?, 'dev', ?, ?)",+ (task_id, "opened https://github.com/o/r/pull/1", at))++ old_success = card("old success")+ kb.claim_task(conn, old_success)+ kb.complete_task(conn, old_success, result="ok", force=True)+ with kb.write_txn(conn):+ conn.execute("UPDATE task_runs SET ended_at = ? WHERE task_id = ?", (iso(30 * 86400), old_success))+ conn.execute("DELETE FROM task_events WHERE task_id = ?", (old_success,))+ conn.execute("UPDATE tasks SET status = 'ready' WHERE id = ?", (old_success,))+ assert kbd.check_respawn_guard(conn, old_success) is None+ with kb.write_txn(conn):+ conn.execute("UPDATE task_runs SET ended_at = ? WHERE task_id = ?", (iso(60), old_success))+ assert kbd.check_respawn_guard(conn, old_success) == "recent_success" # a readable recent ISO still holds+with kb.write_txn(conn):- conn.execute("UPDATE tasks SET started_at = '2020-01-01T00:00:00+00:00', "- "last_heartbeat_at = '2020-01-01T00:00:00+00:00' WHERE id = ?", (task_id,))- conn.execute("UPDATE task_runs SET started_at = 'not-a-timestamp' WHERE id = ?",- (claimed.current_run_id,))- assert kb.get_task(conn, task_id).last_heartbeat_at == 1577836800 # Task coerces it too- assert kbd.enforce_max_runtime(conn) == [] # eligible row (running, pid, cap): skipped, not killed- assert kbd.detect_stale_running(conn, stale_timeout_seconds=1) == [] # same: not reclaimed on it- monkeypatch.setattr(kb, "_pid_alive", lambda pid: False) # text started_at: past the launch grace- assert kbd.detect_crashed_workers(conn) == [task_id]+ old_pr, guarded = card("old pr"), card("guarded")+ comment(old_pr, iso(90 * 86400))+ comment(guarded, now - 60)+ conn.execute("INSERT INTO task_events (task_id, kind, payload, created_at) VALUES "+ "(?, 'assigned', '{\"assignee\": \"ops\", \"from\": \"dev\"}', ?)", (guarded, iso(7200)))+ assert kbd.check_respawn_guard(conn, old_pr) is None+ assert kbd.check_respawn_guard(conn, guarded) == "active_pr"def test_review_retry_still_trips_the_failure_breaker(conn) -> None: