diff --git a/src/core/services/immersion-tracker/storage-session.test.ts b/src/core/services/immersion-tracker/storage-session.test.ts index 07a21995..ff36deb8 100644 --- a/src/core/services/immersion-tracker/storage-session.test.ts +++ b/src/core/services/immersion-tracker/storage-session.test.ts @@ -3,7 +3,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import test from 'node:test'; -import { Database } from './sqlite'; +import { Database, type DatabaseSync } from './sqlite'; import { getStatsExcludedWords, replaceStatsExcludedWords } from './query-lexical'; import { finalizeSessionRecord, startSessionRecord } from './session'; import { @@ -87,6 +87,29 @@ test('applyPragmas sets the SQLite tuning defaults used by immersion tracking', } }); +test('applyPragmas installs the busy timeout before WAL negotiation', () => { + const statements: string[] = []; + const db: DatabaseSync = { + exec(source) { + statements.push(source); + return db; + }, + prepare() { + throw new Error('not used'); + }, + close() { + return db; + }, + }; + + applyPragmas(db); + + assert.deepEqual(statements.slice(0, 2), [ + 'PRAGMA busy_timeout = 2500', + 'PRAGMA journal_mode = WAL', + ]); +}); + test('ensureSchema creates immersion core tables', () => { const dbPath = makeDbPath(); const db = new Database(dbPath); diff --git a/src/core/services/immersion-tracker/storage.ts b/src/core/services/immersion-tracker/storage.ts index 74286dff..d04b3cbd 100644 --- a/src/core/services/immersion-tracker/storage.ts +++ b/src/core/services/immersion-tracker/storage.ts @@ -315,10 +315,12 @@ function migrateSessionEventTimestampsToText(db: DatabaseSync): void { } export function applyPragmas(db: DatabaseSync): void { + // Install the wait policy before WAL negotiation, which can briefly contend with + // another connection closing or checkpointing the same database. + db.exec('PRAGMA busy_timeout = 2500'); db.exec('PRAGMA journal_mode = WAL'); db.exec('PRAGMA synchronous = NORMAL'); db.exec('PRAGMA foreign_keys = ON'); - db.exec('PRAGMA busy_timeout = 2500'); db.exec(`PRAGMA journal_size_limit = ${WAL_JOURNAL_SIZE_LIMIT_BYTES}`); }