CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
fix(tracing): preserve reserved oneshot_operation key; close stream file on subscribe error
xf gong1b5b344c3001
diff --git a/cubepi/tracing/tracer.py b/cubepi/tracing/tracer.pyindex b47272c..57853ac 100644--- a/cubepi/tracing/tracer.py+++ b/cubepi/tracing/tracer.py@@ -511,13 +511,18 @@ class Tracer:CUBEPI_RUN_ID: run_id,GEN_AI_PROVIDER_NAME: "cubepi","cubepi.oneshot.operation": operation,- # Also expose operation under cubepi.metadata.* so the- # `cubepi trace ls --meta oneshot_operation=...` filter works- # (the CLI's --meta filter only reads cubepi.metadata.* attrs).- "cubepi.metadata.oneshot_operation": operation,}+ # User metadata first, then reserved keys, so a caller-supplied+ # ``oneshot_operation`` key in ``metadata`` can't shadow the one+ # derived from the ``operation`` argument (which the documented+ # ``cubepi trace ls --meta oneshot_operation=...`` filter depends+ # on).for k, v in (metadata or {}).items():root_attrs[f"cubepi.metadata.{k}"] = v+ # Also expose operation under cubepi.metadata.* so the+ # `cubepi trace ls --meta oneshot_operation=...` filter works+ # (the CLI's --meta filter only reads cubepi.metadata.* attrs).+ root_attrs["cubepi.metadata.oneshot_operation"] = operationroot_span = self._otel_tracer.start_span(name=SPAN_NAME_INVOKE_AGENT,@@ -571,12 +576,21 @@ class Tracer:)except BaseException:# Unwind any partial subscriptions before re-raising so no- # dangling listeners are left on the provider.+ # dangling listeners are left on the provider. Also close+ # the per-run stream file if one was opened — otherwise+ # this early-return path leaks the JSONL file descriptor+ # for the process lifetime.for d in detachers:try:d()except Exception:pass+ if run.stream_file is not None:+ try:+ run.stream_file.close()+ except Exception:+ pass+ run.stream_file = Noneroot_span.end()raisediff --git a/tests/tracing/test_oneshot.py b/tests/tracing/test_oneshot.pyindex 2d0f52c..be33690 100644--- a/tests/tracing/test_oneshot.py+++ b/tests/tracing/test_oneshot.py@@ -137,6 +137,37 @@ async def test_oneshot_metadata_on_root_span() -> None:assert attrs["cubepi.metadata.conversation_id"] == "conv-abc"+async def test_oneshot_user_metadata_cannot_shadow_reserved_oneshot_operation() -> None:+ """If a caller's metadata dict includes 'oneshot_operation', the value+ derived from the operation argument must still win — the documented+ `cubepi trace ls --meta oneshot_operation=<op>` filter depends on it."""+ provider = FauxProvider()+ provider.append_responses([faux_assistant_message("ok")])+ tracer, exporter = _make_tracer()++ async with tracer.oneshot(+ provider=provider,+ model=MODEL,+ operation="real_op",+ metadata={"oneshot_operation": "user_supplied_value"},+ ) as session:+ await session.generate(+ system="sys",+ messages=[UserMessage(content=[TextContent(text="q")])],+ max_output_tokens=10,+ )++ await tracer.force_flush()+ await tracer.shutdown()++ roots = [s for s in exporter.spans if s.name == "invoke_agent"]+ assert len(roots) == 1+ attrs = dict(roots[0].attributes or {})+ assert attrs["cubepi.metadata.oneshot_operation"] == "real_op"+ assert attrs["cubepi.oneshot.operation"] == "real_op"++@pytest.mark.asyncioasync def test_oneshot_no_metadata_ok() -> None:provider = FauxProvider()@@ -234,6 +265,44 @@ async def test_oneshot_generate_error_event_raises_and_marks_root() -> None:assert attrs.get("error.type") == "RuntimeError"+async def test_oneshot_subscribe_failure_closes_stream_file(tmp_path) -> None: # type: ignore[no-untyped-def]+ """A subscription failure on the pre-yield path must close any per-run+ stream file that was already opened, so record_stream mode doesn't leak+ file descriptors on this error path."""+ from unittest.mock import patch++ exporter = InMemoryExporter()+ tracer = Tracer(+ exporters=[exporter],+ record_stream=True,+ stream_dir=str(tmp_path),+ atexit_flush=False,+ )++ provider = FauxProvider()++ with patch.object(+ provider, "subscribe_chunk", side_effect=RuntimeError("chunk sub failed")+ ):+ with pytest.raises(RuntimeError, match="chunk sub failed"):+ async with tracer.oneshot(provider=provider, model=MODEL):+ pass # pragma: no cover++ await tracer.shutdown()++ # File was created and then closed; it should be a closed handle, not+ # a leaked open one. We can't directly inspect FD state, but writing+ # via run.stream_file would have failed; instead assert the file+ # exists and is empty/parseable (no events written before failure).+ stream_files = list(tmp_path.glob("*.stream.jsonl"))+ assert len(stream_files) == 1+ # File must be closed and finite-size (no leak symptom: pending writes+ # buffered indefinitely or unable-to-stat). On Linux this is a basic+ # sanity check.+ assert stream_files[0].stat().st_size == 0++@pytest.mark.asyncioasync def test_oneshot_propagates_silent_producer_failure() -> None:"""If the producer task fails AFTER emitting done (without an explicit