Skip to content

fix(telegram): photo albums split into several replies when the Gateway is under CPU load - #163863

Merged
steipete merged 4 commits into
mainfrom
steipete/telegram-lane-aware-buffer-flush
Oct 3, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/telegram-lane-aware-buffer-flush

Conversation

@steipete

@steipete steipete commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: Telegram photo albums and multi-message forwards split into several agent turns and replies when the Gateway host is under heavy CPU load, even though Telegram delivered every member in a single getUpdates response.

User Impact

User impact: a photo album or forward burst reaches the agent as one turn with one reply on a busy or slow host, as it already does on an idle one. Quiet windows are unchanged (500 ms for albums, 1 s for forwards), so latency on a healthy host is unchanged. There is no new config, storage, or payload change.

Why This Change Was Made

The album and forward quiet timers start at each member's local buffer entry. Members reach the buffer one at a time through the serialized ingress lane: a drain claim pass, then per-member authorize, session state, dispatch-dedupe claim, and reply-chain record. Under CPU starvation those stretched to 0.6–1.7 s per member.

Live probes showed that in 47 of 48 starved member transitions, the next member was already durably spooled before the previous member even entered the buffer. The window was measuring the Gateway's local lane pace, not Telegram's delivery gaps, so enlarging it would only chase load.

Now, when a quiet timer fires, the buffer asks the lane's owner whether a matching member is still pending, and holds instead of flushing if so:

  • Core. The ingress drain gains an optional, pure readLaneBacklog() on the dispatch lifecycle. It returns same-lane durable rows not yet handed off. The drain stays the single owner of lane state.
  • SDK debouncer. createInboundDebouncer gains an optional shouldHoldFlush(items) hook. It is consulted only on quiet-timer expiry before the existing deadline. Appends supersede an in-flight check, explicit flushes bypass it, and a failing check flushes.
  • Telegram albums. The buffer holds while a row with the same media_group_id and chat is pending. A fixed 20 s deadline bounds holds, including a stalled read and a hold re-arm. It never shortens the normal window for a member Telegram just delivered.
  • Telegram forwards. The buffer holds while a forwarded row from the same sender and chat is pending. The existing 5 s batch deadline bounds it.

This branch is rebased over #163926, which keeps queued albums alive and ordered per conversation. Its album flush now closes the album's already-reserved collection (collectionClosed) instead of enqueueing, so both changes compose: holds decide when collection closes, and #163926 owns queue order and claim liveness.

Release note context: Telegram photo albums and multi-message forwards no longer split into several replies when the Gateway host is under heavy CPU load.

Evidence

Live Telegram Test Server, DM lane, clawstudio.

  • Harness. The telegram-e2e-userbot scenario send.photos and forwardBurst actions, with unique small photos per album.
  • Starvation. The test Gateway alone was starved with taskpolicy -b, plus background-band CPU burners that only contend for efficiency cores.
  • Probes. Logging-only stage probes, not committed.
Build Run Result Agent turns
Base 4 4 of 6 albums split (1+2, 2+1+1 plus a replay, 1+2, 3+1) 10 for 6 albums; 2 rows tripped the 5-minute stall watchdog and replayed
This PR 6 0 of 6 albums split 6 for 6 albums
This PR 7 (heavier contention) 0 of 3 albums and 0 of 3 forward bursts split 6 for 6 actions
  • Two live holds fired. Each covered a gap that would have split (1,258 ms and 1,728 ms between buffer entries), with the pending member already spooled.
  • Every other hold check returned false, so the fix adds no latency when nothing is pending.
  • No stall or replay occurred in the fixed runs.

Tests. Each new regression fails against the previous production code. The forced-flush and unrelated-backlog controls pass on both.

  • Core backlog read (src/channels/message/ingress-drain-lanes.test.ts, 7 tests). Covers ordering, plus exclusion of self, other lanes, retry-delayed rows, and released claims. Vitest suite 2.8 s on Testbox.
  • SDK hold hook (src/auto-reply/inbound-debounce.test.ts, 27 tests). Covers re-arm, append supersession, the deadline with resolved and pending checks, and explicit flush bypass. Suite 0.1 s on Testbox. The grouped pnpm test <both files> --maxWorkers=1 command took 24.9 s of wall time.
  • Telegram durable coalescing (extensions/telegram/src/telegram-ingress-coalescing.e2e.test.ts, 21 cases after the rebase, including fix(telegram): back-to-back photo albums replay or arrive out of order while the agent is busy #163926's; command 39.3 s on Testbox before the shared harness moved into telegram-ingress-coalescing-fixture.test-support.ts to satisfy max-lines). Covers album and forward holds, an unrelated plain-text control, a deadline that bounds a stalled backlog read, and a deadline that caps a hold re-arm.
  • Album fixture (extensions/telegram/src/bot.create-telegram-bot.channel-post-media.test.ts, 20 tests). Adapted to asynchronous queue admission after the backlog read. Suite 1.8 s on Testbox, run with bot.create-telegram-bot.test.ts in a 77.4 s command.

CI notes.

  • The first head's QA Smoke CI (profile 2/4) failed in subagent-empty-completion-recovery (subagent finalization, untouched here). It passed on the rebased head.
  • checks-ui-e2e failed on the rebased head, and on unrelated PRs, in board-mcp-app.e2e.test.ts. That was red main from fix(ui): confirm app messages inside the app view instead of a native dialog #164493: a board-level display: block collapsed the fullscreen MCP App frame. It was fixed directly on main in 11515ce, and this PR touches no UI files.
  • One local run of the coalescing suite under host load hit an intermittent agent-DB owner leak in a pre-existing shutdown test. Two head and two base reruns passed, so it isn't attributable to this change. It is filed as a follow-up.

Gates.

  • tsgo:core, tsgo:extensions, oxlint, oxfmt, plugin-sdk:check-exports, and plugin-sdk:surface:check pass.
  • plugin-sdk:api:diff shows no entrypoint additions or removals; the change is an additive optional member and an optional hook.
  • Autoreview (Codex, P2) is scoped-clean on the final branch.

@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation channel: telegram Channel integration: telegram size: L labels Oct 2, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 2, 2026
@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 3, 2026, 6:56 PM ET / 22:56 UTC (Revision 6).

ClawSweeper review

What this changes

The branch adds bounded checks for queued Telegram album and forward-burst members so slow local processing does not split them into separate replies.

Merge readiness

✅ Ready for maintainer review

This fix remains necessary: current main still flushes albums without checking queued members, and the merged ordering repair addresses a different failure. The live Telegram evidence supports the change, and no blocking introduced defect was found.

Priority: P1
Reviewed head: 2d3e64afd23d5659d4a8ed199d0990e123487b47

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with strong live before/after evidence, bounded asynchronous behavior, and useful regression coverage.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Real Telegram Test Server userbot actions exercised the changed album and forward buffers through a CPU-starved Gateway, with queued-member holds observed and no splits in the fixed runs. Deadline regressions supplement that live evidence. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Real Telegram Test Server userbot actions exercised the changed album and forward buffers through a CPU-starved Gateway, with queued-member holds observed and no splits in the fixed runs. Deadline regressions supplement that live evidence. No stored-data contract changes.
Evidence reviewed 8 items Pinned introduction and merge result: Reviewed the merge-base-to-head introduced changes. The test merge's raw parents are exactly the supplied main revision followed by the pinned PR head; its lifecycle delta preserves the optional backlog reader.
Bounded collection and owner separation: The core reader filters by conversation lane, excludes the current event, delayed retries, and handed-off local claims. Album collection fences asynchronous results by entry and revision, bounds stalled reads and hold re-arms, and preserves newly joined members' quiet windows.
Current main still needs the fix: Current main's album timers directly delete the buffer and close collection; its generic debouncer directly flushes on timer expiry. Neither path checks already-spooled matching members.
Findings None None.
Security None None.

How this fits together

Telegram updates enter a durable queue before the core drain hands them to the plugin. The plugin collects related messages into one agent turn, which produces the chat reply.

flowchart TD
  A[Telegram updates] --> B[Durable ingress queue]
  B --> C[Core conversation drain]
  C --> D[Album and forward buffers]
  D --> E{Matching members still queued?}
  E -->|Yes, before deadline| D
  E -->|No, or deadline reached| F[One collected agent turn]
  F --> G[Telegram reply]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +182, Tests +465, Docs +13. Total +660 across 14 files.

View PR surface stats
Area Files Added Removed Net
Source 7 198 16 +182
Tests 4 691 226 +465
Docs 3 14 1 +13
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 903 243 +660

Review metrics

Metric Value Why it matters
Production versus regression growth production +182 net lines; tests and test support +465 net lines Production growth implements the documented backlog seam and bounded asynchronous collection; regression growth covers distinct drain, debounce, and Telegram boundaries.

Technical review

Best possible solution:

Keep collection timing in Telegram and expose queued-member facts through the existing core drain, preserving delivery windows and bounded flush deadlines.

Do we have a high-confidence way to reproduce the issue?

Yes: queue a matching member before the quiet timer expires while delaying its local dispatch. Current-main source flushes the earlier member, and the supplied live base run demonstrates the same failure under CPU contention; this reviewer did not execute it.

Is this the best way to solve the issue?

Yes: checking already-durable matching input addresses the local-processing delay directly, while enlarging quiet windows would add latency and continue chasing host load.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 8db9539ee84a.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: Real Telegram albums and forward bursts split into multiple agent turns under host load, disrupting an established channel workflow.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Real Telegram Test Server userbot actions exercised the changed album and forward buffers through a CPU-starved Gateway, with queued-member holds observed and no splits in the fixed runs. Deadline regressions supplement that live evidence. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. Real Telegram Test Server userbot actions exercised the changed album and forward buffers through a CPU-starved Gateway, with queued-member holds observed and no splits in the fixed runs. Deadline regressions supplement that live evidence. No stored-data contract changes.
  • proof: telegram-e2e: This PR needs Telegram Test Server proof with the repository E2E skill. Album and forward-burst grouping changes the number of visible Telegram replies; supplied Test Server userbot evidence covers that behavior.

Evidence

What I checked:

  • Pinned introduction and merge result: Reviewed the merge-base-to-head introduced changes. The test merge's raw parents are exactly the supplied main revision followed by the pinned PR head; its lifecycle delta preserves the optional backlog reader. (src/channels/message/ingress-drain-lifecycle.ts:10, d6ebe0269887)
  • Bounded collection and owner separation: The core reader filters by conversation lane, excludes the current event, delayed retries, and handed-off local claims. Album collection fences asynchronous results by entry and revision, bounds stalled reads and hold re-arms, and preserves newly joined members' quiet windows. (extensions/telegram/src/bot-handlers.inbound-media.ts:520, 2d3e64afd23d)
  • Current main still needs the fix: Current main's album timers directly delete the buffer and close collection; its generic debouncer directly flushes on timer expiry. Neither path checks already-spooled matching members. (extensions/telegram/src/bot-handlers.inbound-media.ts:562, 8db9539ee84a)
  • Latest release check: The v2026.9.8 source also closes album buffers directly and contains no lane-backlog hold path. No shipped implementation of this fix was identified. (extensions/telegram/src/bot-handlers.inbound-media.ts:503, fc23bc864e45)
  • Live Telegram after-fix evidence: The captured PR body reports real Test Server userbot album and forward actions through a CPU-starved Gateway: base split 4 of 6 albums; fixed runs split none of 9 albums or 3 forward bursts. Two observed holds covered 1,258 ms and 1,728 ms buffer-entry gaps with the next member already spooled, and fixed runs recorded no stall or replay. The inspected downloaded images demonstrate the related UI change and were not used as Telegram proof.
  • Additive SDK repair and regression coverage: The lifecycle reader and debouncer hook are optional, documented additions through existing SDK exports. Existing callers retain their behavior when the hook is omitted. Inspected regressions cover append supersession, forced flush, pending-read deadlines, matching backlog, unrelated text, and durable restart replay. The body reports negative controls, test wall times, and SDK checks; this read-only review did not execute tests. (src/auto-reply/inbound-debounce.ts:145, 2d3e64afd23d)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • lybnnnn: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (5 earlier review cycles)
  • reviewed 2026-10-02T23:44:28.605Z sha f3040d5 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-03T20:23:00.444Z sha 75d7507 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-03T20:46:45.426Z sha 33ac7f4 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-03T21:52:44.098Z sha 75d7507 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-03T21:58:10.033Z sha 75d7507 :: needs maintainer review before merge. :: none

@steipete

steipete commented Oct 3, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added the app: web-ui App: web-ui label Oct 3, 2026
@steipete
steipete force-pushed the steipete/telegram-lane-aware-buffer-flush branch from 33ac7f4 to 75d7507 Compare October 3, 2026 21:43
@openclaw-barnacle openclaw-barnacle Bot removed the app: web-ui App: web-ui label Oct 3, 2026
@steipete

steipete commented Oct 3, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Oct 3, 2026
… are pending

Albums and multi-message forwards could split into multiple turns when local
per-member ingress work exceeded their quiet windows, even though the next
members were already durably queued.

Expose a pure same-lane backlog read on the core dispatch lifecycle through
the existing monitor and plugin SDK types. Telegram replay participants retain
that reader so album and forward buffers can match their own pending updates
before flushing. The generic debouncer owns asynchronous hold checks, append
supersession, and its existing fixed deadline and forced-flush behavior.

Keep the 500 ms album and 1 s forward quiet windows. Stop extending album
holds after the first member's 20 s hold deadline without shortening its quiet
window. Cover durable coalescing, unrelated queued text, backlog filtering,
and asynchronous debounce races.
A stalled lane-backlog read could keep an album buffered beyond its fixed
20-second hold deadline. Arm the deadline while reading and fence its flush
by the current buffer entry and revision. Clear it when the read settles;
member joins retain their fresh quiet timer and late results are ignored.

Exercise the real ingress queue with a gated backlog read, proving the
buffered member flushes at the deadline and a late result adds no turn.
A matching backlog read resolving near the album hold deadline re-armed a
full quiet window, allowing the hold to exceed its bound. Cap that hold
re-arm at the remaining deadline, as the SDK debouncer already does.

Keep the full delivery quiet window for newly joined members. Extend the
existing ingress deadline regression with a matching read released one
millisecond before the deadline.
Move deferred-turn and timer setup into the existing coalescing fixture support after combining the album hold and same-sender queue regressions. Preserve every test assertion and keep the E2E file within its line limit.
@steipete
steipete merged commit db966d6 into main Oct 3, 2026
132 checks passed
@steipete
steipete deleted the steipete/telegram-lane-aware-buffer-flush branch October 3, 2026 23:37
@steipete

steipete commented Oct 3, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 4, 2026
…ay is under CPU load (openclaw#163863)

* fix(telegram): hold album and forward flushes while same-lane members are pending

Albums and multi-message forwards could split into multiple turns when local
per-member ingress work exceeded their quiet windows, even though the next
members were already durably queued.

Expose a pure same-lane backlog read on the core dispatch lifecycle through
the existing monitor and plugin SDK types. Telegram replay participants retain
that reader so album and forward buffers can match their own pending updates
before flushing. The generic debouncer owns asynchronous hold checks, append
supersession, and its existing fixed deadline and forced-flush behavior.

Keep the 500 ms album and 1 s forward quiet windows. Stop extending album
holds after the first member's 20 s hold deadline without shortening its quiet
window. Cover durable coalescing, unrelated queued text, backlog filtering,
and asynchronous debounce races.

* fix(telegram): bound album holds while the backlog read is pending

A stalled lane-backlog read could keep an album buffered beyond its fixed
20-second hold deadline. Arm the deadline while reading and fence its flush
by the current buffer entry and revision. Clear it when the read settles;
member joins retain their fresh quiet timer and late results are ignored.

Exercise the real ingress queue with a gated backlog read, proving the
buffered member flushes at the deadline and a late result adds no turn.

* fix(telegram): cap album hold re-arm at the hold deadline

A matching backlog read resolving near the album hold deadline re-armed a
full quiet window, allowing the hold to exceed its bound. Cap that hold
re-arm at the remaining deadline, as the SDK debouncer already does.

Keep the full delivery quiet window for newly joined members. Extend the
existing ingress deadline regression with a matching read released one
millisecond before the deadline.

* test(telegram): share deferred ingress fixture setup

Move deferred-turn and timer setup into the existing coalescing fixture support after combining the album hold and same-sender queue regressions. Preserve every test assertion and keep the E2E file within its line limit.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: telegram Channel integration: telegram docs Improvements or additions to documentation P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant