Skip to content

feat: add QueryPlanCache class with LRU eviction for single and batch… - #29784

Closed
amalv35 wants to merge 2 commits into
prisma:v7from
amalv35:fix/memory-leak-in-query-compiler
Closed

amalv35 wants to merge 2 commits into
prisma:v7from
amalv35:fix/memory-leak-in-query-compiler

Conversation

@amalv35

@amalv35 amalv35 commented Jul 24, 2026

Copy link
Copy Markdown

What

Modifies QueryPlanCache in the client package to limit memory usage based on the total number of cached query plans rather than the number of cached batches.
Updates the QueryPlanCache test suite with additional test cases verifying the new eviction logic.

Why

Unbounded Memory Bloat
The previous implementation of QueryPlanCache stored up to 1000 batch entries in the batch cache. However, each batch was treated as a single entry regardless of how many individual query plans it contained. When executing dynamic transactions with highly variable batch sizes (such as mappings over an array of variable length), the cache keys were unique for each batch size. This resulted in caching hundreds of massive batch responses, accumulating hundreds of thousands of individual query plans. This caused Node heap memory to bloat up to 550MB in long running applications like web crawlers before hitting the 1000 entry limit.

Changes

packages/client
[MODIFY] src/runtime/core/engines/client/queryPlanCache.ts

  • Added a tracking property to count the aggregate number of query plans.
  • Updated setBatch to evaluate the query count of multi type batch responses and evict older batches when the total query count exceeds maxSize.
  • Prevented caching of single massive batches if their individual query count exceeds maxSize.

[MODIFY] src/runtime/core/engines/client/queryPlanCache.test.ts

  • Added tests to ensure setBatch properly accounts for the size of multi batch responses.
  • Added tests to verify that batches exceeding maxSize are not cached.

Testing

All unit tests in the query plan cache test suite pass successfully (15 tests total).

This pr resolves issue : #29774

@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

QueryPlanCache now accounts for the total number of queries contained in cached batch responses. Oversized batches are skipped, replacement updates the tracked total, and least-recently-used entries are evicted until the configured capacity is met. Clearing the cache resets the query counter. Tests cover multi-plan batch eviction, cache size reporting, and rejection of batches exceeding capacity.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is related to the cache eviction change, though it says 'add' and is broader than the actual modification.
Description check ✅ Passed The description matches the QueryPlanCache memory and eviction updates described in the diff.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
✨ Simplify code
  • Create PR with simplified code

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/client/src/runtime/core/engines/client/query-plan-cache.ts`:
- Around line 66-73: Update the existing-entry branch in the batch cache
insertion logic to remove the old entry and then reuse the common
insertion/eviction path, rather than returning after updating
`#batchCacheTotalQueries`. Ensure replacement batches trigger the same capacity
eviction loop as new entries, and add a regression case covering a replacement
that exceeds the plan limit.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: e3eb1f52-a7f1-481c-9953-6471f8762e20

📥 Commits

Reviewing files that changed from the base of the PR and between 28d393d and 92c8777.

📒 Files selected for processing (2)
  • packages/client/src/runtime/core/engines/client/query-plan-cache.test.ts
  • packages/client/src/runtime/core/engines/client/query-plan-cache.ts

Comment on lines 66 to 73
if (this.#batchCache.has(key)) {
// Update existing entry (also moves to end for LRU)
const oldResponse = this.#batchCache.get(key)!
this.#batchCacheTotalQueries -= oldResponse.type === 'multi' ? oldResponse.plans.length : 1
this.#batchCache.delete(key)
this.#batchCache.set(key, response)
this.#batchCacheTotalQueries += queryCount
return

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Evict after replacing an existing batch.

A larger replacement updates #batchCacheTotalQueries then returns at Line 73 without running the eviction loop. For example, a cache of 4 plans containing batches of 2 and 2 can replace one batch with 4 plans and retain 6 plans. Reuse the common insertion/eviction path after removing the old entry, and add a replacement regression case.

Proposed fix
     if (this.#batchCache.has(key)) {
-      // Update existing entry (also moves to end for LRU)
       const oldResponse = this.#batchCache.get(key)!
       this.#batchCacheTotalQueries -= oldResponse.type === 'multi' ? oldResponse.plans.length : 1
       this.#batchCache.delete(key)
-      this.#batchCache.set(key, response)
-      this.#batchCacheTotalQueries += queryCount
-      return
     }
 
     this.#batchCache.set(key, response)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (this.#batchCache.has(key)) {
// Update existing entry (also moves to end for LRU)
const oldResponse = this.#batchCache.get(key)!
this.#batchCacheTotalQueries -= oldResponse.type === 'multi' ? oldResponse.plans.length : 1
this.#batchCache.delete(key)
this.#batchCache.set(key, response)
this.#batchCacheTotalQueries += queryCount
return
if (this.#batchCache.has(key)) {
const oldResponse = this.#batchCache.get(key)!
this.#batchCacheTotalQueries -= oldResponse.type === 'multi' ? oldResponse.plans.length : 1
this.#batchCache.delete(key)
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/client/src/runtime/core/engines/client/query-plan-cache.ts` around
lines 66 - 73, Update the existing-entry branch in the batch cache insertion
logic to remove the old entry and then reuse the common insertion/eviction path,
rather than returning after updating `#batchCacheTotalQueries`. Ensure replacement
batches trigger the same capacity eviction loop as new entries, and add a
regression case covering a replacement that exceeds the plan limit.

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