Repository navigation
improve(telegram): polling workers start faster and use half the memory - #190890
vincentkoc merged 4 commits into
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThis PR keeps debug capture dependencies out of Telegram polling workers when capture is disabled. Example: Starting a Telegram polling worker with debug capture disabled on the recorded Linux build.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review This PR remains useful: current main still loads optional capture dependencies into polling workers, and the focused extraction preserves transport behavior without actionable defects. Reviewed head: Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe Telegram parent creates one polling worker per account; each worker fetches Bot API updates and advances its offset after the parent acknowledges durable enqueue. flowchart TD
A[Telegram polling session] --> B[Parent worker factory]
B --> C[Polling worker]
C --> D[Shared transport core]
C --> E[Optional capture adapter]
E --> D
D --> F[Telegram Bot API]
C --> G[Parent durable ingress queue]
Technical reviewBest possible solution: Keep one shared transport implementation and load its existing capture adapter only for workers whose parent enables capture. Do we have a high-confidence way to reproduce the issue? Current-main source confirms the eager import chain, and the supplied paired built-worker measurements quantify its cost; this read-only review ran no target code. Is this the best way to solve the issue? The extraction removes the unnecessary worker dependency graph while retaining the existing transport and capture owners, making it a focused solution to the measured problem. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 3bd892f5a2eb. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +52, Tests +11, Other +296. Total +359 across 12 files. Added test files: 0. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (2 earlier review cycles)
Reviewed November 26, 2026, 5:31 AM ET / 10:31 UTC (Revision 3). |
93c77fd to
e48dff8
Compare
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
e48dff8 to
88cf484
Compare
There was a problem hiding this comment.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.
Each Telegram polling account runs getUpdates in its own worker thread. The worker imported the transport through fetch.ts, whose static plugin-sdk/proxy-capture import evaluated the capture store graph even though capture is off unless OPENCLAW_DEBUG_PROXY_ENABLED is set. The worker runtime also took its marker from the parent factory module, which pulled in process-runtime. Move the transport core to fetch-transport.ts and pass the capture owner functions in as an option. fetch.ts keeps resolveTelegramTransport and resolveTelegramFetch and supplies the SDK functions, so main-thread callers keep capture. The parent passes resolveDebugProxySettings().enabled to the worker, which imports fetch.js only then and only after its stop listener is registered. The marker moves to a side-effect-free module. The six type assertions that move with the transport get SAFETY comments, so its assertion baseline entry goes away. Built worker against a loopback Bot API, 10 alternating samples (scripts/perf/telegram-ingress-worker-measure.mjs): evaluated modules 1,794 -> 550, heap after full GC 42.2 -> 21.9 MiB, first poll-success 487 -> 202 ms (worker CPU 484 -> 199 ms), steady CPU per empty poll 3.04 -> 2.88 ms. Poll sequence and acked update ids match. Under `openclaw proxy run`, a Gateway with one polling account records the worker's getUpdates exchanges the same way on both builds. Whole Gateway with three polling accounts, 5 alternating boots per arm: each Telegram worker heap 42.1 -> 21.8 MiB, process RSS 1,881 -> 1,786 MiB, main heap and spawn -> /healthz time unchanged.
88cf484 to
214a341
Compare
Baseline-Refresh: c0459e5544d2bcbbfbb3602a78d3a845ca818f4e
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
…oid-chat-preview-grapheme-boundary * commit '0bea7ecb3029583dd49d83f760d4f40c9e1f543c': (129 commits) fix(android): settle startup before checking archive refresh (#205891) fix: Gateway retains completed reply runtimes after catalog reloads (#195479) fix: clear unused-export failures in dependency checks (#205905) refactor: share browser routing for meeting captions and cleanup (#205916) fix(ui): update Workshop file preview mode (#205872) refactor(android): decouple shared JSON values from node handlers (#202840) fix(ci): remove bot credit from release notes (#205914) fix: pause interrupted shell turns when their result is unknown (#205859) fix(ui): skip publication options for removed workspaces (#205909) fix: preserve indentation in document previews (#205834) improve(ci): avoid full fixture builds for volume checks (#205903) refactor(android): derive connection readiness from its owner (#202898) fix: preserve side chat text when dictating at the limit (#205710) improve(telegram): polling workers start faster and use half the memory (#190890) fix: keep speaker identities distinct in meeting notes (#205860) fix: wait for cancellation before releasing ACP test preparation (#205893) fix: bound workers retained after deleting sessions across agents (#197409) fix(memory): keep a child's memory audience after its parent resets (#205887) refactor(android): give installed skills one data owner (#202892) fix(cli): share process failure listeners across invocations (#205732) ...
…ry (openclaw#190890) * improve(telegram): polling workers start faster and use half the memory Each Telegram polling account runs getUpdates in its own worker thread. The worker imported the transport through fetch.ts, whose static plugin-sdk/proxy-capture import evaluated the capture store graph even though capture is off unless OPENCLAW_DEBUG_PROXY_ENABLED is set. The worker runtime also took its marker from the parent factory module, which pulled in process-runtime. Move the transport core to fetch-transport.ts and pass the capture owner functions in as an option. fetch.ts keeps resolveTelegramTransport and resolveTelegramFetch and supplies the SDK functions, so main-thread callers keep capture. The parent passes resolveDebugProxySettings().enabled to the worker, which imports fetch.js only then and only after its stop listener is registered. The marker moves to a side-effect-free module. The six type assertions that move with the transport get SAFETY comments, so its assertion baseline entry goes away. Built worker against a loopback Bot API, 10 alternating samples (scripts/perf/telegram-ingress-worker-measure.mjs): evaluated modules 1,794 -> 550, heap after full GC 42.2 -> 21.9 MiB, first poll-success 487 -> 202 ms (worker CPU 484 -> 199 ms), steady CPU per empty poll 3.04 -> 2.88 ms. Poll sequence and acked update ids match. Under `openclaw proxy run`, a Gateway with one polling account records the worker's getUpdates exchanges the same way on both builds. Whole Gateway with three polling accounts, 5 alternating boots per arm: each Telegram worker heap 42.1 -> 21.8 MiB, process RSS 1,881 -> 1,786 MiB, main heap and spawn -> /healthz time unchanged. * fix(perf): bound Telegram worker samples and match capture modes * fix(telegram): preserve dispatcher deadlines in the slim transport --------- Co-authored-by: boeingchoco <[email protected]> Co-authored-by: Vincent Koc <[email protected]>
Closes #190889
What Problem This Solves
Each Telegram polling account runs
getUpdatesin its own worker thread, and every worker loads the debug proxy capture store (about 1,250 modules, roughly 20 MiB of heap) even though capture is off unlessOPENCLAW_DEBUG_PROXY_ENABLEDis set. A Gateway with three bot accounts carries about 60 MiB for code that never runs, and every polling restart pays the import again.User Impact
Each Telegram polling worker holds about half the heap (42.2 → 21.9 MiB) and reaches its first successful poll in less than half the time (487 → 202 ms). With debug proxy capture enabled, the worker records
getUpdatesexchanges exactly as it does on main.Why This Change Was Made
The worker imported the transport through
fetch.ts, whose staticplugin-sdk/proxy-captureimport evaluates the capture store graph. The transport core now lives infetch-transport.tsand takes the capture owner functions as an option.fetch.tskeepsresolveTelegramTransportandresolveTelegramFetchwith the same signatures and passes the SDK functions, so main-thread callers keep capture unchanged.The parent decides capture with the owner's
resolveDebugProxySettings().enabledand passes it inworkerData. Only then does the worker importfetch.js, after its stop listener is registered. The worker marker moves to a side-effect-free protocol module; importing it from the parent factory also pulled inprocess-runtime. The six type assertions that move with the transport now carry// SAFETY:comments, so the assertion baseline loses its Telegram fetch entry instead of moving it.Evidence
Acceptance rule written before measuring: correctness identical, evaluated modules −30% or more, retained worker heap −10 MiB or more, first poll-success wall and CPU median ≤ 1.05× and p95 ≤ 1.20×, steady CPU per poll ≤ 1.05×.
Built worker against a loopback Bot API (one empty short poll, a 20-update batch acked like the parent spool, then empty polls), 10 samples per arm, order alternating each sample, idle host (load 0.2–0.7):
Both arms send the same poll sequence (offsets
null, null, 1020, timeouts0, 1, 1) and ack update 1019.Whole Gateway, built
distof each checkout, booted from a copied state with three Telegram polling accounts inside a network-less sandbox (the workers stay in their poll retry loop, which keeps the import cost and drops the traffic). 5 boots per arm, order flipping each round, idle host (load 0.35–0.91). Each boot waits for/healthz, settles 120 s, then opens Node's inspector withSIGUSR1, forces a full GC in every isolate and readsRuntime.getHeapUsageper worker. Rule written before the run: Telegram worker heap median −10 MiB or more each, process RSS median not higher, spawn →/healthzmedian ≤ 1.10×./healthz200The Telegram heap spread is under 0.03 MiB in both arms. The fifth boot of each arm had extra non-Telegram workers (29 and 27 instead of 23), which raises that boot's RSS in both arms and leaves the medians unchanged.
Capture enabled, whole Gateway: fresh state, one Telegram polling account whose
apiRootpoints at a loopback fake Bot API (firstgetUpdatesempty, the second returns update 5000, then empty), network-less sandbox, one run per build:The Gateway child gets its own state dir because
proxy runholds the owner lease of its own. The run stops after the fifthgetUpdates(still in flight at shutdown, so four pairs are recorded);openclaw proxy sessions --jsonthen lists oneproxy-runsession (34 events on this branch, 36 on main; the extra two are the sandbox's failed DNS lookups for update checks). These are thegetUpdatesrows of that session'scapture_events, with the bot token replaced by<token>and the loopbackhost:portby<fake-bot-api>:The stored batch response is
{"ok":true,"result":[{"update_id":5000,"message":{"message_id":1,"date":1793577600,"chat":{"id":4242,"type":"private"},"from":{"id":4242,"is_bot":false,"first_name":"Proof"},"text":"capture proof"}}]}(synthetic). Main records the same eight rows (its first two responses land in the other order), and both builds record the same 14 main-thread Telegram rows (getMe,deleteWebhook,deleteMyCommands,setMyCommands,sendMessage). On this branch the worker's transport records only when the worker loadedfetch.jsfrom the parent'sdebugProxyCaptureflag, so these rows also show that flag reaching the worker.When the Gateway owns capture itself (
OPENCLAW_DEBUG_PROXY_ENABLED=1withoutproxy run), both builds record those main-thread rows and none of the worker'sgetUpdates: the worker's capture store open is refused withShared-state admission requires the host broker, becauseopenSharedStateSqliteWorkerStorerejects callers off the main thread. That is the same on main, and this PR does not change it.Measured on
0ce08d269ff, and the capture runs use the same two builds. The branch is rebased ontofc6dff488cewithout conflicts;0ce08d269ff..fc6dff488cedoes not touchextensions/telegram,src/proxy-captureor the proxy CLI, and the SAFETY comments and the dropped marker re-export added after the measurements do not change runtime code. The checks below were rerun on the rebased branch.Tests: Telegram fetch, keepalive, ingress worker (factory, runtime, deadline, context) and polling session, plus
src/proxy-capture/coverage.test.ts: 8 files, 72 tests pass. No unit case is added: the capture run above shows the parent's debug proxy setting reaching the worker and the worker recording itsgetUpdatesexchanges.pnpm tsgo:extensions,pnpm tsgo:extensions:test,pnpm deadcode:exports, oxlint and oxfmt pass, and the CI baseline ratchets (check:baseline-ratchets, max-lines, line-cap, assertion-safety, database worker and dialect, timeout race, mock exports) pass against the PR basefc6dff488ce.Overlap: open #151923 also edits
extensions/telegram/src/fetch.ts(dispatcher pool options). The changes are independent, but git will report a conflict for whichever lands second, and that branch moves itsfetch.tsedits intofetch-transport.ts.Diff shape
git diff -M -Bshowsfetch.ts → fetch-transport.tsas a 95% similar copy; the changes there are the type-only SDK import, thedebugProxyCaptureoption, the early return incaptureResponse, andresolveTelegramFetchmoving to the newfetch.ts.scripts/lib/type-assertion-guard-scope.mjsfollows the existing chained assertions to the new path, and the SAFETY comments remove the file's line fromconfig/assertion-safety-baseline.txt.polling-session.test.tsimports the marker from the protocol module.Integrated worker measurements
The integrated candidate
3d49ac4f8a37preserves the shared dispatcher pool, upload deadlines and the most recently acknowledged update ID. I compared it with its main baseline4934b24699c0on the same Linux x64 host using Node 24.22.1 and the repository build. Each arm ran ten fresh polling workers, alternating the order of the two builds.Retained heap fell by 19.33 MiB per polling worker. All seven comparison thresholds passed. The whole-Gateway RSS figures earlier in this description remain the contributor’s measurements on the earlier build.
With capture enabled, each built worker persisted six complete
telegram-fetchrequest/response flows for successfulgetUpdatescalls against the loopback Bot API. Both arms acknowledged update 1019 and polled next with offset 1020. The paired worker harness sets the worker option directly, so the two factory assertions separately cover how the parent selects disabled and enabled capture.Both production builds passed. Nine transport and worker test files passed all 78 cases. Forced worker exit and a stalled sample both produced the expected nonzero result within their deadline and cleaned their temporary state. Integrated CI