Skip to content

fix(webapp): collapse Prisma P1001 errors into a single Sentry issue#3632

Draft
d-cs wants to merge 1 commit into
mainfrom
sentry-db-unreachable-fingerprint
Draft

fix(webapp): collapse Prisma P1001 errors into a single Sentry issue#3632
d-cs wants to merge 1 commit into
mainfrom
sentry-db-unreachable-fingerprint

Conversation

@d-cs
Copy link
Copy Markdown
Collaborator

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

Summary

  • Adds a beforeSend rule in apps/webapp/sentry.server.ts that collapses Prisma P1001 ("Can't reach database server") errors into a single Sentry issue regardless of which call site threw, by setting event.fingerprint = ["prisma-p1001-db-unreachable"] and tagging db_unreachable:true.
  • Matches both err.code === "P1001" (Prisma's KnownRequestError when a connection drops mid-query) and err.errorCode === "P1001" (InitializationError when the client fails to connect at startup).
  • Implemented as a small extensible FINGERPRINT_RULES table so further fan-out errors can be added with one entry.

Verification

End-to-end verified locally with debug: true on the SDK:

  • Real Prisma P1001 thrown from a loader (DB stopped mid-request) is captured by Sentry's Remix auto-instrumentation
  • beforeSend fires with originalException.code === "P1001", rule matches
  • event.fingerprint = ["prisma-p1001-db-unreachable"] and tags.db_unreachable = "true" applied
  • Event lands in Sentry under the new fingerprint

Test plan

  • Deploy to staging; confirm P1001 events appear under a single prisma-p1001-db-unreachable issue rather than fanning out
  • Confirm db_unreachable:true tag is filterable in Sentry
  • Verify non-P1001 errors are unaffected (event passes through beforeSend untouched)

🤖 Generated with Claude Code

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>
@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented May 15, 2026

⚠️ No Changeset found

Latest commit: d27ee9d

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

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

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

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 15, 2026

Review Change Stack

Walkthrough

This change introduces Sentry fingerprint-based grouping for Prisma P1001 database connectivity errors. A new FINGERPRINT_RULES configuration constant defines rules that match P1001 errors via either code or errorCode and assign a fixed fingerprint identifier along with a db_unreachable tag. A beforeSend hook is added to the Sentry init configuration that extracts the original exception from the event hint, matches it against the rules, and when a match is found, sets the event's fingerprint and merges the rule's tags into the event. Documentation is added to describe the change and note the extensible rule table for future collapsing rules.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is largely incomplete compared to the repository template. While it provides thorough technical details about the change and verification, it is missing required checklist items and does not follow the template structure with sections for Testing, Changelog, and Screenshots. Complete the PR description by adding the required checklist section with checkboxes, a dedicated Testing section with concrete steps, and a Changelog section. Include the Screenshots section even if empty.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title directly and clearly describes the main change: collapsing Prisma P1001 errors into a single Sentry issue, which matches the primary objective of the changeset.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch sentry-db-unreachable-fingerprint

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

❤️ Share

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

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
apps/webapp/sentry.server.ts (1)

9-13: 💤 Low value

Consider 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

📥 Commits

Reviewing files that changed from the base of the PR and between 5788573 and d27ee9d.

📒 Files selected for processing (2)
  • .server-changes/webapp-sentry-fingerprint-p1001.md
  • apps/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/core subpaths 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/v3 or deprecated client.defineJob.
Prisma is version 6.14.0. Use the Prisma client from internal-packages/database for all database operations.
For ClickHouse client, schema migrations, and analytics queries, use internal-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 // @Crumbs or wrap blocks in `// `#region` `@crumbs. They stay on the branch throughout development and are stripped by agentcrumbs strip before 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 the env export of env.server.ts instead of directly accessing process.env
Use subpath exports from @trigger.dev/core package instead of importing from the root @trigger.dev/core path

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

Files:

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

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

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

Files:

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

📄 CodeRabbit inference engine (AGENTS.md)

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

Files:

  • apps/webapp/sentry.server.ts
apps/**/*.{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.md for 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!

Comment on lines +4 to +21
// 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" },
},
];
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

🧩 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 -50

Repository: 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:


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.

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