Skip to content

Commit 9156e19

Browse files
rm0nroeclaude
andcommitted
fix(memory): large legacy memory index stalls and restarts instead of finishing
An agent with a large pre-existing memory index could see `openclaw memory index` appear to hang and vector search never reach ready after upgrading to the canonicalized memory schema. The one-time legacy->canonical migration runs in a single transaction on every store open and verifies the copy with a full-tuple anti-join that byte-compares the text/embedding columns it just copied. On a large store that verification dominates migration time and grows super-linearly, so any interruption rolls the transaction back, leaving the legacy tables in place to restart from scratch on the next open. When the canonical table was empty before the copy, INSERT OR IGNORE from a single legacy source cannot collide, so the anti-join can only ever return zero. Verify that case with a row-count match instead, and keep the full anti-join only when the canonical table already held rows (the real conflict case). What gets migrated and conflict handling are unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
1 parent 5971319 commit 9156e19

2 files changed

Lines changed: 119 additions & 20 deletions

File tree

‎packages/memory-host-sdk/src/host/memory-schema.test.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,4 +261,49 @@ describe("memory index schema", () => {
261261
db.close();
262262
}
263263
});
264+
265+
it("keeps legacy tables when an empty-canonical copy loses rows", () => {
266+
const db = new DatabaseSync(":memory:");
267+
try {
268+
// Legacy meta without a primary key can hold two rows for one key. The
269+
// canonical meta PK collapses them, so the cheap empty-canonical row-count
270+
// check must detect the shortfall and keep the legacy tables rather than
271+
// dropping data — the same fail-closed guarantee as the full anti-join.
272+
db.exec(`
273+
CREATE TABLE meta (key TEXT, value TEXT NOT NULL);
274+
CREATE TABLE files (
275+
path TEXT PRIMARY KEY,
276+
source TEXT NOT NULL DEFAULT 'memory',
277+
hash TEXT NOT NULL,
278+
mtime INTEGER NOT NULL,
279+
size INTEGER NOT NULL
280+
);
281+
CREATE TABLE chunks (
282+
id TEXT PRIMARY KEY,
283+
path TEXT NOT NULL,
284+
source TEXT NOT NULL DEFAULT 'memory',
285+
start_line INTEGER NOT NULL,
286+
end_line INTEGER NOT NULL,
287+
hash TEXT NOT NULL,
288+
model TEXT NOT NULL,
289+
text TEXT NOT NULL,
290+
embedding TEXT NOT NULL,
291+
updated_at INTEGER NOT NULL
292+
);
293+
INSERT INTO meta VALUES ('memory_index_meta_v1', 'first');
294+
INSERT INTO meta VALUES ('memory_index_meta_v1', 'second');
295+
`);
296+
297+
expect(() =>
298+
ensureMemoryIndexSchema({
299+
db,
300+
cacheEnabled: false,
301+
ftsEnabled: false,
302+
}),
303+
).toThrow("legacy memory meta rows conflict");
304+
expect(db.prepare("SELECT COUNT(*) AS count FROM meta").get()).toEqual({ count: 2 });
305+
} finally {
306+
db.close();
307+
}
308+
});
264309
});

‎packages/memory-host-sdk/src/host/memory-schema.ts‎

Lines changed: 74 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,46 @@ function assertLegacyRowsCopied(db: DatabaseSync, query: string, tableName: stri
6767
}
6868
}
6969

70+
function canonicalTableHasRows(db: DatabaseSync, table: string): boolean {
71+
return db.prepare(`SELECT 1 FROM ${table} LIMIT 1`).get() !== undefined;
72+
}
73+
74+
function tableRowCount(db: DatabaseSync, table: string): number {
75+
const row = db.prepare(`SELECT COUNT(*) AS count FROM ${table}`).get() as
76+
| { count?: unknown }
77+
| undefined;
78+
return Number(row?.count ?? 0);
79+
}
80+
81+
// Verify a legacy table was fully copied before the caller drops it. When the
82+
// canonical table was empty before the copy, INSERT OR IGNORE from its single
83+
// legacy source cannot collide, so a row-count match proves every row landed.
84+
// Only a canonical table that already held rows can hide a key whose value
85+
// differs from legacy, so the per-row full-tuple anti-join runs only then.
86+
// Skipping it for the common (empty) case keeps large stores (90k+ chunks,
87+
// 170k+ cache rows) from spending the whole migration window comparing
88+
// text/embedding blobs row by row, timing out, and rolling the savepoint back
89+
// on every interrupt — which left the legacy tables in place and re-ran the
90+
// migration forever.
91+
function verifyLegacyRowsCopied(
92+
db: DatabaseSync,
93+
params: {
94+
canonicalPrefilled: boolean;
95+
legacyTable: string;
96+
canonicalTable: string;
97+
conflictQuery: string;
98+
label: string;
99+
},
100+
): void {
101+
if (params.canonicalPrefilled) {
102+
assertLegacyRowsCopied(db, params.conflictQuery, params.label);
103+
return;
104+
}
105+
if (tableRowCount(db, params.canonicalTable) !== tableRowCount(db, params.legacyTable)) {
106+
throw new Error(`legacy memory ${params.label} rows conflict with canonical memory index rows`);
107+
}
108+
}
109+
70110
function migrateCanonicalMemoryIndexSourcesPrimaryKey(db: DatabaseSync): void {
71111
if (
72112
!tableHasExactColumns(db, MEMORY_INDEX_SOURCES_TABLE, MEMORY_INDEX_SOURCE_COLUMNS) ||
@@ -132,6 +172,9 @@ function migrateLegacyMemoryIndexTables(
132172

133173
db.exec("SAVEPOINT migrate_legacy_memory_index_tables");
134174
try {
175+
const metaPrefilled = canonicalTableHasRows(db, MEMORY_INDEX_META_TABLE);
176+
const sourcesPrefilled = canonicalTableHasRows(db, MEMORY_INDEX_SOURCES_TABLE);
177+
const chunksPrefilled = canonicalTableHasRows(db, MEMORY_INDEX_CHUNKS_TABLE);
135178
db.exec(`
136179
INSERT OR IGNORE INTO ${MEMORY_INDEX_META_TABLE} (key, value)
137180
SELECT key, value FROM meta;
@@ -145,19 +188,24 @@ function migrateLegacyMemoryIndexTables(
145188
SELECT id, path, source, start_line, end_line, hash, model, text, embedding, updated_at
146189
FROM chunks;
147190
`);
148-
assertLegacyRowsCopied(
149-
db,
150-
`SELECT COUNT(*) AS missing
191+
verifyLegacyRowsCopied(db, {
192+
canonicalPrefilled: metaPrefilled,
193+
legacyTable: "meta",
194+
canonicalTable: MEMORY_INDEX_META_TABLE,
195+
label: "meta",
196+
conflictQuery: `SELECT COUNT(*) AS missing
151197
FROM meta AS legacy
152198
WHERE NOT EXISTS (
153199
SELECT 1 FROM ${MEMORY_INDEX_META_TABLE} AS canonical
154200
WHERE canonical.key = legacy.key AND canonical.value IS legacy.value
155201
)`,
156-
"meta",
157-
);
158-
assertLegacyRowsCopied(
159-
db,
160-
`SELECT COUNT(*) AS missing
202+
});
203+
verifyLegacyRowsCopied(db, {
204+
canonicalPrefilled: sourcesPrefilled,
205+
legacyTable: "files",
206+
canonicalTable: MEMORY_INDEX_SOURCES_TABLE,
207+
label: "files",
208+
conflictQuery: `SELECT COUNT(*) AS missing
161209
FROM files AS legacy
162210
WHERE NOT EXISTS (
163211
SELECT 1 FROM ${MEMORY_INDEX_SOURCES_TABLE} AS canonical
@@ -167,11 +215,13 @@ function migrateLegacyMemoryIndexTables(
167215
AND canonical.mtime IS legacy.mtime
168216
AND canonical.size IS legacy.size
169217
)`,
170-
"files",
171-
);
172-
assertLegacyRowsCopied(
173-
db,
174-
`SELECT COUNT(*) AS missing
218+
});
219+
verifyLegacyRowsCopied(db, {
220+
canonicalPrefilled: chunksPrefilled,
221+
legacyTable: "chunks",
222+
canonicalTable: MEMORY_INDEX_CHUNKS_TABLE,
223+
label: "chunks",
224+
conflictQuery: `SELECT COUNT(*) AS missing
175225
FROM chunks AS legacy
176226
WHERE NOT EXISTS (
177227
SELECT 1 FROM ${MEMORY_INDEX_CHUNKS_TABLE} AS canonical
@@ -186,8 +236,7 @@ function migrateLegacyMemoryIndexTables(
186236
AND canonical.embedding IS legacy.embedding
187237
AND canonical.updated_at IS legacy.updated_at
188238
)`,
189-
"chunks",
190-
);
239+
});
191240
if (
192241
preservedEmbeddingCacheTable !== "embedding_cache" &&
193242
tableHasExactColumns(db, "embedding_cache", [
@@ -211,15 +260,21 @@ function migrateLegacyMemoryIndexTables(
211260
updated_at INTEGER NOT NULL,
212261
PRIMARY KEY (provider, model, provider_key, hash)
213262
);
263+
`);
264+
const cachePrefilled = canonicalTableHasRows(db, MEMORY_EMBEDDING_CACHE_TABLE);
265+
db.exec(`
214266
INSERT OR IGNORE INTO ${MEMORY_EMBEDDING_CACHE_TABLE} (
215267
provider, model, provider_key, hash, embedding, dims, updated_at
216268
)
217269
SELECT provider, model, provider_key, hash, embedding, dims, updated_at
218270
FROM embedding_cache;
219271
`);
220-
assertLegacyRowsCopied(
221-
db,
222-
`SELECT COUNT(*) AS missing
272+
verifyLegacyRowsCopied(db, {
273+
canonicalPrefilled: cachePrefilled,
274+
legacyTable: "embedding_cache",
275+
canonicalTable: MEMORY_EMBEDDING_CACHE_TABLE,
276+
label: "embedding_cache",
277+
conflictQuery: `SELECT COUNT(*) AS missing
223278
FROM embedding_cache AS legacy
224279
WHERE NOT EXISTS (
225280
SELECT 1 FROM ${MEMORY_EMBEDDING_CACHE_TABLE} AS canonical
@@ -231,8 +286,7 @@ function migrateLegacyMemoryIndexTables(
231286
AND canonical.dims IS legacy.dims
232287
AND canonical.updated_at IS legacy.updated_at
233288
)`,
234-
"embedding_cache",
235-
);
289+
});
236290
db.exec("DROP TABLE embedding_cache");
237291
}
238292
for (const trigger of LEGACY_MEMORY_INDEX_TRIGGERS) {

0 commit comments

Comments
 (0)