ref(anthropic): Factor out streamed result handling #5563
1 issue
find-bugs: Found 1 issue (1 medium)
Medium
Span never closed if synchronous streaming iterator is interrupted - `sentry_sdk/integrations/anthropic.py:358-369`
The _wrap_synchronous_message_iterator function lacks try/finally handling around the iteration loop. If an exception is raised during iteration, or if the consumer breaks out of the loop early (e.g., for event in stream: break), or if the generator is explicitly closed, the code after the for loop (lines 371-389) will never execute. This leaves the span unclosed, causing resource leaks and incomplete traces. Other integrations like google_genai and openai_agents use try/finally patterns to ensure span cleanup.
Also found at:
sentry_sdk/integrations/anthropic.py:405-416
Duration: 4m 3s · Tokens: 841.8k in / 10.2k out · Cost: $1.05 (+extraction: $0.00, +merge: $0.00)
Annotations
Check warning on line 369 in sentry_sdk/integrations/anthropic.py
sentry-warden / warden: find-bugs
Span never closed if synchronous streaming iterator is interrupted
The `_wrap_synchronous_message_iterator` function lacks try/finally handling around the iteration loop. If an exception is raised during iteration, or if the consumer breaks out of the loop early (e.g., `for event in stream: break`), or if the generator is explicitly closed, the code after the `for` loop (lines 371-389) will never execute. This leaves the span unclosed, causing resource leaks and incomplete traces. Other integrations like `google_genai` and `openai_agents` use try/finally patterns to ensure span cleanup.
Check warning on line 416 in sentry_sdk/integrations/anthropic.py
sentry-warden / warden: find-bugs
[EA8-HD2] Span never closed if synchronous streaming iterator is interrupted (additional location)
The `_wrap_synchronous_message_iterator` function lacks try/finally handling around the iteration loop. If an exception is raised during iteration, or if the consumer breaks out of the loop early (e.g., `for event in stream: break`), or if the generator is explicitly closed, the code after the `for` loop (lines 371-389) will never execute. This leaves the span unclosed, causing resource leaks and incomplete traces. Other integrations like `google_genai` and `openai_agents` use try/finally patterns to ensure span cleanup.