Skip to content

Commit 27cb5d0

Browse files
steipeteampagent
andauthored
perf(doctor): snapshot SQLite migration validation (#125361)
* perf(doctor): snapshot SQLite migration validation Amp-Thread-ID: https://ampcode.com/threads/T-01a00a6a-b64e-74a5-8b15-2d3b966a468d * test(doctor): bound SQLite validation reads Amp-Thread-ID: https://ampcode.com/threads/T-01a00a6a-b64e-74a5-8b15-2d3b966a468d --------- Co-authored-by: Amp <[email protected]>
1 parent aebe360 commit 27cb5d0

3 files changed

Lines changed: 195 additions & 127 deletions

File tree

‎src/commands/doctor-session-sqlite-readers.ts‎

Lines changed: 71 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,14 @@ type ReadOnlySqliteSessionEntriesResult =
3131
| { exists: true; ok: true; summaries: ReadOnlySqliteSessionSummary[] }
3232
| { error: unknown; exists: true; ok: false };
3333

34-
type ReadOnlySqliteExactSessionEntryResult =
35-
| { entry?: ReadOnlySqliteSessionSummary; ok: true }
36-
| { error: unknown; ok: false };
34+
export type ReadOnlySqliteValidationSnapshot = {
35+
entriesBySessionKey: ReadonlyMap<string, SessionEntry>;
36+
transcriptEventCountsBySessionId: ReadonlyMap<string, number>;
37+
};
3738

38-
type ReadOnlySqliteTranscriptEventCountResult =
39-
| { events: number; exists: boolean; ok: true }
40-
| { error: unknown; exists: true; ok: false };
39+
type ReadOnlySqliteValidationSnapshotResult =
40+
| { ok: true; snapshot: ReadOnlySqliteValidationSnapshot }
41+
| { error: unknown; ok: false };
4142

4243
type ReadOnlySqliteDbStatsResult =
4344
| {
@@ -291,91 +292,67 @@ export function readSqliteEntryCount(target: SessionStoreTarget): number {
291292
return result.ok ? result.summaries.length : 0;
292293
}
293294

294-
export function readOnlySqliteExactSessionEntry(
295-
target: SessionStoreTarget,
296-
sessionKey: string,
297-
): ReadOnlySqliteExactSessionEntryResult {
298-
const result = readOnlySqliteSessionEntries(target);
299-
if (!result.ok) {
300-
return { error: result.error, ok: false };
301-
}
302-
return {
303-
entry: result.summaries.find((summary) => summary.sessionKey === sessionKey),
304-
ok: true,
305-
};
306-
}
307-
308-
export function readOnlySqliteSessionEntries(
295+
export function readOnlySqliteValidationSnapshot(
309296
target: SessionStoreTarget,
310-
): ReadOnlySqliteSessionEntriesResult {
297+
): ReadOnlySqliteValidationSnapshotResult {
311298
const sqlitePath = resolveTargetSqlitePath(target);
312299
if (!fs.existsSync(sqlitePath)) {
313-
return { exists: false, ok: true, summaries: [] };
300+
return {
301+
ok: true,
302+
snapshot: {
303+
entriesBySessionKey: new Map(),
304+
transcriptEventCountsBySessionId: new Map(),
305+
},
306+
};
314307
}
315308
let database: DatabaseSync | undefined;
316309
try {
317310
database = openNodeSqliteDatabase(sqlitePath, { readOnly: true });
318-
const nodeTable = database
311+
const summaries = readOnlySqliteSessionEntriesFromDatabase(database);
312+
const hasTranscriptEvents = database
319313
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?")
320-
.get("session_nodes");
321-
const legacyEntryTable = nodeTable
322-
? undefined
323-
: database
324-
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?")
325-
.get("session_entries");
326-
if (!nodeTable && !legacyEntryTable) {
327-
return { exists: true, ok: true, summaries: [] };
328-
}
329-
const rows = database
330-
.prepare(
331-
nodeTable
332-
? "SELECT session_key, entry_json FROM session_nodes ORDER BY session_key ASC"
333-
: "SELECT session_key, entry_json FROM session_entries ORDER BY session_key ASC",
334-
)
335-
.all() as Array<{ entry_json?: unknown; session_key?: unknown }>;
314+
.get("transcript_events");
315+
const transcriptRows = hasTranscriptEvents
316+
? (database
317+
.prepare(
318+
"SELECT session_id, COUNT(*) AS count FROM transcript_events GROUP BY session_id",
319+
)
320+
.all() as Array<{ count?: unknown; session_id?: unknown }>)
321+
: [];
336322
return {
337-
exists: true,
338323
ok: true,
339-
summaries: rows.flatMap((row) => {
340-
if (typeof row.session_key !== "string" || typeof row.entry_json !== "string") {
341-
return [];
342-
}
343-
const entry = parseSqliteSessionEntry(row.entry_json);
344-
return entry ? [{ entry, sessionKey: row.session_key }] : [];
345-
}),
324+
snapshot: {
325+
entriesBySessionKey: new Map(summaries.map(({ entry, sessionKey }) => [sessionKey, entry])),
326+
transcriptEventCountsBySessionId: new Map(
327+
transcriptRows.flatMap((row) =>
328+
typeof row.session_id === "string" && typeof row.count === "number"
329+
? [[row.session_id, row.count] as const]
330+
: [],
331+
),
332+
),
333+
},
346334
};
347335
} catch (error) {
348-
return { error, exists: true, ok: false };
336+
return { error, ok: false };
349337
} finally {
350338
database?.close();
351339
}
352340
}
353341

354-
export function readOnlySqliteTranscriptEventCount(
342+
export function readOnlySqliteSessionEntries(
355343
target: SessionStoreTarget,
356-
sessionId: string,
357-
): ReadOnlySqliteTranscriptEventCountResult {
344+
): ReadOnlySqliteSessionEntriesResult {
358345
const sqlitePath = resolveTargetSqlitePath(target);
359346
if (!fs.existsSync(sqlitePath)) {
360-
return { events: 0, exists: false, ok: true };
347+
return { exists: false, ok: true, summaries: [] };
361348
}
362349
let database: DatabaseSync | undefined;
363350
try {
364351
database = openNodeSqliteDatabase(sqlitePath, { readOnly: true });
365-
const table = database
366-
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?")
367-
.get("transcript_events");
368-
if (!table) {
369-
return { events: 0, exists: true, ok: true };
370-
}
371-
const row = database
372-
.prepare("SELECT COUNT(*) AS count FROM transcript_events WHERE session_id = ?")
373-
.get(sessionId) as { count?: unknown } | undefined;
374-
const count = row?.count;
375352
return {
376-
events: typeof count === "number" && Number.isFinite(count) ? count : 0,
377353
exists: true,
378354
ok: true,
355+
summaries: readOnlySqliteSessionEntriesFromDatabase(database),
379356
};
380357
} catch (error) {
381358
return { error, exists: true, ok: false };
@@ -384,6 +361,36 @@ export function readOnlySqliteTranscriptEventCount(
384361
}
385362
}
386363

364+
function readOnlySqliteSessionEntriesFromDatabase(
365+
database: DatabaseSync,
366+
): ReadOnlySqliteSessionSummary[] {
367+
const nodeTable = database
368+
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?")
369+
.get("session_nodes");
370+
const legacyEntryTable = nodeTable
371+
? undefined
372+
: database
373+
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?")
374+
.get("session_entries");
375+
if (!nodeTable && !legacyEntryTable) {
376+
return [];
377+
}
378+
const rows = database
379+
.prepare(
380+
nodeTable
381+
? "SELECT session_key, entry_json FROM session_nodes ORDER BY session_key ASC"
382+
: "SELECT session_key, entry_json FROM session_entries ORDER BY session_key ASC",
383+
)
384+
.all() as Array<{ entry_json?: unknown; session_key?: unknown }>;
385+
return rows.flatMap((row) => {
386+
if (typeof row.session_key !== "string" || typeof row.entry_json !== "string") {
387+
return [];
388+
}
389+
const entry = parseSqliteSessionEntry(row.entry_json);
390+
return entry ? [{ entry, sessionKey: row.session_key }] : [];
391+
});
392+
}
393+
387394
export function readOnlySqliteDbStats(target: SessionStoreTarget): ReadOnlySqliteDbStatsResult {
388395
const sqlitePath = resolveTargetSqlitePath(target);
389396
const sizeFor = (filePath: string): number => {

‎src/commands/doctor-session-sqlite.test.ts‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -727,6 +727,63 @@ describe("runDoctorSessionSqlite", () => {
727727
).toHaveLength(2);
728728
});
729729

730+
it("uses target-bounded validation reads for multi-session imports", async () => {
731+
const countTargetReads = async (sessionCount: number) => {
732+
const store = createLegacyStore();
733+
const sessions = Object.fromEntries(
734+
Array.from({ length: sessionCount }, (_, offset) => {
735+
const index = offset + 1;
736+
return [
737+
index === 1 ? "agent:main:main" : `agent:main:session-${index}`,
738+
{
739+
sessionFile: `session-${index}.jsonl`,
740+
sessionId: `session-${index}`,
741+
updatedAt: 2000 + index,
742+
},
743+
];
744+
}),
745+
);
746+
fs.writeFileSync(store.storePath, `${JSON.stringify(sessions)}\n`, { mode: 0o600 });
747+
for (let index = 2; index <= sessionCount; index += 1) {
748+
fs.writeFileSync(
749+
path.join(store.sessionDir, `session-${index}.jsonl`),
750+
`{"type":"session","sessionId":"session-${index}"}\n{"type":"event","id":"evt-${index}"}\n`,
751+
{ mode: 0o600 },
752+
);
753+
}
754+
755+
const sqlitePath = path.resolve(
756+
resolveTargetSqlitePath({ agentId: "main", storePath: store.storePath }),
757+
);
758+
const openSqlite = vi.spyOn(nodeSqlite, "openNodeSqliteDatabase");
759+
try {
760+
const report = await runDoctorSessionSqlite({
761+
env: store.env,
762+
mode: "import",
763+
store: store.storePath,
764+
});
765+
expect(report.totals).toMatchObject({
766+
importedEntries: sessionCount,
767+
importedTranscriptEvents: sessionCount * 2,
768+
issues: 0,
769+
sqliteEntries: sessionCount,
770+
});
771+
return openSqlite.mock.calls.filter(
772+
([location, options]) =>
773+
path.resolve(location) === sqlitePath && options?.readOnly === true,
774+
).length;
775+
} finally {
776+
openSqlite.mockRestore();
777+
}
778+
};
779+
780+
const singleSessionReads = await countTargetReads(1);
781+
const multiSessionReads = await countTargetReads(3);
782+
783+
expect(singleSessionReads).toBeGreaterThan(0);
784+
expect(multiSessionReads).toBe(singleSessionReads);
785+
});
786+
730787
it("archives legacy stores with valid sessions and invalid cron stubs without failing", async () => {
731788
const store = createLegacyStore();
732789
const legacyStore = JSON.parse(fs.readFileSync(store.storePath, "utf-8")) as Record<

0 commit comments

Comments
 (0)