diff --git a/src/database/storage/SQLiteCacheManager.ts b/src/database/storage/SQLiteCacheManager.ts index 51cdd0bfd..0fff81b4f 100644 --- a/src/database/storage/SQLiteCacheManager.ts +++ b/src/database/storage/SQLiteCacheManager.ts @@ -71,6 +71,46 @@ export interface QueryResult { 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. @@ -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; @@ -131,6 +174,8 @@ export class SQLiteCacheManager implements IStorageBackend, ISQLiteCacheManager private saveInFlight: Promise | 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 | null = null; /** Set by stopAutoSave() and close() to cancel a scheduled follow-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 @@ -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. @@ -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 { + 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 @@ -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 => { 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(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( @@ -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. * @@ -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 @@ -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) { @@ -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; + } } /** diff --git a/src/database/storage/SQLiteWasmBridge.ts b/src/database/storage/SQLiteWasmBridge.ts index c6375a3ec..9f8c1cf19 100644 --- a/src/database/storage/SQLiteWasmBridge.ts +++ b/src/database/storage/SQLiteWasmBridge.ts @@ -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( @@ -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; }; } @@ -55,6 +62,28 @@ type SQLiteModuleFactory = (options?: SQLiteInitOptions) => Promise { const initOptions: SQLiteInitOptions = { @@ -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 ); @@ -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); } diff --git a/tests/perf/cache-save-allocation.test.ts b/tests/perf/cache-save-allocation.test.ts index c9830f53d..92c872efb 100644 --- a/tests/perf/cache-save-allocation.test.ts +++ b/tests/perf/cache-save-allocation.test.ts @@ -152,6 +152,7 @@ async function createAllocationHarness(): Promise { 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 diff --git a/tests/unit/SQLiteCacheManager.test.ts b/tests/unit/SQLiteCacheManager.test.ts index a863495c7..8b4e7aa89 100644 --- a/tests/unit/SQLiteCacheManager.test.ts +++ b/tests/unit/SQLiteCacheManager.test.ts @@ -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) { diff --git a/tests/unit/SQLiteCacheManagerInitSaveFailure.test.ts b/tests/unit/SQLiteCacheManagerInitSaveFailure.test.ts new file mode 100644 index 000000000..3a87ce4e5 --- /dev/null +++ b/tests/unit/SQLiteCacheManagerInitSaveFailure.test.ts @@ -0,0 +1,306 @@ +jest.mock('@dao-xyz/sqlite3-vec/wasm', () => jest.fn(), { virtual: true }); + +import type { App } from 'obsidian'; + +import { SQLiteCacheManager, isAllocationFailure } from '../../src/database/storage/SQLiteCacheManager'; +import { SQLitePersistenceService } from '../../src/database/storage/SQLitePersistenceService'; +import { CURRENT_SCHEMA_VERSION } from '../../src/database/schema/SchemaMigrator'; +import type { CacheBlobStore } from '../../src/database/storage/CacheBlobStore'; +import { HybridStorageAdapter } from '../../src/database/adapters/HybridStorageAdapter'; +import { StartupHydrationController } from '../../src/database/adapters/lifecycle/StartupHydrationController'; +import { InitLifecycleController } from '../../src/database/adapters/lifecycle/InitLifecycleController'; + +/** + * The shape sqlite3_js_db_export really throws when the WASM heap cannot hold + * the serialized database: an SQLite3Error whose resultCode is the generic + * SQLITE_ERROR (1), because the export passes the code as a string, and whose + * message is the only place SQLITE_NOMEM appears. + */ +class FakeSQLite3Error extends Error { + resultCode = 1; + constructor(message: string) { + super(message); + this.name = 'SQLite3Error'; + } +} + +function exportNomem(): Error { + return new FakeSQLite3Error('Database serialization failed with code SQLITE_NOMEM'); +} + +interface InitHarness { + manager: SQLiteCacheManager; + exportAttempts(): number; + exportCount(): number; + failNextExports(error: Error, count: number): void; + dispose(): void; +} + +/** + * A cache manager on a fake WASM bridge, built WITHOUT calling initialize(), + * so a test can make the saves inside initialize() fail. + * + * existingBlobBytes > 0 opens an existing cache instead of creating one; + * schemaVersion below CURRENT_SCHEMA_VERSION makes the migrator apply the + * pending migrations, which is the path that triggers the post-migration save. + */ +function createInitHarness(options: { + autoSaveInterval?: number; + existingBlobBytes?: number; + schemaVersion?: number; +} = {}): InitHarness { + let attempts = 0; + let exported = 0; + let exportFailure: Error | null = null; + let failuresRemaining = 0; + const schemaVersion = options.schemaVersion ?? CURRENT_SCHEMA_VERSION; + + const dbHandle = { + exec: jest.fn(), + prepare: jest.fn(), + close: jest.fn(), + changes: jest.fn(() => 0), + selectValue: jest.fn(() => 'ok') + }; + const sqlite3 = { oo1: {}, wasm: {}, capi: {} }; + + const bridge = { + initializeModule: jest.fn(async () => sqlite3), + createMemoryDatabase: jest.fn(() => dbHandle), + deserializeDatabase: jest.fn(() => dbHandle), + isAutocommit: jest.fn(() => true), + exportDatabase: jest.fn(() => { + attempts++; + if (exportFailure && failuresRemaining > 0) { + failuresRemaining--; + throw exportFailure; + } + exported++; + return new ArrayBuffer(4096); + }), + exec: jest.fn(), + executeStatement: jest.fn(), + collectValues: jest.fn((_db: unknown, sql: string) => { + if (sql.includes("name='schema_version'")) return [['schema_version']]; + if (sql.includes('MAX(version)')) return [[schemaVersion]]; + return []; + }), + query: jest.fn(() => []), + queryOne: jest.fn(() => null), + run: jest.fn(() => ({ changes: 1, lastInsertRowid: 1 })), + getIntegrityCheckResult: jest.fn(() => 'ok'), + close: jest.fn() + }; + + const existingBlobBytes = options.existingBlobBytes ?? 0; + const blobStore = { + read: jest.fn(async () => (existingBlobBytes > 0 ? new ArrayBuffer(existingBlobBytes) : null)), + write: jest.fn(async () => undefined), + remove: jest.fn(async () => undefined), + getMetadata: jest.fn(async () => (existingBlobBytes > 0 ? { size: existingBlobBytes } : null)) + }; + + const app = { + vault: { + configDir: '.obsidian', + adapter: { + exists: jest.fn(async () => true), + readBinary: jest.fn(async () => new ArrayBuffer(8)), + mkdir: jest.fn(async () => undefined), + stat: jest.fn(async () => ({ size: 0 })) + } + } + } as unknown as App; + + const manager = new SQLiteCacheManager({ + app, + dbPath: '.nexus/data/cache.db', + autoSaveInterval: options.autoSaveInterval ?? 0, + blobStore: blobStore as unknown as CacheBlobStore + }); + const internals = manager as unknown as { + bridge: unknown; + persistenceService: SQLitePersistenceService; + }; + internals.bridge = bridge; + internals.persistenceService = new SQLitePersistenceService({ + blobStore: blobStore as unknown as CacheBlobStore, + bridge: bridge as unknown as ConstructorParameters[0]['bridge'] + }); + + return { + manager, + exportAttempts: () => attempts, + exportCount: () => exported, + failNextExports: (error, count) => { + exportFailure = error; + failuresRemaining = count; + }, + dispose: () => manager.stopAutoSave() + }; +} + +describe('SQLiteCacheManager initialize when its own save fails', () => { + let errorSpy: jest.SpyInstance; + let warnSpy: jest.SpyInstance; + + beforeEach(() => { + errorSpy = jest.spyOn(console, 'error').mockImplementation(() => undefined); + warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => undefined); + }); + + afterEach(() => { + errorSpy.mockRestore(); + warnSpy.mockRestore(); + jest.useRealTimers(); + }); + + it('stays usable when the fresh-database save runs out of WASM memory', async () => { + const harness = createInitHarness(); + try { + harness.failNextExports(exportNomem(), 1); + await expect(harness.manager.initialize()).resolves.toBeUndefined(); + expect(harness.manager.isReady()).toBe(true); + // Nothing was persisted, so the cache must still count as unsaved. + expect(harness.manager.hasUnsavedChanges()).toBe(true); + } finally { + harness.dispose(); + } + }); + + it('stays usable when the save after migrating an existing cache runs out of WASM memory', async () => { + const harness = createInitHarness({ + existingBlobBytes: 8192, + schemaVersion: CURRENT_SCHEMA_VERSION - 1 + }); + try { + harness.failNextExports(exportNomem(), 1); + await expect(harness.manager.initialize()).resolves.toBeUndefined(); + expect(harness.exportAttempts()).toBe(1); + expect(harness.manager.isReady()).toBe(true); + // The migration changed the database and that change is not on disk. + expect(harness.manager.hasUnsavedChanges()).toBe(true); + } finally { + harness.dispose(); + } + }); + + it('persists the migrated database on the next save that succeeds', async () => { + const harness = createInitHarness({ + existingBlobBytes: 8192, + schemaVersion: CURRENT_SCHEMA_VERSION - 1 + }); + try { + harness.failNextExports(exportNomem(), 1); + await harness.manager.initialize(); + await harness.manager.save(); + expect(harness.exportCount()).toBe(1); + expect(harness.manager.hasUnsavedChanges()).toBe(false); + } finally { + harness.dispose(); + } + }); + + it('leaves nothing unsaved when the post-migration save succeeds', async () => { + const harness = createInitHarness({ + existingBlobBytes: 8192, + schemaVersion: CURRENT_SCHEMA_VERSION - 1 + }); + try { + await harness.manager.initialize(); + // The post-migration save went through, so nothing is outstanding. + expect(harness.exportCount()).toBe(1); + expect(harness.manager.hasUnsavedChanges()).toBe(false); + } finally { + harness.dispose(); + } + }); + + it('does not let auto-save retry the export before the allocation back-off elapses', async () => { + jest.useFakeTimers(); + const harness = createInitHarness({ + autoSaveInterval: 1000, + existingBlobBytes: 8192, + schemaVersion: CURRENT_SCHEMA_VERSION - 1 + }); + try { + harness.failNextExports(exportNomem(), 1); + await harness.manager.initialize(); + expect(harness.exportAttempts()).toBe(1); + + // First back-off step is two minutes; ticks before it must not export. + await jest.advanceTimersByTimeAsync(119000); + expect(harness.exportAttempts()).toBe(1); + + await jest.advanceTimersByTimeAsync(2000); + expect(harness.exportAttempts()).toBe(2); + expect(harness.manager.hasUnsavedChanges()).toBe(false); + } finally { + harness.dispose(); + } + }); + + it('backs off auto-save after an SQLITE_NOMEM export failure at runtime', async () => { + jest.useFakeTimers(); + const harness = createInitHarness({ autoSaveInterval: 1000 }); + try { + await harness.manager.initialize(); + harness.failNextExports(exportNomem(), 1); + await harness.manager.run('INSERT INTO memory_traces (id) VALUES (?)', ['t1']); + + await jest.advanceTimersByTimeAsync(1000); + const afterFailure = harness.exportAttempts(); + expect(harness.manager.hasUnsavedChanges()).toBe(true); + + await jest.advanceTimersByTimeAsync(118000); + expect(harness.exportAttempts()).toBe(afterFailure); + + await jest.advanceTimersByTimeAsync(2000); + expect(harness.exportAttempts()).toBe(afterFailure + 1); + expect(harness.manager.hasUnsavedChanges()).toBe(false); + } finally { + harness.dispose(); + } + }); + + it('leaves the storage adapter query-ready when the cache could not save during startup', async () => { + const harness = createInitHarness({ + existingBlobBytes: 8192, + schemaVersion: CURRENT_SCHEMA_VERSION - 1 + }); + try { + harness.failNextExports(exportNomem(), 1); + const adapter = Object.create(HybridStorageAdapter.prototype) as HybridStorageAdapter & { + hydration: StartupHydrationController; + initLifecycle: InitLifecycleController; + }; + adapter.hydration = new StartupHydrationController(); + adapter.initLifecycle = new InitLifecycleController(); + // The adapter's own startup awaits the cache's initialize() inside its + // lifecycle; a rejection there is what left the adapter failed for good. + void adapter.initLifecycle + .run(() => harness.manager.initialize(), { blocking: false }) + .catch(() => undefined); + + await expect(adapter.waitForQueryReady(1000)).resolves.toBe(true); + expect(adapter.isQueryReady()).toBe(true); + } finally { + harness.dispose(); + } + }); +}); + +describe('isAllocationFailure', () => { + it('recognises both shapes an out-of-memory export takes', () => { + expect(isAllocationFailure(new RangeError('Array buffer allocation failed'))).toBe(true); + expect(isAllocationFailure(exportNomem())).toBe(true); + expect(isAllocationFailure(Object.assign(new Error('out of memory'), { resultCode: 7 }))).toBe(true); + }); + + it('leaves other failures to the normal cadence', () => { + expect(isAllocationFailure(new RangeError('Invalid array length'))).toBe(false); + expect(isAllocationFailure(new FakeSQLite3Error('Database serialization failed with code SQLITE_IOERR'))).toBe(false); + expect(isAllocationFailure(new Error('disk full'))).toBe(false); + expect(isAllocationFailure(undefined)).toBe(false); + }); +}); diff --git a/tests/unit/SQLiteCacheManagerMemorySafety.test.ts b/tests/unit/SQLiteCacheManagerMemorySafety.test.ts new file mode 100644 index 000000000..5fd79e66b --- /dev/null +++ b/tests/unit/SQLiteCacheManagerMemorySafety.test.ts @@ -0,0 +1,102 @@ +jest.mock('@dao-xyz/sqlite3-vec/wasm', () => jest.fn(), { virtual: true }); + +import type { App } from 'obsidian'; + +import { SQLiteCacheManager } from '../../src/database/storage/SQLiteCacheManager'; +import { SQLitePersistenceService } from '../../src/database/storage/SQLitePersistenceService'; +import type { CacheBlobStore } from '../../src/database/storage/CacheBlobStore'; + +function harness() { + let inTransaction = false; + let exported = 0; + const dbHandle = { exec: jest.fn(), prepare: jest.fn(), close: jest.fn(), changes: jest.fn(() => 0), selectValue: jest.fn(() => 'ok') }; + const cloneHandle = { ...dbHandle, close: jest.fn() }; + const sqlite3 = { oo1: {}, wasm: {}, capi: {} }; + const bridge = { + exportDatabase: jest.fn(() => { exported++; return new ArrayBuffer(16); }), + cloneDatabase: jest.fn(() => cloneHandle), + deserializeDatabase: jest.fn(() => dbHandle), + isAutocommit: jest.fn(() => !inTransaction), + exec: jest.fn(), + run: jest.fn(() => ({ changes: 1, lastInsertRowid: 1 })), + query: jest.fn(() => []), + queryOne: jest.fn(() => null), + close: jest.fn() + }; + const blobStore = { read: jest.fn(), write: jest.fn(async () => undefined), remove: jest.fn(), getMetadata: jest.fn() }; + const manager = new SQLiteCacheManager({ + app: { vault: { configDir: '.obsidian', adapter: {} } } as unknown as App, + dbPath: '.nexus/data/cache.db', + autoSaveInterval: 0, + blobStore: blobStore as unknown as CacheBlobStore + }); + const internals = manager as unknown as Record; + internals.bridge = bridge; + internals.db = dbHandle; + internals.sqlite3 = sqlite3; + internals.isInitialized = true; + internals.persistenceService = new SQLitePersistenceService({ + blobStore: blobStore as unknown as CacheBlobStore, + bridge: bridge as unknown as ConstructorParameters[0]['bridge'] + }); + return { + manager, bridge, cloneHandle, + exported: () => exported, + setInTransaction: (v: boolean) => { inTransaction = v; }, + internals + }; +} + +describe('SQLiteCacheManager memory-safe save and planning clone', () => { + beforeEach(() => jest.useFakeTimers()); + afterEach(() => jest.useRealTimers()); + + it('does not export while a transaction is open, and exports once it ends', async () => { + const h = harness(); + h.setInTransaction(true); + (h.manager as unknown as { markDirty(): void }).markDirty(); + const saving = h.manager.save(); + await jest.advanceTimersByTimeAsync(200); + expect(h.exported()).toBe(0); + h.setInTransaction(false); + await jest.advanceTimersByTimeAsync(100); + await saving; + expect(h.exported()).toBe(1); + expect(h.manager.hasUnsavedChanges()).toBe(false); + }); + + it('defers instead of exporting a transaction that outlives the wait, stays dirty, and retries', async () => { + const h = harness(); + h.setInTransaction(true); + (h.manager as unknown as { markDirty(): void }).markDirty(); + const saving = h.manager.save(); + const outcome = saving.then(() => 'resolved', (error: Error) => error.message); + await jest.advanceTimersByTimeAsync(6000); + // A resolved save means the bytes were written; a deferred one must not resolve. + expect(await outcome).toContain('Save deferred: a transaction is still open'); + expect(h.exported()).toBe(0); + expect(h.manager.hasUnsavedChanges()).toBe(true); + expect(h.internals.nextAutoSaveAttemptAt).toBe(0); + h.setInTransaction(false); + await jest.advanceTimersByTimeAsync(1500); + expect(h.exported()).toBe(1); + expect(h.manager.hasUnsavedChanges()).toBe(false); + }); + + + it('still closes the database when a transaction outlives the final save', async () => { + const h = harness(); + const error = jest.spyOn(console, 'error').mockImplementation(() => undefined); + h.setInTransaction(true); + (h.manager as unknown as { markDirty(): void }).markDirty(); + const closing = h.manager.close(); + await jest.advanceTimersByTimeAsync(6000); + await closing; + expect(h.exported()).toBe(0); + expect(h.bridge.close).toHaveBeenCalled(); + expect(error).toHaveBeenCalledWith(expect.stringContaining('Closing with a transaction still open'), expect.anything()); + await jest.advanceTimersByTimeAsync(2000); + expect(h.exported()).toBe(0); + error.mockRestore(); + }); +}); diff --git a/tests/unit/SQLiteWasmBridgeMemory.test.ts b/tests/unit/SQLiteWasmBridgeMemory.test.ts new file mode 100644 index 000000000..525c25a51 --- /dev/null +++ b/tests/unit/SQLiteWasmBridgeMemory.test.ts @@ -0,0 +1,91 @@ +jest.mock('@dao-xyz/sqlite3-vec/wasm', () => jest.fn(), { virtual: true }); + +import { + SQLiteWasmBridge, + deserializeSlackBytes +} from '../../src/database/storage/SQLiteWasmBridge'; +import type { SQLiteWasmModule, SQLiteDatabaseHandle } from '../../src/database/storage/SQLiteWasmBridge'; + +const NOCOPY = 1; + +/** + * A fake sqlite3 module over a real byte heap: alloc is a bump allocator, and + * sqlite3_serialize(NOCOPY) hands back the buffer a database was deserialized + * from, the way memdb does, or 0 for a database that was never deserialized. + */ +function fakeModule(heapBytes = 4096) { + const heap = new Uint8Array(heapBytes); + let next = 8; + const buffers = new Map(); + const allocs: number[] = []; + const module = { + oo1: { DB: jest.fn().mockImplementation(() => ({ exec: jest.fn(), prepare: jest.fn(), close: jest.fn(), changes: jest.fn(), selectValue: jest.fn() })) }, + wasm: { + allocFromTypedArray: jest.fn(), + alloc: jest.fn((n: number) => { allocs.push(n); if (next + n > heap.byteLength) throw new Error('Failed to allocate'); const p = next; next += n; return p; }), + dealloc: jest.fn(), + heap8u: () => heap, + peek64: (p: number) => new DataView(heap.buffer).getBigInt64(p, true) + }, + capi: { + SQLITE_DESERIALIZE_FREEONCLOSE: 1, + SQLITE_DESERIALIZE_RESIZEABLE: 2, + SQLITE_SERIALIZE_NOCOPY: NOCOPY, + sqlite3_deserialize: jest.fn((db: object, _s: string, ptr: number, size: number, capacity: number) => { buffers.set(db, { ptr, size, capacity }); return 0; }), + sqlite3_serialize: jest.fn((db: object, _s: string, sizePtr: number, flags: number) => { + const b = buffers.get(db); + new DataView(heap.buffer).setBigInt64(sizePtr, BigInt(b?.size ?? 0), true); + return flags === NOCOPY && b ? b.ptr : 0; + }), + sqlite3_js_db_export: jest.fn(() => new Uint8Array([9, 9, 9])), + sqlite3_get_autocommit: jest.fn(() => 1), + sqlite3_last_insert_rowid: jest.fn() + } + }; + return { module: module as unknown as SQLiteWasmModule & typeof module, heap, buffers, allocs }; +} + +describe('SQLiteWasmBridge memory behaviour', () => { + const bridge = new SQLiteWasmBridge(); + + it('opens a database with slack behind it, so the first new page does not double the buffer', () => { + const { module, buffers } = fakeModule(16 * 1024 * 1024); + const data = new Uint8Array([1, 2, 3, 4]); + const db = bridge.deserializeDatabase(module, data); + const b = buffers.get(db as unknown as object)!; + expect(b.size).toBe(4); + expect(b.capacity).toBe(4 + deserializeSlackBytes(4)); + }); + + it('falls back to an exact-size buffer when the heap cannot spare the slack', () => { + const { module, buffers } = fakeModule(64); + const db = bridge.deserializeDatabase(module, new Uint8Array([1, 2, 3, 4])); + expect(buffers.get(db as unknown as object)!.capacity).toBe(4); + }); + + it('exports by copying the database straight out of the heap, without the in-heap export copy', () => { + const { module } = fakeModule(64 * 1024 * 1024); + const data = new Uint8Array([5, 6, 7, 8, 9]); + const db = bridge.deserializeDatabase(module, data); + const out = new Uint8Array(bridge.exportDatabase(module, db)); + expect(Array.from(out)).toEqual([5, 6, 7, 8, 9]); + expect(module.capi.sqlite3_js_db_export).not.toHaveBeenCalled(); + }); + + it('falls back to sqlite3_js_db_export for a database that was never deserialized', () => { + const { module } = fakeModule(); + const fresh = bridge.createMemoryDatabase(module); + const out = new Uint8Array(bridge.exportDatabase(module, fresh)); + expect(Array.from(out)).toEqual([9, 9, 9]); + }); + + it('reports whether a connection is inside a transaction', () => { + const { module } = fakeModule(); + const db = bridge.createMemoryDatabase(module) as SQLiteDatabaseHandle; + expect(bridge.isAutocommit(module, db)).toBe(true); + module.capi.sqlite3_get_autocommit.mockReturnValue(0); + expect(bridge.isAutocommit(module, db)).toBe(false); + }); + +}); +});