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.

Turns end sooner and stream smoothly: a held events request, and a smaller checkpoint (#402)

github-actions[bot]ecd50336c3e1
diff --git a/docs/support-matrix-notes.md b/docs/support-matrix-notes.md
index f12aebf0..a1b3bcca 100644
--- a/docs/support-matrix-notes.md
+++ b/docs/support-matrix-notes.md
@@ -2758,3 +2758,52 @@ something of their own. A level set on the harness or the turn replaces all of t
Also from the hosted service: `backend` on POST /v1/responses took a base's id ("claude-code") as the
backend, matched no model, and refused every model as having no provider there. It names the base's
backend now.
+
+## Where a turn's fixed seconds went (2026-10-05, 0.30.1)
+
+Two changes ported from the hosted service, where both were found and first measured, and measured
+again here through a streamed task (`stream: true`, timed at the client): when the first text
+arrives, in how many steps the answer grows (text arriving after a pause of 0.1 s or more), and how
+long after the last text the task says it is complete. Warm turns of one session, medians.
+
+**The gateway asked for a turn's events every 1.2 s.** So the first text waited up to that long, a
+streamed answer grew in jumps of that size, and the end was heard at the next ask. The runner now
+holds the request (`GET /turn/{id}?wait=`) until it has an event, the turn is done, or the wait has
+passed, and says `held`; the gateway asks again at once, writes the durable trace once per interval
+instead of once per answer, and paces itself the old way when an answer does not say held (an older
+runner) or a request failed. The duties that counted polls (the lease, the heartbeat, the durable
+cancel check) count the clock. `HARNESS_RESP_HOLD_S` sets the hold (3 s; 0 asks the old way). The
+hold waits on the runner's event loop, not on a worker thread: one runner serves every session of an
+instance, and 120 turns held at once answer together in the test.
+
+**A checkpoint carried what a CLI rebuilds for itself.** omp's two native binaries, Codex's plugin
+catalogue and the DeepSeek Harness's unpacked packages travelled in the workspace's archive after
+every turn. They are left out now (`_REBUILT_CACHES`). opencode's npm cache is deliberately not:
+rebuilding it cost a turn 20 s on the hosted service.
+
+| base, model | | 0.30.0 | with the hold | with the hold and the smaller checkpoint |
+|---|---|---:|---:|---:|
+| pi, deepseek-v4-flash | first text | 2.71 s | 2.68 s | 2.88 s |
+| | steps | 2 | 5.5 | 7.5 |
+| | last text to complete | 0.20 s | 0.18 s | 0.15 s |
+| codex, gpt-5.4 | first text | 4.13 s | 3.79 s | 3.98 s |
+| | steps | 3 | 7 | 8 |
+| | last text to complete | 3.72 s | 3.19 s | 0.22 s |
+| | whole turn | 10.4 s | 8.9 s | 6.0 s |
+| omp, gpt-5.4 | steps | | 7 to 9 | 10.5 |
+| | last text to complete | | 7.5 s | 0.37 s |
+| | whole turn | | 15.4 s | 9.6 s |
+| claude-code, claude-haiku-4.5 | first text | 3.99 s | 4.22 s | |
+| | steps | 1 | 1 | |
+| hermes, gpt-5.4 | first text | 28.7 s | 23.7 s | |
+| | steps | 1 | 1 | |
+
+Read with their sizes: four to eight turns per cell, and the model's own time is most of "first
+text". What moved beyond noise is the number of steps a streamed answer grows in (pi 2 to 7.5, Codex
+3 to 8) and the end of a turn on the two bases whose checkpoint shrank (Codex 3.7 s to 0.2 s, omp
+7.5 s to 0.4 s). Claude Code and hermes hand over whole messages, so their answers arrive in one step
+either way; hermes's first text is its whole answer and its difference here is the model's.
+
+Not ported, with the reason: the hosted change that lets a turn's record writes run beside the loop
+(each write costs about 0.4 s there; here the store is a local file), and the per-turn timing log
+line that found these.
diff --git a/gateway/app.py b/gateway/app.py
index 75f4e67d..09077674 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -313,6 +313,30 @@ _TRACE_NONCE = uuid.uuid4().hex[:8]
# Streaming poll cadence for the /v1/responses path — much faster than the background driver's 30s
# because an open SSE connection wants timely deltas (and the fast poll also keeps the sandbox warm).
RESP_POLL_S = float(os.environ.get("HARNESS_RESP_POLL_S", "1.2"))
+# How long one request for a turn's events may be held by the runner until it has something new
+# (GET /turn/{id}?wait=). The gateway used to ask every RESP_POLL_S, which put up to that long
+# before a turn's first text and again before its end (measured on the hosted service, 2026-10-05:
+# first output heard a median 1,249 ms after the runner had it, 225 ms with the hold). 0 asks the
+# old way.
+RESP_HOLD_S = float(os.environ.get("HARNESS_RESP_HOLD_S", "3"))
+
+
+class _Every:
+ """A turn's loop no longer turns once per RESP_POLL_S: it turns when the runner has something.
+ Duties that ran every N polls (the lease, the heartbeat, the durable cancel check) run every N
+ poll intervals of the clock instead. `at_once` names the duties whose first run is immediate;
+ the others first run one interval after `t0`."""
+
+ def __init__(self, t0: float, at_once: tuple[str, ...] = ()) -> None:
+ self._t0 = t0
+ self._last = {k: 0.0 for k in at_once}
+
+ def __call__(self, what: str, polls: int) -> bool:
+ now = time.time()
+ if now - self._last.get(what, self._t0) >= polls * RESP_POLL_S:
+ self._last[what] = now
+ return True
+ return False
def _load_reasoning():
@@ -7684,17 +7708,23 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s
else:
await _vertex_upsert(sid, {"status": "running", "turn_status": "running",
"last_connection": name, "runner_turn_id": rt or ""})
- # cursor = durable fetch offset (only advances on an ack'd flush); fed_upto = how far
- # events have been fed to the translator/emit (advances always) so a held-cursor re-fetch
- # after a failed flush re-persists WITHOUT re-emitting duplicate output.
- cursor, fed_upto, terminal, poll_fails, kill_sent, polls = 0, 0, None, 0, False, 0
+ # 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`.
+ cursor, fed_upto, terminal, poll_fails, kill_sent = 0, 0, None, 0, False
+ pending: list = []
+ last_flush = time.time()
+ # A runner that holds the request says so in its answer; one that does not is paced by our
+ # own sleep, as before. The first request goes out at once either way.
+ held = RESP_HOLD_S > 0
+ every = _Every(time.time())
while True:
- await asyncio.sleep(RESP_POLL_S)
- polls += 1
+ if not held:
+ await asyncio.sleep(RESP_POLL_S)
+ renew = every("renew", LEASE_RENEW_EVERY)
# Heartbeat-renew the session lease so a long turn's lease never expires and gets
# stolen by a follow-up (which would wipe this live workspace). Best-effort.
- if (rec.get("lease_fence") and control_store.enabled()
- and polls % LEASE_RENEW_EVERY == 0):
+ if rec.get("lease_fence") and control_store.enabled() and renew:
try:
await control_store.lease_renew(org, sid, translator.resp_id,
rec["lease_fence"], LEASE_TTL_S)
@@ -7702,16 +7732,16 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s
pass
# Renew the vertex heartbeat too, so the reconcile sweep sees a long turn as live (its
# fresh-heartbeat fast path applies) instead of re-scanning trace chunks every cycle.
- if polls % LEASE_RENEW_EVERY == 0:
+ if renew:
try:
await _vertex_upsert(sid, {"heartbeat": str(time.time())})
except Exception: # noqa: BLE001
pass
# Stop observed mid-turn (bypasses cancel_session's own sandbox call when that raced
- # startup). The durable per-response latch is consulted every 10th poll so a cancel on
+ # startup). The durable per-response latch is consulted every tenth interval so a cancel on
# any replica lands; the in-process flag is instant for a same-replica Stop.
if not kill_sent and await _turn_cancelled(sid, org, translator.resp_id,
- check_store=(polls % 10 == 0)):
+ check_store=every("cancel", 10)):
kill_sent = True
try:
await _sandbox_json(f"/turn/{rt}/cancel", sid, "POST", attempts=2)
@@ -7719,41 +7749,42 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s
terminal = "cancelled" # sandbox unreachable — settle the turn terminally anyway
break
try:
- s = await _sandbox_json(f"/turn/{rt}", sid, "GET", params={"since": cursor}, attempts=3, base=2.0)
+ s = await _sandbox_json(f"/turn/{rt}", sid, "GET", attempts=3, base=2.0,
+ params={"since": fed_upto, **({"wait": RESP_HOLD_S} if RESP_HOLD_S > 0 else {})})
poll_fails = 0
except Exception as e: # noqa: BLE001
# a transient poll hiccup must not abort a live turn — only give up after a run
poll_fails += 1
+ held = False # nothing held the request this time: pace the next one ourselves
if poll_fails >= 5:
rec["tried"].append({"connection": name, "error": f"poll: {str(e)[:150]}"})
break
continue
+ held = bool(s.get("held"))
new = s.get("events") or []
- n_total = s.get("n_total", cursor)
- flush_ok = True
- if new:
- flush_ok = await _trace_flush(tr, {"events": new, "n_total": n_total})
- # Feed/emit ONLY the slice not already fed — so a held-cursor re-fetch (after a failed
- # flush) re-persists the events without re-emitting them into the response/stream.
+ n_total = s.get("n_total", fed_upto)
+ # Fed and emitted the moment they arrive. Asked for from fed_upto, so nothing comes twice.
if new and n_total > fed_upto:
- skip = fed_upto - cursor if fed_upto > cursor else 0
- for cev in new[skip:]:
+ for cev in new:
for oev in translator.feed(cev):
await emit(oev)
fed_upto = n_total
- # HR-INF-014: advance the DURABLE fetch cursor only once the events are acknowledged.
- # On a failed flush we hold it so the next poll re-fetches and re-persists them (the
- # durable trace is the authority and must not lose events). No events → advance.
- if flush_ok or not new:
- if new and flush_ok and cursor != n_total and control_store.enabled():
- # Persist the per-turn harvest cursor so a replica that ADOPTS this turn after we
- # die resumes at exactly the right sandbox index — no re-flush, no re-emit. Only
- # on a real advance (new events actually flushed), so it's ≤ once per poll batch.
- try:
- await control_store.resp_set_cursor(org, translator.resp_id, int(n_total))
- except Exception: # noqa: BLE001 — advisory; adoption falls back to session-count
- pass
- cursor = n_total
+ pending.extend(new)
+ # HR-INF-014: the durable trace is the authority and must not lose events. It is written
+ # once per interval rather than once per answer (a stream of token deltas would otherwise
+ # be a chunk each), and at the turn's end; a failed write keeps `pending` for the next.
+ # `cursor` is how far the trace has been written, and only that is persisted: a replica
+ # that ADOPTS this turn after we die asks the runner again from exactly there.
+ if pending and (s.get("done") or time.time() - last_flush >= RESP_POLL_S):
+ last_flush = time.time()
+ if await _trace_flush(tr, {"events": pending, "n_total": fed_upto}):
+ pending = []
+ if cursor != fed_upto and control_store.enabled():
+ try:
+ await control_store.resp_set_cursor(org, translator.resp_id, int(fed_upto))
+ except Exception: # noqa: BLE001 — advisory; adoption falls back to session-count
+ pass
+ cursor = fed_upto
# Persist the CLI resume id ONLY when it CHANGES (HR-INF-010). The runner echoes
# session_id on every poll (~1.2s), but it's set once per turn — an unconditional
# upsert was ~1500 identical writes/turn to the shared partition. This loop is the
@@ -7794,6 +7825,8 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s
# characters and 200 cut goose's tmp-dir panic at its path (2026-09-13).
"error": (s.get("error") or s.get("result") or "")[:2000]})
break
+ if pending: # the loop was left between two writes (a cancel, a poll that kept failing)
+ await _trace_flush(tr, {"events": pending, "n_total": fed_upto})
_last_err = str(rec["tried"][-1].get("error") or "") if rec["tried"] else ""
if (not terminal and rec["tried"] and rec["tried"][-1].get("connection") == name
and rec["tried"][-1].get("status") and _provider_refused(_last_err)):
diff --git a/gateway/tests/test_turn_loop_clock.py b/gateway/tests/test_turn_loop_clock.py
new file mode 100644
index 00000000..f3a56930
--- /dev/null
+++ b/gateway/tests/test_turn_loop_clock.py
@@ -0,0 +1,63 @@
+"""A turn's loop turns when the runner has something, so its periodic duties count the clock.
+
+The loop used to sleep RESP_POLL_S and run a duty "every N polls" (the lease and the heartbeat every
+20, the durable cancel check every 10). With a held request it turns several times a second while
+text streams and once per hold while a tool runs, so N polls is no longer N intervals of time.
+"""
+import os
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import app as gw # noqa: E402
+
+
+def test_a_duty_runs_once_per_n_intervals_however_often_the_loop_turns(monkeypatch):
+ now = [1000.0]
+ monkeypatch.setattr(gw.time, "time", lambda: now[0])
+ monkeypatch.setattr(gw, "RESP_POLL_S", 1.2)
+ every = gw._Every(now[0])
+ runs = 0
+ for _ in range(600): # ten turns of the loop a second, for a minute
+ now[0] += 0.1
+ runs += every("renew", 20) # 20 intervals of 1.2 s = 24 s
+ assert runs == 2
+ assert not every("cancel", 50) # 60 s after the start, by the clock
+ now[0] += 0.2
+ assert every("cancel", 50) and not every("cancel", 50)
+
+
+def test_a_slow_loop_runs_a_duty_late_by_at_most_one_turn(monkeypatch):
+ now = [0.0]
+ monkeypatch.setattr(gw.time, "time", lambda: now[0])
+ monkeypatch.setattr(gw, "RESP_POLL_S", 1.2)
+ every = gw._Every(0.0)
+ at = []
+ for _ in range(24): # one turn of the loop every 5 s (a held request with nothing new)
+ now[0] += 5.0
+ if every("renew", 20): # due every 24 s
+ at.append(now[0])
+ assert at == [25.0, 50.0, 75.0, 100.0]
+
+
+def test_only_the_named_duties_run_at_once(monkeypatch):
+ now = [500.0]
+ monkeypatch.setattr(gw.time, "time", lambda: now[0])
+ every = gw._Every(now[0], at_once=("touch",))
+ assert every("touch", 20) and not every("touch", 20)
+ assert not every("renew", 20)
+
+
+def test_the_loop_asks_from_what_it_has_fed_holds_by_default_and_paces_itself_without_a_hold():
+ src = open(os.path.join(os.path.dirname(__file__), "..", "app.py")).read()
+ i = src.index("held = RESP_HOLD_S > 0")
+ loop = src[i:src.index("_last_err = str(rec", i)]
+ assert gw.RESP_HOLD_S > 0 # the default holds
+ assert '"since": fed_upto' in loop and '{"wait": RESP_HOLD_S} if RESP_HOLD_S > 0 else {}' in loop
+ assert "if not held:\n await asyncio.sleep(RESP_POLL_S)" in loop # an older runner
+ assert "held = bool(s.get(\"held\"))" in loop
+ # a failed request is not a held one: the next is paced, so a dead runner is not asked in a spin
+ assert loop.index("poll_fails += 1") < loop.index("held = False") < loop.index("if poll_fails >= 5")
+ # the trace is written once per interval and at the end, and what a cut loop left is written after it
+ assert "if pending and (s.get(\"done\") or time.time() - last_flush >= RESP_POLL_S):" in loop
+ assert "if pending: # the loop was left between two writes" in loop
diff --git a/runner/server.py b/runner/server.py
index 45e2705e..b0c586b0 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -42,6 +42,7 @@ Yjs sidecar layer on next.
"""
from __future__ import annotations
+import asyncio
import base64
import contextvars
import hashlib
@@ -72,6 +73,7 @@ import uuid
import yaml
from fastapi import BackgroundTasks, FastAPI, HTTPException, Request, Response
+from fastapi.concurrency import run_in_threadpool
from fastapi.exceptions import RequestValidationError
from fastapi.responses import FileResponse, JSONResponse
from pydantic import BaseModel
@@ -526,10 +528,21 @@ def _reap_spool() -> None:
# the working tree AND the conversation — that's what makes `--resume` work on any sandbox.
HARNESS_STATE = ".harness"
# Paths never persisted in a checkpoint (secrets + regenerated/scratch). Relative to /workspace.
+# What a CLI unpacks or fetches for itself and makes again when it is missing. Saved with the
+# workspace, these were most of what a turn's end waited for (measured on the hosted service,
+# 2026-10-05): omp's two native binaries (352 MB on disk, a 183 MB archive and 10 s after EVERY turn
+# of a three-line chat), Codex's plugin catalogue and the unpacked packages of the DeepSeek Harness.
+# Each was deleted inside a live session there and the next turn completed with it rebuilt: omp about
+# 3 s, the other two with no visible cost. NOT here: opencode's npm cache, whose rebuild cost a turn
+# 20 s. The CLI home is already out of the workspace's own git history (see _git_ensure), so the tar
+# is the one place these travelled.
+_REBUILT_CACHES = (".harness/home/.omp/natives", ".harness/home/.codex/.tmp", ".harness/home/.cache/pkg")
+
# .git history travels in the tarball, so these must be git-ignored too (see _git_ensure).
# Persist conversation transcripts ($HOME -> .harness/home: ~/.claude/projects, ~/.codex/sessions)
# so --resume survives sandbox recycling — but NEVER persist credentials inside them.
-CHECKPOINT_EXCLUDE = ["./tmp", "./.gcp-sa.json", "./.codex", "./.credentials.json",
+CHECKPOINT_EXCLUDE = [*(f"./{c}" for c in _REBUILT_CACHES),
+ "./tmp", "./.gcp-sa.json", "./.codex", "./.credentials.json",
"./.harness/claude/.credentials.json",
"./.harness/home/.claude/.credentials.json",
"./.harness/home/.codex/auth.json",
@@ -9307,6 +9320,20 @@ _HERMES_POLL_S = 0.8
_HERMES_STARTUP_TIMEOUT_S = float(os.environ.get("HERMES_STARTUP_TIMEOUT_S", "90"))
+_HERMES_SID_LINE = re.compile(r"^session_id:\s*\S+$")
+
+
+def _hermes_error_text(err_lines: list[str], rc: int | None, silent_s: float) -> str:
+ """Why a hermes run failed, from its last stderr lines. The CLI closes every run with a
+ `session_id: <id>` line, a failed one too; taken as the reason, it told a person "The last one
+ said: session_id: 20261005_135032_0fb4fd" (the hosted service, 2026-10-05). When the CLI said
+ nothing else, the reason is what is known: it stopped with no final answer, its exit code, and
+ how long it had been silent by then."""
+ said = "\n".join(x for x in err_lines[-30:] if not _HERMES_SID_LINE.match(x.strip())).strip()
+ return (said or f"Hermes ended the turn without a final answer and gave no reason "
+ f"(exit code {rc}, {silent_s:.0f} s after its last message).")[:2000]
+
+
def _hermes_startup_hung(produced: bool, started: float, last_data: float, now: float) -> bool:
"""Whether a hermes turn that has written no message yet is hung, not merely slow to finish its
first one: nothing produced within the limit, and no provider event within it either."""
@@ -9467,6 +9494,7 @@ def _run_hermes_bg(turn_id: str, cwd: str, env: dict, model: str, provider: str,
sid = resume
cursor = 0
produced = False # has the model emitted ANY message yet (see _HERMES_STARTUP_TIMEOUT_S)
+ last_msg = t0 # when the last message of this turn was read from the CLI's database
if resume:
db = _hermes_db_ro(db_path)
if db is not None:
@@ -9480,7 +9508,7 @@ def _run_hermes_bg(turn_id: str, cwd: str, env: dict, model: str, provider: str,
append({"type": "system", "subtype": "init", "session_id": resume, "model": model})
def _sweep() -> None:
- nonlocal sid, cursor, produced
+ nonlocal sid, cursor, produced, last_msg
db = _hermes_db_ro(db_path)
if db is None:
return
@@ -9498,6 +9526,7 @@ def _run_hermes_bg(turn_id: str, cwd: str, env: dict, model: str, provider: str,
for row in db.execute(
"SELECT * FROM messages WHERE session_id=? AND id>? ORDER BY id", (sid, cursor)):
cursor = row["id"]
+ last_msg = time.time()
# The prompt hermes echoes back is not the model producing anything.
if str(row["role"] or "").lower() != "user":
produced = True
@@ -9565,7 +9594,7 @@ def _run_hermes_bg(turn_id: str, cwd: str, env: dict, model: str, provider: str,
if not use_chat:
final = "\n".join(out_buf).strip() or final
ok = rc == 0 and not run_failed and not rec.get("cancelled") and not rec.get("capped") and bool(final.strip())
- err_txt = ("\n".join(err_buf[-30:]).strip() or f"exit_code={rc}")[:2000]
+ err_txt = _hermes_error_text(err_buf, rc, time.time() - last_msg)
if rec.get("startup_timeout"):
# The generic exit_code/stderr text is useless here (the process was killed by US, not a
# normal failure) — say what actually happened instead of leaving a cryptic "exit_code=-9".
@@ -10358,13 +10387,16 @@ def cancel_turn(turn_id: str) -> dict:
return {"turn_id": turn_id, "status": "cancelling", "cancelled": True}
[email protected]("/turn/{turn_id}")
-def get_turn(turn_id: str, since: int = 0) -> dict:
- """Incremental turn status + normalized events (events[since:]). Polling also keeps the
- Timed sandbox alive (every request resets the idle cooldown)."""
- rec = _turns.get(turn_id)
- if not rec:
- raise HTTPException(404, "turn not found")
+# GET /turn/{id}?wait=S holds its answer until the turn has something new, so the gateway hears of
+# an event when it happens instead of at its next poll (it asked every 1.2 s: up to that long before
+# the first text of a turn and again before its end, measured on the hosted service 2026-10-05). The
+# hold is capped, and once something has arrived the answer lingers a moment so a burst of token
+# deltas travels as one answer rather than one request per delta.
+_TURN_HOLD_MAX_S = 10.0
+_TURN_HOLD_LINGER_S = 0.15
+
+
+def _turn_answer(turn_id: str, rec: dict, since: int, held: bool) -> dict:
with _turns_lock:
evs = rec["events"][since:]
n = len(rec["events"])
@@ -10374,5 +10406,30 @@ def get_turn(turn_id: str, since: int = 0) -> dict:
"session_id": rec.get("session_id"), "reason": rec.get("reason") or "",
"handoff": rec.get("handoff"),
"events": evs, "n_total": n, "elapsed": round(time.time() - rec["started"], 1)}
+ if held:
+ out["held"] = True
sec = rec.get("secrets")
return json.loads(_scrub_secrets(json.dumps(out, default=str), sec)) if sec else out
+
+
[email protected]("/turn/{turn_id}")
+async def get_turn(turn_id: str, since: int = 0, wait: float = 0.0) -> dict:
+ """Incremental turn status + normalized events (events[since:]). Polling also keeps the
+ Timed sandbox alive (every request resets the idle cooldown).
+
+ `wait` > 0 holds the answer until there is an event past `since`, the turn is done, or `wait`
+ seconds have passed. Such an answer says `held`, which is how a caller tells this runner from
+ one that ignores the parameter and has to be paced by the caller's own sleep.
+
+ The hold waits on the event loop, not on a worker thread: this one runner serves every session
+ of an instance, and a thread held per running turn would leave none to start the next."""
+ rec = _turns.get(turn_id)
+ if not rec:
+ raise HTTPException(404, "turn not found")
+ if wait > 0:
+ deadline = time.monotonic() + min(wait, _TURN_HOLD_MAX_S)
+ while time.monotonic() < deadline and not rec["done"] and len(rec["events"]) <= since:
+ await asyncio.sleep(0.02)
+ if not rec["done"] and len(rec["events"]) > since:
+ await asyncio.sleep(max(0.0, min(_TURN_HOLD_LINGER_S, deadline - time.monotonic())))
+ return await run_in_threadpool(_turn_answer, turn_id, rec, since, wait > 0)
diff --git a/runner/tests/test_caller_env.py b/runner/tests/test_caller_env.py
index c9e9238d..722c7148 100644
--- a/runner/tests/test_caller_env.py
+++ b/runner/tests/test_caller_env.py
@@ -38,7 +38,7 @@ def test_a_turn_is_read_back_without_its_secret_values(monkeypatch):
"result": "the token is tok_0123456789abcdef in us-east-1", "error": "bad tok_0123456789abcdef",
"events": [{"type": "assistant", "message": {"content": [{"type": "text", "text": "echo tok_0123456789abcdef"}]}}],
"secrets": secrets})
- out = server.get_turn("turn_x")
+ out = __import__("asyncio").run(server.get_turn("turn_x"))
dumped = __import__("json").dumps(out)
assert "tok_0123456789abcdef" not in dumped and "us-east-1" not in dumped
assert out["result"] == "the token is [redacted] in [redacted]" and out["error"] == "bad [redacted]"
diff --git a/runner/tests/test_turn_hold.py b/runner/tests/test_turn_hold.py
new file mode 100644
index 00000000..06fc9365
--- /dev/null
+++ b/runner/tests/test_turn_hold.py
@@ -0,0 +1,155 @@
+"""GET /turn/{id}?wait= holds its answer until the turn has something new.
+
+The gateway asked for a turn's events every 1.2 s, which put up to that long before a turn's first
+text and again before its end (measured on the hosted service, 2026-10-05). A held answer comes when
+there is an event past `since`, when the turn is done, or when `wait` has passed, and says `held` so
+a caller can tell this runner from one that ignores the parameter.
+"""
+import asyncio
+import os
+import sys
+import threading
+import time
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
+import server # noqa: E402
+from server import _hermes_error_text # noqa: E402
+
+
+def get_turn(*a, **kw) -> dict:
+ return asyncio.run(server.get_turn(*a, **kw))
+
+
+def _turn(tid: str) -> dict:
+ rec = {"status": "running", "events": [], "result": "", "done": False, "backend": "pi",
+ "model": "m", "started": time.time()}
+ server._turns[tid] = rec
+ return rec
+
+
+def _later(delay: float, fn) -> None:
+ threading.Timer(delay, fn).start()
+
+
+def test_without_wait_the_answer_is_immediate_and_does_not_claim_to_be_held():
+ _turn("t-plain")
+ t0 = time.monotonic()
+ out = get_turn("t-plain", since=0)
+ assert time.monotonic() - t0 < 0.2 and "held" not in out and out["events"] == []
+
+
+def test_a_held_answer_comes_when_an_event_arrives_not_when_the_wait_ends():
+ rec = _turn("t-event")
+ _later(0.2, lambda: rec["events"].append({"type": "assistant", "n": 1}))
+ t0 = time.monotonic()
+ out = get_turn("t-event", since=0, wait=5)
+ took = time.monotonic() - t0
+ assert 0.2 <= took < 1.0, took
+ assert out["held"] is True and out["n_total"] == 1 and out["events"] == [{"type": "assistant", "n": 1}]
+
+
+def test_events_that_follow_within_a_moment_travel_in_the_same_answer():
+ rec = _turn("t-burst")
+ _later(0.10, lambda: rec["events"].append({"n": 1}))
+ _later(0.15, lambda: rec["events"].append({"n": 2}))
+ _later(0.20, lambda: rec["events"].append({"n": 3}))
+ out = get_turn("t-burst", since=0, wait=5)
+ assert [e["n"] for e in out["events"]] == [1, 2, 3]
+
+
+def test_the_end_of_a_turn_is_answered_at_once_with_no_lingering():
+ rec = _turn("t-done")
+
+ def finish():
+ rec["events"].append({"type": "result"})
+ rec["status"], rec["done"] = "done", True
+ _later(0.2, finish)
+ t0 = time.monotonic()
+ out = get_turn("t-done", since=0, wait=5)
+ assert time.monotonic() - t0 < 0.3 + server._TURN_HOLD_LINGER_S
+ assert out["done"] is True and out["status"] == "done" and out["n_total"] == 1
+
+
+def test_nothing_new_is_answered_when_the_wait_has_passed_and_only_events_past_since_count():
+ rec = _turn("t-quiet")
+ rec["events"].extend([{"n": 1}, {"n": 2}])
+ t0 = time.monotonic()
+ out = get_turn("t-quiet", since=2, wait=0.3)
+ assert 0.3 <= time.monotonic() - t0 < 0.7
+ assert out["held"] is True and out["events"] == [] and out["n_total"] == 2
+
+
+def test_the_hold_is_capped(monkeypatch):
+ _turn("t-cap")
+ monkeypatch.setattr(server, "_TURN_HOLD_MAX_S", 0.2)
+ t0 = time.monotonic()
+ get_turn("t-cap", since=0, wait=3600)
+ assert time.monotonic() - t0 < 0.6
+
+
+def test_many_held_turns_wait_together_without_a_thread_each():
+ """One runner serves every session of a self-hosted instance. A hold that slept on a worker
+ thread would take one per running turn, and the pool that starts turns has forty."""
+ for i in range(120):
+ _turn(f"t-many-{i}")
+
+ async def all_at_once():
+ t0 = time.monotonic()
+ outs = await asyncio.gather(*(server.get_turn(f"t-many-{i}", since=0, wait=0.4) for i in range(120)))
+ return time.monotonic() - t0, outs
+
+ took, outs = asyncio.run(all_at_once())
+ assert took < 1.5, took # together, not forty at a time
+ assert all(o["held"] is True and o["events"] == [] for o in outs)
+
+
+def test_a_hermes_failure_is_not_explained_by_the_clis_closing_session_line():
+ only_sid = ["session_id: 20261005_135032_0fb4fd\n"]
+ text = _hermes_error_text(only_sid, 0, 277.4)
+ assert "session_id" not in text and "without a final answer" in text
+ assert "exit code 0" in text and "277 s" in text
+ said = ["Error: provider returned 400: context length exceeded", "session_id: 20261005_135032_0fb4fd"]
+ assert _hermes_error_text(said, 1, 3.0) == "Error: provider returned 400: context length exceeded"
+
+
+def test_what_a_cli_rebuilds_for_itself_is_not_saved_with_the_workspace(tmp_path):
+ """Saved with the workspace, these were most of what a turn's end waited for: omp's two native
+ binaries were a 183 MB archive and 10 s after every turn (the hosted service, 2026-10-05)."""
+ for p in ("./.harness/home/.omp/natives", "./.harness/home/.codex/.tmp", "./.harness/home/.cache/pkg"):
+ assert p in server.CHECKPOINT_EXCLUDE
+ # with the image's own tar (GNU; bsdtar reads an exclude pattern differently) the folders are
+ # left out while their neighbours, the conversation state a resume needs, are kept
+ import shutil
+ import subprocess
+ tar = next((t for t in ("gtar", "tar") if shutil.which(t)
+ and b"GNU tar" in subprocess.run([t, "--version"], capture_output=True).stdout), None)
+ if not tar:
+ return
+ for rel in (".harness/home/.omp/natives/18.1.13/pi_natives.node", ".harness/home/.omp/agent/agent.db",
+ ".harness/home/.codex/.tmp/plugins/README.md", ".harness/home/.codex/sessions/a.jsonl",
+ ".harness/home/.cache/pkg/abc/lib.so", ".harness/home/.cache/opencode/models.json", "notes.md"):
+ f = tmp_path / rel
+ f.parent.mkdir(parents=True, exist_ok=True)
+ f.write_text("x")
+ excl = [f"--exclude={p}" for p in server.CHECKPOINT_EXCLUDE]
+ made = subprocess.run([tar, "-cf", "-", *excl, "-C", str(tmp_path), "."], capture_output=True, check=True)
+ listed = subprocess.run([tar, "-tf", "-"], input=made.stdout, capture_output=True, check=True).stdout.decode()
+ for gone in ("natives", ".codex/.tmp", ".cache/pkg"):
+ assert gone not in listed, gone
+ for kept in (".omp/agent/agent.db", ".codex/sessions/a.jsonl", ".cache/opencode/models.json", "notes.md"):
+ assert kept in listed, kept
+
+
+def test_the_cli_home_is_out_of_the_workspaces_own_history_so_the_tar_is_the_only_place(tmp_path):
+ """On the hosted service the same binaries had a second copy in .git/objects, which the tar also
+ carries. Here the whole CLI home has been ignored by the workspace's repository since #193."""
+ import subprocess
+ ws = str(tmp_path)
+ for rel in (".harness/home/.omp/natives/18.1.13/pi_natives.node", ".harness/home/.cache/pkg/abc/lib.so", "notes.md"):
+ f = tmp_path / rel
+ f.parent.mkdir(parents=True, exist_ok=True)
+ f.write_text("x")
+ server._git_ensure(ws)
+ subprocess.run(["git", "-C", ws, "add", "-A"], check=True, env={**os.environ, **server._GIT_ENV})
+ tracked = subprocess.run(["git", "-C", ws, "ls-files"], capture_output=True, check=True).stdout.decode()
+ assert "notes.md" in tracked and ".harness/home" not in tracked