fix(anthropic): end streaming spans on early exit and on a failed sync stream #4705
All Vouch review confidence checks passed
Residual risk 0.25 = Change Risk (0.47) × (1 − Review Confidence (0.47)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.47 · 483 lines diff across 6 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.02 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.370
Shallow Review Depth
shallow_review_depth
0.344
Real PR Conversation Timeline
1 comments
"Review active on #4705"
general
weight: 0.35
simin-yuan
Fixes #4536.
Problem
A streamed call ends its span only when the stream is read to the end. Three ways of stopping earlier leave the span open, or finish it without a record:
with client.messages.stream(...)before the stream is exhausted, callsclose(), or drops the object — sync and async (#4536);event: errorfrom the API — the async iterator already ended its span, the sync one did not (#4643);get_final_text()bypassed the proxy, so the span carried no response attributes and a mid-stream error was not recorded on it.Change
streaming.pyandevent_emitter.py:_handle_stream_errorsetsERROR, recordserror.type, the exception event and the duration, and ends the span. This branch leaves__next__and__anext__to it and only keeps every other path inside_instrumentation_completed, so a span still ends exactly once.WrappedMessageStreamManagerkeeps the proxy it builds in__enter__and finishes it in__exit__, after the SDK's own cleanup;WrappedAsyncMessageStreamManagerdoes the same in__aenter__/__aexit__.AnthropicStreamandAnthropicAsyncStreamfinish the span inclose()and in__del__. Every path goes through_instrumentation_completed, so a span ends exactly once.get_final_text()and consume through their own iteration before calling the SDK helper, so the response and token attributes are filled and a stream error ends the span asERROR.emit_streaming_response_eventskeeps atool_usecall whose input is empty or not valid JSON, with{}as its arguments, instead of raising.Streams that are read to the end behave as before: same attributes, same
OKstatus, same token usage. The span for a half-read stream isOKtoo — the call itself succeeded; only the record was missing.Tests
tests/test_stream_span_finalization.py, 16 cases: {sync, async} × {early exit, stream error, completion},close()and garbage collection for the sync client, closing midtool_usefor both clients, partial tool input for the emitter, the directcreate(stream=True)context manager, andget_final_text()for {sync, async} × {success, stream error}. Each case asserts exactly one finished span, its status, and that the SDK still closed the HTTP response; the completion cases also assert the token attributes.The four
get_final_textcases fail againststreaming.pyfrom #4752's head, and pass against this branch:Prerequisite for #4703
#4703 turns the SDK's own span off for the Anthropic instrumentation. Until this lands, a sync stream that errors or exits early has no record at all, so #4703 should merge after this one.
<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
<!-- coderabbit-ai-generated:v1 -->
Summary by CodeRabbit
Bug Fixes
Streaming traces now finish on completion, errors, explicit closure, context-manager exit, or when partially consumed streams are garbage-collected.
Stream errors are recorded in trace status, and instrumentation finalization runs only once.
Completed streams continue to report token usage, and stream resources are closed on early exits and failures.
Tool-call events are recorded even when input is empty or cannot be parsed; arguments are reported as empty in those cases.
Errors while emitting completion events no longer interrupt stream completion.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->