feat(webapp,database): bound Prisma list filter arity, drop unused query-engine metrics - #4480
feat(webapp,database): bound Prisma list filter arity, drop unused query-engine metrics#4480ericallam wants to merge 8 commits into
Conversation
Database list filters (`in` / `notIn`) expand to one bind parameter per element, so every distinct list length produced a different SQL statement and pushed other entries out of the pooler's prepared-statement cache. Values are now padded up to the next power of two by repeating the last element, which leaves results unchanged and collapses hundreds of statement shapes to a handful. Set DB_PAD_IN_LISTS=0 to disable. Separately, the metrics endpoint no longer depends on query-engine internals. Engine stats are an optional section rather than a prefix on the whole scrape body, so a failure there degrades one section instead of failing the entire endpoint. Query duration and error counts are now recorded from application code, keyed by database, datasource and operation.
|
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdded and exported 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
PrismaClientInitializationError carries its code on errorCode, not code, so connection failures such as P1001 were counted as unknown. Those are the failures this counter most needs to name.
The metrics endpoint exposed a block of query-engine counters and gauges that nothing consumes; database observability comes from the OpenTelemetry integration. Drops the engine metrics section, the observable gauges built on top of it, and the schema preview feature that enabled them.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
.server-changes/remove-prisma-engine-metrics.md (1)
6-6: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRewrite this release note in user-visible terms.
The entry exposes internal implementation details such as “query-engine metrics” and “OpenTelemetry integration.” Describe what users can observe instead.
Based on learnings,
.server-changesentries are published verbatim as dashboard-facing release notes and should describe user-visible behavior rather than internal implementation details.Proposed wording
-Remove the unused query-engine metrics from the metrics endpoint. Database observability continues through the existing OpenTelemetry integration. +The metrics endpoint now reports application and runtime metrics without unused database engine metrics.Source: Learnings
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: bd193fab-4f77-4263-a500-b90dc5360e1c
📒 Files selected for processing (6)
.server-changes/remove-prisma-engine-metrics.mdapps/webapp/app/db.server.tsapps/webapp/app/routes/metrics.tsapps/webapp/app/v3/tracer.server.tsinternal-packages/database/prisma/schema.prismainternal-packages/run-ops-database/prisma/schema.prisma
💤 Files with no reviewable changes (3)
- internal-packages/run-ops-database/prisma/schema.prisma
- internal-packages/database/prisma/schema.prisma
- apps/webapp/app/v3/tracer.server.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (15)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (11, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (3, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (7, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (2, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (5, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (6, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (8, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (1, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (10, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (12, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (9, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (4, 12)
- GitHub Check: e2e-webapp / 🧪 E2E Tests: Webapp
- GitHub Check: typecheck / typecheck
- GitHub Check: internal / 🧪 Unit Tests: Internal
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.{ts,tsx}: Use types over interfaces for TypeScript
Avoid using enums; prefer string unions or const objects instead
**/*.{ts,tsx}: Prefer static imports over dynamicimport(); use dynamic imports only for unresolvable circular dependencies, genuine performance code splitting, or conditional runtime loading.
Import Trigger.dev tasks from@trigger.dev/sdk; never use@trigger.dev/sdk/v3or deprecatedclient.defineJob.
Add agentcrumbs while writing code using approved namespaces; mark lines with//@Crumbsor blocks with `// `#region` `@crumbs, and strip them before merging.
Files:
apps/webapp/app/routes/metrics.tsapps/webapp/app/db.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/app/routes/metrics.tsapps/webapp/app/db.server.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Use function declarations instead of default exports
Files:
apps/webapp/app/routes/metrics.tsapps/webapp/app/db.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/app/routes/metrics.tsapps/webapp/app/db.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/corepathDo not reintroduce the removed v1 execution path;
RunEngineVersion.V1branches may only reject or finalize gracefully so v3 clients receive a clean 4xx, never a 5xx.
Files:
apps/webapp/app/routes/metrics.tsapps/webapp/app/db.server.ts
apps/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
For apps, use
typecheckfor verification and never usebuildas the correctness check.
Files:
apps/webapp/app/routes/metrics.tsapps/webapp/app/db.server.ts
apps/webapp/app/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/webapp/CLAUDE.md)
apps/webapp/app/**/*.{ts,tsx}: For dashboard changes, visually verify the running Remix app with Chrome DevTools MCP, using snapshots, screenshots, interaction, and console-message checks as appropriate.
UseuseCallbackanduseMemoonly for context provider values, expensive derived data used as a dependency, or stable references required by dependency arrays; do not wrap ordinary event handlers or trivial computations.
Use named constants for sentinel or placeholder values instead of scattering raw string literals across comparisons.
Files:
apps/webapp/app/routes/metrics.tsapps/webapp/app/db.server.ts
apps/webapp/app/routes/**/*.ts
📄 CodeRabbit inference engine (apps/webapp/CLAUDE.md)
apps/webapp/app/routes/**/*.ts: Use Remix flat-file route conventions with dot-separated segments; for example,api.v1.tasks.$taskId.trigger.tsmaps to/api/v1/tasks/:taskId/trigger.
PAT-authenticated API routes must resolve their target organization or project within the caller's membership scope, using a membership filter or a helper such asfindProjectByReforresolveOrganizationForApiUser; RBAC authorization alone is insufficient.
Files:
apps/webapp/app/routes/metrics.ts
apps/webapp/app/**/*.ts
📄 CodeRabbit inference engine (apps/webapp/CLAUDE.md)
apps/webapp/app/**/*.ts: Never userequest.signalto detect client disconnects. UsegetRequestAbortSignal()fromapp/services/httpAsyncStorage.server.ts, which is wired to Express response close events.
Access environment variables through theenvexport fromapp/env.server.ts; never useprocess.envdirectly.
Always use PrismafindFirstinstead offindUnique.
Always use the$transactionhelper from~/db.server, never callprisma.$transactionor$replica.$transactiondirectly. Pass isolation levels as strings, useSerializablefor correctness-critical read-then-write invariants, and guard possibly undefined helper results when a definite value is required.
Files:
apps/webapp/app/routes/metrics.tsapps/webapp/app/db.server.ts
🧠 Learnings (15)
📚 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/app/routes/metrics.tsapps/webapp/app/db.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/app/routes/metrics.tsapps/webapp/app/db.server.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:
apps/webapp/app/routes/metrics.tsapps/webapp/app/db.server.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:
apps/webapp/app/routes/metrics.tsapps/webapp/app/db.server.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:
apps/webapp/app/routes/metrics.tsapps/webapp/app/db.server.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:
apps/webapp/app/routes/metrics.tsapps/webapp/app/db.server.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:
apps/webapp/app/routes/metrics.tsapps/webapp/app/db.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/app/routes/metrics.tsapps/webapp/app/db.server.ts
📚 Learning: 2026-06-25T18:21:51.905Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4039
File: apps/webapp/app/routes/invite-revoke.tsx:0-0
Timestamp: 2026-06-25T18:21:51.905Z
Learning: During the Zod v4 migration in the triggerdotdev/trigger.dev webapp, ensure any imports from `conform-to/zod` use the Zod-4 subpath: `conform-to/zod/v4` (e.g., `import { parseWithZod } from "conform-to/zod/v4"`). Do not import from the package root `conform-to/zod`, because it is the Zod 3 implementation and may load Zod-3-only symbols (e.g., `ZodBranded`, `ZodEffects`), which can throw at module load (notably with `zod4.4.3`). This should be enforced across `apps/webapp/**/*` where helpers like `parseWithZod` and `conformZodMessage` are used.
Applied to files:
apps/webapp/app/routes/metrics.tsapps/webapp/app/db.server.ts
📚 Learning: 2026-07-03T17:10:21.498Z
Learnt from: 0ski
Repo: triggerdotdev/trigger.dev PR: 4148
File: apps/webapp/app/models/orgMember.server.ts:149-168
Timestamp: 2026-07-03T17:10:21.498Z
Learning: In triggerdotdev/trigger.dev, `User.email` (Prisma schema: `internal-packages/database/prisma/schema.prisma`) currently does NOT use `citext` and does NOT have a `lower(email)` functional unique index. Therefore, do not introduce Prisma queries like `where: { email: { equals: <value>, mode: "insensitive" } }` (or any case-insensitive lookup) against `User.email`, because it can force sequential scans of the `users` table under load. During review, ensure email is normalized (e.g., lowercased/trimmed) before both writes and subsequent lookups, and if true case-insensitive behavior/uniqueness is required, implement it via a separate app-wide migration (e.g., switch to `citext` and/or add a functional unique index with backfill) rather than bolting it onto individual feature PRs.
Applied to files:
apps/webapp/app/routes/metrics.tsapps/webapp/app/db.server.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:
apps/webapp/app/routes/metrics.tsapps/webapp/app/db.server.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:
apps/webapp/app/routes/metrics.tsapps/webapp/app/db.server.ts
📚 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/remove-prisma-engine-metrics.md
📚 Learning: 2026-07-26T13:14:02.968Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 4378
File: .server-changes/realtime-run-reads-from-primary.md:0-0
Timestamp: 2026-07-26T13:14:02.968Z
Learning: For files in the .server-changes directory, the body text is published verbatim as dashboard-facing user release notes. Write entries in terms of user-visible behavior (what users can do/see), and avoid implementation-oriented details such as environment-variable names, internal mechanisms, or configuration knobs. If you need to include operational/configuration specifics, put those details in the PR description instead of the .server-changes entry.
Applied to files:
.server-changes/remove-prisma-engine-metrics.md
📚 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/app/db.server.ts
🔇 Additional comments (2)
apps/webapp/app/db.server.ts (1)
33-33: LGTM!Also applies to: 135-135, 146-147, 155-155, 299-300, 304-309, 312-315, 316-319
apps/webapp/app/routes/metrics.ts (1)
1-2: LGTM!Also applies to: 15-15
Padding was applied to the whole Prisma args object, so it rewrote values as well as predicates: a write payload or JSON comparison value containing a field named in or notIn had its trailing element duplicated. Bounding list arity is better handled per call site, where filter context is unambiguous.
Prisma expands a list filter into one bind parameter per element, so every distinct list length is a separate prepared statement. Where the length tracks data volume, a single call site can mint hundreds of them. Those entries are used once each, but inserting them evicts entries that were being reused, so the cost lands on unrelated queries sharing the pooler's statement cache. An unbounded list also risks the 65535 bind-parameter ceiling. Adds boundedIn(), which pads a filter list to the next power of two by repeating its last element. IN and NOT IN ignore duplicates, so results are unchanged, and a call site drops from one statement per length to at most log2(cap). It pads by repeating rather than with null because x NOT IN (a, b, NULL) is never true. Lists above 32768 are returned unchanged so padding can never push a query past the parameter limit. Two oxlint rules require it: a list filter must be an inline array literal or a boundedIn() call. The first covers filters reached through where/having/cursor and deliberately never descends into data, create, update, set or equals, where a key named "in" is user data rather than a predicate. The second covers bare filter objects passed to where-building helpers, which the first cannot see. Applies the helper to all 74 existing call sites.
@trigger.dev/build
trigger.dev
@trigger.dev/core
@trigger.dev/python
@trigger.dev/react-hooks
@trigger.dev/redis-worker
@trigger.dev/rsc
@trigger.dev/schema-to-json
@trigger.dev/sdk
commit: |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
oxlint-plugins/prisma-in-filter.mjs (1)
74-97: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winClose the spread-element gap in
isBounded.
isBoundedtreats everyArrayExpressionas fixed-arity. An array literal that contains a spread of a variable-length value, for examplein: [...ids]orin: [...ids, "extra"], is still anArrayExpressionnode, so the rule accepts it. Its runtime length is not fixed, so it can still generate one prepared statement per distinct length, the exact problem this rule targets.Check for a
SpreadElementamong the array's elements before treating it as bounded.♻️ Proposed fix to reject spread elements in array literals
- if (current.type === "ArrayExpression") return true; + if (current.type === "ArrayExpression") { + return !current.elements.some((element) => element && element.type === "SpreadElement"); + }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: caddb080-ea79-480b-b56a-dce1a5739d97
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (43)
.oxlintrc.jsonapps/webapp/app/models/vercelIntegration.server.tsapps/webapp/app/presenters/v3/ApiBatchResultsPresenter.server.tsapps/webapp/app/presenters/v3/ApiRunListPresenter.server.tsapps/webapp/app/presenters/v3/EnvironmentVariablesPresenter.server.tsapps/webapp/app/presenters/v3/ErrorsListPresenter.server.tsapps/webapp/app/presenters/v3/PlaygroundPresenter.server.tsapps/webapp/app/presenters/v3/QueueListPresenter.server.tsapps/webapp/app/presenters/v3/SessionListPresenter.server.tsapps/webapp/app/presenters/v3/SessionPresenter.server.tsapps/webapp/app/presenters/v3/TestTaskPresenter.server.tsapps/webapp/app/presenters/v3/WaitpointPresenter.server.tsapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.environment-variables.new/route.tsxapps/webapp/app/routes/admin.api.v1.runs-replication.backfill.tsapps/webapp/app/routes/admin.feature-flags.tsxapps/webapp/app/routes/api.v2.whoami.tsapps/webapp/app/routes/engine.v1.dev.disconnect.tsapps/webapp/app/routes/resources.runs.$runParam.tsapps/webapp/app/services/realtime/runReader.server.tsapps/webapp/app/services/realtime/sessions.server.tsapps/webapp/app/services/runsBackfiller.server.tsapps/webapp/app/services/runsRepository/clickhouseRunsRepository.server.tsapps/webapp/app/services/secrets/secretStore.server.tsapps/webapp/app/services/sessionsRepository/clickhouseSessionsRepository.server.tsapps/webapp/app/services/taskIdentifierRegistry.server.tsapps/webapp/app/v3/runOpsMigration/controlPlaneResolver.server.tsapps/webapp/app/v3/services/alerts/errorAlertEvaluator.server.tsapps/webapp/app/v3/services/bulk/BulkActionV2.server.tsapps/webapp/app/v3/services/createBackgroundWorker.server.tsapps/webapp/app/v3/services/deployment.server.tsinternal-packages/database/package.jsoninternal-packages/database/src/boundedIn.test.tsinternal-packages/database/src/boundedIn.tsinternal-packages/database/src/index.tsinternal-packages/database/vitest.config.tsinternal-packages/run-engine/src/engine/index.tsinternal-packages/run-engine/src/engine/systems/executionSnapshotSystem.tsinternal-packages/run-engine/src/engine/systems/pendingVersionSystem.tsinternal-packages/run-engine/src/engine/systems/ttlSystem.tsinternal-packages/run-engine/src/engine/systems/waitpointSystem.tsinternal-packages/run-store/src/PostgresRunStore.tsinternal-packages/run-store/src/runOpsStore.tsoxlint-plugins/prisma-in-filter.mjs
…eline The boundedIn import shifted four line numbers in ApiBatchResultsPresenter, so the guard read its existing baseline entries as new violations. Same four violations, same file, one line lower.
The rule accepted any array literal as fixed-arity, but a literal containing a spread has runtime-variable length, so [...new Set(ids)] passed. It also walked only plain object properties, leaving filters assembled conditionally invisible: spread-conditional properties, ternary-valued properties, and logical-and objects. Ten further call sites were unbounded behind those shapes, including one in PostgresRunStore whose four sibling hydrators had all been converted.
| const targetIds = [...new Set(links.map((l) => l[joinTargetField]))]; | ||
| const rows = (await targetDelegate.findMany( | ||
| targetFindManyArgs({ id: { in: targetIds } }, projection, ["id"]) | ||
| targetFindManyArgs({ id: { in: boundedIn(targetIds) } }, projection, ["id"]) |
There was a problem hiding this comment.
🟡 Two database lookups still create a fresh query plan for every list size
Two list lookups are left unbounded while their immediate sibling is bounded (boundedIn(targetIds) at internal-packages/run-store/src/PostgresRunStore.ts:245), so those two lookups keep producing a brand-new database query plan for every distinct list length.
Impact: The exact statement-cache churn this change is meant to remove still happens on the run-graph join lookup and on the member environment lookup, so unrelated queries can still lose cached plans.
Why the two lint rules cannot see these sites
The PR states all existing list-filter sites were converted, but two remain:
-
internal-packages/run-store/src/PostgresRunStore.ts:237—where: { [joinParentField]: { in: parentIds } }. The key is a computed property, andpropertyKeyName()inoxlint-plugins/prisma-in-filter.mjsreturnsundefinedfor computed keys, so the walker skips the subtree.parentIdsis the whole batch of parent rows, i.e. exactly the data-volume-tracking fan-out the helper targets, and the very next query in the same function (line 245) was padded. -
apps/webapp/app/models/member.server.ts:237—projectId: { in: projects.map((project) => project.id) }is passed as a bare filter object tomemberDevelopmentEnvironmentWhere(...)and spread intowhere.reportListFiltersfollows aSpreadElementto its argument, but that argument is aCallExpression, which falls through to thenode.type !== "ObjectExpression"early return. The second rule (no-unbounded-list-filter-in-args-helper) only fires for helper names inFILTER_ARG_HELPERSor matching/(?:FindMany|FindFirst|FindUnique|Count|DeleteMany|UpdateMany)Args$/, andmemberDevelopmentEnvironmentWherematches neither.
Both are silent gaps: CI stays green while the call sites keep the unbounded arity.
Prompt for agents
Two Prisma list filters were not converted to boundedIn() and are invisible to both new oxlint rules.
Site 1: internal-packages/run-store/src/PostgresRunStore.ts, function batchHydrateJoinRelation — the join lookup uses `where: { [joinParentField]: { in: parentIds } }`. Because the key is a computed property, propertyKeyName() in oxlint-plugins/prisma-in-filter.mjs returns undefined and the walker never inspects the value. parentIds is the full parent batch, so its length tracks data volume. The sibling target lookup a few lines below was padded, making the omission inconsistent.
Site 2: apps/webapp/app/models/member.server.ts, getProjectsMissingMemberDevelopmentEnvironments — `projectId: { in: projects.map((project) => project.id) }` is passed as a bare where fragment to memberDevelopmentEnvironmentWhere() and spread into `where`. reportListFilters stops when a spread's argument is a CallExpression, and the args-helper rule only recognises a fixed name list plus a `*Args$` naming pattern, so neither rule fires.
Fix both call sites by wrapping the list in boundedIn(). Also consider closing the two detector gaps so future sites are caught: handle computed property keys whose key is a simple identifier reference, and either add memberDevelopmentEnvironmentWhere to FILTER_ARG_HELPERS or broaden the helper-name heuristic (e.g. names ending in `Where`).
Was this helpful? React with 👍 or 👎 to provide feedback.
|
|
||
| // Order matters, core metrics end with `# EOF`, prisma metrics don't | ||
| const metrics = prismaMetrics + coreMetrics; | ||
| const metrics = await metricsRegister.metrics(); |
There was a problem hiding this comment.
🔍 Metrics endpoint no longer concatenates two payloads
The old code relied on ordering because Prometheus metrics ended with # EOF while Prisma's did not; with the Prisma block gone the endpoint returns metricsRegister.metrics() verbatim, which is the correct single-source form. I confirmed no remaining $metrics usage anywhere in the repo, so dropping previewFeatures = ["metrics"] from both schemas leaves no dangling caller. Note this is a user-visible removal of scraped series (db.pool.connections.*, db.client.queries.*); any existing Grafana dashboards or alerts keyed on those names will go blank — worth confirming with whoever owns the dashboards, since the .server-changes note only says nothing consumes them.
Was this helpful? React with 👍 or 👎 to provide feedback.
Summary
Two changes to how the app talks to Postgres: bound the arity of list filters, and drop
query-engine metrics nobody consumes.
List filters. Prisma expands
in/notIninto one bind parameter per element, soevery distinct list length is a separate prepared statement. Where the length tracks data
volume (a batch size, a run-graph fan-out, a prior query's id set) one call site can mint
hundreds of them. Each is used about once, but inserting it evicts an entry that was being
reused, so the cost lands on unrelated queries sharing the pooler's statement cache. An
unbounded list also risks the 65535 bind-parameter ceiling.
boundedIn()pads a filter list to the next power of two by repeating its last element.INandNOT INignore duplicates, so results are unchanged, and a call site drops fromone statement per length to at most
log2(cap). Applied to all 84 existing sites.Metrics. The metrics endpoint exposed a block of query-engine counters and gauges that
nothing consumes, and which needed a schema preview feature to enable. Database
observability comes from the OpenTelemetry integration, so the endpoint section, the
observable gauges, and the preview feature on both schemas are all removed. This also
clears the way for the Rust-free Prisma client, where that API does not exist.
Enforcement
Two oxlint rules require the helper: a list filter must be an inline array literal or a
boundedIn()call.where/having/cursor, and deliberatelynever descends into
data,create,update,setorequals. A key namedininthose positions is user data, not a predicate, and rewriting it would corrupt what gets
stored or compared.
cannot see. It found five sites in the run-graph batch loaders that were otherwise
invisible.
Both rules follow filters through the shapes they are actually written in: conditional
expressions, logical-and objects, and spread-conditional properties. An array literal only
counts as fixed-arity when nothing spreads into it, since
[...new Set(ids)]has a runtimelength. Ten sites were hidden behind those shapes until the rules handled them.
Both are
error, so new call sites fail CI.Notes
boundedInpads by repeating rather than with null:x NOT IN (a, b, NULL)is never true,so null-padding a
notInfilter would silently return no rows. Lists above 32768 arereturned unchanged so padding can never push a query past the parameter limit.
Measured on a local rig: 300 distinct list lengths produce 300 prepared statements
unpadded, 10 padded.