Skip to content

Commit f1381b5

Browse files
authored
fix(telegram): limit startup probes (#80986)
## Summary - Limit Telegram startup `getMe` probes to two concurrent accounts. - Add regression coverage for queued startup and queued abort behavior. - Document the multi-account startup bound and add changelog credit. ## Verification - `pnpm exec oxfmt --check --threads=1 CHANGELOG.md docs/channels/telegram.md extensions/telegram/src/channel.ts extensions/telegram/src/channel.gateway.test.ts extensions/telegram/src/startup-probe-limiter.ts` - `node scripts/format-docs.mjs --check docs/channels/telegram.md` - `git diff --check HEAD~1..HEAD` - `env OPENCLAW_TEST_HEAVY_CHECK_LOCK_HELD=1 OPENCLAW_VITEST_MAX_WORKERS=1 pnpm --config.manage-package-manager-versions=false test extensions/telegram/src/channel.gateway.test.ts src/gateway/server-channels.test.ts` - `env OPENCLAW_TSGO_HEAVY_CHECK_LOCK_HELD=1 pnpm --config.manage-package-manager-versions=false run tsgo:extensions` - `env OPENCLAW_TSGO_HEAVY_CHECK_LOCK_HELD=1 pnpm --config.manage-package-manager-versions=false run tsgo:extensions:test` - GitHub CI mostly green on `2d389e1010742efa884eacea520afd588d0b898f`; `check-test-types` red in unrelated `src/auto-reply/reply/queue/settings.test.ts` outside this PR's diff. Co-authored-by: stainlu <[email protected]>
1 parent b17e77a commit f1381b5

5 files changed

Lines changed: 218 additions & 10 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ Docs: https://docs.openclaw.ai
6868
- WhatsApp: keep optional audio decoding dependencies local to the external plugin so the core npm install no longer pulls WhatsApp-only media helpers.
6969
- Build: skip copied metadata for bundled plugins that are excluded from build entries, preventing update/status rebuilds from advertising missing QQ Bot runtime files. (#80925)
7070
- Control UI/sessions: nest subagent sessions under their parent session in the session picker dropdown using a visual `└─ ` prefix, making the parent-child relationship clear. Fixes #77628. (#78623) Thanks @chinar-amrutkar.
71+
- Telegram: limit concurrent startup `getMe` probes across multi-account bots so large Telegram configs do not fan out all account probes at once during gateway startup. Refs #80695. (#80986) Thanks @stainlu.
7172
- fix(config): reject auto-managed meta.lastTouched\* paths in config set/unset (#80856). Thanks @ai-hpc
7273
- Auto-reply: surface a visible error when the configured model backend fails and fallback produces no visible reply, while preserving intentional silent turns and side-effect-only deliveries. (#80917) Thanks @dutifulbob.
7374
- Agents/exec: skip redundant heartbeat wake-ups for subagent session exec completions, preventing spurious LLM invocations on parent sessions. Fixes #66748. (#66749) Thanks @ggzeng.

‎docs/channels/telegram.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,7 @@ curl "https://api.telegram.org/bot<bot_token>/getUpdates"
293293
- Group sessions are isolated by group ID. Forum topics append `:topic:<threadId>` to keep topics isolated.
294294
- DM messages can carry `message_thread_id`; OpenClaw preserves the thread ID for replies but keeps DMs on the flat session by default. Configure `channels.telegram.dm.threadReplies: "inbound"`, `channels.telegram.direct.<chatId>.threadReplies: "inbound"`, `requireTopic: true`, or a matching topic config when you intentionally want DM topic session isolation.
295295
- Long polling uses grammY runner with per-chat/per-thread sequencing. Overall runner sink concurrency uses `agents.defaults.maxConcurrent`.
296+
- Multi-account startup bounds concurrent Telegram `getMe` probes so large bot fleets do not fan out every account probe at once.
296297
- Long polling is guarded inside each gateway process so only one active poller can use a bot token at a time. If you still see `getUpdates` 409 conflicts, another OpenClaw gateway, script, or external poller is likely using the same token.
297298
- Long-polling watchdog restarts trigger after 120 seconds without completed `getUpdates` liveness by default. Increase `channels.telegram.pollingStallThresholdMs` only if your deployment still sees false polling-stall restarts during long-running work. The value is in milliseconds and is allowed from `30000` to `600000`; per-account overrides are supported.
298299
- Telegram Bot API has no read-receipt support (`sendReadReceipts` does not apply).

‎extensions/telegram/src/channel.gateway.test.ts‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import type { TelegramMonitorFn } from "./monitor.types.js";
99
import { clearTelegramRuntime, setTelegramRuntime } from "./runtime.js";
1010
import type { TelegramProbeFn } from "./runtime.types.js";
1111
import type { TelegramRuntime } from "./runtime.types.js";
12+
import { resetTelegramStartupProbeLimiterForTests } from "./startup-probe-limiter.js";
1213

1314
const probeTelegram = vi.fn();
1415
const monitorTelegramProvider = vi.fn();
@@ -61,6 +62,7 @@ function createTelegramConfig(
6162
function startTelegramAccount(
6263
accountId = "default",
6364
telegramOverrides: Record<string, unknown> = {},
65+
abortSignal?: AbortSignal,
6466
) {
6567
const cfg = createTelegramConfig(accountId, telegramOverrides);
6668
const account = telegramPlugin.config.resolveAccount(cfg, accountId);
@@ -71,6 +73,7 @@ function startTelegramAccount(
7173
const ctx = createStartAccountContext({
7274
account,
7375
cfg,
76+
...(abortSignal ? { abortSignal } : {}),
7477
});
7578
return {
7679
ctx,
@@ -100,8 +103,19 @@ function sendMessageOptionsAt(index: number): Record<string, unknown> {
100103
return options;
101104
}
102105

106+
async function waitForCondition(check: () => boolean, message: string, attempts = 100) {
107+
for (let i = 0; i < attempts; i += 1) {
108+
if (check()) {
109+
return;
110+
}
111+
await Promise.resolve();
112+
}
113+
throw new Error(message);
114+
}
115+
103116
afterEach(() => {
104117
clearTelegramRuntime();
118+
resetTelegramStartupProbeLimiterForTests();
105119
probeTelegram.mockReset();
106120
monitorTelegramProvider.mockReset();
107121
sendMessageTelegram.mockReset();
@@ -235,6 +249,90 @@ describe("telegramPlugin gateway startup", () => {
235249
includeWebhookInfo: false,
236250
});
237251
});
252+
253+
it("limits concurrent startup probes across Telegram accounts", async () => {
254+
installTelegramRuntime();
255+
const releaseProbe: Array<() => void> = [];
256+
let activeProbes = 0;
257+
let maxActiveProbes = 0;
258+
probeTelegram.mockImplementation(async () => {
259+
activeProbes += 1;
260+
maxActiveProbes = Math.max(maxActiveProbes, activeProbes);
261+
await new Promise<void>((resolve) => {
262+
releaseProbe.push(resolve);
263+
});
264+
activeProbes -= 1;
265+
return {
266+
ok: true,
267+
status: null,
268+
error: null,
269+
elapsedMs: 12,
270+
};
271+
});
272+
monitorTelegramProvider.mockResolvedValue(undefined);
273+
274+
const first = startTelegramAccount("alpha");
275+
const second = startTelegramAccount("bravo");
276+
const third = startTelegramAccount("charlie");
277+
278+
await waitForCondition(
279+
() => probeTelegram.mock.calls.length === 2,
280+
"expected two startup probes to begin",
281+
);
282+
expect(maxActiveProbes).toBe(2);
283+
expect(releaseProbe).toHaveLength(2);
284+
285+
releaseProbe.shift()?.();
286+
await waitForCondition(
287+
() => probeTelegram.mock.calls.length === 3,
288+
"expected queued startup probe to begin after a slot opens",
289+
);
290+
expect(maxActiveProbes).toBe(2);
291+
292+
for (const release of releaseProbe.splice(0)) {
293+
release();
294+
}
295+
await Promise.all([first.task, second.task, third.task]);
296+
expect(monitorTelegramProvider).toHaveBeenCalledTimes(3);
297+
});
298+
299+
it("abandons a queued startup probe when the account aborts", async () => {
300+
installTelegramRuntime();
301+
const releaseProbe: Array<() => void> = [];
302+
probeTelegram.mockImplementation(
303+
async () =>
304+
await new Promise((resolve) => {
305+
releaseProbe.push(() =>
306+
resolve({
307+
ok: true,
308+
status: null,
309+
error: null,
310+
elapsedMs: 12,
311+
}),
312+
);
313+
}),
314+
);
315+
monitorTelegramProvider.mockResolvedValue(undefined);
316+
317+
const first = startTelegramAccount("alpha");
318+
const second = startTelegramAccount("bravo");
319+
const abortQueued = new AbortController();
320+
const queued = startTelegramAccount("charlie", {}, abortQueued.signal);
321+
322+
await waitForCondition(
323+
() => probeTelegram.mock.calls.length === 2,
324+
"expected startup probe slots to fill",
325+
);
326+
abortQueued.abort();
327+
await expect(queued.task).resolves.toBeUndefined();
328+
329+
for (const release of releaseProbe.splice(0)) {
330+
release();
331+
}
332+
await Promise.all([first.task, second.task]);
333+
expect(probeTelegram).toHaveBeenCalledTimes(2);
334+
expect(monitorTelegramProvider).toHaveBeenCalledTimes(2);
335+
});
238336
});
239337

240338
describe("telegramPlugin outbound attachments", () => {

‎extensions/telegram/src/channel.ts‎

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ import {
7373
formatDuplicateTelegramTokenReason,
7474
telegramConfigAdapter,
7575
} from "./shared.js";
76+
import { withTelegramStartupProbeSlot } from "./startup-probe-limiter.js";
7677
import { detectTelegramLegacyStateMigrations } from "./state-migrations.js";
7778
import { collectTelegramStatusIssues } from "./status-issues.js";
7879
import { parseTelegramTarget } from "./targets.js";
@@ -896,16 +897,18 @@ export const telegramPlugin = createChatChannelPlugin({
896897
let unauthorizedTokenReason: string | null = null;
897898
let botInfo: TelegramBotInfo | undefined;
898899
try {
899-
const probe = await resolveTelegramProbe()(
900-
token,
901-
resolveTelegramStartupProbeTimeoutMs(account.config.timeoutSeconds),
902-
{
903-
accountId: account.accountId,
904-
proxyUrl: account.config.proxy,
905-
network: account.config.network,
906-
apiRoot: account.config.apiRoot,
907-
includeWebhookInfo: false,
908-
},
900+
const probe = await withTelegramStartupProbeSlot(ctx.abortSignal, () =>
901+
resolveTelegramProbe()(
902+
token,
903+
resolveTelegramStartupProbeTimeoutMs(account.config.timeoutSeconds),
904+
{
905+
accountId: account.accountId,
906+
proxyUrl: account.config.proxy,
907+
network: account.config.network,
908+
apiRoot: account.config.apiRoot,
909+
includeWebhookInfo: false,
910+
},
911+
),
909912
);
910913
const username = probe.ok ? probe.bot?.username?.trim() : null;
911914
if (username) {
@@ -916,6 +919,9 @@ export const telegramPlugin = createChatChannelPlugin({
916919
unauthorizedTokenReason = formatTelegramUnauthorizedTokenError(account);
917920
}
918921
} catch (err) {
922+
if (ctx.abortSignal.aborted) {
923+
return;
924+
}
919925
if (getTelegramRuntime().logging.shouldLogVerbose()) {
920926
ctx.log?.debug?.(`[${account.accountId}] bot probe failed: ${String(err)}`);
921927
}
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
const TELEGRAM_STARTUP_PROBE_CONCURRENCY = 2;
2+
3+
type StartupProbeSlot = () => void;
4+
5+
type StartupProbeWaiter = {
6+
resolve: (release: StartupProbeSlot) => void;
7+
reject: (error: Error) => void;
8+
abortSignal?: AbortSignal;
9+
onAbort?: () => void;
10+
};
11+
12+
let activeStartupProbes = 0;
13+
const pendingStartupProbeWaiters: StartupProbeWaiter[] = [];
14+
15+
function buildStartupProbeAbortError(): Error {
16+
return new Error("telegram startup probe wait aborted");
17+
}
18+
19+
function detachAbortHandler(waiter: StartupProbeWaiter) {
20+
if (!waiter.abortSignal || !waiter.onAbort) {
21+
return;
22+
}
23+
waiter.abortSignal.removeEventListener("abort", waiter.onAbort);
24+
}
25+
26+
function removePendingWaiter(waiter: StartupProbeWaiter) {
27+
const index = pendingStartupProbeWaiters.indexOf(waiter);
28+
if (index >= 0) {
29+
pendingStartupProbeWaiters.splice(index, 1);
30+
}
31+
}
32+
33+
function releaseStartupProbeSlot() {
34+
activeStartupProbes = Math.max(0, activeStartupProbes - 1);
35+
drainStartupProbeWaiters();
36+
}
37+
38+
function drainStartupProbeWaiters() {
39+
while (
40+
activeStartupProbes < TELEGRAM_STARTUP_PROBE_CONCURRENCY &&
41+
pendingStartupProbeWaiters.length > 0
42+
) {
43+
const waiter = pendingStartupProbeWaiters.shift();
44+
if (!waiter) {
45+
return;
46+
}
47+
detachAbortHandler(waiter);
48+
if (waiter.abortSignal?.aborted) {
49+
waiter.reject(buildStartupProbeAbortError());
50+
continue;
51+
}
52+
activeStartupProbes += 1;
53+
waiter.resolve(releaseStartupProbeSlot);
54+
}
55+
}
56+
57+
async function acquireStartupProbeSlot(abortSignal?: AbortSignal): Promise<StartupProbeSlot> {
58+
if (abortSignal?.aborted) {
59+
throw buildStartupProbeAbortError();
60+
}
61+
if (activeStartupProbes < TELEGRAM_STARTUP_PROBE_CONCURRENCY) {
62+
activeStartupProbes += 1;
63+
return releaseStartupProbeSlot;
64+
}
65+
return await new Promise<StartupProbeSlot>((resolve, reject) => {
66+
const waiter: StartupProbeWaiter = {
67+
resolve,
68+
reject,
69+
...(abortSignal ? { abortSignal } : {}),
70+
};
71+
waiter.onAbort = () => {
72+
removePendingWaiter(waiter);
73+
reject(buildStartupProbeAbortError());
74+
};
75+
abortSignal?.addEventListener("abort", waiter.onAbort, { once: true });
76+
pendingStartupProbeWaiters.push(waiter);
77+
});
78+
}
79+
80+
export async function withTelegramStartupProbeSlot<T>(
81+
abortSignal: AbortSignal | undefined,
82+
run: () => Promise<T>,
83+
): Promise<T> {
84+
const release = await acquireStartupProbeSlot(abortSignal);
85+
try {
86+
if (abortSignal?.aborted) {
87+
throw buildStartupProbeAbortError();
88+
}
89+
return await run();
90+
} finally {
91+
release();
92+
}
93+
}
94+
95+
export function resetTelegramStartupProbeLimiterForTests() {
96+
activeStartupProbes = 0;
97+
const pending = pendingStartupProbeWaiters.splice(0);
98+
for (const waiter of pending) {
99+
detachAbortHandler(waiter);
100+
waiter.reject(buildStartupProbeAbortError());
101+
}
102+
}

0 commit comments

Comments
 (0)