fix(core): mint the fallback external trace id per run - #4534
Conversation
🦋 Changeset detectedLatest commit: e840eb0 The changes in this PR will be included in the next version bump. This PR includes changesets to release 27 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
WalkthroughThe tracing SDK adds 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 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 |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/core/src/v3/otel/tracingSDK.ts (1)
397-464: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy liftBind the fallback trace ID at export time.
forCurrentRun()readsgetTraceContextEpoch()in the exporter callback. When batch exports drain aftertraceContexthas been reassigned, queued run-A records can receive run-B’s fallback ID or be skipped, merging unrelated runs in external traces/logs. Capture the run-level fallback/epoch state when each span or log record enters the external processor, or flush external batch processors before replacing the trace context. Add a regression test that queues run-A records, advances to run-B, then exports the queued records.Also applies: lines 522-571.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: d5f5e20b-033f-427f-9c43-5cfbed70a539
📒 Files selected for processing (6)
.changeset/external-trace-id-per-run.mdpackages/core/src/v3/otel/tracingSDK.tspackages/core/src/v3/traceContext/api.tspackages/core/src/v3/traceContext/manager.tspackages/core/src/v3/traceContext/types.tspackages/core/test/externalSpanExporterWrapper.test.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (42)
- GitHub Check: packages / 📊 Merge Reports
- GitHub Check: e2e / 🧪 CLI v3 tests (warp-windows-latest-x64-8x - pnpm)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (11, 12)
- GitHub Check: packages / 🧪 Unit Tests: Packages (3, 3)
- GitHub Check: sdk-compat / Node.js 24.18 (warp-ubuntu-latest-x64-4x)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (8, 12)
- GitHub Check: sdk-compat / Node.js 26.4 (warp-ubuntu-latest-x64-4x)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (5, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (10, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (2, 12)
- GitHub Check: sdk-compat / Cloudflare Workers
- GitHub Check: sdk-compat / Bun Runtime
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (1, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (4, 12)
- GitHub Check: sdk-compat / Deno Runtime
- GitHub Check: e2e / 🧪 CLI v3 tests (warp-windows-latest-x64-8x - npm)
- GitHub Check: sdk-compat / Node.js 22.23 (warp-ubuntu-latest-x64-4x)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (7, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (12, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (3, 12)
- GitHub Check: packages / 🧪 Unit Tests: Packages (1, 3)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (9, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (6, 12)
- GitHub Check: packages / 🧪 Unit Tests: Packages (2, 3)
- GitHub Check: e2e-webapp / 🧪 E2E Tests: Webapp
- GitHub Check: internal / 🧪 Unit Tests: Internal
- GitHub Check: typecheck / typecheck
- GitHub Check: code-quality / code-quality
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (6, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (9, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (11, 12)
- GitHub Check: internal / 🧪 Unit Tests: Internal
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (5, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (7, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (12, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (1, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (3, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (2, 12)
- GitHub Check: e2e-webapp / 🧪 E2E Tests: Webapp
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (8, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (4, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (10, 12)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{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
**/*.{ts,tsx}: Prefer static imports over dynamicimport(); use dynamic imports only for unresolvable circular dependencies, genuine performance code splitting, or conditional runtime loading.
Import Trigger.dev tasks from@trigger.dev/sdk; never use@trigger.dev/sdk/v3or deprecatedclient.defineJob.
Add agentcrumbs while writing code using approved namespaces; mark lines with//@Crumbsor blocks with `// `#region` `@crumbs, and strip them before merging.
Files:
packages/core/src/v3/traceContext/types.tspackages/core/src/v3/traceContext/api.tspackages/core/src/v3/traceContext/manager.tspackages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.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:
packages/core/src/v3/traceContext/types.tspackages/core/src/v3/traceContext/api.tspackages/core/src/v3/traceContext/manager.tspackages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Use function declarations instead of default exports
Files:
packages/core/src/v3/traceContext/types.tspackages/core/src/v3/traceContext/api.tspackages/core/src/v3/traceContext/manager.tspackages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.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:
packages/core/src/v3/traceContext/types.tspackages/core/src/v3/traceContext/api.tspackages/core/src/v3/traceContext/manager.tspackages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
packages/core/**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (packages/core/CLAUDE.md)
Never import the root package (
@trigger.dev/core). Always use subpath imports such as@trigger.dev/core/v3,@trigger.dev/core/v3/utils,@trigger.dev/core/logger, or@trigger.dev/core/schemas
Files:
packages/core/src/v3/traceContext/types.tspackages/core/src/v3/traceContext/api.tspackages/core/src/v3/traceContext/manager.tspackages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
For public packages, use
buildfor verification.
Files:
packages/core/src/v3/traceContext/types.tspackages/core/src/v3/traceContext/api.tspackages/core/src/v3/traceContext/manager.tspackages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
packages/core/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Import
@trigger.dev/coresubpaths only; never import from the package root.
Files:
packages/core/src/v3/traceContext/types.tspackages/core/src/v3/traceContext/api.tspackages/core/src/v3/traceContext/manager.tspackages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
**/*.{test,spec}.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Use vitest for all tests in the Trigger.dev repository
**/*.{test,spec}.{ts,tsx}: Use Vitest exclusively and never mock dependencies; use Testcontainers for integration dependencies.
Place test files next to the source files they test.
Files:
packages/core/test/externalSpanExporterWrapper.test.ts
🧠 Learnings (13)
📚 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:
packages/core/src/v3/traceContext/types.tspackages/core/src/v3/traceContext/api.tspackages/core/src/v3/traceContext/manager.tspackages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.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:
packages/core/src/v3/traceContext/types.tspackages/core/src/v3/traceContext/api.tspackages/core/src/v3/traceContext/manager.tspackages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma error P1001 ("Can't reach database server") in TypeScript, don’t assume a single error shape. Prisma can surface P1001 via two different error classes/fields: `PrismaClientKnownRequestError` exposes it as `err.code === "P1001"` (common during mid-query connection drops), while `PrismaClientInitializationError` exposes it as `err.errorCode === "P1001"` (common on client startup failure). Therefore, predicates should use `err.code === "P1001" || err.errorCode === "P1001"`. Do not flag `err.code === "P1001"` as “unreachable/never matches,” as it is expected in production.
Applied to files:
packages/core/src/v3/traceContext/types.tspackages/core/src/v3/traceContext/api.tspackages/core/src/v3/traceContext/manager.tspackages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma errors for P1001 ("Can't reach database server"), do not assume it only appears under a single property name. Prisma may surface P1001 via either `PrismaClientKnownRequestError` (`err.code === "P1001"`, e.g., mid-query connection drops) or `PrismaClientInitializationError` (`err.errorCode === "P1001"`, e.g., client startup connection failure). To reliably detect the condition, check `err.code === "P1001" || err.errorCode === "P1001"`, and avoid review rules that would incorrectly flag `err.code === "P1001"` as unreachable/never-matching.
Applied to files:
packages/core/src/v3/traceContext/types.tspackages/core/src/v3/traceContext/api.tspackages/core/src/v3/traceContext/manager.tspackages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
📚 Learning: 2026-06-13T19:53:13.759Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3937
File: packages/trigger-sdk/skills/realtime-and-frontend/SKILL.md:258-260
Timestamp: 2026-06-13T19:53:13.759Z
Learning: When reviewing code that uses `trigger.dev/react-hooks`’s `useRealtimeRun`, preserve the call signature where the first argument is the full realtime handle object (not `handle.id`). This is intentional to maintain type-safety and is consistent with the official docs; do not suggest changing the first argument from the handle object to `handle.id`.
Applied to files:
packages/core/src/v3/traceContext/types.tspackages/core/src/v3/traceContext/api.tspackages/core/src/v3/traceContext/manager.tspackages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
📚 Learning: 2026-06-17T17:13:49.929Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3948
File: apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.bulk-actions.$bulkActionParam/route.tsx:48-62
Timestamp: 2026-06-17T17:13:49.929Z
Learning: In triggerdotdev/trigger.dev, within `dashboardLoader`/`dashboardAction` (or similar context resolver code) whenever you resolve an organization ID from an organization slug for RBAC/enterprise authorization scope, always read from the primary Prisma client (`prisma`), not `$replica`. Using `$replica` can hit replica-lag and cause the RBAC lookup/authorization to run without the correct org scope (bypassing intended role enforcement). Implement the slug→org lookup with `prisma.organization.findFirst(...)` (or equivalent primary-client query) and add an inline comment documenting why the primary client is required (replica lag could lead to unscoped RBAC checks).
Applied to files:
packages/core/src/v3/traceContext/types.tspackages/core/src/v3/traceContext/api.tspackages/core/src/v3/traceContext/manager.tspackages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
📚 Learning: 2026-06-23T13:04:21.413Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4023
File: apps/webapp/app/services/upsertBranch.server.ts:14-18
Timestamp: 2026-06-23T13:04:21.413Z
Learning: In TypeScript, it’s valid to `import { type X }` and then use `typeof X` in a type-only position, e.g. `type Alias = z.infer<typeof X>`. The `type` modifier suppresses the runtime import, but the type checker still has the full exported type so `z.infer<typeof X>` can resolve correctly. In code reviews, don’t flag this as a TypeScript compile error as long as `typeof X` is used in a type context (e.g., with `z.infer`, `type` aliases, generics), not as a runtime value.
Applied to files:
packages/core/src/v3/traceContext/types.tspackages/core/src/v3/traceContext/api.tspackages/core/src/v3/traceContext/manager.tspackages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
📚 Learning: 2026-06-04T18:16:35.386Z
Learnt from: nicktrn
Repo: triggerdotdev/trigger.dev PR: 3836
File: apps/supervisor/src/backpressure/backpressureMonitor.ts:3-5
Timestamp: 2026-06-04T18:16:35.386Z
Learning: When reviewing TypeScript in this repo, apply the rule “prefer type aliases over interfaces” only to data/object shapes and union/intersection type modeling. If an interface is being used as a behavioral contract for collaborators to implement (e.g., method-shape interfaces that define required behavior, such as `BackpressureLogger` / `BackpressureSignalSource` in `apps/supervisor/src/backpressure/backpressureMonitor.ts`), keep it as an `interface` and do not flag it as a type-alias-vs-interface violation.
Applied to files:
packages/core/src/v3/traceContext/types.tspackages/core/src/v3/traceContext/api.tspackages/core/src/v3/traceContext/manager.tspackages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
📚 Learning: 2026-06-09T17:58:04.699Z
Learnt from: 0ski
Repo: triggerdotdev/trigger.dev PR: 3879
File: apps/webapp/app/models/vercelIntegration.server.ts:619-630
Timestamp: 2026-06-09T17:58:04.699Z
Learning: In this codebase, outbound raw `fetch` calls should typically rely on Node/undici’s default request timeout (about ~300s) rather than adding a per-call `AbortController` + `setTimeout` wrapper inside individual functions (e.g. in files like `apps/webapp/app/models/vercelIntegration.server.ts`). During code review, do not flag the absence of a per-call timeout on a single `fetch` as an issue; if per-call timeouts are needed, they should be implemented via a codebase-wide convention (e.g., a shared fetch wrapper or documented pattern) rather than ad-hoc per-function changes.
Applied to files:
packages/core/src/v3/traceContext/types.tspackages/core/src/v3/traceContext/api.tspackages/core/src/v3/traceContext/manager.tspackages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
📚 Learning: 2026-05-18T14:40:02.173Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3658
File: packages/core/src/v3/realtimeStreams/manager.test.ts:1-147
Timestamp: 2026-05-18T14:40:02.173Z
Learning: In this repo’s trigger.dev codebase, the “never mock — use testcontainers” guideline should only be applied to integration tests that talk to real external services (e.g., Redis, Postgres, S2). For unit tests that validate in-memory logic (e.g., deduplication/cache behavior in StandardRealtimeStreamsManager and similar module-boundary call counting), it is allowed to use Vitest mocks like `vi.fn()` and to stub/mock `ApiClient` objects to count calls or simulate in-process collaborators. Do not flag `vi.fn()`-based mocks as policy violations in these unit-test scenarios; reserve the rule for true external-service integration tests.
Applied to files:
packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-05-18T14:40:02.173Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3658
File: packages/core/src/v3/realtimeStreams/manager.test.ts:1-147
Timestamp: 2026-05-18T14:40:02.173Z
Learning: In the triggerdotdev/trigger.dev repo, the policy “Never mock anything — use testcontainers instead” should only be enforced for integration tests that interact with real external services (e.g., Redis, Postgres) via actual infrastructure. For unit tests that exercise pure in-memory logic (e.g., cache semantics) it is OK to stub collaborators such as `ApiClient` using Vitest (`vi.fn()`) to assert call counts or control behavior. Do not flag `vi.fn()`-based `ApiClient` stubs in unit tests as violations of the testcontainers policy.
Applied to files:
packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-05-28T10:30:48.203Z
Learnt from: nicktrn
Repo: triggerdotdev/trigger.dev PR: 3768
File: packages/core/test/externalSpanExporterWrapper.test.ts:1-7
Timestamp: 2026-05-28T10:30:48.203Z
Learning: In the `triggerdotdev/trigger.dev` repository, treat `packages/core/test/` as the established convention for `packages/core` test files. When reviewing `packages/core`, do not flag newly added test files under `packages/core/test/` (e.g., `*.test.ts`) as violating any “colocated tests” or similar guideline—tests should continue to be added there for consistency.
Applied to files:
packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-06-16T09:19:47.637Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3960
File: apps/webapp/test/prismaInfrastructureErrorCapture.test.ts:0-0
Timestamp: 2026-06-16T09:19:47.637Z
Learning: In this repo’s Vitest setup, `vitest.config.ts` uses `globals: true`, so identifiers like `vi`, `describe`, `it`, and `expect` are available as globals in Vitest test files. During code review, do not flag missing `vi`/`describe`/`it`/`expect` imports as a runtime error or correctness issue when they’re used in `*.test.ts/tsx` or `*.spec.ts/tsx` files. Explicit imports are still preferred for consistency, but they’re not required for runtime behavior.
Applied to files:
packages/core/test/externalSpanExporterWrapper.test.ts
🪛 OpenGrep (1.26.0)
packages/core/test/externalSpanExporterWrapper.test.ts
[ERROR] 15-15: Possible credit card number (PAN) detected in source code. Credit card numbers should never be hardcoded or stored in source files. Use a secrets manager or tokenization service instead.
(coderabbit.pii.credit-card-number)
🔇 Additional comments (6)
packages/core/test/externalSpanExporterWrapper.test.ts (1)
2-16: LGTM!Also applies to: 45-56, 70-103, 113-113, 128-262
.changeset/external-trace-id-per-run.md (1)
1-5: LGTM!packages/core/src/v3/traceContext/types.ts (1)
5-10: LGTM!packages/core/src/v3/traceContext/manager.ts (1)
7-28: LGTM!packages/core/src/v3/traceContext/api.ts (1)
13-16: LGTM!Also applies to: 65-67
packages/core/src/v3/otel/tracingSDK.ts (1)
165-183: LGTM!Also applies to: 235-250
f837ccc to
3331b42
Compare
Runs that carry no external trace context (schedules, task-to-task triggers) fall back to a trace id generated once in the TracingSDK constructor. With `experimental_processKeepAlive` the TracingSDK outlives the run, so every run on a warm process was exported to the external OTLP endpoint under that one id, merging unrelated runs into a single trace. Across our production traces, 80.3% contained spans from more than one run, worst case 25. This is the same warm-start hazard c043c4a fixed for the external context path, which read the context live but deliberately left the fallback captured at construction. Key the fallback off the internal trace id that every span and log record of a run already carries, rather than off ambient state. Batch processors drain asynchronously, so a run's records are routinely exported after the next run has started; deciding the id at export time from whatever run is current would stamp the earlier run's records with the later run's id. Letting the record decide sidesteps the timing entirely, and makes a run's spans and logs agree without coordinating. The map is bounded, since a warm process serves unboundedly many runs and only the in-flight ones can still have records to export. An empty configured id still means external export is off. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
3331b42 to
e840eb0
Compare
|
@coderabbitai Good catch, and it sent me back to the drawing board — fixed in e840eb0. You're right that Rather than bind at export time, I removed the ambient read entirely. The fallback id is now keyed off the internal trace id that every span and log record of a run already carries, so the record decides its own id no matter when it drains. That also drops the interface change I'd previously made to Added the regression test you asked for: Also added a bound on the map, since a warm process serves unboundedly many runs. |
|
Tip For best results, initiate chat on the files or code changes.
The new regression test covers the failure mode I identified. The bounded map also prevents unbounded retention on warm workers. 🐇 ✅ ✏️ Learnings added
If you found this review helpful, would you consider giving us a shout-out on X? Thank you for using CodeRabbit! You are interacting with an AI system. |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/core/src/v3/otel/tracingSDK.ts (1)
470-490: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy liftRemove exporter-time ambient trace-context lookup.
A delayed record can observe a later run's external context and receive that run's trace ID. This reintroduces the warm-worker attribution bug.
packages/core/src/v3/otel/tracingSDK.ts#L470-L490: resolve trace identity from record-associated state, nottraceContext.getExternalTraceContext().packages/core/src/v3/otel/tracingSDK.ts#L554-L603: apply the same record-scoped resolution for log records.packages/core/test/externalSpanExporterWrapper.test.ts#L177-L200: setmanager.traceContext.external.traceparentso the test fails against the current ambient lookup.Based on PR objective: exporter callbacks must not use ambient trace context.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 653f5e03-1361-4822-a5c5-37d33932b6bf
📒 Files selected for processing (2)
packages/core/src/v3/otel/tracingSDK.tspackages/core/test/externalSpanExporterWrapper.test.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (27)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (2, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (11, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (3, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (9, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (7, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (12, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (4, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (5, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (1, 12)
- GitHub Check: packages / 🧪 Unit Tests: Packages (2, 3)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (8, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (6, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (10, 12)
- GitHub Check: sdk-compat / Cloudflare Workers
- GitHub Check: sdk-compat / Deno Runtime
- GitHub Check: sdk-compat / Node.js 26.4 (warp-ubuntu-latest-x64-4x)
- GitHub Check: e2e-webapp / 🧪 E2E Tests: Webapp
- GitHub Check: packages / 🧪 Unit Tests: Packages (1, 3)
- GitHub Check: sdk-compat / Bun Runtime
- GitHub Check: sdk-compat / Node.js 24.18 (warp-ubuntu-latest-x64-4x)
- GitHub Check: packages / 🧪 Unit Tests: Packages (3, 3)
- GitHub Check: e2e / 🧪 CLI v3 tests (warp-windows-latest-x64-8x - npm)
- GitHub Check: e2e / 🧪 CLI v3 tests (warp-windows-latest-x64-8x - pnpm)
- GitHub Check: runops-guard / runops-guard
- GitHub Check: internal / 🧪 Unit Tests: Internal
- GitHub Check: typecheck / typecheck
- GitHub Check: code-quality / code-quality
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{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
**/*.{ts,tsx}: Prefer static imports over dynamicimport(); use dynamic imports only for unresolvable circular dependencies, genuine performance code splitting, or conditional runtime loading.
Import Trigger.dev tasks from@trigger.dev/sdk; never use@trigger.dev/sdk/v3or deprecatedclient.defineJob.
Add agentcrumbs while writing code using approved namespaces; mark lines with//@Crumbsor blocks with `// `#region` `@crumbs, and strip them before merging.
Files:
packages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.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:
packages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Use function declarations instead of default exports
Files:
packages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
**/*.{test,spec}.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Use vitest for all tests in the Trigger.dev repository
**/*.{test,spec}.{ts,tsx}: Use Vitest exclusively and never mock dependencies; use Testcontainers for integration dependencies.
Place test files next to the source files they test.
Files:
packages/core/test/externalSpanExporterWrapper.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:
packages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
packages/core/**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (packages/core/CLAUDE.md)
Never import the root package (
@trigger.dev/core). Always use subpath imports such as@trigger.dev/core/v3,@trigger.dev/core/v3/utils,@trigger.dev/core/logger, or@trigger.dev/core/schemas
Files:
packages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
For public packages, use
buildfor verification.
Files:
packages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
packages/core/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Import
@trigger.dev/coresubpaths only; never import from the package root.
Files:
packages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
🧠 Learnings (13)
📚 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:
packages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.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:
packages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma error P1001 ("Can't reach database server") in TypeScript, don’t assume a single error shape. Prisma can surface P1001 via two different error classes/fields: `PrismaClientKnownRequestError` exposes it as `err.code === "P1001"` (common during mid-query connection drops), while `PrismaClientInitializationError` exposes it as `err.errorCode === "P1001"` (common on client startup failure). Therefore, predicates should use `err.code === "P1001" || err.errorCode === "P1001"`. Do not flag `err.code === "P1001"` as “unreachable/never matches,” as it is expected in production.
Applied to files:
packages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma errors for P1001 ("Can't reach database server"), do not assume it only appears under a single property name. Prisma may surface P1001 via either `PrismaClientKnownRequestError` (`err.code === "P1001"`, e.g., mid-query connection drops) or `PrismaClientInitializationError` (`err.errorCode === "P1001"`, e.g., client startup connection failure). To reliably detect the condition, check `err.code === "P1001" || err.errorCode === "P1001"`, and avoid review rules that would incorrectly flag `err.code === "P1001"` as unreachable/never-matching.
Applied to files:
packages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
📚 Learning: 2026-06-13T19:53:13.759Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3937
File: packages/trigger-sdk/skills/realtime-and-frontend/SKILL.md:258-260
Timestamp: 2026-06-13T19:53:13.759Z
Learning: When reviewing code that uses `trigger.dev/react-hooks`’s `useRealtimeRun`, preserve the call signature where the first argument is the full realtime handle object (not `handle.id`). This is intentional to maintain type-safety and is consistent with the official docs; do not suggest changing the first argument from the handle object to `handle.id`.
Applied to files:
packages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
📚 Learning: 2026-06-17T17:13:49.929Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3948
File: apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.bulk-actions.$bulkActionParam/route.tsx:48-62
Timestamp: 2026-06-17T17:13:49.929Z
Learning: In triggerdotdev/trigger.dev, within `dashboardLoader`/`dashboardAction` (or similar context resolver code) whenever you resolve an organization ID from an organization slug for RBAC/enterprise authorization scope, always read from the primary Prisma client (`prisma`), not `$replica`. Using `$replica` can hit replica-lag and cause the RBAC lookup/authorization to run without the correct org scope (bypassing intended role enforcement). Implement the slug→org lookup with `prisma.organization.findFirst(...)` (or equivalent primary-client query) and add an inline comment documenting why the primary client is required (replica lag could lead to unscoped RBAC checks).
Applied to files:
packages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
📚 Learning: 2026-06-23T13:04:21.413Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4023
File: apps/webapp/app/services/upsertBranch.server.ts:14-18
Timestamp: 2026-06-23T13:04:21.413Z
Learning: In TypeScript, it’s valid to `import { type X }` and then use `typeof X` in a type-only position, e.g. `type Alias = z.infer<typeof X>`. The `type` modifier suppresses the runtime import, but the type checker still has the full exported type so `z.infer<typeof X>` can resolve correctly. In code reviews, don’t flag this as a TypeScript compile error as long as `typeof X` is used in a type context (e.g., with `z.infer`, `type` aliases, generics), not as a runtime value.
Applied to files:
packages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
📚 Learning: 2026-05-18T14:40:02.173Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3658
File: packages/core/src/v3/realtimeStreams/manager.test.ts:1-147
Timestamp: 2026-05-18T14:40:02.173Z
Learning: In this repo’s trigger.dev codebase, the “never mock — use testcontainers” guideline should only be applied to integration tests that talk to real external services (e.g., Redis, Postgres, S2). For unit tests that validate in-memory logic (e.g., deduplication/cache behavior in StandardRealtimeStreamsManager and similar module-boundary call counting), it is allowed to use Vitest mocks like `vi.fn()` and to stub/mock `ApiClient` objects to count calls or simulate in-process collaborators. Do not flag `vi.fn()`-based mocks as policy violations in these unit-test scenarios; reserve the rule for true external-service integration tests.
Applied to files:
packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-05-18T14:40:02.173Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3658
File: packages/core/src/v3/realtimeStreams/manager.test.ts:1-147
Timestamp: 2026-05-18T14:40:02.173Z
Learning: In the triggerdotdev/trigger.dev repo, the policy “Never mock anything — use testcontainers instead” should only be enforced for integration tests that interact with real external services (e.g., Redis, Postgres) via actual infrastructure. For unit tests that exercise pure in-memory logic (e.g., cache semantics) it is OK to stub collaborators such as `ApiClient` using Vitest (`vi.fn()`) to assert call counts or control behavior. Do not flag `vi.fn()`-based `ApiClient` stubs in unit tests as violations of the testcontainers policy.
Applied to files:
packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-05-28T10:30:48.203Z
Learnt from: nicktrn
Repo: triggerdotdev/trigger.dev PR: 3768
File: packages/core/test/externalSpanExporterWrapper.test.ts:1-7
Timestamp: 2026-05-28T10:30:48.203Z
Learning: In the `triggerdotdev/trigger.dev` repository, treat `packages/core/test/` as the established convention for `packages/core` test files. When reviewing `packages/core`, do not flag newly added test files under `packages/core/test/` (e.g., `*.test.ts`) as violating any “colocated tests” or similar guideline—tests should continue to be added there for consistency.
Applied to files:
packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-06-04T18:16:35.386Z
Learnt from: nicktrn
Repo: triggerdotdev/trigger.dev PR: 3836
File: apps/supervisor/src/backpressure/backpressureMonitor.ts:3-5
Timestamp: 2026-06-04T18:16:35.386Z
Learning: When reviewing TypeScript in this repo, apply the rule “prefer type aliases over interfaces” only to data/object shapes and union/intersection type modeling. If an interface is being used as a behavioral contract for collaborators to implement (e.g., method-shape interfaces that define required behavior, such as `BackpressureLogger` / `BackpressureSignalSource` in `apps/supervisor/src/backpressure/backpressureMonitor.ts`), keep it as an `interface` and do not flag it as a type-alias-vs-interface violation.
Applied to files:
packages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
📚 Learning: 2026-06-09T17:58:04.699Z
Learnt from: 0ski
Repo: triggerdotdev/trigger.dev PR: 3879
File: apps/webapp/app/models/vercelIntegration.server.ts:619-630
Timestamp: 2026-06-09T17:58:04.699Z
Learning: In this codebase, outbound raw `fetch` calls should typically rely on Node/undici’s default request timeout (about ~300s) rather than adding a per-call `AbortController` + `setTimeout` wrapper inside individual functions (e.g. in files like `apps/webapp/app/models/vercelIntegration.server.ts`). During code review, do not flag the absence of a per-call timeout on a single `fetch` as an issue; if per-call timeouts are needed, they should be implemented via a codebase-wide convention (e.g., a shared fetch wrapper or documented pattern) rather than ad-hoc per-function changes.
Applied to files:
packages/core/test/externalSpanExporterWrapper.test.tspackages/core/src/v3/otel/tracingSDK.ts
📚 Learning: 2026-06-16T09:19:47.637Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3960
File: apps/webapp/test/prismaInfrastructureErrorCapture.test.ts:0-0
Timestamp: 2026-06-16T09:19:47.637Z
Learning: In this repo’s Vitest setup, `vitest.config.ts` uses `globals: true`, so identifiers like `vi`, `describe`, `it`, and `expect` are available as globals in Vitest test files. During code review, do not flag missing `vi`/`describe`/`it`/`expect` imports as a runtime error or correctness issue when they’re used in `*.test.ts/tsx` or `*.spec.ts/tsx` files. Explicit imports are still preferred for consistency, but they’re not required for runtime behavior.
Applied to files:
packages/core/test/externalSpanExporterWrapper.test.ts
🪛 OpenGrep (1.26.0)
packages/core/test/externalSpanExporterWrapper.test.ts
[ERROR] 15-15: Possible credit card number (PAN) detected in source code. Credit card numbers should never be hardcoded or stored in source files. Use a secrets manager or tokenization service instead.
(coderabbit.pii.credit-card-number)
🔇 Additional comments (2)
packages/core/src/v3/otel/tracingSDK.ts (1)
165-183: LGTM!Also applies to: 235-250, 397-462
packages/core/test/externalSpanExporterWrapper.test.ts (1)
2-116: LGTM!Also applies to: 131-171, 202-261
✅ Checklist
Problem
Runs that carry no external trace context (schedules, task-to-task triggers, anything not started from an incoming
traceparent) fall back to a generated external trace id. That id is generated once, in theTracingSDKconstructor:https://github.com/triggerdotdev/trigger.dev/blob/main/packages/core/src/v3/otel/tracingSDK.ts#L165
With
experimental_processKeepAliveenabled, theTracingSDKoutlives the run, so every run that executes on a warm process is exported to the external OTLP endpoint under that same trace id and unrelated runs get merged into one trace on the receiving backend.This is the same warm-start hazard that c043c4a fixed for the external-context path. That commit made the wrappers read
traceContext.getExternalTraceContext()live instead of capturing it at construction, but deliberately left the fallback captured, so the bug survives for exactly the runs that have no external context.What it looks like in production
We export to a self-hosted Langfuse via
telemetry.exporters. Measured over our production traces:Per-trace cost and latency attribution is meaningless as a result: a trace shows an unrelated mix of workloads, and drilling into one run is impossible.
Disabling
experimental_processKeepAliveavoids it, but that is a significant throughput regression and not a real option for us.Fix
FallbackExternalTraceIdhands out one generated id per run, keyed by the internal trace id that every span and log record of a run already carries.TracingSDKconstructs one instance and passes it to everyExternalSpanExporterWrapperandExternalLogRecordExporterWrapper.Keying off the record rather than off ambient state is the part that matters. Batch processors drain asynchronously, so a run's records are routinely exported after the next run has already started. Anything that decides the id at export time by asking "which run is current?" will stamp the earlier run's records with the later run's id — reintroducing the merge this is meant to fix, just in a narrower window. Letting the record decide removes the timing question completely, and has the side benefit that a run's spans and logs agree without the two exporters having to coordinate.
The map is bounded (
MAX_TRACKED_INTERNAL_TRACES), since a warm process serves unboundedly many runs over its life while only the in-flight ones can still have records to export. Eviction is oldest-first.One behaviour held deliberately: an empty configured id still means external export is off, so it short-circuits rather than minting an id and switching the feature on for a deployment that never asked for it. The id generated in the constructor is used for the first run, so it isn't thrown away.
Cost / benefit
This touches core tracing, so the trade-off in full:
Benefit. Per-run attribution in external observability backends is restored for every run that doesn't continue an incoming trace. For anyone running
experimental_processKeepAlivewithtelemetry.exporters, that is currently most of their traces.Blast radius. The wrappers are only constructed when
exporters/logExportersare configured, so deployments that don't export externally are untouched. Nothing outsidetracingSDK.tschanges — no interface changes, no changes to the trace context manager.Risk. The main assumption is that a run's records share one internal trace id, which holds because a run without external context roots its own trace. If a run somehow produced two internal traces it would appear as two external traces rather than merging with another run, so the failure mode degrades toward splitting rather than merging.
Testing
Ran locally against this branch, rebased on current
main:pnpm exec vitest runinpackages/core— 45 files, 674 tests, all passingpnpm run formatandpnpm run lint:fix— no diff producedpnpm exec oxfmt --check .— cleanpackages/core/test/externalSpanExporterWrapper.test.tscovers:Each was mutation-checked rather than just observed passing. Keying off ambient state instead of the record fails three of them, including the late-drain case; removing the eviction bound fails the bounding test.
The test harness needed one fix to make any of this meaningful.
traceContext.setGlobalManager()delegates toregisterGlobal, which ignores a second registration, so the existingbeforeEachonly ever installed the first test's manager and every later test was mutating an object that was no longer global. CallingtraceContext.disable()first makes each test's manager actually take effect.A note on CI
The five failing
webappunit test shards are the ones containingcontainerTestsuites, and they fail for a reason outside this change: fork PRs don't receive repository secrets, sounit-tests-webapp.ymlskips the DockerHub login and the "Pre-pull testcontainer images" step (both are gated onenv.DOCKERHUB_USERNAME). The container tests then time out at 60s pulling images anonymously. The same five shards failed identically across two runs, and every failure isTest timed out in 60000msin a container-backed test. Happy to be told otherwise if you can run them with secrets available.Changelog
Runs that don't continue an incoming trace are no longer merged into one trace when they execute on the same warm worker process. Each run now appears as its own trace in your external observability tool.
Screenshots
n/a
Supersedes #4526 and #4533. The first was auto-closed before I was vouched, the second because I opened it ready-for-review rather than as a draft; GitHub won't let either reopen. Devin's findings on #4526 are addressed here.