Skip to content

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

test(tracing): cover mid-stream cancel and mark defensive paths no-cover

xf gong707f95b3cf58
diff --git a/cubepi/tracing/tracer.py b/cubepi/tracing/tracer.py
index 57853ac..483f0d0 100644
--- a/cubepi/tracing/tracer.py
+++ b/cubepi/tracing/tracer.py
@@ -561,7 +561,9 @@ class Tracer:
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:
+ except (
+ Exception
+ ): # pragma: no cover — defensive: tracing must never break the caller
pass
detachers: list[Callable[[], None]] = []
@@ -583,12 +585,12 @@ class Tracer:
for d in detachers:
try:
d()
- except Exception:
+ except Exception: # pragma: no cover — defensive
pass
if run.stream_file is not None:
try:
run.stream_file.close()
- except Exception:
+ except Exception: # pragma: no cover — defensive
pass
run.stream_file = None
root_span.end()
@@ -620,7 +622,7 @@ class Tracer:
root_span.set_status(Status(StatusCode.ERROR, str(_exc)[:256]))
root_span.set_attribute(ERROR_TYPE, type(_exc).__name__)
root_span.record_exception(_exc)
- except Exception:
+ except Exception: # pragma: no cover — defensive
pass
raise
finally:
@@ -628,7 +630,7 @@ class Tracer:
for d in detachers:
try:
d()
- except Exception:
+ except Exception: # pragma: no cover — defensive
pass
# Close any chat span left open by a cancelled/timed-out stream.
# We don't reuse Recorder._close_open_spans because that helper
@@ -643,7 +645,7 @@ class Tracer:
run.chat_span.set_attribute(CUBEPI_ABORTED, True)
run.chat_span.set_attribute(ERROR_TYPE, "cubepi.aborted")
run.chat_span.end()
- except Exception:
+ except Exception: # pragma: no cover — defensive
pass
run.chat_span = None
# Stamp content on the root invoke_agent span. The agent path
@@ -681,14 +683,14 @@ class Tracer:
GEN_AI_OUTPUT_MESSAGES,
messages_to_semconv(run.output_messages),
)
- except Exception:
+ except Exception: # pragma: no cover — defensive
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:
+ except Exception: # pragma: no cover — defensive
pass
run.stream_file = None
recorder._run = None
@@ -699,7 +701,7 @@ class Tracer:
# asyncio.run() can exit before the BatchSpanProcessor drains.
try:
await self.force_flush(timeout_seconds=5.0)
- except Exception:
+ except Exception: # pragma: no cover — defensive
pass
async def __aenter__(self) -> "Tracer":
diff --git a/tests/tracing/test_oneshot.py b/tests/tracing/test_oneshot.py
index be33690..7329153 100644
--- a/tests/tracing/test_oneshot.py
+++ b/tests/tracing/test_oneshot.py
@@ -580,6 +580,44 @@ async def test_oneshot_cancelled_generate_closes_chat_span() -> None:
assert attrs.get("error.type") == "cubepi.aborted"
+async def test_oneshot_cancel_mid_stream_marks_open_chat_span_aborted() -> None:
+ """When cancellation happens after the chat span has been opened by the
+ provider request listener but before the response listener has closed
+ it, the oneshot cleanup must close it and stamp cubepi.aborted."""
+ import asyncio
+
+ # Slow provider: streams the response one token at a time so we can
+ # cancel mid-stream (after _on_provider_request has fired).
+ provider = FauxProvider(tokens_per_second=5.0)
+ provider.append_responses([faux_assistant_message("a b c d e f g h")])
+ tracer, exporter = _make_tracer()
+
+ async def do_work():
+ async with tracer.oneshot(provider=provider, model=MODEL) as session:
+ await session.generate(
+ system="sys",
+ messages=[UserMessage(content=[TextContent(text="q")])],
+ max_output_tokens=50,
+ )
+
+ task = asyncio.create_task(do_work())
+ await asyncio.sleep(0.15) # let chunks start, chat span opens
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ await tracer.force_flush()
+ await tracer.shutdown()
+
+ # Chat span must have been ended with cubepi.aborted=true
+ chat_spans = [s for s in exporter.spans if s.name.startswith("chat ")]
+ assert chat_spans, "expected at least one chat span (opened by request listener)"
+ chat_attrs = dict(chat_spans[0].attributes or {})
+ assert chat_attrs.get("cubepi.aborted") is True
+ assert chat_attrs.get("error.type") == "cubepi.aborted"
+
+
@pytest.mark.asyncio
async def test_oneshot_does_not_interfere_with_concurrent_agent() -> None:
"""Oneshot's active-run gate must not bleed into a concurrent Agent run."""