Skip to content

feat(webapp): link Sentry events to OTel traces via trace_id#3531

Open
d-cs wants to merge 1 commit intomainfrom
align-sentry-axiom-errors
Open

feat(webapp): link Sentry events to OTel traces via trace_id#3531
d-cs wants to merge 1 commit intomainfrom
align-sentry-axiom-errors

Conversation

@d-cs
Copy link
Copy Markdown
Collaborator

@d-cs d-cs commented May 6, 2026

Summary

Stamps the active OpenTelemetry trace_id and span_id onto every Sentry event captured from the webapp, so engineers can copy a trace_id from a Sentry issue and search for the corresponding trace in any OTel-aware backend. Also adds an otel_sampled tag to indicate whether the trace was head-sampled — a cheap signal for whether the link will resolve to span data or hit a missing trace.

Why

Sentry and OTel were OTel-disconnected: apps/webapp/sentry.server.ts initialised Sentry with skipOpenTelemetrySetup: true, and no error-capture site (logger.server.ts, the Remix-wrapped handleError, the root ErrorBoundary) attached OTel context to the event. With many spans/sec across services, getting from a Sentry issue to its trace was guesswork.

Approach

Single global Sentry event processor, registered immediately after Sentry.init. On each event it reads trace.getActiveSpan()?.spanContext() via @opentelemetry/api, then writes:

  • event.contexts.trace.trace_id and event.contexts.trace.span_id (Sentry's native trace context fields)
  • event.tags.otel_sampled = "true" | "false" (derived from traceFlags)

If no active span (module-load errors, scheduled timers without a context, primary cluster process), the processor returns the event unmodified — Sentry's default propagation context fills in.

Implementation is co-located in apps/webapp/sentry.server.ts (no separate helper module — sentry.server.ts is built standalone by esbuild and a separate import would have required a new bundling step). Helper functions are exported so the unit tests can reach them without re-running Sentry.init.

Non-goals (deliberate)

  • No sample rate change. ~95% of Sentry events will carry a trace_id that returns no spans in the tracing backend (head-sampled out). The otel_sampled tag makes that obvious at a glance. Raising find-rate is a separate conversation with cost trade-offs.
  • No user/org tags or Sentry.setUser (would need auth-helper + per-request scope wiring across multiple worker entrypoints — separate ticket).
  • Webapp image only. No changes to supervisor or CLI workers.

Test plan

  • Unit tests in apps/webapp/test/sentryTraceContext.server.test.ts — 9 tests covering: helper returns `undefined` with no active span; returns `traceId`/`spanId`/`sampled=true` for a recording span; returns `sampled=false` for a non-recording span; processor leaves the event unchanged with no active span; processor stamps `trace_id`/`span_id` onto `contexts.trace`; preserves existing `contexts.trace` fields; tags `otel_sampled` correctly for both sampled and non-sampled cases; never throws if `@opentelemetry/api` access throws.
  • `pnpm run typecheck --filter webapp` passes.
  • Manually verified end-to-end against a sandboxed Sentry project: confirmed both sampled and non-sampled traces correctly populate `contexts.trace.trace_id` matching the OTel ids logged from the loader, and the `otel_sampled` tag appears with the expected value.

@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented May 6, 2026

⚠️ No Changeset found

Latest commit: 7ef196a

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@d-cs d-cs self-assigned this May 6, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 6, 2026

Review Change Stack

Walkthrough

The pull request adds OpenTelemetry integration to Sentry to stamp the active OTel trace_id and span_id onto Sentry events for cross-referencing with traces in any OTel backend. Two new utility functions are introduced: getActiveTraceIds() extracts the active OTel trace/span identifiers and sampling status, while addOtelTraceContextToEvent() injects this OTEL context into Sentry events as trace context and sampling tags. The integration is registered with Sentry's event processor pipeline, and comprehensive test coverage validates behavior across multiple scenarios.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely summarizes the main change: linking Sentry events to OpenTelemetry traces via trace_id, which is the core objective of this PR.
Description check ✅ Passed The description is comprehensive with Summary, Why, Approach, Non-goals, and Test plan sections. While it doesn't follow the exact template structure (missing Closes #issue, Testing, Changelog, Screenshots sections), it provides significantly more detailed technical context about the implementation, rationale, and testing than the template requires.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 align-sentry-axiom-errors

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@d-cs d-cs force-pushed the align-sentry-axiom-errors branch from 5cfb5ad to 693f829 Compare May 7, 2026 07:38
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
apps/webapp/test/sentryTraceContext.server.test.ts (2)

3-3: ⚡ Quick win

Heads-up: importing ../sentry.server pulls in module-level side effects.

sentry.server.ts runs if (process.env.SENTRY_DSN) { Sentry.init(...); Sentry.addEventProcessor(...) } at import time. In a test process where SENTRY_DSN happens to be set (e.g. a developer's shell, a misconfigured CI), simply importing this module to grab the helpers will initialize Sentry and register the processor as a side effect, which can leak state across the test suite and send unexpected events.

Consider extracting getActiveTraceIds and addOtelTraceContextToEvent into a side-effect-free module (e.g. apps/webapp/app/utils/sentryTraceContext.server.ts) and have sentry.server.ts import them. Tests then import only the pure helpers.

🤖 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 `@apps/webapp/test/sentryTraceContext.server.test.ts` at line 3, Importing
../sentry.server pulls in module-level Sentry.init/addEventProcessor side
effects; move the pure helpers into a side-effect-free module (e.g.
apps/webapp/app/utils/sentryTraceContext.server.ts) and export getActiveTraceIds
and addOtelTraceContextToEvent from there, then have sentry.server.ts import
those helpers internally so it still wires Sentry when SENTRY_DSN is present;
update tests to import getActiveTraceIds and addOtelTraceContextToEvent from the
new module so importing in tests no longer triggers Sentry.init or register
processors.

116-127: 💤 Low value

Mocking trace.getActiveSpan conflicts with the project's "never mock" testing guideline.

This block uses vi.spyOn(trace, "getActiveSpan").mockImplementation(...) to simulate a throw. The repo's testing rule is to avoid mocks/stubs in favor of real dependencies (testcontainers when needed). Since getActiveTraceIds already swallows errors via try/catch, you can exercise the same defensive path without mocking the OTel API — for example by passing a span/context that triggers a real exception (e.g. a wrapSpanContext with values that cause a downstream throw), or by extracting the OTel accessor as an injectable parameter so the test can supply a function that throws. Either approach removes the spy and keeps coverage of the catch branch.

If you decide the mock is the only practical route for this single negative path, consider documenting why this case is exempt so future readers don't treat it as precedent.

As per coding guidelines: "Use vitest exclusively for testing and never mock anything - use testcontainers instead".

🤖 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 `@apps/webapp/test/sentryTraceContext.server.test.ts` around lines 116 - 127,
The test should avoid spying on trace.getActiveSpan; refactor
addOtelTraceContextToEvent to accept an optional otel accessor parameter
(defaulting to trace.getActiveSpan) so callers/tests can inject a throwing
accessor to exercise the catch path in getActiveTraceIds; update
addOtelTraceContextToEvent (and any call sites) to use the injected accessor and
change the test to pass a function that throws instead of using vi.spyOn,
referencing the existing symbols addOtelTraceContextToEvent, getActiveTraceIds,
and trace.getActiveSpan.
🤖 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 `@apps/webapp/test/sentryTraceContext.server.test.ts`:
- Line 3: Importing ../sentry.server pulls in module-level
Sentry.init/addEventProcessor side effects; move the pure helpers into a
side-effect-free module (e.g.
apps/webapp/app/utils/sentryTraceContext.server.ts) and export getActiveTraceIds
and addOtelTraceContextToEvent from there, then have sentry.server.ts import
those helpers internally so it still wires Sentry when SENTRY_DSN is present;
update tests to import getActiveTraceIds and addOtelTraceContextToEvent from the
new module so importing in tests no longer triggers Sentry.init or register
processors.
- Around line 116-127: The test should avoid spying on trace.getActiveSpan;
refactor addOtelTraceContextToEvent to accept an optional otel accessor
parameter (defaulting to trace.getActiveSpan) so callers/tests can inject a
throwing accessor to exercise the catch path in getActiveTraceIds; update
addOtelTraceContextToEvent (and any call sites) to use the injected accessor and
change the test to pass a function that throws instead of using vi.spyOn,
referencing the existing symbols addOtelTraceContextToEvent, getActiveTraceIds,
and trace.getActiveSpan.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: b5daaaad-53c5-4357-95cb-7b460b21b7aa

📥 Commits

Reviewing files that changed from the base of the PR and between 62e0066 and 693f829.

📒 Files selected for processing (3)
  • .server-changes/sentry-trace-id-context.md
  • apps/webapp/sentry.server.ts
  • apps/webapp/test/sentryTraceContext.server.test.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (28)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (5, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (2, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (3, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (6, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (7, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (8, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (3, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (4, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (1, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (1, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (5, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (4, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (7, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (8, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (6, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (2, 8)
  • GitHub Check: units / packages / 🧪 Unit Tests: Packages (1, 1)
  • GitHub Check: units / e2e-webapp / 🧪 E2E Tests: Webapp
  • GitHub Check: sdk-compat / Bun Runtime
  • GitHub Check: sdk-compat / Node.js 20.20 (ubuntu-latest)
  • GitHub Check: sdk-compat / Node.js 22.12 (ubuntu-latest)
  • GitHub Check: sdk-compat / Deno Runtime
  • GitHub Check: typecheck / typecheck
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - npm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - pnpm)
  • GitHub Check: sdk-compat / Cloudflare Workers
🧰 Additional context used
📓 Path-based instructions (14)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Use types over interfaces for TypeScript
Avoid using enums; prefer string unions or const objects instead

Files:

  • apps/webapp/sentry.server.ts
  • apps/webapp/test/sentryTraceContext.server.test.ts
{packages/core,apps/webapp}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use zod for validation in packages/core and apps/webapp

Files:

  • apps/webapp/sentry.server.ts
  • apps/webapp/test/sentryTraceContext.server.test.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use function declarations instead of default exports

Files:

  • apps/webapp/sentry.server.ts
  • apps/webapp/test/sentryTraceContext.server.test.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/otel-metrics.mdc)

**/*.ts: When creating or editing OTEL metrics (counters, histograms, gauges), ensure metric attributes have low cardinality by using only enums, booleans, bounded error codes, or bounded shard IDs
Do not use high-cardinality attributes in OTEL metrics such as UUIDs/IDs (envId, userId, runId, projectId, organizationId), unbounded integers (itemCount, batchSize, retryCount), timestamps (createdAt, startTime), or free-form strings (errorMessage, taskName, queueName)
When exporting OTEL metrics via OTLP to Prometheus, be aware that the exporter automatically adds unit suffixes to metric names (e.g., 'my_duration_ms' becomes 'my_duration_ms_milliseconds', 'my_counter' becomes 'my_counter_total'). Account for these transformations when writing Grafana dashboards or Prometheus queries

Files:

  • apps/webapp/sentry.server.ts
  • apps/webapp/test/sentryTraceContext.server.test.ts
apps/webapp/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/webapp.mdc)

apps/webapp/**/*.{ts,tsx}: Access environment variables through the env export of env.server.ts instead of directly accessing process.env
Use subpath exports from @trigger.dev/core package instead of importing from the root @trigger.dev/core path

Use named constants for sentinel/placeholder values (e.g. const UNSET_VALUE = '__unset__') instead of raw string literals scattered across comparisons

Files:

  • apps/webapp/sentry.server.ts
  • apps/webapp/test/sentryTraceContext.server.test.ts
apps/webapp/**/*.server.ts

📄 CodeRabbit inference engine (apps/webapp/CLAUDE.md)

apps/webapp/**/*.server.ts: Never use request.signal for detecting client disconnects. Use getRequestAbortSignal() from app/services/httpAsyncStorage.server.ts instead, which is wired directly to Express res.on('close') and fires reliably
Access environment variables via env export from app/env.server.ts. Never use process.env directly
Always use findFirst instead of findUnique in Prisma queries. findUnique has an implicit DataLoader that batches concurrent calls and has active bugs even in Prisma 6.x (uppercase UUIDs returning null, composite key SQL correctness issues, 5-10x worse performance). findFirst is never batched and avoids this entire class of issues

Files:

  • apps/webapp/sentry.server.ts
{apps,internal-packages}/**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (CLAUDE.md)

Use pnpm run typecheck to verify changes in apps and internal packages (apps/*, internal-packages/*) instead of build, which proves almost nothing about correctness

Files:

  • apps/webapp/sentry.server.ts
  • apps/webapp/test/sentryTraceContext.server.test.ts
{package.json,**/*.{ts,tsx,js}}

📄 CodeRabbit inference engine (CLAUDE.md)

Pin Zod to version 3.25.76 exactly across the entire monorepo - never use a different version or version range

Files:

  • apps/webapp/sentry.server.ts
  • apps/webapp/test/sentryTraceContext.server.test.ts
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx,js}: Import from @trigger.dev/core using subpaths only, never the root export
Always import tasks from @trigger.dev/sdk, never from @trigger.dev/sdk/v3 or deprecated client.defineJob
Add crumbs to code using // @Crumbs comments or `// `#region` `@crumbs blocks for debug tracing during development

Files:

  • apps/webapp/sentry.server.ts
  • apps/webapp/test/sentryTraceContext.server.test.ts
**/*.{ts,tsx,js,jsx,json,md,css,scss}

📄 CodeRabbit inference engine (AGENTS.md)

Code formatting is enforced using Prettier. Run pnpm run format before committing

Files:

  • apps/webapp/sentry.server.ts
  • apps/webapp/test/sentryTraceContext.server.test.ts
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use vitest for all tests in the Trigger.dev repository

Files:

  • apps/webapp/test/sentryTraceContext.server.test.ts
apps/webapp/**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/webapp.mdc)

Do not import env.server.ts directly or indirectly into test files; instead pass environment-dependent values through options/parameters to make code testable

For testable code, never import env.server.ts in test files. Pass configuration as options instead (e.g., realtimeClient.server.ts takes config as constructor arg, realtimeClientGlobal.server.ts creates singleton with env config)

Files:

  • apps/webapp/test/sentryTraceContext.server.test.ts
**/*.test.{ts,tsx,js}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.test.{ts,tsx,js}: Use vitest exclusively for testing and never mock anything - use testcontainers instead
Place test files next to source files using the pattern MyService.ts -> MyService.test.ts

**/*.test.{ts,tsx,js}: Use vitest for unit testing and run tests with pnpm run test
Test files should live beside the files under test with descriptive describe and it blocks
Tests should avoid mocks or stubs and use helpers from @internal/testcontainers when Redis or Postgres are needed

Files:

  • apps/webapp/test/sentryTraceContext.server.test.ts
**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Use testcontainers with redisTest, postgresTest, or containerTest from @internal/testcontainers for testing with Redis/PostgreSQL dependencies

Files:

  • apps/webapp/test/sentryTraceContext.server.test.ts
🧠 Learnings (3)
📚 Learning: 2026-03-22T13:26:12.060Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3244
File: apps/webapp/app/components/code/TextEditor.tsx:81-86
Timestamp: 2026-03-22T13:26:12.060Z
Learning: In the triggerdotdev/trigger.dev codebase, do not flag `navigator.clipboard.writeText(...)` calls for `missing-await`/`unhandled-promise` issues. These clipboard writes are intentionally invoked without `await` and without `catch` handlers across the project; keep that behavior consistent when reviewing TypeScript/TSX files (e.g., usages like in `apps/webapp/app/components/code/TextEditor.tsx`).

Applied to files:

  • apps/webapp/sentry.server.ts
  • apps/webapp/test/sentryTraceContext.server.test.ts
📚 Learning: 2026-03-22T19:24:14.403Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3187
File: apps/webapp/app/v3/services/alerts/deliverErrorGroupAlert.server.ts:200-204
Timestamp: 2026-03-22T19:24:14.403Z
Learning: In the triggerdotdev/trigger.dev codebase, webhook URLs are not expected to contain embedded credentials/secrets (e.g., fields like `ProjectAlertWebhookProperties` should only hold credential-free webhook endpoints). During code review, if you see logging or inclusion of raw webhook URLs in error messages, do not automatically treat it as a credential-leak/secrets-in-logs issue by default—first verify the URL does not contain embedded credentials (for example, no username/password in the URL, no obvious secret/token query params or fragments). If the URL is credential-free per this project’s conventions, allow the logging.

Applied to files:

  • apps/webapp/sentry.server.ts
  • apps/webapp/test/sentryTraceContext.server.test.ts
📚 Learning: 2026-05-05T09:38:02.512Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3523
File: apps/webapp/app/routes/api.v3.batches.ts:178-181
Timestamp: 2026-05-05T09:38:02.512Z
Learning: When reviewing code that catches `ServiceValidationError` in `*.server.ts` files, do not blindly forward `error.status` to HTTP responses, because SVEs may be thrown with non-default statuses (e.g., 400/500) and forwarding them can cause client-visible behavioral regressions (e.g., surfacing 500s to clients). Prefer a safe default response status of `error.status ?? 422`, but only after confirming via the reachable call graph that the caught `ServiceValidationError` instances are expected to carry those non-default statuses; otherwise, normalize to `422` to avoid unexpected client-visible 5xx behavior.

Applied to files:

  • apps/webapp/sentry.server.ts
🔇 Additional comments (4)
.server-changes/sentry-trace-id-context.md (1)

1-7: LGTM — change-note clearly captures intent.

The note accurately summarizes the user-visible behavior: stamping OTel trace_id/span_id on Sentry events for cross-referencing.

apps/webapp/sentry.server.ts (2)

1-45: Implementation looks solid.

  • getActiveTraceIds() correctly derives sampling from traceFlags & TraceFlags.SAMPLED and is wrapped in try/catch so any failure in @opentelemetry/api falls back to undefined.
  • addOtelTraceContextToEvent returns a new object via spread, preserves any pre-existing event.contexts.trace / event.tags fields, and the inline comment on L25–L29 nicely justifies why overwriting Sentry's own trace_id/span_id is intentional given skipOpenTelemetrySetup: true.
  • Returning the original event reference when no active span exists keeps the no-op path allocation-free and makes the toBe(event) assertions in tests meaningful.

77-77: Processor registration is correctly scoped to the DSN-enabled branch.

Registering addOtelTraceContextToEvent only inside the if (process.env.SENTRY_DSN) block avoids attaching a processor to a Sentry instance that was never initialized. Good.

apps/webapp/test/sentryTraceContext.server.test.ts (1)

6-114: Good coverage of the positive paths.

The matrix across getActiveTraceIds and addOtelTraceContextToEvent (no span / recording / non-recording / preservation of prior contexts.trace and tags) is tight and uses real OTel primitives (trace.wrapSpanContext, context.with, startActiveSpan) rather than fakes — exactly the right shape for these helpers.

One small observation: createInMemoryTracing() from ./utils/tracing calls NodeTracerProvider.register() (per the file's own comment on L26–L27), which mutates global OTel state. Re-invoking it in subsequent tests should be a no-op for correctness, but if you ever see flaky cross-test interactions it's worth confirming the helper is idempotent.

@d-cs d-cs force-pushed the align-sentry-axiom-errors branch 3 times, most recently from c3bb682 to 417bada Compare May 7, 2026 08:15
@d-cs d-cs marked this pull request as ready for review May 7, 2026 09:54
Copy link
Copy Markdown
Contributor

@devin-ai-integration devin-ai-integration Bot left a comment

Choose a reason for hiding this comment

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

✅ Devin Review: No Issues Found

Devin Review analyzed this PR and found no potential bugs to report.

View in Devin Review to see 3 additional findings.

Open in Devin Review

Stamps the active OpenTelemetry trace_id and span_id onto every
Sentry event captured from the webapp, plus an otel_sampled tag
indicating whether the corresponding trace was head-sampled.
Engineers can now copy the trace_id from any Sentry issue and search
their tracing backend by it directly.

Implemented as a single global Sentry event processor registered
after Sentry.init in apps/webapp/sentry.server.ts. The processor
reads the active OTel context via @opentelemetry/api and writes
Sentry's native contexts.trace fields. No tracer config or sampling
changes; no client-side Sentry init exists in this codebase.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@d-cs d-cs force-pushed the align-sentry-axiom-errors branch from 417bada to 7ef196a Compare May 7, 2026 10:58
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 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.

Inline comments:
In `@apps/webapp/test/sentryTraceContext.server.test.ts`:
- Around line 9-47: The tests register a global OTel provider via
createInMemoryTracing() which is never torn down, causing order-dependent
failures; add an afterEach cleanup that calls shutdown on the global tracer
provider returned by trace.getTracerProvider() (or the provider instance created
by createInMemoryTracing()), then call trace.disable() and context.disable() to
reset to NOOP defaults so getActiveTraceIds() behaves deterministically across
tests and the "returns undefined when no OTel span is active" test no longer
depends on ordering.
- Around line 1-7: The test file is placed under the top-level test directory
instead of co-located with its source; move
apps/webapp/test/sentryTraceContext.server.test.ts to the same folder as the
source (apps/webapp/app/utils/) and update imports in the test to use the
relative path "./sentryTraceContext.server" for functions
addOtelTraceContextToEvent and getActiveTraceIds, keeping the existing imports
of ROOT_CONTEXT/TraceFlags/context/trace and createInMemoryTracing unchanged;
ensure the test filename matches the source pattern
(sentryTraceContext.server.test.ts) so tooling picks it up.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 7ab433e6-cc0e-43c4-aff7-526780fe98a6

📥 Commits

Reviewing files that changed from the base of the PR and between 417bada and 7ef196a.

📒 Files selected for processing (5)
  • .server-changes/sentry-trace-id-context.md
  • apps/webapp/app/utils/sentryTraceContext.server.ts
  • apps/webapp/package.json
  • apps/webapp/sentry.server.ts
  • apps/webapp/test/sentryTraceContext.server.test.ts
✅ Files skipped from review due to trivial changes (2)
  • apps/webapp/sentry.server.ts
  • .server-changes/sentry-trace-id-context.md
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/webapp/package.json
  • apps/webapp/app/utils/sentryTraceContext.server.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (21)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (3, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (6, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (8, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (7, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (1, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (5, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (5, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (2, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (8, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (6, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (7, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (4, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (2, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (4, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (3, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (1, 8)
  • GitHub Check: units / e2e-webapp / 🧪 E2E Tests: Webapp
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
  • GitHub Check: units / packages / 🧪 Unit Tests: Packages (1, 1)
  • GitHub Check: typecheck / typecheck
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Use types over interfaces for TypeScript
Avoid using enums; prefer string unions or const objects instead

Files:

  • apps/webapp/test/sentryTraceContext.server.test.ts
{packages/core,apps/webapp}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use zod for validation in packages/core and apps/webapp

Files:

  • apps/webapp/test/sentryTraceContext.server.test.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use function declarations instead of default exports

Files:

  • apps/webapp/test/sentryTraceContext.server.test.ts
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use vitest for all tests in the Trigger.dev repository

Files:

  • apps/webapp/test/sentryTraceContext.server.test.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/otel-metrics.mdc)

**/*.ts: When creating or editing OTEL metrics (counters, histograms, gauges), ensure metric attributes have low cardinality by using only enums, booleans, bounded error codes, or bounded shard IDs
Do not use high-cardinality attributes in OTEL metrics such as UUIDs/IDs (envId, userId, runId, projectId, organizationId), unbounded integers (itemCount, batchSize, retryCount), timestamps (createdAt, startTime), or free-form strings (errorMessage, taskName, queueName)
When exporting OTEL metrics via OTLP to Prometheus, be aware that the exporter automatically adds unit suffixes to metric names (e.g., 'my_duration_ms' becomes 'my_duration_ms_milliseconds', 'my_counter' becomes 'my_counter_total'). Account for these transformations when writing Grafana dashboards or Prometheus queries

Files:

  • apps/webapp/test/sentryTraceContext.server.test.ts
apps/webapp/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/webapp.mdc)

apps/webapp/**/*.{ts,tsx}: Access environment variables through the env export of env.server.ts instead of directly accessing process.env
Use subpath exports from @trigger.dev/core package instead of importing from the root @trigger.dev/core path

Use named constants for sentinel/placeholder values (e.g. const UNSET_VALUE = '__unset__') instead of raw string literals scattered across comparisons

Files:

  • apps/webapp/test/sentryTraceContext.server.test.ts
apps/webapp/**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/webapp.mdc)

Do not import env.server.ts directly or indirectly into test files; instead pass environment-dependent values through options/parameters to make code testable

For testable code, never import env.server.ts in test files. Pass configuration as options instead (e.g., realtimeClient.server.ts takes config as constructor arg, realtimeClientGlobal.server.ts creates singleton with env config)

Files:

  • apps/webapp/test/sentryTraceContext.server.test.ts
{apps,internal-packages}/**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (CLAUDE.md)

Use pnpm run typecheck to verify changes in apps and internal packages (apps/*, internal-packages/*) instead of build, which proves almost nothing about correctness

Files:

  • apps/webapp/test/sentryTraceContext.server.test.ts
**/*.test.{ts,tsx,js}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.test.{ts,tsx,js}: Use vitest exclusively for testing and never mock anything - use testcontainers instead
Place test files next to source files using the pattern MyService.ts -> MyService.test.ts

**/*.test.{ts,tsx,js}: Use vitest for unit testing and run tests with pnpm run test
Test files should live beside the files under test with descriptive describe and it blocks
Tests should avoid mocks or stubs and use helpers from @internal/testcontainers when Redis or Postgres are needed

Files:

  • apps/webapp/test/sentryTraceContext.server.test.ts
**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Use testcontainers with redisTest, postgresTest, or containerTest from @internal/testcontainers for testing with Redis/PostgreSQL dependencies

Files:

  • apps/webapp/test/sentryTraceContext.server.test.ts
{package.json,**/*.{ts,tsx,js}}

📄 CodeRabbit inference engine (CLAUDE.md)

Pin Zod to version 3.25.76 exactly across the entire monorepo - never use a different version or version range

Files:

  • apps/webapp/test/sentryTraceContext.server.test.ts
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx,js}: Import from @trigger.dev/core using subpaths only, never the root export
Always import tasks from @trigger.dev/sdk, never from @trigger.dev/sdk/v3 or deprecated client.defineJob
Add crumbs to code using // @Crumbs comments or `// `#region` `@crumbs blocks for debug tracing during development

Files:

  • apps/webapp/test/sentryTraceContext.server.test.ts
**/*.{ts,tsx,js,jsx,json,md,css,scss}

📄 CodeRabbit inference engine (AGENTS.md)

Code formatting is enforced using Prettier. Run pnpm run format before committing

Files:

  • apps/webapp/test/sentryTraceContext.server.test.ts
🧠 Learnings (2)
📚 Learning: 2026-03-22T13:26:12.060Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3244
File: apps/webapp/app/components/code/TextEditor.tsx:81-86
Timestamp: 2026-03-22T13:26:12.060Z
Learning: In the triggerdotdev/trigger.dev codebase, do not flag `navigator.clipboard.writeText(...)` calls for `missing-await`/`unhandled-promise` issues. These clipboard writes are intentionally invoked without `await` and without `catch` handlers across the project; keep that behavior consistent when reviewing TypeScript/TSX files (e.g., usages like in `apps/webapp/app/components/code/TextEditor.tsx`).

Applied to files:

  • apps/webapp/test/sentryTraceContext.server.test.ts
📚 Learning: 2026-03-22T19:24:14.403Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3187
File: apps/webapp/app/v3/services/alerts/deliverErrorGroupAlert.server.ts:200-204
Timestamp: 2026-03-22T19:24:14.403Z
Learning: In the triggerdotdev/trigger.dev codebase, webhook URLs are not expected to contain embedded credentials/secrets (e.g., fields like `ProjectAlertWebhookProperties` should only hold credential-free webhook endpoints). During code review, if you see logging or inclusion of raw webhook URLs in error messages, do not automatically treat it as a credential-leak/secrets-in-logs issue by default—first verify the URL does not contain embedded credentials (for example, no username/password in the URL, no obvious secret/token query params or fragments). If the URL is credential-free per this project’s conventions, allow the logging.

Applied to files:

  • apps/webapp/test/sentryTraceContext.server.test.ts

Comment on lines +1 to +7
import { ROOT_CONTEXT, TraceFlags, context, trace } from "@opentelemetry/api";
import { describe, expect, it } from "vitest";
import {
addOtelTraceContextToEvent,
getActiveTraceIds,
} from "../app/utils/sentryTraceContext.server";
import { createInMemoryTracing } from "./utils/tracing";
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.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Move the test file next to its source to satisfy the co-location guideline.

The source is apps/webapp/app/utils/sentryTraceContext.server.ts, so the test should live at apps/webapp/app/utils/sentryTraceContext.server.test.ts — not under the top-level test/ directory. The import path on Line 6 would then simplify to "./sentryTraceContext.server".

As per coding guidelines: "Place test files next to source files using the pattern MyService.ts -> MyService.test.ts".

🤖 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 `@apps/webapp/test/sentryTraceContext.server.test.ts` around lines 1 - 7, The
test file is placed under the top-level test directory instead of co-located
with its source; move apps/webapp/test/sentryTraceContext.server.test.ts to the
same folder as the source (apps/webapp/app/utils/) and update imports in the
test to use the relative path "./sentryTraceContext.server" for functions
addOtelTraceContextToEvent and getActiveTraceIds, keeping the existing imports
of ROOT_CONTEXT/TraceFlags/context/trace and createInMemoryTracing unchanged;
ensure the test filename matches the source pattern
(sentryTraceContext.server.test.ts) so tooling picks it up.

Comment on lines +9 to +47
describe("getActiveTraceIds", () => {
it("returns undefined when no OTel span is active", () => {
expect(getActiveTraceIds()).toBeUndefined();
});

it("returns the trace_id, span_id, and sampled=true for an active recording span", () => {
const { tracer } = createInMemoryTracing();

tracer.startActiveSpan("test-span", (span) => {
const ids = getActiveTraceIds();
expect(ids).toEqual({
traceId: span.spanContext().traceId,
spanId: span.spanContext().spanId,
sampled: true,
});
span.end();
});
});

it("returns sampled=false when the active span is non-recording", () => {
// Initialise the global context manager (createInMemoryTracing does this
// as a side effect of NodeTracerProvider.register()).
createInMemoryTracing();

const nonSampledSpan = trace.wrapSpanContext({
traceId: "0123456789abcdef0123456789abcdef",
spanId: "0123456789abcdef",
traceFlags: TraceFlags.NONE,
});

context.with(trace.setSpan(ROOT_CONTEXT, nonSampledSpan), () => {
expect(getActiveTraceIds()).toEqual({
traceId: "0123456789abcdef0123456789abcdef",
spanId: "0123456789abcdef",
sampled: false,
});
});
});
});
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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Global OTel provider registrations are never torn down — implicit test-order dependency.

Each createInMemoryTracing() call registers a NodeTracerProvider globally (via provider.register()). There is no afterEach/afterAll to shut down or deregister the provider. The first test ("returns undefined when no OTel span is active", Line 10–12) relies on running before any provider is registered; once any other test runs first, the context manager is active and trace.getActiveSpan() may no longer return undefined as intended.

Consider adding cleanup to guard against ordering fragility:

import { context, trace, ProxyTracerProvider } from "@opentelemetry/api";

afterEach(async () => {
  // Reset the global tracer/context-manager back to NOOP defaults
  await (trace.getTracerProvider() as any)?.shutdown?.();
  trace.disable();
  context.disable();
});
🤖 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 `@apps/webapp/test/sentryTraceContext.server.test.ts` around lines 9 - 47, The
tests register a global OTel provider via createInMemoryTracing() which is never
torn down, causing order-dependent failures; add an afterEach cleanup that calls
shutdown on the global tracer provider returned by trace.getTracerProvider() (or
the provider instance created by createInMemoryTracing()), then call
trace.disable() and context.disable() to reset to NOOP defaults so
getActiveTraceIds() behaves deterministically across tests and the "returns
undefined when no OTel span is active" test no longer depends on ordering.

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.

1 participant