Skip to content

The agent that grows with you

fix(kanban): dispatcher sweeps survive text timestamps too

kshitijk4poorf5a6651231cf
diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.py
index 55066f1afa8..36d5736f73e 100644
--- a/hermes_cli/kanban_db.py
+++ b/hermes_cli/kanban_db.py
@@ -673,7 +673,7 @@ class Task:
skills_value = [str(s) for s in parsed if s] if isinstance(parsed, list) else None
return cls(
**{col: _lossy_text(row[col]) for col in _TASK_REQUIRED_COLUMNS},
- **{col: _to_epoch(row[col]) for col in _TASK_EPOCH_COLUMNS}, # outside writers may store text: epoch or None
+ **{col: _to_epoch(g(col)) for col in _TASK_EPOCH_COLUMNS}, # outside writers may store text: epoch or None
**{col: g(col) for col in _TASK_OPTIONAL_COLUMNS},
**{col: g(col) or None for col in _TASK_EMPTY_IS_NULL_COLUMNS},
# Pre-migration fallbacks (spawn_failures / last_spawn_error) are only
@@ -691,11 +691,11 @@ _TASK_REQUIRED_COLUMNS = (
"id", "title", "body", "assignee", "status", "priority", "created_by",
"workspace_kind", "workspace_path", "claim_lock",
)
-_TASK_EPOCH_COLUMNS = ("created_at", "started_at", "completed_at", "claim_expires")
+_TASK_EPOCH_COLUMNS = ("created_at", "started_at", "completed_at", "claim_expires", "last_heartbeat_at")
# Later-added columns read as NULL when absent from the row.
_TASK_OPTIONAL_COLUMNS = (
"branch_name", "project_id", "tenant", "result", "idempotency_key", "worker_pid",
- "max_runtime_seconds", "last_heartbeat_at", "current_run_id", "workflow_template_id",
+ "max_runtime_seconds", "current_run_id", "workflow_template_id",
"current_step_key", "max_retries", "session_id", "completion_contract",
)
# Text columns where "" is stored/read as "not set".
@@ -2382,10 +2382,10 @@ def release_stale_claims(
).fetchall()
for row in stale:
host_local = (row["claim_lock"] or "").startswith(host_prefix)
- hb = row["last_heartbeat_at"]
+ hb = _to_epoch(row["last_heartbeat_at"])
# Backstop: a heartbeat older than the max-stale threshold means no
# observable progress — reclaim even if the PID is alive (logic loop).
- heartbeat_stale = hb is not None and (now - int(hb)) > DEFAULT_CLAIM_HEARTBEAT_MAX_STALE_SECONDS
+ heartbeat_stale = hb is not None and (now - hb) > DEFAULT_CLAIM_HEARTBEAT_MAX_STALE_SECONDS
started_at = _row_get(row, "worker_started_at")
if (host_local and row["worker_pid"] and _worker_alive(row["worker_pid"], started_at)
and not heartbeat_stale):
@@ -2421,8 +2421,8 @@ def release_stale_claims(
payload={
"stale_lock": row["claim_lock"],
"worker_pid": _opt_int(row["worker_pid"]),
- "claim_expires": int(row["claim_expires"]),
- "last_heartbeat_at": _opt_int(row["last_heartbeat_at"]),
+ "claim_expires": _to_epoch(row["claim_expires"]),
+ "last_heartbeat_at": hb,
"now": now,
"host_local": host_local,
"heartbeat_stale": bool(heartbeat_stale),
@@ -2484,9 +2484,9 @@ def _extend_live_stale_claim(conn: sqlite3.Connection, row: sqlite3.Row, now: in
"reason": "pid_alive",
"worker_pid": int(row["worker_pid"]),
"claim_lock": row["claim_lock"],
- "claim_expires_was": int(row["claim_expires"]),
+ "claim_expires_was": _to_epoch(row["claim_expires"]),
"claim_expires_now": new_expires,
- "last_heartbeat_at": _opt_int(row["last_heartbeat_at"]),
+ "last_heartbeat_at": _to_epoch(row["last_heartbeat_at"]),
},
run_id=run_id,
)
diff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.py
index 38ae835875a..bf6c75bc5e2 100644
--- a/hermes_cli/kanban_db_dispatch.py
+++ b/hermes_cli/kanban_db_dispatch.py
@@ -673,7 +673,7 @@ def enforce_max_runtime(conn: sqlite3.Connection, *, signal_fn=None) -> list[str
continue
# Runtime is per attempt: ``tasks.started_at`` records the FIRST start,
# so retries must be measured from the active task_runs row.
- elapsed = now - int(row["active_started_at"])
+ elapsed = now - (_kb._to_epoch(row["active_started_at"]) or now) # unreadable clock: never kill
limit = int(row["max_runtime_seconds"])
if elapsed < limit:
continue
@@ -778,12 +778,12 @@ def detect_stale_running(
for row in rows:
if row["active_started_at"] is None:
continue
- elapsed = now - int(row["active_started_at"])
+ elapsed = now - (_kb._to_epoch(row["active_started_at"]) or now) # unreadable clock: never reclaim
if elapsed < stale_timeout_seconds:
continue
- last_hb = row["last_heartbeat_at"]
- hb_age = (now - int(last_hb)) if last_hb is not None else None
+ last_hb = _kb._to_epoch(row["last_heartbeat_at"])
+ hb_age = (now - last_hb) if last_hb is not None else None
if hb_age is not None and hb_age < _STALE_HEARTBEAT_GAP_SECONDS:
continue
@@ -883,7 +883,7 @@ def reconcile_orphaned_running(conn: sqlite3.Connection) -> list[str]:
payload = {
"reason": "orphaned_running",
"claim_lock": row["claim_lock"],
- "claim_expires": _kb._opt_int(row["claim_expires"]),
+ "claim_expires": _kb._to_epoch(row["claim_expires"]),
"worker_pid": int(pid) if pid else None,
"now": now,
}
@@ -1159,7 +1159,7 @@ def _reclaim_dead_workers(conn: sqlite3.Connection, board: Optional[str] = None)
continue
# Launch-window grace so a freshly-spawned worker isn't reclaimed
# before its PID is visible on /proc.
- started_at = _kb._row_get(row, "started_at")
+ started_at = _kb._to_epoch(_kb._row_get(row, "started_at"))
if started_at is not None and time.time() - started_at < _kb._resolve_crash_grace_seconds():
continue
if _worker_alive(row["worker_pid"], _kb._row_get(row, "worker_started_at")):
@@ -1639,7 +1639,7 @@ def check_respawn_guard(
"SELECT kind, payload FROM task_events "
"WHERE task_id = ? AND created_at > ? "
"AND kind IN ('assigned', 'changes_requested', 'review_reopened')",
- (task_id, int(c["created_at"] or 0)),
+ (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):
return None
diff --git a/hermes_cli/kanban_ops.py b/hermes_cli/kanban_ops.py
index 13d4d5be82b..37acd1872ec 100644
--- a/hermes_cli/kanban_ops.py
+++ b/hermes_cli/kanban_ops.py
@@ -294,7 +294,7 @@ def _cmd_watch(args: argparse.Namespace) -> int:
payload = None
pl = f" {payload}" if payload else ""
print(
- f"[{_fmt_ts(r['created_at'])}] {r['task_id']:10s} "
+ f"[{_fmt_ts(kb._to_epoch(r['created_at']))}] {r['task_id']:10s} "
f"{r['kind']:18s} (@{r['assignee'] or '-'}){pl}",
flush=True,
)
diff --git a/tests/hermes_cli/test_kanban_cli.py b/tests/hermes_cli/test_kanban_cli.py
index 109de962497..00b459356ab 100644
--- a/tests/hermes_cli/test_kanban_cli.py
+++ b/tests/hermes_cli/test_kanban_cli.py
@@ -133,8 +133,8 @@ def test_show_survives_iso_strings_in_integer_timestamp_columns(kanban_home):
payload = json.loads(kc.run_slash(f"show {task_id} --json"))
assert payload["task"]["id"] == task_id
- assert payload["runs"] and all(isinstance(r["ended_at"], int) for r in payload["runs"])
- assert payload["events"] and all(isinstance(e["created_at"], int) for e in payload["events"])
+ assert [r["ended_at"] for r in payload["runs"]] == [1787927722] # iso_utc, not a 0 fallback
+ assert payload["events"] and {e["created_at"] for e in payload["events"]} == {1787936336} # iso_z
def test_kanban_edit_updates_documented_task_fields(kanban_home):
diff --git a/tests/hermes_cli/test_kanban_review_lifecycle_complete.py b/tests/hermes_cli/test_kanban_review_lifecycle_complete.py
index a30440ae751..826b07b3ae4 100644
--- a/tests/hermes_cli/test_kanban_review_lifecycle_complete.py
+++ b/tests/hermes_cli/test_kanban_review_lifecycle_complete.py
@@ -383,6 +383,27 @@ def test_interrupted_review_runs_retry_in_review_phase(
assert event.payload.get("retry_status") == "review"
+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)
+ 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]
+
+
def test_review_retry_still_trips_the_failure_breaker(conn) -> None:
task_id, _review = _claimed_review(conn, "Reviewer repeatedly fails")
assert kbd._record_task_failure(