Skip to content

HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.

responses: a turn that has not started is not an orphan (#234)

github-actions[bot]5dff51a73862
diff --git a/gateway/app.py b/gateway/app.py
index e1b1ed29..33dd8c36 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -2703,6 +2703,14 @@ def _hb_seconds(v: dict) -> float:
return 0.0
+def _born_seconds(d: dict) -> float:
+ """When a record or a session vertex was created; 0 when unreadable."""
+ try:
+ return float(d.get("created_at") or 0)
+ except Exception: # noqa: BLE001
+ return 0.0
+
+
async def _reconcile_response(rid: str, rec: dict) -> dict:
"""Durable settler for an async (background) response record. GET /v1/responses/{id} is the
ONLY completion signal a background poller has, so a record left at 'running' by a replica that
@@ -2716,6 +2724,15 @@ async def _reconcile_response(rid: str, rec: dict) -> dict:
if not sid:
return rec
v = await _vertex_get(sid) or {}
+ if not v:
+ # THE OWNER HAS NOT WRITTEN THE SESSION YET. A background record is readable the moment its
+ # POST returns, and the turn's task writes the session vertex a beat later; a poller that
+ # reads in between saw no vertex, an "infinitely stale" heartbeat and an age past the hard
+ # cap, and this settled the record as failed and PERSISTED it, so every later read said
+ # failed until the owner's final write (measured 2026-09-21: every inner run a calibrator
+ # started read `failed`, error null, for its whole life). A turn that has not started is
+ # not an orphan.
+ return rec
vs = str(v.get("status") or "")
settled = None
if vs in ("done", "failed", "cancelled") and time.time() - _hb_seconds(v) < _RECONCILE_STALE_S:
@@ -2750,7 +2767,10 @@ async def _reconcile_response(rid: str, rec: dict) -> dict:
# That is the invented-diagnosis bug this field exists to remove, one layer down.
# Unknown stays absent, and the console renders the neutral badge with no line.
else:
- hb = _hb_seconds(v)
+ # The floor under the heartbeat is the turn's birth, the record's and the vertex's: a vertex
+ # the turn has not stamped yet carries no heartbeat, and an orphan test that reads 0 for
+ # "never" calls every newborn a corpse. Staleness is measured from the last sign of life.
+ hb = max(_hb_seconds(v), _born_seconds(rec), _born_seconds(v))
if time.time() - hb >= _RECONCILE_STALE_S: # owner stopped heartbeating → orphaned
ts = await _trace_terminal_status(v.get("trace_blob"))
if ts:
diff --git a/gateway/tests/test_reconcile_newborn.py b/gateway/tests/test_reconcile_newborn.py
new file mode 100644
index 00000000..7ea43c8a
--- /dev/null
+++ b/gateway/tests/test_reconcile_newborn.py
@@ -0,0 +1,74 @@
+"""A background response is readable the moment its POST returns; the turn's task writes the
+session vertex and its first heartbeat a beat later. The reconciler that settles orphans must not
+call that newborn a corpse: no vertex yet, or a vertex without a heartbeat yet, is a turn that has
+not started, not one that died (measured 2026-09-21: every inner run a calibrator started read
+`failed`, error null, for its whole life, because the reconciler persisted `failed` on the first
+read and the owner's final write was the only thing that ever corrected it)."""
+import asyncio
+import os
+import pathlib
+import sys
+import time
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+os.environ.setdefault("HR_BACKING", "local")
+import app as gw # noqa: E402
+
+
+def _run(rec, vertex, monkeypatch, trace_status=None):
+ puts: list = []
+
+ async def _vget(sid):
+ return vertex
+
+ async def _bput(key, data, kb=0):
+ puts.append(key)
+ return True
+
+ async def _bget(key, kb=0):
+ return None
+
+ async def _vgup(label, vid, props, **kw):
+ return None
+
+ async def _tts(blob):
+ return trace_status
+
+ monkeypatch.setattr(gw, "_vertex_get", _vget)
+ monkeypatch.setattr(gw, "_blob_put", _bput)
+ monkeypatch.setattr(gw, "_blob_get", _bget)
+ monkeypatch.setattr(gw, "_vg_upsert", _vgup)
+ monkeypatch.setattr(gw, "_trace_terminal_status", _tts)
+ monkeypatch.setattr(gw, "_resp_cache_forget", lambda rid: None)
+ out = asyncio.run(gw._reconcile_response("resp_1", dict(rec)))
+ return out, puts
+
+
+def test_a_record_whose_session_vertex_does_not_exist_yet_is_left_running(monkeypatch):
+ rec = {"status": "running", "_session_id": "hsess1", "created_at": int(time.time())}
+ out, puts = _run(rec, None, monkeypatch)
+ assert out["status"] == "running" and puts == []
+
+
+def test_a_vertex_the_turn_has_not_stamped_yet_is_a_newborn_not_an_orphan(monkeypatch):
+ now = time.time()
+ rec = {"status": "running", "_session_id": "hsess1", "created_at": int(now)}
+ vertex = {"status": "running", "created_at": str(now)} # no heartbeat yet
+ out, puts = _run(rec, vertex, monkeypatch)
+ assert out["status"] == "running" and puts == []
+
+
+def test_a_turn_that_stopped_heartbeating_past_the_cap_is_still_settled(monkeypatch):
+ old = time.time() - gw._GW_MAX_TURN_S - 600
+ rec = {"status": "running", "_session_id": "hsess1", "created_at": int(old)}
+ vertex = {"status": "running", "created_at": str(old), "heartbeat": str(old)}
+ out, puts = _run(rec, vertex, monkeypatch)
+ assert out["status"] == "failed" and puts == ["responses/resp_1.json"]
+
+
+def test_a_stale_turn_with_a_terminal_trace_settles_from_the_trace(monkeypatch):
+ old = time.time() - gw._RECONCILE_STALE_S - 60
+ rec = {"status": "running", "_session_id": "hsess1", "created_at": int(old)}
+ vertex = {"status": "running", "created_at": str(old), "heartbeat": str(old), "trace_blob": "x"}
+ out, puts = _run(rec, vertex, monkeypatch, trace_status="done")
+ assert out["status"] == "completed" and puts == ["responses/resp_1.json"]