Skip to content

Cache: survive a failed save in initialize, export without a second in-heap copy, never export mid-transaction - #449

Closed
gcp007-ops wants to merge 3 commits into
ProfSynapse:mainfrom
gcp007-ops:fix/cache-save-memory
Closed

gcp007-ops wants to merge 3 commits into
ProfSynapse:mainfrom
gcp007-ops:fix/cache-save-memory

Conversation

@gcp007-ops

@gcp007-ops gcp007-ops commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #448, and closes two more ways the full-database export can run the WASM heap out of memory or write a corrupt snapshot.

What changes

  1. initialize() survives a failed save (keep initialize alive when its own save fails). This is the fix proposed in SQLiteCacheManager.initialize() fails for the whole session when a save inside it hits SQLITE_NOMEM (no back-off for the export error) #448. Both saves inside initialize() go through saveDuringInitialize(): it marks the database dirty, because migrations write through the raw handle, and logs the failure instead of rethrowing. isAllocationFailure() recognises the export's SQLITE_NOMEM, which arrives as SQLite3Error with resultCode 1 and SQLITE_NOMEM only in the message, so the existing back-off applies to it too.
  2. Export without a second in-heap copy, and open with slack.
    • sqlite3_js_db_export first copies the whole database inside the WASM heap. A deserialized database is already one contiguous memdb buffer, so it is copied straight out of the heap with sqlite3_serialize(SQLITE_SERIALIZE_NOCOPY).
    • The bytes are identical: same sha256 on real caches. A fresh :memory: database has no such buffer; NOCOPY returns null for it and the old export is used.
    • Deserialized databases open with slack behind them (1/8 of the size, 8–64 MiB). The first write of a session that needs a new page no longer makes memdb double the buffer while still holding the old one.
  3. Never export mid-transaction.
    • Transactions span awaits, so the auto-save timer can fire inside one. Once the transaction has spilled past the page cache (16 MiB by default), the export is a half-written database. We reproduced this: invalid rootpage / malformed database schema. The next load discards it as corrupt and rebuilds, which may be one source of reports like HybridStorageAdapter waitForQueryReady times out (60s, repeated) → embeddings skipped, MCP tool calls hang — v5.9.3, idb backend #209.
    • The save now waits up to 5 s for the connection's autocommit flag. It checks the connection rather than the coordinator, because the coordinator does not see the raw beginTransaction().
    • If the transaction is still open after 5 s, the save rejects with SaveDeferredError, so a resolved save still means the bytes were written. The database stays dirty and one retry is armed. close() logs and closes anyway.

Measurements

All runs used the shipped sqlite3.wasm (SQLite 3.51.0) in Node, on a real 314 MiB cache and on synthetic databases with 8 KiB pages.

Scenario Before After
Heap after load 378 MiB 425 MiB (the slack)
Save after one new page 1,273 MiB peak 425 MiB
Save of a 523 MiB / 645 MiB database (after a new page) SQLITE_NOMEM OK

The same build is running in a desktop vault: heap 426 MiB, saves of ~330 MB succeed.

Limits that remain

  • memdb's 1 GiB maximum size (SQLITE_MEMDB_DEFAULT_MAXSIZE) is unchanged.
  • A session that grows past the slack still doubles the buffer once.
  • A fresh database, on first run or after Rebuild Cache, uses the old export until its next load.

Only a page-level VFS removes the full-database export altogether.

Tests

  • Three new suites: SQLiteWasmBridgeMemory, SQLiteCacheManagerMemorySafety and SQLiteCacheManagerInitSaveFailure. Most of their cases fail without the change; the two fallback cases are regression guards.
  • Existing cache suites pass. The isAutocommit stub was added to their bridge mocks.
  • tsc, eslint, check-mobile-imports and npm run build are clean.
  • The full jest run fails the same 12 tests in 5 suites as main (8125f79). Those are pre-existing failures, unrelated to the cache: DataAnalysisGuards, RunPythonTool, SemanticSearchSettings, SettingsSectionSummaries and OpenAICompatibleContextWindow.

🤖 Generated with Claude Code

Gustavo Cunha Prazeres and others added 3 commits November 23, 2026 10:48
initialize() awaited two saves without protection: after creating a fresh
database and after applying schema migrations to an existing one. When the
full export does not fit in the WASM heap, sqlite3_js_db_export throws an
SQLite3Error ("Database serialization failed with code SQLITE_NOMEM"),
initialize() rethrows it, and the storage adapter stays failed for the whole
session; every restart repeats the same export and fails the same way.

- Both saves go through saveDuringInitialize(), which marks the database
  dirty first (the migrator writes through the raw handle, so nothing else
  would) and logs instead of rethrowing. Auto-save and close() retry.
- isAllocationFailure() recognises the SQLITE_NOMEM export failure as well
  as the RangeError of a JS-side copy, so the existing exponential back-off
  also applies to it instead of re-exporting on every tick. resultCode is
  the generic SQLITE_ERROR for this throw, so the message is what carries it.

Tests cover both init paths, the retry after a failed init save, the back-off
after SQLITE_NOMEM at init and at runtime, and the adapter staying query-ready.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
sqlite3_js_db_export allocates a full copy of the database inside the WASM
heap before handing it to JS, so a save needs roughly twice the database in
the heap. A deserialized database is already one contiguous memdb buffer, so
copy it straight out of the heap with sqlite3_serialize(SQLITE_SERIALIZE_NOCOPY);
the bytes are identical (sha256 checked on real caches). A fresh :memory:
database has no such buffer, NOCOPY returns null for it, and the old export
is used.

Deserialized databases are also opened in a buffer with slack behind it
(1/8 of the size, 8-64 MiB). Without it, the first write of a session that
needs one more page makes memdb double the buffer while holding the old one,
about three times the database in the heap for a moment. The slack is not part
of the database and the memdb size ceiling is unchanged.

Measured with the shipped sqlite3.wasm (3.51.0) on a real 314 MiB cache: the
save after one new page peaked at 1273 MiB of heap; now 425 MiB. Saves of 523
and 645 MiB databases, which failed with "Database serialization failed with
code SQLITE_NOMEM", now pass.

Refs ProfSynapse#448.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Transactions span awaits, so the autosave timer can fire inside one. Once the
transaction outgrows the page cache, its pages are already in the in-memory
file and the export is a half-written database ("invalid rootpage"), which
the next load discards as corrupt. The save now waits up to 5 s for the
connection's autocommit flag (the coordinator does not see raw
beginTransaction), then defers: nothing written, still dirty, no allocation
back-off, one retry armed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@gcp007-ops

Copy link
Copy Markdown
Contributor Author

Closing this: the proposal continues in #448, where the patch is linked from our fork for reference.

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.

SQLiteCacheManager.initialize() fails for the whole session when a save inside it hits SQLITE_NOMEM (no back-off for the export error)

1 participant