← Back to Pull requests

fix(anthropic): end streaming spans on early exit and on a failed sync stream #4705

Open
unknown opened this pull request with 483 lines diff across 6 files
View on GitHub
unknown unknown commented on Nov 12, 2026 17:58 UTC
Author

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:

  • the caller leaves with client.messages.stream(...) before the stream is exhausted, calls close(), or drops the object — sync and async (#4536);

  • a sync stream raises mid-way, for example an event: error from the API — the async iterator already ended its span, the sync one did not (#4643);

  • a stream read through 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.py and event_emitter.py:

  • The stream-error branch is #4752's: _handle_stream_error sets ERROR, records error.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.

  • WrappedMessageStreamManager keeps the proxy it builds in __enter__ and finishes it in __exit__, after the SDK's own cleanup; WrappedAsyncMessageStreamManager does the same in __aenter__/__aexit__.

  • AnthropicStream and AnthropicAsyncStream finish the span in close() and in __del__. Every path goes through _instrumentation_completed, so a span ends exactly once.

  • Both proxies now intercept 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 as ERROR.

  • emit_streaming_response_events keeps a tool_use call 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 OK status, same token usage. The span for a half-read stream is OK too — 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 mid tool_use for both clients, partial tool input for the emitter, the direct create(stream=True) context manager, and get_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_text cases fail against streaming.py from #4752's head, and pass against this branch:

    $ uv run --frozen pytest -q tests/test_stream_span_finalization.py -k get_final_text
    4 failed   # streaming.py from #4752
    4 passed   # this branch
    $ uv run --frozen pytest -q tests
    290 passed
    $ uv run --frozen ruff check .
    All checks passed!
    

    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 -->

    Diff: 483 lines (+362 / -121) across 6 files Reviewer: simin-yuan Review duration: 25777m
    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
    0.47
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    46%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    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
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 46.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 47.3% (MEDIUM) · Higher = larger blast radius
    47.3%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 46.7% · Lower = rushed or shallow review
    46.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 25.2% · Safe to merge
    25.2%