Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
144 changes: 139 additions & 5 deletions src/database/storage/SQLiteCacheManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,46 @@ export interface QueryResult<T> {
totalCount?: number;
}

/**
* Whether a failed save ran out of memory rather than failing for a reason a
* retry cannot fix.
*
* Two shapes reach the save path. A JS-side copy of the export that cannot be
* allocated is a RangeError. The export itself running out of WASM heap is an
* SQLite3Error from sqlite3_js_db_export, and that one carries SQLITE_NOMEM
* only in its message: the export passes the code as a string, so resultCode
* is the generic SQLITE_ERROR. The numeric code is checked too, for a build
* that reports it properly.
*/
export function isAllocationFailure(error: unknown): boolean {
if (error instanceof RangeError) {
return /array buffer allocation failed/i.test(error.message);
}
if (typeof error !== 'object' || error === null) {
return false;
}
const { message, resultCode } = error as { message?: unknown; resultCode?: unknown };
return resultCode === SQLITE_NOMEM_CODE
|| (typeof message === 'string' && /\bSQLITE_NOMEM\b/.test(message));
}

/**
* A save that did not write because a transaction stayed open past the wait.
* The database is still dirty and a retry is armed.
*/
export class SaveDeferredError extends Error {
constructor() {
super(
'Save deferred: a transaction is still open, and exporting now could write a '
+ 'half-applied database. Changes stay unsaved and the save is retried.'
);
this.name = 'SaveDeferredError';
}
}

/** SQLITE_NOMEM, from sqlite3.h. */
const SQLITE_NOMEM_CODE = 7;

/**
* Database adapter that wraps raw WASM SQLite database to provide
* exec() and run() methods for MigratableDatabase interface.
Expand Down Expand Up @@ -105,6 +145,9 @@ class DatabaseAdapter {
export class SQLiteCacheManager implements IStorageBackend, ISQLiteCacheManager {
private static readonly ALLOCATION_RETRY_BASE_MS = 2 * 60 * 1000;
private static readonly ALLOCATION_RETRY_MAX_MS = 30 * 60 * 1000;
private static readonly SAVE_TRANSACTION_WAIT_MS = 5 * 1000;
private static readonly SAVE_TRANSACTION_POLL_MS = 50;
private static readonly SAVE_DEFERRED_RETRY_MS = 1000;
private app: App;
private dbPath: string; // Relative path within vault
private wasmPath?: string;
Expand All @@ -131,6 +174,8 @@ export class SQLiteCacheManager implements IStorageBackend, ISQLiteCacheManager
private saveInFlight: Promise<void> | null = null;
/** The write generation the in-flight save captured before its export. */
private inFlightGeneration = 0;
/** Retry armed when a save gave up waiting for a transaction to end. */
private deferredSaveTimer: number | null = null;
/** The one coalesced save scheduled to follow the in-flight one, if any. */
private pendingSave: Promise<void> | null = null;
/** Set by stopAutoSave() and close() to cancel a scheduled follow-up. */
Expand Down Expand Up @@ -367,7 +412,7 @@ export class SQLiteCacheManager implements IStorageBackend, ISQLiteCacheManager
const sqlite3 = this.getSqlite3OrThrow();
const db = this.persistenceService.createFreshDatabase(sqlite3, SCHEMA_SQL);
this.db = db;
await this.saveToFile();
await this.saveDuringInitialize('creating it');
}

// Run schema migrations for existing databases
Expand All @@ -376,7 +421,7 @@ export class SQLiteCacheManager implements IStorageBackend, ISQLiteCacheManager
const migrator = new SchemaMigrator(dbAdapter);
const migrationResult = await migrator.migrate();
if (migrationResult.applied > 0) {
await this.saveToFile(); // Save after migrations
await this.saveDuringInitialize('applying schema migrations');
}
// Hand the signal to the caller rather than dropping it: the result object
// used to die in this scope, so `needsRebuild` could never mean anything.
Expand All @@ -401,6 +446,34 @@ export class SQLiteCacheManager implements IStorageBackend, ISQLiteCacheManager
}
}

/**
* Persist a change initialize() itself made, without letting the save decide
* whether the cache opens.
*
* The database is already open and correct in memory at this point; only
* writing it out can fail, and the usual reason is that exporting the whole
* database does not fit in the WASM heap (SQLITE_NOMEM). Rethrowing used to
* fail initialize(), which left the storage adapter failed for the session,
* every restart repeating the same export. Instead the change is recorded as
* unsaved, so auto-save and close() retry it, and an allocation failure arms
* the same back-off a failed auto-save does.
*
* The migrator writes through the raw handle, so nothing else marks those
* writes dirty; without markDirty() a swallowed failure would never be retried.
*/
private async saveDuringInitialize(step: string): Promise<void> {
this.markDirty();
try {
await this.saveToFile();
} catch (error) {
console.error(
`[SQLiteCacheManager] Could not save the cache after ${step}; `
+ 'continuing with the changes unsaved, auto-save will retry:',
error
);
}
}

/**
* Whether the schema migration that just ran needs the cache replayed from
* JSONL, clearing the flag as it reports it. Consume-once so the second
Expand Down Expand Up @@ -455,16 +528,37 @@ export class SQLiteCacheManager implements IStorageBackend, ISQLiteCacheManager
// Captured BEFORE saveDatabase is called, not inside it: that method
// exports the database as the first thing it does, so every write after
// this line is newer than the bytes about to be written.
const generation = this.writeGeneration;
let generation = this.writeGeneration;
this.inFlightGeneration = generation;

const save = async (): Promise<void> => {
const db = this.getDbOrThrow();
const sqlite3 = this.getSqlite3OrThrow();
// Never export with a transaction open. Exporting mid-transaction writes
// whatever the transaction has already spilled into the in-memory file:
// once it outgrows the page cache (16 MiB by default) the snapshot is a
// half-written database, and the next load discards it as corrupt.
// Transactions span awaits, so the auto-save timer can fire inside one.
// The connection's own autocommit flag is checked, not the coordinator,
// because the coordinator does not see the raw beginTransaction().
const deadline = Date.now() + SQLiteCacheManager.SAVE_TRANSACTION_WAIT_MS;
while (!this.bridge.isAutocommit(sqlite3, db)) {
if (Date.now() >= deadline) {
this.deferSave();
throw new SaveDeferredError();
}
await new Promise<void>(resolve => window.setTimeout(resolve, SQLiteCacheManager.SAVE_TRANSACTION_POLL_MS));
}
// From the check above to the export inside saveDatabase (which runs
// before its first await) there is no await, so nothing can open a
// transaction in between. Writes committed while waiting are in this
// snapshot, hence the generation is taken again here.
generation = this.writeGeneration;
this.inFlightGeneration = generation;
try {
await this.persistenceService.saveDatabase(sqlite3, db);
} catch (error) {
if (error instanceof RangeError && /array buffer allocation failed/i.test(error.message)) {
if (isAllocationFailure(error)) {
this.allocationFailureCount++;
const exponent = Math.min(this.allocationFailureCount - 1, 20);
const delay = Math.min(
Expand Down Expand Up @@ -495,6 +589,27 @@ export class SQLiteCacheManager implements IStorageBackend, ISQLiteCacheManager
return inFlight;
}

/**
* A save that found a transaction still open after waiting: nothing is
* written, the database stays dirty, and one retry is armed. The caller gets
* SaveDeferredError, because a resolved save means the bytes were written;
* it is not an allocation failure, so the back-off is left alone.
*/
private deferSave(): void {
if (this.deferredSaveTimer !== null || this.followUpCancelled || !this.isInitialized) {
return;
}
this.deferredSaveTimer = window.setTimeout(() => {
this.deferredSaveTimer = null;
if (this.followUpCancelled || !this.isInitialized || this.db === null || !this.hasUnsavedData) {
return;
}
this.saveToFile().catch(error => {
console.error('[SQLiteCacheManager] Deferred save failed:', error);
});
}, SQLiteCacheManager.SAVE_DEFERRED_RETRY_MS);
}

/**
* Schedule exactly one save to run after the in-flight one.
*
Expand Down Expand Up @@ -546,6 +661,10 @@ export class SQLiteCacheManager implements IStorageBackend, ISQLiteCacheManager
// it would have written, and nothing may reach the blob store after
// close() returns: Rebuild Cache removes the blob on the next line.
this.followUpCancelled = true;
if (this.deferredSaveTimer !== null) {
window.clearTimeout(this.deferredSaveTimer);
this.deferredSaveTimer = null;
}

// Let an export that is already running finish before starting another,
// so closing never puts a second full-size buffer alongside it. Its
Expand All @@ -557,7 +676,18 @@ export class SQLiteCacheManager implements IStorageBackend, ISQLiteCacheManager

// Final save
if (this.hasUnsavedData) {
await this.saveToFile();
try {
await this.saveToFile();
} catch (error) {
if (!(error instanceof SaveDeferredError)) {
throw error;
}
console.error(
'[SQLiteCacheManager] Closing with a transaction still open; the changes since the '
+ 'last save are not written and are rebuilt from the event store on next start.',
error
);
}
}

if (this.db) {
Expand Down Expand Up @@ -869,6 +999,10 @@ export class SQLiteCacheManager implements IStorageBackend, ISQLiteCacheManager
// already scheduled independently of it, and it would export after the
// caller believes writes have stopped.
this.followUpCancelled = true;
if (this.deferredSaveTimer !== null) {
window.clearTimeout(this.deferredSaveTimer);
this.deferredSaveTimer = null;
}
}

/**
Expand Down
106 changes: 99 additions & 7 deletions src/database/storage/SQLiteWasmBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ export interface SQLiteWasmModule {
};
wasm: {
allocFromTypedArray(data: Uint8Array): number;
alloc(size: number): number;
dealloc(ptr: number): void;
heap8u(): Uint8Array;
peek64(ptr: number): bigint;
};
capi: {
sqlite3_deserialize(
Expand All @@ -36,9 +40,12 @@ export interface SQLiteWasmModule {
flags: number
): number;
sqlite3_js_db_export(db: SQLiteDatabaseHandle): { buffer: ArrayBuffer };
sqlite3_serialize(db: SQLiteDatabaseHandle, schema: string, sizePtr: number, flags: number): number;
sqlite3_get_autocommit(db: SQLiteDatabaseHandle): number;
sqlite3_last_insert_rowid(db: SQLiteDatabaseHandle): number | bigint;
SQLITE_DESERIALIZE_FREEONCLOSE: number;
SQLITE_DESERIALIZE_RESIZEABLE: number;
SQLITE_SERIALIZE_NOCOPY: number;
};
}

Expand All @@ -55,6 +62,28 @@ type SQLiteModuleFactory = (options?: SQLiteInitOptions) => Promise<SQLiteWasmMo

const sqliteModuleFactory = sqlite3InitModule as unknown as SQLiteModuleFactory;

/**
* Free space allocated behind a deserialized database, as a share of its size,
* clamped to [MIN, MAX].
*
* A deserialized database lives in one heap buffer exactly its own size, and
* the first write that needs one more page makes SQLite double that buffer
* (memdbEnlarge), holding old and new at once while it copies. For a 314 MiB
* cache that is ~940 MiB of WASM heap from a single new page. Allocating the
* buffer with room to spare lets ordinary growth land in that room, so a
* session doubles only after it has written more than the slack.
*/
const DESERIALIZE_SLACK_SHARE = 1 / 8;
const DESERIALIZE_SLACK_MIN_BYTES = 8 * 1024 * 1024;
const DESERIALIZE_SLACK_MAX_BYTES = 64 * 1024 * 1024;

export function deserializeSlackBytes(size: number): number {
return Math.min(
DESERIALIZE_SLACK_MAX_BYTES,
Math.max(DESERIALIZE_SLACK_MIN_BYTES, Math.ceil(size * DESERIALIZE_SLACK_SHARE))
);
}

export class SQLiteWasmBridge {
async initializeModule(wasmBinary: ArrayBuffer): Promise<SQLiteWasmModule> {
const initOptions: SQLiteInitOptions = {
Expand All @@ -79,15 +108,82 @@ export class SQLiteWasmBridge {
return new module.oo1.DB(':memory:');
}

/**
* Open `data` as an in-memory database, in a heap buffer with slack behind it
* (see DESERIALIZE_SLACK_SHARE). The slack is never part of the database:
* exports and serializations cover the database's own size only.
*/
deserializeDatabase(module: SQLiteWasmModule, data: Uint8Array): SQLiteDatabaseHandle {
const ptr = module.wasm.allocFromTypedArray(data);
const size = data.byteLength;
let capacity = size + deserializeSlackBytes(size);
let ptr: number;
try {
ptr = module.wasm.alloc(capacity);
} catch {
// The slack is an optimisation; a heap that cannot spare it still opens
// the database the way it always did.
capacity = size;
ptr = module.wasm.alloc(capacity);
}
module.wasm.heap8u().set(data, ptr);
return this.adoptBuffer(module, ptr, size, capacity);
}

/**
* Export the whole database as bytes outside the WASM heap.
*
* A deserialized database is already one contiguous buffer, so it is copied
* straight out of the heap (SQLITE_SERIALIZE_NOCOPY) instead of through
* sqlite3_js_db_export, which first allocates a second full-size copy inside
* the heap - the allocation that fails with SQLITE_NOMEM once the database
* is around a quarter of the heap. Same bytes either way. A database that
* was never deserialized (a fresh :memory: one) has no such buffer; NOCOPY
* returns null for it and the old export is used.
*/
exportDatabase(module: SQLiteWasmModule, db: SQLiteDatabaseHandle): ArrayBuffer {
const view = this.serializeInPlace(module, db);
if (view === null) {
return module.capi.sqlite3_js_db_export(db).buffer;
}
return view.heap.slice(view.ptr, view.ptr + view.size).buffer;
}

/** Whether `db` is outside any transaction (sqlite3_get_autocommit). */
isAutocommit(module: SQLiteWasmModule, db: SQLiteDatabaseHandle): boolean {
return module.capi.sqlite3_get_autocommit(db) !== 0;
}

private serializeInPlace(
module: SQLiteWasmModule,
db: SQLiteDatabaseHandle
): { heap: Uint8Array; ptr: number; size: number } | null {
const sizePtr = module.wasm.alloc(8);
let ptr: number;
let size: number;
try {
ptr = module.capi.sqlite3_serialize(db, 'main', sizePtr, module.capi.SQLITE_SERIALIZE_NOCOPY);
size = Number(module.wasm.peek64(sizePtr));
} finally {
module.wasm.dealloc(sizePtr);
}
if (!ptr) {
return null;
}
const heap = module.wasm.heap8u();
if (size < 0 || ptr + size > heap.byteLength) {
throw new Error(`In-place serialization returned a buffer outside the WASM heap (ptr ${ptr}, size ${size})`);
}
return { heap, ptr, size };
}

private adoptBuffer(module: SQLiteWasmModule, ptr: number, size: number, capacity: number): SQLiteDatabaseHandle {
const db = this.createMemoryDatabase(module);
const rc = module.capi.sqlite3_deserialize(
db,
'main',
ptr,
data.byteLength,
data.byteLength,
size,
capacity,
module.capi.SQLITE_DESERIALIZE_FREEONCLOSE |
module.capi.SQLITE_DESERIALIZE_RESIZEABLE
);
Expand All @@ -99,10 +195,6 @@ export class SQLiteWasmBridge {
return db;
}

exportDatabase(module: SQLiteWasmModule, db: SQLiteDatabaseHandle): ArrayBuffer {
return module.capi.sqlite3_js_db_export(db).buffer;
}

exec(db: SQLiteDatabaseHandle, sql: string): void {
db.exec(sql);
}
Expand Down
1 change: 1 addition & 0 deletions tests/perf/cache-save-allocation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ async function createAllocationHarness(): Promise<AllocationHarness> {
initializeModule: jest.fn(async () => sqlite3),
createMemoryDatabase: jest.fn(() => dbHandle),
deserializeDatabase: jest.fn(() => dbHandle),
isAutocommit: jest.fn(() => true),
exportDatabase: jest.fn(() => {
exportCount += 1;
// A real allocation of the modelled size, so this fails the same way the
Expand Down
1 change: 1 addition & 0 deletions tests/unit/SQLiteCacheManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,7 @@ describe('SQLiteCacheManager save path', () => {
deserializeDatabase: jest.fn(() => dbHandle),
// A distinct buffer per call, so two overlapping saves are two live
// allocations and not one shared object.
isAutocommit: jest.fn(() => true),
exportDatabase: jest.fn(() => {
attempts++;
if (exportFailure && failuresRemaining > 0) {
Expand Down
Loading
Loading