perf(db): batch node lookups, fix insertNode cache, auto-ANALYZE after writes#108
Open
andreinknv wants to merge 1 commit into
Open
perf(db): batch node lookups, fix insertNode cache, auto-ANALYZE after writes#108andreinknv wants to merge 1 commit into
andreinknv wants to merge 1 commit into
Conversation
…r writes
Three DB-layer improvements bundled in one PR.
## 1. Batch getNodesByIds — fix N+1 in graph traversal
QueryBuilder.getNodesByIds(ids[]) returns Map<id, Node> in one
round-trip (chunked at 500 for SQLite param-limit safety, cache-aware
so already-cached entries are served from memory and only the misses
hit SQL).
Replaces 9 N+1 loops in src/graph/traversal.ts:
- getCallersRecursive / getCalleesRecursive
- getTypeAncestors / getTypeDescendants
- findUsages
- getImpactRecursive (both inner loops: contains-children + dependents)
- findPath BFS frontier
- traverseBFS / traverseDFS neighbor expansion
- getChildren
Each previously did `getNodeById` per edge inside a loop; for a function
with N callers at depth D, that was N^D point reads per traversal.
Now: one IN-list query per traversal step. Expected 10-50x speedup on
deep / fan-out-heavy traversals (impact analysis on popular utilities,
call graphs of central modules).
## 2. insertNode cache invalidation — fix correctness bug
QueryBuilder.insertNode uses INSERT OR REPLACE INTO nodes. The LRU
nodeCache was invalidated by updateNode and deleteNode but NOT by
insertNode, so a re-indexed node (replacing a cached row) would still
serve the pre-replace version on next getNodeById until LRU eviction
pushed it out.
Now invalidates `nodeCache.delete(node.id)` at the top of insertNode
(after validation, before SQL — so failed-validation early-returns
don't churn the cache).
## 3. Auto-maintenance after bulk writes
DatabaseConnection.runMaintenance() runs:
- PRAGMA optimize (incremental ANALYZE; only re-analyzes tables
whose row counts changed materially since last
ANALYZE — without it, the SQLite query planner
has zero statistics on freshly-bulk-loaded
tables and can pick wrong indexes)
- PRAGMA wal_checkpoint(PASSIVE)
(fold WAL pages back into the main DB file so
the WAL doesn't grow unboundedly between
automatic checkpoints which fire at 1000 pages)
Both are non-blocking and silently swallowed on failure — best-effort,
never load-bearing for correctness. Wired into indexAll (when files
were indexed) and sync (when files changed). No-op when nothing
happened.
## Files changed
| File | Change |
|---|---|
| src/db/queries.ts | Add getNodesByIds; invalidate cache in insertNode |
| src/db/index.ts | Add runMaintenance() helper |
| src/graph/traversal.ts | Replace 9 N+1 loops with batch lookups |
| src/index.ts | Call runMaintenance after indexAll/sync |
| __tests__/db-perf.test.ts (NEW) | 9 regression tests |
## Test plan
- [x] npm test: 388/389 pass on macOS (one pre-existing fs.watch flake)
- [x] npx tsc --noEmit clean
- [x] Independent reviewer pass before pushing — APPROVE; one info
finding addressed (getChildren was the 9th N+1 site, now batched
too)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This was referenced Apr 26, 2026
This was referenced May 6, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Three DB-layer improvements bundled in one PR. All low-risk, high-leverage.
1. Batch
getNodesByIds— fix N+1 in graph traversalQueryBuilder.getNodesByIds(ids[])returnsMap<id, Node>in one SQL round-trip (chunked at 500 for SQLite param-limit safety; cache-aware so already-cached entries are served from memory and only the misses hit SQL).Replaces 9 N+1 loops in
src/graph/traversal.ts:getCallersRecursive/getCalleesRecursivegetTypeAncestors/getTypeDescendantsfindUsagesgetImpactRecursive(both inner loops: contains-children + dependents)findPathBFS frontiertraverseBFS/traverseDFSneighbor expansiongetChildrenEach previously did
getNodeByIdper edge inside a loop; for a function with N callers at depth D, that was N^D point reads. Now: one IN-list query per traversal step. Expected 10–50× speedup on deep / fan-out-heavy traversals (impact analysis on popular utilities, call graphs of central modules).2.
insertNodecache invalidation — fix correctness bugQueryBuilder.insertNodeusesINSERT OR REPLACE INTO nodes. The LRUnodeCachewas invalidated byupdateNodeanddeleteNodebut NOT byinsertNode, so a re-indexed node (replacing a cached row) would still serve the pre-replace version on nextgetNodeByIduntil LRU eviction pushed it out.Now invalidates
nodeCache.delete(node.id)at the top ofinsertNode(after validation, before SQL — so failed-validation early-returns don't churn the cache).3. Auto-maintenance after bulk writes
DatabaseConnection.runMaintenance()runs:PRAGMA optimize— incremental ANALYZE; only re-analyzes tables whose row counts changed materially since the last ANALYZE. Without it, the SQLite query planner has zero statistics on freshly-bulk-loaded tables and can pick wrong indexes.PRAGMA wal_checkpoint(PASSIVE)— fold WAL pages back into the main DB file so the WAL doesn't grow unboundedly between automatic checkpoints (which fire at 1000 pages).Both non-blocking and silently swallowed on failure — best-effort, never load-bearing. Wired into
indexAll(when files were indexed) andsync(when files changed). No-op when nothing happened.Files changed
src/db/queries.tsgetNodesByIds; invalidate cache ininsertNodesrc/db/index.tsrunMaintenance()helpersrc/graph/traversal.tssrc/index.tsrunMaintenanceafterindexAll/sync__tests__/db-perf.test.ts(NEW)Test plan
npm test: 388/389 pass on macOS (one pre-existing fs.watch flake)npx tsc --noEmitcleangetChildrenwas the 9th N+1 site, now batched too)🤖 Generated with Claude Code