Skip to content

feat(webapp,database): opt-in per-client Prisma driver adapters - #4539

Merged
ericallam merged 5 commits into
mainfrom
feat/prisma-adapter-pg-per-client-toggles
Aug 8, 2026
Merged

feat(webapp,database): opt-in per-client Prisma driver adapters#4539
ericallam merged 5 commits into
mainfrom
feat/prisma-adapter-pg-per-client-toggles

Conversation

@ericallam

@ericallam ericallam commented Aug 8, 2026

Copy link
Copy Markdown
Member

What

Adds an opt-in path to run each Prisma client through @prisma/adapter-pg (the node-postgres driver) instead of the built-in engine driver, controlled by a per-client env var, all off by default:

env var client
CONTROL_PLANE_DATABASE_WRITER_DRIVER_ADAPTER control-plane writer
CONTROL_PLANE_DATABASE_REPLICA_DRIVER_ADAPTER control-plane replica
RUN_OPS_DATABASE_WRITER_DRIVER_ADAPTER new run-ops writer
RUN_OPS_DATABASE_REPLICA_DRIVER_ADAPTER new run-ops replica
RUN_OPS_LEGACY_DATABASE_WRITER_DRIVER_ADAPTER legacy run-ops writer
RUN_OPS_LEGACY_DATABASE_REPLICA_DRIVER_ADAPTER legacy run-ops replica

With every flag unset the construction path is byte-identical to today (datasources URL + Rust engine), so this is inert until a flag is turned on. Per-client granularity allows enabling the adapter only where it's wanted.

How

  • Enables the driverAdapters preview feature on both schemas (@trigger.dev/database and @internal/run-ops-database). This keeps the Rust query engine — it does NOT add queryCompiler — so query behavior, result types, and engine tracing spans are unchanged.
  • A shared buildDriverAdapterPool builds each client's pg.Pool with an explicit max, a bounded connectionTimeoutMillis (the node-postgres pool otherwise waits unbounded on acquire), and an onPoolError handler (an unhandled idle-connection error would otherwise crash the process). Threaded through all four client builders via a useDriverAdapter flag.
  • Adds @prisma/adapter-pg + @types/pg to the webapp; pg is already pinned at 8.15.6 (adapter-pg 6.x requires pg < 8.17).

Connect-failure handling (the important correctness/security bit)

Under the adapter an unreachable DB no longer surfaces as PrismaClientInitializationError / P1001; it becomes a P2010 "Database not reachable: " (or a raw ECONNREFUSED/ENOTFOUND-class error). Two handlers are updated so a client on the adapter behaves like today:

  • isInfrastructureError now recognizes those shapes (P2010 with a connectivity message, and raw connectivity errno codes). Without this, the DB hostname would leak into API-client-facing errors and the failure would go unlogged. Security-relevant.
  • isPrismaRetriableError treats the adapter's pool-acquire timeout ("timeout exceeded when trying to connect") as retriable, preserving the P2024 retry behavior the adapter otherwise drops.

Evidence

Validated on an isolated stack that mirrors the production DB topology (chained PgBouncers in front of writer + reader):

  • Behavioral parity: raw-query results and Prisma error codes/meta are byte-identical between the engine driver and the adapter across the queried shapes (unique-constraint meta.target, record-not-found, transaction-timeout, serialization-failure, etc.).
  • Feature matrix: a full 380-project queue-ay pass shows no adapter-caused regressions — pass/fail parity between adapter-off and adapter-on, with the residual failures being pre-existing known-failures/flakes common to both.

Rollout / rollback

All flags default off; enable per client via env var, roll back by unsetting and redeploying (no data migration). Recommended first target is a single writer; enable one client at a time.

Follow-ups (not in this PR)

  • $metrics-based pool observability is removed under the adapter (the Prometheus route + db.pool.connections.* instruments); the metrics replacement (via pg.Pool counters) lands in a separate PR.
  • Note for operators: on the adapter path, interactive-transaction maxWait does not bound pool acquisition — connectionTimeoutMillis does.

Note on connection-string parameters

The adapter pool is built from the base DSN, so Prisma-specific DSN parameters that node-postgres does not understand are not honored when a client is on the adapter:

  • Prisma TLS spellings (sslaccept, sslcert, etc.) — node-postgres uses sslmode/ssl instead. Our production DSNs do not use these Prisma-specific TLS params, but any deployment whose DSN relies on them must be checked before enabling a flag.
  • pgbouncer=true and statement_cache_size — effectively moot under the adapter, which uses no persistent named prepared statements.

connection_limit, pool_timeout, and schema are handled explicitly (passed as max/connectionTimeoutMillis and PrismaPg's {schema} option).

refs TRI-13039

Add per-client env vars to route each Prisma client through @prisma/adapter-pg
(node-postgres) instead of the built-in engine driver. All default off, so
behavior is unchanged unless a flag is set:

- CONTROL_PLANE_DATABASE_WRITER_DRIVER_ADAPTER
- CONTROL_PLANE_DATABASE_REPLICA_DRIVER_ADAPTER
- RUN_OPS_DATABASE_WRITER_DRIVER_ADAPTER
- RUN_OPS_DATABASE_REPLICA_DRIVER_ADAPTER
- RUN_OPS_LEGACY_DATABASE_WRITER_DRIVER_ADAPTER
- RUN_OPS_LEGACY_DATABASE_REPLICA_DRIVER_ADAPTER

Enables the driverAdapters preview feature on both schemas (keeps the Rust
query engine; does not add queryCompiler). Each adapter pool is built with a
bounded connectionTimeoutMillis and an onPoolError handler.

Handle the connect-failure differences the adapter introduces:
- isInfrastructureError now recognizes the adapter's connect-failure shapes
  (P2010 'not reachable' and raw ECONNREFUSED/ENOTFOUND-class errors) so the DB
  host is still scrubbed from API-client errors and infra failures are logged.
- isPrismaRetriableError treats the adapter pool-acquire timeout as retriable,
  preserving the P2024 retry behavior.

refs TRI-13039

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@changeset-bot

changeset-bot Bot commented Aug 8, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: afbd62b

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.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

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

coderabbitai Bot commented Aug 8, 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

Walkthrough

The web application adds optional PostgreSQL driver-adapter support for control-plane, run-ops, and legacy run-ops Prisma writers and replicas. Environment flags independently enable each adapter. Adapter-backed clients use configured PostgreSQL pools. Default behavior continues to use datasource URLs. Prisma generators and package dependencies are updated. Connectivity detection handles adapter timeout messages, network errors, and connectivity-related P2010 errors. Prisma metrics failures no longer interrupt core metrics responses or tracer callbacks.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 and concisely describes the opt-in per-client Prisma driver-adapter change.
Description check ✅ Passed The description thoroughly explains the change, configuration, testing evidence, rollout, rollback, and follow-ups, but omits the template checklist and issue-closing line.
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 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/prisma-adapter-pg-per-client-toggles

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[bot]

This comment was marked as resolved.

- Pass the per-client resolved connection limit into the adapter pool instead
  of always using DATABASE_CONNECTION_LIMIT, so per-client overrides (e.g.
  RUN_OPS_DATABASE_READ_REPLICA_CONNECTION_LIMIT) are honored on the adapter path.
- Build the adapter pool from the base DSN (drops prisma-only URL params the pg
  driver ignores and the duplicate application_name).
- Scope the connectivity message match to 'database not reachable' so a generic
  'not reachable' error is no longer misclassified as infrastructure.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@ericallam
ericallam marked this pull request as ready for review August 8, 2026 18:05
devin-ai-integration[bot]

This comment was marked as resolved.

- Pass the datasource schema (?schema=) to PrismaPg as its {schema} option so
  custom-schema installs keep talking to the right schema on the adapter (the
  adapter does not honor ?schema= in the connection string).
- Set disposeExternalPool: true so $disconnect() closes the pg pool instead of
  leaking sockets, matching the engine-driver path.
- Guard the two $metrics consumers (the /metrics route and the OTel batch
  observable callback) so a client on a driver adapter degrades to empty metrics
  instead of failing the scrape / rejecting the callback.
- isPrismaRetriableError checks the adapter acquire-timeout message independently
  of the coded-error branch, so the pool-acquire retry still engages if the
  timeout arrives wrapped as a coded error.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@github-actions

github-actions Bot commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Observability map

As of afbd62b.

18/100 over 413 measured of 429 entry points (base 18, no change)

What this PR changed
No entry point this PR touches changed its score.

FIX FIRST

  • /api/v1/projects/:projectRef/envvars (sensitive) - auth-boundary, request-context
  • /auth/sso (sensitive) - auth-boundary, request-context
  • /_app/orgs/:organizationSlug/settings/team (sensitive) - error-classification, auth-scope, request-context

AUDIT 3 of 50 sensitive mutations record an actor. 47 without one.
CONTEXT 11 of 413 entry points name a tenant on a failure path. 324 appear only here, 39 of them sensitive, in the JSON rather than the fix list.

What the score is made of
CHECKS
  error-classification  169 applicable,  94 pass,   0 sole, global without it 10
  auth-boundary          62 applicable,  57 pass,   0 sole, global without it 15
  auth-scope             19 applicable,  17 pass,   0 sole, global without it 18
  request-context       413 applicable,  11 pass, 222 sole, global without it 63
  audit-trail            50 applicable,   3 pass,   0 sole, not in the score

The score and findings here are report-only and never gate the merge. Separately, a required test suite keeps this tool's symbol and route lists in sync with the code they name, and can fail a pull request that renames or removes a symbol they reference, or that adds the first route with a segment they anticipate. Each failure names the list to edit. The rules and their reasons: internal-packages/observability-map/README.md.

devin-ai-integration[bot]

This comment was marked as resolved.

The retry decision used retryCodes.includes(error.code) directly, inside the
isPrismaKnownError branch, so the broadened isPrismaRetriableError check never
governed retries. Route the retry decision through isPrismaRetriableError so the
adapter's pool-acquire timeout is retried like P2024 was, while keeping
prismaError()/swallow behavior for coded errors only.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
devin-ai-integration[bot]

This comment was marked as resolved.

…r drainer

isRetryablePgError only recognized the Rust engine's DB-unreachable shapes (P1001
/ "Can't reach database server"). Under a driver adapter the same outage surfaces
as P2010 "Database not reachable" / ECONNREFUSED / ENOTFOUND, so buffered runs
were permanently failed on a transient outage. Reuse the shared
looksLikeConnectivityError predicate (now exported from prismaErrors) so those
are retried too.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

@devin-ai-integration devin-ai-integration 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.

Devin Review found 1 new potential issue.

View 1 additional finding in Devin Review.

Open in Devin Review

Comment thread apps/webapp/app/db.server.ts
@ericallam
ericallam merged commit 90e8bd5 into main Aug 8, 2026
64 of 72 checks passed
@ericallam
ericallam deleted the feat/prisma-adapter-pg-per-client-toggles branch August 8, 2026 20: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.

3 participants