Skip to content

feat(webapp,database): bound Prisma list filter arity, drop unused query-engine metrics - #4480

Draft
ericallam wants to merge 8 commits into
mainfrom
feat/db-metrics-and-in-list-padding
Draft

feat(webapp,database): bound Prisma list filter arity, drop unused query-engine metrics#4480
ericallam wants to merge 8 commits into
mainfrom
feat/db-metrics-and-in-list-padding

Conversation

@ericallam

@ericallam ericallam commented Aug 2, 2026

Copy link
Copy Markdown
Member

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 / notIn into one bind parameter per element, so
every 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.
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). 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.

  • The first covers filters reached through where / having / cursor, and deliberately
    never descends into data, create, update, set or equals. A key named in in
    those positions is user data, not a predicate, and rewriting it would corrupt what gets
    stored or compared.
  • The second covers bare filter objects passed to where-building helpers, which the first
    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 runtime
length. Ten sites were hidden behind those shapes until the rules handled them.

Both are error, so new call sites fail CI.

Notes

boundedIn pads by repeating rather than with null: x NOT IN (a, b, NULL) is never true,
so null-padding a notIn filter would silently return no rows. Lists above 32768 are
returned 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.

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.
@changeset-bot

changeset-bot Bot commented Aug 2, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: eb4604d

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 2, 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

Added and exported boundedIn to normalize eligible Prisma in and notIn filters. Updated webapp, run-engine, and run-store queries to use the helper. Added Vitest coverage and Oxlint rules for unbounded Prisma list filters. Removed Prisma engine metrics collection from the metrics route and tracer while retaining Node.js and host metrics.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 46.43% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description explains the changes in detail but omits the required issue, checklist, testing, changelog, and screenshots sections. Add the required template sections, complete the checklist, document testing steps, add a changelog entry, and provide an issue reference or state that none applies.
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly summarizes both primary changes: bounded Prisma list-filter arity and removal of unused query-engine metrics.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/db-metrics-and-in-list-padding

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.

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.
@ericallam ericallam changed the title perf(webapp): pad list filters, decouple db metrics from the engine perf(webapp): pad list filters, drop unused query-engine metrics Aug 3, 2026
@ericallam
ericallam marked this pull request as ready for review August 3, 2026 09:20

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
.server-changes/remove-prisma-engine-metrics.md (1)

6-6: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Rewrite 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-changes entries 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

📥 Commits

Reviewing files that changed from the base of the PR and between cedb54c and 823c46d.

📒 Files selected for processing (6)
  • .server-changes/remove-prisma-engine-metrics.md
  • apps/webapp/app/db.server.ts
  • apps/webapp/app/routes/metrics.ts
  • apps/webapp/app/v3/tracer.server.ts
  • internal-packages/database/prisma/schema.prisma
  • internal-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 dynamic import(); use dynamic imports only for unresolvable circular dependencies, genuine performance code splitting, or conditional runtime loading.
Import Trigger.dev tasks from @trigger.dev/sdk; never use @trigger.dev/sdk/v3 or deprecated client.defineJob.
Add agentcrumbs while writing code using approved namespaces; mark lines with // @Crumbs or blocks with `// `#region` `@crumbs, and strip them before merging.

Files:

  • apps/webapp/app/routes/metrics.ts
  • apps/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.ts
  • apps/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.ts
  • apps/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.ts
  • apps/webapp/app/db.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

Do not reintroduce the removed v1 execution path; RunEngineVersion.V1 branches may only reject or finalize gracefully so v3 clients receive a clean 4xx, never a 5xx.

Files:

  • apps/webapp/app/routes/metrics.ts
  • apps/webapp/app/db.server.ts
apps/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

For apps, use typecheck for verification and never use build as the correctness check.

Files:

  • apps/webapp/app/routes/metrics.ts
  • apps/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.
Use useCallback and useMemo only 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.ts
  • apps/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.ts maps 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 as findProjectByRef or resolveOrganizationForApiUser; 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 use request.signal to detect client disconnects. Use getRequestAbortSignal() from app/services/httpAsyncStorage.server.ts, which is wired to Express response close events.
Access environment variables through the env export from app/env.server.ts; never use process.env directly.
Always use Prisma findFirst instead of findUnique.
Always use the $transaction helper from ~/db.server, never call prisma.$transaction or $replica.$transaction directly. Pass isolation levels as strings, use Serializable for correctness-critical read-then-write invariants, and guard possibly undefined helper results when a definite value is required.

Files:

  • apps/webapp/app/routes/metrics.ts
  • apps/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.ts
  • apps/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.ts
  • apps/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.ts
  • apps/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.ts
  • apps/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.ts
  • apps/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.ts
  • apps/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.ts
  • apps/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.ts
  • apps/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.ts
  • apps/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.ts
  • apps/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.ts
  • apps/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.ts
  • apps/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

devin-ai-integration[bot]

This comment was marked as resolved.

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.
@ericallam ericallam changed the title perf(webapp): pad list filters, drop unused query-engine metrics refactor(webapp): drop unused query-engine metrics Aug 3, 2026
@ericallam
ericallam marked this pull request as draft August 3, 2026 09:47
devin-ai-integration[bot]

This comment was marked as resolved.

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.
@ericallam ericallam changed the title refactor(webapp): drop unused query-engine metrics feat(webapp,database): bound Prisma list filter arity, drop unused query-engine metrics Aug 3, 2026
@pkg-pr-new

pkg-pr-new Bot commented Aug 3, 2026

Copy link
Copy Markdown

Open in StackBlitz

@trigger.dev/build

npm i https://pkg.pr.new/@trigger.dev/build@411fff9

trigger.dev

npm i https://pkg.pr.new/trigger.dev@411fff9

@trigger.dev/core

npm i https://pkg.pr.new/@trigger.dev/core@411fff9

@trigger.dev/python

npm i https://pkg.pr.new/@trigger.dev/python@411fff9

@trigger.dev/react-hooks

npm i https://pkg.pr.new/@trigger.dev/react-hooks@411fff9

@trigger.dev/redis-worker

npm i https://pkg.pr.new/@trigger.dev/redis-worker@411fff9

@trigger.dev/rsc

npm i https://pkg.pr.new/@trigger.dev/rsc@411fff9

@trigger.dev/schema-to-json

npm i https://pkg.pr.new/@trigger.dev/schema-to-json@411fff9

@trigger.dev/sdk

npm i https://pkg.pr.new/@trigger.dev/sdk@411fff9

commit: 411fff9

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
oxlint-plugins/prisma-in-filter.mjs (1)

74-97: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Close the spread-element gap in isBounded.

isBounded treats every ArrayExpression as fixed-arity. An array literal that contains a spread of a variable-length value, for example in: [...ids] or in: [...ids, "extra"], is still an ArrayExpression node, 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 SpreadElement among 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

📥 Commits

Reviewing files that changed from the base of the PR and between 823c46d and 411fff9.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (43)
  • .oxlintrc.json
  • apps/webapp/app/models/vercelIntegration.server.ts
  • apps/webapp/app/presenters/v3/ApiBatchResultsPresenter.server.ts
  • apps/webapp/app/presenters/v3/ApiRunListPresenter.server.ts
  • apps/webapp/app/presenters/v3/EnvironmentVariablesPresenter.server.ts
  • apps/webapp/app/presenters/v3/ErrorsListPresenter.server.ts
  • apps/webapp/app/presenters/v3/PlaygroundPresenter.server.ts
  • apps/webapp/app/presenters/v3/QueueListPresenter.server.ts
  • apps/webapp/app/presenters/v3/SessionListPresenter.server.ts
  • apps/webapp/app/presenters/v3/SessionPresenter.server.ts
  • apps/webapp/app/presenters/v3/TestTaskPresenter.server.ts
  • apps/webapp/app/presenters/v3/WaitpointPresenter.server.ts
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.environment-variables.new/route.tsx
  • apps/webapp/app/routes/admin.api.v1.runs-replication.backfill.ts
  • apps/webapp/app/routes/admin.feature-flags.tsx
  • apps/webapp/app/routes/api.v2.whoami.ts
  • apps/webapp/app/routes/engine.v1.dev.disconnect.ts
  • apps/webapp/app/routes/resources.runs.$runParam.ts
  • apps/webapp/app/services/realtime/runReader.server.ts
  • apps/webapp/app/services/realtime/sessions.server.ts
  • apps/webapp/app/services/runsBackfiller.server.ts
  • apps/webapp/app/services/runsRepository/clickhouseRunsRepository.server.ts
  • apps/webapp/app/services/secrets/secretStore.server.ts
  • apps/webapp/app/services/sessionsRepository/clickhouseSessionsRepository.server.ts
  • apps/webapp/app/services/taskIdentifierRegistry.server.ts
  • apps/webapp/app/v3/runOpsMigration/controlPlaneResolver.server.ts
  • apps/webapp/app/v3/services/alerts/errorAlertEvaluator.server.ts
  • apps/webapp/app/v3/services/bulk/BulkActionV2.server.ts
  • apps/webapp/app/v3/services/createBackgroundWorker.server.ts
  • apps/webapp/app/v3/services/deployment.server.ts
  • internal-packages/database/package.json
  • internal-packages/database/src/boundedIn.test.ts
  • internal-packages/database/src/boundedIn.ts
  • internal-packages/database/src/index.ts
  • internal-packages/database/vitest.config.ts
  • internal-packages/run-engine/src/engine/index.ts
  • internal-packages/run-engine/src/engine/systems/executionSnapshotSystem.ts
  • internal-packages/run-engine/src/engine/systems/pendingVersionSystem.ts
  • internal-packages/run-engine/src/engine/systems/ttlSystem.ts
  • internal-packages/run-engine/src/engine/systems/waitpointSystem.ts
  • internal-packages/run-store/src/PostgresRunStore.ts
  • internal-packages/run-store/src/runOpsStore.ts
  • oxlint-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.
coderabbitai[bot]

This comment was marked as resolved.

@ericallam
ericallam marked this pull request as ready for review August 3, 2026 14:25
devin-ai-integration[bot]

This comment was marked as resolved.

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.
@ericallam
ericallam marked this pull request as draft August 3, 2026 14:42

@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 2 new potential issues.

Open in Devin Review

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"])

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.

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

  1. internal-packages/run-store/src/PostgresRunStore.ts:237where: { [joinParentField]: { in: parentIds } }. The key is a computed property, and propertyKeyName() in oxlint-plugins/prisma-in-filter.mjs returns undefined for computed keys, so the walker skips the subtree. parentIds is 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.

  2. apps/webapp/app/models/member.server.ts:237projectId: { in: projects.map((project) => project.id) } is passed as a bare filter object to memberDevelopmentEnvironmentWhere(...) and spread into where. reportListFilters follows a SpreadElement to its argument, but that argument is a CallExpression, which falls through to the node.type !== "ObjectExpression" early return. The second rule (no-unbounded-list-filter-in-args-helper) only fires for helper names in FILTER_ARG_HELPERS or matching /(?:FindMany|FindFirst|FindUnique|Count|DeleteMany|UpdateMany)Args$/, and memberDevelopmentEnvironmentWhere matches 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`).
Open in Devin Review

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();

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.

🔍 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.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

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