Skip to content

Commit 709855d

Browse files
committed
fix(telegram): delete retired dispatch dedupe buckets after doctor import
1 parent 272b599 commit 709855d

5 files changed

Lines changed: 123 additions & 49 deletions

File tree

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -461,6 +461,12 @@ describe("telegram state migrations", () => {
461461
[replayKey]: now,
462462
},
463463
});
464+
legacyStore.register("legacy-bucket-lock", {
465+
scopeKey: "old-session-store",
466+
namespace: "ops:lock",
467+
bucketId: "00",
468+
entries: {},
469+
});
464470

465471
const cfg = {
466472
channels: {
@@ -485,6 +491,7 @@ describe("telegram state migrations", () => {
485491
kind: "plugin-state-import",
486492
pluginId: TELEGRAM_MESSAGE_DISPATCH_DEDUPE_STATE_PLUGIN_ID,
487493
namespace: dispatchNamespace,
494+
cleanupWhenEmpty: true,
488495
});
489496
if (!plan || plan.kind !== "plugin-state-import") {
490497
throw new Error("expected Telegram message dispatch plugin-state import plan");
@@ -520,13 +527,27 @@ describe("telegram state migrations", () => {
520527
);
521528
}
522529

530+
// The plan stays detectable while legacy bucket rows remain so doctor --fix
531+
// can finish by deleting the retired source namespace.
523532
const plansAfterImport = await detectTelegramLegacyStateMigrations({ cfg, env });
524533
expect(
525534
plansAfterImport.some(
526535
(candidate) =>
527536
candidate.kind === "plugin-state-import" &&
528537
candidate.sourcePath === "plugin state:telegram.message-dispatch-dedupe:ops",
529538
),
539+
).toBe(true);
540+
541+
await plan.removeSource?.();
542+
expect(legacyStore.entries()).toHaveLength(0);
543+
544+
const plansAfterCleanup = await detectTelegramLegacyStateMigrations({ cfg, env });
545+
expect(
546+
plansAfterCleanup.some(
547+
(candidate) =>
548+
candidate.kind === "plugin-state-import" &&
549+
candidate.sourcePath === "plugin state:telegram.message-dispatch-dedupe:ops",
550+
),
530551
).toBe(false);
531552
} finally {
532553
await rm(dir, { recursive: true, force: true });

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

Lines changed: 43 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import type { ChannelLegacyStateMigrationPlan } from "openclaw/plugin-sdk/channe
55
import { resolveChannelAllowFromPath } from "openclaw/plugin-sdk/channel-pairing";
66
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
77
import {
8-
type PersistentDedupeEntry,
98
type PersistentDedupeLegacyJsonImportEntry,
109
createPersistentDedupeImportEntry,
1110
listPersistentDedupeLegacyJsonFileEntries,
@@ -130,28 +129,45 @@ function remainingMessageDispatchDedupeTtlMs(seenAt: number, now: number): numbe
130129
return ttlMs > 0 ? ttlMs : undefined;
131130
}
132131

133-
function listTelegramLegacyMessageDispatchPluginStateEntries(params: {
134-
accountId: string;
135-
env: NodeJS.ProcessEnv;
136-
now?: number;
137-
}): PersistentDedupeLegacyJsonImportEntry[] {
138-
const store = createPluginStateSyncKeyedStore<unknown>("telegram", {
132+
function openTelegramLegacyMessageDispatchBucketStore(env: NodeJS.ProcessEnv) {
133+
return createPluginStateSyncKeyedStore<unknown>("telegram", {
139134
namespace: TELEGRAM_MESSAGE_DISPATCH_LEGACY_BUCKET_NAMESPACE,
140135
maxEntries: TELEGRAM_MESSAGE_DISPATCH_LEGACY_BUCKET_MAX_ENTRIES,
141-
env: params.env,
136+
env,
142137
});
138+
}
139+
140+
function readTelegramLegacyMessageDispatchBuckets(params: {
141+
accountId: string;
142+
env: NodeJS.ProcessEnv;
143+
now?: number;
144+
}): { importEntries: PersistentDedupeLegacyJsonImportEntry[]; recordKeys: string[] } {
145+
const store = openTelegramLegacyMessageDispatchBucketStore(params.env);
143146
const latestSeenAtByKey = new Map<string, number>();
147+
const recordKeys: string[] = [];
144148
for (const entry of store.entries()) {
145149
const record = readLegacyMessageDispatchDedupeRecord(entry.value);
146-
if (!record || record.namespace !== params.accountId) {
150+
if (!record) {
151+
continue;
152+
}
153+
// Lock rows persist as `<accountId>:lock` buckets without dedupe entries;
154+
// track them as removable so cleanup empties the retired namespace.
155+
const ownsRecord =
156+
record.namespace === params.accountId ||
157+
record.namespace.startsWith(`${params.accountId}:`);
158+
if (!ownsRecord) {
159+
continue;
160+
}
161+
recordKeys.push(entry.key);
162+
if (record.namespace !== params.accountId) {
147163
continue;
148164
}
149165
for (const [key, seenAt] of Object.entries(record.entries)) {
150166
latestSeenAtByKey.set(key, Math.max(latestSeenAtByKey.get(key) ?? 0, seenAt));
151167
}
152168
}
153169
const now = params.now ?? Date.now();
154-
return [...latestSeenAtByKey.entries()].flatMap(([key, seenAt]) => {
170+
const importEntries = [...latestSeenAtByKey.entries()].flatMap(([key, seenAt]) => {
155171
const ttlMs = remainingMessageDispatchDedupeTtlMs(seenAt, now);
156172
return ttlMs == null
157173
? []
@@ -166,33 +182,17 @@ function listTelegramLegacyMessageDispatchPluginStateEntries(params: {
166182
}),
167183
];
168184
});
185+
return { importEntries, recordKeys };
169186
}
170187

171-
function hasCurrentMessageDispatchDedupeTargets(params: {
172-
namespace: string;
173-
entries: PersistentDedupeLegacyJsonImportEntry[];
188+
function removeTelegramLegacyMessageDispatchBuckets(params: {
189+
accountId: string;
174190
env: NodeJS.ProcessEnv;
175-
}): boolean {
176-
const store = createPluginStateSyncKeyedStore<PersistentDedupeEntry>(
177-
TELEGRAM_MESSAGE_DISPATCH_DEDUPE_STATE_PLUGIN_ID,
178-
{
179-
namespace: params.namespace,
180-
maxEntries: TELEGRAM_MESSAGE_DISPATCH_DEDUPE_STATE_MAX_ENTRIES,
181-
defaultTtlMs: TELEGRAM_MESSAGE_DISPATCH_DEDUPE_TTL_MS,
182-
env: params.env,
183-
},
184-
);
185-
const existingByKey = new Map(store.entries().map((entry) => [entry.key, entry.value]));
186-
return params.entries.every((entry) => {
187-
const existingValue = existingByKey.get(entry.key);
188-
return (
189-
existingValue != null &&
190-
!shouldReplacePersistentDedupeEntry({
191-
existingValue,
192-
incomingValue: entry.value,
193-
})
194-
);
195-
});
191+
}): void {
192+
const store = openTelegramLegacyMessageDispatchBucketStore(params.env);
193+
for (const key of readTelegramLegacyMessageDispatchBuckets(params).recordKeys) {
194+
store.delete(key);
195+
}
196196
}
197197

198198
function mapTelegramMessageDispatchDedupeImportEntries(params: {
@@ -491,19 +491,15 @@ function detectTelegramMessageDispatchLegacyStateMigration(params: {
491491
}),
492492
};
493493
});
494-
let pluginStateEntries: PersistentDedupeLegacyJsonImportEntry[];
494+
let legacyRecordKeys: string[];
495495
try {
496-
pluginStateEntries = listTelegramLegacyMessageDispatchPluginStateEntries({
497-
accountId,
498-
env,
499-
});
496+
legacyRecordKeys = readTelegramLegacyMessageDispatchBuckets({ accountId, env }).recordKeys;
500497
} catch {
501-
pluginStateEntries = [];
498+
legacyRecordKeys = [];
502499
}
503-
if (
504-
pluginStateEntries.length === 0 ||
505-
hasCurrentMessageDispatchDedupeTargets({ namespace, entries: pluginStateEntries, env })
506-
) {
500+
// Emit the plan while any retired bucket rows remain (even TTL-expired ones)
501+
// so doctor --fix imports live entries and then deletes the legacy source.
502+
if (legacyRecordKeys.length === 0) {
507503
return jsonPlans;
508504
}
509505
const pluginStatePlan: ChannelLegacyStateMigrationPlan = {
@@ -516,14 +512,12 @@ function detectTelegramMessageDispatchLegacyStateMigration(params: {
516512
maxEntries: TELEGRAM_MESSAGE_DISPATCH_DEDUPE_STATE_MAX_ENTRIES,
517513
defaultTtlMs: TELEGRAM_MESSAGE_DISPATCH_DEDUPE_TTL_MS,
518514
scopeKey: "",
515+
cleanupWhenEmpty: true,
519516
preview: `- Telegram message dispatch dedupe: plugin state (${TELEGRAM_MESSAGE_DISPATCH_LEGACY_BUCKET_NAMESPACE}) → plugin state (${namespace})`,
520517
shouldReplaceExistingEntry: ({ existingValue, incomingValue }) =>
521518
shouldReplacePersistentDedupeEntry({ existingValue, incomingValue }),
522-
readEntries: () =>
523-
listTelegramLegacyMessageDispatchPluginStateEntries({
524-
accountId,
525-
env,
526-
}),
519+
readEntries: () => readTelegramLegacyMessageDispatchBuckets({ accountId, env }).importEntries,
520+
removeSource: () => removeTelegramLegacyMessageDispatchBuckets({ accountId, env }),
527521
};
528522
return jsonPlans.concat(pluginStatePlan);
529523
});

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ export type ChannelLegacyStateMigrationPlan =
1818
stateDir?: string;
1919
cleanupSource?: "rename";
2020
cleanupWhenEmpty?: boolean;
21+
/** Deletes a non-file legacy source (e.g. plugin-state rows) once all entries are covered. */
22+
removeSource?: () => void | Promise<void>;
2123
preview?: string;
2224
shouldReplaceExistingEntry?: (params: {
2325
key: string;

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

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1122,6 +1122,55 @@ describe("doctor legacy state migrations", () => {
11221122
});
11231123
});
11241124

1125+
it("removes plugin-state legacy sources through removeSource once covered", async () => {
1126+
const root = await makeTempRoot();
1127+
const removeSource = vi.fn();
1128+
const removeEmptySource = vi.fn();
1129+
mockedChannelMigrationPlans.plans = [
1130+
{
1131+
kind: "plugin-state-import",
1132+
label: "Test bucket cache",
1133+
sourcePath: "plugin state:test.legacy-buckets",
1134+
targetPath: "plugin state:test.bucket-cache",
1135+
pluginId: "telegram",
1136+
namespace: "test.bucket-cache",
1137+
maxEntries: 4,
1138+
scopeKey: "",
1139+
removeSource,
1140+
readEntries: () => [{ key: "default", value: { body: "bucket" } }],
1141+
},
1142+
{
1143+
kind: "plugin-state-import",
1144+
label: "Test empty bucket cache",
1145+
sourcePath: "plugin state:test.legacy-empty",
1146+
targetPath: "plugin state:test.empty-cache",
1147+
pluginId: "telegram",
1148+
namespace: "test.empty-cache",
1149+
maxEntries: 4,
1150+
scopeKey: "",
1151+
cleanupWhenEmpty: true,
1152+
removeSource: removeEmptySource,
1153+
readEntries: () => [],
1154+
},
1155+
];
1156+
1157+
const detected = await detectLegacyStateMigrations({
1158+
cfg: {},
1159+
env: { OPENCLAW_STATE_DIR: root } as NodeJS.ProcessEnv,
1160+
});
1161+
const result = await runLegacyStateMigrations({ detected });
1162+
1163+
expect(result.warnings).toStrictEqual([]);
1164+
expect(removeSource).toHaveBeenCalledTimes(1);
1165+
expect(removeEmptySource).toHaveBeenCalledTimes(1);
1166+
expect(result.changes).toContain(
1167+
"Removed Test bucket cache legacy source (plugin state:test.legacy-buckets)",
1168+
);
1169+
expect(result.changes).toContain(
1170+
"Removed Test empty bucket cache legacy source (plugin state:test.legacy-empty)",
1171+
);
1172+
});
1173+
11251174
it("replaces existing plugin-state entries when a channel import plan asks for it", async () => {
11261175
const root = await makeTempRoot();
11271176
const sourcePath = path.join(root, "legacy-cache.json");

‎src/infra/state-migrations.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1712,6 +1712,14 @@ async function runLegacyMigrationPlans(
17121712
warnings,
17131713
});
17141714
}
1715+
if (allEntriesCovered && plan.removeSource) {
1716+
try {
1717+
await plan.removeSource();
1718+
changes.push(`Removed ${plan.label} legacy source (${plan.sourcePath})`);
1719+
} catch (err) {
1720+
warnings.push(`Failed removing ${plan.label} legacy source: ${String(err)}`);
1721+
}
1722+
}
17151723
});
17161724
continue;
17171725
}

0 commit comments

Comments
 (0)