Skip to content

fix(telegram): release undici dispatcher sockets on polling transport rebuild - #68128

Closed
hchen13 wants to merge 3 commits into
openclaw:mainfrom
hchen13:fix/telegram-transport-lifecycle
Closed

hchen13 wants to merge 3 commits into
openclaw:mainfrom
hchen13:fix/telegram-transport-lifecycle

Conversation

@hchen13

@hchen13 hchen13 commented Apr 17, 2026

Copy link
Copy Markdown
Contributor

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 into
hundreds 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 TelegramTransport an explicit lifecycle (close()),
wires TelegramPollingSession / TelegramPollingTransportState to
invoke it on shutdown and on every dirty rebuild, and adds bounded
keep-alive defaults (keepAliveTimeout, keepAliveMaxTimeout,
connections, pipelining) on every constructed Agent /
ProxyAgent / EnvHttpProxyAgent as defence in depth.

Root cause

Three interlocking issues in extensions/telegram/src/:

  1. fetch.ts new Agent(...) / new ProxyAgent(...) / new EnvHttpProxyAgent(...)
    were constructed without keepAliveTimeout or connections, so
    undici's defaults allowed the per-origin connection pool to grow
    without bound and keep-alive sockets to stay open indefinitely
    under steady polling load.

  2. fetch.ts fallback dispatcher closures (IPv4-only and
    IP-pinned) cache the dispatcher in a closure — createDispatcher
    lazily creates it once and never releases it. A single fallback
    activation pins that dispatcher's sockets to api.telegram.org
    for the entire process lifetime.

  3. polling-transport-state.ts acquireForNextCycle() silently
    overwrote #telegramTransport whenever 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:351 and :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 pools
are effectively immortal.

How to reproduce

Any long-running openclaw-gateway whose upstream network path
enforces 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:

# GET /connections while in failure state
total connections: 325
  299 chain: <selected proxy> / <default group> / telegram-messages
   12 DIRECT
  ...

# netstat against the upstream proxy IP:port
305 ESTABLISHED   1 LAST_ACK   1 TIME_WAIT

# all 299 originated from the gateway's TUN local IP,
# destination host api.telegram.org (fake-IP mapped)
process owner: openclaw-gateway (node)
age: median ~4h, oldest ~5h

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 required
    part of the transport surface. Implementations built by
    resolveTelegramTransport track every dispatcher they own (default
    • both fallback dispatchers once instantiated) and close()
      destroys all of them. Caller-owned transports (built from
      globalThis.fetch / a proxyFetch the caller already manages)
      expose an async no-op close() so the surface is uniform.
  • TelegramPollingTransportState gained a dispose() method and
    now closes the previous transport (fire-and-forget, errors logged
    via the existing [telegram][diag] channel) whenever the dirty
    flag fires a rebuild.
  • TelegramPollingSession.runUntilAbort() wraps its main loop
    in try / finally and calls #transportState.dispose() on exit
    so every session has a paired open / close.
  • Agent pool defaults (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:

Commit Scope
fix(telegram): release undici dispatchers via TelegramTransport.close() transport surface + tracked dispatchers + pool defaults
fix(telegram): dispose polling transport on shutdown and dirty rebuild session/state wiring
docs(changelog): note Telegram undici dispatcher lifecycle fix CHANGELOG entry

Test plan

  • pnpm tsgo — clean
  • pnpm lint extensions/telegram — 0 warnings / 0 errors
  • pnpm test:extensions (telegram project) — 92 files / 1301
    tests pass, including the new lifecycle coverage:
    • fetch.test.ts > transport lifecycle — 4 new tests covering:
      bounded pool configuration, close() destroys every owned
      dispatcher 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 is
      idempotent, post-dispose acquireForNextCycle() returns
      undefined.
    • polling-session.test.ts — 2 new tests covering: close() is
      called once on graceful runUntilAbort exit, both old and new
      transports close across a stalled-rebuild cycle.

Issue diagnosed by myself from production symptoms; root-cause
investigation and implementation assisted by
Claude Code.

@openclaw-barnacle openclaw-barnacle Bot added channel: telegram Channel integration: telegram size: L labels Apr 17, 2026
@greptile-apps

greptile-apps Bot commented Apr 17, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a multi-year socket leak in the Telegram polling transport: every dirty rebuild (stall watchdog, recoverable network error) silently abandoned undici Agent/ProxyAgent/EnvHttpProxyAgent instances without calling destroy(), letting keep-alive sockets accumulate until a per-origin upstream proxy limit was saturated. The fix introduces an explicit close(): Promise<void> surface on TelegramTransport, wires TelegramPollingTransportState to fire-and-forget close stale transports on rebuild and await-close the final transport in dispose(), and wraps runUntilAbort() in try/finally to guarantee the session lifecycle is paired. Pool bounds (keepAliveTimeout, connections, etc.) are added to all four dispatcher constructors as defence in depth. Test coverage is thorough with new lifecycle-specific suites.

Confidence Score: 5/5

Safe 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 openclaw#TBD placeholders in fetch.ts and polling-session.ts.

Prompt To Fix All 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.

---

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

Comment thread extensions/telegram/src/fetch.ts Outdated
// 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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.

Suggested change
// 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, thanks! Updated the reference to openclaw#68128 in 7415436.

Comment thread extensions/telegram/src/fetch.ts Outdated
Comment on lines +537 to +545
await Promise.allSettled(
[...dispatchers].map(async (dispatcher) => {
try {
await dispatcher.destroy();
} catch {
// Intentionally ignored: dispatcher may already be destroyed.
}
}),
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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).

Suggested change
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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +725 to +727
// 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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.

Suggested change
// 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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.

Suggested change
// 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks — filled this in as openclaw#68128 in ed1f167 alongside the fetch.ts one.

hchen13 and others added 3 commits April 17, 2026 22:48
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]>
@hchen13
hchen13 force-pushed the fix/telegram-transport-lifecycle branch from b3fbc6d to 438a2e1 Compare April 17, 2026 14:48
@steipete

Copy link
Copy Markdown
Contributor

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 TelegramTransport a real close() lifecycle, disposes stale transports in TelegramPollingTransportState, and bounds every dispatcher pool in extensions/telegram/src/fetch.ts. That directly matches the long-running gateway symptom where repeated recoveries leave old sockets around.

Suggested before merge: please fold in allowH2: false on the common dispatcher pool options too, or explicitly stack this with #69243. #66885 points at undici HTTP/2 negotiation on Windows as a separate stall trigger, and merging the lifecycle fix without the HTTP/1-only invariant leaves that regression class open.

Recommended path: merge this after adding allowH2: false coverage in extensions/telegram/src/fetch.test.ts, then re-evaluate the watchdog/liveness PRs on top.

@steipete

Copy link
Copy Markdown
Contributor

Thanks for digging into this. I landed this via #69476 / 60fea81, keeping the transport close() lifecycle and dirty-rebuild disposal, then folding it together with the HTTP/1 dispatcher and polling-health fixes. Closing this PR as superseded by the landed integration.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: telegram Channel integration: telegram size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants