perf(shared): cached SQLite statements no longer hold large parameters #17785
main fromrefs/pull/17785/head·opened View on GitHubProblem#
packages/shared/src/nodeSqliteClient.ts keeps up to 200 prepared statements in a cache for 10 minutes. SQLite keeps its own copy of a statement's text and blob parameters until the statement is bound again or finalized, and node:sqlite has no way to clear them. Each cached statement therefore pins the last payload it ran with. That memory is native: it shows in RSS and not in heapUsed. The server writes serialised event and projection payloads through this client, so those are the payloads that stay pinned.
Change#
An execution that binds more than 64 KiB of text and blob data in total now runs on a throwaway statement that nothing retains, so it is finalized when it is collected. Everything else uses the prepare cache as before. Both execution paths (run and runValues) pick their statement the same way.
- The size check counts string length and
byteLengthof buffer views, including the values of a named-parameter object. If measuring a parameter throws, the execution takes the throwaway statement and the statement reports the error through the existing classification. - The values path used to inherit its integer mode from whatever last ran on the cached statement. A throwaway statement has no such history, so the values path now sets the mode from the caller's
SafeIntegers, asrunalready did and as@effect/sql-sqlite-nodedoes. This is needed for the same fix: without it a large-parameter.valuesquery underSafeIntegersstops returning BigInts. The visible consequence is that a cached.valuesquery no longer returns BigInts just because an earlierSafeIntegersquery ran the same SQL. The onlySafeIntegersuser in the repo isapps/server/scripts/t3-sqlite-state.ts.
Alternatives I ruled out:
- Clearing bindings after execution.
StatementSyncon Node 24.13.1 exposesiterate,all,get,run,columnsand four setters; there is no reset, clear-bindings or dispose. - Calling
iterate()with no parameters to rebind without stepping. It only works becauseiterate()happens to be lazy; where it steps eagerly it would execute writes with null parameters.
Cost: small-parameter executions pay one loop over their parameters. Large ones pay a prepare and a fresh binding buffer each time. Measured on a 6-parameter upsert, a fresh statement against a reused one took 49 vs 33 µs at a 64 KiB payload and 580 vs 188 µs at 1 MiB; preparing alone is about 4.4 µs. The 64 KiB threshold is a judgement, not derived from real payload sizes. It bounds worst-case retention at about 12.8 MiB (200 statements × 64 KiB, more for multi-byte text because strings are counted in UTF-16 units).
Scope and approval#
No prior issue or discussion. This is a focused memory fix in one file with no change to contracts, product behaviour or defaults: cached statements were holding payloads nobody can read back. I am submitting it under the small, focused fix exception; if you would rather see an issue first, say so and I will open one with the reproduction below.
Verification#
How I established the problem, on Node 24.13.1 (the repo's engines), SQLite 3.51.2, Linux x64. A standalone script opens an in-memory database and prepares 32 distinct SELECT length(?) statements, so nothing is stored and anything retained is the binding. It runs each with a 1 MiB value and samples process.memoryUsage() after forced GC.
| Step | RSS vs baseline | heapUsed vs baseline |
|---|---|---|
| 32 kept statements, each run with a 1 MiB string | +35.1 MiB | +1.0 MiB |
| Same statements rebound to empty strings | +0.3 MiB | 0.0 |
| 32 throwaway statements, each run with a 1 MiB string | +1.3 MiB | +1.0 MiB |
32 kept statements, each run with a 1 MiB Uint8Array | +38.2 MiB | 0.0 |
- Without any explicit GC, 640 throwaway executions of 1 MiB peaked at +6 MiB RSS, so ordinary collection finalizes them.
- Through this client, same 32 × 1 MiB shape: +33.6 MiB RSS on
c77a7b7eeband about +0.6 MiB with the bypass, two runs each. I measured this on the first version of the change and did not repeat it after the review fixes, which did not touch the bypass for positional parameters.
Checks, run in packages/shared on Node 24.13.1:
vp test run --config ../../vite.config.ts src/nodeSqliteClient.test.ts: 11 passed.vp lintandvp fmt --checkon the two changed files, andtsc --noEmit: exit 0.
The three new tests, each of which failed before the part of the change it covers:
- Large text and blob parameters, positional and named, on both paths, never run on a statement that is used again, while small parameters keep reusing one cached statement per query.
- The values path reads integers as the caller asked, cached or not.
- A parameter that cannot be measured (a
DataViewover a detached buffer, a throwing getter) gives the same result or a classifiedexecuteerror.
The tests assert which statement an execution ran on, not a memory number, since RSS is not a stable assertion.
Not checked:
- How much memory this saves on a real server, or how often real event and projection payloads exceed 64 KiB. Everything above is synthetic.
- Finalization timing under sustained server load.
- Electron's bundled Node, and Node versions other than 24.3.0 and 24.13.1.
Known limitation: the size check reads a named-parameter object's values once before node:sqlite reads them, so a getter that returns a different value on each read is read one extra time. No caller in the repo passes named parameters.
Claude Opus 5.5 in Claude Code, running inside T3 Code. Reviewed by GPT-6.1-Sol in Codex.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:M
Approvability#
Verdict: Approved at
07988bdMacroscope's review found this PR approvable — This is a narrowly scoped SQLite memory-retention fix that preserves cached execution for small parameters while safely bypassing the cache for large or unmeasurable bindings. Production behavior is covered by focused tests, with no schema, deployment, security, billing, authentication, default, or static-analysis changes.
Notes:
- Diff unchanged. Approvability was decided on eligibility alone.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
-
⚙️ Run configuration
-
- Configuration used: Path: .coderabbit.config.ts
- Review profile: CHILL
- Plan: Advanced
- Run ID:
6ff72cc8-8293-4d57-9753-d6b40347d74a
📥 Commits
-
Reviewing files that changed from the base of the PR and between c77a7b7eebd6ea8a3a63bbcaaa7c1707fe65c86e and 07988bd476ecc35fd24771ed7e1ac1b8bafd4858.
📒 Files selected for processing (2)
-
packages/shared/src/nodeSqliteClient.test.tspackages/shared/src/nodeSqliteClient.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.
-
📝 Walkthrough
-
Walkthrough#
The SQLite client measures bound parameters and bypasses the prepared-statement cache for payloads over 64 KiB or payloads it cannot measure. Values-based execution also applies the current
SafeIntegerssetting.Changes#
SQLite binding handling
Layer / File(s) Summary Binding measurement and statement selection
packages/shared/src/nodeSqliteClient.ts,packages/shared/src/nodeSqliteClient.test.tsThe client measures strings, views, and named-parameter values. Large or unmeasurable bindings use uncached statements. Tests cover cache reuse, oversized payloads, detached views, and measurement errors. Safe integer values
packages/shared/src/nodeSqliteClient.ts,packages/shared/src/nodeSqliteClient.test.tsValues-based execution applies the current SafeIntegerssetting. Tests check integer results with small and oversized string bindings.Priority: ⬇️ Low
Estimated code review effort: 3 (Moderate) | ~20 minutes
Change: Bug fix
Suggested reviewers:
juliusmarminge
Merge Risk | ⚪ Minimal · up to
07988-
Merge Risk: ⚪ Minimal · up to
07988No actionable issue remains from these findings. The change is mergeable after normal checks.
-
Security Architecture Review
-
Security architecture risk: 🔵 Low · up to
07988The change preserves database permissions and query execution paths while reducing retention of large parameters. No security regression was established. Memory reclamation for repeated large executions still depends on garbage collection, whose behavior under sustained load was not verified.
Retained concerns No architecture-level concerns identified.
-
Security review details
-
Security Blast Radius
- inferred — The demonstrated exposure is statement behavior and native-memory retention within processes using this shared client. The inspected change does not expand which database, environment, or privilege an existing caller can access; broader tenant exposure was not established.
Trust Boundaries and Controls
- observed — Large or unmeasurable parameters still reach the existing native preparation and execution functions with their existing error classification. The size check does not grant authority, bypass a database permission check, or reject oversized input.
Resilience and Maintainability Implications
- inferred — Cache bypass removes one long-lived owner of large bindings, but does not prove a process-memory ceiling during repeated executions or failures. Eventual collection and existing unprepared execution are counterevidence to treating this as a demonstrated leak; sustained native-memory failure containment remains a coverage gap.
-
-
-
-
Pre-merge checks |
4-
✅ Passed checks (4 passed)
-
Check name Status Explanation Title check The title clearly and concisely describes the primary change: large SQLite parameters no longer remain in cached prepared statements. Description check The description includes the required Problem, Change, Scope and approval, and Verification sections. It explains the memory-retention issue, implementation, scope rationale, tests, observed results, … Linked Issues check Check skipped because no linked issues were found for this pull request. Out of Scope Changes check Check skipped because no linked issues were found for this pull request.
-
✨ Finishing Touches
-
🧪 Generate unit tests (beta)
-
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Comment `@coderabbitai help` to get the list of available commands.-
coderabbitai[bot](GitHub profile, opens in a new tab) approved these changes
juliusmarminge added labelsmacroscope-review
macroscopeapp[bot](GitHub profile, opens in a new tab) approved these changes
Note
🤖 Claude Opus 5.5 responding on behalf of Theo
This conflicted with the reader worker from #19226, so I carried it forward in #19305. Your two commits are kept as authored, and you are credited and co-authored there.
One addition: the reader worker has its own statement cache with no TTL, so it had the same pinning problem. Worker requests with large parameters now ask for an uncached statement, with a test that fails without it.
Note
Grok responding on behalf of Julius.
Superseded by #19305, which merged as 4cd0076. It took this PR over to resolve conflicts with the reader worker from #19226. Your two commits are kept as authored, and it applies the same large-parameter bypass to the reader worker too. Thanks @tris203 for the diagnosis and fix! Closing this one.
juliusmarminge closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed