Skip to content

Commit 1971dfc

Browse files
openclaw-clawsweeper[bot]claude
andcommitted
fix(plugin-state): preserve legacy created_at through a migration-only write path
Imported legacy rows previously went through the normal register path, which stamps created_at with the import time. Because cap eviction removes the smallest created_at first, older migrated rows became the newest rows in the namespace, so the next live write could evict fresher pre-existing entries before the legacy ones. Route imports (and mid-import restores) through a migration-only write that keeps the legacy timestamp, and add a regression test proving the next live write evicts the migrated row instead of the fresher existing row. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent e2f5d6c commit 1971dfc

5 files changed

Lines changed: 162 additions & 10 deletions

File tree

‎src/channels/plugins/legacy-state-migration.types.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,11 @@ export type ChannelLegacyStateMigrationPlan =
2626
existingValue: unknown;
2727
incomingValue: unknown;
2828
}) => boolean | Promise<boolean>;
29-
/** `timestamp` (epoch ms) and `ttlMs` order entries newest-first when capacity forces a partial import. */
29+
/**
30+
* `timestamp` (epoch ms) and `ttlMs` order entries newest-first when capacity forces a
31+
* partial import; `timestamp` is also persisted as the migrated row's creation time so
32+
* cap eviction keeps treating imported rows as old as their legacy source.
33+
*/
3034
readEntries: () =>
3135
| Array<{ key: string; value: unknown; ttlMs?: number; timestamp?: number }>
3236
| Promise<Array<{ key: string; value: unknown; ttlMs?: number; timestamp?: number }>>;

‎src/commands/doctor-state-migrations.test.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1797,6 +1797,61 @@ describe("doctor legacy state migrations", () => {
17971797
});
17981798
});
17991799

1800+
it("preserves legacy creation times so later live writes evict migrated rows before fresher existing rows", async () => {
1801+
const root = await makeTempRoot();
1802+
const sourcePath = path.join(root, "legacy-cache.json");
1803+
fs.writeFileSync(sourcePath, "legacy", "utf-8");
1804+
mockedChannelMigrationPlans.plans = [
1805+
{
1806+
kind: "plugin-state-import",
1807+
label: "Test recency cache",
1808+
sourcePath,
1809+
targetPath: "plugin state:test.recency-cache",
1810+
pluginId: "telegram",
1811+
namespace: "test.recency-cache",
1812+
maxEntries: 2,
1813+
scopeKey: "",
1814+
cleanupSource: "rename",
1815+
readEntries: () => [
1816+
{ key: "legacy-old", value: { body: "old" }, timestamp: 1_000 },
1817+
{ key: "legacy-new", value: { body: "new" }, timestamp: 2_000 },
1818+
],
1819+
},
1820+
];
1821+
1822+
await withStateDir(root, async () => {
1823+
const store = createPluginStateKeyedStore<{ body: string }>("telegram", {
1824+
namespace: "test.recency-cache",
1825+
maxEntries: 2,
1826+
});
1827+
await store.register("current", { body: "current" });
1828+
});
1829+
resetPluginStateStoreForTests();
1830+
1831+
const detected = await detectLegacyStateMigrations({
1832+
cfg: {},
1833+
env: { OPENCLAW_STATE_DIR: root } as NodeJS.ProcessEnv,
1834+
});
1835+
const result = await runLegacyStateMigrations({ detected });
1836+
expect(result.changes).toStrictEqual(["Migrated 1 Test recency cache entry → plugin state"]);
1837+
1838+
await withStateDir(root, async () => {
1839+
const store = createPluginStateKeyedStore<{ body: string }>("telegram", {
1840+
namespace: "test.recency-cache",
1841+
maxEntries: 2,
1842+
});
1843+
const migrated = (await store.entries()).find(({ key }) => key === "legacy-new");
1844+
expect(migrated?.createdAt).toBe(2_000);
1845+
1846+
// The next live write must evict the oldest logical entry (the migrated
1847+
// legacy row), never the fresher pre-existing row.
1848+
await store.register("after", { body: "after" });
1849+
expect(await store.lookup("current")).toStrictEqual({ body: "current" });
1850+
expect(await store.lookup("after")).toStrictEqual({ body: "after" });
1851+
expect(await store.lookup("legacy-new")).toBeUndefined();
1852+
});
1853+
});
1854+
18001855
it("imports deferred entries on a later run once the namespace frees capacity", async () => {
18011856
const root = await makeTempRoot();
18021857
const sourcePath = path.join(root, "legacy-cache.json");

‎src/infra/state-migrations.plugin-state.ts‎

Lines changed: 53 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import type { ChannelLegacyStateMigrationPlan } from "../channels/plugins/types.
44
import {
55
countPluginStateLiveEntries,
66
createPluginStateKeyedStore,
7+
registerMigratedPluginStateEntry,
78
resolveMaxPluginStateEntriesPerPlugin,
89
} from "../plugin-state/plugin-state-store.js";
910
import {
@@ -284,7 +285,7 @@ export async function runLegacyMigrationPlans(
284285
for (const plan of plans) {
285286
if (plan.kind === "plugin-state-import") {
286287
await withPluginStateImportEnv(plan, async () => {
287-
let storeEntries: Array<{ key: string; value: unknown }>;
288+
let storeEntries: Array<{ key: string; value: unknown; createdAt: number }>;
288289
let pluginEntryCount;
289290
const store = createPluginStateKeyedStore<unknown>(plan.pluginId, {
290291
namespace: plan.namespace,
@@ -302,6 +303,9 @@ export async function runLegacyMigrationPlans(
302303
}
303304
const existingKeys = new Set(storeEntries.map(({ key }) => key));
304305
const existingValuesByKey = new Map(storeEntries.map(({ key, value }) => [key, value]));
306+
const existingCreatedAtByKey = new Map(
307+
storeEntries.map(({ key, createdAt }) => [key, createdAt]),
308+
);
305309
const expectedKeys = new Set(existingKeys);
306310
const namespaceRemainingCapacity = Math.max(0, plan.maxEntries - storeEntries.length);
307311
let entries: Awaited<ReturnType<typeof plan.readEntries>>;
@@ -361,15 +365,56 @@ export async function runLegacyMigrationPlans(
361365
: `Deferring ${plan.label} migration because ${constraint} of ${missingEntryCount} missing entries; left legacy source in place to retry when capacity frees`,
362366
);
363367
}
368+
// Eviction removes the smallest created_at first, so imported rows must
369+
// keep their legacy creation time; writing them through the normal
370+
// register path would stamp them "now" and let later live writes evict
371+
// fresher pre-existing rows before the migrated ones.
372+
const registerPreservingCreatedAt = async (params: {
373+
key: string;
374+
value: unknown;
375+
ttlMs?: number;
376+
createdAtMs?: number;
377+
}) => {
378+
if (
379+
params.createdAtMs === undefined ||
380+
!Number.isFinite(params.createdAtMs) ||
381+
params.createdAtMs < 0
382+
) {
383+
await store.register(
384+
params.key,
385+
params.value,
386+
params.ttlMs != null ? { ttlMs: params.ttlMs } : undefined,
387+
);
388+
return;
389+
}
390+
registerMigratedPluginStateEntry({
391+
pluginId: plan.pluginId,
392+
namespace: plan.namespace,
393+
maxEntries: plan.maxEntries,
394+
...(plan.defaultTtlMs != null ? { defaultTtlMs: plan.defaultTtlMs } : {}),
395+
key: params.key,
396+
value: params.value,
397+
...(params.ttlMs != null ? { ttlMs: params.ttlMs } : {}),
398+
createdAtMs: params.createdAtMs,
399+
});
400+
};
401+
const restoreExistingEntry = async (key: string) => {
402+
await registerPreservingCreatedAt({
403+
key,
404+
value: existingValuesByKey.get(key),
405+
createdAtMs: existingCreatedAtByKey.get(key),
406+
});
407+
};
364408
let imported = 0;
365409
const changedKeys = new Set<string>();
366410
for (const entry of [...replacementEntries, ...newEntries]) {
367411
try {
368-
await store.register(
369-
entry.targetKey,
370-
entry.value,
371-
entry.ttlMs != null ? { ttlMs: entry.ttlMs } : undefined,
372-
);
412+
await registerPreservingCreatedAt({
413+
key: entry.targetKey,
414+
value: entry.value,
415+
...(entry.ttlMs != null ? { ttlMs: entry.ttlMs } : {}),
416+
...(entry.timestamp !== undefined ? { createdAtMs: entry.timestamp } : {}),
417+
});
373418
const nextExpectedKeys = new Set(expectedKeys);
374419
nextExpectedKeys.add(entry.targetKey);
375420
const liveKeys = new Set((await store.entries()).map(({ key }) => key));
@@ -380,7 +425,7 @@ export async function runLegacyMigrationPlans(
380425
// row when we still hold its value, and keep everything imported so far —
381426
// deferred entries stay in the legacy source for the next startup.
382427
if (existingValuesByKey.has(entry.targetKey)) {
383-
await store.register(entry.targetKey, existingValuesByKey.get(entry.targetKey));
428+
await restoreExistingEntry(entry.targetKey);
384429
} else {
385430
await store.delete(entry.targetKey);
386431
}
@@ -391,7 +436,7 @@ export async function runLegacyMigrationPlans(
391436
imported = Math.max(0, imported - 1);
392437
} else if (existingValuesByKey.has(missingKey)) {
393438
try {
394-
await store.register(missingKey, existingValuesByKey.get(missingKey));
439+
await restoreExistingEntry(missingKey);
395440
} catch (restoreErr) {
396441
warnings.push(
397442
`Failed restoring ${plan.label} entry ${missingKey} after cap eviction: ${String(restoreErr)}`,

‎src/plugin-state/plugin-state-store.sqlite.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -481,6 +481,9 @@ export function pluginStateRegister(params: {
481481
maxEntries: number;
482482
overflowPolicy: PluginStateOverflowPolicy;
483483
ttlMs?: number;
484+
// Migration-only override: eviction orders rows by created_at, so imported
485+
// legacy rows must keep their original age instead of the import time.
486+
createdAtMs?: number;
484487
env?: NodeJS.ProcessEnv;
485488
}): void {
486489
try {
@@ -522,7 +525,7 @@ export function pluginStateRegister(params: {
522525
namespace: params.namespace,
523526
key: params.key,
524527
valueJson: params.valueJson,
525-
createdAt: now,
528+
createdAt: params.createdAtMs ?? now,
526529
expiresAt,
527530
}),
528531
);

‎src/plugin-state/plugin-state-store.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,51 @@ function createSyncKeyedStoreForPluginId<T>(
399399
};
400400
}
401401

402+
/**
403+
* Migration-only write path that preserves a legacy entry's original creation
404+
* timestamp. Cap eviction removes the oldest `created_at` first, so imported
405+
* rows must keep their real age instead of being stamped with the import time
406+
* (which would let later live writes evict fresher pre-existing rows first).
407+
* Not part of the plugin-facing store API.
408+
*/
409+
export function registerMigratedPluginStateEntry(params: {
410+
pluginId: string;
411+
namespace: string;
412+
maxEntries: number;
413+
overflowPolicy?: PluginStateOverflowPolicy;
414+
defaultTtlMs?: number;
415+
key: string;
416+
value: unknown;
417+
ttlMs?: number;
418+
createdAtMs: number;
419+
env?: NodeJS.ProcessEnv;
420+
}): void {
421+
if (!Number.isFinite(params.createdAtMs) || params.createdAtMs < 0) {
422+
throw invalidInput("plugin state migration createdAtMs must be a non-negative finite number");
423+
}
424+
const namespace = validateNamespace(params.namespace, "register");
425+
const maxEntries = validateMaxEntries(params.maxEntries);
426+
const overflowPolicy = validateOverflowPolicy(params.overflowPolicy);
427+
const defaultTtlMs = validateOptionalTtlMs(params.defaultTtlMs);
428+
const prepared = prepareRegisterParams(
429+
params.key,
430+
params.value,
431+
defaultTtlMs,
432+
params.ttlMs != null ? { ttlMs: params.ttlMs } : undefined,
433+
);
434+
pluginStateRegister({
435+
pluginId: params.pluginId,
436+
namespace,
437+
key: prepared.key,
438+
valueJson: prepared.valueJson,
439+
maxEntries,
440+
overflowPolicy,
441+
createdAtMs: Math.floor(params.createdAtMs),
442+
...(params.env ? { env: params.env } : {}),
443+
...(prepared.ttlMs != null ? { ttlMs: prepared.ttlMs } : {}),
444+
});
445+
}
446+
402447
/** Opens an async plugin-state namespace for a non-core plugin id. */
403448
export function createPluginStateKeyedStore<T>(
404449
pluginId: string,

0 commit comments

Comments
 (0)