Skip to content

Commit 13a52cf

Browse files
authored
fix: prevent Telegram migration no-op loops (#108744)
* fix(state): prevent partial legacy imports * chore: drop release-owned changelog edit * test(telegram): consolidate TTL migration coverage * style(telegram): format migration fixture
1 parent 011d027 commit 13a52cf

4 files changed

Lines changed: 124 additions & 16 deletions

File tree

‎extensions/telegram/src/sent-message-cache.ts‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ function readLegacySentMessages(filePath: string): SentMessageStore {
105105
if (
106106
typeof timestamp === "number" &&
107107
Number.isFinite(timestamp) &&
108-
now - timestamp <= TTL_MS
108+
now - timestamp < TTL_MS
109109
) {
110110
messages.set(messageId, timestamp);
111111
}
@@ -224,10 +224,17 @@ export function listTelegramLegacySentMessageCacheEntries(params: {
224224
? readLegacySentMessages(filePath)
225225
: createSentMessageStore();
226226
return [...legacy.entries()].flatMap(([chatId, messages]) =>
227-
[...messages.entries()].map(([messageId, timestamp]) => ({
228-
key: sentMessageEntryKey(scopeKey, chatId, messageId),
229-
value: { scopeKey, chatId, messageId, timestamp },
230-
ttlMs: Math.max(1, TTL_MS - Math.max(0, Date.now() - timestamp)),
231-
})),
227+
[...messages.entries()].flatMap(([messageId, timestamp]) => {
228+
const ttlMs = TTL_MS - Math.max(0, Date.now() - timestamp);
229+
return ttlMs > 0
230+
? [
231+
{
232+
key: sentMessageEntryKey(scopeKey, chatId, messageId),
233+
value: { scopeKey, chatId, messageId, timestamp },
234+
ttlMs,
235+
},
236+
]
237+
: [];
238+
}),
232239
);
233240
}

‎extensions/telegram/src/state-migrations.test.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import {
1010
resetPluginStateStoreForTests,
1111
} from "openclaw/plugin-sdk/plugin-state-test-runtime";
1212
import { resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime";
13-
import { afterEach, describe, expect, it } from "vitest";
13+
import { afterEach, describe, expect, it, vi } from "vitest";
1414
import { resolveTelegramBotInfoCachePath } from "./bot-info-cache.js";
1515
import { resolveTelegramMessageCachePath } from "./message-cache.js";
1616
import {
@@ -478,7 +478,9 @@ describe("telegram state migrations", () => {
478478
}
479479
});
480480

481-
it("cleans up expired Telegram TTL cache sidecars with no importable entries", async () => {
481+
it("cleans up expired and boundary Telegram TTL cache sidecars", async () => {
482+
vi.useFakeTimers();
483+
vi.setSystemTime(new Date("2026-07-15T12:00:00.000Z"));
482484
const dir = await mkdtemp(path.join(os.tmpdir(), "openclaw-telegram-state-migration-"));
483485
const env = { ...process.env, OPENCLAW_STATE_DIR: dir };
484486
const storePath = resolveStorePath(undefined, { env });
@@ -488,9 +490,10 @@ describe("telegram state migrations", () => {
488490
namespace: "ops",
489491
});
490492
const expiredAt = Date.now() - 8 * 24 * 60 * 60 * 1000;
493+
const boundaryAt = Date.now() - 24 * 60 * 60 * 1000;
491494
try {
492495
await mkdir(path.dirname(sentMessagePath), { recursive: true });
493-
await writeFile(sentMessagePath, JSON.stringify({ 7: { 42: expiredAt } }));
496+
await writeFile(sentMessagePath, JSON.stringify({ 7: { 42: expiredAt, 43: boundaryAt } }));
494497
await writeFile(
495498
dispatchPath,
496499
JSON.stringify({ [JSON.stringify(["message", "7", 42])]: expiredAt }),
@@ -523,6 +526,7 @@ describe("telegram state migrations", () => {
523526
expect(await plan.readEntries()).toStrictEqual([]);
524527
}
525528
} finally {
529+
vi.useRealTimers();
526530
await rm(dir, { recursive: true, force: true });
527531
}
528532
});

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

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1740,6 +1740,103 @@ describe("doctor legacy state migrations", () => {
17401740
expect(fs.existsSync(`${sourcePath}.migrated`)).toBe(false);
17411741
});
17421742

1743+
it("skips plugin-state imports when the namespace lacks room for every missing entry", async () => {
1744+
const root = await makeTempRoot();
1745+
const sourcePath = path.join(root, "legacy-cache.json");
1746+
fs.writeFileSync(sourcePath, "legacy", "utf-8");
1747+
mockedChannelMigrationPlans.plans = [
1748+
{
1749+
kind: "plugin-state-import",
1750+
label: "Test namespace-capped cache",
1751+
sourcePath,
1752+
targetPath: "plugin state:test.namespace-capped-cache",
1753+
pluginId: "telegram",
1754+
namespace: "test.namespace-capped-cache",
1755+
maxEntries: 2,
1756+
scopeKey: "",
1757+
cleanupSource: "rename",
1758+
readEntries: () => [
1759+
{ key: "legacy-first", value: { body: "first" } },
1760+
{ key: "legacy-second", value: { body: "second" } },
1761+
],
1762+
},
1763+
];
1764+
1765+
await withStateDir(root, async () => {
1766+
const store = createPluginStateKeyedStore<{ body: string }>("telegram", {
1767+
namespace: "test.namespace-capped-cache",
1768+
maxEntries: 2,
1769+
});
1770+
await store.register("current", { body: "current" });
1771+
});
1772+
resetPluginStateStoreForTests();
1773+
1774+
const detected = await detectLegacyStateMigrations({
1775+
cfg: {},
1776+
env: { OPENCLAW_STATE_DIR: root } as NodeJS.ProcessEnv,
1777+
});
1778+
const result = await runLegacyStateMigrations({ detected });
1779+
1780+
expect(result.changes).toStrictEqual([]);
1781+
expect(result.warnings).toStrictEqual([
1782+
"Skipped migrating Test namespace-capped cache because plugin state namespace test.namespace-capped-cache has room for 1 of 2 missing entries; left legacy source in place",
1783+
]);
1784+
expect(fs.existsSync(sourcePath)).toBe(true);
1785+
expect(fs.existsSync(`${sourcePath}.migrated`)).toBe(false);
1786+
1787+
await withStateDir(root, async () => {
1788+
const store = createPluginStateKeyedStore<{ body: string }>("telegram", {
1789+
namespace: "test.namespace-capped-cache",
1790+
maxEntries: 2,
1791+
});
1792+
expect(await store.lookup("current")).toStrictEqual({ body: "current" });
1793+
expect(await store.lookup("legacy-first")).toBeUndefined();
1794+
expect(await store.lookup("legacy-second")).toBeUndefined();
1795+
});
1796+
});
1797+
1798+
it("archives fully covered plugin-state imports when the namespace is full", async () => {
1799+
const root = await makeTempRoot();
1800+
const sourcePath = path.join(root, "legacy-cache.json");
1801+
fs.writeFileSync(sourcePath, "legacy", "utf-8");
1802+
mockedChannelMigrationPlans.plans = [
1803+
{
1804+
kind: "plugin-state-import",
1805+
label: "Test covered cache",
1806+
sourcePath,
1807+
targetPath: "plugin state:test.covered-cache",
1808+
pluginId: "telegram",
1809+
namespace: "test.covered-cache",
1810+
maxEntries: 1,
1811+
scopeKey: "",
1812+
cleanupSource: "rename",
1813+
readEntries: () => [{ key: "covered", value: { body: "legacy" } }],
1814+
},
1815+
];
1816+
1817+
await withStateDir(root, async () => {
1818+
const store = createPluginStateKeyedStore<{ body: string }>("telegram", {
1819+
namespace: "test.covered-cache",
1820+
maxEntries: 1,
1821+
});
1822+
await store.register("covered", { body: "current" });
1823+
});
1824+
resetPluginStateStoreForTests();
1825+
1826+
const detected = await detectLegacyStateMigrations({
1827+
cfg: {},
1828+
env: { OPENCLAW_STATE_DIR: root } as NodeJS.ProcessEnv,
1829+
});
1830+
const result = await runLegacyStateMigrations({ detected });
1831+
1832+
expect(result.warnings).toStrictEqual([]);
1833+
expect(result.changes).toContain(
1834+
`Archived Test covered cache legacy source → ${sourcePath}.migrated`,
1835+
);
1836+
expect(fs.existsSync(sourcePath)).toBe(false);
1837+
expect(fs.existsSync(`${sourcePath}.migrated`)).toBe(true);
1838+
});
1839+
17431840
it("keeps plugin-state import source when plugin cap eviction drops an imported row", async () => {
17441841
const root = await makeTempRoot();
17451842
const maxPluginStateEntries = 40;

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

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -289,7 +289,7 @@ export async function runLegacyMigrationPlans(
289289
const existingKeys = new Set(storeEntries.map(({ key }) => key));
290290
const existingValuesByKey = new Map(storeEntries.map(({ key, value }) => [key, value]));
291291
const expectedKeys = new Set(existingKeys);
292-
let remainingCapacity = Math.max(0, plan.maxEntries - storeEntries.length);
292+
const namespaceRemainingCapacity = Math.max(0, plan.maxEntries - storeEntries.length);
293293
let entries: Awaited<ReturnType<typeof plan.readEntries>>;
294294
try {
295295
entries = await plan.readEntries();
@@ -325,6 +325,12 @@ export async function runLegacyMigrationPlans(
325325
candidateEntries.push({ ...entry, targetKey, existedBefore: false });
326326
missingEntryCount++;
327327
}
328+
if (missingEntryCount > namespaceRemainingCapacity) {
329+
warnings.push(
330+
`Skipped migrating ${plan.label} because plugin state namespace ${plan.namespace} has room for ${namespaceRemainingCapacity} of ${missingEntryCount} missing entries; left legacy source in place`,
331+
);
332+
return;
333+
}
328334
const pluginRemainingCapacity = Math.max(
329335
0,
330336
MAX_PLUGIN_STATE_ENTRIES_PER_PLUGIN - pluginEntryCount,
@@ -338,9 +344,6 @@ export async function runLegacyMigrationPlans(
338344
let imported = 0;
339345
const changedKeys: string[] = [];
340346
for (const entry of candidateEntries) {
341-
if (!entry.existedBefore && remainingCapacity <= 0) {
342-
break;
343-
}
344347
try {
345348
await store.register(
346349
entry.targetKey,
@@ -372,9 +375,6 @@ export async function runLegacyMigrationPlans(
372375
expectedKeys.add(entry.targetKey);
373376
existingKeys.add(entry.targetKey);
374377
changedKeys.push(entry.targetKey);
375-
if (!entry.existedBefore) {
376-
remainingCapacity--;
377-
}
378378
imported++;
379379
} catch (err) {
380380
failedTargetKeys.add(entry.targetKey);

0 commit comments

Comments
 (0)