Repository navigation
Fix two races in Claude Agent SDK tool-use hook instrumentation - #2194
Conversation
… Claude Agent SDK instrumentation The SDK runs hook callbacks in separate anyio tasks, so a PreToolUse hook could close the current chat span before the main task had applied the assistant message that announced the tool call, losing the span's output and model attributes. The hook now waits (with a safety-valve timeout) until the assistant message announcing its tool_use_id has been handled.
Spans created in hook tasks inferred their code location from the hook task's stack, which bottoms out in the event loop: the first non-library frame is whatever launched the process (e.g. a console script's module frame), and under pytest-xdist workers there is no such frame at all, so the attributes varied by environment. Capture the user's frame when receive_response is entered and use it for tool spans instead.
|
Warning Review limit reached
Next review available in: 9 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughClaude Agent SDK tracing now waits for assistant 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
tests/otel_integrations/test_claude_agent_sdk.py (1)
487-540: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAssert the emitted spans in both new tests.
Both tests create and close spans. Add the
exporter: TestExporterfixture and assertexported_spans_as_dict(parse_json_attributes=True)against an inline snapshot. This verifies the ordering fix and timeout fallback at the telemetry boundary.As per coding guidelines, “For span-producing tests, use
TestExporter, assertexported_spans_as_dict(parse_json_attributes=True)against aninline_snapshot.”🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/otel_integrations/test_claude_agent_sdk.py` around lines 487 - 540, Update test_pre_hook_waits_for_tool_announcement and test_pre_hook_announcement_timeout to accept the exporter: TestExporter fixture, then assert exporter.exported_spans_as_dict(parse_json_attributes=True) with inline snapshots after the spans are closed. Capture the expected emitted span ordering and timeout-fallback telemetry at the exporter boundary while preserving the existing behavioral assertions.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@tests/otel_integrations/test_claude_agent_sdk.py`:
- Around line 487-540: Update test_pre_hook_waits_for_tool_announcement and
test_pre_hook_announcement_timeout to accept the exporter: TestExporter fixture,
then assert exporter.exported_spans_as_dict(parse_json_attributes=True) with
inline snapshots after the spans are closed. Capture the expected emitted span
ordering and timeout-fallback telemetry at the exporter boundary while
preserving the existing behavioral assertions.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: dc55bf38-5663-4c89-8ab8-01dae8a7dff0
📒 Files selected for processing (2)
logfire/_internal/integrations/claude_agent_sdk.pytests/otel_integrations/test_claude_agent_sdk.py
🔗 Linked repositories identified
CodeRabbit considers these linked repositories for cross-repo context during reviews:
pydantic/logfire(manual)pydantic/pydantic-ai(manual)pydantic/platform(auto-detected)pydantic/pydantic(auto-detected)
There was a problem hiding this comment.
All reported issues were addressed across 2 files
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
… captured Per review: if get_user_stack_info() found no user frame at receive_response time, updating with an empty dict would keep the environment-dependent frames this change is meant to remove.
Two fixes for spans created by the Claude Agent SDK integration's tool-use hooks, which run in separate anyio tasks:
PreToolUse hooks raced with assistant message processing. The CLI sends the assistant message (containing the
tool_useblock) before invoking the PreToolUse hook, but the hook runs in its own task and could be scheduled first. When that happened, the hook closed the current chat span before the main task had applied the assistant message, so the chat span lost its output messages, model attributes, and name, and the conversation history fed to later chat spans was missing the assistant turn. The hook now waits (with a 1s safety-valve timeout) until the assistant message announcing itstool_use_idhas been handled.Tool span code attributes were environment-dependent junk. Spans created inside hook tasks inferred
code.filepath/code.linenofrom the hook task's stack, which bottoms out in the event loop; the first non-library frame is whatever launched the process (e.g. a console script's<module>frame), and in some environments there is no such frame at all. Tool spans now use the user's frame captured whenreceive_responseis entered.Both were exposed by running the test suite under pytest-xdist (#2179): the cassette test's span snapshots flipped depending on task scheduling and process launch context. The cassette test now also runs a delayed-consumer variant that deterministically exercises the hook-waits-for-announcement path.