Skip to content

Commit d648aeb

Browse files
authored
perf(memory): builtin sqlite hot-path follow-ups (#53939)
* chore(perf): start builtin sqlite hotpath workstream * perf(memory): reuse sqlite statements during sync * perf(memory): snapshot file state during sync * perf(memory): consolidate status sqlite reads * docs(changelog): note builtin sqlite perf work * perf(memory): avoid session table scans on targeted sync
1 parent 23a4ae4 commit d648aeb

4 files changed

Lines changed: 255 additions & 80 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ Docs: https://docs.openclaw.ai
2222

2323
### Fixes
2424

25+
- Memory/builtin sqlite: cut redundant sync and status query churn by snapshotting file state once per source, reusing sync statements, and consolidating status aggregation reads, which reduces builtin memory overhead on sync/status/doctor-style paths. Thanks @vincentkoc.
2526
- ACP/direct chats: always deliver a terminal ACP result when final TTS does not yield audio, even if block text already streamed earlier, and skip redundant empty-text final synthesis. (#53692) Thanks @w-sss.
2627
- Doctor/image generation: seed migrated legacy Nano Banana Google provider config with the `/v1beta` API root and an empty model list so `openclaw doctor --fix` completes and the migrated native Google image path keeps hitting the correct endpoint. (#53757) Thanks @mahopan.
2728
- Security/skills: validate skill installer metadata against strict regex allowlists per package manager, sanitize skill metadata for terminal output, add URL protocol allowlisting in markdown preview and skill homepage links, warn on non-bundled skill install sources, and remove unsafe `file://` workspace links. (#53471) Thanks @BunsDev.

‎src/memory/index.test.ts‎

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -554,6 +554,7 @@ describe("memory index", () => {
554554
db: {
555555
prepare: (sql: string) => {
556556
get: (path: string, source: string) => { hash: string } | undefined;
557+
all?: (...args: unknown[]) => unknown;
557558
};
558559
};
559560
}
@@ -587,13 +588,41 @@ describe("memory index", () => {
587588
})}\n`,
588589
);
589590

591+
const originalPrepare = db.prepare.bind(db);
592+
let bulkSessionStateAllCalls = 0;
593+
let perFileSessionHashPrepareCalls = 0;
594+
db.prepare = ((sql: string) => {
595+
const statement = originalPrepare(sql);
596+
if (sql === `SELECT path, hash FROM files WHERE source = ?`) {
597+
if (!statement.all) {
598+
throw new Error("expected sqlite statement.all for bulk session state query");
599+
}
600+
const bulkAll = statement.all.bind(statement);
601+
return {
602+
...statement,
603+
all: (...args: unknown[]) => {
604+
bulkSessionStateAllCalls += 1;
605+
return bulkAll(...args);
606+
},
607+
};
608+
}
609+
if (sql === `SELECT hash FROM files WHERE path = ? AND source = ?`) {
610+
perFileSessionHashPrepareCalls += 1;
611+
}
612+
return statement;
613+
}) as typeof db.prepare;
614+
590615
await manager.sync?.({
591616
reason: "post-compaction",
592617
sessionFiles: [firstSessionPath],
593618
});
594619

620+
db.prepare = originalPrepare;
621+
595622
expect(getSessionHash("sessions/targeted-first.jsonl")).not.toBe(firstOriginalHash);
596623
expect(getSessionHash("sessions/targeted-second.jsonl")).toBe(secondOriginalHash);
624+
expect(bulkSessionStateAllCalls).toBe(0);
625+
expect(perFileSessionHashPrepareCalls).toBeGreaterThan(0);
597626
await manager.close?.();
598627
} finally {
599628
if (previousStateDir === undefined) {
@@ -990,6 +1019,121 @@ describe("memory index", () => {
9901019
await manager.close?.();
9911020
});
9921021

1022+
it("snapshots builtin file hashes with a single sqlite query per sync", async () => {
1023+
await fs.writeFile(path.join(memoryDir, "2026-01-13.md"), "beta line\n");
1024+
const cfg = createCfg({
1025+
storePath: path.join(workspaceDir, `index-prepare-reuse-${randomUUID()}.sqlite`),
1026+
onSearch: false,
1027+
});
1028+
1029+
const result = await getMemorySearchManager({ cfg, agentId: "main" });
1030+
const manager = requireManager(result);
1031+
managersForCleanup.add(manager);
1032+
1033+
const db = (
1034+
manager as unknown as {
1035+
db: {
1036+
prepare: (sql: string) => { get: (...args: unknown[]) => unknown };
1037+
};
1038+
}
1039+
).db;
1040+
const originalPrepare = db.prepare.bind(db);
1041+
let selectSourceFileStatePrepareCalls = 0;
1042+
let perFileHashPrepareCalls = 0;
1043+
db.prepare = ((sql: string) => {
1044+
if (sql === `SELECT path, hash FROM files WHERE source = ?`) {
1045+
selectSourceFileStatePrepareCalls += 1;
1046+
}
1047+
if (sql === `SELECT hash FROM files WHERE path = ? AND source = ?`) {
1048+
perFileHashPrepareCalls += 1;
1049+
}
1050+
return originalPrepare(sql);
1051+
}) as typeof db.prepare;
1052+
1053+
try {
1054+
await manager.sync({ reason: "test" });
1055+
} finally {
1056+
db.prepare = originalPrepare;
1057+
}
1058+
1059+
expect(selectSourceFileStatePrepareCalls).toBe(1);
1060+
expect(perFileHashPrepareCalls).toBe(0);
1061+
});
1062+
1063+
it("uses a single sqlite aggregation query for status counts", async () => {
1064+
const cfg = createCfg({
1065+
storePath: path.join(workspaceDir, `index-status-aggregate-${randomUUID()}.sqlite`),
1066+
sources: ["memory", "sessions"],
1067+
sessionMemory: true,
1068+
onSearch: false,
1069+
});
1070+
1071+
await fs.writeFile(path.join(memoryDir, "2026-01-13.md"), "beta line\n");
1072+
1073+
const stateDir = path.join(fixtureRoot, `state-status-${randomUUID()}`);
1074+
vi.stubEnv("OPENCLAW_STATE_DIR", stateDir);
1075+
const sessionDir = path.join(stateDir, "agents", "main", "sessions");
1076+
await fs.mkdir(sessionDir, { recursive: true });
1077+
await fs.writeFile(
1078+
path.join(sessionDir, "status.jsonl"),
1079+
JSON.stringify({
1080+
type: "message",
1081+
message: { role: "user", content: [{ type: "text", text: "session status line" }] },
1082+
}) + "\n",
1083+
);
1084+
1085+
const result = await getMemorySearchManager({ cfg, agentId: "main" });
1086+
const manager = requireManager(result);
1087+
managersForCleanup.add(manager);
1088+
await manager.sync({ reason: "test" });
1089+
1090+
const db = (
1091+
manager as unknown as {
1092+
db: {
1093+
prepare: (sql: string) => { all: (...args: unknown[]) => unknown };
1094+
};
1095+
}
1096+
).db;
1097+
const originalPrepare = db.prepare.bind(db);
1098+
let aggregatePrepareCalls = 0;
1099+
let legacyCountPrepareCalls = 0;
1100+
db.prepare = ((sql: string) => {
1101+
if (
1102+
sql.includes(`SELECT 'files' AS kind, source, COUNT(*) as c FROM files`) &&
1103+
sql.includes(`UNION ALL`)
1104+
) {
1105+
aggregatePrepareCalls += 1;
1106+
}
1107+
if (
1108+
sql === `SELECT COUNT(*) as c FROM files WHERE 1=1` ||
1109+
sql === `SELECT COUNT(*) as c FROM chunks WHERE 1=1` ||
1110+
sql === `SELECT source, COUNT(*) as c FROM files WHERE 1=1 GROUP BY source` ||
1111+
sql === `SELECT source, COUNT(*) as c FROM chunks WHERE 1=1 GROUP BY source`
1112+
) {
1113+
legacyCountPrepareCalls += 1;
1114+
}
1115+
return originalPrepare(sql);
1116+
}) as typeof db.prepare;
1117+
1118+
try {
1119+
const status = manager.status();
1120+
expect(status.files).toBeGreaterThan(0);
1121+
expect(status.chunks).toBeGreaterThan(0);
1122+
expect(
1123+
status.sourceCounts?.find((entry) => entry.source === "memory")?.files,
1124+
).toBeGreaterThan(0);
1125+
expect(
1126+
status.sourceCounts?.find((entry) => entry.source === "sessions")?.files,
1127+
).toBeGreaterThan(0);
1128+
} finally {
1129+
db.prepare = originalPrepare;
1130+
vi.unstubAllEnvs();
1131+
}
1132+
1133+
expect(aggregatePrepareCalls).toBe(1);
1134+
expect(legacyCountPrepareCalls).toBe(0);
1135+
});
1136+
9931137
it("reindexes when Gemini outputDimensionality changes", async () => {
9941138
const base = createCfg({
9951139
storePath: indexModelPath,

‎src/memory/manager-sync-ops.ts‎

Lines changed: 80 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -705,6 +705,23 @@ export abstract class MemoryManagerSyncOps {
705705
log.debug("Skipping memory file sync in FTS-only mode (no embedding provider)");
706706
return;
707707
}
708+
const selectSourceFileState = this.db.prepare(`SELECT path, hash FROM files WHERE source = ?`);
709+
const deleteFileByPathAndSource = this.db.prepare(
710+
`DELETE FROM files WHERE path = ? AND source = ?`,
711+
);
712+
const deleteChunksByPathAndSource = this.db.prepare(
713+
`DELETE FROM chunks WHERE path = ? AND source = ?`,
714+
);
715+
const deleteVectorRowsByPathAndSource =
716+
this.vector.enabled && this.vector.available
717+
? this.db.prepare(
718+
`DELETE FROM ${VECTOR_TABLE} WHERE id IN (SELECT id FROM chunks WHERE path = ? AND source = ?)`,
719+
)
720+
: null;
721+
const deleteFtsRowsByPathSourceAndModel =
722+
this.fts.enabled && this.fts.available
723+
? this.db.prepare(`DELETE FROM ${FTS_TABLE} WHERE path = ? AND source = ? AND model = ?`)
724+
: null;
708725

709726
const files = await listMemoryFiles(
710727
this.workspaceDir,
@@ -726,6 +743,11 @@ export abstract class MemoryManagerSyncOps {
726743
batch: this.batch.enabled,
727744
concurrency: this.getIndexConcurrency(),
728745
});
746+
const existingRows = selectSourceFileState.all("memory") as Array<{
747+
path: string;
748+
hash: string;
749+
}>;
750+
const existingHashes = new Map(existingRows.map((row) => [row.path, row.hash]));
729751
const activePaths = new Set(fileEntries.map((entry) => entry.path));
730752
if (params.progress) {
731753
params.progress.total += fileEntries.length;
@@ -737,10 +759,7 @@ export abstract class MemoryManagerSyncOps {
737759
}
738760

739761
const tasks = fileEntries.map((entry) => async () => {
740-
const record = this.db
741-
.prepare(`SELECT hash FROM files WHERE path = ? AND source = ?`)
742-
.get(entry.path, "memory") as { hash: string } | undefined;
743-
if (!params.needsFullReindex && record?.hash === entry.hash) {
762+
if (!params.needsFullReindex && existingHashes.get(entry.path) === entry.hash) {
744763
if (params.progress) {
745764
params.progress.completed += 1;
746765
params.progress.report({
@@ -761,27 +780,20 @@ export abstract class MemoryManagerSyncOps {
761780
});
762781
await runWithConcurrency(tasks, this.getIndexConcurrency());
763782

764-
const staleRows = this.db
765-
.prepare(`SELECT path FROM files WHERE source = ?`)
766-
.all("memory") as Array<{ path: string }>;
767-
for (const stale of staleRows) {
783+
for (const stale of existingRows) {
768784
if (activePaths.has(stale.path)) {
769785
continue;
770786
}
771-
this.db.prepare(`DELETE FROM files WHERE path = ? AND source = ?`).run(stale.path, "memory");
772-
try {
773-
this.db
774-
.prepare(
775-
`DELETE FROM ${VECTOR_TABLE} WHERE id IN (SELECT id FROM chunks WHERE path = ? AND source = ?)`,
776-
)
777-
.run(stale.path, "memory");
778-
} catch {}
779-
this.db.prepare(`DELETE FROM chunks WHERE path = ? AND source = ?`).run(stale.path, "memory");
780-
if (this.fts.enabled && this.fts.available) {
787+
deleteFileByPathAndSource.run(stale.path, "memory");
788+
if (deleteVectorRowsByPathAndSource) {
789+
try {
790+
deleteVectorRowsByPathAndSource.run(stale.path, "memory");
791+
} catch {}
792+
}
793+
deleteChunksByPathAndSource.run(stale.path, "memory");
794+
if (deleteFtsRowsByPathSourceAndModel) {
781795
try {
782-
this.db
783-
.prepare(`DELETE FROM ${FTS_TABLE} WHERE path = ? AND source = ? AND model = ?`)
784-
.run(stale.path, "memory", this.provider.model);
796+
deleteFtsRowsByPathSourceAndModel.run(stale.path, "memory", this.provider.model);
785797
} catch {}
786798
}
787799
}
@@ -797,6 +809,24 @@ export abstract class MemoryManagerSyncOps {
797809
log.debug("Skipping session file sync in FTS-only mode (no embedding provider)");
798810
return;
799811
}
812+
const selectFileHash = this.db.prepare(`SELECT hash FROM files WHERE path = ? AND source = ?`);
813+
const selectSourceFileState = this.db.prepare(`SELECT path, hash FROM files WHERE source = ?`);
814+
const deleteFileByPathAndSource = this.db.prepare(
815+
`DELETE FROM files WHERE path = ? AND source = ?`,
816+
);
817+
const deleteChunksByPathAndSource = this.db.prepare(
818+
`DELETE FROM chunks WHERE path = ? AND source = ?`,
819+
);
820+
const deleteVectorRowsByPathAndSource =
821+
this.vector.enabled && this.vector.available
822+
? this.db.prepare(
823+
`DELETE FROM ${VECTOR_TABLE} WHERE id IN (SELECT id FROM chunks WHERE path = ? AND source = ?)`,
824+
)
825+
: null;
826+
const deleteFtsRowsByPathSourceAndModel =
827+
this.fts.enabled && this.fts.available
828+
? this.db.prepare(`DELETE FROM ${FTS_TABLE} WHERE path = ? AND source = ? AND model = ?`)
829+
: null;
800830

801831
const targetSessionFiles = params.needsFullReindex
802832
? null
@@ -807,6 +837,15 @@ export abstract class MemoryManagerSyncOps {
807837
const activePaths = targetSessionFiles
808838
? null
809839
: new Set(files.map((file) => sessionPathForFile(file)));
840+
const existingRows =
841+
activePaths === null
842+
? null
843+
: (selectSourceFileState.all("sessions") as Array<{
844+
path: string;
845+
hash: string;
846+
}>);
847+
const existingHashes =
848+
existingRows === null ? null : new Map(existingRows.map((row) => [row.path, row.hash]));
810849
const indexAll =
811850
params.needsFullReindex || Boolean(targetSessionFiles) || this.sessionsDirtyFiles.size === 0;
812851
log.debug("memory sync: indexing session files", {
@@ -848,10 +887,16 @@ export abstract class MemoryManagerSyncOps {
848887
}
849888
return;
850889
}
851-
const record = this.db
852-
.prepare(`SELECT hash FROM files WHERE path = ? AND source = ?`)
853-
.get(entry.path, "sessions") as { hash: string } | undefined;
854-
if (!params.needsFullReindex && record?.hash === entry.hash) {
890+
const existingHash =
891+
existingHashes?.get(entry.path) ??
892+
(
893+
selectFileHash.get(entry.path, "sessions") as
894+
| {
895+
hash: string;
896+
}
897+
| undefined
898+
)?.hash;
899+
if (!params.needsFullReindex && existingHash === entry.hash) {
855900
if (params.progress) {
856901
params.progress.completed += 1;
857902
params.progress.report({
@@ -880,31 +925,20 @@ export abstract class MemoryManagerSyncOps {
880925
return;
881926
}
882927

883-
const staleRows = this.db
884-
.prepare(`SELECT path FROM files WHERE source = ?`)
885-
.all("sessions") as Array<{ path: string }>;
886-
for (const stale of staleRows) {
928+
for (const stale of existingRows ?? []) {
887929
if (activePaths.has(stale.path)) {
888930
continue;
889931
}
890-
this.db
891-
.prepare(`DELETE FROM files WHERE path = ? AND source = ?`)
892-
.run(stale.path, "sessions");
893-
try {
894-
this.db
895-
.prepare(
896-
`DELETE FROM ${VECTOR_TABLE} WHERE id IN (SELECT id FROM chunks WHERE path = ? AND source = ?)`,
897-
)
898-
.run(stale.path, "sessions");
899-
} catch {}
900-
this.db
901-
.prepare(`DELETE FROM chunks WHERE path = ? AND source = ?`)
902-
.run(stale.path, "sessions");
903-
if (this.fts.enabled && this.fts.available) {
932+
deleteFileByPathAndSource.run(stale.path, "sessions");
933+
if (deleteVectorRowsByPathAndSource) {
934+
try {
935+
deleteVectorRowsByPathAndSource.run(stale.path, "sessions");
936+
} catch {}
937+
}
938+
deleteChunksByPathAndSource.run(stale.path, "sessions");
939+
if (deleteFtsRowsByPathSourceAndModel) {
904940
try {
905-
this.db
906-
.prepare(`DELETE FROM ${FTS_TABLE} WHERE path = ? AND source = ? AND model = ?`)
907-
.run(stale.path, "sessions", this.provider.model);
941+
deleteFtsRowsByPathSourceAndModel.run(stale.path, "sessions", this.provider.model);
908942
} catch {}
909943
}
910944
}

0 commit comments

Comments
 (0)