Skip to content

Commit 7a84e2a

Browse files
author
SymbolStar
committed
fix(telegram): release polling leases at in-process gateway restart boundary
The Telegram polling lease registry lives on a process-global Symbol so it survives gateway restarts that recycle the lifecycle without exiting Node (SIGUSR1 in-process restart, OPENCLAW_NO_RESPAWN reload). When the previous lifecycle's monitor task is dropped before its `finally` releases the lease, the next lifecycle's `acquireTelegramPollingLease()` sees a stale same-token entry and rejects every Telegram account with the duplicate-poller error indefinitely. Add a generic `in-process-restart-hooks` registry on `process` and run it from the gateway run-loop's restart iteration hook, alongside the existing `resetAllLanes` / `resetGatewayRestartStateForInProcessRestart` / `reloadTaskRegistryFromStore` calls. Telegram's polling-lease module self-registers a hook on first load that drains the lease registry. Late `release()` calls from dropped previous-lifecycle tasks remain safe (release is owner-checked and idempotent), and the same-lifecycle live duplicate guard is unchanged. Regression tests cover both the cleanup behavior and the same-lifecycle guard, plus the run-loop wiring. Fixes #81507
1 parent 308b39e commit 7a84e2a

8 files changed

Lines changed: 264 additions & 0 deletions

File tree

‎extensions/telegram/src/polling-lease.test.ts‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
import { runInProcessRestartHooks } from "openclaw/plugin-sdk/lifecycle-restart-hooks";
23
import {
34
acquireTelegramPollingLease,
5+
releaseTelegramPollingLeasesForLifecycleReset,
46
resetTelegramPollingLeasesForTests,
57
} from "./polling-lease.js";
68

@@ -99,4 +101,91 @@ describe("Telegram polling lease", () => {
99101
vi.useRealTimers();
100102
}
101103
});
104+
105+
// Regression: openclaw/openclaw#81507
106+
// The polling lease registry lives on a process-global Symbol, so a stale
107+
// entry left by a dropped previous-lifecycle monitor task blocks every new
108+
// acquire after an in-process gateway restart. The Telegram extension
109+
// registers a lifecycle reset hook that drains the registry at the restart
110+
// boundary; after that runs, a fresh acquire for the same token must
111+
// succeed even though the old lease was never explicitly released.
112+
it("clears stale same-token leases at the in-process restart boundary", async () => {
113+
const oldAbort = new AbortController();
114+
const stale = await acquireTelegramPollingLease({
115+
token: "123:abc",
116+
accountId: "old-lifecycle",
117+
abortSignal: oldAbort.signal,
118+
});
119+
120+
// Simulate the previous lifecycle dying without ever calling release()
121+
// (its `finally` block was interrupted by the in-process restart).
122+
await expect(
123+
acquireTelegramPollingLease({
124+
token: "123:abc",
125+
accountId: "new-lifecycle",
126+
waitMs: 0,
127+
}),
128+
).rejects.toThrow('refusing duplicate poller for account "new-lifecycle"');
129+
130+
// The gateway run-loop drains plugin-registered subsystem hooks at the
131+
// restart boundary. The Telegram extension registers itself on first
132+
// module load, so this drain frees the stale lease.
133+
const drained = releaseTelegramPollingLeasesForLifecycleReset();
134+
expect(drained).toBe(1);
135+
136+
const fresh = await acquireTelegramPollingLease({
137+
token: "123:abc",
138+
accountId: "new-lifecycle",
139+
});
140+
expect(fresh.tokenFingerprint).toBe(stale.tokenFingerprint);
141+
142+
// A late `release()` from the dropped previous-lifecycle task must NOT
143+
// delete the fresh lease (owner-checked release).
144+
stale.release();
145+
await expect(
146+
acquireTelegramPollingLease({
147+
token: "123:abc",
148+
accountId: "third",
149+
}),
150+
).rejects.toThrow('refusing duplicate poller for account "new-lifecycle"');
151+
152+
fresh.release();
153+
});
154+
155+
// Regression: openclaw/openclaw#81507
156+
// The cleanup is lifecycle-owned, not steady-state. Two concurrent live
157+
// pollers within the same lifecycle (no restart in between) must still be
158+
// rejected by the same-token guard.
159+
it("keeps the same-token live duplicate guard outside the restart boundary", async () => {
160+
const first = await acquireTelegramPollingLease({
161+
token: "123:abc",
162+
accountId: "a",
163+
});
164+
await expect(
165+
acquireTelegramPollingLease({
166+
token: "123:abc",
167+
accountId: "b",
168+
}),
169+
).rejects.toThrow('refusing duplicate poller for account "b"');
170+
first.release();
171+
});
172+
173+
// The Telegram extension wires its cleanup through the shared
174+
// in-process-restart-hooks registry on first module load. Running the
175+
// registry must cascade through to the Telegram lease registry without
176+
// any callers having to know about the Telegram-specific helper.
177+
it("is wired into the shared in-process restart hook registry", async () => {
178+
const lease = await acquireTelegramPollingLease({
179+
token: "123:abc",
180+
accountId: "hook-test",
181+
});
182+
expect(runInProcessRestartHooks()).toBeGreaterThanOrEqual(1);
183+
const fresh = await acquireTelegramPollingLease({
184+
token: "123:abc",
185+
accountId: "hook-test-2",
186+
});
187+
fresh.release();
188+
// Late stale release from the dropped previous-lifecycle task is safe.
189+
lease.release();
190+
});
102191
});

‎extensions/telegram/src/polling-lease.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { registerInProcessRestartHook } from "openclaw/plugin-sdk/lifecycle-restart-hooks";
12
import { fingerprintTelegramBotToken } from "./token-fingerprint.js";
23

34
const TELEGRAM_POLLING_LEASES_KEY = Symbol.for("openclaw.telegram.pollingLeases");
@@ -187,3 +188,66 @@ export async function acquireTelegramPollingLease(
187188
export function resetTelegramPollingLeasesForTests(): void {
188189
pollingLeaseRegistry().clear();
189190
}
191+
192+
/**
193+
* Self-register the lifecycle reset hook on first module load. The underlying
194+
* registry already de-duplicates by hook identity, but a fresh closure would
195+
* be created on every module load, so we guard with a process-symbol flag to
196+
* keep the registration idempotent across ESM/CJS interop boundaries.
197+
*/
198+
const LIFECYCLE_HOOK_REGISTERED_KEY = Symbol.for(
199+
"openclaw.telegram.pollingLeases.lifecycleHookRegistered",
200+
);
201+
{
202+
const host = process as NodeJS.Process & {
203+
[LIFECYCLE_HOOK_REGISTERED_KEY]?: boolean;
204+
};
205+
if (!host[LIFECYCLE_HOOK_REGISTERED_KEY]) {
206+
host[LIFECYCLE_HOOK_REGISTERED_KEY] = true;
207+
registerInProcessRestartHook(() => {
208+
releaseTelegramPollingLeasesForLifecycleReset();
209+
});
210+
}
211+
}
212+
213+
/**
214+
* Lifecycle boundary cleanup for in-process gateway restarts.
215+
*
216+
* The lease registry lives on a process-global symbol so it survives Node-level
217+
* restarts that recycle the gateway lifecycle without exiting the process
218+
* (SIGUSR1 in-process restart, OPENCLAW_NO_RESPAWN reload, etc.). When the old
219+
* lifecycle's monitor task is dropped before its `finally` releases the lease,
220+
* the next lifecycle's `acquireTelegramPollingLease()` sees a stale same-token
221+
* entry and rejects every Telegram account with the duplicate-poller error.
222+
*
223+
* The fix is lifecycle-owned: at the restart boundary the gateway clears every
224+
* lease this process is holding. We deliberately drop entries even if the
225+
* abort signal has not yet observed the abort, because by definition the old
226+
* lifecycle is ending and any still-running poller belongs to it. Late
227+
* `release()` calls from the dropped tasks are safe — release() is idempotent
228+
* and owner-checked, so they will not delete a fresh lease acquired by the new
229+
* lifecycle.
230+
*
231+
* Same-token guard within a single lifecycle is unaffected: this function is
232+
* only called from the in-process restart boundary, never from steady-state
233+
* acquire/release paths. Two concurrent live pollers within one lifecycle are
234+
* still rejected by `acquireTelegramPollingLease()`.
235+
*
236+
* Issue: openclaw/openclaw#81507
237+
*/
238+
export function releaseTelegramPollingLeasesForLifecycleReset(): number {
239+
const registry = pollingLeaseRegistry();
240+
if (registry.size === 0) {
241+
return 0;
242+
}
243+
const entries = Array.from(registry.values());
244+
registry.clear();
245+
for (const entry of entries) {
246+
try {
247+
entry.resolveDone();
248+
} catch {
249+
// resolveDone is safe to call multiple times; ignore.
250+
}
251+
}
252+
return entries.length;
253+
}

‎package.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,10 @@
343343
"types": "./dist/plugin-sdk/heartbeat-runtime.d.ts",
344344
"default": "./dist/plugin-sdk/heartbeat-runtime.js"
345345
},
346+
"./plugin-sdk/lifecycle-restart-hooks": {
347+
"types": "./dist/plugin-sdk/lifecycle-restart-hooks.d.ts",
348+
"default": "./dist/plugin-sdk/lifecycle-restart-hooks.js"
349+
},
346350
"./plugin-sdk/number-runtime": {
347351
"types": "./dist/plugin-sdk/number-runtime.d.ts",
348352
"default": "./dist/plugin-sdk/number-runtime.js"

‎src/cli/gateway-cli/lifecycle.runtime.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,5 +29,6 @@ export {
2929
resetAllLanes,
3030
waitForActiveTasks,
3131
} from "../../process/command-queue.js";
32+
export { runInProcessRestartHooks } from "../../infra/in-process-restart-hooks.js";
3233
export { getInspectableActiveTaskRestartBlockers } from "../../tasks/task-registry.maintenance.js";
3334
export { reloadTaskRegistryFromStore } from "../../tasks/runtime-internal.js";

‎src/cli/gateway-cli/run-loop.test.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ const markGatewayDraining = vi.fn();
5050
const waitForActiveTasks = vi.fn(async (_timeoutMs?: number) => ({ drained: true }));
5151
const resetAllLanes = vi.fn();
5252
const reloadTaskRegistryFromStore = vi.fn();
53+
const runInProcessRestartHooks = vi.fn();
5354
const restartGatewayProcessWithFreshPid = vi.fn<
5455
() => { mode: "spawned" | "supervised" | "disabled" | "failed"; pid?: number; detail?: string }
5556
>(() => ({ mode: "disabled" }));
@@ -133,6 +134,10 @@ vi.mock("../../tasks/runtime-internal.js", () => ({
133134
reloadTaskRegistryFromStore: () => reloadTaskRegistryFromStore(),
134135
}));
135136

137+
vi.mock("../../infra/in-process-restart-hooks.js", () => ({
138+
runInProcessRestartHooks: () => runInProcessRestartHooks(),
139+
}));
140+
136141
vi.mock("../../tasks/task-registry.maintenance.js", () => ({
137142
getInspectableActiveTaskRestartBlockers: () => getInspectableActiveTaskRestartBlockers(),
138143
}));
@@ -532,6 +537,7 @@ describe("runGatewayLoop", () => {
532537
expect(resetAllLanes).toHaveBeenCalledTimes(1);
533538
expect(resetGatewayRestartStateForInProcessRestart).toHaveBeenCalledTimes(1);
534539
expect(reloadTaskRegistryFromStore).toHaveBeenCalledTimes(1);
540+
expect(runInProcessRestartHooks).toHaveBeenCalledTimes(1);
535541

536542
sigusr1();
537543

@@ -546,6 +552,7 @@ describe("runGatewayLoop", () => {
546552
expect(resetAllLanes).toHaveBeenCalledTimes(2);
547553
expect(resetGatewayRestartStateForInProcessRestart).toHaveBeenCalledTimes(2);
548554
expect(reloadTaskRegistryFromStore).toHaveBeenCalledTimes(2);
555+
expect(runInProcessRestartHooks).toHaveBeenCalledTimes(2);
549556
expect(acquireGatewayLock).toHaveBeenCalledTimes(3);
550557

551558
sigterm();

‎src/cli/gateway-cli/run-loop.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -525,10 +525,15 @@ export async function runGatewayLoop(params: {
525525
reloadTaskRegistryFromStore,
526526
resetAllLanes,
527527
resetGatewayRestartStateForInProcessRestart,
528+
runInProcessRestartHooks,
528529
} = await loadGatewayLifecycleRuntimeModule();
529530
resetAllLanes();
530531
resetGatewayRestartStateForInProcessRestart();
531532
reloadTaskRegistryFromStore();
533+
// Drain plugin-registered subsystem cleanup (e.g. Telegram polling
534+
// leases) at the same boundary so process-global state seeded by the
535+
// previous lifecycle does not leak into the next one. (#81507)
536+
runInProcessRestartHooks();
532537
});
533538

534539
// Keep process alive; SIGUSR1 triggers an in-process restart (no supervisor required).
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/**
2+
* Process-global registry of subsystem cleanup hooks invoked at the gateway
3+
* in-process restart boundary (SIGUSR1 / OPENCLAW_NO_RESPAWN reload).
4+
*
5+
* Most subsystem state is recreated per gateway lifecycle, but a few helpers
6+
* (notably the Telegram polling lease registry) live on `process[Symbol.for(...)]`
7+
* so they survive across in-process restarts. When the previous lifecycle's
8+
* task is dropped before its `finally` releases the resource, the next
9+
* lifecycle observes a stale entry and rejects all work for that subsystem
10+
* (#81507). The fix is for those subsystems to register a lifecycle reset
11+
* hook here; the gateway run-loop drains them at the same boundary that
12+
* already resets command lanes and restart-deferral state.
13+
*
14+
* Hooks must be:
15+
* - synchronous and side-effect-only (no I/O, no awaiting), so the boundary
16+
* stays cheap and predictable;
17+
* - safe to call repeatedly (idempotent), so process-respawn paths and
18+
* test harnesses can invoke them without coordinating ordering;
19+
* - safe to throw \u2014 errors from one hook never block sibling hooks.
20+
*
21+
* Hooks are stored on a `Symbol.for()`-keyed registry on `process`, matching
22+
* the storage style used by the subsystems they clean up. A second module
23+
* load (e.g. ESM/CJS interop boundaries) reuses the same Set instead of
24+
* creating a duplicate.
25+
*/
26+
27+
const HOOKS_KEY = Symbol.for("openclaw.inProcessRestartHooks.v1");
28+
29+
type ResetHook = () => void;
30+
31+
type RegistryHost = NodeJS.Process & {
32+
[HOOKS_KEY]?: Set<ResetHook>;
33+
};
34+
35+
function getRegistry(): Set<ResetHook> {
36+
const host = process as RegistryHost;
37+
host[HOOKS_KEY] ??= new Set<ResetHook>();
38+
return host[HOOKS_KEY];
39+
}
40+
41+
/**
42+
* Register a lifecycle reset hook. Returns an unregister function; calling
43+
* it more than once is safe.
44+
*/
45+
export function registerInProcessRestartHook(hook: ResetHook): () => void {
46+
const registry = getRegistry();
47+
registry.add(hook);
48+
let unregistered = false;
49+
return () => {
50+
if (unregistered) {
51+
return;
52+
}
53+
unregistered = true;
54+
registry.delete(hook);
55+
};
56+
}
57+
58+
/**
59+
* Run every registered hook, swallowing per-hook errors so a single failing
60+
* subsystem cannot block the rest. Returns the number of hooks invoked.
61+
*/
62+
export function runInProcessRestartHooks(): number {
63+
const registry = getRegistry();
64+
if (registry.size === 0) {
65+
return 0;
66+
}
67+
// Snapshot to allow hooks to safely register/unregister others.
68+
const snapshot = Array.from(registry);
69+
for (const hook of snapshot) {
70+
try {
71+
hook();
72+
} catch {
73+
// Hooks must be best-effort; swallow to keep the restart boundary
74+
// moving. Subsystems that need to surface failures should log inside
75+
// the hook itself.
76+
}
77+
}
78+
return snapshot.length;
79+
}
80+
81+
/** Test-only helper: drop every registered hook. */
82+
export function clearInProcessRestartHooksForTests(): void {
83+
getRegistry().clear();
84+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// Lifecycle reset hook registry. Plugins may register a synchronous cleanup
2+
// callback that the gateway run-loop drains at the in-process restart
3+
// boundary (SIGUSR1 / OPENCLAW_NO_RESPAWN reload). See `in-process-restart-hooks`
4+
// docs and openclaw/openclaw#81507 for context.
5+
6+
export {
7+
registerInProcessRestartHook,
8+
runInProcessRestartHooks,
9+
clearInProcessRestartHooksForTests,
10+
} from "../infra/in-process-restart-hooks.js";

0 commit comments

Comments
 (0)