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 trace whose chunk could not be read says so, and is never served as a short transcript (#556)
Rudy Mizrahi Celeklib42ba41c28da
diff --git a/gateway/app.py b/gateway/app.pyindex df5ec8af..8fddb2e5 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -5332,6 +5332,11 @@ async def get_trace_events(sid: str, request: Request, chunk: int = 0) -> Responreturn Response(content=b, media_type="application/x-ndjson")+# A chunk read that could not be answered is said (503 server_error, as the conversation's turns say+# it since #540), never served as a transcript that happens to end early.+_TRACE_UNREADABLE = "This transcript could not be loaded just now. Try again in a moment."++@app.get("/v1/traces/{sid}/all")async def get_trace_all(sid: str, request: Request, compact: int = 0) -> Response:"""ALL events for a session in ONE response.@@ -5387,7 +5392,15 @@ async def get_trace_all(sid: str, request: Request, compact: int = 0) -> Responsexcept Exception: # noqa: BLE001n = 0chunk_ids = [f"{base}/events/{i:06d}.jsonl" for i in range(max(n, 1))]- parts = await asyncio.gather(*[_blob_get(cid, kb=TRACE_KB) for cid in chunk_ids])+ # STRICT reads (#540's instrument): the cache below already refuses to store a join whose chunk+ # read failed — the same failure must not be SERVED either, as a short 200. get_or_raise answers+ # None only for a chunk that is not there (the synthesized fallback key above may name one, and+ # that is still an empty transcript), and raises when a read could not be answered.+ try:+ parts = await asyncio.gather(*[_blob_get_or_raise(cid, kb=TRACE_KB) for cid in chunk_ids])+ except backing.BlobUnavailable as e:+ print(f"[trace] a trace chunk could not be read sid={sid}: {type(e).__name__}", flush=True)+ raise uhp_error(503, "server_error", _TRACE_UNREADABLE) from ebody = b"".join(p for p in parts if p)if finalized and body and all(p is not None for p in parts):# Cache ONLY a provably-complete join (a transient chunk-get failure must never become adiff --git a/gateway/tests/test_trace_all_never_silently_short.py b/gateway/tests/test_trace_all_never_silently_short.pynew file mode 100644index 00000000..9b2e29ce--- /dev/null+++ b/gateway/tests/test_trace_all_never_silently_short.py@@ -0,0 +1,122 @@+"""A transcript is never served SHORT because a chunk read failed.++`GET /v1/traces/{sid}/all` joins the session's event chunks. The join skipped any chunk that came+back empty, so a chunk the store could not read was dropped and the route answered 200 with a+transcript missing the middle of the run — while the CACHE beside it already refused to store+exactly that join ("a transient chunk-get failure must never become a permanently-truncated+authoritative transcript"). What these pin, on the self-hosted file store where a read can really+fail (a directory where the object's file belongs: EISDIR, as EIO or EMFILE would be):+ a chunk that cannot be read is said (503 server_error, the protocol's code), never a short 200;+ every chunk readable still reads back the WHOLE transcript, in chunk order, compact and full;+ a chunk that is simply NOT THERE is still not a failure — the join carries on, as before.+"""+from __future__ import annotations++import asyncio+import json+import os+import sys+from pathlib import Path++import pytest+from fastapi.testclient import TestClient++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+os.environ.setdefault("HR_BACKING", "local")+import app as gw # noqa: E402+import backing # noqa: E402++ORG = "local"+_n = [0]+++def stores(monkeypatch, tmp_path):+ monkeypatch.setattr(gw.BACKING, "graph", backing.SqliteGraphStore(str(tmp_path / "graph.db")))+ monkeypatch.setattr(gw.BACKING, "blob", backing.FileBlobStore(str(tmp_path / "blobs")))+ monkeypatch.setattr(gw, "VG_GATEWAY_URL", "")++ async def principal(request):+ return {"org": ORG, "member": "me@local"}+ monkeypatch.setattr(gw, "_principal", principal)+ return tmp_path+++def _event(i: int) -> bytes:+ return json.dumps({"type": "message", "seq": i}).encode() + b"\n"+++def _trace(chunks: list[bytes], status: str = "done") -> tuple[str, str, list[str]]:+ """A session whose events/ holds `chunks`, written as a turn writes them. Returns+ (sid, base, chunk keys in order)."""+ _n[0] += 1+ sid = f"hsesstrall{_n[0]}{os.urandom(3).hex()}"+ base = f"{ORG}/0000_{sid}"+ keys = []+ for i, c in enumerate(chunks):+ key = f"{base}/events/{1792560576000 + i}-aaaa-{i}-{c.count(b'\n')}.jsonl"+ assert asyncio.run(gw._blob_put(key, c, kb=gw.TRACE_KB))+ keys.append(key)+ asyncio.run(gw._blob_put(gw._manifest_key(base), json.dumps({"status": status}).encode(),+ kb=gw.TRACE_KB))+ asyncio.run(gw._vertex_upsert(sid, {"tenant": ORG, "status": status, "trace_blob": base,+ "member_id": "me@local"}))+ return sid, base, keys+++def _unreadable(tmp_path: Path, key: str) -> None:+ """The chunk's object is there, is LISTED, and cannot be read (EACCES, as EIO or EMFILE would+ be): not the same thing as a chunk that is not there."""+ (tmp_path / "blobs" / gw.TRACE_KB / key).chmod(0o000)+++def test_a_whole_transcript_reads_back_whole(stores):+ chunks = [_event(0) + _event(1), _event(2), _event(3)]+ sid, _, _ = _trace(chunks)+ api = TestClient(gw.app)+ r = api.get(f"/v1/traces/{sid}/all")+ assert r.status_code == 200, r.text+ assert r.content == b"".join(chunks)+ assert [json.loads(ln)["seq"] for ln in r.content.splitlines()] == [0, 1, 2, 3]+ assert len(api.get(f"/v1/traces/{sid}/all?compact=1").content.splitlines()) == 4+++def test_a_chunk_that_cannot_be_read_is_said_never_a_short_transcript(stores):+ tmp = stores+ chunks = [_event(0), _event(1), _event(2)]+ sid, base, keys = _trace(chunks)+ _unreadable(tmp, keys[1])+ r = TestClient(gw.app).get(f"/v1/traces/{sid}/all")+ assert r.status_code == 503, f"{r.status_code} {r.content!r}"+ err = r.json()["error"]+ assert err["type"] == "server_error" and err["code"] == "server_error"+ assert err["message"] == "This transcript could not be loaded just now. Try again in a moment."+ # and nothing was cached from the failed join+ assert asyncio.run(gw._blob_get(f"{base}/all.jsonl", kb=gw.TRACE_KB)) is None+ assert TestClient(gw.app).get(f"/v1/traces/{sid}/all?compact=1").status_code == 503+++def test_a_chunk_that_is_not_there_is_still_not_a_failure(stores):+ """The join falls back to a SYNTHESIZED key when the listing comes back empty, and that key+ names an object that is not there. That is an empty transcript, not a failure."""+ sid, _, _ = _trace([])+ r = TestClient(gw.app).get(f"/v1/traces/{sid}/all")+ assert r.status_code == 200, f"{r.status_code} {r.content!r}"+ assert r.content == b""+++def test_an_empty_but_readable_chunk_is_not_a_failure(stores, monkeypatch):+ """A chunk read that SUCCEEDS with no bytes contributes nothing to the join and is not the+ failure above. The writer never emits one (_trace_flush writes only a non-empty chunk, always+ newline-terminated) and FileBlobStore.put refuses empty data, so this drives the store+ directly — the point is that the strict read leaves the empty case exactly as it was."""+ chunks = [_event(0), _event(1)]+ sid, _, keys = _trace(chunks)+ real = gw.BACKING.blob.get_or_raise++ async def get_or_raise(kb, file_id):+ return b"" if file_id == keys[0] else await real(kb, file_id)+ monkeypatch.setattr(gw.BACKING.blob, "get_or_raise", get_or_raise)+ r = TestClient(gw.app).get(f"/v1/traces/{sid}/all")+ assert r.status_code == 200, f"{r.status_code} {r.content!r}"+ assert r.content == chunks[1]