|
| 1 | +import { describe, expect, it, spyOn } from 'bun:test'; |
| 2 | +import { Database } from 'bun:sqlite'; |
| 3 | +import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs'; |
| 4 | +import { tmpdir } from 'node:os'; |
| 5 | +import { join } from 'node:path'; |
| 6 | +import { applyPendingRestore, swapDatabaseFromSnapshot } from '../../src/services/backup/restore-swap.js'; |
| 7 | +import { readLastRestoreResult, stagePendingRestore } from '../../src/services/backup/snapshot-files.js'; |
| 8 | +import { LATEST_SCHEMA_VERSION } from '../../src/services/sqlite/connection.js'; |
| 9 | +import { ChromaSyncState } from '../../src/services/sync/ChromaSyncState.js'; |
| 10 | +import { paths } from '../../src/shared/paths.js'; |
| 11 | + |
| 12 | +function createDatabase(file: string, value: string, schemaVersion: number) { |
| 13 | + const db = new Database(file); |
| 14 | + db.run('CREATE TABLE memories (value TEXT)'); |
| 15 | + db.run('INSERT INTO memories VALUES (?)', [value]); |
| 16 | + db.run(`PRAGMA user_version = ${schemaVersion}`); |
| 17 | + db.close(); |
| 18 | +} |
| 19 | + |
| 20 | +function fixture(schemaVersion: number) { |
| 21 | + const dir = mkdtempSync(join(tmpdir(), 'restore-schema-')); |
| 22 | + const dbPath = join(dir, 'live.db'); |
| 23 | + const backupsDir = join(dir, 'backups'); |
| 24 | + mkdirSync(backupsDir); |
| 25 | + const snapshotName = 'claude-mem-2026-01-01T00-00-00-000Z.db'; |
| 26 | + const snapshotPath = join(backupsDir, snapshotName); |
| 27 | + createDatabase(dbPath, 'healthy current database', LATEST_SCHEMA_VERSION); |
| 28 | + createDatabase(snapshotPath, 'snapshot database', schemaVersion); |
| 29 | + return { dir, dbPath, backupsDir, snapshotName, snapshotPath }; |
| 30 | +} |
| 31 | + |
| 32 | +describe('restore schema compatibility before live changes', () => { |
| 33 | + it('rejects a newer-schema snapshot before replacing or backing up the healthy live database', async () => { |
| 34 | + const { dir, dbPath, backupsDir, snapshotName, snapshotPath } = fixture(LATEST_SCHEMA_VERSION + 1); |
| 35 | + const originalLive = readFileSync(dbPath); |
| 36 | + const originalSnapshot = readFileSync(snapshotPath); |
| 37 | + try { |
| 38 | + let failure: unknown; |
| 39 | + try { await swapDatabaseFromSnapshot(dbPath, snapshotPath, { preRestoreDir: backupsDir }); } |
| 40 | + catch (error) { failure = error; } |
| 41 | + expect(failure instanceof Error).toBe(true); |
| 42 | + expect((failure as Error).message).toContain(`schema v${LATEST_SCHEMA_VERSION + 1}`); |
| 43 | + expect(readFileSync(dbPath)).toEqual(originalLive); |
| 44 | + expect(readFileSync(snapshotPath)).toEqual(originalSnapshot); |
| 45 | + expect(readdirSync(backupsDir)).toEqual([snapshotName]); |
| 46 | + expect(readdirSync(dir).filter(name => name.includes('.restore-'))).toEqual([]); |
| 47 | + } finally { rmSync(dir, { recursive: true, force: true }); } |
| 48 | + }); |
| 49 | + |
| 50 | + it('records a failed pending restore and leaves the worker able to use its existing database', async () => { |
| 51 | + const { dir, dbPath, backupsDir, snapshotName } = fixture(LATEST_SCHEMA_VERSION + 1); |
| 52 | + const pendingFile = join(dir, 'restore-pending.json'); |
| 53 | + const resultFile = join(dir, 'last-restore.json'); |
| 54 | + const pendingSpy = spyOn(paths, 'pendingRestore').mockReturnValue(pendingFile); |
| 55 | + const resultSpy = spyOn(paths, 'lastRestore').mockReturnValue(resultFile); |
| 56 | + let semanticRebuilds = 0; |
| 57 | + const rebuildSpy = spyOn(ChromaSyncState, 'markAllForRebuild').mockImplementation(() => { semanticRebuilds++; }); |
| 58 | + try { |
| 59 | + stagePendingRestore(snapshotName); |
| 60 | + const result = await applyPendingRestore(dbPath, backupsDir); |
| 61 | + expect(result?.ok).toBe(false); |
| 62 | + expect(result?.error).toContain(`schema v${LATEST_SCHEMA_VERSION + 1}`); |
| 63 | + expect(result?.preRestoreCopy).toBeNull(); |
| 64 | + expect(readLastRestoreResult()).toEqual(result); |
| 65 | + expect(existsSync(pendingFile)).toBe(false); |
| 66 | + expect(semanticRebuilds).toBe(0); |
| 67 | + const db = new Database(dbPath); |
| 68 | + try { |
| 69 | + expect(db.query('SELECT value FROM memories').get()).toEqual({ value: 'healthy current database' }); |
| 70 | + expect(db.query('PRAGMA user_version').get()).toEqual({ user_version: LATEST_SCHEMA_VERSION }); |
| 71 | + } finally { db.close(); } |
| 72 | + } finally { |
| 73 | + rebuildSpy.mockRestore(); resultSpy.mockRestore(); pendingSpy.mockRestore(); |
| 74 | + rmSync(dir, { recursive: true, force: true }); |
| 75 | + } |
| 76 | + }); |
| 77 | + |
| 78 | + it('also refuses a newer schema stamp committed only in a snapshot WAL', async () => { |
| 79 | + const { dir, dbPath, backupsDir, snapshotPath } = fixture(LATEST_SCHEMA_VERSION); |
| 80 | + const writer = new Database(snapshotPath); |
| 81 | + try { |
| 82 | + writer.run('PRAGMA journal_mode = WAL'); |
| 83 | + writer.run('PRAGMA wal_autocheckpoint = 0'); |
| 84 | + writer.run(`PRAGMA user_version = ${LATEST_SCHEMA_VERSION + 1}`); |
| 85 | + // The main file alone still has the compatible stamp; the restore must |
| 86 | + // validate the actual staged main + WAL state that it would install. |
| 87 | + const mainOnly = join(dir, 'main-only.db'); |
| 88 | + copyFileSync(snapshotPath, mainOnly); |
| 89 | + const probe = new Database(mainOnly); |
| 90 | + try { expect(probe.query('PRAGMA user_version').get()).toEqual({ user_version: LATEST_SCHEMA_VERSION }); } |
| 91 | + finally { probe.close(); } |
| 92 | + const originalLive = readFileSync(dbPath); |
| 93 | + let failure: unknown; |
| 94 | + try { await swapDatabaseFromSnapshot(dbPath, snapshotPath, { preRestoreDir: backupsDir }); } |
| 95 | + catch (error) { failure = error; } |
| 96 | + expect(failure instanceof Error).toBe(true); |
| 97 | + expect((failure as Error).message).toContain(`schema v${LATEST_SCHEMA_VERSION + 1}`); |
| 98 | + expect(readFileSync(dbPath)).toEqual(originalLive); |
| 99 | + } finally { writer.close(); rmSync(dir, { recursive: true, force: true }); } |
| 100 | + }); |
| 101 | + |
| 102 | + it('continues restoring unstamped, older, and current-schema snapshots', async () => { |
| 103 | + for (const schemaVersion of [0, LATEST_SCHEMA_VERSION - 1, LATEST_SCHEMA_VERSION]) { |
| 104 | + const { dir, dbPath, backupsDir, snapshotPath } = fixture(schemaVersion); |
| 105 | + try { |
| 106 | + const result = await swapDatabaseFromSnapshot(dbPath, snapshotPath, { preRestoreDir: backupsDir }); |
| 107 | + expect(result.preRestoreCopy).not.toBeNull(); |
| 108 | + const db = new Database(dbPath); |
| 109 | + try { |
| 110 | + expect(db.query('SELECT value FROM memories').get()).toEqual({ value: 'snapshot database' }); |
| 111 | + expect(db.query('PRAGMA user_version').get()).toEqual({ user_version: schemaVersion }); |
| 112 | + expect(db.query('PRAGMA quick_check').get()).toEqual({ quick_check: 'ok' }); |
| 113 | + } finally { db.close(); } |
| 114 | + } finally { rmSync(dir, { recursive: true, force: true }); } |
| 115 | + } |
| 116 | + }); |
| 117 | +}); |
0 commit comments