fix(memory): close the sql.js handle in checkMemoryInitialization on every path (#3249) (#3280)

`checkMemoryInitialization` constructed its sql.js handle inside the `try` and
reached `db.close()` only on the success path. The schema query is exactly the
call that throws on an image sql.js cannot parse — an RFE1-encrypted `memory.db`
being the common case once encryption at rest is on — so the `catch` returned
`{ initialized: false }` and the handle was never released. Every memory MCP
tool call runs this check first (memory-tools.ts `ensureInitialized`), so each
call left another handle open.

Hoist the handle out of the `try` and release it in a `finally`, so the parsed
and the rejected path both close it. The returned value is unchanged, so this is
behaviour-preserving apart from the release itself. Decrypt-before-open is
deliberately out of scope: changing `initialized` for an encrypted store would
alter what every caller sees, which is a separate decision from the leak.

Verified against the real sql.js, not a mock: `new SQL.Database(<RFE1 bytes>)`
succeeds (the constructor does not check the SQLite header) and the schema query
then throws `file is not a database` — the exact throw that skipped the close.
Retention was measured one arm per process, since Emscripten linear memory only
grows and measuring both arms in one process lets the first contaminate the
second: 8 unclosed handles over a 4,235,264-byte image retain ~0.21x the image
each, versus ~0.08x when each is closed. The issue reports ~1.0x per call; that
larger figure is not reproduced here, so this commit claims the leak, not its
magnitude.

Regression coverage in __tests__/memory-init-handle-leak-3249.test.ts asserts
the handle is closed on the rejected path, still closed on the parsed path, and
never opened when the file is absent. The first case fails against the pre-fix
source with "expected false to be true" and passes after.
This commit is contained in:
Wu Shuwen authored and GitHub committed 2026-09-16 02:22:51 +00:00
1 parent 90889f4772
commit 9b98bf7ee6
2 files changed
+130 -3

No files matched your search

@@ -0,0 +1,112 @@
/**
* Regression coverage for #3249: `checkMemoryInitialization` must release the
* sql.js handle on the failure path too.
*
* With encryption at rest the on-disk `memory.db` is an RFE1 ciphertext image.
* sql.js accepts those bytes, but the schema query cannot parse them as SQLite
* and throws — so `checkMemoryInitialization` fell through to its catch and
* returned `{ initialized: false }` without ever reaching the inline
* `db.close()`. That left the sql.js Database and its MEMFS copy open for the
* life of the process, and every memory MCP tool call runs this check first, so
* a long session accumulates one unclosed handle per call.
*
* The sql.js module is mocked so the assertion is on the observable contract
* (was a handle opened, and was it closed?) rather than on process memory,
* which would make the test slow and flaky.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const handle = vi.hoisted(() => ({
instances: [] as Array<{ closed: boolean }>,
}));
// Set per test: what `db.exec()` does once the handle exists.
const behaviour = vi.hoisted(() => ({
exec: (() => {
throw new Error('file is not a database');
}) as () => unknown,
}));
vi.mock('sql.js', () => {
class Database {
closed = false;
constructor(_data?: unknown) {
handle.instances.push(this);
}
exec(_sql: string): unknown {
return behaviour.exec();
}
close(): void {
this.closed = true;
}
}
return { default: async () => ({ Database }) };
});
const {
_resetMemoryRootCache,
checkMemoryInitialization,
} = await import('../src/memory/memory-initializer.js');
let testDir: string;
let originalMemoryPath: string | undefined;
beforeEach(() => {
testDir = mkdtempSync(join(tmpdir(), 'memory-init-leak-3249-'));
originalMemoryPath = process.env.CLAUDE_FLOW_MEMORY_PATH;
process.env.CLAUDE_FLOW_MEMORY_PATH = testDir;
_resetMemoryRootCache();
handle.instances.length = 0;
behaviour.exec = () => {
throw new Error('file is not a database');
};
});
afterEach(() => {
if (originalMemoryPath === undefined) delete process.env.CLAUDE_FLOW_MEMORY_PATH;
else process.env.CLAUDE_FLOW_MEMORY_PATH = originalMemoryPath;
_resetMemoryRootCache();
rmSync(testDir, { recursive: true, force: true });
});
describe('checkMemoryInitialization handle lifecycle (#3249)', () => {
it('closes the handle when the schema query rejects the image', async () => {
const dbPath = join(testDir, 'memory.db');
// RFE1 ciphertext: bytes sql.js will accept but cannot parse as SQLite.
writeFileSync(dbPath, Buffer.from('RFE1\x00\x01\x02 not a sqlite image', 'utf8'));
const result = await checkMemoryInitialization(dbPath);
expect(result.initialized).toBe(false);
expect(handle.instances).toHaveLength(1);
// The regression: this was `false` before the fix — the handle leaked.
expect(handle.instances[0].closed).toBe(true);
});
it('closes the handle on the parsed path as well', async () => {
const dbPath = join(testDir, 'memory.db');
writeFileSync(dbPath, Buffer.from('SQLite format 3\x00', 'utf8'));
behaviour.exec = () => [{ values: [['memory_entries'], ['metadata'], ['patterns']] }];
const result = await checkMemoryInitialization(dbPath);
expect(result.initialized).toBe(true);
expect(result.tables).toContain('memory_entries');
expect(handle.instances).toHaveLength(1);
expect(handle.instances[0].closed).toBe(true);
});
it('opens no handle at all when the file is absent', async () => {
const result = await checkMemoryInitialization(join(testDir, 'missing.db'));
expect(result.initialized).toBe(false);
expect(handle.instances).toHaveLength(0);
});
});
@@ -2077,13 +2077,17 @@ export async function checkMemoryInitialization(dbPath?: string): Promise<{
return { initialized: false };
}
// #3249: declared outside the try so the handle can be released on the
// failure path as well as the success path.
let db: any;
try {
// Try to load with sql.js
const initSqlJs = (await import('sql.js')).default;
const SQL = await initSqlJs();
const fileBuffer = fs.readFileSync(path_);
const db = new SQL.Database(fileBuffer);
db = new SQL.Database(fileBuffer);
// Check for metadata table
const tables = db.exec("SELECT name FROM sqlite_master WHERE type='table'");
@@ -2102,8 +2106,6 @@ export async function checkMemoryInitialization(dbPath?: string): Promise<{
// Metadata table might not exist
}
db.close();
return {
initialized: true,
version,
@@ -2118,6 +2120,19 @@ export async function checkMemoryInitialization(dbPath?: string): Promise<{
} catch {
// Could not read database
return { initialized: false };
} finally {
// #3249: release the handle on every path. An RFE1-encrypted image is not
// parseable as SQLite, so the schema query above throws and the catch
// returns — which used to skip the inline db.close() entirely, leaving the
// sql.js Database and its MEMFS copy open for the life of the process.
// Every memory MCP tool call runs this check, so a long session accumulates
// one unclosed handle per call. Measured retention is a few hundred KiB per
// leaked handle (it does not scale with image size).
try {
db?.close();
} catch {
// Already closed, or never successfully constructed.
}
}
}