Skip to content

Fix two races in Claude Agent SDK tool-use hook instrumentation - #2194

Merged
dmontagu merged 3 commits into
mainfrom
dm/claude-hook-races
Aug 5, 2026
Merged

dmontagu merged 3 commits into
mainfrom
dm/claude-hook-races

Conversation

@dmontagu

@dmontagu dmontagu commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Two fixes for spans created by the Claude Agent SDK integration's tool-use hooks, which run in separate anyio tasks:

  1. PreToolUse hooks raced with assistant message processing. The CLI sends the assistant message (containing the tool_use block) 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 its tool_use_id has been handled.

  2. Tool span code attributes were environment-dependent junk. Spans created inside hook tasks inferred code.filepath/code.lineno 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 in some environments there is no such frame at all. Tool spans now use the user's frame captured when receive_response is 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.

Review in cubic

… 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.
@dmontagu dmontagu added the revertible Can be safely reverted after merge label Aug 5, 2026
@dmontagu dmontagu self-assigned this Aug 5, 2026
@coderabbitai

coderabbitai Bot commented Aug 5, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@dmontagu, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 9 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b95e0204-2e85-487a-93c7-57c925a2c007

📥 Commits

Reviewing files that changed from the base of the PR and between 1c545c9 and 37339bf.

📒 Files selected for processing (1)
  • logfire/_internal/integrations/claude_agent_sdk.py
📝 Walkthrough

Walkthrough

Claude Agent SDK tracing now waits for assistant ToolUseBlock announcements before creating tool spans, with a one-second timeout fallback. Conversation state records announced tool IDs, signals waiting hooks, and captures user stack attributes for tool spans. Tests cover delayed announcements, timeout behavior, delayed message consumption, and exact snapshot attributes.

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the two race fixes in Claude Agent SDK tool-use hook instrumentation.
Description check ✅ Passed The description directly explains both fixes, their causes, and the tests added to validate the behavior.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch dm/claude-hook-races

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
tests/otel_integrations/test_claude_agent_sdk.py (1)

487-540: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the emitted spans in both new tests.

Both tests create and close spans. Add the exporter: TestExporter fixture and assert exported_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, assert exported_spans_as_dict(parse_json_attributes=True) against an inline_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

📥 Commits

Reviewing files that changed from the base of the PR and between 0c98a61 and 1c545c9.

📒 Files selected for processing (2)
  • logfire/_internal/integrations/claude_agent_sdk.py
  • tests/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)

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@dmontagu
dmontagu removed this pull request from the merge queue due to a manual request Aug 5, 2026
@dmontagu
dmontagu added this pull request to the merge queue Aug 5, 2026
Merged via the queue into main with commit 3626755 Aug 5, 2026
4 checks passed
@dmontagu
dmontagu deleted the dm/claude-hook-races branch August 5, 2026 13:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

revertible Can be safely reverted after merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant