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): forward abort signal to oneshot provider stream
xf gongfc41131f75ef
diff --git a/cubepi/tracing/tracer.py b/cubepi/tracing/tracer.pyindex f0036ca..5bbaad4 100644--- a/cubepi/tracing/tracer.py+++ b/cubepi/tracing/tracer.py@@ -63,9 +63,14 @@ class _OneShotSession:The provider listeners wired by :meth:`Tracer.oneshot` will recorda ``chat`` child span covering this call automatically."""+ import asyncio as _asyncio+from cubepi.providers.base import (AssistantMessage as _AssistantMessage,)+ from cubepi.providers.base import (+ StreamOptions as _StreamOptions,+ )from cubepi.providers.base import (TextContent as _TextContent,)@@ -78,22 +83,36 @@ class _OneShotSession:self._run.input_messages = list(messages)self._run.system_prompt = system+ # Cancellation signal forwarded to the provider so a cancelled+ # consumer (e.g. asyncio.wait_for timeout) tears down the+ # producer task instead of leaking it past the oneshot context.+ # Mirrors the agent loop's ``StreamOptions(signal=...)`` use.+ abort_signal = _asyncio.Event()+model = self._model.model_copy(update={"max_tokens": max_output_tokens})stream = await self._provider.stream(model=model,messages=messages,system_prompt=system,+ options=_StreamOptions(signal=abort_signal),)parts: list[str] = []error_msg: str | None = None- async for evt in stream:- if evt.type == "text_delta" and evt.delta:- parts.append(evt.delta)- elif evt.type == "error":- error_msg = evt.error_message or "oneshot generation failed"- break- elif evt.type == "done":- break+ try:+ async for evt in stream:+ if evt.type == "text_delta" and evt.delta:+ parts.append(evt.delta)+ elif evt.type == "error":+ error_msg = evt.error_message or "oneshot generation failed"+ break+ elif evt.type == "done":+ break+ except BaseException:+ # On cancellation/timeout, tell the producer to stop so it+ # doesn't keep running after we exit. ``stream.result()``+ # below then surfaces the (now-completed) producer's state.+ abort_signal.set()+ raise# Wait for the producer task to finish — its ``finally`` block# invokes the response listeners (including the recorder's# ``_on_provider_response`` that closes the chat span and recordsdiff --git a/tests/tracing/test_oneshot.py b/tests/tracing/test_oneshot.pyindex 43c158f..799dd6e 100644--- a/tests/tracing/test_oneshot.py+++ b/tests/tracing/test_oneshot.py@@ -278,6 +278,59 @@ async def test_oneshot_detacher_exception_is_swallowed() -> None:assert text == "ok"+async def test_oneshot_passes_signal_to_provider_and_sets_on_cancel() -> None:+ """generate() must forward a StreamOptions.signal so a cancellation in+ the consumer tears the producer task down too."""+ import asyncio+ from unittest.mock import AsyncMock, MagicMock, patch++ from cubepi.providers.base import StreamOptions++ provider = FauxProvider()+ tracer, _ = _make_tracer()++ captured_options: dict[str, StreamOptions | None] = {"opts": None}++ async def hanging_stream():+ # Never yields, simulating a long provider call+ await asyncio.sleep(60)+ yield # pragma: no cover++ hanging = MagicMock()+ hanging.__aiter__ = lambda self: hanging_stream()++ real_stream = AsyncMock(return_value=hanging)++ async def patched_stream(**kwargs):+ captured_options["opts"] = kwargs.get("options")+ return await real_stream(**kwargs)++ async def do_work():+ async with tracer.oneshot(provider=provider, model=MODEL) as session:+ with patch.object(provider, "stream", new=patched_stream):+ await session.generate(+ system="sys",+ messages=[UserMessage(content=[TextContent(text="q")])],+ max_output_tokens=10,+ )++ task = asyncio.create_task(do_work())+ await asyncio.sleep(0.05)+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task++ await tracer.shutdown()++ # The provider received options with a signal Event…+ opts = captured_options["opts"]+ assert opts is not None+ assert opts.signal is not None+ # …and the signal was set when the consumer was cancelled.+ assert opts.signal.is_set()++@pytest.mark.asyncioasync 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