fix(webapp): collapse Prisma P1001 errors into a single Sentry issue#3632
fix(webapp): collapse Prisma P1001 errors into a single Sentry issue#3632d-cs wants to merge 1 commit into
Conversation
DB outages currently produce hundreds of distinct Sentry issues — one per call site — which buries other alerts. Add a beforeSend rule that detects err.code === "P1001" (KnownRequestError when a connection drops mid-query) or err.errorCode === "P1001" (InitializationError when the client fails to connect at startup) and assigns a stable fingerprint plus a db_unreachable tag so all P1001 events collapse into one issue regardless of stack trace. The rule list is extensible — additional fan-out errors can be added with one entry. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
WalkthroughThis change introduces Sentry fingerprint-based grouping for Prisma P1001 database connectivity errors. A new Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
apps/webapp/sentry.server.ts (1)
9-13: 💤 Low valueConsider exporting the rule type for better extensibility.
Since the comments emphasize extensibility, exporting the type would make it easier for developers to understand the rule structure when adding new rules in the future.
♻️ Suggested refactor
+type FingerprintRule = { + match: (err: { code?: unknown; errorCode?: unknown; name?: unknown }) => boolean; + fingerprint: string; + tags?: Record<string, string>; +}; + -const FINGERPRINT_RULES: Array<{ - match: (err: { code?: unknown; errorCode?: unknown; name?: unknown }) => boolean; - fingerprint: string; - tags?: Record<string, string>; -}> = [ +const FINGERPRINT_RULES: Array<FingerprintRule> = [🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/webapp/sentry.server.ts` around lines 9 - 13, Export a named type for the fingerprint rule shape so other modules can import and extend it instead of relying on the inline annotation; define and export something like FingerprintRule describing match: (err: { code?: unknown; errorCode?: unknown; name?: unknown }) => boolean, fingerprint: string, tags?: Record<string,string>, then replace the inline Array<...> annotation on FINGERPRINT_RULES with FingerprintRule[] and update any references to use the new exported type.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/webapp/sentry.server.ts`:
- Around line 4-21: The FINGERPRINT_RULES match predicate incorrectly checks
err.code for P1001 (which never appears) and may miss P1001 when err.errorCode
is undefined; update the match logic in the FINGERPRINT_RULES entry so it
detects PrismaClientInitializationError correctly—preferably by checking the
error type/name (e.g., instanceof or err.name ===
"PrismaClientInitializationError") and err.errorCode === "P1001", and add a safe
fallback that inspects err.message or another cheap string check for "P1001" to
cover cases where errorCode is intermittently undefined.
---
Nitpick comments:
In `@apps/webapp/sentry.server.ts`:
- Around line 9-13: Export a named type for the fingerprint rule shape so other
modules can import and extend it instead of relying on the inline annotation;
define and export something like FingerprintRule describing match: (err: {
code?: unknown; errorCode?: unknown; name?: unknown }) => boolean, fingerprint:
string, tags?: Record<string,string>, then replace the inline Array<...>
annotation on FINGERPRINT_RULES with FingerprintRule[] and update any references
to use the new exported type.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: f8dc5b82-4e39-4744-94ad-f5f9d4ded1cc
📒 Files selected for processing (2)
.server-changes/webapp-sentry-fingerprint-p1001.mdapps/webapp/sentry.server.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (4, 8)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (8, 8)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (2, 8)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (1, 8)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (5, 8)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (6, 8)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (7, 8)
- GitHub Check: typecheck / typecheck
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (3, 8)
- 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}: Import from@trigger.dev/coresubpaths only, never from the root. Subpath imports must be used to maintain proper module boundaries.
When writing Trigger.dev tasks, always import from@trigger.dev/sdk. Never use@trigger.dev/sdk/v3or deprecatedclient.defineJob.
Prisma is version 6.14.0. Use the Prisma client frominternal-packages/databasefor all database operations.
For ClickHouse client, schema migrations, and analytics queries, useinternal-packages/clickhouse.
Files:
apps/webapp/sentry.server.ts
{packages/core,apps/webapp}/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Use zod for validation in packages/core and apps/webapp
Files:
apps/webapp/sentry.server.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Use function declarations instead of default exports
Add crumbs as you write code — not just when debugging. Mark lines with
//@Crumbsor wrap blocks in `// `#region` `@crumbs. They stay on the branch throughout development and are stripped byagentcrumbs stripbefore merge.
Files:
apps/webapp/sentry.server.ts
**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/otel-metrics.mdc)
**/*.ts: When creating or editing OTEL metrics (counters, histograms, gauges), ensure metric attributes have low cardinality by using only enums, booleans, bounded error codes, or bounded shard IDs
Do not use high-cardinality attributes in OTEL metrics such as UUIDs/IDs (envId, userId, runId, projectId, organizationId), unbounded integers (itemCount, batchSize, retryCount), timestamps (createdAt, startTime), or free-form strings (errorMessage, taskName, queueName)
When exporting OTEL metrics via OTLP to Prometheus, be aware that the exporter automatically adds unit suffixes to metric names (e.g., 'my_duration_ms' becomes 'my_duration_ms_milliseconds', 'my_counter' becomes 'my_counter_total'). Account for these transformations when writing Grafana dashboards or Prometheus queries
Files:
apps/webapp/sentry.server.ts
apps/webapp/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/webapp.mdc)
apps/webapp/**/*.{ts,tsx}: Access environment variables through theenvexport ofenv.server.tsinstead of directly accessingprocess.env
Use subpath exports from@trigger.dev/corepackage instead of importing from the root@trigger.dev/corepathUse named constants for sentinel/placeholder values (e.g.
const UNSET_VALUE = '__unset__') instead of raw string literals scattered across comparisons
Files:
apps/webapp/sentry.server.ts
apps/webapp/**/*.server.ts
📄 CodeRabbit inference engine (apps/webapp/CLAUDE.md)
apps/webapp/**/*.server.ts: Never userequest.signalfor detecting client disconnects. UsegetRequestAbortSignal()fromapp/services/httpAsyncStorage.server.tsinstead, which is wired directly to Expressres.on('close')and fires reliably
Access environment variables viaenvexport fromapp/env.server.ts. Never useprocess.envdirectly
Always usefindFirstinstead offindUniquein Prisma queries.findUniquehas an implicit DataLoader that batches concurrent calls and has active bugs even in Prisma 6.x (uppercase UUIDs returning null, composite key SQL correctness issues, 5-10x worse performance).findFirstis never batched and avoids this entire class of issues
Files:
apps/webapp/sentry.server.ts
**/*.{ts,tsx,js,jsx,json,md,css,scss}
📄 CodeRabbit inference engine (AGENTS.md)
Code formatting is enforced using Prettier. Run
pnpm run formatbefore committing
Files:
apps/webapp/sentry.server.ts
apps/**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
When modifying only server components (
apps/webapp/,apps/supervisor/, etc.) with no package changes, add a.server-changes/file instead of a changeset. See.server-changes/README.mdfor format and documentation.
Files:
apps/webapp/sentry.server.ts
🧠 Learnings (5)
📚 Learning: 2026-05-14T14:54:39.095Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3545
File: .server-changes/agent-view-sessions.md:10-10
Timestamp: 2026-05-14T14:54:39.095Z
Learning: In the `trigger.dev` repository, do not flag inconsistent dot vs slash notation in route/path strings inside `.server-changes/*.md` files. These markdown files are consumed verbatim into the changelog, so the mixed notation (e.g., `resources.orgs.../runs.$runParam/...`) is intentional and should be preserved as-is.
Applied to files:
.server-changes/webapp-sentry-fingerprint-p1001.md
📚 Learning: 2026-03-22T13:26:12.060Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3244
File: apps/webapp/app/components/code/TextEditor.tsx:81-86
Timestamp: 2026-03-22T13:26:12.060Z
Learning: In the triggerdotdev/trigger.dev codebase, do not flag `navigator.clipboard.writeText(...)` calls for `missing-await`/`unhandled-promise` issues. These clipboard writes are intentionally invoked without `await` and without `catch` handlers across the project; keep that behavior consistent when reviewing TypeScript/TSX files (e.g., usages like in `apps/webapp/app/components/code/TextEditor.tsx`).
Applied to files:
apps/webapp/sentry.server.ts
📚 Learning: 2026-03-22T19:24:14.403Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3187
File: apps/webapp/app/v3/services/alerts/deliverErrorGroupAlert.server.ts:200-204
Timestamp: 2026-03-22T19:24:14.403Z
Learning: In the triggerdotdev/trigger.dev codebase, webhook URLs are not expected to contain embedded credentials/secrets (e.g., fields like `ProjectAlertWebhookProperties` should only hold credential-free webhook endpoints). During code review, if you see logging or inclusion of raw webhook URLs in error messages, do not automatically treat it as a credential-leak/secrets-in-logs issue by default—first verify the URL does not contain embedded credentials (for example, no username/password in the URL, no obvious secret/token query params or fragments). If the URL is credential-free per this project’s conventions, allow the logging.
Applied to files:
apps/webapp/sentry.server.ts
📚 Learning: 2026-05-05T09:38:02.512Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3523
File: apps/webapp/app/routes/api.v3.batches.ts:178-181
Timestamp: 2026-05-05T09:38:02.512Z
Learning: When reviewing code that catches `ServiceValidationError` in `*.server.ts` files, do not blindly forward `error.status` to HTTP responses, because SVEs may be thrown with non-default statuses (e.g., 400/500) and forwarding them can cause client-visible behavioral regressions (e.g., surfacing 500s to clients). Prefer a safe default response status of `error.status ?? 422`, but only after confirming via the reachable call graph that the caught `ServiceValidationError` instances are expected to carry those non-default statuses; otherwise, normalize to `422` to avoid unexpected client-visible 5xx behavior.
Applied to files:
apps/webapp/sentry.server.ts
📚 Learning: 2026-05-12T21:04:05.815Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3542
File: apps/webapp/app/components/sessions/v1/SessionStatus.tsx:1-3
Timestamp: 2026-05-12T21:04:05.815Z
Learning: In this Remix + TypeScript codebase, do not flag a server/client boundary violation when a file imports only types from a module matching `*.server`.
Specifically, it’s safe to import types using `import type { Foo } from "*.server"` or `import { type Foo } from "*.server"` because TypeScript erases type-only imports at compile time and they emit no JavaScript, so they won’t cross the Remix server/client bundle boundary.
Only raise the boundary concern for value imports (e.g., `import { Foo }` without `type`, or `import Foo`), since those produce JavaScript output.
Applied to files:
apps/webapp/sentry.server.ts
🔇 Additional comments (2)
apps/webapp/sentry.server.ts (1)
52-64: LGTM!.server-changes/webapp-sentry-fingerprint-p1001.md (1)
1-6: LGTM!
| // Rules for collapsing high-volume errors into a single Sentry issue. | ||
| // Without this, e.g. a DB outage produces hundreds of distinct issues — | ||
| // one per stack trace — which buries other alerts. Add a new rule here | ||
| // when you spot another error that fans out across call sites. Keep | ||
| // predicates cheap (string compare, not regex over stack traces). | ||
| const FINGERPRINT_RULES: Array<{ | ||
| match: (err: { code?: unknown; errorCode?: unknown; name?: unknown }) => boolean; | ||
| fingerprint: string; | ||
| tags?: Record<string, string>; | ||
| }> = [ | ||
| { | ||
| // Prisma surfaces P1001 on `code` for KnownRequestError (mid-query connection drop) | ||
| // and `errorCode` for InitializationError (client failed to connect at startup). | ||
| match: (err) => err.code === "P1001" || err.errorCode === "P1001", | ||
| fingerprint: "prisma-p1001-db-unreachable", | ||
| tags: { db_unreachable: "true" }, | ||
| }, | ||
| ]; |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Check Prisma source code for P1001 error property names
# Search for P1001 error definitions and usage in node_modules
echo "=== Searching for P1001 in Prisma client ==="
fd -e d -d 1 'prisma' node_modules/@prisma 2>/dev/null | head -1 | xargs -I {} find {} -name "*.d.ts" -o -name "*.ts" 2>/dev/null | xargs rg -n "P1001|errorCode|KnownRequestError|InitializationError" -C 2 2>/dev/null | head -100
echo ""
echo "=== Checking internal-packages/database for Prisma usage ==="
rg -n "code.*P1001|errorCode.*P1001" internal-packages/database -C 2 | head -50Repository: triggerdotdev/trigger.dev
Length of output: 8678
🌐 Web query:
Prisma 6.14.0 error code P1001 KnownRequestError InitializationError code vs errorCode property
💡 Result:
In Prisma, P1001 is a specific error code indicating that the Prisma Client cannot reach the database server [1][2]. This error is typically categorized as a PrismaClientInitializationError, which occurs when the query engine fails to start or establish a connection to the database [3][2]. Regarding the distinction between errorCode and code properties: 1. PrismaClientKnownRequestError uses the.code property to identify specific database-related errors (e.g., P2002 for unique constraint violations) [3][2]. 2. PrismaClientInitializationError is documented to use the.errorCode property to identify initialization-related errors, such as P1001 [4][2]. However, there is a known, long-standing issue where the errorCode property on PrismaClientInitializationError can intermittently return undefined [5][6][7]. This often happens when the error is thrown during an implicit connection attempt (e.g., the first query execution) rather than an explicit call to prisma.$connect [6]. Because of this inconsistency, developers are often advised to rely on the error message or to ensure explicit connection handling to improve reliability [6][7]. Regarding Prisma 6.14.0 specifically, users have reported regressions in this version, including breaking changes related to extending the PrismaClient class and issues with the engine connection state [8][9]. If you are encountering unexpected behavior with error handling in this version, it may be related to these broader architectural changes rather than a change in the error property definitions themselves [8].
Citations:
- 1: https://www.prisma.io/docs/reference/api-reference/error-reference/
- 2: https://www.prisma.io/docs/orm/v6/reference/error-reference
- 3: https://mintlify.com/prisma/prisma/client/error-handling
- 4: https://www.prisma.io/docs/orm/reference/error-reference
- 5: PrismaClientInitializationError contains undefined errorCode prisma/prisma#19622
- 6:
PrismaClientInitializationErroris missingerrorCodeproperty prisma/prisma#18813 - 7:
PrismaClientInitializationErroris missing expected error code prisma/prisma#10229 - 8: PrismaClientUnknownRequestError after updating from 6.10 to 6.11 (and 6.14) prisma/prisma#27936
- 9: Prisma 6.14.0 adds breaking change for extending of PrismaClient prisma/prisma#27894
P1001 is a PrismaClientInitializationError, not KnownRequestError—the error detection logic is partially incorrect.
The rule checks err.code === "P1001" || err.errorCode === "P1001", but P1001 only appears on PrismaClientInitializationError via the .errorCode property. The .code property is used only by PrismaClientKnownRequestError for database errors (e.g., P2002). The check for err.code === "P1001" will never match.
Additionally, there is a known Prisma issue where .errorCode on InitializationError can intermittently return undefined during implicit connection attempts (e.g., on the first query execution). Relying solely on the .errorCode check may miss some P1001 errors. Consider either explicitly catching PrismaClientInitializationError by type or handling the error message as a fallback.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/webapp/sentry.server.ts` around lines 4 - 21, The FINGERPRINT_RULES
match predicate incorrectly checks err.code for P1001 (which never appears) and
may miss P1001 when err.errorCode is undefined; update the match logic in the
FINGERPRINT_RULES entry so it detects PrismaClientInitializationError
correctly—preferably by checking the error type/name (e.g., instanceof or
err.name === "PrismaClientInitializationError") and err.errorCode === "P1001",
and add a safe fallback that inspects err.message or another cheap string check
for "P1001" to cover cases where errorCode is intermittently undefined.
Summary
beforeSendrule inapps/webapp/sentry.server.tsthat collapses PrismaP1001("Can't reach database server") errors into a single Sentry issue regardless of which call site threw, by settingevent.fingerprint = ["prisma-p1001-db-unreachable"]and taggingdb_unreachable:true.err.code === "P1001"(Prisma'sKnownRequestErrorwhen a connection drops mid-query) anderr.errorCode === "P1001"(InitializationErrorwhen the client fails to connect at startup).FINGERPRINT_RULEStable so further fan-out errors can be added with one entry.Verification
End-to-end verified locally with
debug: trueon the SDK:P1001thrown from a loader (DB stopped mid-request) is captured by Sentry's Remix auto-instrumentationbeforeSendfires withoriginalException.code === "P1001", rule matchesevent.fingerprint = ["prisma-p1001-db-unreachable"]andtags.db_unreachable = "true"appliedTest plan
prisma-p1001-db-unreachableissue rather than fanning outdb_unreachable:truetag is filterable in SentrybeforeSenduntouched)🤖 Generated with Claude Code