Skip to content

fix(core): mint the fallback external trace id per run - #4534

Draft
NERLOE wants to merge 1 commit into
triggerdotdev:mainfrom
NERLOE:fix/external-trace-id-per-run
Draft

fix(core): mint the fallback external trace id per run#4534
NERLOE wants to merge 1 commit into
triggerdotdev:mainfrom
NERLOE:fix/external-trace-id-per-run

Conversation

@NERLOE

@NERLOE NERLOE commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

✅ Checklist

  • I have followed every step in the contributing guide
  • The PR title follows the convention.
  • I ran and tested the code works

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 the TracingSDK constructor:

https://github.com/triggerdotdev/trigger.dev/blob/main/packages/core/src/v3/otel/tracingSDK.ts#L165

With experimental_processKeepAlive enabled, the TracingSDK outlives 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:

  • 80.3% of traces contain spans from more than one Trigger run
  • worst case: 25 distinct runs collapsed into a single trace

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_processKeepAlive avoids it, but that is a significant throughput regression and not a real option for us.

Fix

FallbackExternalTraceId hands out one generated id per run, keyed by the internal trace id that every span and log record of a run already carries. TracingSDK constructs one instance and passes it to every ExternalSpanExporterWrapper and ExternalLogRecordExporterWrapper.

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_processKeepAlive with telemetry.exporters, that is currently most of their traces.

Blast radius. The wrappers are only constructed when exporters / logExporters are configured, so deployments that don't export externally are untouched. Nothing outside tracingSDK.ts changes — 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 run in packages/core — 45 files, 673 tests, all passing
  • pnpm run format and pnpm run lint:fix — no diff produced
  • pnpm exec oxfmt --check . — clean

packages/core/test/externalSpanExporterWrapper.test.ts covers:

  • gives each run its own fallback trace id when there is no external context
  • keeps one fallback trace id across every export within a run
  • stamps records with their own run's id even when exported after the next run started (drives the span and log wrappers together, so it also covers those two agreeing)
  • leaves external export off when no external trace id was configured
  • bounds how many runs it remembers

Each was mutation-checked rather than just observed passing. Keying off ambient state instead of the record fails three of them; pointing the log wrapper at a different key fails 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 to registerGlobal, which ignores a second registration, so the existing beforeEach only ever installed the first test's manager and every later test was mutating an object that was no longer global. Calling traceContext.disable() first makes each test's manager actually take effect.

A note on CI

The five failing webapp unit test shards are the ones containing containerTest suites, and they fail for a reason outside this change: fork PRs don't receive repository secrets, so unit-tests-webapp.yml skips the DockerHub login and the "Pre-pull testcontainer images" step (both are gated on env.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 is Test timed out in 60000ms in 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.

@changeset-bot

changeset-bot Bot commented Aug 7, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: c379df4

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 27 packages
Name Type
@trigger.dev/core Patch
@trigger.dev/build Patch
trigger.dev Patch
@trigger.dev/python Patch
@trigger.dev/redis-worker Patch
@trigger.dev/schema-to-json Patch
@trigger.dev/sdk Patch
@internal/cache Patch
@internal/clickhouse Patch
@internal/llm-model-catalog Patch
@internal/metrics-pipeline Patch
@trigger.dev/rbac Patch
@internal/redis Patch
@internal/replication Patch
@internal/run-engine Patch
@internal/run-store Patch
@internal/schedule-engine Patch
@trigger.dev/sso Patch
@internal/testcontainers Patch
@internal/tracing Patch
@internal/tsql Patch
@internal/dashboard-agent Patch
@internal/sdk-compat-tests Patch
@trigger.dev/react-hooks Patch
@trigger.dev/rsc Patch
@trigger.dev/database Patch
@trigger.dev/otlp-importer Patch

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

@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 687a4c65-f577-4be2-b80b-b10e5f8f16fd

📥 Commits

Reviewing files that changed from the base of the PR and between 82e03ee and c379df4.

📒 Files selected for processing (2)
  • packages/core/src/v3/otel/tracingSDK.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
📜 Recent review details
⏰ Context from checks skipped due to timeout. (27)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (5, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (6, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (3, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (12, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (2, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (9, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (7, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (11, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (10, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (8, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (1, 12)
  • GitHub Check: sdk-compat / Node.js 26.4 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (4, 12)
  • GitHub Check: e2e / 🧪 CLI v3 tests (warp-windows-latest-x64-8x - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (warp-windows-latest-x64-8x - npm)
  • GitHub Check: sdk-compat / Cloudflare Workers
  • GitHub Check: sdk-compat / Node.js 24.18 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: sdk-compat / Bun Runtime
  • GitHub Check: typecheck / typecheck
  • GitHub Check: sdk-compat / Deno Runtime
  • GitHub Check: e2e-webapp / 🧪 E2E Tests: Webapp
  • GitHub Check: runops-guard / runops-guard
  • GitHub Check: internal / 🧪 Unit Tests: Internal
  • GitHub Check: packages / 🧪 Unit Tests: Packages (1, 3)
  • GitHub Check: packages / 🧪 Unit Tests: Packages (2, 3)
  • GitHub Check: packages / 🧪 Unit Tests: Packages (3, 3)
  • 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 dynamic import(); 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/v3 or deprecated client.defineJob.
Add agentcrumbs while writing code using approved namespaces; mark lines with // @Crumbs or blocks with `// `#region` `@crumbs, and strip them before merging.

Files:

  • packages/core/src/v3/otel/tracingSDK.ts
  • packages/core/test/externalSpanExporterWrapper.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:

  • packages/core/src/v3/otel/tracingSDK.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
**/*.{ts,tsx,js,jsx}

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

Use function declarations instead of default exports

Files:

  • packages/core/src/v3/otel/tracingSDK.ts
  • 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/src/v3/otel/tracingSDK.ts
  • packages/core/test/externalSpanExporterWrapper.test.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/otel/tracingSDK.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

For public packages, use build for verification.

Files:

  • packages/core/src/v3/otel/tracingSDK.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
packages/core/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Import @trigger.dev/core subpaths only; never import from the package root.

Files:

  • packages/core/src/v3/otel/tracingSDK.ts
  • packages/core/test/externalSpanExporterWrapper.test.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 (27)
📚 Learning: 2026-08-07T14:52:19.054Z
Learnt from: NERLOE
Repo: triggerdotdev/trigger.dev PR: 0
File: :0-0
Timestamp: 2026-08-07T14:52:19.054Z
Learning: In `packages/core/src/v3/otel/tracingSDK.ts`, external fallback trace IDs must be derived from the internal trace ID carried by each span or log record. Do not resolve the fallback ID from ambient trace context during exporter callbacks, because records can export after a later run has replaced that context.

Applied to files:

  • packages/core/src/v3/otel/tracingSDK.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-05-07T12:25:21.024Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3531
File: apps/webapp/test/sentryTraceContext.server.test.ts:9-47
Timestamp: 2026-05-07T12:25:21.024Z
Learning: In the triggerdotdev/trigger.dev webapp test suite, `createInMemoryTracing()` calls that register a `NodeTracerProvider` globally are intentionally left without `afterEach`/`afterAll` teardown. This is consistent across tests like `runsReplicationService.part1.test.ts`, `runsBackfiller.test.ts`, and `runsReplicationBenchmark.test.ts`. The "returns undefined when no OTel span is active" pattern is safe because `trace.getActiveSpan()` outside a `context.with(...)` block reads from `AsyncLocalStorage.getStore()` (undefined when no `run()` is in scope), falling back to `ROOT_CONTEXT` with no attached span — regardless of which provider is registered. Do not flag missing OTel provider teardown in webapp tests as a test-ordering risk.

Applied to files:

  • packages/core/src/v3/otel/tracingSDK.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-03-02T12:43:25.254Z
Learnt from: CR
Repo: triggerdotdev/trigger.dev PR: 0
File: internal-packages/run-engine/CLAUDE.md:0-0
Timestamp: 2026-03-02T12:43:25.254Z
Learning: Applies to internal-packages/run-engine/src/engine/systems/**/*.ts : Integrate OpenTelemetry tracer and meter instrumentation in RunEngine systems for observability

Applied to files:

  • packages/core/src/v3/otel/tracingSDK.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 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/otel/tracingSDK.ts
  • packages/core/test/externalSpanExporterWrapper.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:

  • packages/core/src/v3/otel/tracingSDK.ts
  • packages/core/test/externalSpanExporterWrapper.test.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/otel/tracingSDK.ts
  • packages/core/test/externalSpanExporterWrapper.test.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/otel/tracingSDK.ts
  • packages/core/test/externalSpanExporterWrapper.test.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/otel/tracingSDK.ts
  • packages/core/test/externalSpanExporterWrapper.test.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/otel/tracingSDK.ts
  • packages/core/test/externalSpanExporterWrapper.test.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/otel/tracingSDK.ts
  • 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/src/v3/otel/tracingSDK.ts
  • packages/core/test/externalSpanExporterWrapper.test.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/otel/tracingSDK.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-07-27T15:07:14.579Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 4397
File: apps/webapp/test/batchStreamGrants.test.ts:0-0
Timestamp: 2026-07-27T15:07:14.579Z
Learning: In `triggerdotdev/trigger.dev`, `apps/webapp/test/authorizationRateLimitMiddleware.test.ts` remains skipped because correcting its plaintext Redis fixture setup (`tlsDisabled`) exposed a timing-sensitive sliding-window test based on real 10-second windows. The new authorization-rate-limit bypass coverage instead lives in the unskipped, deterministic `apps/webapp/test/authorizationRateLimitMiddlewareBypass.test.ts`. Do not flag the legacy suite's continued skip as missing coverage for the bypass behavior.

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-07-18T18:31:37.633Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 4285
File: internal-packages/run-store/src/runOpsStore.presentersWaitpointReadView.replicaLag.test.ts:24-65
Timestamp: 2026-07-18T18:31:37.633Z
Learning: In `triggerdotdev/trigger.dev`’s `internal-packages/run-store/src/runOpsStore.presentersWaitpointReadView.replicaLag.test.ts`, retain the local real-Testcontainers Prisma proxy rather than requiring the shared `laggingReplica` helper: the test must simulate lag for `waitpointTag` reads and for `findWaitpointConnectedRunIds`, which uses `$queryRaw`. The shared primitive intercepts configured Prisma models but not raw queries, so replacing the proxy would allow the live raw join to observe primary data and invalidate the replica-lag guard. The related taskRun-only tests (`runOpsStore.realtimeServicesReadView.replicaLag.test.ts`, `runOpsStore.replayReadAfterWrite.replicaLag.test.ts`, and `runOpsStore.resolveRunForMutationReplicaLag.test.ts`) can use the shared primitive with `{ model: "taskRun", mode: "missing" }`.

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-03-02T12:43:25.254Z
Learnt from: CR
Repo: triggerdotdev/trigger.dev PR: 0
File: internal-packages/run-engine/CLAUDE.md:0-0
Timestamp: 2026-03-02T12:43:25.254Z
Learning: Applies to internal-packages/run-engine/src/engine/tests/**/*.test.ts : Implement tests for RunEngine in `src/engine/tests/` using testcontainers for Redis and PostgreSQL containerization

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-07-18T18:31:43.376Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 4285
File: internal-packages/run-engine/src/engine/tests/runAttemptSystemReplicaLag.guard.test.ts:30-92
Timestamp: 2026-07-18T18:31:43.376Z
Learning: In `internal-packages/run-engine/src/engine/tests/runAttemptSystemReplicaLag.guard.test.ts`, retain the bespoke `laggingReadReplica` proxy for the retry-decision and usage read-modify-write tests. It must fabricate distinct stale `taskRun.findFirst` scalar snapshots only for their exact `select` shapes while all other reads remain live; the shared `laggingReplica` primitive cannot express projection-specific lag. Use the shared primitive separately for whole-row missing replica behavior.

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-03-03T13:07:33.177Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3166
File: internal-packages/run-engine/src/batch-queue/tests/index.test.ts:711-713
Timestamp: 2026-03-03T13:07:33.177Z
Learning: In `internal-packages/run-engine/src/batch-queue/tests/index.test.ts`, test assertions for rate limiter stubs can use `toBeGreaterThanOrEqual` rather than exact equality (`toBe`) because the consumer loop may call the rate limiter during empty pops in addition to actual item processing, and this over-calling is acceptable in integration tests.

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-04-16T13:45:22.317Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3368
File: apps/webapp/test/engine/taskIdentifierRegistry.test.ts:3-19
Timestamp: 2026-04-16T13:45:22.317Z
Learning: In `apps/webapp/test/engine/taskIdentifierRegistry.test.ts`, the `vi.mock` calls for `~/services/taskIdentifierCache.server` (stubbing `getTaskIdentifiersFromCache` and `populateTaskIdentifierCache`), `~/models/task.server` (stubbing `getAllTaskIdentifiers`), and `~/db.server` (stubbing `prisma` and `$replica`) are intentional. The suite uses real Postgres via testcontainers for all `TaskIdentifier` DB operations, but isolates the Redis cache layer and legacy query fallback as separate concerns not exercised in this test file. Do not flag these mocks as violations of the no-mocks policy in future reviews.

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-07-18T18:17:26.381Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 4285
File: internal-packages/run-store/src/runOpsStore.sessionRunProbeReadAfterWrite.test.ts:154-182
Timestamp: 2026-07-18T18:17:26.381Z
Learning: For session-run replica-lag coverage, `internal-packages/run-store/src/runOpsStore.sessionRunProbeReadAfterWrite.test.ts` intentionally characterizes only the `RoutingRunStore.findRun` store seam: an owning-replica miss followed by a writer read recovers the live run. The behavioral no-double-trigger contract belongs in `apps/webapp/test/realtimeServices.replicaLag.test.ts`, which invokes the real exported `ensureRunForSession` and asserts reuse (`triggered: false`) with zero `TriggerTaskService` calls.

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-07-18T13:08:53.789Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 4284
File: internal-packages/run-store/src/runOpsStore.batchDependentAttemptReadView.replicaLag.test.ts:232-241
Timestamp: 2026-07-18T13:08:53.789Z
Learning: For the batch-dependent-attempt validation in `apps/webapp/app/v3/services/batchTriggerV3.server.ts`, `runStore.findTaskRunAttempt` is intentionally supplied the owning primary client for read-your-writes consistency. `internal-packages/run-store/src/runOpsStore.batchDependentAttemptReadView.replicaLag.test.ts` instead documents the raw client-less store-routing seam, where a replica-lag miss is expected; caller-level rejection behavior is covered by `apps/webapp/test/batchServices.replicaLag.test.ts`.

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-07-26T00:55:21.349Z
Learnt from: 1stvamp
Repo: triggerdotdev/trigger.dev PR: 4367
File: internal-packages/run-engine/design/plans/2026-07-23-ck-virtual-time-scheduling-plan.md:678-685
Timestamp: 2026-07-26T00:55:21.349Z
Learning: For CK virtual-time scheduling in `internal-packages/run-engine/src/run-queue/tests/ckVtimeConcurrency.test.ts`, the Redis operation-count assertion is intentionally a regression guard for a measured scenario rather than a formal worst-case complexity proof. Pass-1 and pass-2 `tryServe` attempts are bounded by their scan windows; the resulting window-versus-attempt overhead limitation is documented in `internal-packages/run-engine/src/run-queue/CK_VTIME_KNOWN_LIMITATIONS.md`.

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-06-01T15:01:35.175Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3756
File: apps/webapp/app/v3/services/resetIdempotencyKey.server.ts:65-94
Timestamp: 2026-06-01T15:01:35.175Z
Learning: In `apps/webapp/app/v3/services/resetIdempotencyKey.server.ts` (triggerdotdev/trigger.dev), a transient `buffer.resetIdempotency()` failure when `pgCount > 0` does NOT warrant a 503 and should return success. The mollifier `ack` and `fail` Lua scripts always DEL the idempotency lookup key as part of the run's natural lifecycle (drain→ack or terminal→fail or cancel-bifurcation), so stale buffered idempotency lookups converge automatically without caller retries. Only when `pgCount === 0 && bufferResetFailed` is a 503 appropriate, because then the run's existence is genuinely unobservable (the buffer outage hides a potentially matching buffered run). The test "returns success when PG cleared >=1 run, even if the buffer reset throws" documents this contract explicitly.

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-04-07T14:12:18.946Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3331
File: apps/webapp/test/engine/batchPayloads.test.ts:5-24
Timestamp: 2026-04-07T14:12:18.946Z
Learning: In `apps/webapp/test/engine/batchPayloads.test.ts`, using `vi.mock` for `~/v3/objectStore.server` (stubbing `hasObjectStoreClient` and `uploadPacketToObjectStore`), `~/env.server` (overriding offload thresholds), and `~/v3/tracer.server` (stubbing `startActiveSpan`) is intentional and acceptable. Simulating controlled transient upload failures (e.g., fail N times then succeed) to verify `p-retry` behavior cannot be reproduced with real services or testcontainers. This file is an explicit exception to the repo's general no-mocks policy.

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 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] 16-16: 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/src/v3/otel/tracingSDK.ts (5)

165-183: LGTM!


235-250: LGTM!


397-455: LGTM!


457-460: LGTM!

Also applies to: 469-483


541-545: LGTM!

Also applies to: 547-552, 583-596

packages/core/test/externalSpanExporterWrapper.test.ts (1)

190-203: Fix ambient trace lookup in ExternalLogRecordExporterWrapper.

At Line 196, the Run A log exports after Line 192 sets Run B context. The current log exporter reads ambient traceContext during export. It will stamp the Run A log with Run B's trace ID, so the assertion at Line 203 fails.

Resolve the fallback ID from log.spanContext.traceId through the shared FallbackExternalTraceIds instance.


Walkthrough

The tracing SDK adds FallbackExternalTraceIds to generate bounded fallback IDs per internal trace. Span and log exporters share this instance and resolve IDs from each record’s trace context. Log records without span context remain unchanged. Tests cover ID reuse, reminting, delayed exports, disabled fallback behavior, shared exporter IDs, and eviction. A patch changeset documents the release.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% 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 clearly summarizes the primary change: generating fallback external trace IDs per run.
Description check ✅ Passed The description provides the problem, implementation, testing, changelog, checklist, and CI context required to review the change.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@coderabbitai coderabbitai Bot left a comment

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.

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 lift

Bind the fallback trace ID at export time.

forCurrentRun() reads getTraceContextEpoch() in the exporter callback. When batch exports drain after traceContext has 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

📥 Commits

Reviewing files that changed from the base of the PR and between 63176a6 and f837ccc.

📒 Files selected for processing (6)
  • .changeset/external-trace-id-per-run.md
  • packages/core/src/v3/otel/tracingSDK.ts
  • packages/core/src/v3/traceContext/api.ts
  • packages/core/src/v3/traceContext/manager.ts
  • packages/core/src/v3/traceContext/types.ts
  • packages/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 dynamic import(); 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/v3 or deprecated client.defineJob.
Add agentcrumbs while writing code using approved namespaces; mark lines with // @Crumbs or blocks with `// `#region` `@crumbs, and strip them before merging.

Files:

  • packages/core/src/v3/traceContext/types.ts
  • packages/core/src/v3/traceContext/api.ts
  • packages/core/src/v3/traceContext/manager.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
  • packages/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.ts
  • packages/core/src/v3/traceContext/api.ts
  • packages/core/src/v3/traceContext/manager.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
  • packages/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.ts
  • packages/core/src/v3/traceContext/api.ts
  • packages/core/src/v3/traceContext/manager.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
  • packages/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.ts
  • packages/core/src/v3/traceContext/api.ts
  • packages/core/src/v3/traceContext/manager.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
  • packages/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.ts
  • packages/core/src/v3/traceContext/api.ts
  • packages/core/src/v3/traceContext/manager.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
  • packages/core/src/v3/otel/tracingSDK.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

For public packages, use build for verification.

Files:

  • packages/core/src/v3/traceContext/types.ts
  • packages/core/src/v3/traceContext/api.ts
  • packages/core/src/v3/traceContext/manager.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
  • packages/core/src/v3/otel/tracingSDK.ts
packages/core/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Import @trigger.dev/core subpaths only; never import from the package root.

Files:

  • packages/core/src/v3/traceContext/types.ts
  • packages/core/src/v3/traceContext/api.ts
  • packages/core/src/v3/traceContext/manager.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
  • packages/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.ts
  • packages/core/src/v3/traceContext/api.ts
  • packages/core/src/v3/traceContext/manager.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
  • packages/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.ts
  • packages/core/src/v3/traceContext/api.ts
  • packages/core/src/v3/traceContext/manager.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
  • packages/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.ts
  • packages/core/src/v3/traceContext/api.ts
  • packages/core/src/v3/traceContext/manager.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
  • packages/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.ts
  • packages/core/src/v3/traceContext/api.ts
  • packages/core/src/v3/traceContext/manager.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
  • packages/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.ts
  • packages/core/src/v3/traceContext/api.ts
  • packages/core/src/v3/traceContext/manager.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
  • packages/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.ts
  • packages/core/src/v3/traceContext/api.ts
  • packages/core/src/v3/traceContext/manager.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
  • packages/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.ts
  • packages/core/src/v3/traceContext/api.ts
  • packages/core/src/v3/traceContext/manager.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
  • packages/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.ts
  • packages/core/src/v3/traceContext/api.ts
  • packages/core/src/v3/traceContext/manager.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
  • packages/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.ts
  • packages/core/src/v3/traceContext/api.ts
  • packages/core/src/v3/traceContext/manager.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
  • packages/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

@NERLOE
NERLOE force-pushed the fix/external-trace-id-per-run branch 2 times, most recently from 3331b42 to e840eb0 Compare August 7, 2026 14:51
@NERLOE

NERLOE commented Aug 7, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai Good catch, and it sent me back to the drawing board — fixed in e840eb0.

You're right that forCurrentRun() read ambient state in the exporter callback, which is the wrong moment. The window was narrower than it looks (managed-run-worker.ts awaits _lastFlushPromise before assigning the new run's trace context), but flushTracingSDK races a 10s timeout, so a slow external OTLP endpoint — precisely the situation this PR serves — leaves run A's records draining after run B has begun.

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 TraceContextManager — the diff is now confined to tracingSDK.ts and its test.

Added the regression test you asked for: stamps records with their own run's id even when exported after the next run started queues run A's records, advances to run B, then exports them and asserts they keep run A's id and that the log agrees with the span. Mutation-checked — pointing the lookup at ambient state instead of the record fails it, along with two others.

Also added a bound on the map, since a warm process serves unboundedly many runs.

@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@NERLOE Thanks for the detailed correction. Keying the fallback ID from each record’s internal trace ID fixes the delayed-export race.

The new regression test covers the failure mode I identified. The bounded map also prevents unbounded retention on warm workers.

🐇 ✅


✏️ Learnings added
Learnt from: NERLOE
URL: https://github.com/triggerdotdev/trigger.dev/pull/4534

Timestamp: 2026-08-07T14:52:19.054Z
Learning: In `packages/core/src/v3/otel/tracingSDK.ts`, external fallback trace IDs must be derived from the internal trace ID carried by each span or log record. Do not resolve the fallback ID from ambient trace context during exporter callbacks, because records can export after a later run has replaced that context.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


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.

@coderabbitai coderabbitai Bot left a comment

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.

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 lift

Remove 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, not traceContext.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: set manager.traceContext.external.traceparent so 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

📥 Commits

Reviewing files that changed from the base of the PR and between f837ccc and e840eb0.

📒 Files selected for processing (2)
  • packages/core/src/v3/otel/tracingSDK.ts
  • packages/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 dynamic import(); 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/v3 or deprecated client.defineJob.
Add agentcrumbs while writing code using approved namespaces; mark lines with // @Crumbs or blocks with `// `#region` `@crumbs, and strip them before merging.

Files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
  • packages/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.ts
  • packages/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.ts
  • packages/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.ts
  • packages/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.ts
  • packages/core/src/v3/otel/tracingSDK.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

For public packages, use build for verification.

Files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
  • packages/core/src/v3/otel/tracingSDK.ts
packages/core/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Import @trigger.dev/core subpaths only; never import from the package root.

Files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
  • packages/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.ts
  • packages/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.ts
  • packages/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.ts
  • packages/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.ts
  • packages/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.ts
  • packages/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.ts
  • packages/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.ts
  • packages/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.ts
  • packages/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.ts
  • packages/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

@NERLOE
NERLOE force-pushed the fix/external-trace-id-per-run branch from e840eb0 to 552d21f Compare August 12, 2026 09:45
@coderabbitai

coderabbitai Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 935b894c-23c3-4a6d-8b0a-b64fc7cbdcfd

📥 Commits

Reviewing files that changed from the base of the PR and between 7b390e5 and 552d21f.

📒 Files selected for processing (3)
  • .changeset/external-trace-id-per-run.md
  • packages/core/src/v3/otel/tracingSDK.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • .changeset/external-trace-id-per-run.md
  • packages/core/src/v3/otel/tracingSDK.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (23)
  • GitHub Check: e2e / 🧪 CLI v3 tests (warp-windows-latest-x64-8x - pnpm)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (9, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (4, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (8, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (1, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (6, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (2, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (10, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (11, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (12, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (7, 12)
  • GitHub Check: sdk-compat / Cloudflare Workers
  • GitHub Check: e2e / 🧪 CLI v3 tests (warp-windows-latest-x64-8x - npm)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (3, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (5, 12)
  • GitHub Check: e2e-webapp / 🧪 E2E Tests: Webapp
  • GitHub Check: packages / 🧪 Unit Tests: Packages (3, 3)
  • GitHub Check: sdk-compat / Node.js 24.18 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: packages / 🧪 Unit Tests: Packages (1, 3)
  • GitHub Check: packages / 🧪 Unit Tests: Packages (2, 3)
  • GitHub Check: runops-guard / runops-guard
  • GitHub Check: internal / 🧪 Unit Tests: Internal
  • 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 dynamic import(); 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/v3 or deprecated client.defineJob.
Add agentcrumbs while writing code using approved namespaces; mark lines with // @Crumbs or blocks with `// `#region` `@crumbs, and strip them before merging.

Files:

  • packages/core/test/externalSpanExporterWrapper.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:

  • packages/core/test/externalSpanExporterWrapper.test.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.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.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.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

For public packages, use build for verification.

Files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
packages/core/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Import @trigger.dev/core subpaths only; never import from the package root.

Files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
🧠 Learnings (28)
📓 Common learnings
Learnt from: NERLOE
Repo: triggerdotdev/trigger.dev PR: 0
File: :0-0
Timestamp: 2026-08-07T14:52:19.054Z
Learning: In `packages/core/src/v3/otel/tracingSDK.ts`, external fallback trace IDs must be derived from the internal trace ID carried by each span or log record. Do not resolve the fallback ID from ambient trace context during exporter callbacks, because records can export after a later run has replaced that context.
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 4237
File: internal-packages/run-store/src/runOpsStore.ts:1606-1653
Timestamp: 2026-07-13T10:07:23.733Z
Learning: In `internal-packages/run-store/src/runOpsStore.ts`, `RoutingRunStore.upsertWaitpointTag` and `findManyWaitpointTags` currently route/dedupe `WaitpointTag` by `id`, not by the natural key `(environmentId, name)`. This is a known, intentionally deferred gap (tracked separately, not fixed in the PR that introduced run-ops residency routing): if the same `(environmentId, name)` exists on NEW with a different id than the LEGACY write target, upserts can create/update a duplicate row and reads can return duplicates or a stale NEW copy. A proper fix would resolve the existing natural-key row before choosing the write store and dedupe reads by `(environmentId, name)`.
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3453
File: internal-packages/run-engine/src/engine/systems/debounceSystem.ts:517-547
Timestamp: 2026-04-27T16:39:43.098Z
Learning: In `internal-packages/run-engine/src/engine/systems/debounceSystem.ts`, the `try/catch` around `runLock.lock(...)` in `handleExistingRun` routes errors matching `#isLockContentionError` (`LockAcquisitionTimeoutError`, `name === "ExecutionError"`, `name === "ResourceLockedError"`) to a fallback. This is intentionally NOT guarded by a `lockAcquired` flag because the only code executed inside the lock callback (`#handleExistingRunLocked`) calls Prisma and ioredis, neither of which emits errors with those names — those names are redlock-specific. There are no nested `runLock.lock` calls in this path so callback-thrown errors cannot be misclassified. A `lockAcquired` guard should be revisited only if a nested lock call is ever introduced inside `#handleExistingRunLocked`.
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3531
File: apps/webapp/test/sentryTraceContext.server.test.ts:9-47
Timestamp: 2026-05-07T12:25:21.024Z
Learning: In the triggerdotdev/trigger.dev webapp test suite, `createInMemoryTracing()` calls that register a `NodeTracerProvider` globally are intentionally left without `afterEach`/`afterAll` teardown. This is consistent across tests like `runsReplicationService.part1.test.ts`, `runsBackfiller.test.ts`, and `runsReplicationBenchmark.test.ts`. The "returns undefined when no OTel span is active" pattern is safe because `trace.getActiveSpan()` outside a `context.with(...)` block reads from `AsyncLocalStorage.getStore()` (undefined when no `run()` is in scope), falling back to `ROOT_CONTEXT` with no attached span — regardless of which provider is registered. Do not flag missing OTel provider teardown in webapp tests as a test-ordering risk.
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3754
File: apps/webapp/app/v3/mollifierStaleSweepWorker.server.ts:30-32
Timestamp: 2026-06-01T12:05:44.112Z
Learning: In the triggerdotdev/trigger.dev codebase, the mollifier stale-entry sweep (`initMollifierStaleSweepWorker` in `apps/webapp/app/v3/mollifierStaleSweepWorker.server.ts`) intentionally runs per-webapp instance without a distributed lease in its initial implementation. All Redis ops (cursor, counts hash, reconcile) are individually atomic and produce correct shared state even with multiple concurrent sweepers. The known limitation is that OpenTelemetry metric output (`recordStaleEntry`, `reportStaleEntrySnapshot`) multiplies by N webapp instances, mis-calibrating alert thresholds by a factor of N. A SETNX-based per-tick lease (SET NX PX on the sweep's existing Redis) is the planned follow-up fix. Until then, alert thresholds should be scaled accordingly. Do not re-raise this as a blocking correctness bug — it is a documented metric-scaling limitation with a tracked follow-up.
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 4577
File: apps/webapp/app/v3/services/createBackgroundWorker.server.ts:779-781
Timestamp: 2026-08-12T06:32:24.127Z
Learning: In `apps/webapp/app/v3/services/createBackgroundWorker.server.ts`, `syncDeclarativeSchedules` has a pre-existing non-serialized read/modify/delete reconciliation flow. Changes that reuse its initial schedule snapshot instead of a redundant re-fetch do not introduce this concurrency risk. Track reconciliation serialization separately from read-side performance changes unless a change modifies the synchronization boundary.
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 4285
File: internal-packages/run-store/src/runOpsStore.presentersWaitpointReadView.replicaLag.test.ts:24-65
Timestamp: 2026-07-18T18:31:37.633Z
Learning: In `triggerdotdev/trigger.dev`’s `internal-packages/run-store/src/runOpsStore.presentersWaitpointReadView.replicaLag.test.ts`, retain the local real-Testcontainers Prisma proxy rather than requiring the shared `laggingReplica` helper: the test must simulate lag for `waitpointTag` reads and for `findWaitpointConnectedRunIds`, which uses `$queryRaw`. The shared primitive intercepts configured Prisma models but not raw queries, so replacing the proxy would allow the live raw join to observe primary data and invalidate the replica-lag guard. The related taskRun-only tests (`runOpsStore.realtimeServicesReadView.replicaLag.test.ts`, `runOpsStore.replayReadAfterWrite.replicaLag.test.ts`, and `runOpsStore.resolveRunForMutationReplicaLag.test.ts`) can use the shared primitive with `{ model: "taskRun", mode: "missing" }`.
📚 Learning: 2026-08-07T14:52:19.054Z
Learnt from: NERLOE
Repo: triggerdotdev/trigger.dev PR: 0
File: :0-0
Timestamp: 2026-08-07T14:52:19.054Z
Learning: In `packages/core/src/v3/otel/tracingSDK.ts`, external fallback trace IDs must be derived from the internal trace ID carried by each span or log record. Do not resolve the fallback ID from ambient trace context during exporter callbacks, because records can export after a later run has replaced that context.

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-05-07T12:25:21.024Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3531
File: apps/webapp/test/sentryTraceContext.server.test.ts:9-47
Timestamp: 2026-05-07T12:25:21.024Z
Learning: In the triggerdotdev/trigger.dev webapp test suite, `createInMemoryTracing()` calls that register a `NodeTracerProvider` globally are intentionally left without `afterEach`/`afterAll` teardown. This is consistent across tests like `runsReplicationService.part1.test.ts`, `runsBackfiller.test.ts`, and `runsReplicationBenchmark.test.ts`. The "returns undefined when no OTel span is active" pattern is safe because `trace.getActiveSpan()` outside a `context.with(...)` block reads from `AsyncLocalStorage.getStore()` (undefined when no `run()` is in scope), falling back to `ROOT_CONTEXT` with no attached span — regardless of which provider is registered. Do not flag missing OTel provider teardown in webapp tests as a test-ordering risk.

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-07-27T15:07:14.579Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 4397
File: apps/webapp/test/batchStreamGrants.test.ts:0-0
Timestamp: 2026-07-27T15:07:14.579Z
Learning: In `triggerdotdev/trigger.dev`, `apps/webapp/test/authorizationRateLimitMiddleware.test.ts` remains skipped because correcting its plaintext Redis fixture setup (`tlsDisabled`) exposed a timing-sensitive sliding-window test based on real 10-second windows. The new authorization-rate-limit bypass coverage instead lives in the unskipped, deterministic `apps/webapp/test/authorizationRateLimitMiddlewareBypass.test.ts`. Do not flag the legacy suite's continued skip as missing coverage for the bypass behavior.

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-07-18T18:31:37.633Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 4285
File: internal-packages/run-store/src/runOpsStore.presentersWaitpointReadView.replicaLag.test.ts:24-65
Timestamp: 2026-07-18T18:31:37.633Z
Learning: In `triggerdotdev/trigger.dev`’s `internal-packages/run-store/src/runOpsStore.presentersWaitpointReadView.replicaLag.test.ts`, retain the local real-Testcontainers Prisma proxy rather than requiring the shared `laggingReplica` helper: the test must simulate lag for `waitpointTag` reads and for `findWaitpointConnectedRunIds`, which uses `$queryRaw`. The shared primitive intercepts configured Prisma models but not raw queries, so replacing the proxy would allow the live raw join to observe primary data and invalidate the replica-lag guard. The related taskRun-only tests (`runOpsStore.realtimeServicesReadView.replicaLag.test.ts`, `runOpsStore.replayReadAfterWrite.replicaLag.test.ts`, and `runOpsStore.resolveRunForMutationReplicaLag.test.ts`) can use the shared primitive with `{ model: "taskRun", mode: "missing" }`.

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-03-02T12:43:25.254Z
Learnt from: CR
Repo: triggerdotdev/trigger.dev PR: 0
File: internal-packages/run-engine/CLAUDE.md:0-0
Timestamp: 2026-03-02T12:43:25.254Z
Learning: Applies to internal-packages/run-engine/src/engine/tests/**/*.test.ts : Implement tests for RunEngine in `src/engine/tests/` using testcontainers for Redis and PostgreSQL containerization

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-07-18T18:31:43.376Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 4285
File: internal-packages/run-engine/src/engine/tests/runAttemptSystemReplicaLag.guard.test.ts:30-92
Timestamp: 2026-07-18T18:31:43.376Z
Learning: In `internal-packages/run-engine/src/engine/tests/runAttemptSystemReplicaLag.guard.test.ts`, retain the bespoke `laggingReadReplica` proxy for the retry-decision and usage read-modify-write tests. It must fabricate distinct stale `taskRun.findFirst` scalar snapshots only for their exact `select` shapes while all other reads remain live; the shared `laggingReplica` primitive cannot express projection-specific lag. Use the shared primitive separately for whole-row missing replica behavior.

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-03-02T12:43:25.254Z
Learnt from: CR
Repo: triggerdotdev/trigger.dev PR: 0
File: internal-packages/run-engine/CLAUDE.md:0-0
Timestamp: 2026-03-02T12:43:25.254Z
Learning: Applies to internal-packages/run-engine/src/engine/systems/**/*.ts : Integrate OpenTelemetry tracer and meter instrumentation in RunEngine systems for observability

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-03-03T13:07:33.177Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3166
File: internal-packages/run-engine/src/batch-queue/tests/index.test.ts:711-713
Timestamp: 2026-03-03T13:07:33.177Z
Learning: In `internal-packages/run-engine/src/batch-queue/tests/index.test.ts`, test assertions for rate limiter stubs can use `toBeGreaterThanOrEqual` rather than exact equality (`toBe`) because the consumer loop may call the rate limiter during empty pops in addition to actual item processing, and this over-calling is acceptable in integration tests.

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-04-16T13:45:22.317Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3368
File: apps/webapp/test/engine/taskIdentifierRegistry.test.ts:3-19
Timestamp: 2026-04-16T13:45:22.317Z
Learning: In `apps/webapp/test/engine/taskIdentifierRegistry.test.ts`, the `vi.mock` calls for `~/services/taskIdentifierCache.server` (stubbing `getTaskIdentifiersFromCache` and `populateTaskIdentifierCache`), `~/models/task.server` (stubbing `getAllTaskIdentifiers`), and `~/db.server` (stubbing `prisma` and `$replica`) are intentional. The suite uses real Postgres via testcontainers for all `TaskIdentifier` DB operations, but isolates the Redis cache layer and legacy query fallback as separate concerns not exercised in this test file. Do not flag these mocks as violations of the no-mocks policy in future reviews.

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-07-18T18:17:26.381Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 4285
File: internal-packages/run-store/src/runOpsStore.sessionRunProbeReadAfterWrite.test.ts:154-182
Timestamp: 2026-07-18T18:17:26.381Z
Learning: For session-run replica-lag coverage, `internal-packages/run-store/src/runOpsStore.sessionRunProbeReadAfterWrite.test.ts` intentionally characterizes only the `RoutingRunStore.findRun` store seam: an owning-replica miss followed by a writer read recovers the live run. The behavioral no-double-trigger contract belongs in `apps/webapp/test/realtimeServices.replicaLag.test.ts`, which invokes the real exported `ensureRunForSession` and asserts reuse (`triggered: false`) with zero `TriggerTaskService` calls.

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-07-26T00:55:21.349Z
Learnt from: 1stvamp
Repo: triggerdotdev/trigger.dev PR: 4367
File: internal-packages/run-engine/design/plans/2026-07-23-ck-virtual-time-scheduling-plan.md:678-685
Timestamp: 2026-07-26T00:55:21.349Z
Learning: For CK virtual-time scheduling in `internal-packages/run-engine/src/run-queue/tests/ckVtimeConcurrency.test.ts`, the Redis operation-count assertion is intentionally a regression guard for a measured scenario rather than a formal worst-case complexity proof. Pass-1 and pass-2 `tryServe` attempts are bounded by their scan windows; the resulting window-versus-attempt overhead limitation is documented in `internal-packages/run-engine/src/run-queue/CK_VTIME_KNOWN_LIMITATIONS.md`.

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-06-01T15:01:35.175Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3756
File: apps/webapp/app/v3/services/resetIdempotencyKey.server.ts:65-94
Timestamp: 2026-06-01T15:01:35.175Z
Learning: In `apps/webapp/app/v3/services/resetIdempotencyKey.server.ts` (triggerdotdev/trigger.dev), a transient `buffer.resetIdempotency()` failure when `pgCount > 0` does NOT warrant a 503 and should return success. The mollifier `ack` and `fail` Lua scripts always DEL the idempotency lookup key as part of the run's natural lifecycle (drain→ack or terminal→fail or cancel-bifurcation), so stale buffered idempotency lookups converge automatically without caller retries. Only when `pgCount === 0 && bufferResetFailed` is a 503 appropriate, because then the run's existence is genuinely unobservable (the buffer outage hides a potentially matching buffered run). The test "returns success when PG cleared >=1 run, even if the buffer reset throws" documents this contract explicitly.

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-07-18T13:08:53.789Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 4284
File: internal-packages/run-store/src/runOpsStore.batchDependentAttemptReadView.replicaLag.test.ts:232-241
Timestamp: 2026-07-18T13:08:53.789Z
Learning: For the batch-dependent-attempt validation in `apps/webapp/app/v3/services/batchTriggerV3.server.ts`, `runStore.findTaskRunAttempt` is intentionally supplied the owning primary client for read-your-writes consistency. `internal-packages/run-store/src/runOpsStore.batchDependentAttemptReadView.replicaLag.test.ts` instead documents the raw client-less store-routing seam, where a replica-lag miss is expected; caller-level rejection behavior is covered by `apps/webapp/test/batchServices.replicaLag.test.ts`.

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 Learning: 2026-04-07T14:12:18.946Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3331
File: apps/webapp/test/engine/batchPayloads.test.ts:5-24
Timestamp: 2026-04-07T14:12:18.946Z
Learning: In `apps/webapp/test/engine/batchPayloads.test.ts`, using `vi.mock` for `~/v3/objectStore.server` (stubbing `hasObjectStoreClient` and `uploadPacketToObjectStore`), `~/env.server` (overriding offload thresholds), and `~/v3/tracer.server` (stubbing `startActiveSpan`) is intentional and acceptable. Simulating controlled transient upload failures (e.g., fail N times then succeed) to verify `p-retry` behavior cannot be reproduced with real services or testcontainers. This file is an explicit exception to the repo's general no-mocks policy.

Applied to files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
📚 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.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.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.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.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.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.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.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.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.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] 16-16: 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/test/externalSpanExporterWrapper.test.ts (2)

2-24: LGTM!

Also applies to: 49-60, 74-107, 117-117, 132-172


203-220: LGTM!

Also applies to: 222-236, 238-262

Comment thread packages/core/test/externalSpanExporterWrapper.test.ts
@NERLOE
NERLOE force-pushed the fix/external-trace-id-per-run branch from 552d21f to 82e03ee Compare August 12, 2026 14:21

@coderabbitai coderabbitai Bot left a comment

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.

♻️ Duplicate comments (1)
packages/core/test/externalSpanExporterWrapper.test.ts (1)

190-203: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Remove the remaining ambient context lookup from log export.

At Line 196, the current ExternalLogRecordExporterWrapper.export() implementation reads traceContext.getExternalTraceContext(). Line 192 sets that context to Run B. The queued Run A log record then receives Run B's external trace ID, so the assertion at Line 203 fails.

Resolve the fallback ID from log.spanContext.traceId through the shared FallbackExternalTraceId. Do not read ambient trace context during exporter callbacks.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a090ddc9-8ee9-48ff-a100-08826fc20109

📥 Commits

Reviewing files that changed from the base of the PR and between 552d21f and 82e03ee.

📒 Files selected for processing (2)
  • packages/core/src/v3/otel/tracingSDK.ts
  • packages/core/test/externalSpanExporterWrapper.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/core/src/v3/otel/tracingSDK.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (23)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (12, 12)
  • GitHub Check: e2e / 🧪 CLI v3 tests (warp-windows-latest-x64-8x - pnpm)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (2, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (9, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (8, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (7, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (11, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (10, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (3, 12)
  • GitHub Check: e2e / 🧪 CLI v3 tests (warp-windows-latest-x64-8x - npm)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (1, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (5, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (6, 12)
  • GitHub Check: sdk-compat / Cloudflare Workers
  • GitHub Check: internal / 🧪 Unit Tests: Internal
  • GitHub Check: sdk-compat / Node.js 26.4 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: typecheck / typecheck
  • GitHub Check: sdk-compat / Bun Runtime
  • GitHub Check: packages / 🧪 Unit Tests: Packages (2, 3)
  • GitHub Check: packages / 🧪 Unit Tests: Packages (3, 3)
  • GitHub Check: packages / 🧪 Unit Tests: Packages (1, 3)
  • GitHub Check: sdk-compat / Deno Runtime
  • GitHub Check: e2e-webapp / 🧪 E2E Tests: Webapp
🧰 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 dynamic import(); 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/v3 or deprecated client.defineJob.
Add agentcrumbs while writing code using approved namespaces; mark lines with // @Crumbs or blocks with `// `#region` `@crumbs, and strip them before merging.

Files:

  • packages/core/test/externalSpanExporterWrapper.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:

  • packages/core/test/externalSpanExporterWrapper.test.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.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.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.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

For public packages, use build for verification.

Files:

  • packages/core/test/externalSpanExporterWrapper.test.ts
packages/core/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Import @trigger.dev/core subpaths only; never import from the package root.

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/test/externalSpanExporterWrapper.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:

  • packages/core/test/externalSpanExporterWrapper.test.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.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.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.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.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.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.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.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] 16-16: 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 (1)
packages/core/test/externalSpanExporterWrapper.test.ts (1)

2-172: LGTM!

Also applies to: 206-246

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>
@NERLOE
NERLOE force-pushed the fix/external-trace-id-per-run branch from 82e03ee to c379df4 Compare August 12, 2026 14:27
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