Skip to content

Commit d17027c

Browse files
authored
fix(memory): prevent cache overflow during forced reindex publication (#135373)
* fix(memory): bound shadow cache before reindex publication Apply the existing cache cap before copying memory tables into the shared agent database; failed full rebuilds must not prune the primary cache. Preserve incremental cleanup and expose per-source chunk payload bytes. Related: #135347. Thanks Alexis for reporting the 2026.8.1 database-growth and session-loss incident. No schema, retention, or config changes. * chore(memory): remove unused status adapter type import * test(memory): assert source payload sizes in integration fixtures * fix(memory): preserve sync cleanup and isolate byte diagnostics Address pre-land review: cover ordinary preflight and unresolved-target cleanup without mutating a forced rebuild cache after failure. Keep payload-byte scans on explicit diagnostics and preserve fresh status --index results. Extend real SQLite regressions for the early exits and serving-manager isolation. * style(memory): remove redundant reindex boolean conversion
1 parent 9030d86 commit d17027c

12 files changed

Lines changed: 521 additions & 310 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -754,7 +754,7 @@ extensions/memory-core/src/memory/manager-source-state.ts 2
754754
extensions/memory-core/src/memory/manager-sync-base.ts 5
755755
extensions/memory-core/src/memory/manager-vector-rebuild-state.ts 1
756756
extensions/memory-core/src/memory/manager-watch-ops.ts 4
757-
extensions/memory-core/src/memory/manager.ts 3
757+
extensions/memory-core/src/memory/manager.ts 2
758758
extensions/memory-core/src/memory/project-ranking.ts 1
759759
extensions/memory-core/src/memory/search-deadline.ts 1
760760
extensions/memory-core/src/migration/doctor-host-event-sources.ts 1

‎docs/concepts/memory-builtin.md‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,14 @@ which support selective deletion after promotion. For coverage and limits, see
117117

118118
Full reindexes build a replacement in a temporary database and publish the
119119
memory tables atomically. Concurrent searches and status reads keep using the
120-
published index; a failed rebuild leaves that index intact.
120+
published index; a failed rebuild leaves that index intact. The embedding cache
121+
is bounded before publication, not after copying excess entries into the
122+
shared database.
123+
124+
`openclaw memory status` reports stored chunk text and JSON embedding bytes
125+
for each source (`sourceCounts[].chunkBytes` in JSON). These are payload sizes,
126+
not total disk usage: embedding cache, FTS/vector tables, SQLite overhead, and
127+
WAL/free pages are excluded.
121128

122129
After an upgrade, automatic project and trigger recall may need to repair
123130
legacy provenance. That repair runs in the background. Replies continue while

‎extensions/memory-core/src/cli-status.runtime.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
resolveMemoryLightDreamingConfig,
77
resolveMemoryRemDreamingConfig,
88
} from "openclaw/plugin-sdk/memory-core-host-status";
9+
import { formatByteSize } from "openclaw/plugin-sdk/number-runtime";
910
import { asNullableRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
1011
import {
1112
formatAuditCounts,
@@ -373,7 +374,16 @@ export async function runMemoryStatus(
373374
total === null
374375
? `${entry.files}/? files · ${entry.chunks} chunks`
375376
: `${entry.files}/${total} files · ${entry.chunks} chunks`;
376-
lines.push(` ${accent(entry.source)} ${muted("·")} ${muted(counts)}`);
377+
const payload =
378+
entry.chunkBytes === undefined
379+
? ""
380+
: ` · ${formatByteSize(entry.chunkBytes, {
381+
style: "iec",
382+
maxUnit: "tera",
383+
separator: " ",
384+
fractionDigits: 1,
385+
})} text + embeddings`;
386+
lines.push(` ${accent(entry.source)} ${muted("·")} ${muted(counts + payload)}`);
377387
}
378388
}
379389
if (status.fallback) {

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -710,6 +710,7 @@ describe("memory cli", () => {
710710
makeMemoryStatus({
711711
files: 2,
712712
chunks: 5,
713+
sourceCounts: [{ source: "memory", files: 2, chunks: 5, chunkBytes: 2048 }],
713714
cache: { enabled: true, entries: 123, maxEntries: 50000 },
714715
fts: { enabled: true, available: true },
715716
vector: {
@@ -735,6 +736,7 @@ describe("memory cli", () => {
735736
expectLogged(log, "Vector dims: 1024");
736737
expectLogged(log, "Vector path: /opt/sqlite-vec.dylib");
737738
expectLogged(log, "FTS: ready");
739+
expectLogged(log, "2.0 KiB text + embeddings");
738740
expectLogged(log, "Embedding cache: enabled (123 entries)");
739741
expect(close).toHaveBeenCalled();
740742
});

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2300,6 +2300,38 @@ describe("memory index", () => {
23002300
}
23012301
});
23022302

2303+
it("refreshes diagnostic byte totals after indexing without changing the serving manager", async () => {
2304+
const cfg = createCfg({ provider: "none" });
2305+
const serving = await getPersistentManager(cfg);
2306+
await serving.sync({ reason: "test", force: true });
2307+
const diagnostic = await getFreshManager(cfg, "cli", true);
2308+
try {
2309+
expect(diagnostic).not.toBe(serving);
2310+
const previousBytes = diagnostic.status().sourceCounts?.[0]?.chunkBytes;
2311+
expect(previousBytes).toBeGreaterThan(0);
2312+
await fs.writeFile(
2313+
path.join(fixture.paths.memory, "2026-01-12.md"),
2314+
"# Reindexed diagnostic\n\nFresh expedition notes 🦞 with a different stored payload size.\n",
2315+
);
2316+
2317+
await diagnostic.sync({ reason: "cli", force: true });
2318+
2319+
const db = Reflect.get(diagnostic, "db") as DatabaseSync;
2320+
const storedBytes = db
2321+
.prepare(
2322+
"SELECT SUM(length(CAST(text AS BLOB)) + length(CAST(embedding AS BLOB))) AS bytes FROM memory_index_chunks WHERE source = 'memory'",
2323+
)
2324+
.get()?.bytes;
2325+
const refreshedBytes = diagnostic.status().sourceCounts?.[0]?.chunkBytes;
2326+
expect(refreshedBytes).toBe(storedBytes);
2327+
expect(refreshedBytes).not.toBe(previousBytes);
2328+
} finally {
2329+
await diagnostic.close();
2330+
}
2331+
expect((await getMemorySearchManager({ cfg, agentId: "main" })).manager).toBe(serving);
2332+
expect(serving.status().sourceCounts?.[0]?.chunkBytes).toBeUndefined();
2333+
});
2334+
23032335
it("reports vector availability after probe", async () => {
23042336
const cfg = createCfg({ vectorEnabled: true });
23052337
const manager = await getPersistentManager(cfg);

‎extensions/memory-core/src/memory/manager-status-state.test.ts‎

Lines changed: 87 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Memory Core tests cover manager status state plugin behavior.
2-
import type { SQLInputValue } from "node:sqlite";
2+
import { DatabaseSync } from "node:sqlite";
33
import { describe, expect, it } from "vitest";
44
import {
55
collectMemoryStatusAggregate,
@@ -74,37 +74,92 @@ describe("memory manager status state", () => {
7474
expect(resolveStatusProviderInfo(params)).toEqual(expected);
7575
});
7676

77-
it("uses one aggregation query for status counts and source breakdowns", () => {
78-
const calls: Array<{ sql: string; params: SQLInputValue[] }> = [];
79-
const aggregate = collectMemoryStatusAggregate({
80-
db: {
81-
prepare: (sql) => ({
82-
all: (...params) => {
83-
calls.push({ sql, params });
84-
return [
85-
{ kind: "files" as const, source: "memory" as const, c: 2 },
86-
{ kind: "chunks" as const, source: "memory" as const, c: 5 },
87-
{ kind: "files" as const, source: "sessions" as const, c: 1 },
88-
{ kind: "chunks" as const, source: "sessions" as const, c: 3 },
89-
];
90-
},
91-
}),
92-
},
93-
sources: ["memory", "sessions"],
94-
sourceFilterSql: " AND source IN (?, ?)",
95-
sourceFilterParams: ["memory", "sessions"],
96-
});
77+
it("counts ordinary status without evaluating stored payload columns", () => {
78+
const db = new DatabaseSync(":memory:");
79+
let payloadReads = 0;
80+
try {
81+
db.function("read_payload", { deterministic: true }, (source) => {
82+
payloadReads += 1;
83+
return `${String(source)} payload`;
84+
});
85+
db.exec(`
86+
CREATE TABLE memory_index_sources (source TEXT);
87+
CREATE TABLE memory_index_chunks (
88+
source TEXT,
89+
text TEXT GENERATED ALWAYS AS (read_payload(source)) VIRTUAL,
90+
embedding TEXT GENERATED ALWAYS AS (read_payload(source)) VIRTUAL
91+
);
92+
CREATE INDEX sources_by_source ON memory_index_sources(source);
93+
CREATE INDEX chunks_by_source ON memory_index_chunks(source);
94+
INSERT INTO memory_index_sources VALUES ('memory'), ('sessions');
95+
INSERT INTO memory_index_chunks(source) VALUES ('memory'), ('sessions');
96+
`);
97+
payloadReads = 0;
9798

98-
expect(calls).toHaveLength(1);
99-
expect(calls[0]?.sql).toContain("source IN (?, ?)");
100-
expect(calls[0]?.params).toEqual(["memory", "sessions", "memory", "sessions"]);
101-
expect(aggregate).toEqual({
102-
files: 3,
103-
chunks: 8,
104-
sourceCounts: [
105-
{ source: "memory", files: 2, chunks: 5 },
106-
{ source: "sessions", files: 1, chunks: 3 },
107-
],
108-
});
99+
const status = collectMemoryStatusAggregate({ db, sources: ["memory", "sessions"] });
100+
101+
expect(payloadReads).toBe(0);
102+
expect(status).toEqual({
103+
files: 2,
104+
chunks: 2,
105+
sourceCounts: [
106+
{ source: "memory", files: 1, chunks: 1 },
107+
{ source: "sessions", files: 1, chunks: 1 },
108+
],
109+
});
110+
} finally {
111+
db.close();
112+
}
113+
});
114+
115+
it("reports stored payload bytes by source without counting characters or other sources", () => {
116+
const db = new DatabaseSync(":memory:");
117+
try {
118+
db.exec(`
119+
CREATE TABLE memory_index_sources (source TEXT);
120+
CREATE TABLE memory_index_chunks (source TEXT, text TEXT, embedding TEXT);
121+
INSERT INTO memory_index_sources VALUES ('memory'), ('memory'), ('sessions');
122+
INSERT INTO memory_index_chunks VALUES
123+
('memory', '🦞', '[1,2]'), ('memory', 'abc', '[]'),
124+
('sessions', 'session', '[3]');
125+
`);
126+
expect(
127+
collectMemoryStatusAggregate({
128+
db,
129+
includeChunkBytes: true,
130+
sources: ["memory", "sessions"],
131+
}),
132+
).toEqual({
133+
files: 3,
134+
chunks: 3,
135+
sourceCounts: [
136+
{ source: "memory", files: 2, chunks: 2, chunkBytes: 14 },
137+
{ source: "sessions", files: 1, chunks: 1, chunkBytes: 10 },
138+
],
139+
});
140+
expect(
141+
collectMemoryStatusAggregate({
142+
db,
143+
includeChunkBytes: true,
144+
sources: ["memory"],
145+
sourceFilterSql: " AND source IN (?)",
146+
sourceFilterParams: ["memory"],
147+
}),
148+
).toEqual({
149+
files: 2,
150+
chunks: 2,
151+
sourceCounts: [{ source: "memory", files: 2, chunks: 2, chunkBytes: 14 }],
152+
});
153+
db.exec("DELETE FROM memory_index_sources; DELETE FROM memory_index_chunks;");
154+
expect(
155+
collectMemoryStatusAggregate({ db, sources: ["memory"], includeChunkBytes: true }),
156+
).toEqual({
157+
files: 0,
158+
chunks: 0,
159+
sourceCounts: [{ source: "memory", files: 0, chunks: 0, chunkBytes: 0 }],
160+
});
161+
} finally {
162+
db.close();
163+
}
109164
});
110165
});

‎extensions/memory-core/src/memory/manager-status-state.ts‎

Lines changed: 31 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Memory Core plugin module implements manager status state behavior.
2-
import type { SQLInputValue } from "node:sqlite";
2+
import type { DatabaseSync } from "node:sqlite";
33
import type { MemorySource } from "openclaw/plugin-sdk/memory-core-host-engine-storage";
44

55
type StatusProvider = {
@@ -11,19 +11,9 @@ type StatusAggregateRow = {
1111
kind: "files" | "chunks";
1212
source: MemorySource;
1313
c: number;
14+
bytes: number | null;
1415
};
1516

16-
type StatusAggregateDb = {
17-
prepare: (sql: string) => {
18-
all: (...args: SQLInputValue[]) => StatusAggregateRow[];
19-
};
20-
};
21-
22-
const MEMORY_STATUS_AGGREGATE_SQL =
23-
`SELECT 'files' AS kind, source, COUNT(*) as c FROM memory_index_sources WHERE 1=1__FILTER__ GROUP BY source\n` +
24-
`UNION ALL\n` +
25-
`SELECT 'chunks' AS kind, source, COUNT(*) as c FROM memory_index_chunks WHERE 1=1__FILTER__ GROUP BY source`;
26-
2717
export function resolveInitialMemoryDirty(params: {
2818
hasMemorySource: boolean;
2919
statusOnly: boolean;
@@ -68,42 +58,46 @@ export function resolveStatusProviderInfo(params: {
6858
}
6959

7060
export function collectMemoryStatusAggregate(params: {
71-
db: StatusAggregateDb;
61+
db: Pick<DatabaseSync, "prepare">;
7262
sources: Iterable<MemorySource>;
7363
sourceFilterSql?: string;
7464
sourceFilterParams?: MemorySource[];
65+
includeChunkBytes?: boolean;
7566
}): {
7667
files: number;
7768
chunks: number;
78-
sourceCounts: Array<{ source: MemorySource; files: number; chunks: number }>;
69+
sourceCounts: Array<{ source: MemorySource; files: number; chunks: number; chunkBytes?: number }>;
7970
} {
80-
const sources = Array.from(params.sources);
81-
const bySource = new Map<MemorySource, { files: number; chunks: number }>();
82-
for (const source of sources) {
83-
bySource.set(source, { files: 0, chunks: 0 });
84-
}
71+
const totals = { files: 0, chunks: 0 };
72+
const emptyCounts = { ...totals, ...(params.includeChunkBytes ? { chunkBytes: 0 } : {}) };
73+
const bySource = new Map<MemorySource, typeof emptyCounts>();
74+
// Ordinary status uses covering indexes; payload-byte inspection is diagnostic.
75+
const chunkBytes = params.includeChunkBytes
76+
? "COALESCE(SUM(octet_length(text) + octet_length(embedding)), 0)"
77+
: "NULL";
8578
const sourceFilterSql = params.sourceFilterSql ?? "";
86-
const sourceFilterParams = params.sourceFilterParams ?? [];
87-
const aggregateRows = params.db
88-
.prepare(MEMORY_STATUS_AGGREGATE_SQL.replaceAll("__FILTER__", sourceFilterSql))
89-
.all(...sourceFilterParams, ...sourceFilterParams);
90-
let files = 0;
91-
let chunks = 0;
92-
for (const row of aggregateRows) {
93-
const count = row.c ?? 0;
94-
const entry = bySource.get(row.source) ?? { files: 0, chunks: 0 };
95-
if (row.kind === "files") {
96-
entry.files = count;
97-
files += count;
98-
} else {
99-
entry.chunks = count;
100-
chunks += count;
79+
const query =
80+
`SELECT 'files' AS kind, source, COUNT(*) as c, 0 AS bytes FROM memory_index_sources WHERE 1=1${sourceFilterSql} GROUP BY source\n` +
81+
`UNION ALL\n` +
82+
`SELECT 'chunks' AS kind, source, COUNT(*) as c, ${chunkBytes} AS bytes FROM memory_index_chunks WHERE 1=1${sourceFilterSql} GROUP BY source`;
83+
const filterParams = params.sourceFilterParams ?? [];
84+
const rows = params.db
85+
.prepare(query)
86+
// SAFETY: Both UNION branches return the declared kind/source, count, and nullable byte total.
87+
.all(...filterParams, ...filterParams) as StatusAggregateRow[];
88+
for (const row of rows) {
89+
const entry = bySource.get(row.source) ?? { ...emptyCounts };
90+
entry[row.kind] = row.c;
91+
totals[row.kind] += row.c;
92+
if (row.kind === "chunks" && row.bytes !== null) {
93+
entry.chunkBytes = row.bytes;
10194
}
10295
bySource.set(row.source, entry);
10396
}
10497
return {
105-
files,
106-
chunks,
107-
sourceCounts: sources.map((source) => Object.assign({ source }, bySource.get(source)!)),
98+
...totals,
99+
sourceCounts: Array.from(params.sources, (source) =>
100+
Object.assign({ source, ...emptyCounts }, bySource.get(source)),
101+
),
108102
};
109103
}

‎extensions/memory-core/src/memory/manager-sync-ops.startup-catchup.test.ts‎

Lines changed: 1 addition & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -482,29 +482,14 @@ describe("session startup catch-up", () => {
482482
];
483483

484484
it.each(cacheBoundSyncs)("bounds the embedding cache on a %s sync", async (_label, params) => {
485-
// Enforcement first lived inside runInPlaceReindex's shadow rebuild, bounding a throwaway
486-
// database and never the live one; moving it into the incremental branch then skipped the
487-
// paths that return early. Long-running databases stayed unbounded (openclaw/openclaw#114612).
488-
await writeSessionFile("thread.jsonl");
485+
await writeSqliteSession();
489486
const harness = new SessionStartupCatchupHarness([]);
490487

491488
await harness.runSyncForTest(params);
492489

493490
expect(harness.embeddingCachePrunes).toBeGreaterThan(0);
494491
});
495492

496-
it("bounds the embedding cache when the sync pass aborts", async () => {
497-
// The full-reindex branch returns before the incremental code and cannot complete against
498-
// this harness, so it stands in for every early or failed exit: enforcement inside any one
499-
// branch skips them, a finally around the pass does not.
500-
await writeSessionFile("thread.jsonl");
501-
const harness = new SessionStartupCatchupHarness([]);
502-
503-
await expect(harness.runSyncForTest({ reason: "cli", force: true })).rejects.toThrow();
504-
505-
expect(harness.embeddingCachePrunes).toBeGreaterThan(0);
506-
});
507-
508493
it("does not fall back to full session sync when identity targets normalize away", async () => {
509494
await writeSessionFile("thread.jsonl");
510495
const harness = new SessionStartupCatchupHarness([]);

0 commit comments

Comments
 (0)