Skip to content

fix(client): bound QueryPlanCache batch memory by total query plans - #29785

Closed
arab971 wants to merge 4 commits into
prisma:v7from
arab971:fm/query-compiler-leak
Closed

arab971 wants to merge 4 commits into
prisma:v7from
arab971:fm/query-compiler-leak

Conversation

@arab971

@arab971 arab971 commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes unbounded memory growth in QueryPlanCache where each batch was counted as one entry regardless of how many individual query plans it contained. With maxSize=1000, if every batch held 1000 plans, the cache could accumulate 1,000,000 query plans while appearing to respect the limit.

Changes

Root causes fixed

  1. Batch eviction now tracks total query plans — a new #batchCacheTotalQueries counter ensures the while(totalQueries > maxSize) loop actually caps the number of cached query plans, not batches. Previously, #batchCache.size >= #maxSize meant the cache could hold unbounded plans per batch entry.

  2. Replacement entries trigger eviction — old setBatch returned early after updating an existing entry, skipping the eviction loop entirely. Now replaced entries flow through the same insertion+eviction path as new keys. CodeRabbit caught this regression: replacing a 1-plan batch with a 4-plan batch in a 4-plan cache would leave 6 total plans in cache.

  3. Skip oversized single batches — a new guard rejects setBatch of a single batch whose query count already exceeds maxSize, preventing a single query from exhausting the entire cache.

Files Changed

File Change
packages/client/src/runtime/core/engines/client/query-plan-cache.ts Core fix: #batchCacheTotalQueries, while loop, skip guard
packages/client/src/runtime/core/engines/client/query-plan-cache.test.ts 3 new tests: LRU-by-plan-count, replacement regression, oversized skip

Testing

All 16 QueryPlanCache unit tests pass:

✓ evicts oldest batch entry when at capacity (tracking total queries)
✓ triggers eviction when replacing an existing batch exceeds max total queries  
✓ does not cache a batch if its queries exceed maxSize

Related Issues

Closes #29774 (memory leak in query compiler, memory grows from ~100MB to ~550MB over an hour).
Relates to PR #29784 (incoming QueryPlanCache update with same goal but missing the replacement-eviction fix).

Summary by CodeRabbit

  • Bug Fixes
    • Improved query-plan cache capacity management by accounting for the total number of cached queries across batch entries.
    • Batch entries are now evicted as needed to remain within the configured cache limit.
    • Oversized batches are no longer cached.
    • Replacing an existing batch correctly updates cache capacity and triggers eviction when necessary.
    • Empty and compacted batches now contribute accurately to cache usage calculations.

Fixes unbounded memory growth in QueryPlanCache where each batch was counted
as one entry regardless of how many individual query plans it contained.
With maxSize=1000, if every batch held 1000 plans, the cache could accumulate
1,000,000 query plans while appearing to respect the limit.

Fixes two related issues:
1. Batch eviction now tracks total query plans (not just batch count),
   ensuring total cached plans never exceed maxSize.
2. Replacement entries (existing key in setBatch) now trigger the eviction
   loop instead of returning early, preventing the total from growing
   unbounded when the same batch key is repeatedly replaced with larger
   response batches.

Tests added:
- 'evicts oldest batch entry when at capacity (tracking total queries)'
  verifies LRU eviction based on plan count not entry count.
- 'triggers eviction when replacing an existing batch exceeds max total
  queries' is a regression test for the early-return replacement bug.
- 'does not cache a batch if its queries exceed maxSize' verifies that
  oversized single batches are silently skipped.

Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 60c0368a-18d6-4fea-90f4-4283d053f776

📥 Commits

Reviewing files that changed from the base of the PR and between 5a18c48 and 53a7294.

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

📝 Walkthrough

Walkthrough

QueryPlanCache now tracks aggregate query counts for cached batch responses. It counts multi-batch plans with a minimum of one and compacted batches by execution count, rejects oversized batches, adjusts totals on replacement, evicts oldest entries until within capacity, and resets accounting when cleared. Tests cover these behaviors.

Changes

Batch cache capacity

Layer / File(s) Summary
Track and enforce aggregate batch capacity
packages/client/src/runtime/core/engines/client/query-plan-cache.ts
Batch entries are accounted for by aggregate query count, oversized entries are skipped, replacements adjust totals, oldest entries are evicted until capacity is restored, and clearing resets the counter.
Validate aggregate eviction scenarios
packages/client/src/runtime/core/engines/client/query-plan-cache.test.ts
Tests cover aggregate eviction, replacement, oversized and empty batches, compacted execution counts, and related literal typing cleanup.

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

Suggested reviewers: sijie-z

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: bounding QueryPlanCache batch growth by total query plans.
Linked Issues check ✅ Passed The cache now limits retained query plans and evicts by total plan count, matching the memory-leak fix requested in #29774.
Out of Scope Changes check ✅ Passed The changes stay focused on QueryPlanCache eviction logic and related regression tests, with no clear unrelated additions.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

🤖 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 @.status.txt:
- Around line 1-2: Remove the scratch investigation log .status.txt from the
change unless repository policy explicitly requires it; retain only source or
documentation files intended for long-term maintenance.

In `@packages/client/src/runtime/core/engines/client/query-plan-cache.ts`:
- Around line 59-64: Update the queryCount calculation in setBatch to count
every cached batch as at least one query, including multi responses with an
empty plans array. Preserve the existing plans.length count for non-empty multi
responses and the single-query count for other response types so empty entries
contribute to `#batchCacheTotalQueries` and trigger eviction.
- Line 59: Update the queryCount calculation in the query-plan cache to
distinguish both BatchResponse variants: count multi responses using
response.plans.length, and count compacted responses using
response.arguments.length. Use this execution count when evicting entries from
`#batchCache`.
🪄 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: 779529df-a6ed-4bd8-83da-08a744284415

📥 Commits

Reviewing files that changed from the base of the PR and between 28d393d and 8a56475.

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

Comment thread .status.txt Resolved
Address 3 CodeRabbit findings on the QueryPlanCache fix:

1. Remove .status.txt scratch file from the PR (not project docs)

2. CompactedBatchResponse now counts as arguments.length not 1.
   response.type === 'compacted' entries with many argument sets previously
   counted as 1 toward the eviction budget regardless of how many actual
   executions they represented — another unbounded-growth path.

3. Empty multi batches count as 1 (Math.max(plans.length, 1)).
   A { type:'multi', plans:[] } batch previously contributed 0 to
   batchCacheTotalQueries and could never trigger eviction.

All 18 tests pass.

Co-Authored-By: Claude <[email protected]>
@arab971

arab971 commented Jul 24, 2026

Copy link
Copy Markdown
Contributor Author

Hey @aqrln, this PR fixes a memory leak in QueryPlanCache that was causing unbounded memory growth (the root cause of issue #29774). Key changes:

  • Batch cache now tracks total query plans (not just entry count) so maxSize truly caps memory
  • CompactedBatchResponse entries count as arguments.length (not 1), preventing a single compacted batch with many argument sets from consuming the entire budget
  • Empty multi batches floor at 1 plan to prevent bypass of eviction
  • Replacement entries (same cache key) now properly trigger the LRU eviction loop (was returning early before)

All 18 unit tests pass. CI checks are running. Could you take a look when you get a chance?

Comment on lines +158 to +168
cache.setBatch('key1', {
type: 'multi' as const,
plans: [
{ type: 'value' as const, args: 1 },
{ type: 'value' as const, args: 2 },
],
}) // Total: 2
cache.setBatch('key2', {
type: 'multi' as const,
plans: [{ type: 'value' as const, args: 3 }],
}) // Total: 3

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

why do we need as const everywhere here, can't TypeScript infer it from the argument type?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

as const on variables preserves the literal type discriminator — without it TS widens 'value' to string, breaking assignability to QueryPlanNode.

@tensordreams
tensordreams changed the base branch from main to v7 July 28, 2026 08:51
@arab971
arab971 requested a review from aqrln July 28, 2026 18:34
@arab971

arab971 commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @aqrln , @nurul3101 @sorenbs could you please take a look at this PR when you have a moment? Thanks in advance!

@wmadden-electric

Copy link
Copy Markdown
Contributor

Thank you. The batch plan cache is already limited by its number of entries; the memory comes from a few very large plans. #30581 stops caching those, which fixes the measured cause without changing what queryPlanCacheMaxSize means. Closing this one.

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.

Possible memory leak in query compiler

3 participants