fix(memory): isolate backup rotation and restore by store

This commit is contained in:
Rudy Celekli committed 2026-09-26 19:25:59 -04:00
1 parent 39ea61fda9
commit f50488e4d6
2 files changed
+78 -4

No files matched your search

@@ -0,0 +1,62 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import Database from 'better-sqlite3';
import { backupMemoryDb, restoreMemoryDbFromBackup } from '../src/services/memory-backup.js';
let dir: string;
const start = 1_700_000_000_000;
beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'memory-backup-isolation-')); });
afterEach(() => { rmSync(dir, { recursive: true, force: true }); });
function seed(name: string) {
const dbPath = join(dir, name);
const db = new Database(dbPath);
db.exec('CREATE TABLE memory_entries (content TEXT)');
db.prepare('INSERT INTO memory_entries VALUES (?)').run(name);
db.close();
return dbPath;
}
function content(dbPath: string) {
const db = new Database(dbPath, { readonly: true });
try { return db.prepare('SELECT content FROM memory_entries').get(); }
finally { db.close(); }
}
describe('backup identity across sibling memory stores', () => {
it('does not overwrite a different store snapshot at the same timestamp', async () => {
const primary = seed('memory.db');
const mirror = seed('agentdb-memory.db');
const a = await backupMemoryDb({ dbPath: primary, timestamp: start });
const b = await backupMemoryDb({ dbPath: mirror, timestamp: start });
expect(a.backedUp).toBe(true);
expect(b.backedUp).toBe(true);
expect(a.path).not.toBe(b.path);
expect(content(a.path!)).toEqual({ content: 'memory.db' });
expect(content(b.path!)).toEqual({ content: 'agentdb-memory.db' });
});
it('rotates only snapshots belonging to the selected store', async () => {
const primary = seed('memory.db');
const mirror = seed('agentdb-memory.db');
const a = await backupMemoryDb({ dbPath: primary, timestamp: start, keep: 1 });
const b = await backupMemoryDb({ dbPath: mirror, timestamp: start + 1000, keep: 1 });
const c = await backupMemoryDb({ dbPath: mirror, timestamp: start + 2000, keep: 1 });
expect(existsSync(a.path!)).toBe(true);
expect(existsSync(b.path!)).toBe(false);
expect(existsSync(c.path!)).toBe(true);
expect(c.rotatedAway).toHaveLength(1);
});
it.each(['memory.db', 'agentdb-memory.db'])('restores only %s snapshots even when another store is newer', async (name) => {
const primary = seed(name);
const other = seed(name === 'memory.db' ? 'agentdb-memory.db' : 'memory.db');
const a = await backupMemoryDb({ dbPath: primary, timestamp: start });
await backupMemoryDb({ dbPath: other, timestamp: start + 1000 });
writeFileSync(primary, 'corrupt source');
const restored = await restoreMemoryDbFromBackup(primary);
expect(restored.restored).toBe(true);
expect(restored.from).toBe(a.path);
expect(content(primary)).toEqual({ content: name });
});
});
@@ -47,6 +47,18 @@ function fileStamp(ms: number): string {
return new Date(ms).toISOString().replace(/[:.]/g, '-');
}
/** Keep legacy memory.db names; give every other basename its own snapshot set. */
function snapshotPrefix(dbPath: string): string {
const name = path.basename(dbPath);
return name === 'memory.db' ? 'memory-' : `${encodeURIComponent(name)}-`;
}
function isSnapshotFor(file: string, dbPath: string): boolean {
const prefix = snapshotPrefix(dbPath);
return file.startsWith(prefix)
&& /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z\.db$/.test(file.slice(prefix.length));
}
export async function backupMemoryDb(opts: BackupOptions = {}): Promise<BackupResult> {
const dbPath = opts.dbPath ?? defaultMemoryDbPath();
if (!dbPath || !fs.existsSync(dbPath)) return { backedUp: false, skipped: 'no-db' };
@@ -61,7 +73,7 @@ export async function backupMemoryDb(opts: BackupOptions = {}): Promise<BackupRe
const destDir = opts.destDir ?? path.join(path.dirname(dbPath), 'backups');
try { fs.mkdirSync(destDir, { recursive: true }); } catch { /* */ }
const destPath = path.join(destDir, `memory-${fileStamp(opts.timestamp ?? Date.now())}.db`);
const destPath = path.join(destDir, `${snapshotPrefix(dbPath)}${fileStamp(opts.timestamp ?? Date.now())}.db`);
// WAL-safe online backup: read-only source, consistent snapshot to destPath.
let db: any;
@@ -88,7 +100,7 @@ export async function backupMemoryDb(opts: BackupOptions = {}): Promise<BackupRe
const keep = typeof opts.keep === 'number' && opts.keep > 0 ? opts.keep : 7;
const rotatedAway: string[] = [];
try {
const snaps = fs.readdirSync(destDir).filter(f => /^memory-.*\.db$/.test(f)).sort();
const snaps = fs.readdirSync(destDir).filter(f => isSnapshotFor(f, dbPath)).sort();
while (snaps.length > keep) {
const old = snaps.shift()!;
try { fs.rmSync(path.join(destDir, old), { force: true }); rotatedAway.push(old); } catch { /* */ }
@@ -119,7 +131,7 @@ export async function backupMemoryDb(opts: BackupOptions = {}): Promise<BackupRe
const keep = typeof opts.keep === 'number' && opts.keep > 0 ? opts.keep : 7;
const rotatedAway: string[] = [];
try {
const snaps = fs.readdirSync(destDir).filter(f => /^memory-.*\.db$/.test(f)).sort();
const snaps = fs.readdirSync(destDir).filter(f => isSnapshotFor(f, dbPath)).sort();
while (snaps.length > keep) {
const old = snaps.shift()!;
try { fs.rmSync(path.join(destDir, old), { force: true }); rotatedAway.push(old); } catch { /* */ }
@@ -183,7 +195,7 @@ export async function restoreMemoryDbFromBackup(
try {
snaps = fs
.readdirSync(destDir)
.filter(f => /^memory-.*\.db$/.test(f))
.filter(f => isSnapshotFor(f, dbPath))
.map(f => path.join(destDir, f))
.sort() // ISO-stamped names sort chronologically
.reverse(); // newest first