Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

fix(tracing): open and close per-run stream file for oneshot when record_stream=True

xf gongc1f382425d78
diff --git a/cubepi/tracing/tracer.py b/cubepi/tracing/tracer.py
index a931074..f0036ca 100644
--- a/cubepi/tracing/tracer.py
+++ b/cubepi/tracing/tracer.py
@@ -520,6 +520,21 @@ class Tracer:
)
recorder._run = run
+ # Open the per-run stream file when record_stream is enabled, so
+ # ``_on_provider_chunk`` writes ``<run_id>.stream.jsonl`` for the
+ # oneshot the same way the agent path does. Closed in the finally
+ # block below.
+ if self._record_stream and self._stream_dir is not None:
+ try:
+ import time as _time
+
+ self._stream_dir.mkdir(parents=True, exist_ok=True)
+ stream_path = self._stream_dir / f"{run_id}.stream.jsonl"
+ run.stream_file = stream_path.open("w", encoding="utf-8")
+ run.stream_start_time = _time.time()
+ except Exception:
+ pass
+
detachers: list[Callable[[], None]] = []
if isinstance(provider, _BaseProvider):
try:
@@ -606,6 +621,14 @@ class Tracer:
)
except Exception:
pass
+ # Close the stream file opened above (mirrors the agent
+ # _on_agent_end / _close_open_spans path).
+ if run.stream_file is not None:
+ try:
+ run.stream_file.close()
+ except Exception:
+ pass
+ run.stream_file = None
recorder._run = None
root_span.end()
# Flush synchronously so the trace is visible after the block.
diff --git a/tests/tracing/test_oneshot.py b/tests/tracing/test_oneshot.py
index 60bf3ea..43c158f 100644
--- a/tests/tracing/test_oneshot.py
+++ b/tests/tracing/test_oneshot.py
@@ -278,6 +278,42 @@ async def test_oneshot_detacher_exception_is_swallowed() -> None:
assert text == "ok"
+async def test_oneshot_record_stream_writes_jsonl(tmp_path) -> None: # type: ignore[no-untyped-def]
+ """When record_stream is on, oneshot must open a per-run stream.jsonl
+ so _on_provider_chunk can write the same per-chunk log as the agent path."""
+ exporter = InMemoryExporter()
+ tracer = Tracer(
+ exporters=[exporter],
+ record_stream=True,
+ stream_dir=str(tmp_path),
+ atexit_flush=False,
+ )
+
+ provider = FauxProvider()
+ provider.append_responses([faux_assistant_message("streamed text")])
+
+ async with tracer.oneshot(provider=provider, model=MODEL) as session:
+ text = await session.generate(
+ system="sys",
+ messages=[UserMessage(content=[TextContent(text="hi")])],
+ max_output_tokens=20,
+ )
+
+ await tracer.shutdown()
+
+ assert text == "streamed text"
+ stream_files = list(tmp_path.glob("*.stream.jsonl"))
+ assert len(stream_files) == 1, f"expected one stream file, got {stream_files}"
+ content = stream_files[0].read_text(encoding="utf-8").strip()
+ assert content, "stream file should have at least one event"
+ # The file should be one JSON object per line — sanity-check parse
+ import json
+
+ for line in content.splitlines():
+ json.loads(line)
+
+
@pytest.mark.asyncio
async def test_oneshot_partial_subscribe_failure_unwinds_listeners() -> None:
"""If subscribe_chunk raises after subscribe_request succeeded, the first