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.

produced files: one too large to attach is named in the answer, and never read into the gateway (#522)

github-actions[bot]7c8e71c44189
diff --git a/gateway/app.py b/gateway/app.py
index aba83a1c..894dcf38 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -377,10 +377,16 @@ def _reasoning_level(value, where: str = "") -> str:
return level
# Output (container) files produced by a turn are capped to keep a single response bounded.
RESP_MAX_FILES = int(os.environ.get("HARNESS_RESP_MAX_FILES", "25"))
-RESP_MAX_FILE_BYTES = int(os.environ.get("HARNESS_RESP_MAX_FILE_BYTES", str(25 * 1024 * 1024)))
+# A produced file over this is never read into the gateway (_sandbox_file): it gets no card and the
+# answer names it, its size and where it is (_too_large_note). 64 MiB, up from 25: the files seen
+# over the old cap were 25.5 to 49.1 MiB (hosted, 2026-10-19). Its size is learned before any byte
+# is read (the runner's listing, else the stated length), so a collection holds at most one file of
+# this size at a time.
+RESP_MAX_FILE_BYTES = int(os.environ.get("HARNESS_RESP_MAX_FILE_BYTES", str(64 * 1024 * 1024)))
# /v1/files upload cap (HR-INF-015): the route had NO cap — a huge upload buffered whole in the
# gateway AND ballooned again as base64 in the runner turn body. 25 MiB matches the engine's
-# attachment cap and RESP_MAX_FILE_BYTES, bounding the inline-b64 turn payload to ~33 MB.
+# attachment cap, bounding the inline-b64 turn payload to ~33 MB. (Produced files are never inlined
+# into a turn, so their cap above is not bound to this one.)
_UPLOAD_MAX_BYTES = int(os.environ.get("HARNESS_UPLOAD_MAX_BYTES", str(25 * 1024 * 1024)))
RESP_BLOB_KB = os.environ.get("HARNESS_RESP_BLOB_KB", "harness-responses") # response records + container files
# Durable session-workspace store (git checkpoint tarball per session) lives in vg-gateway blob
@@ -1811,6 +1817,40 @@ async def _sandbox(path: str, sid: str, method: str = "POST", body: dict | None
headers=_pool_headers(), **kw)
+async def _sandbox_file(sid: str, path: str, cap: int) -> tuple[int, bytes | None, str, int | None]:
+ """One workspace file from the runner, never holding more than `cap` bytes of it plus one chunk:
+ (status, its bytes or None when it is over the cap, media type, its size when known).
+
+ The length the runner states is read before the body, so a file over the cap is never read at
+ all; a body with no stated length is read in chunks and abandoned once it passes the cap (its
+ size is then unknown, only that it is over). It used to be read whole and measured after: a turn's
+ seven images of 33 to 49 MB passed through the gateway in two seconds to be dropped (hosted,
+ 2026-10-19)."""
+ c = _client()
+ req = c.build_request("GET", f"{POOL_ENDPOINT}/file", params={"identifier": sid, "path": path},
+ headers=_pool_headers())
+ r = await c.send(req, stream=True)
+ try:
+ media = r.headers.get("content-type", "application/octet-stream")
+ if r.status_code >= 400:
+ return r.status_code, None, media, None
+ try:
+ stated = int(r.headers.get("content-length") or -1)
+ except ValueError:
+ stated = -1
+ if stated > cap:
+ return r.status_code, None, media, stated
+ chunks, got = [], 0
+ async for chunk in r.aiter_bytes():
+ got += len(chunk)
+ if got > cap:
+ return r.status_code, None, media, None
+ chunks.append(chunk)
+ return r.status_code, b"".join(chunks), media, got
+ finally:
+ await r.aclose()
+
+
class _SandboxRefused(RuntimeError):
"""The runner answered with its own verdict (a 4xx other than 429): `status` and the reason it
gave (`detail`), so a turn it refused to start says why rather than reading as a connection
@@ -2914,17 +2954,12 @@ async def _adopt_orphan_turn(sid: str, org: str, v: dict) -> bool:
if translator.charge:
rec["charge"] = translator.charge
await _vertex_upsert(sid, {"status": rec["status"], "turn_status": rec["status"]})
+ produced: list[dict] = []
try:
# Every terminal outcome collects. A cancelled or failed turn may already have written the
# deliverable (a Stop that lands after the file is saved, an OOM at finalize) — skipping
# collection threw those files away from the record while they sat in the workspace.
produced = await _collect_produced(sid, set())
- # Translate for the wire, the same way the persist just below does: `rec["status"]` holds
- # the trace's name for the outcome (`done`, `max_turns`, `timeout`), and `complete()` both
- # puts it in the response object and looks the event name up by it, so an untranslated
- # status reached subscribers as `status: "max_turns"` under a `response.completed` (#480).
- for oev in translator.complete(_RESP_STATUS_MAP.get(rec["status"], "failed"), produced):
- _emit(oev)
except Exception: # noqa: BLE001
pass
# The turn's browser closes BEFORE the trace is finalized: its stop row (the vendor's stop
@@ -2933,7 +2968,19 @@ async def _adopt_orphan_turn(sid: str, org: str, v: dict) -> bool:
# the manifest said terminal, so the row reached the audit and never the trace (hosted, every
# base of the browser column, 2026-09-27). persist() still closes a turn that never got here.
await _browser_close(sid, "turn_end")
+ # Saved before the answer completes, as on the primary path: whether a file too large to
+ # attach is in the task's files is known only once the save has landed (_too_large_saved).
await _checkpoint(sid, rec)
+ try:
+ _too_large_saved(produced, rec)
+ # Translate for the wire, the same way the persist just below does: `rec["status"]` holds
+ # the trace's name for the outcome (`done`, `max_turns`, `timeout`), and `complete()` both
+ # puts it in the response object and looks the event name up by it, so an untranslated
+ # status reached subscribers as `status: "max_turns"` under a `response.completed` (#480).
+ for oev in translator.complete(_RESP_STATUS_MAP.get(rec["status"], "failed"), produced):
+ _emit(oev)
+ except Exception: # noqa: BLE001
+ pass
await _trace_finalize(sid, rec)
# Persist the response record with the FULL turn output — NOT translator.output, which only
# holds events AFTER our resume cursor (we joined mid-turn). Reconstruct the whole turn from the
@@ -2945,7 +2992,10 @@ async def _adopt_orphan_turn(sid: str, org: str, v: dict) -> bool:
stored = {**translator._response_obj(_status), "_session_id": sid, "_org": org,
"_member": member}
if full_output:
- stored["output"] = full_output
+ # the trace holds the runner's events, not the gateway's own closing paragraph on files
+ # too large to attach (complete), so that paragraph is carried over onto the record
+ note = translator.note_item
+ stored["output"] = full_output + ([note] if note and note not in full_output else [])
await _resp_put(resp_id, stored, org, sid, None, _status, translator.created_at, True)
except Exception: # noqa: BLE001
pass
@@ -6236,6 +6286,7 @@ class _RespTranslator:
self.error: dict | None = None
self.cur: dict | None = None
self.any_text = False
+ self.note_item: dict | None = None # the answer's paragraph on files too large to attach (complete)
def _ev(self, type_: str, **f) -> dict:
e = {"type": type_, "sequence_number": self.seq, **f}
@@ -6411,6 +6462,10 @@ class _RespTranslator:
def complete(self, status: str, files: list[dict] | None = None) -> list[dict]:
evs: list[dict] = []
+ # A file too large to attach (_collect_produced) has no card: the answer says so in its own
+ # last paragraph, kept as note_item for a record rebuilt from the trace (_adopt_orphan_turn).
+ big = [f for f in (files or []) if f.get("too_large")]
+ files = [f for f in (files or []) if not f.get("too_large")]
if files:
if not (self.cur and self.cur["kind"] == "message"):
evs += self._close_cur()
@@ -6421,6 +6476,11 @@ class _RespTranslator:
"download_url": _file_url(f["container_id"], f["file_id"]),
"start_index": 0, "end_index": len(self.cur["text"])} for f in files]
evs += self._close_cur()
+ if big:
+ evs += self._open_message()
+ evs += self._handle("text", _too_large_note(big))
+ evs += self._close_cur()
+ self.note_item = self.output[-1]
ev_type = {"completed": "response.completed", "incomplete": "response.incomplete",
"failed": "response.failed", "cancelled": "response.failed"}.get(status, "response.completed")
evs.append(self._ev(ev_type, response=self._response_obj(status)))
@@ -8115,6 +8175,42 @@ def _produced_rel(path: str) -> str:
return path
+def _too_large_saved(produced: list[dict], rec: dict) -> None:
+ """Mark each file too large to attach with whether it is in the task's files: the turn's save
+ landed (_checkpoint) and the files listing shows that path (_ws_visible). Only then does the
+ answer say where it is; a file the listing would not show is never said to be there."""
+ saved = rec.get("checkpointed") is True
+ for f in produced:
+ if f.get("too_large"):
+ f["saved"] = saved and _ws_visible(str(f.get("filename") or ""))
+
+
+def _too_large_note(big: list[dict]) -> str:
+ """The answer's last paragraph for the turn's files too large to attach: each by its path and
+ size (MB, the unit RESP_MAX_FILE_BYTES is set in), and where it is when it is saved. A file whose
+ reading was stopped at the cap (no stated length) is "over" the cap, never a guessed size."""
+ def _mb(f: dict) -> str:
+ n = f.get("bytes")
+ return f"{n / (1024 * 1024):.1f} MB" if n else f"over {RESP_MAX_FILE_BYTES / (1024 * 1024):g} MB"
+
+ def _named(fs: list[dict]) -> str:
+ return ", ".join(f"{f['filename']} ({_mb(f)})" for f in fs)
+ saved = [f for f in big if f.get("saved")]
+ unsaved = [f for f in big if not f.get("saved")]
+ lines = []
+ if len(saved) == 1:
+ f = saved[0]
+ lines.append(f"{f['filename']} is too large to attach here ({_mb(f)}); it's saved in the task's files.")
+ elif saved:
+ lines.append(f"These files are too large to attach here; they're saved in the task's files: {_named(saved)}.")
+ if len(unsaved) == 1:
+ f = unsaved[0]
+ lines.append(f"{f['filename']} is too large to attach here ({_mb(f)}).")
+ elif unsaved:
+ lines.append(f"These files are too large to attach here: {_named(unsaved)}.")
+ return "\n\n".join(lines)
+
+
async def _collect_produced(sid: str, exclude: set[str] | None = None) -> list[dict]:
exclude = exclude or set()
try:
@@ -8135,25 +8231,43 @@ async def _collect_produced(sid: str, exclude: set[str] | None = None) -> list[d
# The cap counts produced files, so what is never one (an internal name, an input file the
# caller attached) is set aside before it: an internal file newer than the rest must not
# take a slot from a real one.
- wanted: list[tuple[str, str]] = []
+ wanted: list[tuple[dict, str]] = []
for it in items:
path = (it or {}).get("path")
rel = _produced_rel(path) if path else ""
if rel and rel not in exclude and not _is_internal_output(rel):
- wanted.append((path, rel))
- for path, rel in wanted[:RESP_MAX_FILES]:
+ wanted.append((it, rel))
+ for it, rel in wanted[:RESP_MAX_FILES]:
+ path = it["path"]
try:
- fr = await _sandbox("/file", sid, "GET", params={"path": path})
- if fr.status_code >= 400 or not fr.content or len(fr.content) > RESP_MAX_FILE_BYTES:
+ # Its size before any byte of it: the runner's listing says it (a runner from before the
+ # field does not), else the length the runner states, else the read stops at the cap.
+ try:
+ listed = int(it.get("size"))
+ except (TypeError, ValueError):
+ listed = -1
+ if listed > RESP_MAX_FILE_BYTES:
+ status, data, media, size = 200, None, "", listed # never asked for
+ else:
+ status, data, media, size = await _sandbox_file(sid, path, RESP_MAX_FILE_BYTES)
+ if status >= 400:
+ continue
+ if data is None:
+ # No card, but named: the answer says it is too large to attach and where it is
+ # (_too_large_note). Skipped in silence, a person was left looking for a file the
+ # agent had named (hosted, 2026-10-19, nine images of 25.5 to 49.1 MB).
+ print(f"[produced] sid={sid} file_too_big {size or f'over {RESP_MAX_FILE_BYTES}'}", flush=True)
+ out.append({"filename": rel, "bytes": size, "too_large": True})
continue
+ if not data:
+ continue # an empty file: nothing to hand over
cfile = _rid("cfile")
- media = fr.headers.get("content-type", "application/octet-stream")
fname = rel
- if await _blob_put(f"containers/{sid}/{cfile}", fr.content, kb=RESP_BLOB_KB):
+ if await _blob_put(f"containers/{sid}/{cfile}", data, kb=RESP_BLOB_KB):
await _blob_put(f"containers/{sid}/{cfile}.meta",
json.dumps({"filename": fname, "media_type": media,
"written_at": time.time()}).encode(), kb=RESP_BLOB_KB)
- out.append({"container_id": sid, "file_id": cfile, "filename": fname, "bytes": len(fr.content)})
+ out.append({"container_id": sid, "file_id": cfile, "filename": fname, "bytes": len(data)})
except Exception: # noqa: BLE001
continue
# Advance the runner's collection cursor ONLY now that the files are captured to blobs. This is
@@ -8702,6 +8816,7 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s
_cancel_req.pop(sid, None) # turn settled — a leftover Stop must not hit the next turn
await _browser_close(sid, "turn_end") # before the checkpoint and the finalize: the stop row belongs in the trace (see _adopt_orphan_turn)
await _checkpoint(sid, rec)
+ _too_large_saved(produced, rec) # the answer says a file is in the task's files only once it is
# The checkpoint replaced the workspace tarball with the sandbox's own copy, so anything the
# media server wrote into it during the turn is gone. Re-project here — one line, one place,
# and the only ordering at which a hosted write survives.
diff --git a/gateway/tests/test_produced_too_large.py b/gateway/tests/test_produced_too_large.py
new file mode 100644
index 00000000..8c2da799
--- /dev/null
+++ b/gateway/tests/test_produced_too_large.py
@@ -0,0 +1,309 @@
+"""A produced file too large to attach is said in the turn's answer, never dropped in silence, and never
+read into the gateway.
+
+_collect_produced skipped a file over RESP_MAX_FILE_BYTES with no card and no word in the answer, while
+the file sat in the task's files (hosted, 2026-10-19: two turns, nine images of 25.5 to 49.1 MB). Each
+was also read whole into the gateway before it was measured. The answer now ends with a plain sentence
+naming each one, its size and, only when the turn's save landed and the files listing shows it, where it
+is; and its size is learned before any byte of it is read.
+
+These run the real fetch (_sandbox_file) against a stand-in runner, so "never read" is observed on the
+wire: the runner's listing size means the file is never asked for; a stated length over the cap means
+its body is never read; with no length, the read stops one chunk past the cap.
+"""
+import asyncio
+import io
+import os
+import pathlib
+import sys
+import tarfile
+
+import httpx
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+os.environ.setdefault("HR_BACKING", "local")
+import app as A # noqa: E402
+
+MB = 1024 * 1024
+CAP = 1000
+
+
+class _Body(httpx.AsyncByteStream):
+ """A file's body that records how many of its chunks were read."""
+ def __init__(self, data: bytes, chunk: int = 100):
+ self.chunks = [data[i:i + chunk] for i in range(0, len(data), chunk)]
+ self.read = 0
+
+ async def __aiter__(self):
+ for c in self.chunks:
+ self.read += 1
+ yield c
+
+ async def aclose(self):
+ pass
+
+
+class _Runner:
+ """A stand-in runner: /produced lists the files (with sizes when `sized`), /file serves each one
+ with or without a stated length, and every request and body read is recorded."""
+ def __init__(self, files: dict[str, bytes], *, sized: bool, stated: bool = True):
+ self.files, self.sized, self.stated = files, sized, stated
+ self.asked: list[str] = []
+ self.bodies: dict[str, _Body] = {}
+
+ def __call__(self, req: httpx.Request) -> httpx.Response:
+ if req.url.path == "/produced":
+ return httpx.Response(200, json={"files": [
+ {"path": p, "mtime": i, **({"size": len(d)} if self.sized else {})}
+ for i, (p, d) in enumerate(self.files.items())]})
+ if req.url.path == "/file":
+ path = req.url.params["path"]
+ self.asked.append(path)
+ body = self.bodies[path] = _Body(self.files[path])
+ headers = {"content-type": "image/png"}
+ if self.stated:
+ headers["content-length"] = str(len(self.files[path]))
+ return httpx.Response(200, headers=headers, stream=body)
+ return httpx.Response(200, json={})
+
+
+def _wire(monkeypatch, runner: _Runner, cap: int = CAP):
+ client = httpx.AsyncClient(transport=httpx.MockTransport(runner))
+ stored: dict[str, bytes] = {}
+
+ async def blob_put(fid, data, kb=None):
+ stored[fid] = data
+ return True
+ monkeypatch.setattr(A, "_client", lambda: client)
+ monkeypatch.setattr(A, "_pool_headers", lambda: {})
+ monkeypatch.setattr(A, "POOL_ENDPOINT", "http://runner")
+ monkeypatch.setattr(A, "_blob_put", blob_put)
+ monkeypatch.setattr(A, "RESP_MAX_FILE_BYTES", cap)
+ return stored
+
+
+def _collect(monkeypatch, capsys, runner: _Runner):
+ stored = _wire(monkeypatch, runner)
+ out = asyncio.run(A._collect_produced("hsess_big"))
+ logged = capsys.readouterr().out.count("file_too_big")
+ return out, stored, logged
+
+
+_FILES = {"small.png": b"s" * 40, "out/hero.png": b"h" * (CAP * 3)}
+
+
+def test_the_cap_is_64_mib_by_default():
+ assert int(os.environ.get("HARNESS_RESP_MAX_FILE_BYTES", 64 * MB)) == A.RESP_MAX_FILE_BYTES == 64 * MB
+
+
+def test_a_file_the_listing_says_is_over_the_cap_is_never_asked_for(monkeypatch, capsys):
+ runner = _Runner(dict(_FILES), sized=True)
+ out, stored, logged = _collect(monkeypatch, capsys, runner)
+ assert runner.asked == ["small.png"] # hero.png never requested
+ assert logged == 1 # still logged
+ assert [f for f in out if f.get("too_large")] == [{"filename": "out/hero.png", "bytes": CAP * 3, "too_large": True}]
+ assert [f["filename"] for f in out if not f.get("too_large")] == ["small.png"]
+ assert not any(v == _FILES["out/hero.png"] for v in stored.values())
+
+
+def test_a_stated_length_over_the_cap_means_the_body_is_never_read(monkeypatch, capsys):
+ runner = _Runner(dict(_FILES), sized=False) # a runner from before the listing's sizes
+ out, stored, logged = _collect(monkeypatch, capsys, runner)
+ assert runner.bodies["out/hero.png"].read == 0 # asked, its length read, not one byte of it
+ assert runner.bodies["small.png"].read == 1
+ assert [f for f in out if f.get("too_large")] == [{"filename": "out/hero.png", "bytes": CAP * 3, "too_large": True}]
+ assert logged == 1 and not any(v == _FILES["out/hero.png"] for v in stored.values())
+
+
+def test_with_no_stated_length_the_read_stops_one_chunk_past_the_cap(monkeypatch, capsys):
+ runner = _Runner(dict(_FILES), sized=False, stated=False)
+ out, stored, logged = _collect(monkeypatch, capsys, runner)
+ hero = runner.bodies["out/hero.png"]
+ assert hero.read == CAP // 100 + 1 < len(hero.chunks) # 11 of 30 chunks: the cap plus one chunk
+ assert [f for f in out if f.get("too_large")] == [{"filename": "out/hero.png", "bytes": None, "too_large": True}]
+ assert logged == 1
+ small = [f for f in out if not f.get("too_large")]
+ assert [f["bytes"] for f in small] == [40] and stored[f"containers/hsess_big/{small[0]['file_id']}"] == _FILES["small.png"]
+ big = dict(next(f for f in out if f.get("too_large")), saved=True)
+ monkeypatch.setattr(A, "RESP_MAX_FILE_BYTES", 64 * MB) # a size never guessed: "over" the cap
+ assert A._too_large_note([big]) == "out/hero.png is too large to attach here (over 64 MB); it's saved in the task's files."
+
+
+def test_a_file_under_the_cap_is_read_as_before(monkeypatch, capsys):
+ runner = _Runner({"a.png": b"a" * CAP}, sized=True) # exactly the cap is under it
+ out, stored, logged = _collect(monkeypatch, capsys, runner)
+ assert logged == 0 and runner.asked == ["a.png"] and out[0]["bytes"] == CAP
+ assert stored[f"containers/hsess_big/{out[0]['file_id']}"] == b"a" * CAP
+
+
+def test_the_file_over_the_cap_is_listed_in_the_task_s_files_and_downloads(monkeypatch):
+ """What the answer's "saved in the task's files" promises: the files listing (read from the
+ turn's save) names it, and its id downloads the whole file."""
+ data = _FILES["out/hero.png"]
+ buf = io.BytesIO()
+ with tarfile.open(fileobj=buf, mode="w:gz") as tf:
+ for name, body in (("./out/hero.png", data), ("./small.png", b"s" * 40)):
+ ti = tarfile.TarInfo(name)
+ ti.size = len(body)
+ tf.addfile(ti, io.BytesIO(body))
+ raw = buf.getvalue()
+
+ async def wtar(sid):
+ return tarfile.open(fileobj=io.BytesIO(raw), mode="r:gz")
+
+ async def owned(request, sid):
+ return "org.t", {"tenant": "org.t"}
+
+ async def no_captures(sid):
+ return {}
+ monkeypatch.setattr(A, "_workspace_tar", wtar)
+ monkeypatch.setattr(A, "_owned_session", owned)
+ monkeypatch.setattr(A, "_cfile_by_name", no_captures)
+ monkeypatch.setattr(A, "_WS_FILES_CACHE", {})
+ listing = asyncio.run(A.session_workspace_files("hsess_big", None))
+ hero = next(f for f in listing["files"] if f["path"] == "out/hero.png")
+ assert hero["bytes"] == len(data)
+ resp = asyncio.run(A.container_file_content("hsess_big", hero["file_id"], None))
+ assert resp.body == data and 'filename="hero.png"' in resp.headers["content-disposition"]
+
+
+def _answer(files, text="Here are your images."):
+ tr = A._RespTranslator("resp_t", "m", None, True, 0.0, sid="hsess_big")
+ tr._handle("text", text)
+ tr.complete("completed", files)
+ return A._output_to_turn_fields(tr.output), tr
+
+
+_CARD = {"container_id": "hsess_big", "file_id": "cfile_1", "filename": "small.png", "bytes": 4}
+
+
+def test_the_answer_says_where_a_saved_file_is_and_the_attached_one_keeps_its_card():
+ big = {"filename": "out/hero.png", "bytes": int(46.1 * MB), "too_large": True, "saved": True}
+ (asst, _tools, cards), _tr = _answer([_CARD, big])
+ assert asst.endswith("out/hero.png is too large to attach here (46.1 MB); it's saved in the task's files.")
+ assert asst.startswith("Here are your images.")
+ assert [c["filename"] for c in cards] == ["small.png"]
+
+
+def test_several_files_are_named_in_one_sentence():
+ big = [{"filename": f"p{i}.png", "bytes": n * MB, "too_large": True, "saved": True} for i, n in ((1, 40), (2, 49))]
+ (asst, _t, cards), _tr = _answer(big)
+ assert asst.endswith("These files are too large to attach here; they're saved in the task's files: "
+ "p1.png (40.0 MB), p2.png (49.0 MB).")
+ assert cards == []
+
+
+def test_a_file_whose_save_did_not_land_is_not_said_to_be_saved():
+ big = {"filename": "hero.png", "bytes": 30 * MB, "too_large": True, "saved": False}
+ (asst, _t, _c), _tr = _answer([big])
+ assert asst.endswith("hero.png is too large to attach here (30.0 MB).")
+ assert "saved" not in asst
+
+
+def test_saved_only_when_the_checkpoint_landed_and_the_listing_shows_the_path():
+ files = [{"filename": "hero.png", "too_large": True}, {"filename": "node_modules/x.bin", "too_large": True},
+ {"container_id": "s", "file_id": "cfile_1", "filename": "a.png"}]
+ A._too_large_saved(files, {"checkpointed": True})
+ assert [f.get("saved") for f in files] == [True, False, None]
+ A._too_large_saved(files, {"checkpointed": False})
+ assert [f.get("saved") for f in files] == [False, False, None]
+ A._too_large_saved(files, {}) # a save skipped (stale lease, failed restore)
+ assert files[0]["saved"] is False
+
+
+def test_the_note_streams_as_text_and_is_kept_for_the_record():
+ big = {"filename": "hero.png", "bytes": 30 * MB, "too_large": True, "saved": True}
+ tr = A._RespTranslator("resp_t", "m", None, True, 0.0, sid="hsess_big")
+ tr._handle("text", "Done.")
+ evs = tr.complete("completed", [big])
+ deltas = "".join(e.get("delta", "") for e in evs if e["type"] == "response.output_text.delta")
+ assert "hero.png is too large to attach here (30.0 MB)" in deltas
+ assert tr.note_item is not None and tr.note_item in tr.output
+ assert evs[-1]["type"] == "response.completed"
+
+
+def test_no_note_when_every_file_was_attached():
+ (asst, _t, cards), tr = _answer([_CARD])
+ assert asst == "Here are your images." and len(cards) == 1 and tr.note_item is None
+
+
+class _Store:
+ """The control store an adopter needs: it is enabled, the lease is free, the cursor is at 0."""
+ @staticmethod
+ def enabled():
+ return True
+
+ async def lease_admit(self, *a, **k):
+ return {"fence": 7}
+
+ async def resp_get_cursor(self, *a, **k):
+ return 0
+
+ async def resp_set_cursor(self, *a, **k):
+ return None
+
+ async def lease_renew(self, *a, **k):
+ return None
+
+ async def lease_release(self, *a, **k):
+ return None
+
+
+def test_an_adopted_turn_says_it_too_and_keeps_it_on_the_record(monkeypatch):
+ """A gateway that adopts a turn (its owner died) settles it from the trace, which holds the
+ runner's events only: the closing paragraph must still reach the stream and the record, and only
+ after the save, since the save decides whether the file may be said to be there."""
+ polls = iter([{"done": False, "events": [], "n_total": 0}, # the probe: still running
+ {"done": True, "status": "done", "events": [], "n_total": 0}])
+
+ async def sandbox_json(path, sid, method="POST", body=None, params=None, **k):
+ return next(polls)
+
+ async def nothing(*a, **k):
+ return None
+
+ async def false(*a, **k):
+ return False
+
+ async def resp_get(rid):
+ return {"created_at": 100.0}
+
+ async def replay(*a, **k):
+ return [{"type": "message", "content": [{"type": "output_text", "text": "Made it.", "annotations": []}]}]
+ order: list[str] = []
+ published: list[dict] = []
+ big = {"filename": "hero.png", "bytes": 30 * MB, "too_large": True}
+
+ async def collect(*a, **k):
+ order.append("collect")
+ return [dict(big)]
+
+ async def checkpoint(sid, rec):
+ order.append("save")
+ rec["checkpointed"] = True
+ stored: dict = {}
+
+ async def resp_put(rid, rec, *a, **k):
+ stored.update(rec)
+ monkeypatch.setattr(A, "POOL_ENDPOINT", "http://runner")
+ monkeypatch.setattr(A, "control_store", _Store())
+ monkeypatch.setattr(A, "RESP_POLL_S", 0)
+ monkeypatch.setattr(A, "_prefix_from_vertex", lambda sid, v: "traces/hsessX")
+ monkeypatch.setattr(A, "_sandbox_json", sandbox_json)
+ monkeypatch.setattr(A, "_turn_cancelled", false)
+ monkeypatch.setattr(A, "_resp_get", resp_get)
+ monkeypatch.setattr(A, "_vertex_upsert", nothing)
+ monkeypatch.setattr(A, "_browser_close", nothing)
+ monkeypatch.setattr(A, "_trace_finalize", nothing)
+ monkeypatch.setattr(A, "_bus_publish", lambda *a: published.append(a[-1]))
+ monkeypatch.setattr(A, "_collect_produced", collect)
+ monkeypatch.setattr(A, "_checkpoint", checkpoint)
+ monkeypatch.setattr(A, "_replay_output_from_trace", replay)
+ monkeypatch.setattr(A, "_resp_put", resp_put)
+ v = {"runner_turn_id": "rt1", "running_response_id": "resp_adopt", "member_id": "m", "harness_id": "h"}
+ assert asyncio.run(A._adopt_orphan_turn("hsessX", "org.a", v)) is True
+ assert order == ["collect", "save"]
+ said = "hero.png is too large to attach here (30.0 MB); it's saved in the task's files."
+ assert any(e.get("delta") == said for e in published)
+ asst, _t, _c = A._output_to_turn_fields(stored["output"])
+ assert asst == "Made it.\n\n" + said
diff --git a/gateway/tests/test_produced_total.py b/gateway/tests/test_produced_total.py
index 7bfaf772..9ee1ec12 100644
--- a/gateway/tests/test_produced_total.py
+++ b/gateway/tests/test_produced_total.py
@@ -41,7 +41,10 @@ def test_collection_keeps_the_newest_and_counts_them_all(monkeypatch):
return _Resp(200, json.dumps({"files": listed}).encode())
if path == "/produced/ack":
return _Resp(200, b"{}")
- return _Resp(200, b"bytes", "image/jpeg") # GET /files/<path>
+ return _Resp(200, b"{}")
+
+ async def _file(s, path, cap): # GET /file, read no further than the cap
+ return 200, b"bytes", "image/jpeg", 5
async def _blob_put(key, data, kb=0):
stored[key] = data
@@ -49,6 +52,7 @@ def test_collection_keeps_the_newest_and_counts_them_all(monkeypatch):
monkeypatch.setattr(gw, "_sandbox", _sandbox)
monkeypatch.setattr(gw, "_blob_put", _blob_put)
monkeypatch.setattr(gw, "RESP_MAX_FILES", 25)
+ monkeypatch.setattr(gw, "_sandbox_file", _file)
out = asyncio.run(gw._collect_produced(sid))
names = [o["filename"] for o in out]
assert len(out) == 25 and names[0] == "observations/000029.jpg" and names[-1] == "observations/000005.jpg"
diff --git a/runner/server.py b/runner/server.py
index 5972721b..20e1ea67 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -12812,13 +12812,21 @@ def _produced_list(ws: str) -> list[dict]:
seen = {k: v for k, v in seen.items() if k in keep}
# mtime rides on each item so a reader can put the newest first: a response carries at most
# HARNESS_RESP_MAX_FILES of them, and git's path order handed a Mario run its first 24 frames
- # of 1,400 (hosted, 2026-09-25). 0 when the file is gone (a deletion) or cannot be stat'ed.
- def _mtime(rel: str) -> float:
+ # of 1,400 (hosted, 2026-09-25). size rides beside it so a reader never has to fetch a file to
+ # learn it is over its cap (the gateway's RESP_MAX_FILE_BYTES; a 49 MB image was read whole
+ # into the gateway only to be dropped, hosted 2026-10-19). Both 0 when the file is gone (a
+ # deletion) or cannot be stat'ed.
+ def _stat(rel: str) -> tuple[float, int]:
try:
- return float(os.stat(os.path.join(ws, rel)).st_mtime)
+ st = os.stat(os.path.join(ws, rel))
+ return float(st.st_mtime), int(st.st_size)
except OSError:
- return 0.0
- return [{"path": k, "status": v, "mtime": _mtime(k)} for k, v in seen.items()]
+ return 0.0, 0
+ out = []
+ for k, v in seen.items():
+ mtime, size = _stat(k)
+ out.append({"path": k, "status": v, "mtime": mtime, "size": size})
+ return out
def _produced_visible(ws: str) -> list[dict]:
diff --git a/runner/tests/test_produced_cursor.py b/runner/tests/test_produced_cursor.py
index d5d098b6..29a09b69 100644
--- a/runner/tests/test_produced_cursor.py
+++ b/runner/tests/test_produced_cursor.py
@@ -120,3 +120,14 @@ def test_a_libreoffice_profile_in_the_workspace_is_not_a_deliverable():
# a profile at the workspace root, and a folder named user/ that is not a profile, both read right
assert _without_lo_profiles(["user/registrymodifications.xcu", "user/pack/a", "out.pdf"]) == ["out.pdf"]
assert _without_lo_profiles(["user/readme.md", "out.pdf"]) == ["user/readme.md", "out.pdf"]
+
+
+def test_each_produced_item_says_how_big_it_is():
+ """The gateway reads a file over its cap from this field and never fetches it (a 49 MB image was
+ read whole into the gateway only to be dropped, hosted 2026-10-19)."""
+ d = _ws()
+ (pathlib.Path(d) / "hero.png").write_bytes(b"x" * 4096)
+ (pathlib.Path(d) / "out").mkdir()
+ (pathlib.Path(d) / "out" / "a.txt").write_text("abc")
+ by = {f["path"]: f for f in _produced_list(d)}
+ assert by["hero.png"]["size"] == 4096 and by["out/a.txt"]["size"] == 3