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.
Python agent-apiagent-frameworkagent-harnessai-agentsai-infrastructurecoding-agentconformance-testingdeepseek-harnessharness-engineeringhermesllmopen-protocolopen-sourceopen-standardpi-coding-agentself-hosteduhpunified-apiunified-harness-protocolunified-interface
gateway: a turn's heartbeat stays fresh until its runner turn is on record; the sweep's cap is the runner's limit plus a placement margin (#538)
github-actions[bot]a69531d1ae85
diff --git a/gateway/app.py b/gateway/app.pyindex 5d5106e3..f7ee932c 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -866,6 +866,17 @@ def _tenant_sem(t: str) -> asyncio.Semaphore:return _tenant_sems.setdefault(t or "_", asyncio.Semaphore(_conc_limit("tenant")))+# Set once a turn's runner turn is on record (the vertex carries runner_turn_id): from then the poll+# loop renews the heartbeat itself, and _turn_slot's own beat stops. One per session, while its slot is held.+_RUNNER_TURN_ON: "dict[str, asyncio.Event]" = {}+++def _runner_turn_recorded(sid: str) -> None:+ ev = _RUNNER_TURN_ON.get(sid)+ if ev is not None:+ ev.set()++@contextlib.asynccontextmanagerasync def _turn_slot(org: str, sid: str):"""Both concurrency gates, held for the turn, with the session's heartbeat kept fresh while the@@ -877,14 +888,22 @@ async def _turn_slot(org: str, sid: str):read it as a dead turn and settled it, session and response, as failed; the turn then ran andits final write said completed. Measured 2026-10-12 on a 4-core instance with nine turns inflight: a background poller read `failed` (error null) four seconds in, for the 28 seconds the- turn waited, and `completed` at 55 s. The newborn trap of 0.23.2, one stage later."""+ turn waited, and `completed` at 55 s. The newborn trap of 0.23.2, one stage later.++ The beat goes on past the gates, through every phase before the runner turn is on record (the+ lease, the workspace restore, plugins, the runner's /turn start and its retries): until then the+ sweep has neither a runner turn to ask nor a heartbeat from the poll loop, and "no runner turn on+ record" read a live turn restoring a large workspace as gone (CAT, 2026-10-21; restores past the+ 120 s stale window were measured on the hosted service). It stops when the poll loop takes over+ (_runner_turn_recorded) or the slot is released."""beat_s = max(1, _RECONCILE_STALE_S // 4)- got = asyncio.Event()+ on_record = asyncio.Event()+ _RUNNER_TURN_ON[sid] = on_recordasync def beat():while True:try:- await asyncio.wait_for(got.wait(), timeout=beat_s)+ await asyncio.wait_for(on_record.wait(), timeout=beat_s)returnexcept asyncio.TimeoutError:pass@@ -896,11 +915,12 @@ async def _turn_slot(org: str, sid: str):t = asyncio.create_task(beat())try:async with _global_sem(), _tenant_sem(org):- got.set()yieldfinally:- got.set()+ on_record.set()t.cancel()+ if _RUNNER_TURN_ON.get(sid) is on_record:+ _RUNNER_TURN_ON.pop(sid, None)def _pool_is_local() -> bool:@@ -2774,6 +2794,19 @@ _SESSION_TERMINAL = {"done", "completed", "failed", "incomplete", "max_turns", "_RECONCILE_STALE_S = int(os.environ.get("HARNESS_RECONCILE_STALE_S", "120"))_RECONCILE_EVERY_S = int(os.environ.get("HARNESS_RECONCILE_EVERY_S", "60"))_GW_MAX_TURN_S = int(os.environ.get("HARNESS_MAX_TURN_S", "21600"))+# The runner's own wall-clock ceiling for a turn (runner/server.py MAX_TURN_SECONDS, read from the same+# environment on one container), and the time a turn may spend before the runner's clock starts: the+# lease, placement and the workspace restore. The sweep and the response reconciler settle a turn as+# timed out only past BOTH limits plus that margin, counted from the turn's start (turn_at, stamped at+# accept). The gateway's clock starts first, so a cap equal to the runner's would settle a turn that is+# still working, minutes inside the runner's own limit, as timed out for good (CAT, 2026-10-21).+_RUNNER_MAX_TURN_S = int(os.environ.get("MAX_TURN_SECONDS", "21600"))+_CAP_MARGIN_S = int(os.environ.get("HARNESS_CAP_MARGIN_S", "1800"))+++def _sweep_cap_s() -> int:+ """Seconds from a turn's start after which nothing can still be working on it."""+ return max(_GW_MAX_TURN_S, _RUNNER_MAX_TURN_S) + _CAP_MARGIN_Sdef _turn_since_ms(rec: dict | None, for_result: bool = True) -> int:@@ -3141,7 +3174,18 @@ async def _reconcile_session(v: dict) -> bool:if not seen:return False # no time on record at all: an unknown age is past no capage = time.time() - seen- if age < _RECONCILE_STALE_S:+ # The hard cap runs from the TURN's start (turn_at, stamped at accept), never from the heartbeat:+ # _turn_slot beats until the runner turn is on record, and a beat that goes on while a restore+ # hangs must not keep the turn alive forever (CAT, 2026-10-21). Past the cap with no runner turn+ # on record, a fresh beat is the slot's and not proof of progress, so it does not protect the+ # turn. Once a runner turn exists the poll loop holds its own wall-clock cap.+ try:+ turn_at = float(v.get("turn_at") or 0)+ except (TypeError, ValueError):+ turn_at = 0.0+ turn_age = time.time() - turn_at if turn_at > 0 else age+ stuck = turn_at > 0 and turn_age > _sweep_cap_s() and not str(v.get("runner_turn_id") or "")+ if age < _RECONCILE_STALE_S and not stuck:return False # fresh heartbeat (or a newborn turn) -> still being polledbase = v.get("trace_blob")rid_run = str(v.get("running_response_id") or "")@@ -3162,15 +3206,23 @@ async def _reconcile_session(v: dict) -> bool:status = await _trace_terminal_status(base, since)end_reason = ""if status is None:- if age > _GW_MAX_TURN_S:- status = "failed" # past the hard cap with no result+ if turn_age > _sweep_cap_s():+ status = "failed" # past the hard cap, from the turn's start, with no resultend_reason = "timeout"+ rt_cap = str(v.get("runner_turn_id") or "")+ if rt_cap:+ # nothing may keep working on a turn settled as timed out: stop the runner's turn too+ try:+ await _sandbox(f"/turn/{rt_cap}/cancel", str(sid), "POST")+ except Exception: # noqa: BLE001 — gone already, or unreachable; the settle stands+ passelse:# First ask the RUNNER whether the recorded turn still exists. Turn records are# in-memory there, so a restart answers 404 — and a 404 means the process that owned# this turn is gone and it can never finish. Settle it NOW: failed, its error saying a- # restart cut it (#505, _interrupted_error), so a follow-up continues it. Only the 404- # proves that; no runner turn recorded at all is failed with no reason claimed.+ # restart cut it (#505, _interrupted_error), so a follow-up continues it. A runner turn+ # never on record says the same: the turn never reached the runner, and the process that+ # owned it stopped beating (_turn_slot beats until the runner turn is on record).# Without this the single-container deployment showed "Working" for the full six-hour cap after any# restart: adoption below is gated on the control store, which self-hosted does not# have, so nothing else could ever settle the record. Seen live: a SIGKILLed container@@ -3321,8 +3373,8 @@ async def _reconcile_response(rid: str, rec: dict) -> dict:ts = await _trace_terminal_status(v.get("trace_blob"), _turn_since_ms(rec))if ts:settled = _RESP_STATUS_MAP.get(ts, "failed")- elif time.time() - hb > _GW_MAX_TURN_S:- settled = "failed" # past the hard cap with no result+ elif time.time() - (_born_seconds(rec) or hb) > _sweep_cap_s():+ settled = "failed" # past the hard cap, from the turn's start, with no resultcapped = Trueif not settled or settled == str(rec.get("status") or ""):return rec@@ -4924,7 +4976,7 @@ async def _card_settle(sid: str, m: dict) -> dict | None:hb = float(v.get("heartbeat") or 0)except Exception: # noqa: BLE001hb = 0- if hb and time.time() - hb > _GW_MAX_TURN_S:+ if hb and time.time() - hb > _sweep_cap_s(): # the sweep's cap, so card and record agreestatus = "failed"if not status or status == str(m.get("status") or ""):return None@@ -8818,6 +8870,7 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, selse:await _vertex_upsert(sid, {"status": "running", "turn_status": "running","last_connection": name, "runner_turn_id": rt or ""})+ _runner_turn_recorded(sid) # the runner turn is on record; the poll loop beats from here# cursor = how far the durable trace has been written; fed_upto = how far events have been# fed to the translator and emitted. Events are asked for from fed_upto, so nothing comes# twice, and what is fed and not yet written waits in `pending`.diff --git a/gateway/tests/test_card_settle.py b/gateway/tests/test_card_settle.pyindex cb8f015e..a79974b4 100644--- a/gateway/tests/test_card_settle.py+++ b/gateway/tests/test_card_settle.py@@ -33,7 +33,7 @@ def test_a_live_turn_is_left_alone(monkeypatch):def test_a_dead_heartbeat_past_the_cap_reads_failed(monkeypatch):indexed = []- _wire(monkeypatch, {"status": "running", "turn_status": "running", "heartbeat": str(time.time() - gw._GW_MAX_TURN_S - 5)}, indexed)+ _wire(monkeypatch, {"status": "running", "turn_status": "running", "heartbeat": str(time.time() - gw._sweep_cap_s() - 5)}, indexed)m = asyncio.run(gw._card_settle("sid", {"session_id": "sid", "status": "running"}))assert m["status"] == "failed" and indexeddiff --git a/gateway/tests/test_incomplete_reason.py b/gateway/tests/test_incomplete_reason.pyindex dab5692e..f8fadeca 100644--- a/gateway/tests/test_incomplete_reason.py+++ b/gateway/tests/test_incomplete_reason.py@@ -162,10 +162,10 @@ def test_a_turn_past_the_hard_cap_fails_saying_it_ran_out_of_time(monkeypatch):"""Past the hard cap with no result: failed, never bare, with detail.reason timeout."""import timev = {"id": "hsess1", "status": "running", "turn_status": "running", "runner_turn_id": "rt_1",- "running_response_id": "resp_1", "heartbeat": str(time.time() - A._GW_MAX_TURN_S - 60),- "turn_at": str(time.time() - A._GW_MAX_TURN_S - 60)}+ "running_response_id": "resp_1", "heartbeat": str(time.time() - A._sweep_cap_s() - 60),+ "turn_at": str(time.time() - A._sweep_cap_s() - 60)}rec = {"id": "resp_1", "status": "running", "_session_id": "hsess1", "output": [],- "created_at": int(time.time() - A._GW_MAX_TURN_S - 60)}+ "created_at": int(time.time() - A._sweep_cap_s() - 60)}settled, writes, stored = _sweep(monkeypatch, v, 200, rec)assert settled is True and writes[0] == {"status": "failed", "turn_status": "failed", "end_reason": "timeout"}assert stored["error"] == {"type": "harness_error", "code": "harness_error",@@ -339,18 +339,19 @@ def test_a_running_turn_with_no_readable_record_is_scoped_by_its_turn_at(monkeypasync def _tts(blob, since_ms=0):seen.append(since_ms)return None+ turn_at = round(time.time() - 600, 3) # inside the hard cap, which runs from turn_atv = {"id": "hsess1", "status": "running", "turn_status": "running", "runner_turn_id": "rt_1",- "running_response_id": "", "trace_blob": "org/inv_hsess1", "turn_at": "4.25",+ "running_response_id": "", "trace_blob": "org/inv_hsess1", "turn_at": str(turn_at),"heartbeat": str(time.time() - 600)}settled, writes, _ = _sweep(monkeypatch, v, 404, None, tts=_tts)- assert seen[0] == 4250 and writes[0]["end_reason"] == "interrupted"+ assert seen[0] == int(turn_at * 1000) and writes[0]["end_reason"] == "interrupted"def test_the_reconcilers_own_hard_cap_is_never_a_bare_failed(monkeypatch):"""A background poll's reconcile that settles a record past the hard cap gives it the timeouterror, so a failed task always says why (lifecycle §3)."""import asyncio, time- long_ago = time.time() - A._GW_MAX_TURN_S - 60+ long_ago = time.time() - A._sweep_cap_s() - 60v = {"id": "hsess1", "status": "running", "turn_status": "running", "heartbeat": str(long_ago),"created_at": str(long_ago), "running_response_id": "resp_1"}async def _vget(sid):diff --git a/gateway/tests/test_reconcile_newborn.py b/gateway/tests/test_reconcile_newborn.pyindex fe32af9a..8f5ef5da 100644--- a/gateway/tests/test_reconcile_newborn.py+++ b/gateway/tests/test_reconcile_newborn.py@@ -59,7 +59,7 @@ def test_a_vertex_the_turn_has_not_stamped_yet_is_a_newborn_not_an_orphan(monkeydef test_a_turn_that_stopped_heartbeating_past_the_cap_is_still_settled(monkeypatch):- old = time.time() - gw._GW_MAX_TURN_S - 600+ old = time.time() - gw._sweep_cap_s() - 600rec = {"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)diff --git a/gateway/tests/test_turn_slot.py b/gateway/tests/test_turn_slot.pyindex 9f0216ca..f6f74e2b 100644--- a/gateway/tests/test_turn_slot.py+++ b/gateway/tests/test_turn_slot.py@@ -40,7 +40,8 @@ def test_a_turn_waiting_for_a_slot_keeps_its_heartbeat_fresh_and_stops_once_admiasync def turn():async with gw._turn_slot("org", "hsess1"):admitted.set()- await asyncio.sleep(2.5) # running: no queue beats now+ gw._runner_turn_recorded("hsess1") # its runner turn is on record: the poll loop beats+ await asyncio.sleep(2.5) # running: no slot beats nowtask = asyncio.create_task(turn())await asyncio.sleep(2.5)@@ -69,12 +70,50 @@ def test_a_turn_that_gets_its_slot_at_once_writes_no_extra_beat(monkeypatch):async def main():_gates(monkeypatch)async with gw._turn_slot("org", "hsess1"):+ gw._runner_turn_recorded("hsess1")await asyncio.sleep(1.5)asyncio.run(main())assert beats == []+def test_a_turn_still_restoring_its_workspace_keeps_beating_and_is_never_settled(monkeypatch):+ """Past the gates but before its runner turn is on record (the workspace restore, plugins, the+ runner's /turn start), a turn has no runner turn for the sweep to ask and no poll loop to beat.+ The slot keeps its heartbeat fresh through all of it, so a restore longer than the stale window+ is never read as gone (CAT, 2026-10-21: restores past 120 s measured on the hosted service).+ Time is compressed: a stale window of 4 s, a restore of 6 s."""+ beats: list = []+ vertex = {"id": "hsess1", "tenant": "org", "status": "running", "turn_status": "starting",+ "runner_turn_id": "", "heartbeat": str(time.time())}++ async def _vup(sid, props):+ beats.append(props)+ vertex.update(props)++ monkeypatch.setattr(gw, "_vertex_upsert", _vup)+ monkeypatch.setattr(gw, "_RECONCILE_STALE_S", 4)++ async def sandbox(*a, **k):+ raise AssertionError("a session with a fresh heartbeat is not probed")+ monkeypatch.setattr(gw, "_sandbox", sandbox)++ async def main():+ _gates(monkeypatch)+ async with gw._turn_slot("org", "hsess1"):+ await asyncio.sleep(6) # the restore, longer than the stale window+ settled = await gw._reconcile_session(dict(vertex))+ before = len(beats)+ gw._runner_turn_recorded("hsess1")+ await asyncio.sleep(1.5)+ return settled, before++ settled, before = asyncio.run(main())+ assert settled is False+ assert before >= 4 and len(beats) == before # it beat until the runner turn was on record+ assert gw._RUNNER_TURN_ON.get("hsess1") is None # and the slot cleaned up after itself++def test_the_sweep_leaves_a_queued_turn_alone(monkeypatch):# what the accept-time write leaves on the vertex: starting, no runner turn, a fresh heartbeatwrites: list = []@@ -98,3 +137,97 @@ def test_the_accept_time_write_stamps_the_heartbeat():assert '"heartbeat": str(time.time())' in src[i:i + 200]assert src.count("async with _turn_slot(org, sid):") == 3assert src.count("async with _global_sem(), _tenant_sem(org):") == 1 # inside _turn_slot only+++def test_a_restore_that_hangs_past_the_cap_settles_at_the_cap_though_the_slot_still_beats(monkeypatch):+ """The slot's beat keeps a restoring turn alive, but not forever: the hard cap runs from the+ turn's start (turn_at), so a turn still without a runner turn past the cap is settled failed with+ reason timeout even while its heartbeat is fresh (CAT, 2026-10-21). Scaled: a 3 s cap, a 4 s stale+ window, a restore that hangs for 4.5 s."""+ started = time.time()+ vertex = {"id": "hsess1", "tenant": "org", "status": "running", "turn_status": "starting",+ "runner_turn_id": "", "running_response_id": "", "turn_at": str(started), "heartbeat": str(started)}+ writes: list = []++ async def _vup(sid, props):+ writes.append(dict(props))+ vertex.update(props)++ async def _tts(base, since_ms=0):+ return None++ async def sandbox(*a, **k):+ raise AssertionError("past the cap, nothing needs asking")+ monkeypatch.setattr(gw, "_vertex_upsert", _vup)+ monkeypatch.setattr(gw, "_trace_terminal_status", _tts)+ monkeypatch.setattr(gw, "_sandbox", sandbox)+ monkeypatch.setattr(gw, "_RECONCILE_STALE_S", 4)+ monkeypatch.setattr(gw, "_GW_MAX_TURN_S", 2)+ monkeypatch.setattr(gw, "_RUNNER_MAX_TURN_S", 2)+ monkeypatch.setattr(gw, "_CAP_MARGIN_S", 1) # the cap: max(2, 2) + 1 = 3 s++ async def main():+ _gates(monkeypatch)+ async with gw._turn_slot("org", "hsess1"):+ await asyncio.sleep(4.5) # the restore hangs past the cap+ fresh = time.time() - float(vertex["heartbeat"]) < 4+ return fresh, await gw._reconcile_session(dict(vertex))++ fresh, settled = asyncio.run(main())+ assert fresh, "the slot was still beating"+ assert settled is True+ assert {"status": "failed", "turn_status": "failed", "end_reason": "timeout"} in writes+++def _cap_sweep(monkeypatch, turn_age: float, probe: int = 200):+ """The sweep on a turn whose runner turn is on record and whose heartbeat went stale (its poll loop+ is gone), `turn_age` seconds after its start; the runner answers `probe` for the turn. Scaled: the+ gateway's and the runner's limit 100 s, the placement and restore margin 30 s."""+ monkeypatch.setattr(gw, "_GW_MAX_TURN_S", 100)+ monkeypatch.setattr(gw, "_RUNNER_MAX_TURN_S", 100)+ monkeypatch.setattr(gw, "_CAP_MARGIN_S", 30)+ monkeypatch.setattr(gw, "_adopting", {"hsess1"}) # an adoption is already running: spawn none+ now = time.time()+ v = {"id": "hsess1", "tenant": "org", "status": "running", "turn_status": "running", "runner_turn_id": "rt_1",+ "running_response_id": "", "turn_at": str(now - turn_age), "heartbeat": str(now - 300)}+ writes, calls = [], []++ async def _vup(sid, props):+ writes.append(dict(props))++ async def _tts(base, since_ms=0):+ return None++ class _R:+ def __init__(self, code):+ self.status_code = code++ async def sandbox(path, sid, method="POST", **k):+ calls.append((method, path))+ return _R(probe)+ monkeypatch.setattr(gw, "_vertex_upsert", _vup)+ monkeypatch.setattr(gw, "_trace_terminal_status", _tts)+ monkeypatch.setattr(gw, "_sandbox", sandbox)+ return asyncio.run(gw._reconcile_session(v)), writes, calls+++def test_the_sweep_cap_is_the_runners_limit_plus_the_placement_margin(monkeypatch):+ monkeypatch.setattr(gw, "_GW_MAX_TURN_S", 100)+ monkeypatch.setattr(gw, "_RUNNER_MAX_TURN_S", 120)+ monkeypatch.setattr(gw, "_CAP_MARGIN_S", 30)+ assert gw._sweep_cap_s() == 150+++def test_a_turn_still_inside_the_runners_limit_plus_margin_is_not_settled_as_timed_out(monkeypatch):+ """The gateway's clock starts at accept, before placement and restore; past the runner's limit+ but inside the margin, the runner may still be working on it, so nothing is settled as timed out."""+ settled, writes, calls = _cap_sweep(monkeypatch, turn_age=120)+ assert settled is False and not any(w.get("end_reason") == "timeout" for w in writes)+ assert ("POST", "/turn/rt_1/cancel") not in calls+++def test_past_the_limit_plus_margin_it_settles_timed_out_and_the_runners_turn_is_cancelled(monkeypatch):+ settled, writes, calls = _cap_sweep(monkeypatch, turn_age=140)+ assert settled is True+ assert writes[0] == {"status": "failed", "turn_status": "failed", "end_reason": "timeout"}+ assert ("POST", "/turn/rt_1/cancel") in calls