Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
9 changes: 6 additions & 3 deletions docs/providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
60 changes: 60 additions & 0 deletions docs/streaming.md
Original file line number Diff line number Diff line change
@@ -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.
75 changes: 75 additions & 0 deletions tests/compat/test_anthropic_compat.py
Original file line number Diff line number Diff line change
@@ -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")
Expand Down Expand Up @@ -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
40 changes: 40 additions & 0 deletions tests/compat/test_openai_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
3 changes: 3 additions & 0 deletions tests/test_integrations_anthropic.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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()
Expand Down Expand Up @@ -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()
Expand Down
5 changes: 4 additions & 1 deletion tests/test_integrations_openai_responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading
Loading