Skip to content

Commit 863443f

Browse files
authored
fix(memory): recover derived sidecar conflicts (#108652)
1 parent 0f32033 commit 863443f

2 files changed

Lines changed: 104 additions & 65 deletions

File tree

‎extensions/memory-core/doctor-contract-api.test.ts‎

Lines changed: 72 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1369,7 +1369,7 @@ describe("memory-core doctor dreaming migration", () => {
13691369
await expect(fs.access(retryPath)).resolves.toBeUndefined();
13701370
});
13711371

1372-
it("leaves the legacy memory sidecar in place when metadata conflicts", async () => {
1372+
it("keeps canonical metadata and archives a conflicting derived legacy index", async () => {
13731373
const stateDir = path.join(rootDir, "state");
13741374
const legacyPath = path.join(stateDir, "memory", "main.sqlite");
13751375
const agentPath = path.join(stateDir, "agents", "main", "agent", "openclaw-agent.sqlite");
@@ -1378,17 +1378,50 @@ describe("memory-core doctor dreaming migration", () => {
13781378

13791379
const result = await legacyMemoryIndexMigration().migrateLegacyState(migrationParams());
13801380

1381-
expect(result.warnings).toEqual([
1382-
expect.stringContaining(
1383-
"Skipped Memory Core legacy memory index import for agent main because legacy rows could not be imported: Error: legacy memory meta rows conflict with canonical memory index rows",
1384-
),
1381+
expect(result.warnings).toEqual([]);
1382+
expect(result.changes).toEqual([
1383+
"Resolved Memory Core legacy memory index conflict for agent main by keeping canonical per-agent SQLite rows",
1384+
expect.stringContaining("Archived Memory Core legacy memory index sidecar"),
13851385
]);
1386-
expect(result.changes).toEqual([]);
13871386
expect(readMemoryRows(agentPath).chunks).toEqual([
13881387
{ id: "canonical-other-chunk", text: "canonical unrelated memory" },
13891388
]);
1390-
await expect(fs.access(legacyPath)).resolves.toBeUndefined();
1391-
await expect(fs.access(`${legacyPath}.migrated`)).rejects.toThrow();
1389+
await expect(fs.access(legacyPath)).rejects.toThrow();
1390+
await expect(fs.access(`${legacyPath}.migrated`)).resolves.toBeUndefined();
1391+
1392+
const secondRun = await legacyMemoryIndexMigration().migrateLegacyState(migrationParams());
1393+
expect(secondRun).toEqual({ changes: [], warnings: [] });
1394+
});
1395+
1396+
it("keeps canonical chunks and archives a conflicting derived legacy index", async () => {
1397+
const stateDir = path.join(rootDir, "state");
1398+
const legacyPath = path.join(stateDir, "memory", "main.sqlite");
1399+
const agentPath = path.join(stateDir, "agents", "main", "agent", "openclaw-agent.sqlite");
1400+
await writeLegacyMemorySidecar(legacyPath);
1401+
await createCanonicalLegacyMemoryRowsWithFts(agentPath, "remember this");
1402+
const canonicalDb = new DatabaseSync(agentPath);
1403+
try {
1404+
canonicalDb
1405+
.prepare("UPDATE memory_index_chunks SET text = ? WHERE id = ?")
1406+
.run("canonical memory remains authoritative", "chunk-1");
1407+
} finally {
1408+
canonicalDb.close();
1409+
}
1410+
1411+
const result = await legacyMemoryIndexMigration().migrateLegacyState(migrationParams());
1412+
1413+
expect(result.warnings).toEqual([]);
1414+
expect(result.changes).toEqual([
1415+
"Resolved Memory Core legacy memory index conflict for agent main by keeping canonical per-agent SQLite rows",
1416+
expect.stringContaining("Archived Memory Core legacy memory index sidecar"),
1417+
]);
1418+
expect(readMemoryRows(agentPath)).toEqual({
1419+
sources: [{ path: "MEMORY.md", source: "memory", hash: "file-hash" }],
1420+
chunks: [{ id: "chunk-1", text: "canonical memory remains authoritative" }],
1421+
cache: [],
1422+
});
1423+
await expect(fs.access(legacyPath)).rejects.toThrow();
1424+
await expect(fs.access(`${legacyPath}.migrated`)).resolves.toBeUndefined();
13921425
});
13931426

13941427
it("merges legacy sidecar rows into a non-empty canonical index when rows do not conflict", async () => {
@@ -1529,7 +1562,7 @@ describe("memory-core doctor dreaming migration", () => {
15291562
legacyDims: null,
15301563
},
15311564
])(
1532-
"leaves legacy sidecars in place when cache collision $reason",
1565+
"keeps canonical cache rows when a legacy collision has $reason",
15331566
async ({ canonicalEmbedding, canonicalDims, legacyEmbedding, legacyDims }) => {
15341567
const stateDir = path.join(rootDir, "state");
15351568
const legacyPath = path.join(stateDir, "memory", "main.sqlite");
@@ -1552,12 +1585,11 @@ describe("memory-core doctor dreaming migration", () => {
15521585

15531586
const result = await legacyMemoryIndexMigration().migrateLegacyState(migrationParams());
15541587

1555-
expect(result.warnings).toEqual([
1556-
expect.stringContaining(
1557-
"Skipped Memory Core legacy memory index import for agent main because legacy rows could not be imported: Error: legacy memory embedding_cache rows conflict with canonical memory index rows",
1558-
),
1588+
expect(result.warnings).toEqual([]);
1589+
expect(result.changes).toEqual([
1590+
"Resolved Memory Core legacy memory index conflict for agent main by keeping canonical per-agent SQLite rows",
1591+
expect.stringContaining("Archived Memory Core legacy memory index sidecar"),
15591592
]);
1560-
expect(result.changes).toEqual([]);
15611593
expect(readMemoryRows(agentPath)).toEqual({
15621594
sources: [{ path: "OTHER.md", source: "memory", hash: "canonical-other-file-hash" }],
15631595
chunks: [{ id: "canonical-other-chunk", text: "canonical unrelated memory" }],
@@ -1574,8 +1606,8 @@ describe("memory-core doctor dreaming migration", () => {
15741606
updated_at: 99,
15751607
},
15761608
]);
1577-
await expect(fs.access(legacyPath)).resolves.toBeUndefined();
1578-
await expect(fs.access(`${legacyPath}.migrated`)).rejects.toThrow();
1609+
await expect(fs.access(legacyPath)).rejects.toThrow();
1610+
await expect(fs.access(`${legacyPath}.migrated`)).resolves.toBeUndefined();
15791611
},
15801612
);
15811613

@@ -1598,7 +1630,7 @@ describe("memory-core doctor dreaming migration", () => {
15981630
await expect(fs.access(`${legacyPath}.migrated`)).rejects.toThrow();
15991631
});
16001632

1601-
it("leaves legacy vector sidecars in place when canonical vector rows conflict", async () => {
1633+
it("keeps canonical vector rows and archives a conflicting derived legacy index", async () => {
16021634
const stateDir = path.join(rootDir, "state");
16031635
const legacyPath = path.join(stateDir, "memory", "main.sqlite");
16041636
const agentPath = path.join(stateDir, "agents", "main", "agent", "openclaw-agent.sqlite");
@@ -1607,14 +1639,13 @@ describe("memory-core doctor dreaming migration", () => {
16071639

16081640
const result = await legacyMemoryIndexMigration().migrateLegacyState(migrationParams());
16091641

1610-
expect(result.warnings).toEqual([
1611-
expect.stringContaining(
1612-
"Skipped Memory Core legacy memory index import for agent main because legacy rows could not be imported: Error: legacy memory chunks_vec rows conflict with canonical memory index rows",
1613-
),
1642+
expect(result.warnings).toEqual([]);
1643+
expect(result.changes).toEqual([
1644+
"Resolved Memory Core legacy memory index conflict for agent main by keeping canonical per-agent SQLite rows",
1645+
expect.stringContaining("Archived Memory Core legacy memory index sidecar"),
16141646
]);
1615-
expect(result.changes).toEqual([]);
1616-
await expect(fs.access(legacyPath)).resolves.toBeUndefined();
1617-
await expect(fs.access(`${legacyPath}.migrated`)).rejects.toThrow();
1647+
await expect(fs.access(legacyPath)).rejects.toThrow();
1648+
await expect(fs.access(`${legacyPath}.migrated`)).resolves.toBeUndefined();
16181649
});
16191650

16201651
it("leaves legacy vector sidecars in place when vector rows have no chunk", async () => {
@@ -1632,15 +1663,15 @@ describe("memory-core doctor dreaming migration", () => {
16321663

16331664
expect(result.warnings).toEqual([
16341665
expect.stringContaining(
1635-
"Skipped Memory Core legacy memory index import for agent main because legacy rows could not be imported: Error: legacy memory chunks_vec chunk references rows conflict",
1666+
"Skipped Memory Core legacy memory index import for agent main because legacy rows could not be imported: Error: legacy memory chunks_vec rows reference missing chunks",
16361667
),
16371668
]);
16381669
expect(result.changes).toEqual([]);
16391670
await expect(fs.access(legacyPath)).resolves.toBeUndefined();
16401671
await expect(fs.access(`${legacyPath}.migrated`)).rejects.toThrow();
16411672
});
16421673

1643-
it("leaves legacy sidecars in place when canonical FTS rows conflict", async () => {
1674+
it("keeps canonical FTS rows and archives a conflicting derived legacy index", async () => {
16441675
const stateDir = path.join(rootDir, "state");
16451676
const legacyPath = path.join(stateDir, "memory", "main.sqlite");
16461677
const agentPath = path.join(stateDir, "agents", "main", "agent", "openclaw-agent.sqlite");
@@ -1649,17 +1680,18 @@ describe("memory-core doctor dreaming migration", () => {
16491680

16501681
const result = await legacyMemoryIndexMigration().migrateLegacyState(migrationParams());
16511682

1652-
expect(result.warnings).toEqual([
1653-
expect.stringContaining(
1654-
"Skipped Memory Core legacy memory index import for agent main because legacy rows could not be imported: Error: legacy memory fts rows conflict",
1655-
),
1683+
expect(result.warnings).toEqual([]);
1684+
expect(result.changes).toEqual([
1685+
"Resolved Memory Core legacy memory index conflict for agent main by keeping canonical per-agent SQLite rows",
1686+
expect.stringContaining("Archived Memory Core legacy memory index sidecar"),
16561687
]);
1657-
expect(result.changes).toEqual([]);
1658-
await expect(fs.access(legacyPath)).resolves.toBeUndefined();
1659-
await expect(fs.access(`${legacyPath}.migrated`)).rejects.toThrow();
1688+
const keywordRows = await searchMigratedKeywordRows(agentPath, "stale");
1689+
expect(keywordRows.map((row) => row.id)).toEqual(["chunk-1"]);
1690+
await expect(fs.access(legacyPath)).rejects.toThrow();
1691+
await expect(fs.access(`${legacyPath}.migrated`)).resolves.toBeUndefined();
16601692
});
16611693

1662-
it("leaves legacy vector sidecars in place when canonical metadata dimensions conflict", async () => {
1694+
it("keeps canonical vector metadata and archives a conflicting derived legacy index", async () => {
16631695
const stateDir = path.join(rootDir, "state");
16641696
const legacyPath = path.join(stateDir, "memory", "main.sqlite");
16651697
const agentPath = path.join(stateDir, "agents", "main", "agent", "openclaw-agent.sqlite");
@@ -1668,17 +1700,16 @@ describe("memory-core doctor dreaming migration", () => {
16681700

16691701
const result = await legacyMemoryIndexMigration().migrateLegacyState(migrationParams());
16701702

1671-
expect(result.warnings).toEqual([
1672-
expect.stringContaining(
1673-
"Skipped Memory Core legacy memory index import for agent main because legacy rows could not be imported: Error: legacy memory meta rows conflict with canonical memory index rows",
1674-
),
1703+
expect(result.warnings).toEqual([]);
1704+
expect(result.changes).toEqual([
1705+
"Resolved Memory Core legacy memory index conflict for agent main by keeping canonical per-agent SQLite rows",
1706+
expect.stringContaining("Archived Memory Core legacy memory index sidecar"),
16751707
]);
1676-
expect(result.changes).toEqual([]);
16771708
expect(readMemoryRows(agentPath).chunks).toEqual([
16781709
{ id: "canonical-other-chunk", text: "canonical unrelated memory" },
16791710
]);
1680-
await expect(fs.access(legacyPath)).resolves.toBeUndefined();
1681-
await expect(fs.access(`${legacyPath}.migrated`)).rejects.toThrow();
1711+
await expect(fs.access(legacyPath)).rejects.toThrow();
1712+
await expect(fs.access(`${legacyPath}.migrated`)).resolves.toBeUndefined();
16821713
});
16831714
});
16841715
/* oxlint-disable max-lines -- TODO: split this grandfathered oversized file. */

‎extensions/memory-core/doctor-contract-api.ts‎

Lines changed: 32 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ type LegacyMemorySidecarImportResult = {
106106

107107
type MemoryFtsTokenizer = "unicode61" | "trigram";
108108

109-
class LegacyMemoryRowsConflictError extends Error {
109+
class LegacyMemoryDerivedRowsConflictError extends Error {
110110
constructor(readonly tableName: string) {
111111
super(`legacy memory ${tableName} rows conflict with canonical memory index rows`);
112112
}
@@ -211,10 +211,26 @@ function formatLegacyVectorRows(count: number | undefined): string {
211211
return count === undefined ? "legacy vector rows" : `${count} vector row(s)`;
212212
}
213213

214-
function assertLegacyRowsCopied(db: DatabaseSync, query: string, tableName: string): void {
214+
function assertLegacyDerivedRowsCopied(db: DatabaseSync, query: string, tableName: string): void {
215215
const row = db.prepare(query).get() as { missing?: unknown } | undefined;
216216
if (Number(row?.missing ?? 0) > 0) {
217-
throw new LegacyMemoryRowsConflictError(tableName);
217+
throw new LegacyMemoryDerivedRowsConflictError(tableName);
218+
}
219+
}
220+
221+
function assertLegacyVectorRowsReferenceChunks(db: DatabaseSync, schema: string): void {
222+
const row = db
223+
.prepare(
224+
`SELECT COUNT(*) AS missing
225+
FROM ${schema}.${LEGACY_MEMORY_VECTOR_TABLE} AS legacy
226+
WHERE NOT EXISTS (
227+
SELECT 1 FROM main.${MEMORY_INDEX_CHUNKS_TABLE} AS chunk
228+
WHERE chunk.id = legacy.id
229+
)`,
230+
)
231+
.get() as { missing?: unknown } | undefined;
232+
if (Number(row?.missing ?? 0) > 0) {
233+
throw new Error(`legacy memory ${LEGACY_MEMORY_VECTOR_TABLE} rows reference missing chunks`);
218234
}
219235
}
220236

@@ -340,17 +356,8 @@ function copyLegacyMemoryVectorRows(db: DatabaseSync, schema: string): void {
340356
if (!tableExists(db, "main", MEMORY_INDEX_VECTOR_TABLE)) {
341357
return;
342358
}
343-
assertLegacyRowsCopied(
344-
db,
345-
`SELECT COUNT(*) AS missing
346-
FROM ${schema}.${LEGACY_MEMORY_VECTOR_TABLE} AS legacy
347-
WHERE NOT EXISTS (
348-
SELECT 1 FROM main.${MEMORY_INDEX_CHUNKS_TABLE} AS chunk
349-
WHERE chunk.id = legacy.id
350-
)`,
351-
`${LEGACY_MEMORY_VECTOR_TABLE} chunk references`,
352-
);
353-
assertLegacyRowsCopied(
359+
assertLegacyVectorRowsReferenceChunks(db, schema);
360+
assertLegacyDerivedRowsCopied(
354361
db,
355362
`SELECT COUNT(*) AS missing
356363
FROM ${schema}.${LEGACY_MEMORY_VECTOR_TABLE} AS legacy
@@ -368,7 +375,7 @@ function copyLegacyMemoryVectorRows(db: DatabaseSync, schema: string): void {
368375
WHERE canonical.id = legacy.id
369376
);
370377
`);
371-
assertLegacyRowsCopied(
378+
assertLegacyDerivedRowsCopied(
372379
db,
373380
`SELECT COUNT(*) AS missing
374381
FROM ${schema}.${LEGACY_MEMORY_VECTOR_TABLE} AS legacy
@@ -398,7 +405,7 @@ function copyLegacyMemoryFtsRows(db: DatabaseSync, schema: string): void {
398405
WHERE canonical.id = legacy.id
399406
);
400407
`);
401-
assertLegacyRowsCopied(
408+
assertLegacyDerivedRowsCopied(
402409
db,
403410
`SELECT COUNT(*) AS missing
404411
FROM ${schema}.chunks AS legacy
@@ -435,7 +442,7 @@ function copyLegacyMemoryIndexRows(
435442
SELECT id, path, source, start_line, end_line, hash, model, text, embedding, updated_at
436443
FROM ${schema}.chunks;
437444
`);
438-
assertLegacyRowsCopied(
445+
assertLegacyDerivedRowsCopied(
439446
db,
440447
`SELECT COUNT(*) AS missing
441448
FROM ${schema}.meta AS legacy
@@ -445,7 +452,7 @@ function copyLegacyMemoryIndexRows(
445452
)`,
446453
"meta",
447454
);
448-
assertLegacyRowsCopied(
455+
assertLegacyDerivedRowsCopied(
449456
db,
450457
`SELECT COUNT(*) AS missing
451458
FROM ${schema}.files AS legacy
@@ -459,7 +466,7 @@ function copyLegacyMemoryIndexRows(
459466
)`,
460467
"files",
461468
);
462-
assertLegacyRowsCopied(
469+
assertLegacyDerivedRowsCopied(
463470
db,
464471
`SELECT COUNT(*) AS missing
465472
FROM ${schema}.chunks AS legacy
@@ -500,8 +507,9 @@ function copyLegacyMemoryIndexRows(
500507
SELECT provider, model, provider_key, hash, embedding, dims, updated_at
501508
FROM ${schema}.embedding_cache;
502509
`);
503-
// Canonical derived payloads win only when both rows match their shared dimensions.
504-
assertLegacyRowsCopied(
510+
// Matching cache keys are derived rows. Validate shape before deciding whether the
511+
// entire stale sidecar should yield to the canonical index.
512+
assertLegacyDerivedRowsCopied(
505513
db,
506514
`SELECT COUNT(*) AS missing
507515
FROM ${schema}.embedding_cache AS legacy
@@ -939,9 +947,9 @@ async function migrateLegacyMemorySidecarSource(params: {
939947
requireVectorRows: vectorEnabled,
940948
});
941949
} catch (err) {
942-
if (err instanceof LegacyMemoryRowsConflictError && err.tableName === "files") {
943-
// Memory index rows are derived from canonical memory sources. Keep the
944-
// current per-agent index and let normal sync rebuild any stale entries.
950+
if (err instanceof LegacyMemoryDerivedRowsConflictError) {
951+
// Every imported table is a derived search index. A same-identity mismatch means the
952+
// current per-agent row wins; normal sync rebuilds any rows skipped with the sidecar.
945953
params.changes.push(
946954
`Resolved Memory Core legacy memory index conflict for agent ${params.source.agentId} by keeping canonical per-agent SQLite rows`,
947955
);

0 commit comments

Comments
 (0)