Skip to content

HTTP response callbacks cause startInactiveSpan and error events to lose the active parent after GC (OpenTelemetry setup on) #26217

Closed

Description

@chrisolszewski

Is there an existing issue for this?

  • I have checked for existing issues
  • I have reviewed the documentation
  • I am using the latest SDK release

How do you use Sentry?

Sentry SaaS (sentry.io)

Which SDK are you using?

@sentry/node (we run @sentry/tanstackstart-react on the server)

SDK Version

11.11.0 (first seen on 11.8.0)

Framework Version

Node.js 26.13.0

Reproduction Example/SDK Setup

// npm i @sentry/node@11.11.0
// node --expose-gc repro.cjs
const http = require("node:http");
const Sentry = require("@sentry/node");

const errorSpanIds = [];
Sentry.init({
  dsn: "https://public@example.invalid/1",
  tracesSampleRate: 1,
  enableOpenTelemetrySetup: true,
  beforeSend(event) {
    errorSpanIds.push(event.contexts?.trace?.span_id);
    return null;
  },
});

const tick = () => new Promise((resolve) => setImmediate(resolve));
const server = http.createServer((_req, res) => res.end("hello"));
server.listen(0, "127.0.0.1", async () => {
  try {
    await Sentry.startSpan({ name: "parent" }, async (parent) => {
      const childParentId = () => {
        const child = Sentry.startInactiveSpan({ name: "child" });
        child.end();
        return Sentry.spanToJSON(child).parent_span_id;
      };
      console.log("parent span id:", parent.spanContext().spanId);
      console.log("child parent before HTTP:", childParentId());

      await new Promise((resolve, reject) => {
        http
          .get(`http://127.0.0.1:${server.address().port}/`, { agent: false }, (res) => {
            res.resume();
            res.on("end", resolve);
            res.on("error", reject);
          })
          .on("error", reject);
      });

      console.log("child parent after HTTP, before GC:", childParentId());
      await tick();
      globalThis.gc();
      await tick();
      console.log("child parent after GC:", childParentId());
      console.log("getActiveSpan() === parent:", Sentry.getActiveSpan() === parent);
      Sentry.captureException(new Error("boom"));
      await Sentry.flush(1000);
      console.log("error event span_id:", errorSpanIds[0]);
    });
  } finally {
    server.close();
    await Sentry.close(1000);
  }
});

This reproduction does not call bindScopeToEmitter. The SDK's HTTP client instrumentation binds the response automatically. Forced GC makes the failure easy to reproduce. We also reproduced it without --expose-gc, using ordinary object allocation between event-loop turns.

Steps to Reproduce

  1. npm i @sentry/node@11.11.0
  2. node --expose-gc repro.cjs

Expected Result

The child span and the error event stay attached to parent after the HTTP response has been handled:

parent span id: a1dfb6ececa2d31c
child parent before HTTP: a1dfb6ececa2d31c
child parent after HTTP, before GC: a1dfb6ececa2d31c
child parent after GC: a1dfb6ececa2d31c
getActiveSpan() === parent: true
error event span_id: a1dfb6ececa2d31c

That is the output when globalThis.gc() is replaced with a no-op.

Actual Result

parent span id: 8850fa2541397537
child parent before HTTP: 8850fa2541397537
child parent after HTTP, before GC: 8850fa2541397537
child parent after GC: undefined
getActiveSpan() === parent: true
error event span_id: 9eb4ab36a0ba6c1a

After a GC, startInactiveSpan creates a new root span, and the error event carries a span id that is not parent's. getActiveSpan() with no argument still returns parent. With enableOpenTelemetrySetup: false, attribution stays correct.

When a trace is continued from a sentry-trace header, the new local root gets the propagated parent span id instead of the active local span's id. We reproduced that variant too. We investigated this after seeing many one-span transactions and inconsistent parent relationships in our application. Those symptoms are consistent with this bug, but the reproduction does not show that it explains every affected record.

Additional Context

We think the cause is this sequence:

  1. bindListenerToScope in packages/core/src/tracing/bindScopeToEmitter.ts runs each listener with withScope(scope, ...), passing the captured scope object itself. packages/core/src/integrations/http/client-subscriptions.ts binds outgoing HTTP responses this way.
  2. With OpenTelemetry setup on, withSetScope in packages/opentelemetry/src/asyncContextStrategy.ts builds a new context for that scope. buildContextWithSentryScopes reuses the same scope object and sets its context link to the new context. The link is a WeakRef (setContextOnScope in packages/opentelemetry/src/utils/contextData.ts).
  3. The listener's context is short-lived. Once it is collected, getActiveSpan(scope) in packages/opentelemetry/src/utils/getActiveSpan.ts finds no context for the scope and returns undefined. The parent span and the original context are still alive; only the scope's link to its context has been overwritten.
  4. startInactiveSpan without an explicit parent resolves its parent through getActiveSpan(scope) (packages/core/src/tracing/trace.ts). Event preparation also calls getActiveSpan(finalScope) (packages/core/src/utils/prepareEvent.ts). After collection, both find no span even though the ambient OpenTelemetry context still has the parent. In this reproduction, startSpan and startSpanManual still find the correct parent through their scope-forking path.

Cloning the scope for each listener invocation fixes these reproductions on 11.8.0 and 11.11.0. It changes the API's existing scope-sharing behavior, so we are treating it as a local workaround rather than a behavior-preserving fix:

 function bindListenerToScope(listener, scope) {
   return function (...args) {
-    return withScope(scope, () => listener.apply(this, args));
+    return withScope(scope.clone(), () => listener.apply(this, args));
   };
 }

With this change, each listener invocation gets a new current-scope object. Changes made through getCurrentScope() inside a listener no longer persist to the caller, to other listeners or to later invocations. It also changes scope identity, which the existing bindScopeToEmitter unit tests assert. The isolation scope stays shared, so Sentry.setTag() and Sentry.addBreadcrumb() still affect it. Cloning is shallow and adds an allocation and copy per invocation. We have not run the SDK's test suite against it or measured the overhead. A fix in the context-management code that keeps the existing binding semantics may be better.

Activity

  1. linear-code commented on Nov 9, 2026

    @linear-code
  2. self-assigned this
    on Nov 9, 2026
  3. msonnb commented on Nov 10, 2026

    @msonnb
    Member

    Hey @chrisolszewski thanks for reporting! I have a PR open to fix.

  4. added a commit that references this issue on Nov 16, 2026
    b0d975d
  5. github-actions commented on Nov 16, 2026

    @github-actions
    Contributor

    A PR closing this issue has just been released 🚀

    This issue was referenced by PR #26234, which was included in the 11.13.0 release.

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

Metadata

Metadata

Assignees

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions