Skip to content

Refresh planner statistics before the MCP server opens Lattice - #14

Closed
shadowrider17 wants to merge 2 commits into
jsflax:mainfrom
shadowrider17:fix/refresh-planner-stats-at-startup
Closed

shadowrider17 wants to merge 2 commits into
jsflax:mainfrom
shadowrider17:fix/refresh-planner-stats-at-startup

Conversation

@shadowrider17

@shadowrider17 shadowrider17 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Every cross-process notification makes each Lattice instance run SELECT ... FROM AuditLog WHERE id > ? ORDER BY id. When sqlite_stat1 was 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-time PRAGMA optimize does 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:

  • each notification cost 4-22 s per server;
  • the servers together held about 9 cores.

Solution

The MCP server now runs a bounded PRAGMA optimize=0x10002 on a short-lived connection before Lattice opens the hub and the synced store.

  • It takes the writer lock with BEGIN IMMEDIATE, so a concurrent commit costs at most the existing 2 s busy timeout.
  • It never creates a missing database.
  • SQLite before 3.46 ignores the 0x10000 bit, so those builds are reported as unsupported instead of being logged as a success.
  • Group spokes are skipped because they open without IPC, so the cursor query never runs on them.

Why this approach

  • It runs before Lattice opens. An open connection keeps the statistics it loaded, and an ANALYZE from another connection does not reach it.
  • It uses the all-tables form. Plain PRAGMA optimize only re-analyzes tables whose stats the planner used on that connection. The cursor query is a rowid scan that uses no index, so plain optimize never selects AuditLog. The 0x10000 bit lifts that restriction.
  • It takes the lock up front. A bare optimize starts as a reader and upgrades to a writer. SQLite fails a contended upgrade at once, without consulting the busy handler.
  • It fixes the statistics, not the query. NOT INDEXED does not help: the plan is still SCAN.
  • It lives in Engram for now. The trap is in LatticeCore (see the follow-ups), but the damage concentrates in Engram's many long-lived server processes, and this change does not wait on a LatticeCore release.

The measurements behind each point are in the evidence toggle below.

Validation
  • 6 new Swift Testing cases in PlannerStatisticsTests:
    • stale statistics scan before the refresh and seek after it;
    • a second refresh is idempotent;
    • a missing file is not created;
    • an unsupported SQLite leaves the store untouched;
    • a held writer lock waits the timeout and then returns SQLITE_BUSY;
    • an open reader does not block the refresh.
  • Each of these changes makes its targeted test fail: plain PRAGMA optimize, plain BEGIN, removing the version guard, and removing the missing-file guard.
  • Release binary against a copy of a real 1.8 GB hub with stale statistics:
    • the first start repaired them in 1.9-3.2 s and the plan flipped to SEARCH;
    • later starts took 6-22 ms.
  • On one machine, after running the fixed binary for a few hours:
    • every memory server stayed under 1% CPU and 60-210 MB RSS, against about 1 GB for servers started before the fix;
    • every startup refresh took 1-13 ms.
  • An independent review approved the change after one round of fixes.
  • Rebased onto v0.15.28 (main at 440811c) on 2026-11-06:
    • the 6 tests pass;
    • on the same stale-statistics hub copy, main without this change kept AuditLog's estimate at 1 row and the plan at SCAN, while this branch repaired it in 2.5 s and the plan became SEARCH;
    • LatticeCore 2.2.8 still runs only plain PRAGMA optimize, so the trap is still there upstream.
  • Built with Xcode 27 (Swift 6.4). The visualizer's Metal shaders need the Metal toolchain, so the test bundle ran through swiftpm-testing-helper against the EngramTests target.
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_stat1 for the hub, against the real row counts:

Table Stored estimate Actual rows
AuditLog 1 2,768,033
Memory 2,075 13,522
Edge 3 213,867
sqlite> EXPLAIN QUERY PLAN SELECT id, tableName, operation, rowId, globalRowId, changedFieldsNames
   ...>   FROM AuditLog WHERE id > ?1 ORDER BY id ASC;
`--SCAN AuditLog                                   -- with the stats above
`--SEARCH AuditLog USING INTEGER PRIMARY KEY (rowid>?)   -- after ANALYZE AuditLog

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 INDEXED does not help; the plan is still SCAN.

What the servers were doing

  • 12 memory servers (one per Claude Code session) at 74-87% CPU each, about 940% in total. Load average was 65-118 on 12 cores.
  • sample on one server:
    1542 lattice::lattice_db::handle_cross_process_notification()
    1542 sqlite3_step
    1494 sqlite3BtreeNext
    
    That is 1542 of 1542 samples in the handler, on a full B-tree walk.
  • AuditLog received 18,518 rows in one hour, across at least 791 distinct 100 ms commit windows (about one commit every 4.5 s). Each commit wakes every other server, so each server's notification queue never drained.
  • The WAL could not rewind while those scans overlapped. It reached 4.7 GB. After the fix, with no pre-fix servers left, it rewound to 0.27 GB. It grew again later for a separate reason (see the trial section below).

Where the AuditLog rows come from

Change Rows Last day
Memory lastAccessedAt update (recall bump) 1,002,304 58,269
Memory accessCount update (recall bump) 1,000,605 58,164
Edge insert 436,021 19,141
Edge delete 222,154 75,944
SessionState updates (hooks) 52,960 3,038

The hub has no replication slots, so compactHistory() deletes nothing, and Engram never sets auditRetention.

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

Scenario Plan, or stored AuditLog stat
Already-open connection, before anything SCAN
Same connection, after another connection runs ANALYZE still SCAN
Same connection, after another connection creates and drops a table still SCAN
Same connection, after its own ANALYZE sqlite_schema SEARCH
A fresh connection SEARCH
Plain PRAGMA optimize stat stays 1 1
Query AuditLog first, then plain PRAGMA optimize stat stays 1 1
PRAGMA optimize=0x10002 stat becomes 20000 1

The SQLite docs say plain optimize only 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 plain optimize never selects AuditLog. The 0x10000 bit 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 optimize starts 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. With BEGIN IMMEDIATE it 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_DB pointing at the copy)

first commit, first start:   Planner statistics refresh rc=0 in 3155ms
first commit, second start:  Planner statistics refresh rc=0 in 22ms
second commit, first start:  Planner statistics refresh refreshed in 1973ms
second commit, second start: Planner statistics refresh refreshed in 6ms

After each first start the copy's AuditLog stat read 2774775 1 and the plan was SEARCH. 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 a recall that returned results.

Local trial (the fixed binary as ~/.claude/bin/memory)

  • Every new session logged refreshed in 1-13 ms, with no failures.
  • Fixed-build servers: 0.2-0.7% CPU at idle and 60-210 MB RSS. Servers started before the fix were at about 1 GB.
  • The one server left on the old build kept spiking to 76-94% CPU on commit bursts until its session reconnected the MCP server.
Scope and compatibility
  • SQLite 3.46 or newer is required for the repair. The 0x10000 optimize bit arrived in 3.46. The check uses sqlite3_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 reads unsupportedSQLite(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.
  • Repaired: the hub and the synced store, when the MCP server starts.
  • Not touched: group spokes, which open without IPC so the cursor query never runs on them, plus memory-hooks, memory-sync and the Visualizer. They pick up the repaired statistics the next time they open the database.
  • Servers already running keep their stale statistics until they restart. A refresh from one process does not reach connections another process already holds open.
  • Startup cost per store: up to the existing 2 s busy wait, plus the analysis.
    • About 20-30 ms on fresh statistics.
    • A few seconds once on a stale multi-GB hub.
    • During that one-time repair the writer lock is held. A concurrent writer with a short timeout may get SQLITE_BUSY once, and a server starting in the same window keeps the stale statistics until its next start.
  • No schema change, and no dependency bump. The branch is based on v0.15.28 (main at 440811c). Lattice 2.2.5 and LatticeCore 2.2.8 are unchanged.
  • Built and tested with Xcode 27 (Swift 6.4). Lattice 2.2.5 declares Swift tools 6.3, so Xcode 26.3 (Swift 6.2) cannot build the package.
Possible follow-ups (not in this PR)
  1. Fix the trap in LatticeCore. Run PRAGMA optimize=0x10002 when a read-write connection opens, before the reader and notification connections. Make Lattice.optimize() use the all-tables form, and reload statistics on the instance's own connections (ANALYZE sqlite_schema). Today optimize() uses plain PRAGMA optimize, which does not repair AuditLog here.
  2. Bound AuditLog on stores without sync slots. compactHistory() deletes nothing there, and Engram does not set auditRetention. About 72% of the rows on this hub are recall access bumps (lastAccessedAt and accessCount).
  3. Reduce recall write amplification. Each recall writes two audit rows per returned memory, and each commit wakes every other server. Options: mark the access columns no_history, batch the bumps, or keep access statistics outside the audited table.
  4. Support SQLite older than 3.46. A targeted fallback would compare AuditLog's stored estimate with its real size (max(id) - min(id), a cheap lookup) and run a bounded ANALYZE AuditLog when the estimate is more than 10 times too small. It was left out of this PR to keep it small.
  5. Look at the learner's footprint. Each Stop with new content can spawn a headless claude with its own memory server. One such server used about 48 s of CPU and 808 MB in its first 4 minutes before going idle.
  6. Make minimumVersion internal. It is public only so the tests can reach it; @testable import would do instead.
Six-day trial on a live machine (2026-10-08 to 2026-10-14)

The scan did not come back. For six days, one machine ran this build as ~/.claude/bin/memory. In all 407 samples, the cursor query used the rowid seek (SEARCH), and the stored AuditLog estimate stayed within 1.0 to 1.2 times the real row count.

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.

Check Result
Query plan for the cursor query SEARCH in 407 of 407 samples
AuditLog estimate vs real rows 1.0 to 1.2 (2.77M to 3.25M rows over the trial)
Startup refreshes 1,249 runs. Slowest per 5-minute window: median 6 ms, 95th percentile 309 ms
Interactive memory servers, total CPU (327 samples) Median 1.9%, 95th percentile 10.6%, maximum 96.6%
Interactive memory servers, resident memory Median 25 MB per server, maximum 217 MB

Before 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

  • Short bursts across all servers (2 seen, about a minute each). Total CPU reached 220% and 254%. The plan stayed SEARCH and refreshes stayed under 35 ms, so this does not look like the scan. The cause is unconfirmed.
  • WAL growth (0.27 GB to 3.68 GB). Not caused by this change. The fix build and v0.14.10 behaved the same in every WAL experiment on copies of the hub. A long-lived reader holds an old snapshot, so the checkpoint cannot rewind. It is being investigated separately.
Method and limits
  • One Apple Silicon Mac, macOS 26, system SQLite 3.51. Only memory was replaced; hooks, the sync daemon and the bundles stayed on v0.14.10.
  • CPU checks cover interactive servers only. Headless learner servers were tracked separately (follow-up 5 above).
  • The live statistics were already repaired by a one-off ANALYZE before 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).
  • Five-minute sampling can miss short bursts. A 60-second watcher, run for part of the trial, caught the two bursts above.

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
shadowrider17 force-pushed the fix/refresh-planner-stats-at-startup branch from 6c65bc0 to b5d5e12 Compare November 6, 2026 06:14
@jsflax

jsflax commented Nov 17, 2026

Copy link
Copy Markdown
Owner

Consolidated in #88 (PRAGMA optimize=0x10002 startup planner statistics refresh with explicit SQLite < 3.46 reporting).

@jsflax jsflax closed this Nov 17, 2026
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.

2 participants