Repository navigation
Refresh planner statistics before the MCP server opens Lattice - #14
Closed
shadowrider17 wants to merge 2 commits into
Closed
shadowrider17 wants to merge 2 commits into
shadowrider17 wants to merge 2 commits into
Conversation
shadowrider17
marked this pull request as ready for review
October 20, 2026 16:32
Each cross-process notification makes every Lattice instance run `SELECT ... FROM AuditLog WHERE id > ? ORDER BY id`. On a hub whose sqlite_stat1 was written while AuditLog was tiny, the planner believes the table holds 1 row and picks a full scan instead of a rowid seek. With a 2.77M-row AuditLog each notification cost 4-22 s, and a dozen MCP servers rescanning in turn held about 9 cores and 1 GB of RAM each. LatticeCore no longer runs ANALYZE at open, its close-time PRAGMA optimize does not repair these statistics, and an ANALYZE from another connection does not reach a connection that is already open. So the server now runs the bounded all-tables `PRAGMA optimize=0x10002` on a short-lived connection before Lattice opens the hub and the synced store. It costs about 30 ms on fresh statistics and a few seconds once on a stale hub. It takes the writer lock with BEGIN IMMEDIATE, so a concurrent commit costs at most the existing 2 s busy timeout, and a busy hub is skipped until the next start.
Review follow-up to the planner statistics refresh. - PRAGMA optimize's 0x10000 (all tables) bit arrived in SQLite 3.46. Older libraries ignore it and analyze nothing, which the refresh used to log as success. It now checks sqlite3_libversion_number() and reports unsupportedSQLite(version:) without touching the store. - refresh returns an Outcome (refreshed, skippedMissingFile, unsupportedSQLite, failed(code:message:)) so the startup log carries the SQLite error message. - Documented the real startup cost (busy wait plus a few seconds of analysis once on a stale hub, per store) and the one-time writer-lock hold. - Softened the close-time optimize claim: in practice it does not repair AuditLog (servers usually exit through _exit, and the cursor query uses no index). - Tests: remove temp databases, use #require for setup, rename the no-op test to refreshIsIdempotent and assert the statistics stay unchanged, add a test for the unsupported path, and skip plan assertions on old SQLite. Correction to the previous commit message: the ~1 GB RSS per server was the cache and mmap baseline, not a measured effect of the rescanning.
shadowrider17
force-pushed
the
fix/refresh-planner-stats-at-startup
branch
from
November 6, 2026 06:14
6c65bc0 to
b5d5e12
Compare
Owner
|
Consolidated in #88 (PRAGMA optimize=0x10002 startup planner statistics refresh with explicit SQLite < 3.46 reporting). |
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.
Problem
Every cross-process notification makes each Lattice instance run
SELECT ... FROM AuditLog WHERE id > ? ORDER BY id. Whensqlite_stat1was written while AuditLog was small, the planner keeps believing the table holds about one row, and it picks a full table scan instead of a rowid seek. LatticeCore no longer runs ANALYZE at open, and in practice its close-timePRAGMA optimizedoes not repair this table, so the statistics never recover on their own.The effect on a hub with 2.77M AuditLog rows and 12-17 Claude Code sessions open:
Solution
The MCP server now runs a bounded
PRAGMA optimize=0x10002on a short-lived connection before Lattice opens the hub and the synced store.BEGIN IMMEDIATE, so a concurrent commit costs at most the existing 2 s busy timeout.Why this approach
PRAGMA optimizeonly re-analyzes tables whose stats the planner used on that connection. The cursor query is a rowid scan that uses no index, so plainoptimizenever selects AuditLog. The0x10000bit lifts that restriction.optimizestarts as a reader and upgrades to a writer. SQLite fails a contended upgrade at once, without consulting the busy handler.NOT INDEXEDdoes not help: the plan is stillSCAN.The measurements behind each point are in the evidence toggle below.
Validation
PlannerStatisticsTests:SQLITE_BUSY;PRAGMA optimize, plainBEGIN, removing the version guard, and removing the missing-file guard.SEARCH;mainat440811c) on 2026-11-06:mainwithout this change kept AuditLog's estimate at 1 row and the plan atSCAN, while this branch repaired it in 2.5 s and the plan becameSEARCH;PRAGMA optimize, so the trap is still there upstream.swiftpm-testing-helperagainst theEngramTeststarget.Supporting evidence
All measurements are from one Apple Silicon Mac (macOS 26, system SQLite 3.51) on 2026-10-07 and 2026-10-08, against a hub with 13.5K memories, 214K edges and 2.77M AuditLog rows.
The stale statistics and the plan they produce
sqlite_stat1for the hub, against the real row counts:The same query on a backup copy, returning the 20 newest rows: 4.2 s with the stale stats and 0.021 s after
ANALYZE AuditLog. On the live machine, under load, one full pass over AuditLog took 7-22 s.NOT INDEXEDdoes not help; the plan is stillSCAN.What the servers were doing
sampleon one server:Where the AuditLog rows come from
lastAccessedAtupdate (recall bump)accessCountupdate (recall bump)The hub has no replication slots, so
compactHistory()deletes nothing, and Engram never setsauditRetention.Why the refresh has to run before Lattice opens, and in this form
A standalone reproduction (20,000-row AuditLog, stats rewritten to claim 1 row):
SCANANALYZESCANSCANANALYZE sqlite_schemaSEARCHSEARCHPRAGMA optimize1 1PRAGMA optimize1 1PRAGMA optimize=0x1000220000 1The SQLite docs say plain
optimizeonly re-analyzes a table if the query planner used that table's stats on the current connection. The cursor query is a rowid scan that uses no index, so plainoptimizenever selects AuditLog. The0x10000bit lifts that restriction.Cost of
PRAGMA analysis_limit=400; PRAGMA optimize=0x10002;on a copy of the stale 1.8 GB hub: 5.4 s the first time, and 0.033 s once the stats are fresh.A bare
optimizestarts as a reader and upgrades to a writer. SQLite fails a contended upgrade at once without calling the busy handler: 0 ms with another writer holding the lock. WithBEGIN IMMEDIATEit waits for the timeout: about 220-250 ms against a 200 ms timeout.End-to-end runs (release binary, copy of the stale hub,
CLAUDE_MEMORY_DBpointing at the copy)After each first start the copy's AuditLog stat read
2774775 1and the plan wasSEARCH. The server then sat at 0.3% CPU. A full MCP round trip also worked against the installed v0.14.10 resource bundles: initialize, 24 tools, and arecallthat returned results.Local trial (the fixed binary as
~/.claude/bin/memory)refreshed in 1-13 ms, with no failures.Scope and compatibility
0x10000optimize bit arrived in 3.46. The check usessqlite3_libversion_number(), so it follows the library loaded at runtime, not the macOS version. On an older system SQLite the refresh does nothing, and the startup log readsunsupportedSQLite(version: ...)instead of a false success. Engram's.macOS(.v15)floor likely includes such systems: macOS 15 is reported to ship an SQLite older than 3.46, but that has not been checked here. Only SQLite 3.51 on macOS 26 was tested.memory-hooks,memory-syncand the Visualizer. They pick up the repaired statistics the next time they open the database.SQLITE_BUSYonce, and a server starting in the same window keeps the stale statistics until its next start.mainat440811c). Lattice 2.2.5 and LatticeCore 2.2.8 are unchanged.Possible follow-ups (not in this PR)
PRAGMA optimize=0x10002when a read-write connection opens, before the reader and notification connections. MakeLattice.optimize()use the all-tables form, and reload statistics on the instance's own connections (ANALYZE sqlite_schema). Todayoptimize()uses plainPRAGMA optimize, which does not repair AuditLog here.compactHistory()deletes nothing there, and Engram does not setauditRetention. About 72% of the rows on this hub are recall access bumps (lastAccessedAtandaccessCount).no_history, batch the bumps, or keep access statistics outside the audited table.max(id) - min(id), a cheap lookup) and run a boundedANALYZE AuditLogwhen the estimate is more than 10 times too small. It was left out of this PR to keep it small.Stopwith new content can spawn a headlessclaudewith its own memory server. One such server used about 48 s of CPU and 808 MB in its first 4 minutes before going idle.minimumVersioninternal. It is public only so the tests can reach it;@testable importwould do instead.Six-day trial on a live machine (2026-10-08 to 2026-10-14)
What was measured
A read-only monitor sampled every 5 minutes from 2026-10-08 to 2026-10-14. It sampled for 33.6 of the 151 elapsed hours (22%); the gaps are deliberate pauses and machine sleep.
SEARCHin 407 of 407 samplesBefore the fix, the same machine's servers held about 9 cores between them (see "Supporting evidence" above).
Side effects, and whether this change causes them
SEARCHand refreshes stayed under 35 ms, so this does not look like the scan. The cause is unconfirmed.Method and limits
memorywas replaced; hooks, the sync daemon and the bundles stayed on v0.14.10.ANALYZEbefore the trial began. So on the live hub, this trial shows the build is safe in daily use. The repair itself is shown on stale copies (the end-to-end runs above).