Repository navigation
Conversation
Greptile SummaryThis PR fixes a multi-year socket leak in the Telegram polling transport: every dirty rebuild (stall watchdog, recoverable network error) silently abandoned undici Confidence Score: 5/5Safe to merge — all remaining findings are P2 style/cleanup issues that do not affect correctness or the leak fix. The core fix is logically sound: the transport lifecycle contract is well-defined, idempotency is correctly guarded, the fire-and-forget vs. awaited close split is correctly placed, and the finally-block wiring in runUntilAbort is the right hook point. Test coverage is thorough with purpose-built lifecycle suites. Only P2 (style/placeholder) findings remain. No files require special attention beyond the two Prompt To Fix All With AIThis is a comment left during a code review.
Path: extensions/telegram/src/fetch.ts
Line: 36
Comment:
**`openclaw#TBD` placeholder not filled in**
The comment references `openclaw#TBD` but no issue number has been substituted. The same placeholder also appears in `polling-session.ts` (line 118). Both should be updated to the actual GitHub issue/PR number before merging so future `git blame` readers can trace the context.
```suggestion
// fix for the leak observed in openclaw#68128 is the transport lifecycle that
```
How can I resolve this? If you propose a fix, please make it concise.
---
This is a comment left during a code review.
Path: extensions/telegram/src/fetch.ts
Line: 537-545
Comment:
**Redundant `Promise.allSettled` — inner `try/catch` makes it equivalent to `Promise.all`**
The inner `async` callback swallows every error from `await dispatcher.destroy()` via its own `try/catch`, so it always resolves. `Promise.allSettled` and `Promise.all` are therefore identical here; the outer wrapper adds no extra safety. Consider simplifying to `Promise.all`, or dropping the inner try/catch and relying solely on `allSettled` (with a note that the settled results are intentionally discarded).
```suggestion
await Promise.all(
[...dispatchers].map(async (dispatcher) => {
try {
await dispatcher.destroy();
} catch {
// Intentionally ignored: dispatcher may already be destroyed.
}
}),
);
```
How can I resolve this? If you propose a fix, please make it concise.
---
This is a comment left during a code review.
Path: extensions/telegram/src/polling-session.test.ts
Line: 725-727
Comment:
**Misleading test comment — transport1 is only closed once, not twice**
The comment opens with "transport1 should be closed twice" but immediately self-corrects: `dispose()` closes `transport2` (the current held transport after the rebuild), not `transport1`. The sentence structure creates a false expectation and then contradicts it, which is confusing for future readers. Consider rewriting to directly state the actual invariant.
```suggestion
// Dirty-rebuild closes transport1 (fire-and-forget via #closeTransportAsync).
// dispose() closes transport2 since it becomes the held transport after the rebuild.
```
How can I resolve this? If you propose a fix, please make it concise.
---
This is a comment left during a code review.
Path: extensions/telegram/src/polling-session.ts
Line: 118
Comment:
**Second `openclaw#TBD` placeholder**
Same unfilled issue reference as in `fetch.ts` line 36 — both should be updated to the actual issue/PR number before landing.
```suggestion
// leak to api.telegram.org; see openclaw#68128.
```
How can I resolve this? If you propose a fix, please make it concise.Reviews (1): Last reviewed commit: "docs(changelog): note Telegram undici di..." | Re-trigger Greptile |
| // strict enough that (a) idle sockets are closed even when the pool is still | ||
| // actively used and (b) the pool itself cannot grow unbounded under transient | ||
| // concurrency spikes. These values are a defence-in-depth layer; the primary | ||
| // fix for the leak observed in openclaw#TBD is the transport lifecycle that |
There was a problem hiding this comment.
openclaw#TBD placeholder not filled in
The comment references openclaw#TBD but no issue number has been substituted. The same placeholder also appears in polling-session.ts (line 118). Both should be updated to the actual GitHub issue/PR number before merging so future git blame readers can trace the context.
| // fix for the leak observed in openclaw#TBD is the transport lifecycle that | |
| // fix for the leak observed in openclaw#68128 is the transport lifecycle that |
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/telegram/src/fetch.ts
Line: 36
Comment:
**`openclaw#TBD` placeholder not filled in**
The comment references `openclaw#TBD` but no issue number has been substituted. The same placeholder also appears in `polling-session.ts` (line 118). Both should be updated to the actual GitHub issue/PR number before merging so future `git blame` readers can trace the context.
```suggestion
// fix for the leak observed in openclaw#68128 is the transport lifecycle that
```
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
Good catch, thanks! Updated the reference to openclaw#68128 in 7415436.
| await Promise.allSettled( | ||
| [...dispatchers].map(async (dispatcher) => { | ||
| try { | ||
| await dispatcher.destroy(); | ||
| } catch { | ||
| // Intentionally ignored: dispatcher may already be destroyed. | ||
| } | ||
| }), | ||
| ); |
There was a problem hiding this comment.
Redundant
Promise.allSettled — inner try/catch makes it equivalent to Promise.all
The inner async callback swallows every error from await dispatcher.destroy() via its own try/catch, so it always resolves. Promise.allSettled and Promise.all are therefore identical here; the outer wrapper adds no extra safety. Consider simplifying to Promise.all, or dropping the inner try/catch and relying solely on allSettled (with a note that the settled results are intentionally discarded).
| await Promise.allSettled( | |
| [...dispatchers].map(async (dispatcher) => { | |
| try { | |
| await dispatcher.destroy(); | |
| } catch { | |
| // Intentionally ignored: dispatcher may already be destroyed. | |
| } | |
| }), | |
| ); | |
| await Promise.all( | |
| [...dispatchers].map(async (dispatcher) => { | |
| try { | |
| await dispatcher.destroy(); | |
| } catch { | |
| // Intentionally ignored: dispatcher may already be destroyed. | |
| } | |
| }), | |
| ); |
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/telegram/src/fetch.ts
Line: 537-545
Comment:
**Redundant `Promise.allSettled` — inner `try/catch` makes it equivalent to `Promise.all`**
The inner `async` callback swallows every error from `await dispatcher.destroy()` via its own `try/catch`, so it always resolves. `Promise.allSettled` and `Promise.all` are therefore identical here; the outer wrapper adds no extra safety. Consider simplifying to `Promise.all`, or dropping the inner try/catch and relying solely on `allSettled` (with a note that the settled results are intentionally discarded).
```suggestion
await Promise.all(
[...dispatchers].map(async (dispatcher) => {
try {
await dispatcher.destroy();
} catch {
// Intentionally ignored: dispatcher may already be destroyed.
}
}),
);
```
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
Fair point — the outer Promise.allSettled was belt-and-braces given the inner try/catch already guarantees the per-dispatcher promise resolves. Switched to Promise.all in 7415436 and tweaked the comment to explain why Promise.all is safe here.
| // transport1 should be closed twice: once when the dirty-rebuild replaces | ||
| // it with transport2, once again defensively by dispose() — but our impl | ||
| // only holds a single transport at a time, so dispose closes transport2. |
There was a problem hiding this comment.
Misleading test comment — transport1 is only closed once, not twice
The comment opens with "transport1 should be closed twice" but immediately self-corrects: dispose() closes transport2 (the current held transport after the rebuild), not transport1. The sentence structure creates a false expectation and then contradicts it, which is confusing for future readers. Consider rewriting to directly state the actual invariant.
| // transport1 should be closed twice: once when the dirty-rebuild replaces | |
| // it with transport2, once again defensively by dispose() — but our impl | |
| // only holds a single transport at a time, so dispose closes transport2. | |
| // Dirty-rebuild closes transport1 (fire-and-forget via #closeTransportAsync). | |
| // dispose() closes transport2 since it becomes the held transport after the rebuild. |
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/telegram/src/polling-session.test.ts
Line: 725-727
Comment:
**Misleading test comment — transport1 is only closed once, not twice**
The comment opens with "transport1 should be closed twice" but immediately self-corrects: `dispose()` closes `transport2` (the current held transport after the rebuild), not `transport1`. The sentence structure creates a false expectation and then contradicts it, which is confusing for future readers. Consider rewriting to directly state the actual invariant.
```suggestion
// Dirty-rebuild closes transport1 (fire-and-forget via #closeTransportAsync).
// dispose() closes transport2 since it becomes the held transport after the rebuild.
```
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
Agreed, the original phrasing set up an expectation and immediately contradicted itself. Took your suggested wording in ed1f167.
| } finally { | ||
| // Release the transport's dispatchers on session shutdown. Without | ||
| // this, the undici keep-alive sockets survive beyond the session and | ||
| // leak to api.telegram.org; see openclaw#TBD. |
There was a problem hiding this comment.
Second
openclaw#TBD placeholder
Same unfilled issue reference as in fetch.ts line 36 — both should be updated to the actual issue/PR number before landing.
| // leak to api.telegram.org; see openclaw#TBD. | |
| // leak to api.telegram.org; see openclaw#68128. |
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/telegram/src/polling-session.ts
Line: 118
Comment:
**Second `openclaw#TBD` placeholder**
Same unfilled issue reference as in `fetch.ts` line 36 — both should be updated to the actual issue/PR number before landing.
```suggestion
// leak to api.telegram.org; see openclaw#68128.
```
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
Thanks — filled this in as openclaw#68128 in ed1f167 alongside the fetch.ts one.
TelegramTransport now exposes an explicit close() that destroys every owned undici dispatcher (default Agent plus lazily-created IPv4 and IP-pinned fallback Agents) and the TCP sockets they hold. Dispatcher constructors are also given bounded keep-alive defaults (keepAliveTimeout, keepAliveMaxTimeout, connections, pipelining) as a defence-in-depth layer so the pool cannot grow unbounded even if a caller forgets to call close(). Without this, every transport that went through a fallback retry left its fallback Agents anchored forever in a closure; long-running polling sessions accumulated hundreds of ESTABLISHED keep-alive sockets to api.telegram.org, saturating the per-IP quota on upstream forward proxies and making the currently-active outbound node time out while every other node still tested healthy. Mock dispatchers in fetch.test.ts gain destroy() spies so the close() chain is assertable. Call sites that built caller-owned transports from globalThis.fetch (delivery.resolve-media, test helpers) return an async no-op close(), matching the new required surface. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Every recoverable network error and stall-watchdog trip sets TelegramPollingTransportState.#transportDirty so the next polling cycle rebuilds the transport inside acquireForNextCycle(). Previously the rebuild simply overwrote the field, leaving the old transport's keep-alive sockets anchored in the now-unreferenced dispatcher — the polling loop has no natural GC point for these resources, and Node's object GC never touches OS-level sockets. acquireForNextCycle() now closes the previous transport (fire-and- forget so the polling cycle is not blocked by a slow destroy) before swapping in the rebuilt one. dispose() is a new method that the owning TelegramPollingSession calls from the finally block of runUntilAbort(), so a single transport is always tied to a single polling session lifetime. After dispose(), acquireForNextCycle() returns undefined to prevent zombie rebuilds. Under high sustained polling traffic over long-lived sessions, this is what stops the per-gateway connection count to api.telegram.org from growing indefinitely and saturating upstream proxy quotas. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
b3fbc6d to
438a2e1
Compare
|
Maintainer triage from the Telegram slow/stall reports (#69147, #64288, #66885): this is the strongest merge candidate for the socket-leak / dirty-rebuild side. Why: the current polling transport rebuild path can abandon undici dispatcher pools; this PR gives Suggested before merge: please fold in Recommended path: merge this after adding |
Summary
The Telegram polling transport has never released the undici
dispatchers it constructs, so every transport rebuild (stall,
recoverable network error, fallback retry) leaks its keep-alive sockets
to
api.telegram.org. On a long-running gateway this accumulates intohundreds of ESTABLISHED TCP connections per session, which saturates
upstream forward-proxy quotas and is observable as: the currently
active upstream proxy route times out while every other route still
reports fine latency, and restarting the gateway instantly restores
the connection.
This PR gives
TelegramTransportan explicit lifecycle (close()),wires
TelegramPollingSession/TelegramPollingTransportStatetoinvoke it on shutdown and on every dirty rebuild, and adds bounded
keep-alive defaults (
keepAliveTimeout,keepAliveMaxTimeout,connections,pipelining) on every constructedAgent/ProxyAgent/EnvHttpProxyAgentas defence in depth.Root cause
Three interlocking issues in
extensions/telegram/src/:fetch.ts
new Agent(...)/new ProxyAgent(...)/new EnvHttpProxyAgent(...)were constructed without
keepAliveTimeoutorconnections, soundici's defaults allowed the per-origin connection pool to grow
without bound and keep-alive sockets to stay open indefinitely
under steady polling load.
fetch.ts fallback dispatcher closures (IPv4-only and
IP-pinned) cache the dispatcher in a closure —
createDispatcherlazily creates it once and never releases it. A single fallback
activation pins that dispatcher's sockets to
api.telegram.orgfor the entire process lifetime.
polling-transport-state.ts
acquireForNextCycle()silentlyoverwrote
#telegramTransportwhenever the dirty flag fired,abandoning the old transport's dispatcher set. Since
markDirty()is called from the polling stall watchdog and from every caught
recoverable network error (
polling-session.ts:351and:406),repeated transient errors on a long-running session accumulate
leaks linearly.
Node's object GC does not release OS-level sockets when a dispatcher
becomes unreachable, so without an explicit
.destroy()these poolsare effectively immortal.
How to reproduce
Any long-running
openclaw-gatewaywhose upstream network pathenforces a per-client concurrent-connection limit to
api.telegram.org(commonly: a forward proxy with a bounded worker pool per upstream
origin). The leak is load-independent — each transport dirty-rebuild
adds a fresh dispatcher pool regardless of traffic volume — but the
failure mode surfaces sooner when the upstream limit is tighter.
Observed on a gateway running for two days of steady polling:
Raw TCP to the upstream proxy IP:port still succeeded (
nc -zv),proving the failure was in the upstream application-layer worker pool
rather than the TCP transport itself. Killing the gateway process
collapsed the 305 ESTABLISHED to 302 TIME_WAIT plus a handful of
still-live connections; a fresh gateway process started leaking from
zero again.
A 60-second polling harness captured 494 samples across ~8h; 228
samples were anomalous (active route timed out, every other route
healthy), all on whichever route was active at the sample time.
Design
Minimal-invasive, defensive-in-depth:
TelegramTransport.close(): Promise<void>is now a requiredpart of the transport surface. Implementations built by
resolveTelegramTransporttrack every dispatcher they own (defaultclose()destroys all of them. Caller-owned transports (built from
globalThis.fetch/ aproxyFetchthe caller already manages)expose an async no-op
close()so the surface is uniform.TelegramPollingTransportStategained adispose()method andnow closes the previous transport (fire-and-forget, errors logged
via the existing
[telegram][diag]channel) whenever the dirtyflag fires a rebuild.
TelegramPollingSession.runUntilAbort()wraps its main loopin
try / finallyand calls#transportState.dispose()on exitso every session has a paired open / close.
keepAliveTimeout: 30s,keepAliveMaxTimeout: 10min,connections: 10,pipelining: 1)are applied uniformly to all four constructor call sites. This is
not the primary fix but prevents silent regression if a future
caller forgets to invoke
close().Commits are split by concern:
fix(telegram): release undici dispatchers via TelegramTransport.close()fix(telegram): dispose polling transport on shutdown and dirty rebuilddocs(changelog): note Telegram undici dispatcher lifecycle fixTest plan
pnpm tsgo— cleanpnpm lint extensions/telegram— 0 warnings / 0 errorspnpm test:extensions(telegram project) — 92 files / 1301tests pass, including the new lifecycle coverage:
fetch.test.ts > transport lifecycle— 4 new tests covering:bounded pool configuration,
close()destroys every owneddispatcher including lazy fallbacks,
close()is idempotent,close()swallows dispatcher destroy failures.polling-transport-state.test.ts— new file, 8 tests covering:dirty rebuild closes previous transport, no-op when rebuild
keeps same instance,
dispose()closes current and isidempotent, post-dispose
acquireForNextCycle()returnsundefined.
polling-session.test.ts— 2 new tests covering:close()iscalled once on graceful
runUntilAbortexit, both old and newtransports close across a stalled-rebuild cycle.
Issue diagnosed by myself from production symptoms; root-cause
investigation and implementation assisted by
Claude Code.