diff --git a/CHANGELOG.md b/CHANGELOG.md index b308d81..101074d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,15 @@ under Unreleased and move into a version section at release time. ## Unreleased +### Fixed + +- Streaming wrappers now finalize once across exhaustion, explicit closure, + cancellation, and iterator errors. Early closure/cancellation records an + unsuccessful inference with partial metadata when available. TTFT ignores + lifecycle/role-only chunks; telemetry callbacks cannot break iteration and + retain the trace context captured at stream creation. Remote API streams + ending without their completion marker record `STREAM_INCOMPLETE`. + ### Added - OpenAI sync and async `embeddings.create()` instrumentation records latency, diff --git a/README.md b/README.md index e2687a9..81ac433 100644 --- a/README.md +++ b/README.md @@ -172,6 +172,7 @@ Report security and privacy issues to: support@wildedge.dev - [Manual tracking](https://github.com/wild-edge/wildedge-python/blob/main/docs/manual-tracking.md) - [LLM API tracking](https://github.com/wild-edge/wildedge-python/blob/main/docs/llm_api.md) - [Compatibility Matrix](https://github.com/wild-edge/wildedge-python/blob/main/docs/compatibility.md) +- [Streaming lifecycle](docs/streaming.md) - [Changelog](https://github.com/wild-edge/wildedge-python/blob/main/CHANGELOG.md) - [License](https://github.com/wild-edge/wildedge-python/blob/main/LICENSE) diff --git a/docs/providers.md b/docs/providers.md index 14e72e1..2adb279 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -76,12 +76,15 @@ are recorded as unsuccessful. No prompt or response text is uploaded by this adapter. String input and simple user messages provide text input metadata; input iterators are passed through without being consumed by instrumentation. +See [Streaming lifecycle](streaming.md) for completion, closure, cancellation, +and coverage limits. + For streams, consume the iterator to exhaustion to record the terminal response and its usage. Time to first output ignores lifecycle events and measures the first nonempty text, refusal, function argument, or audio delta. Streams without -a terminal response do not produce a successful inference event. Early closure, -cancellation, background response polling, and individual tool spans are outside -this initial coverage. API exceptions retain their original behavior and use +a terminal response record an unsuccessful inference. Explicit early closure and +async cancellation are tracked; background response polling and individual tool +spans remain outside coverage. API exceptions retain their original behavior and use the same error tracking as Chat Completions. OpenAI-compatible hosts must implement the Responses endpoint to use this path. diff --git a/docs/streaming.md b/docs/streaming.md new file mode 100644 index 0000000..0891535 --- /dev/null +++ b/docs/streaming.md @@ -0,0 +1,60 @@ +# Streaming lifecycle and coverage + +The shared wrappers track OpenAI Chat Completions and Responses +`create(stream=True)`, Anthropic `messages.create(stream=True)` (sync and async), +and llama-cpp-python/GGUF completion iterators (sync). + +| Outcome | Telemetry | +|---|---| +| Iterator exhausted | One inference event; remote APIs require their completion marker | +| Explicit `close()` / `aclose()` or early context exit | One unsuccessful inference with `STREAM_CLOSED`, unless already finalized | +| Async cancellation while awaiting a chunk or exiting its context | One unsuccessful inference with `STREAM_CANCELLED`; cancellation is re-raised | +| Provider/iterator exception | One error event using existing error classification; original exception is re-raised | +| Remote API EOF without completion marker | One unsuccessful inference with `STREAM_INCOMPLETE` | + +Repeated exhaustion and closing after finalization do not emit another outcome. +Partial usage is retained when supplied by the provider, but missing totals are +not estimated. Responses interrupted before a terminal response has no final +usage; first-output timing is retained when available. Telemetry callback failures +are logged at debug level and do not break application iteration. + +TTFT measures from the original call until the first nonempty output delta, +ignoring role-only chunks, usage chunks, and message/response lifecycle events. +Output can be text, refusal, tool arguments, or supported audio/reasoning deltas; +it need not be user-visible text. No output means TTFT is omitted. Callbacks use +the trace context captured when the stream wrapper was created, even when the +application consumes it later under another context. + +Use a context manager or explicitly close the stream when stopping early: + +```python +with client.chat.completions.create(model=model, messages=messages, stream=True) as stream: + for chunk in stream: + if enough_output(chunk): + break +``` + +Async streams support `async with`, `await stream.close()`, and +`await stream.aclose()`. A bare `break` without closing, or simply abandoning an +unconsumed stream, does not provide an observable end of the operation. There is +no garbage-collection finalizer. Keep stream consumption within the lifetime of +the SDK client and do not consume one iterator concurrently from multiple tasks. + +## Audit findings outside these wrappers + +- Anthropic's `messages.stream()` helper calls its transport directly and bypasses + the currently instrumented `messages.create()`. Use `create(stream=True)` for + the coverage above. Adding native helper support needs its own instrumentation + for `text_stream` and `get_final_message()`. +- Provider convenience properties/methods that consume an underlying stream + directly can bypass iteration on the wrapper. They are not covered by the + lifecycle contract above; use the wrapped event iterator. +- MLX instruments `mlx_lm.generate()` and model calls, not + `mlx_lm.stream_generate()`. Streaming generation requires a dedicated adapter + and suppression of nested token-loop model calls. +- Transformers instruments pipeline/model calls; user-supplied streamers and + background generation threads are not wrapped stream iterators. +- `wildedge.llm_api()` is a manual context manager: its lifetime is controlled by + the caller, and the caller must supply usage and first-output marks. + +The audit does not claim coverage for streaming APIs that are not instrumented. diff --git a/tests/compat/test_anthropic_compat.py b/tests/compat/test_anthropic_compat.py index 93a7566..3e1b39c 100644 --- a/tests/compat/test_anthropic_compat.py +++ b/tests/compat/test_anthropic_compat.py @@ -1,6 +1,9 @@ from __future__ import annotations +import json + import anthropic +import pytest from conftest import sdk_http_module httpx = sdk_http_module("anthropic") @@ -70,3 +73,75 @@ def test_api_error_is_tracked(compat_client): error = compat_client.one("error") assert error["error"]["http_status"] == 529 assert error["error"]["provider_error_code"] == "overloaded_error" + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("early_close", [False, True]) +@pytest.mark.parametrize("truncated", [False, True]) +async def test_stream_lifecycle(compat_client, asynchronous, early_close, truncated): + compat_client.instrument("anthropic") + events = [ + { + "type": "message_start", + "message": { + **MESSAGE, + "content": [], + "stop_reason": None, + "usage": {"input_tokens": 12, "output_tokens": 0}, + }, + }, + { + "type": "content_block_delta", + "index": 0, + "delta": {"type": "text_delta", "text": "Hello"}, + }, + { + "type": "message_delta", + "delta": {"stop_reason": "end_turn", "stop_sequence": None}, + "usage": {"output_tokens": 3}, + }, + {"type": "message_stop"}, + ] + if truncated: + events = events[:-1] + body = "".join(f"event: {e['type']}\ndata: {json.dumps(e)}\n\n" for e in events) + + def handler(request): + return httpx.Response( + 200, text=body, headers={"content-type": "text/event-stream"} + ) + + if asynchronous: + async with anthropic.AsyncAnthropic( + api_key="sk-ant-compat", + http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)), + ) as client: + async with await client.messages.create( + model="claude-haiku-4-5", max_tokens=32, messages=[], stream=True + ) as stream: + if early_close: + await anext(stream) + else: + assert len([event async for event in stream]) == len(events) + await stream.close() + else: + with _client(handler) as client: + with client.messages.create( + model="claude-haiku-4-5", max_tokens=32, messages=[], stream=True + ) as stream: + if early_close: + next(stream) + else: + assert len(list(stream)) == len(events) + stream.close() + inference = compat_client.one("inference")["inference"] + assert inference["success"] == (not early_close and not truncated) + assert inference["output_meta"]["tokens_in"] == 12 + if early_close: + assert inference["error_code"] == "STREAM_CLOSED" + assert inference["output_meta"].get("time_to_first_token_ms") is None + else: + if truncated: + assert inference["error_code"] == "STREAM_INCOMPLETE" + assert inference["output_meta"]["tokens_out"] == 3 + assert inference["output_meta"]["time_to_first_token_ms"] is not None diff --git a/tests/compat/test_openai_compat.py b/tests/compat/test_openai_compat.py index 587b482..6e26539 100644 --- a/tests/compat/test_openai_compat.py +++ b/tests/compat/test_openai_compat.py @@ -320,3 +320,43 @@ def handler(request): } assert inference["api_meta"]["resolved_model_id"] == "text-embedding-3-small" assert "embedding" not in inference["output_meta"] + + +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_early_stream_close_is_tracked_once(compat_client, asynchronous): + compat_client.instrument("openai") + chunk = { + "id": "c", + "object": "chat.completion.chunk", + "created": 1, + "model": "gpt-4o-mini", + "choices": [{"index": 0, "delta": {"content": "Hi"}}], + } + body = f"data: {json.dumps(chunk)}\n\ndata: [DONE]\n\n" + + def handler(request): + return httpx.Response( + 200, text=body, headers={"content-type": "text/event-stream"} + ) + + if asynchronous: + async with openai.AsyncOpenAI( + api_key="sk-compat", + http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)), + ) as client: + async with await client.chat.completions.create( + model="gpt-4o-mini", messages=[], stream=True + ) as stream: + assert (await anext(stream)).choices[0].delta.content == "Hi" + await stream.close() + else: + with _client(handler) as client: + with client.chat.completions.create( + model="gpt-4o-mini", messages=[], stream=True + ) as stream: + assert next(stream).choices[0].delta.content == "Hi" + stream.close() + inference = compat_client.one("inference")["inference"] + assert inference["success"] is False + assert inference["error_code"] == "STREAM_CLOSED" + assert inference["output_meta"]["time_to_first_token_ms"] is not None diff --git a/tests/test_integrations_anthropic.py b/tests/test_integrations_anthropic.py index 68964b1..43f438f 100644 --- a/tests/test_integrations_anthropic.py +++ b/tests/test_integrations_anthropic.py @@ -426,6 +426,7 @@ def test_streaming_records_inference_on_exhaustion(self): ), make_content_block_delta_event("Hello world"), make_message_delta_event(output_tokens=20, stop_reason="end_turn"), + SimpleNamespace(type="message_stop"), ] messages = FakeStreamingMessages(events) client = make_fake_client() @@ -449,6 +450,7 @@ def test_streaming_captures_token_counts_from_events(self): events = [ make_message_start_event(input_tokens=8, cached=2), make_message_delta_event(output_tokens=15, stop_reason="end_turn"), + SimpleNamespace(type="message_stop"), ] messages = FakeStreamingMessages(events) client = make_fake_client() @@ -555,6 +557,7 @@ async def test_streaming_records_inference_on_exhaustion(self): make_message_start_event(input_tokens=10, model="claude-opus-4-6-20251101"), make_content_block_delta_event("Hello world"), make_message_delta_event(output_tokens=20, stop_reason="end_turn"), + SimpleNamespace(type="message_stop"), ] messages = FakeAsyncStreamingMessages(events) client = make_fake_client() diff --git a/tests/test_integrations_openai_responses.py b/tests/test_integrations_openai_responses.py index 3d43655..19c48d8 100644 --- a/tests/test_integrations_openai_responses.py +++ b/tests/test_integrations_openai_responses.py @@ -134,7 +134,10 @@ def test_unfinished_and_error_streams(): on_chunk, on_done = make_responses_stream_callbacks(handle, [], 0) on_chunk(SimpleNamespace(type="response.created")) on_done(100, 1) - handle.track_inference.assert_not_called() + handle.track_inference.assert_called_once() + assert handle.track_inference.call_args.kwargs["error_code"] == "STREAM_INCOMPLETE" + handle = MagicMock() + on_chunk, on_done = make_responses_stream_callbacks(handle, [], 0) on_chunk(SimpleNamespace(type="error", code="server_error")) on_done(100, 1) handle.track_error.assert_called_once() diff --git a/tests/test_streaming_lifecycle.py b/tests/test_streaming_lifecycle.py new file mode 100644 index 0000000..dd03fbd --- /dev/null +++ b/tests/test_streaming_lifecycle.py @@ -0,0 +1,268 @@ +from __future__ import annotations + +import asyncio +import time +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest + +from wildedge.integrations.anthropic import make_anthropic_stream_callbacks +from wildedge.integrations.common import ( + AsyncStreamWrapper, + SyncStreamWrapper, + stream_chunk_has_output, +) +from wildedge.integrations.gguf import make_gguf_stream_callbacks +from wildedge.integrations.openai import ( + make_openai_stream_callbacks, + make_responses_stream_callbacks, +) +from wildedge.tracing import get_trace_context, trace_context + + +def wrapper(original, on_chunk=None, on_done=None): + handle = MagicMock() + done = on_done or MagicMock() + return ( + SyncStreamWrapper(original, handle, time.perf_counter(), on_chunk, done), + handle, + done, + ) + + +def test_single_pass_completion_and_close(): + stream, handle, done = wrapper(iter([1, 2])) + assert next(stream) == 1 + assert list(stream) == [2] + assert list(stream) == [] + stream.close() + done.assert_called_once() + handle.track_error.assert_not_called() + + +def test_explicit_close_and_context_exit(): + original = MagicMock() + original.__iter__.return_value = iter([1, 2]) + stream, _, done = wrapper(original) + with stream: + assert next(stream) == 1 + original.__exit__.assert_called_once() + stream.close() + done.assert_called_once() + assert done.call_args.kwargs == {"outcome": "closed"} + + +def test_midstream_error_preserved_once(): + error = TimeoutError("broken stream") + + def chunks(): + yield 1 + raise error + + stream, handle, done = wrapper(chunks()) + assert next(stream) == 1 + with pytest.raises(TimeoutError) as caught: + next(stream) + assert caught.value is error + stream.close() + handle.track_error.assert_called_once() + done.assert_not_called() + + +def test_callback_failures_do_not_break_iteration(): + stream, handle, _ = wrapper( + iter([1, 2]), + MagicMock(side_effect=ValueError()), + MagicMock(side_effect=ValueError()), + ) + assert list(stream) == [1, 2] + handle.track_error.assert_not_called() + + +def test_correlation_uses_creation_context(): + seen = [] + with trace_context(trace_id="origin"): + stream, _, _ = wrapper( + iter([1]), on_done=lambda *_: seen.append(get_trace_context().trace_id) + ) + with trace_context(trace_id="consumer"): + list(stream) + assert seen == ["origin"] + + +class AsyncChunks: + def __init__(self, items, error=None): + self.items = iter(items) + self.error = error + self.closed = False + + def __aiter__(self): + return self + + async def __anext__(self): + try: + return next(self.items) + except StopIteration: + if self.error is not None: + raise self.error from None + raise StopAsyncIteration from None + + async def aclose(self): + self.closed = True + + +@pytest.mark.parametrize( + "error", [None, TimeoutError("timeout"), asyncio.CancelledError()] +) +async def test_async_lifecycle(error): + original = AsyncChunks([1], error) + handle, done = MagicMock(), MagicMock() + stream = AsyncStreamWrapper(original, handle, time.perf_counter(), None, done) + assert await anext(stream) == 1 + if error is None: + assert [item async for item in stream] == [] + done.assert_called_once() + else: + with pytest.raises(type(error)) as caught: + await anext(stream) + assert caught.value is error + if isinstance(error, asyncio.CancelledError): + assert done.call_args.kwargs == {"outcome": "cancelled"} + else: + handle.track_error.assert_called_once() + done.assert_not_called() + await stream.aclose() + assert original.closed + assert [item async for item in stream] == [] + assert done.call_count + handle.track_error.call_count == 1 + + +async def test_async_context_early_exit(): + original = AsyncChunks([1, 2]) + done = MagicMock() + stream = AsyncStreamWrapper(original, MagicMock(), time.perf_counter(), None, done) + async with stream: + assert await anext(stream) == 1 + assert original.closed + assert done.call_args.kwargs == {"outcome": "closed"} + + +@pytest.mark.parametrize( + "factory", + [ + lambda h: make_openai_stream_callbacks(h, []), + lambda h: make_anthropic_stream_callbacks(h, []), + lambda h: make_gguf_stream_callbacks(h, "hello"), + lambda h: make_responses_stream_callbacks(h, [], time.perf_counter()), + ], +) +@pytest.mark.parametrize("outcome", ["closed", "cancelled"]) +def test_all_integrations_record_interruption(factory, outcome): + handle = MagicMock() + _, on_done = factory(handle) + on_done(100, None, outcome=outcome) + handle.track_inference.assert_called_once() + event = handle.track_inference.call_args.kwargs + assert event["success"] is False + assert event["error_code"] == "STREAM_" + outcome.upper() + + +@pytest.mark.parametrize( + ("chunk", "expected"), + [ + ({"choices": [{"delta": {"role": "assistant"}}]}, False), + ({"choices": [], "usage": {}}, False), + ({"choices": [{"delta": {"content": "hello"}}]}, True), + ({"choices": [{"text": "hello"}]}, True), + (SimpleNamespace(type="message_start"), False), + ( + SimpleNamespace( + type="content_block_delta", delta=SimpleNamespace(text="hello") + ), + True, + ), + (SimpleNamespace(type="response.created"), False), + ], +) +def test_first_output_detection(chunk, expected): + assert stream_chunk_has_output(chunk) is expected + + +async def test_task_cancellation_while_waiting(): + entered = asyncio.Event() + + async def chunks(): + entered.set() + await asyncio.Event().wait() + yield 1 + + handle, done = MagicMock(), MagicMock() + stream = AsyncStreamWrapper(chunks(), handle, time.perf_counter(), None, done) + task = asyncio.create_task(anext(stream)) + await entered.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + await stream.aclose() + done.assert_called_once() + assert done.call_args.kwargs == {"outcome": "cancelled"} + handle.track_error.assert_not_called() + + +def test_ttft_waits_for_output(monkeypatch): + clock = [1] + monkeypatch.setattr("wildedge.integrations.common.elapsed_ms", lambda _: clock[0]) + chunks = iter( + [ + {"choices": [{"delta": {"role": "assistant"}}]}, + {"choices": [{"delta": {"content": "hello"}}]}, + ] + ) + stream, _, done = wrapper(chunks) + next(stream) + clock[0] = 42 + next(stream) + clock[0] = 100 + list(stream) + assert done.call_args.args == (100, 42) + + +def test_underlying_close_error_is_preserved(): + original = MagicMock() + original.close.side_effect = ValueError("close failed") + stream, _, done = wrapper(original) + with pytest.raises(ValueError, match="close failed"): + stream.close() + done.assert_called_once() + assert done.call_args.kwargs == {"outcome": "closed"} + + +async def test_async_telemetry_and_context(): + seen = [] + with trace_context(trace_id="origin"): + stream = AsyncStreamWrapper( + AsyncChunks([1]), + MagicMock(), + time.perf_counter(), + MagicMock(side_effect=ValueError()), + lambda *_: seen.append(get_trace_context().trace_id), + ) + with trace_context(trace_id="consumer"): + assert [item async for item in stream] == [1] + assert seen == ["origin"] + + +@pytest.mark.parametrize( + "factory", [make_openai_stream_callbacks, make_anthropic_stream_callbacks] +) +def test_remote_eof_without_completion_is_incomplete(factory): + handle = MagicMock() + callbacks = factory(handle, []) + stream = SyncStreamWrapper(iter([]), handle, time.perf_counter(), *callbacks) + list(stream) + stream.close() + handle.track_inference.assert_called_once() + event = handle.track_inference.call_args.kwargs + assert event["success"] is False + assert event["error_code"] == "STREAM_INCOMPLETE" diff --git a/wildedge/integrations/anthropic.py b/wildedge/integrations/anthropic.py index 4544802..d39d55a 100644 --- a/wildedge/integrations/anthropic.py +++ b/wildedge/integrations/anthropic.py @@ -152,10 +152,20 @@ def make_anthropic_stream_callbacks( cached_tokens: list[int | None] = [None] stop_reason: list[str | None] = [None] resolved_model: list[str | None] = [None] + message_stopped = False def on_chunk(event: object) -> None: + nonlocal message_stopped event_type = type(event).__name__ - if event_type == "RawMessageStartEvent": + if ( + getattr(event, "type", None) == "message_stop" + or event_type == "RawMessageStopEvent" + ): + message_stopped = True + if ( + event_type == "RawMessageStartEvent" + or getattr(event, "type", None) == "message_start" + ): msg = getattr(event, "message", None) if msg is not None: usage = getattr(msg, "usage", None) @@ -163,7 +173,10 @@ def on_chunk(event: object) -> None: tokens_in[0] = getattr(usage, "input_tokens", None) cached_tokens[0] = getattr(usage, "cache_read_input_tokens", None) resolved_model[0] = getattr(msg, "model", None) - elif event_type == "RawMessageDeltaEvent": + elif ( + event_type == "RawMessageDeltaEvent" + or getattr(event, "type", None) == "message_delta" + ): usage = getattr(event, "usage", None) if usage is not None: tokens_out[0] = getattr(usage, "output_tokens", None) @@ -173,7 +186,11 @@ def on_chunk(event: object) -> None: if reason: stop_reason[0] = reason - def on_done(duration_ms: int, ttft_ms: int | None) -> None: + def on_done( + duration_ms: int, ttft_ms: int | None, *, outcome: str = "completed" + ) -> None: + if outcome == "completed" and not message_stopped: + outcome = "incomplete" ti, to, cr, sr = tokens_in[0], tokens_out[0], cached_tokens[0], stop_reason[0] tps = round(to / duration_ms * 1000, 1) if duration_ms > 0 and to else None api_meta = ( @@ -183,7 +200,8 @@ def on_done(duration_ms: int, ttft_ms: int | None) -> None: duration_ms=duration_ms, input_modality="text", output_modality="generation", - success=True, + success=outcome == "completed", + error_code=None if outcome == "completed" else "STREAM_" + outcome.upper(), input_meta=build_input_meta(messages, ti), output_meta=GenerationOutputMeta( task="generation", diff --git a/wildedge/integrations/common.py b/wildedge/integrations/common.py index bd8f523..685bce8 100644 --- a/wildedge/integrations/common.py +++ b/wildedge/integrations/common.py @@ -2,6 +2,8 @@ from __future__ import annotations +import asyncio +import contextvars import itertools from collections.abc import Callable from typing import TYPE_CHECKING, Any @@ -268,105 +270,232 @@ def num_classes_from_output_shape(shape: tuple) -> int: # --------------------------------------------------------------------------- # Each integration provides: # on_chunk(chunk) -> None : update mutable state from a single chunk -# on_done(duration_ms, ttft_ms) : record inference once the stream is exhausted +# on_done(duration_ms, ttft_ms, *, outcome="completed") : record one outcome # # The wrappers handle TTFT capture, error tracking, context-manager delegation, # and attribute proxying so callers get a drop-in replacement for the raw stream. -class SyncStreamWrapper: - """Wraps a sync iterable stream to capture TTFT and record inference on exhaustion.""" +def stream_chunk_has_output(chunk: object) -> bool: + """Ignore role, usage, and lifecycle chunks when measuring first output.""" + + def field(value: object, name: str) -> Any: + return ( + value.get(name) if isinstance(value, dict) else getattr(value, name, None) + ) + + choices = field(chunk, "choices") + if choices is not None: + for choice in choices: + delta = field(choice, "delta") + if field(choice, "text") or any( + field(delta, key) + for key in ("content", "refusal", "tool_calls", "function_call") + ): + return True + return False + event_type = field(chunk, "type") + if event_type is not None: + if event_type == "content_block_delta": + delta = field(chunk, "delta") + return any( + field(delta, key) + for key in ("text", "thinking", "partial_json", "data") + ) + return event_type in ( + "response.output_text.delta", + "response.refusal.delta", + "response.function_call_arguments.delta", + "response.output_audio.delta", + ) and bool(field(chunk, "delta")) + return True + + +class StreamState: + """One lifecycle per stream, with telemetry isolated from application code.""" def __init__( self, - original: object, handle: ModelHandle, t0: float, on_chunk: Callable[[object], None] | None, - on_done: Callable[[int, int | None], None], + on_done: Callable[..., None], ) -> None: - self._original = original self._handle = handle self._t0 = t0 self._on_chunk = on_chunk self._on_done = on_done + self._finished = False + self._ttft_ms = None + self._context = contextvars.copy_context() + + def _safe(self, callback: Callable, *args: Any, **kwargs: Any) -> Any: + try: + return self._context.run(callback, *args, **kwargs) + except Exception as exc: + debug_failure("stream", "telemetry callback", exc) + return None + + def _chunk(self, chunk: object) -> None: + if self._ttft_ms is None and self._safe(stream_chunk_has_output, chunk): + self._ttft_ms = elapsed_ms(self._t0) + if self._on_chunk is not None: + self._safe(self._on_chunk, chunk) + + def _finish(self, outcome: str = "completed") -> None: + if self._finished: + return + self._finished = True + if outcome == "completed": + self._safe(self._on_done, elapsed_ms(self._t0), self._ttft_ms) + else: + self._safe( + self._on_done, elapsed_ms(self._t0), self._ttft_ms, outcome=outcome + ) - def __iter__(self): - return self._track() + def _error(self, exc: Exception) -> None: + if not self._finished: + self._finished = True + self._safe(track_api_error, self._handle, exc, elapsed_ms(self._t0)) - def _track(self): - ttft_ms: int | None = None + +class SyncStreamWrapper(StreamState): + """A single-pass iterator tracking exhaustion, failure, and explicit closure.""" + + def __init__( + self, + original: Any, + handle: ModelHandle, + t0: float, + on_chunk: Callable[[object], None] | None, + on_done: Callable[..., None], + ) -> None: + super().__init__(handle, t0, on_chunk, on_done) + self._original = original + self._iterator = None + + def __iter__(self) -> SyncStreamWrapper: + return self + + def __next__(self) -> Any: + if self._finished: + raise StopIteration try: - for chunk in self._original: # type: ignore[union-attr] - if ttft_ms is None: - ttft_ms = elapsed_ms(self._t0) - if self._on_chunk is not None: - self._on_chunk(chunk) - yield chunk + if self._iterator is None: + self._iterator = iter(self._original) + chunk = next(self._iterator) + except StopIteration: + self._finish() + raise except Exception as exc: - track_api_error(self._handle, exc, elapsed_ms(self._t0)) + self._error(exc) raise - else: - self._on_done(elapsed_ms(self._t0), ttft_ms) + self._chunk(chunk) + return chunk + + def close(self) -> Any: + try: + close = getattr(self._original, "close", None) + if close is not None: + return close() + return None + finally: + self._finish("closed") def __enter__(self) -> SyncStreamWrapper: if hasattr(self._original, "__enter__"): - self._original.__enter__() # type: ignore[union-attr] + self._original.__enter__() return self - def __exit__(self, *args: object) -> object: - if hasattr(self._original, "__exit__"): - return self._original.__exit__(*args) # type: ignore[union-attr] - return None - - def __getattr__(self, name: str) -> object: + def __exit__(self, *args: Any) -> Any: + try: + if hasattr(self._original, "__exit__"): + return self._original.__exit__(*args) + close = getattr(self._original, "close", None) + if close is not None: + close() + return None + finally: + self._finish("closed") + + def __getattr__(self, name: str) -> Any: return getattr(self._original, name) -class AsyncStreamWrapper: - """Wraps an async iterable stream to capture TTFT and record inference on exhaustion.""" +class AsyncStreamWrapper(StreamState): + """Async counterpart, including cancellation while waiting for a chunk.""" def __init__( self, - original: object, + original: Any, handle: ModelHandle, t0: float, on_chunk: Callable[[object], None] | None, - on_done: Callable[[int, int | None], None], + on_done: Callable[..., None], ) -> None: + super().__init__(handle, t0, on_chunk, on_done) self._original = original - self._handle = handle - self._t0 = t0 - self._on_chunk = on_chunk - self._on_done = on_done + self._iterator = None - def __aiter__(self): - return self._track() + def __aiter__(self) -> AsyncStreamWrapper: + return self - async def _track(self): - ttft_ms: int | None = None + async def __anext__(self) -> Any: + if self._finished: + raise StopAsyncIteration try: - async for chunk in self._original: # type: ignore[union-attr] - if ttft_ms is None: - ttft_ms = elapsed_ms(self._t0) - if self._on_chunk is not None: - self._on_chunk(chunk) - yield chunk + if self._iterator is None: + self._iterator = self._original.__aiter__() + chunk = await self._iterator.__anext__() + except StopAsyncIteration: + self._finish() + raise + except asyncio.CancelledError: + self._finish("cancelled") + raise except Exception as exc: - track_api_error(self._handle, exc, elapsed_ms(self._t0)) + self._error(exc) raise - else: - self._on_done(elapsed_ms(self._t0), ttft_ms) + self._chunk(chunk) + return chunk + + async def close(self) -> Any: + try: + close = getattr(self._original, "aclose", None) or getattr( + self._original, "close", None + ) + if close is not None: + return await close() + return None + finally: + self._finish("closed") + + async def aclose(self) -> Any: + return await self.close() async def __aenter__(self) -> AsyncStreamWrapper: if hasattr(self._original, "__aenter__"): - await self._original.__aenter__() # type: ignore[union-attr] + await self._original.__aenter__() return self - async def __aexit__(self, *args: object) -> object: - if hasattr(self._original, "__aexit__"): - return await self._original.__aexit__(*args) # type: ignore[union-attr] - return None - - def __getattr__(self, name: str) -> object: + async def __aexit__(self, *args: Any) -> Any: + try: + if hasattr(self._original, "__aexit__"): + return await self._original.__aexit__(*args) + close = getattr(self._original, "aclose", None) or getattr( + self._original, "close", None + ) + if close is not None: + await close() + return None + finally: + self._finish( + "cancelled" + if args + and args[0] is not None + and issubclass(args[0], asyncio.CancelledError) + else "closed" + ) + + def __getattr__(self, name: str) -> Any: return getattr(self._original, name) diff --git a/wildedge/integrations/gguf.py b/wildedge/integrations/gguf.py index f024766..df9c9db 100644 --- a/wildedge/integrations/gguf.py +++ b/wildedge/integrations/gguf.py @@ -237,14 +237,17 @@ def on_chunk(chunk: object) -> None: if text: reply_parts.append(text) - def on_done(duration_ms: int, ttft_ms: int | None) -> None: + def on_done( + duration_ms: int, ttft_ms: int | None, *, outcome: str = "completed" + ) -> None: ti, to, sr = tokens_in[0], tokens_out[0], stop_reason[0] handle.track_inference( # type: ignore[union-attr] duration_ms=duration_ms, input_modality="text", output_modality="generation", input_meta=make_gguf_input_meta(prompt, ti, messages), - success=True, + success=outcome == "completed", + error_code=None if outcome == "completed" else "STREAM_" + outcome.upper(), output_meta=make_gguf_output_meta(ti, to, sr, ttft_ms, duration_ms), generation_config=generation_config, attachments=make_gguf_attachments( diff --git a/wildedge/integrations/openai.py b/wildedge/integrations/openai.py index f8b8f2e..d295148 100644 --- a/wildedge/integrations/openai.py +++ b/wildedge/integrations/openai.py @@ -177,14 +177,19 @@ def on_chunk(chunk: object) -> None: if reason: stop_reason[0] = reason - def on_done(duration_ms: int, ttft_ms: int | None) -> None: + def on_done( + duration_ms: int, ttft_ms: int | None, *, outcome: str = "completed" + ) -> None: ti, to, sr = tokens_in[0], tokens_out[0], stop_reason[0] + if outcome == "completed" and sr is None: + outcome = "incomplete" output_meta = build_streaming_output_meta(ttft_ms, ti, to, sr, duration_ms) handle.track_inference( duration_ms=duration_ms, input_modality="text", output_modality="generation", - success=True, + success=outcome == "completed", + error_code=None if outcome == "completed" else "STREAM_" + outcome.upper(), input_meta=build_input_meta(messages, ti), output_meta=output_meta, api_meta=build_api_meta(last_chunk[0]) @@ -344,8 +349,26 @@ def on_chunk(chunk: object) -> None: ) recorded = True - def on_done(duration_ms: int, _first_event_ms: int | None) -> None: + def on_done( + duration_ms: int, _first_event_ms: int | None, *, outcome: str = "completed" + ) -> None: nonlocal recorded + if response is None and not recorded: + recorded = True + handle.track_inference( + duration_ms=duration_ms, + input_modality="text", + output_modality="generation", + input_meta=build_input_meta(messages, None), + output_meta=GenerationOutputMeta( + time_to_first_token_ms=ttft, + stop_reason=outcome if outcome != "completed" else "incomplete", + ), + success=False, + error_code="STREAM_INCOMPLETE" + if outcome == "completed" + else "STREAM_" + outcome.upper(), + ) if response is not None and not recorded: recorded = True record_response(handle, response, messages, duration_ms, ttft)