Skip to content

Commit 21163a7

Browse files
jalehmanvincentkoc
authored andcommitted
fix(memory): make file index publication atomic
1 parent d16d246 commit 21163a7

2 files changed

Lines changed: 92 additions & 43 deletions

File tree

‎extensions/memory-core/src/memory/index.test.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -551,6 +551,52 @@ describe("memory index", () => {
551551
}
552552
});
553553

554+
it("keeps existing file index rows when chunk publication fails", async () => {
555+
const cfg = createCfg({});
556+
const manager = await getFreshManager(cfg);
557+
try {
558+
const db = Reflect.get(manager, "db") as DatabaseSync;
559+
560+
await manager.sync({ reason: "test" });
561+
562+
const initialSource = db
563+
.prepare("SELECT hash FROM memory_index_sources WHERE path LIKE ? AND source = ?")
564+
.get("%2026-01-12.md", "memory") as { hash: string } | undefined;
565+
const initialChunk = db
566+
.prepare("SELECT text FROM memory_index_chunks WHERE path LIKE ? AND source = ?")
567+
.get("%2026-01-12.md", "memory") as { text: string } | undefined;
568+
expect(initialSource?.hash).toBeTruthy();
569+
expect(initialChunk?.text).toContain("Alpha memory line.");
570+
571+
db.exec(`
572+
CREATE TRIGGER fail_chunk_publication
573+
AFTER INSERT ON memory_index_chunks
574+
BEGIN
575+
SELECT RAISE(FAIL, 'forced chunk publication failure');
576+
END;
577+
`);
578+
await fs.writeFile(path.join(memoryDir, "2026-01-12.md"), "# Log\nUpdated memory line.");
579+
Reflect.set(manager, "dirty", true);
580+
581+
await expect(manager.sync({ reason: "test" })).rejects.toThrow(
582+
"forced chunk publication failure",
583+
);
584+
585+
expect(
586+
db
587+
.prepare("SELECT hash FROM memory_index_sources WHERE path LIKE ? AND source = ?")
588+
.get("%2026-01-12.md", "memory"),
589+
).toEqual(initialSource);
590+
expect(
591+
db
592+
.prepare("SELECT text FROM memory_index_chunks WHERE path LIKE ? AND source = ?")
593+
.get("%2026-01-12.md", "memory"),
594+
).toEqual(initialChunk);
595+
} finally {
596+
await manager.close?.();
597+
}
598+
});
599+
554600
it("reindexes memory tables in place without deleting unrelated agent rows", async () => {
555601
const stateDir = path.join(workspaceDir, "managed-memory-state");
556602
vi.stubEnv("OPENCLAW_STATE_DIR", stateDir);

‎extensions/memory-core/src/memory/manager-embedding-ops.ts‎

Lines changed: 46 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
type MemorySource,
2323
} from "openclaw/plugin-sdk/memory-core-host-engine-storage";
2424
import { MAX_TIMER_TIMEOUT_MS, resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
25+
import { runSqliteImmediateTransactionSync } from "openclaw/plugin-sdk/sqlite-runtime";
2526
import {
2627
MEMORY_BATCH_FAILURE_LIMIT,
2728
recordMemoryBatchFailure,
@@ -747,53 +748,56 @@ export abstract class MemoryManagerEmbeddingOps extends MemoryManagerSyncOps {
747748
vectorReady: boolean,
748749
): void {
749750
const now = Date.now();
750-
this.clearIndexedFileData(entry.path, source);
751-
for (let i = 0; i < chunks.length; i++) {
752-
const chunk = chunks[i];
753-
const embedding = embeddings[i] ?? [];
754-
const id = hashText(
755-
`${source}:${entry.path}:${chunk.startLine}:${chunk.endLine}:${chunk.hash}:${model}`,
756-
);
757-
this.db
758-
.prepare(
759-
`INSERT INTO memory_index_chunks (id, path, source, start_line, end_line, hash, model, text, embedding, updated_at)
760-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
761-
ON CONFLICT(id) DO UPDATE SET
762-
hash=excluded.hash,
763-
model=excluded.model,
764-
text=excluded.text,
765-
embedding=excluded.embedding,
766-
updated_at=excluded.updated_at`,
767-
)
768-
.run(
769-
id,
770-
entry.path,
771-
source,
772-
chunk.startLine,
773-
chunk.endLine,
774-
chunk.hash,
775-
model,
776-
chunk.text,
777-
JSON.stringify(embedding),
778-
now,
751+
runSqliteImmediateTransactionSync(this.db, () => {
752+
this.clearIndexedFileData(entry.path, source);
753+
for (let i = 0; i < chunks.length; i++) {
754+
const chunk = chunks[i];
755+
const embedding = embeddings[i] ?? [];
756+
const id = hashText(
757+
`${source}:${entry.path}:${chunk.startLine}:${chunk.endLine}:${chunk.hash}:${model}`,
779758
);
780-
if (vectorReady && embedding.length > 0) {
781-
replaceMemoryVectorRow({
782-
db: this.db,
783-
tableName: VECTOR_TABLE,
784-
id,
785-
embedding,
786-
});
787-
}
788-
if (this.fts.enabled && this.fts.available) {
789759
this.db
790760
.prepare(
791-
`INSERT INTO ${FTS_TABLE} (text, id, path, source, model, start_line, end_line)\n` +
792-
` VALUES (?, ?, ?, ?, ?, ?, ?)`,
761+
`INSERT INTO memory_index_chunks (id, path, source, start_line, end_line, hash, model, text, embedding, updated_at)
762+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
763+
ON CONFLICT(id) DO UPDATE SET
764+
hash=excluded.hash,
765+
model=excluded.model,
766+
text=excluded.text,
767+
embedding=excluded.embedding,
768+
updated_at=excluded.updated_at`,
793769
)
794-
.run(chunk.text, id, entry.path, source, model, chunk.startLine, chunk.endLine);
770+
.run(
771+
id,
772+
entry.path,
773+
source,
774+
chunk.startLine,
775+
chunk.endLine,
776+
chunk.hash,
777+
model,
778+
chunk.text,
779+
JSON.stringify(embedding),
780+
now,
781+
);
782+
if (vectorReady && embedding.length > 0) {
783+
replaceMemoryVectorRow({
784+
db: this.db,
785+
tableName: VECTOR_TABLE,
786+
id,
787+
embedding,
788+
});
789+
}
790+
if (this.fts.enabled && this.fts.available) {
791+
this.db
792+
.prepare(
793+
`INSERT INTO ${FTS_TABLE} (text, id, path, source, model, start_line, end_line)\n` +
794+
` VALUES (?, ?, ?, ?, ?, ?, ?)`,
795+
)
796+
.run(chunk.text, id, entry.path, source, model, chunk.startLine, chunk.endLine);
797+
}
795798
}
796-
}
799+
this.upsertFileRecord(entry, source);
800+
});
797801
this.vectorDegradedWriteWarningShown = logMemoryVectorDegradedWrite({
798802
vectorEnabled: this.vector.enabled,
799803
vectorReady,
@@ -802,7 +806,6 @@ export abstract class MemoryManagerEmbeddingOps extends MemoryManagerSyncOps {
802806
loadError: this.vector.loadError,
803807
warn: (message) => log.warn(message),
804808
});
805-
this.upsertFileRecord(entry, source);
806809
}
807810

808811
private async prepareIndexEntry(

0 commit comments

Comments
 (0)