Skip to content

feat(server-utils): Group the tool spans of an Anthropic session runner under one invoke_agent span - #25995

Open
RulaKhaled wants to merge 4 commits into
developfrom
feat/anthropic-session-runner-span-worker-hook
Open

RulaKhaled wants to merge 4 commits into
developfrom
feat/anthropic-session-runner-span-worker-hook

Conversation

@RulaKhaled

@RulaKhaled RulaKhaled commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

EnvironmentWorker drives Managed Agents sessions from a background loop with no active span, so every execute_tool span from #25554 became its own root and all sessions shared one trace. Each SessionToolRunner now gets one gen_ai.invoke_agent span over its tool spans, with the session id as gen_ai.conversation.id on the span and, through the scope, on its tool spans, unless the app set its own with Sentry.setConversationId().

A session started from top-level code, which is how the SDK documents running the worker, gets its own trace and a clean scope. Anywhere else it stays in the caller's trace, like Anthropic's own tracing does.

Known limits: a failed event stream still reports ok, since the SDK swallows it. Spans a tool creates in close() land outside the session, since the SDK calls it after the loop ends.

Fixes #25768

🤖 Generated with Claude Code

@github-actions

github-actions Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

size-limit report 📦

Compared: eea9247 (PR test merge using develop at 88a5e3b)

Against: 88a5e3b (develop) · base run #65049

✅ Baseline matches: this diff contains only this PR's changes.

Path Size % Change Change
@sentry/browser 30.4 kB -0.01% -1 B 🔽
@sentry/browser - with treeshaking flags 28.54 kB - -
@sentry/browser - with treeshaking flags tracing without tracing 28.43 kB - -
@sentry/browser (incl. Tracing) 52.73 kB -0.01% -1 B 🔽
@sentry/browser (incl. Tracing + Span Streaming) 52.73 kB - -
@sentry/browser (incl. Tracing, Profiling) 55.7 kB -0.01% -1 B 🔽
@sentry/browser (incl. Tracing, Replay) 93.03 kB +0.01% +1 B 🔺
@sentry/browser (incl. Tracing, Replay) - with treeshaking flags 81.63 kB - -
@sentry/browser (incl. Tracing, Replay with Canvas) 97.78 kB +0.01% +2 B 🔺
@sentry/browser (incl. Tracing, Replay, Feedback) 110.77 kB -0.01% -1 B 🔽
@sentry/browser (incl. Feedback) 47.98 kB -0.01% -1 B 🔽
@sentry/browser (incl. sendFeedback) 35.5 kB -0.01% -1 B 🔽
@sentry/browser (incl. FeedbackAsync) 40.61 kB -0.01% -1 B 🔽
@sentry/browser (incl. Metrics) 31.44 kB -0.01% -1 B 🔽
@sentry/browser (incl. Logs) 31.73 kB -0.01% -1 B 🔽
@sentry/browser (incl. Metrics & Logs) 32.45 kB -0.01% -1 B 🔽
@sentry/react 32.29 kB -0.01% -1 B 🔽
@sentry/react (incl. Tracing) 55.1 kB - -
@sentry/vue 38.67 kB - -
@sentry/vue (incl. Tracing) 55.75 kB +0.01% +1 B 🔺
@sentry/svelte 30.43 kB -0.01% -1 B 🔽
@sentry/remix (Remix 3 client bundle) 57.82 kB -0.01% -2 B 🔽
CDN Bundle 32.19 kB - -
CDN Bundle (incl. Tracing) 53.26 kB - -
CDN Bundle (incl. Logs, Metrics) 34.47 kB - -
CDN Bundle (incl. Tracing, Logs, Metrics) 55.2 kB - -
CDN Bundle (incl. Replay, Logs, Metrics) 75.88 kB - -
CDN Bundle (incl. Tracing, Replay) 91.47 kB - -
CDN Bundle (incl. Tracing, Replay, Logs, Metrics) 93.4 kB - -
CDN Bundle (incl. Tracing, Replay, Feedback) 97.58 kB - -
CDN Bundle (incl. Tracing, Replay, Feedback, Logs, Metrics) 99.58 kB - -
CDN Bundle - uncompressed 94.67 kB - -
CDN Bundle (incl. Tracing) - uncompressed 157.67 kB - -
CDN Bundle (incl. Logs, Metrics) - uncompressed 101.14 kB - -
CDN Bundle (incl. Tracing, Logs, Metrics) - uncompressed 163.41 kB - -
CDN Bundle (incl. Replay, Logs, Metrics) - uncompressed 232.71 kB - -
CDN Bundle (incl. Tracing, Replay) - uncompressed 279.36 kB - -
CDN Bundle (incl. Tracing, Replay, Logs, Metrics) - uncompressed 285.08 kB - -
CDN Bundle (incl. Tracing, Replay, Feedback) - uncompressed 293.06 kB - -
CDN Bundle (incl. Tracing, Replay, Feedback, Logs, Metrics) - uncompressed 298.77 kB - -
@sentry/nextjs (client) 58.05 kB -0.01% -1 B 🔽
@sentry/sveltekit (client) 53.24 kB -0.01% -1 B 🔽
@sentry/core/server 44.25 kB -0.01% -1 B 🔽
@sentry/core/browser 13.93 kB - -
@sentry/node 156.2 kB +0.17% +254 B 🔺
@sentry/node/import (ESM hook with diagnostics-channel injection) 82.28 kB - -
@sentry/node - without tracing 96.91 kB +0.02% +16 B 🔺
@sentry/node - without channel injection 136.53 kB +0.19% +253 B 🔺
@sentry/aws-serverless 105.12 kB +0.02% +20 B 🔺
@sentry/cloudflare (withSentry) - minified 200.68 kB +0.01% +8 B 🔺
@sentry/cloudflare (withSentry) 499.05 kB +0.01% +8 B 🔺
@sentry/nextjs/cloudflare (withSentry) - minified 222.66 kB +0.01% +8 B 🔺

View base workflow run

@github-actions

github-actions Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Optional E2E tests

Some optional checks were not successful. They do not block the merge. 3 not successful, 53 successful. See the run.

Check Status
❌ CI: Optional E2E Tests / E2E node-flue (latest) Test (optional) Failing after 3m Details
❌ CI: Optional E2E Tests / E2E nextjs-16-cacheComponents (cloudflare) Test (optional) Failing after 10m Details
❌ CI: Optional E2E Tests / E2E cloudflare-pi-durable (latest) Test (optional) Failing after 1m Details
Successful checks
Check Status
✅ CI: Optional E2E Tests / E2E cloudflare-mastra Test (optional) Successful in 50s Details
✅ CI: Optional E2E Tests / E2E cloudflare-agent Test (optional) Successful in 48s Details
✅ CI: Optional E2E Tests / E2E cloudflare-flue-send-to-sentry Test (optional) Successful in 9m Details
✅ CI: Optional E2E Tests / E2E cloudflare-think Test (optional) Successful in 1m Details
✅ CI: Optional E2E Tests / E2E debug-id-sourcemaps Test (optional) Successful in 38s Details
✅ CI: Optional E2E Tests / E2E nextjs-16 (deno) Test (optional) Successful in 2m Details
✅ CI: Optional E2E Tests / E2E deno (latest) Test (optional) Successful in 1m Details
✅ CI: Optional E2E Tests / E2E cloudflare-pi-durable Test (optional) Successful in 1m Details
✅ CI: Optional E2E Tests / E2E nextjs-15 (latest) Test (optional) Successful in 4m Details
✅ CI: Optional E2E Tests / E2E nuxt-5-sourcemaps (static / nuxt generate) Test (optional) Successful in 41s Details
✅ CI: Optional E2E Tests / E2E gen-ai-libraries (cloudflare) Test (optional) Successful in 54s Details
✅ CI: Optional E2E Tests / E2E gen-ai-libraries (latest) Test (optional) Successful in 8m Details
✅ CI: Optional E2E Tests / E2E astro-7 Test (optional) Successful in 1m Details
✅ CI: Optional E2E Tests / E2E node-eve Test (optional) Successful in 9m Details
✅ CI: Optional E2E Tests / E2E gen-ai-libraries Test (optional) Successful in 1m Details
✅ CI: Optional E2E Tests / E2E nextjs-16 (vinext) Test (optional) Successful in 2m Details
✅ CI: Optional E2E Tests / E2E node-eve (orchestrion) Test (optional) Successful in 1m Details
✅ CI: Optional E2E Tests / E2E node-express-mcp-v2 Test (optional) Successful in 42s Details
✅ CI: Optional E2E Tests / E2E cloudflare-think (ai v6) Test (optional) Successful in 1m Details
✅ CI: Optional E2E Tests / E2E node-mastra Test (optional) Successful in 1m Details
✅ CI: Optional E2E Tests / E2E nextjs-orpc Test (optional) Successful in 2m Details
✅ CI: Optional E2E Tests / E2E nuxt-5-sourcemaps Test (optional) Successful in 41s Details
✅ CI: Optional E2E Tests / E2E nextjs-16-tunnel (cloudflare) Test (optional) Successful in 1m Details
✅ CI: Optional E2E Tests / E2E node-flue Test (optional) Successful in 2m Details
✅ CI: Optional E2E Tests / E2E nextjs-15 (turbo) Test (optional) Successful in 2m Details
✅ CI: Optional E2E Tests / E2E cloudflare-workers-send-to-sentry Test (optional) Successful in 3m Details
✅ CI: Optional E2E Tests / E2E nextjs-16 (cloudflare, latest) Test (optional) Successful in 9m Details
✅ CI: Optional E2E Tests / E2E astro-7-static Test (optional) Successful in 1m Details
✅ CI: Optional E2E Tests / E2E nextjs-16 (vinext, bun) Test (optional) Successful in 2m Details
✅ CI: Optional E2E Tests / E2E node-eve (latest) Test (optional) Successful in 1m Details
✅ CI: Optional E2E Tests / E2E react-router-7-framework-instrumentation Test (optional) Successful in 3m Details
✅ CI: Optional E2E Tests / E2E nuxt-5 Test (optional) Successful in 2m Details
✅ CI: Optional E2E Tests / E2E tanstackstart-react-cloudflare Test (optional) Successful in 46s Details
✅ CI: Optional E2E Tests / E2E nestjs-12 (latest) Test (optional) Successful in 59s Details
✅ CI: Optional E2E Tests / E2E node-fastify-6 Test (optional) Successful in 51s Details
✅ CI: Optional E2E Tests / E2E nextjs-14 (latest) Test (optional) Successful in 1m Details
✅ CI: Optional E2E Tests / E2E node-express-send-to-sentry-static Test (optional) Successful in 3m Details
✅ CI: Optional E2E Tests / E2E node-fastify-6 (tracer provider) Test (optional) Successful in 50s Details
✅ CI: Optional E2E Tests / E2E node-mastra (latest) Test (optional) Successful in 1m Details
✅ CI: Optional E2E Tests / E2E node-express-mcp-v1 Test (optional) Successful in 37s Details
✅ CI: Optional E2E Tests / E2E node-express-send-to-sentry Test (optional) Successful in 1m Details
✅ CI: Optional E2E Tests / E2E react-send-to-sentry Test (optional) Successful in 4m Details
✅ CI: Optional E2E Tests / E2E solidstart-2 Test (optional) Successful in 59s Details
✅ CI: Optional E2E Tests / E2E nuxt-5 (tunnel-dev) Test (optional) Successful in 1m Details
✅ CI: Optional E2E Tests / E2E nuxt-5-sourcemaps (client source maps kept) Test (optional) Successful in 40s Details
✅ CI: Optional E2E Tests / E2E node-openai-decisions (latest) Test (optional) Successful in 52s Details
✅ CI: Optional E2E Tests / E2E node-pi-durable (latest) Test (optional) Successful in 52s Details
✅ CI: Optional E2E Tests / E2E supabase-nextjs Test (optional) Successful in 3m Details
✅ CI: Optional E2E Tests / E2E tanstackstart-react (latest) Test (optional) Successful in 1m Details
✅ CI: Optional E2E Tests / E2E node-pi-durable Test (optional) Successful in 59s Details
✅ CI: Optional E2E Tests / E2E vue-3 (no Options API) Test (optional) Successful in 1m Details
✅ CI: Optional E2E Tests / E2E tanstackstart-react-sourcemaps Test (optional) Successful in 53s Details
✅ CI: Optional E2E Tests / E2E node-openai-decisions Test (optional) Successful in 8m Details

@RulaKhaled

Copy link
Copy Markdown
Collaborator Author

bugbot run

@cursor cursor 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.

Stale Bugbot comment from a previous run.

@RulaKhaled

Copy link
Copy Markdown
Collaborator Author

bugbot run

@cursor cursor 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.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 60fd1da. Configure here.

@RulaKhaled
RulaKhaled marked this pull request as ready for review November 3, 2026 12:07
@RulaKhaled
RulaKhaled requested a review from a team as a code owner November 3, 2026 12:07
@RulaKhaled
RulaKhaled requested review from isaacs and mydea and removed request for a team November 3, 2026 12:07
@mydea

mydea commented Nov 4, 2026

Copy link
Copy Markdown
Member

this seems pretty complicated 😅 is there no other way to achieve this too? 🤔 (maybe there isn't, just wanted to play devils advocate here... 😅 )

Some ideas to look into - this was investigated with LLM help, so consider with caution:

1. Can we drop the EnvironmentWorker hook?

  • It's only needed in one case: worker.run() started inside a span or forked scope. At top level, which is the daemon usage in the SDK's docs, startSessionSpan already gives each session
    its own trace through !getActiveSpan() && scope === default.
  • What it costs: a new orchestrion entry and channel, a subscriber, the workerLoopScopes WeakSet side channel, and the 112-line scenario.
  • The precedent doesn't really apply: the PR cites Flue and pi-durable, but Flue's loop is always started by the first admission, so it always inherits a request's context. A worker is
    started explicitly by the user, usually at boot.
  • It also overrides user intent: Sentry.startSpan({ name: 'daemon' }, () => worker.run()) now silently loses its parent, and any scope data set around it is dropped.
  • What we'd give up: a worker started fire-and-forget from a request would nest its sessions under that request's trace. I'd accept that and document startNewTrace as the workaround.

2. Only the first next() needs the session context

runEachCallInSession re-enters three saved contexts on every call: isolation scope, scope and span. That's also why the code needs the WeakRef workaround that Bugbot flagged.

But #streamLoop starts on the first next(), and all tool dispatch hangs off it. In my experiment, with only the first next() wrapped:

  • Every tool ran in the session context, including ones that ran after later next() calls from the outer context.
  • The generator's finally block ran in the outer context.

So per-call re-entry only buys parenting for tool.close(), and for the unlikely manual throw(), since for await never calls it. A plain loop removes the shim and the saved-scope logic
(untested sketch):

  async function* traceSessionLoop(sdk, sessionId) {
    let span;
    const first = inSessionScopes(() =>
      startSpanManual(spanOptions(sessionId), s => {
        span = s;
        getCurrentScope().setConversationId(sessionId);
        return sdk.next();
      }),
    );
    try {
      let result = await first;
      while (!result.done) {
        yield result.value;
        result = await sdk.next();
      }
    } catch (e) {
      span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });
      throw e;
    } finally {
      await sdk.return?.(); // drains in-flight tools before the span ends
      span.end();
    }
  }

The trade-off is that spans created inside tool.close() would no longer sit under the session, and the test asserting that would go.

3. Don't reimplement fill

wrapInPlace was rewritten only because fill takes name: string. fill already does the wrapped marking and the try/catch that the rewrite adds. Widening its type to string | symbol and
using String(name) in its debug log would let this part of the diff go. That log needs the change because a template literal throws on a symbol.

4. Drop the setsConversationId branch

pi-durable sets the id unconditionally, and the session id is the more precise value anyway. Honouring an earlier setConversationId adds a four-line branch, and I don't see that the
issue asks for it. If the scope is set before the span starts, the attribute could come from one place. That only works if conversationIdIntegration is always installed, which I didn't
confirm, so the explicit attribute may need to stay.

I would keep setting the id on the scope rather than reading it from the parent span. That way, a messages.create call inside a tool also gets the id.

@RulaKhaled

Copy link
Copy Markdown
Collaborator Author

this seems pretty complicated 😅 is there no other way to achieve this too? 🤔 (maybe there isn't, just wanted to play devils advocate here... 😅 )

Some ideas to look into - this was investigated with LLM help, so consider with caution:

1. Can we drop the EnvironmentWorker hook?

  • It's only needed in one case: worker.run() started inside a span or forked scope. At top level, which is the daemon usage in the SDK's docs, startSessionSpan already gives each session
    its own trace through !getActiveSpan() && scope === default.
  • What it costs: a new orchestrion entry and channel, a subscriber, the workerLoopScopes WeakSet side channel, and the 112-line scenario.
  • The precedent doesn't really apply: the PR cites Flue and pi-durable, but Flue's loop is always started by the first admission, so it always inherits a request's context. A worker is
    started explicitly by the user, usually at boot.
  • It also overrides user intent: Sentry.startSpan({ name: 'daemon' }, () => worker.run()) now silently loses its parent, and any scope data set around it is dropped.
  • What we'd give up: a worker started fire-and-forget from a request would nest its sessions under that request's trace. I'd accept that and document startNewTrace as the workaround.

2. Only the first next() needs the session context

runEachCallInSession re-enters three saved contexts on every call: isolation scope, scope and span. That's also why the code needs the WeakRef workaround that Bugbot flagged.

But #streamLoop starts on the first next(), and all tool dispatch hangs off it. In my experiment, with only the first next() wrapped:

  • Every tool ran in the session context, including ones that ran after later next() calls from the outer context.
  • The generator's finally block ran in the outer context.

So per-call re-entry only buys parenting for tool.close(), and for the unlikely manual throw(), since for await never calls it. A plain loop removes the shim and the saved-scope logic (untested sketch):

  async function* traceSessionLoop(sdk, sessionId) {
    let span;
    const first = inSessionScopes(() =>
      startSpanManual(spanOptions(sessionId), s => {
        span = s;
        getCurrentScope().setConversationId(sessionId);
        return sdk.next();
      }),
    );
    try {
      let result = await first;
      while (!result.done) {
        yield result.value;
        result = await sdk.next();
      }
    } catch (e) {
      span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });
      throw e;
    } finally {
      await sdk.return?.(); // drains in-flight tools before the span ends
      span.end();
    }
  }

The trade-off is that spans created inside tool.close() would no longer sit under the session, and the test asserting that would go.

3. Don't reimplement fill

wrapInPlace was rewritten only because fill takes name: string. fill already does the wrapped marking and the try/catch that the rewrite adds. Widening its type to string | symbol and using String(name) in its debug log would let this part of the diff go. That log needs the change because a template literal throws on a symbol.

4. Drop the setsConversationId branch

pi-durable sets the id unconditionally, and the session id is the more precise value anyway. Honouring an earlier setConversationId adds a four-line branch, and I don't see that the issue asks for it. If the scope is set before the span starts, the attribute could come from one place. That only works if conversationIdIntegration is always installed, which I didn't confirm, so the explicit attribute may need to stay.

I would keep setting the id on the scope rather than reading it from the parent span. That way, a messages.create call inside a tool also gets the id.

yeah fair, went through all and most check out as we are fine with tradeoffs:

  1. the worker hook: some context on why it's there. the model is anthropic's own tracing, the OTel spans the SDK emits itself in 1.x, which we turn off by default. it wraps each work item in an anthropic.environment.work span with the session id on it, and the worker creates one runner per item, so our per-runner span already gives the same grouping. the hook went one step further and gave every session its own trace even when run() was called inside a request.

but agreed! every example I found runs worker from top-level code (which with the hook off still gets one trace per session). one catch: startNewTrace(() => worker.run()) doesn't work as a workaround, it forks the scope so both sessions share one trace, so the note would be "start the worker from top-level code"

  1. only the first next(): confirmed. the SDK still drains in-flight tools before the span ends, so the only thing we lose is spans created inside a tool's close(), which is just cleanup (e.g. an MCP toolset closing its connection) and still gets sent, just not under the session. fine with that imo?

  2. fill: yep, widening it works!

  3. setsConversationId: I'd keep this one. without it, if an app sets its own conversation id with Sentry.setConversationId(), the session's spans ignore it and use the session id instead, that goes against the expected/docs, which say setConversationId() applies to all AI spans and that ids inferred by an integration are the fallback. I think we need to unify this experience across integrations: LangChain, LangGraph and anthropic's own tracing all let the app's id win

will push the simplified version shortly

@RulaKhaled
RulaKhaled requested review from a team as code owners November 4, 2026 19:35
@RulaKhaled
RulaKhaled requested review from logaretm and s1gr1d and removed request for a team November 4, 2026 19:35
RulaKhaled and others added 4 commits November 4, 2026 20:50
…er under one invoke_agent span

Each SessionToolRunner gets one gen_ai.invoke_agent span over its tool
spans, with the session id as gen_ai.conversation.id. A hook on the
EnvironmentWorker constructor runs run() apart from whatever started it,
and each session it drives gets its own trace and clean scope.

Fixes #25768

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
… session runner

With OpenTelemetry set up, a scope reaches its context only through a
WeakRef, so re-entering the session scope after a garbage collection lost
the active span. Also bind the SDK iterator's return and throw instead of
asserting them.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…irst next() in the session

From review: a worker run from top-level code, as the SDK documents it,
already gets one trace per session without the hook. Only the first
next() needs the session context, since the SDK starts its tool loop
there. Widen core fill() to take a symbol key instead of a local copy.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The 1.x suite from #25750 asserted that session tool spans are children of
the caller's span. They now sit under the session's invoke_agent span.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@RulaKhaled
RulaKhaled force-pushed the feat/anthropic-session-runner-span-worker-hook branch from 229ddd8 to 28eb4bb Compare November 4, 2026 19:53

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(server-utils): Parent the tool spans of an Anthropic session runner under one span per session

2 participants