feat(webapp): link Sentry events to OTel traces via trace_id#3531
feat(webapp): link Sentry events to OTel traces via trace_id#3531
Conversation
|
WalkthroughThe 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)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
5cfb5ad to
693f829
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (2)
apps/webapp/test/sentryTraceContext.server.test.ts (2)
3-3: ⚡ Quick winHeads-up: importing
../sentry.serverpulls in module-level side effects.
sentry.server.tsrunsif (process.env.SENTRY_DSN) { Sentry.init(...); Sentry.addEventProcessor(...) }at import time. In a test process whereSENTRY_DSNhappens 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
getActiveTraceIdsandaddOtelTraceContextToEventinto a side-effect-free module (e.g.apps/webapp/app/utils/sentryTraceContext.server.ts) and havesentry.server.tsimport 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 valueMocking
trace.getActiveSpanconflicts 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). SincegetActiveTraceIdsalready swallows errors viatry/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. awrapSpanContextwith 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
📒 Files selected for processing (3)
.server-changes/sentry-trace-id-context.mdapps/webapp/sentry.server.tsapps/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.tsapps/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.tsapps/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.tsapps/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.tsapps/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 theenvexport ofenv.server.tsinstead of directly accessingprocess.env
Use subpath exports from@trigger.dev/corepackage instead of importing from the root@trigger.dev/corepathUse 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.tsapps/webapp/test/sentryTraceContext.server.test.ts
apps/webapp/**/*.server.ts
📄 CodeRabbit inference engine (apps/webapp/CLAUDE.md)
apps/webapp/**/*.server.ts: Never userequest.signalfor detecting client disconnects. UsegetRequestAbortSignal()fromapp/services/httpAsyncStorage.server.tsinstead, which is wired directly to Expressres.on('close')and fires reliably
Access environment variables viaenvexport fromapp/env.server.ts. Never useprocess.envdirectly
Always usefindFirstinstead offindUniquein Prisma queries.findUniquehas 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).findFirstis 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 typecheckto verify changes in apps and internal packages (apps/*,internal-packages/*) instead ofbuild, which proves almost nothing about correctness
Files:
apps/webapp/sentry.server.tsapps/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.tsapps/webapp/test/sentryTraceContext.server.test.ts
**/*.{ts,tsx,js}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{ts,tsx,js}: Import from@trigger.dev/coreusing subpaths only, never the root export
Always import tasks from@trigger.dev/sdk, never from@trigger.dev/sdk/v3or deprecatedclient.defineJob
Add crumbs to code using//@Crumbscomments or `// `#region` `@crumbsblocks for debug tracing during development
Files:
apps/webapp/sentry.server.tsapps/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 formatbefore committing
Files:
apps/webapp/sentry.server.tsapps/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.tsdirectly or indirectly into test files; instead pass environment-dependent values through options/parameters to make code testableFor testable code, never import
env.server.tsin test files. Pass configuration as options instead (e.g.,realtimeClient.server.tstakes config as constructor arg,realtimeClientGlobal.server.tscreates 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 patternMyService.ts->MyService.test.ts
**/*.test.{ts,tsx,js}: Use vitest for unit testing and run tests withpnpm run test
Test files should live beside the files under test with descriptivedescribeanditblocks
Tests should avoid mocks or stubs and use helpers from@internal/testcontainerswhen 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, orcontainerTestfrom@internal/testcontainersfor 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.tsapps/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.tsapps/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_idon Sentry events for cross-referencing.apps/webapp/sentry.server.ts (2)
1-45: Implementation looks solid.
getActiveTraceIds()correctly derives sampling fromtraceFlags & TraceFlags.SAMPLEDand is wrapped intry/catchso any failure in@opentelemetry/apifalls back toundefined.addOtelTraceContextToEventreturns a new object via spread, preserves any pre-existingevent.contexts.trace/event.tagsfields, and the inline comment on L25–L29 nicely justifies why overwriting Sentry's owntrace_id/span_idis intentional givenskipOpenTelemetrySetup: true.- Returning the original
eventreference when no active span exists keeps the no-op path allocation-free and makes thetoBe(event)assertions in tests meaningful.
77-77: Processor registration is correctly scoped to the DSN-enabled branch.Registering
addOtelTraceContextToEventonly inside theif (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
getActiveTraceIdsandaddOtelTraceContextToEvent(no span / recording / non-recording / preservation of priorcontexts.traceandtags) 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/tracingcallsNodeTracerProvider.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.
c3bb682 to
417bada
Compare
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>
417bada to
7ef196a
Compare
There was a problem hiding this comment.
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
📒 Files selected for processing (5)
.server-changes/sentry-trace-id-context.mdapps/webapp/app/utils/sentryTraceContext.server.tsapps/webapp/package.jsonapps/webapp/sentry.server.tsapps/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 theenvexport ofenv.server.tsinstead of directly accessingprocess.env
Use subpath exports from@trigger.dev/corepackage instead of importing from the root@trigger.dev/corepathUse 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.tsdirectly or indirectly into test files; instead pass environment-dependent values through options/parameters to make code testableFor testable code, never import
env.server.tsin test files. Pass configuration as options instead (e.g.,realtimeClient.server.tstakes config as constructor arg,realtimeClientGlobal.server.tscreates 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 typecheckto verify changes in apps and internal packages (apps/*,internal-packages/*) instead ofbuild, 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 patternMyService.ts->MyService.test.ts
**/*.test.{ts,tsx,js}: Use vitest for unit testing and run tests withpnpm run test
Test files should live beside the files under test with descriptivedescribeanditblocks
Tests should avoid mocks or stubs and use helpers from@internal/testcontainerswhen 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, orcontainerTestfrom@internal/testcontainersfor 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/coreusing subpaths only, never the root export
Always import tasks from@trigger.dev/sdk, never from@trigger.dev/sdk/v3or deprecatedclient.defineJob
Add crumbs to code using//@Crumbscomments or `// `#region` `@crumbsblocks 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 formatbefore 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
| 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"; |
There was a problem hiding this comment.
🛠️ 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.
| 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, | ||
| }); | ||
| }); | ||
| }); | ||
| }); |
There was a problem hiding this comment.
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.
Summary
Stamps the active OpenTelemetry
trace_idandspan_idonto every Sentry event captured from the webapp, so engineers can copy atrace_idfrom a Sentry issue and search for the corresponding trace in any OTel-aware backend. Also adds anotel_sampledtag 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.tsinitialised Sentry withskipOpenTelemetrySetup: true, and no error-capture site (logger.server.ts, the Remix-wrappedhandleError, the rootErrorBoundary) 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 readstrace.getActiveSpan()?.spanContext()via@opentelemetry/api, then writes:event.contexts.trace.trace_idandevent.contexts.trace.span_id(Sentry's native trace context fields)event.tags.otel_sampled="true"|"false"(derived fromtraceFlags)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.tsis 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-runningSentry.init.Non-goals (deliberate)
trace_idthat returns no spans in the tracing backend (head-sampled out). Theotel_sampledtag makes that obvious at a glance. Raising find-rate is a separate conversation with cost trade-offs.Sentry.setUser(would need auth-helper + per-request scope wiring across multiple worker entrypoints — separate ticket).Test plan
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.