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
fix(gateway): a recycle restores the session's checkpoint and never checkpoints first (#70)
github-actions[bot]c66645051b02
diff --git a/gateway/app.py b/gateway/app.pyindex 4382543c..8cd0bcff 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -1874,9 +1874,11 @@ async def _brain_mint_room(sid: str) -> str | None:return None-async def _hydrate(sid: str, rec: dict) -> None:+async def _hydrate(sid: str, rec: dict, force: bool = False) -> None:"""Restore the session's last checkpoint into the sandbox /workspace before the turn runs, and- pass the blackboard room so the runner (re)starts the realtime sidecar for this session."""+ pass the blackboard room so the runner (re)starts the realtime sidecar for this session.+ `force` skips the warm-sandbox probe: the workspace is wiped and restored from the durable+ checkpoint even when the sandbox still holds it (a recycle on purpose)."""params = {}v = await _vertex_get(sid) or {} # single durable read: blackboard room + checkpoint sharoom = (v.get("brain_room") or None) if COLLAB_URL else None@@ -1887,7 +1889,7 @@ async def _hydrate(sid: str, rec: dict) -> None:# checkpoint (sha marker kept by the runner), skip the blob download and the full# wipe+untar — the dominant cost of every follow-up turn on a big workspace.want_sha = str(v.get("ws_sha") or "")- if want_sha:+ if want_sha and not force:try:pr = await _sandbox("/hydrate", sid, "POST", content=b"",params={**(params or {}), "probe": want_sha})@@ -5913,19 +5915,23 @@ async def storage_usage() -> dict:@app.post("/internal/sessions/{sid}/recycle", dependencies=[Depends(_internal_only)])async def recycle_session_sandbox(sid: str) -> dict:- """Recycle a session's sandbox on purpose: persist the workspace, then hydrate it back into the- same sandbox, which wipes and restores exactly as a fresh sandbox would after the old one was- let go. The support matrix uses it to test "a follow-up after the sandbox is gone" for every- harness and model without waiting out a cooldown. Refused while a turn is live."""+ """Recycle a session's sandbox on purpose: wipe the workspace and restore it from the durable+ checkpoint, exactly what a follow-up pays after the pool let the old sandbox go. The support+ matrix uses it to test "a follow-up after the sandbox is gone" for every harness and model+ without waiting out the pool's cooldown. Refused while a turn is live.++ Hydrate only, never checkpoint first: every turn already ends with a checkpoint, so the blob IS+ the post-turn workspace, and a checkpoint taken from a sandbox that no longer holds the session+ would tar an empty directory over it (that is how the first recycle pass lost the history of+ every session whose sandbox had gone cold)."""v = await _vertex_get(sid)if not v:raise HTTPException(404, "no such session")if {"running", "starting"} & {str(v.get("turn_status") or ""), str(v.get("status") or "")}:raise HTTPException(409, "a turn is running; recycle after it settles")rec: dict = {}- await _checkpoint(sid, rec)- await _hydrate(sid, rec)- return {"session_id": sid, "checkpoint": rec.get("checkpoint") or rec.get("checkpoint_bytes"),+ await _hydrate(sid, rec, force=True)+ return {"session_id": sid, "checkpoint_sha": str(v.get("ws_sha") or ""),"hydrated": bool(rec.get("hydrated")), "hydrate": rec.get("hydrate"), "hydrate_error": rec.get("hydrate_error")}diff --git a/gateway/tests/test_recycle_route.py b/gateway/tests/test_recycle_route.pynew file mode 100644index 00000000..0ee5b913--- /dev/null+++ b/gateway/tests/test_recycle_route.py@@ -0,0 +1,75 @@+"""The recycle route restores the durable checkpoint into the sandbox and never checkpoints first:+a checkpoint taken from a sandbox that no longer holds the session would overwrite the good blob+with an empty workspace."""+import asyncio+import sys+from pathlib import Path++import pytest+from fastapi import HTTPException++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+import app # noqa: E402++++def test_recycle_hydrates_without_probe_and_without_checkpoint(monkeypatch):+ calls = []+ async def vertex_get(sid):+ return {"ws_sha": "abc123", "turn_status": "completed"}+ async def sandbox(path, sid, method, **kw):+ calls.append(("probe", kw.get("params")))+ raise AssertionError("the probe must not run on a forced hydrate")+ class R:+ status_code = 200+ headers = {"content-type": "application/json"}+ def json(self):+ return {"ok": True, "restored": True, "skipped": False}+ async def relay(sid, params):+ calls.append(("relay", sid))+ return R()+ async def checkpoint(sid, rec):+ calls.append(("checkpoint", sid))+ monkeypatch.setattr(app, "_vertex_get", vertex_get)+ monkeypatch.setattr(app, "_sandbox", sandbox)+ monkeypatch.setattr(app, "_hydrate_relay", relay)+ monkeypatch.setattr(app, "_checkpoint", checkpoint)+ monkeypatch.setattr(app, "COLLAB_URL", "")+ out = asyncio.run(app.recycle_session_sandbox("hsess1"))+ assert calls == [("relay", "hsess1")]+ assert out["hydrated"] is True and out["hydrate"]["restored"] is True+ assert out["checkpoint_sha"] == "abc123"+++def test_recycle_refused_while_a_turn_runs(monkeypatch):+ async def vertex_get(sid):+ return {"ws_sha": "abc123", "turn_status": "running"}+ monkeypatch.setattr(app, "_vertex_get", vertex_get)+ with pytest.raises(HTTPException) as e:+ asyncio.run(app.recycle_session_sandbox("hsess1"))+ assert e.value.status_code == 409+++def test_hydrate_probe_still_used_for_ordinary_turns(monkeypatch):+ """Without force the warm-sandbox probe runs first and a match skips the restore."""+ calls = []+ async def vertex_get(sid):+ return {"ws_sha": "abc123"}+ class P:+ status_code = 200+ headers = {"content-type": "application/json"}+ def json(self):+ return {"ok": True, "skipped": True, "restored": False}+ async def sandbox(path, sid, method, **kw):+ calls.append(("probe", (kw.get("params") or {}).get("probe")))+ return P()+ async def relay(sid, params):+ calls.append(("relay", sid))+ raise AssertionError("a matching probe must skip the relay")+ monkeypatch.setattr(app, "_vertex_get", vertex_get)+ monkeypatch.setattr(app, "_sandbox", sandbox)+ monkeypatch.setattr(app, "_hydrate_relay", relay)+ monkeypatch.setattr(app, "COLLAB_URL", "")+ rec = {}+ asyncio.run(app._hydrate("hsess1", rec))+ assert calls == [("probe", "abc123")] and rec["hydrated"] is True and rec["hydrate"]["skipped"] is True