Skip to content

perf(param-graph): reuse decoded schemas across client instances - #30687

Merged
wmadden-electric merged 4 commits into
prisma:v7from
levish0:cache-param-graph-deserialization
Nov 19, 2026
Merged

wmadden-electric merged 4 commits into
prisma:v7from
levish0:cache-param-graph-deserialization

Conversation

@levish0

@levish0 levish0 commented Oct 12, 2026 •

Copy link
Copy Markdown

Linked issue

Refs #30645. This addresses repeated ParamGraph deserialization in Prisma 7; it does not resolve the issue's first-client startup costs.

Summary

Creating a new Prisma Client per request repeatedly decodes the same parameterization schema, allocating a complete input/output graph for every live client. This is especially expensive for request-scoped clients in Cloudflare Workers, where a single client cannot own database sockets across requests.

Cache decoded ParamGraphData in a WeakMap keyed by the generated client's immutable SerializedParamGraph object. Each call still creates a fresh ParamGraph wrapper, string index and enum lookup. Different schema objects remain isolated, failed decodes are not cached, and no client, adapter, connection or query data is shared. This source change applies to the Prisma 7 runtimes rather than only the edge bundle.

Testing performed

  • pnpm --filter @prisma/param-graph test: 17 tests pass (8 new wrapper/cache tests and 9 existing serialization tests). Before the implementation, the two cache-reuse assertions fail with 2/4 decodes instead of 1/2.
  • pnpm --filter @prisma/param-graph build: CJS/ESM bundles and declarations build successfully; both built entry points pass a construction smoke check.
  • Package source typecheck, standalone benchmark typecheck, ESLint with zero warnings, Prettier and git diff --check pass.
  • actionlint .github/workflows/test-template.yml passes. The package tests are added to the Linux client-internals Node matrix and the Windows/macOS no-docker job.
  • Independent review covered shared-data safety, schema and enum isolation, and CI wiring.

The full Prisma Client functional/database suites have not been run in this checkout.

Reproduction and measurements

From the repository root after installing dependencies:

node --expose-gc --import tsx packages/param-graph/helpers/benchmark-deserialization.ts 32 4096

The committed script uses a synthetic graph: 4,096 input nodes, 4,096 output nodes, 16 fields per node and a 16-entry string table. It keeps 32 wrappers alive, measures the first construction separately, and measures additional retained heap after explicit GC. It performs no database work and verifies graph access on every wrapper. Copy the same script onto the base revision to compare.

Example run on Windows, Node v24.12.0, base 97ea359250335c1a174504c9b2b7e5fe030ab937:

Measurement Base This change
First construction 7.895 ms 7.448 ms
Next 31 constructions, total 194.126 ms 0.079 ms
Additional retained heap after the first wrapper 323,224,704 bytes 15,768 bytes

These are illustrative measurements of the ParamGraph factory, not end-to-end Prisma Client timings. The deliberately small string table does not represent the per-instance string-index cost of a large generated schema. Time measurements are not asserted by the unit tests.

Skill update

n/a: internal Prisma 7 runtime change. Package documentation and agent notes describe the reuse contract and standalone reproduction.

Checklist

  • All commits are signed off and GPG-signed.
  • Read the v7 contribution rules; the change is scoped to repeated deserialization.
  • Added regression tests and connected them to CI.
  • Filled in the skill-update section.

Notes for the reviewer

The cache assumes the generated serialized schema is not mutated after a successful decode; this is now explicit in the factory documentation. Weak keys avoid retaining discarded schema objects. The first decode remains eager, and query-compiler initialization is unchanged. Linking the issue with Refs is intentional so merging this improvement does not close the broader startup report.

Summary by CodeRabbit

  • Performance
    • Repeatedly deserializing the same unchanged parameter graph now reuses decoded data, while returning separate graph instances with their own enum lookups.
    • Added a benchmark for comparing the time and memory use of single and repeated deserialization.
  • Documentation
    • Documented the behavior and benchmark for repeated deserialization, including the requirement not to modify a graph after it has been successfully deserialized.
  • Tests
    • Added coverage for reuse, schema isolation, enum lookups, and recovery from failed deserialization.

Signed-off-by: Levi Laine <shiueo.csh@gmail.com>
Signed-off-by: Levi Laine <shiueo.csh@gmail.com>
@coderabbitai

coderabbitai Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

Run configuration

  • Source mode: Auto
  • Repository: prisma/orm
  • Branch: v7
  • File: .coderabbit.yml
  • Commit: f8e30b5
  • Layers: Repository YAML
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 5a91cefd-2ed8-4d7d-834e-8331e6aaedb2
Commits

Reviewing files that changed from the base of the PR and between 4e32d2b and c3237e6.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review

No actionable comments were generated in the recent review.

Walkthrough

ParamGraph.deserialize now caches decoded graph data by serialized object identity while returning a separate wrapper for each call. The changes add regression tests, a benchmark, documentation, and CI test steps for packages/param-graph.

Changes: ParamGraph deserialization cache

Layer / File(s) Summary
Cache implementation and validation
packages/param-graph/src/param-graph.ts, packages/param-graph/src/param-graph.test.ts, .github/workflows/test-template.yml
ParamGraph.deserialize reuses decoded data for the same serialized object and still creates a new wrapper per call. Tests cover cache reuse, wrapper-specific enum lookups, schema isolation, returned views, and retry behavior. CI adds package test steps to two jobs.
Benchmark and cache documentation
packages/param-graph/helpers/benchmark-deserialization.ts, packages/param-graph/README.md, AGENTS.md
The benchmark reports deserialization timing and additional heap use. The README and architecture note describe cache behavior and benchmark usage.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Refactor

Suggested reviewers: aqrln

Merge Risk: Minimal · previous review 4e32d

No merge-blocking issue was identified; the change is ready for normal merge checks.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 4e32d

Schema reuse remains isolated by object identity, and each client retains its own wrapper and enum lookup. No new request-controlled path to shared schema data was established. The main residual risk is compatibility with code that mutates a schema after initialization, which the new contract explicitly prohibits.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The shared-state scope is client wrappers using the same serialized object in the same loaded ParamGraph class. Distinct schema objects have separate entries. Violating schema immutability could affect multiple wrappers within that scope, but no request-controlled producer of the schema object was established.

Trust Boundaries and Controls

  • observed — Generated schema configuration supplies structural data at engine construction. Query inputs reach parameterization later and do not supply SerializedParamGraph. Enum lookup remains per-wrapper, and returned root and edge records do not expose cached structural records directly.

Resilience and Maintainability Implications

  • inferred — For ordinary generated objects, synchronous construction prevents partially decoded data from becoming visible through the cache. Weak keys do not keep discarded schema objects alive, and decoded values do not retain the key object itself. Collection timing remains runtime-dependent.

Hardening Proposals

  • proposed — If custom loaders or runtime schema replacement become supported, enforce immutable schema ownership or replace the entire serialized object when changing schemas. This would strengthen the cache contract; it is not remediation for a verified attack path.
Pre-merge checks | Passed 4 | Failed 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%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 3 files. (3 skipped: 3 … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: reusing decoded ParamGraph schemas across client instances for performance.
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.
Full details: Docstring Coverage

Explanation

Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 3 files. (3 skipped: 3 unsupported.)

Finishing Touches

🧪 Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
ℹ️ Recent review info

⚙️ Run configuration

  • Configuration used: Repository: prisma/orm/.coderabbit.yml
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 23a107de-bd1c-489f-8eda-7827561a1850
📥 Commits

Reviewing files that changed from the base of the PR and between 97ea359 and 4e32d2b.

📒 Files selected for processing (6)

  • .github/workflows/test-template.yml
  • AGENTS.md
  • packages/param-graph/README.md
  • packages/param-graph/helpers/benchmark-deserialization.ts
  • packages/param-graph/src/param-graph.test.ts
  • packages/param-graph/src/param-graph.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

wmadden-electric and others added 2 commits November 20, 2026 08:04
The package README already describes the cache and the benchmark.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: willbot <w.a.madden+machine@gmail.com>
Signed-off-by: Will Madden <madden@prisma.io>

@wmadden-electric wmadden-electric 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.

Thank you. The decoded graph is only read, so sharing it across clients is safe. I merged v7 in and removed the unrelated AGENTS.md edit; the CI change stays, since nothing else runs these tests on v7.

@wmadden-electric
wmadden-electric merged commit 8d8ac63 into prisma:v7 Nov 19, 2026
253 of 254 checks passed
ksalesin pushed a commit to ksalesin/classmoji that referenced this pull request Dec 2, 2026
Workers builds carry prisma/orm#30687 for @prisma/client 7.10.1: the
runtime the Workers client imports caches ParamGraph.deserialize's result
in a WeakMap keyed by the serialized schema. The build fails if the
function or version does not match, or if nothing was patched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.

2 participants