Skip to content

fix(telegram): deliver final replies through Telegram flood waits - #157349

Merged
obviyus merged 9 commits into
mainfrom
fix/telegram-429-backoff
Sep 24, 2026
Merged

obviyus merged 9 commits into
mainfrom
fix/telegram-429-backoff

Conversation

@obviyus

@obviyus obviyus commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Fixes: when Telegram rate-limits a bot (429 Too Many Requests: retry after N), for example while it answers in several forum topics at once, the final answer can be lost and the user sees "I couldn't confirm the reply reached Telegram. Check OpenClaw chat history…" instead.

User Impact

User impact: under Telegram flood control the real answer is delivered after Telegram's wait. The "couldn't confirm" notice only appears when a reply still cannot be sent after a five-minute flood budget.

Why This Change Was Made

A Telegram 429 penalizes the bot token, but OpenClaw handled it per call: each send retried on its own (3 attempts), and stream previews kept their own suspension window. Previews in other topics kept spending the budget, so three consecutive 429s on a final reply exhausted the send retries and the turn fell through to the failure notice.

The per-token account limiter (account-throttler.ts) is now the only owner of flood waits:

  • One limiter per bot token: a global pause gate plus the existing per-chat budgets (grammY throttler: about 1 message/s per chat, 20/min per group).
  • A 429 closes the gate for every chat and topic on that token until retry_after. The gate keeps the later of the current and new deadline, so a shorter 429 that lands during a longer pause never shortens it. A bare 429 without retry_after gets one fixed 1 s pause. No strike count or exponential fallback carries state between responses. This follows python-telegram-bot's AIORateLimiter: a single global pause on RetryAfter, on top of proactive per-chat budgets. Telegram 429s carry parameters.retry_after, so a backoff ladder only adds shared state (and its ordering bugs) for a case Telegram does not send.
  • Final replies, deletes and other non-replaceable calls wait and retry within TELEGRAM_OUTBOUND_FLOOD_BUDGET_MS (5 min). After that, the 429 surfaces and the existing honest failure path runs.
  • Stream previews and typing are replaceable: while the gate is closed they are skipped, not queued. In a group they also yield to a pending reply in the same chat. The draft stream keeps the newest text pending and no longer spends its failure budget on skipped previews.
  • One enforcement point where a request leaves for Telegram, after every group scheduler and throttler queue wait. A closed gate holds the request back, and the caller's writer check re-runs against the current writer. Waiting and retry policy stays outside the queues. The writer check comes from the prepared sender, the API-context helper, and final stream edits. A replaced writer's stale final is never posted, even when it was queued behind another topic.
  • A 429 on a typing action (thrown by the chat-action handler) also pauses the whole token. The handler's own 401 and transient backoff is unchanged.
  • Superseded paths removed: the draft-stream suspension window, TELEGRAM_OUTBOUND_RETRY_AFTER_CAP_MS, and 429 retries in the Telegram send retry predicate.

The Telegram E2E proxy's telegramApiReject can now return a Bot API 429 with retry_after (retryAfter, 0 for a bare 429) for times consecutive matching requests. The run summary includes telegramApiRequestLog (method, at, status only, with no bodies or IDs), so live runs can prove what reached Telegram inside a flood window.

Production trace note

In the incident that surfaced this, preview edits in two topics got 429s (retry after 3/10/15). The one topic that showed the notice had its final fail with a plugin-reload error in the same window. That reload defect is handled separately. This PR fixes the 429 path, which reproduces the same notice on its own (evidence below).

Evidence

Live Telegram matrix. Setup: Telegram Test Server, a real user account, and a fresh Gateway from built dist. The fix column ran on head 2237e953b8 (row 6 on 732cf33078), the base column on b5346d6. The E2E proxy injected the faults and logged every Bot API call with a timestamp. Times are measured from the user's message.

# Scenario Base This PR
1 DM final: sendMessage gets 429 retry after 5 three times Failure notice "I couldn't confirm the reply reached Telegram…" at 14.5 s Real answer OPENCLAW_E2E_OK at 17.8 s. Retries at +5.0 / +10.0 / +15.1 s after the first 429, none inside a window
2 DM final: bare 429 without retry_after, three times (not run on base) Real answer at 5.7 s. Retries 1.0 s apart (+1.02 / +2.04 / +3.05 s), no failure notice
3 DM with progress preview (streaming progress). The preview edit gets 429 retry after 5 while an announced cron job delivers to the same bot Cron sendMessage reached Telegram inside the window (+2.4 s), typing at +3.4 s No Bot API call inside the 5 s window, in 2 of 2 runs. Cron sendMessage was held until +5.02 s, then delivered. Preview edits resumed after the window
6 Cross-chat on one bot token. The DM final gets 429 retry after 5 twice, while an announced cron job delivers into the basic group on the same bot Group sendMessage reached Telegram inside the first DM window, at +2.25 s and +2.20 s after the first 429 (2 of 2 runs) Group sendMessage held until the first window ended: +5.03 s and +5.02 s (2 of 2 runs). The DM final was delivered after the second window. No notice in either chat
5a DM happy path, no injected fault Reply at 2.34 s Reply at 2.33 s
5b Group happy path (mention), no injected fault Reply at 2.33 s Reply at 2.32 s

Not run live:

  • Row 6 detail: when the first window ends, the held group send and the DM's retry wake together. In one fix run the DM retry reached Telegram 7 ms first and drew the second injected 429 just before the group send went out. That group send was admitted after the first window with no active pause. A 429 still in flight cannot pause a request that has already left, which is the same boundary as any client-side limiter. The proxy log tags calls only as private or group, never with ids.
  • A forum group with two topics answering at once (item 3 as originally specified). The leased pool credential has only a basic group. Forum fixtures are owner-provisioned, and the harness's private-forum setup targets production Telegram. Row 6 proves the token-wide pause across two chats live, and scenario 3 proves it across two deliveries in one chat. Cross-chat and group-topic ordering are covered by the limiter and HTTP-boundary tests below.
  • Scenario 3's own final answer is not delivered on base or fix. The mock provider repeats the tool call about 30 times until the run times out; that is a pre-existing fixture behavior, not this change.

Focused tests:

  • bot-message-dispatch.progress-lifecycle.telegram-http.test.ts › "delivers the final answer through repeated Telegram flood waits" drives a real dispatch over HTTP with 3 × 429 on the final. Fails on base (visible message is the failure notice). Passes on this PR.
  • account-throttler.test.ts: a 429 in one group chat delays a send to another chat on the same token until retry_after, and a preview during the wait is skipped without an HTTP call. With no retry_after, each bare 429 pauses about 1 s (repeats do not grow the wait) and the preview yields. Two overlapping 429s (retry_after 10, then 2) keep the 10 s deadline for a send to a third chat.
  • draft-stream.test.ts: skipped (flooded) previews keep the newest text pending and do not stop the stream.
  • Also passed: lane-delivery, send.proxy, send.telegram-http, network-errors, delivery.resolve-media-local, final-delivery-lifecycle, preview.telegram-http, sendchataction-401-backoff, and the E2E proxy/scenario node --test suites. pnpm tsgo:extensions and pnpm tsgo:extensions:test are clean on the current head.

Review follow-ups (second commit), red on the previous head's production code and green on this head:

  • send.proxy.test.ts › "rechecks send authority after a flood wait on a turn-bound client". The writer is replaced during an injected 429 retry after 5: no second Bot API send, and the send fails with the authority error (red before: the stale final was sent). With a current writer the final is delivered after the wait.
  • account-throttler.test.ts › "lets a typing flood wait hold replies in another chat on the same token". A typing 429 (retry after 6) in one chat holds a sendMessage to another chat until 6 s (red before: sent immediately).

Group queue follow-up (third commit), an HTTP-boundary test in a forum group. Topic 1's send is held at the server and then answered 429 retry after 5. Topic 2 has already passed the gate and waits in the group queue behind it:

  • send.proxy.test.ts › "admits a queued group topic send only after the flood wait and for the current writer (current)": nothing reaches Telegram inside retry_after (1 request at 4.9 s), then both topics deliver. Red on the previous head: topic 2 reached Telegram inside the window.
  • "(replaced)": the group writer is replaced while topic 2 is queued, so topic 2 sends nothing and fails with the authority error. Red on the previous head: the stale topic 2 message was sent.
  • Each case is red on the previous head's limiter when run alone. In a combined run of both cases, the first case can pass on the previous head, so the per-case runs are the discriminating proof. Both pass on this head in every run, including the whole file.

Test cost (--maxWorkers=1): account-throttler.test.ts whole file 1.1 s (17 tests, 4 new, fake timers; wall 2.0 s). The new fixed-pause and overlapping-deadline cases take 12 ms and 7 ms. send.proxy.test.ts whole file 8.3 s (wall 9.9 s, 11 tests); the new authority cases take 0.1 s and 0.24 s and the new group queue cases about 0.31 s each. The new dispatch flood test takes 2.7 s in its file run (16.6 s wall, including the shared HTTP fixture startup). No real sleeps.

Proof gap: no live forum-topic run (see above). Group topics are covered at the HTTP boundary.

A 429 from Telegram now pauses every outbound call for that bot token until
retry_after (bounded exponential backoff with jitter when it is missing).
Final replies wait and retry within a five-minute delivery budget; stream
previews and typing are skipped instead of queued, and yield to a pending
reply in the same group. The account limiter is the only flood-wait owner:
send retry runners no longer retry 429 and the draft stream no longer keeps
its own suspension window.

The Telegram E2E proxy can now inject repeated 429 responses with
retry_after through telegramApiReject.
@clawsweeper

clawsweeper Bot commented Sep 24, 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.

@obviyus
obviyus marked this pull request as ready for review September 24, 2026 15:06
@openclaw-barnacle openclaw-barnacle Bot added channel: telegram Channel integration: telegram size: L labels Sep 24, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 24, 2026
@clawsweeper

clawsweeper Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 24, 2026, 3:59 PM ET / 19:59 UTC (Revision 6).

ClawSweeper review

What this changes

The Telegram plugin moves outbound 429 waits into its per-token limiter so final replies can retry while previews yield, and extends flood-control tests and Test Server fault injection.

Merge readiness

✅ Ready for maintainer review

Current main still lacks a bot-token-wide Telegram flood wait. The PR has relevant Test Server evidence and focused boundary coverage, and this review found no blocking introduced defect.

Priority: P1
Reviewed head: 732cf33078e31eab5bebd39b05afc22236c7478d

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Detailed live flood traces and discriminating boundary cases support a coherent repair, with the forum-topic live scenario disclosed as a limit.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The Telegram account limiter and final-send path were exercised in a Test Server Gateway run with injected Bot API 429s; the recorded after-fix result delivered the real answer after three waits, while focused HTTP-boundary cases cover queued forum topics and replaced writers. A live concurrent forum-topic fault run remains a disclosed coverage gap. 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): The Telegram account limiter and final-send path were exercised in a Test Server Gateway run with injected Bot API 429s; the recorded after-fix result delivered the real answer after three waits, while focused HTTP-boundary cases cover queued forum topics and replaced writers. A live concurrent forum-topic fault run remains a disclosed coverage gap. No stored-data contract changes.
Evidence reviewed 6 items Current main remains affected: The current-main account throttler has per-chat scheduling but no token-wide flood gate; the current-main send retry predicate still retries 429 per call.
Introduced flood owner: The introduced account limiter holds non-replaceable requests through a bounded token-wide gate and checks caller authority at the network admission point after queue waits.
Final-effect authority coverage: The HTTP-boundary cases check that a queued topic send does not reach Telegram during a 429 wait and that replacing its writer prevents the final send.
Findings None None.
Security None None.

How this fits together

The Telegram plugin turns agent replies and progress previews into Bot API requests. Its token limiter and group queue control when those requests reach Telegram and what users see in chats and topics.

flowchart LR
 A[Agent final reply] --> C[Telegram sender]
 B[Progress preview] --> C
 C --> D[Group queue and throttler]
 D --> E{Token flood wait active?}
 E -->|Final waits| D
 E -->|Preview yields| G[Next preview update]
 E -->|Admitted| F[Telegram Bot API]
 F --> H[User chat]
 F -->|429 retry window| E
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +241, Tests +421, Docs +23, Other +59. Total +744 across 18 files.

View PR surface stats
Area Files Added Removed Net
Source 6 358 117 +241
Tests 7 501 80 +421
Docs 2 26 3 +23
Config 0 0 0 0
Generated 0 0 0 0
Other 3 75 16 +59
Total 18 960 216 +744

Review metrics

Metric Value Why it matters
Implementation and validation growth production +241, tests +421, Test Server harness +59 lines The production growth is tied to consolidating flood policy at the token limiter, with boundary and live-scenario coverage.

Technical review

Best possible solution:

Keep one bounded flood policy in the Telegram account limiter, with final replies checked for current writer authority after every wait and queue.

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

Yes: injecting three final-send 429 responses with a five-second retry_after is a concrete path, and the PR records the failure on its base Test Server run. Current main retains the same per-call retry mechanism, though this review did not run it.

Is this the best way to solve the issue?

Yes: the existing Telegram account limiter is the narrow owner for token-wide waits, and the patch rechecks writer authority where queued requests leave for Telegram.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 510d72b2efec.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: Telegram flood control can suppress a real final reply and leave users with a delivery-warning notice.
  • merge-risk: 🚨 message-delivery: The new token-wide gate and group queue behavior directly control when final replies and previews reach Telegram.
  • 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): The Telegram account limiter and final-send path were exercised in a Test Server Gateway run with injected Bot API 429s; the recorded after-fix result delivered the real answer after three waits, while focused HTTP-boundary cases cover queued forum topics and replaced writers. A live concurrent forum-topic fault run remains a disclosed coverage gap. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The Telegram account limiter and final-send path were exercised in a Test Server Gateway run with injected Bot API 429s; the recorded after-fix result delivered the real answer after three waits, while focused HTTP-boundary cases cover queued forum topics and replaced writers. A live concurrent forum-topic fault run remains a disclosed coverage gap. No stored-data contract changes.
  • proof: telegram-e2e: This PR needs Telegram Test Server proof with the repository E2E skill. Under a flood wait, Telegram users visibly receive the final answer instead of a delivery-warning notice.

Evidence

What I checked:

  • Current main remains affected: The current-main account throttler has per-chat scheduling but no token-wide flood gate; the current-main send retry predicate still retries 429 per call. (extensions/telegram/src/account-throttler.ts:188, 510d72b2efec)
  • Introduced flood owner: The introduced account limiter holds non-replaceable requests through a bounded token-wide gate and checks caller authority at the network admission point after queue waits. (extensions/telegram/src/account-throttler.ts:135, 732cf33078e3)
  • Final-effect authority coverage: The HTTP-boundary cases check that a queued topic send does not reach Telegram during a 429 wait and that replacing its writer prevents the final send. (extensions/telegram/src/send.proxy.test.ts:162, 732cf33078e3)
  • Live behavior evidence: The captured PR body reports a Telegram Test Server before/after run: three injected final-send 429s produced the failure notice on base and delivered the answer after the waits on head 2237e95. It also reports a token-wide pause during concurrent delivery. The author explicitly notes that a live concurrent forum-topic fault run was unavailable; the forum case is covered at the HTTP boundary. (2237e953b8bc)
  • Previous review continuity: The captured current PR body now describes a fixed one-second pause for bare 429s, addressing the previous review's documentation request. Earlier writer, typing, and group-queue concerns have corresponding introduced boundary cases. (extensions/telegram/src/account-throttler.test.ts:416, 732cf33078e3)
  • Area history: Current-main history shows earlier Telegram account-limiter work by gaoanze888, merged delivery work by Ayaan Zaidi, and recent limiter and stream refactors by Peter Steinberger. Exact source-line introduction could not be established from the partial local object set. (extensions/telegram/src/account-throttler.ts, 510d72b2efec)

Likely related people:

  • obviyus: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • gaoanze888: 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-09-24T15:14:25.958Z sha 13947ee :: needs real behavior proof before merge. :: [P1] Recheck writer authority before each flood retry | [P2] Feed typing 429s into the shared flood gate
  • reviewed 2026-09-24T16:07:13.998Z sha ae2ab24 :: needs real behavior proof before merge. :: [P1] Recheck the flood gate inside the group request queue
  • reviewed 2026-09-24T16:48:26.114Z sha 731418d :: needs maintainer review before merge. :: none
  • reviewed 2026-09-24T17:20:16.773Z sha 549cb8e :: blocked before merge. :: [P2] Preserve newer flood strikes when an older request succeeds
  • reviewed 2026-09-24T19:11:56.820Z sha 2237e95 :: needs changes before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Sep 24, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 24, 2026
@clawsweeper clawsweeper Bot added 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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 24, 2026
@obviyus
obviyus merged commit bb6bb77 into main Sep 24, 2026
224 checks passed
@obviyus
obviyus deleted the fix/telegram-429-backoff branch September 24, 2026 21:27
@obviyus

obviyus commented Sep 24, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in bb6bb77.

  • Bug: a Telegram 429 penalizes the whole bot token, but sends retried per call and previews in other chats kept sending, so a final reply could exhaust its retries and the user saw the generic "couldn't confirm" notice.
  • Fix: one limiter per bot token holds a global pause until retry_after (a bare 429 pauses 1 s; overlapping pauses keep the later deadline), checked at the network edge with the writer re-check; finals retry within a five-minute budget while previews step aside. Same model as python-telegram-bot's AIORateLimiter, on top of grammY's proactive throttler.
  • Proof: live Telegram Test Server runs, base vs fix: DM finals under 3 × 429 (notice vs real answer), bare 429s, a preview flood holding a concurrent delivery, a DM flood holding a group delivery across chats, and unchanged happy-path latency; focused limiter, proxy and dispatch tests.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 25, 2026
…enclaw#157349)

## What Problem This Solves

Fixes: when Telegram rate-limits a bot (`429 Too Many Requests: retry after N`), for example while it answers in several forum topics at once, the final answer can be lost and the user sees "I couldn't confirm the reply reached Telegram. Check OpenClaw chat history…" instead.

## User Impact

User impact: under Telegram flood control the real answer is delivered after Telegram's wait. The "couldn't confirm" notice only appears when a reply still cannot be sent after a five-minute flood budget.

## Why This Change Was Made

A Telegram 429 penalizes the bot token, but OpenClaw handled it per call: each send retried on its own (3 attempts), and stream previews kept their own suspension window. Previews in other topics kept spending the budget, so three consecutive 429s on a final reply exhausted the send retries and the turn fell through to the failure notice.

The per-token account limiter (`account-throttler.ts`) is now the only owner of flood waits:

- One limiter per bot token: a global pause gate plus the existing per-chat budgets (grammY throttler: about 1 message/s per chat, 20/min per group).
- A 429 closes the gate for every chat and topic on that token until `retry_after`. The gate keeps the later of the current and new deadline, so a shorter 429 that lands during a longer pause never shortens it. A bare 429 without `retry_after` gets one fixed 1 s pause. No strike count or exponential fallback carries state between responses. This follows python-telegram-bot's `AIORateLimiter`: a single global pause on `RetryAfter`, on top of proactive per-chat budgets. Telegram 429s carry `parameters.retry_after`, so a backoff ladder only adds shared state (and its ordering bugs) for a case Telegram does not send.
- Final replies, deletes and other non-replaceable calls wait and retry within `TELEGRAM_OUTBOUND_FLOOD_BUDGET_MS` (5 min). After that, the 429 surfaces and the existing honest failure path runs.
- Stream previews and typing are replaceable: while the gate is closed they are skipped, not queued. In a group they also yield to a pending reply in the same chat. The draft stream keeps the newest text pending and no longer spends its failure budget on skipped previews.
- One enforcement point where a request leaves for Telegram, after every group scheduler and throttler queue wait. A closed gate holds the request back, and the caller's writer check re-runs against the current writer. Waiting and retry policy stays outside the queues. The writer check comes from the prepared sender, the API-context helper, and final stream edits. A replaced writer's stale final is never posted, even when it was queued behind another topic.
- A 429 on a typing action (thrown by the chat-action handler) also pauses the whole token. The handler's own 401 and transient backoff is unchanged.
- Superseded paths removed: the draft-stream suspension window, `TELEGRAM_OUTBOUND_RETRY_AFTER_CAP_MS`, and 429 retries in the Telegram send retry predicate.

The Telegram E2E proxy's `telegramApiReject` can now return a Bot API 429 with `retry_after` (`retryAfter`, `0` for a bare 429) for `times` consecutive matching requests. The run summary includes `telegramApiRequestLog` (`method`, `at`, `status` only, with no bodies or IDs), so live runs can prove what reached Telegram inside a flood window.

<details><summary>Production trace note</summary>

In the incident that surfaced this, preview edits in two topics got 429s (`retry after 3/10/15`). The one topic that showed the notice had its final fail with a plugin-reload error in the same window. That reload defect is handled separately. This PR fixes the 429 path, which reproduces the same notice on its own (evidence below).

</details>

## Evidence

Live Telegram matrix. Setup: Telegram Test Server, a real user account, and a fresh Gateway from built `dist`. The fix column ran on head `2237e953b8` (row 6 on `732cf33078`), the base column on `c852711`. The E2E proxy injected the faults and logged every Bot API call with a timestamp. Times are measured from the user's message.

| # | Scenario | Base | This PR |
| --- | --- | --- | --- |
| 1 | DM final: `sendMessage` gets `429 retry after 5` three times | Failure notice "I couldn't confirm the reply reached Telegram…" at 14.5 s | Real answer `OPENCLAW_E2E_OK` at 17.8 s. Retries at +5.0 / +10.0 / +15.1 s after the first 429, none inside a window |
| 2 | DM final: bare `429` without `retry_after`, three times | (not run on base) | Real answer at 5.7 s. Retries 1.0 s apart (+1.02 / +2.04 / +3.05 s), no failure notice |
| 3 | DM with progress preview (streaming `progress`). The preview edit gets `429 retry after 5` while an announced cron job delivers to the same bot | Cron `sendMessage` reached Telegram **inside** the window (+2.4 s), typing at +3.4 s | No Bot API call inside the 5 s window, in 2 of 2 runs. Cron `sendMessage` was held until +5.02 s, then delivered. Preview edits resumed after the window |
| 6 | Cross-chat on one bot token. The DM final gets `429 retry after 5` twice, while an announced cron job delivers into the basic group on the same bot | Group `sendMessage` reached Telegram **inside** the first DM window, at +2.25 s and +2.20 s after the first 429 (2 of 2 runs) | Group `sendMessage` held until the first window ended: +5.03 s and +5.02 s (2 of 2 runs). The DM final was delivered after the second window. No notice in either chat |
| 5a | DM happy path, no injected fault | Reply at 2.34 s | Reply at 2.33 s |
| 5b | Group happy path (mention), no injected fault | Reply at 2.33 s | Reply at 2.32 s |

Not run live:

- Row 6 detail: when the first window ends, the held group send and the DM's retry wake together. In one fix run the DM retry reached Telegram 7 ms first and drew the second injected 429 just before the group send went out. That group send was admitted after the first window with no active pause. A 429 still in flight cannot pause a request that has already left, which is the same boundary as any client-side limiter. The proxy log tags calls only as `private` or `group`, never with ids.
- A forum group with two topics answering at once (item 3 as originally specified). The leased pool credential has only a basic group. Forum fixtures are owner-provisioned, and the harness's private-forum setup targets production Telegram. Row 6 proves the token-wide pause across two chats live, and scenario 3 proves it across two deliveries in one chat. Cross-chat and group-topic ordering are covered by the limiter and HTTP-boundary tests below.
- Scenario 3's own final answer is not delivered on base or fix. The mock provider repeats the tool call about 30 times until the run times out; that is a pre-existing fixture behavior, not this change.

Focused tests:

- `bot-message-dispatch.progress-lifecycle.telegram-http.test.ts` › "delivers the final answer through repeated Telegram flood waits" drives a real dispatch over HTTP with 3 × 429 on the final. **Fails on base** (visible message is the failure notice). Passes on this PR.
- `account-throttler.test.ts`: a 429 in one group chat delays a send to **another chat on the same token** until `retry_after`, and a preview during the wait is skipped without an HTTP call. With no `retry_after`, each bare 429 pauses about 1 s (repeats do not grow the wait) and the preview yields. Two overlapping 429s (`retry_after` 10, then 2) keep the 10 s deadline for a send to a third chat.
- `draft-stream.test.ts`: skipped (flooded) previews keep the newest text pending and do not stop the stream.
- Also passed: `lane-delivery`, `send.proxy`, `send.telegram-http`, `network-errors`, `delivery.resolve-media-local`, `final-delivery-lifecycle`, `preview.telegram-http`, `sendchataction-401-backoff`, and the E2E proxy/scenario `node --test` suites. `pnpm tsgo:extensions` and `pnpm tsgo:extensions:test` are clean on the current head.

Review follow-ups (second commit), red on the previous head's production code and green on this head:

- `send.proxy.test.ts` › "rechecks send authority after a flood wait on a turn-bound client". The writer is replaced during an injected `429 retry after 5`: no second Bot API send, and the send fails with the authority error (red before: the stale final was sent). With a current writer the final is delivered after the wait.
- `account-throttler.test.ts` › "lets a typing flood wait hold replies in another chat on the same token". A typing 429 (`retry after 6`) in one chat holds a `sendMessage` to another chat until 6 s (red before: sent immediately).

Group queue follow-up (third commit), an HTTP-boundary test in a forum group. Topic 1's send is held at the server and then answered `429 retry after 5`. Topic 2 has already passed the gate and waits in the group queue behind it:

- `send.proxy.test.ts` › "admits a queued group topic send only after the flood wait and for the current writer (current)": nothing reaches Telegram inside `retry_after` (1 request at 4.9 s), then both topics deliver. Red on the previous head: topic 2 reached Telegram inside the window.
- "(replaced)": the group writer is replaced while topic 2 is queued, so topic 2 sends nothing and fails with the authority error. Red on the previous head: the stale topic 2 message was sent.
- Each case is red on the previous head's limiter when run alone. In a combined run of both cases, the first case can pass on the previous head, so the per-case runs are the discriminating proof. Both pass on this head in every run, including the whole file.

Test cost (`--maxWorkers=1`): `account-throttler.test.ts` whole file 1.1 s (17 tests, 4 new, fake timers; wall 2.0 s). The new fixed-pause and overlapping-deadline cases take 12 ms and 7 ms. `send.proxy.test.ts` whole file 8.3 s (wall 9.9 s, 11 tests); the new authority cases take 0.1 s and 0.24 s and the new group queue cases about 0.31 s each. The new dispatch flood test takes 2.7 s in its file run (16.6 s wall, including the shared HTTP fixture startup). No real sleeps.

Proof gap: no live forum-topic run (see above). Group topics are covered at the HTTP boundary.

Co-authored-by: Ayaan Zaidi <[email protected]>
roboclaw-bot added a commit that referenced this pull request Sep 27, 2026
Backport Telegram #157349: bb6bb77
Backport OpenCode #158056: beadb8c
Backport Codex #156556: 07347ac

Preserve Telegram replaceability and current-writer authority through every
network queue and repeated flood wait. Restore OpenCode v1/v2 catalog and
activity using the released 2.0.16 contract, isolated cwd and preserved
launcher resolution. Normalize the documented empty activity watermark.

Prepare the selected desktop's unified Computer Use artifacts without
preseeding a renamed cache identity. Effective native disable and MCP/tool
policy precede feature enablement and replacement installation.

The development-snapshot operation-ID/filter/flag accusations were disproven
against released tag 3a103fe0aff726a4edc7492f03f7b88195d9e4c9; do not migrate
working released APIs to an unrelated development contract.

Independent correction review and 55 focused cases pass; unchanged original
proof is retained. The identical marketplace selector moved to its existing
owner and the cache-policy regression to a standalone file for frozen budgets.
Their 23 boundary cases, lint, frozen ratchets and Madge pass.
Installed CLI, Telegram Test Server and signed macOS/TCC gaps remain explicit.
Publication is held by the prepared PR size-policy decision.

Co-authored-by: Ayaan Zaidi <[email protected]>
Co-authored-by: Ben Badejo <[email protected]>
Co-authored-by: Shakker <[email protected]>
Co-authored-by: RomneyDa <[email protected]>
Co-authored-by: vyctorbrzezowski <[email protected]>
Co-authored-by: steipete <[email protected]>
Co-authored-by: jalehman <[email protected]>
obviyus added a commit that referenced this pull request Oct 18, 2026
…les (#176320)

Related: #176053, #176308

## What Problem This Solves

Fixes: agents working in a subsystem load scoped `AGENTS.md` guides that name removed code and commands, repeat root rules, and in places contradict current root rules (restart the Gateway for proof, run `check-changed.mjs` locally, avoid `importOriginal` mocks that a check now requires).

## User Impact

No user-visible change. Agents get shorter scoped guides with current names and commands and one owner per rule. Scoped `AGENTS.md` total: 98,031 → 73,215 characters (−25%). Six guides with no remaining unique rule are deleted.

## Why This Change Was Made

Every line of the 28 scoped guides was checked against `origin/main` and its history. Edits only remove or rewrite lines that are stale, duplicated, behavior-free, or in conflict with root; conflicts resolve toward current root. Lines that encode a recent maintainer decision are unchanged.

**Stale (fixed):**
- Telegram: `createTelegramTransportIngressDrain` (removed in #111214) → the monitor in `telegram-ingress-drain-factory.ts`; throttle owner → `getOrCreateAccountThrottler` (#157349).
- `src/channels`: memory profile command → `pnpm test:extensions:memory`.
- `extensions`: removed the `src/plugin-sdk/<id>.ts` facade allowance (the SDK guide forbids new ones) and the deleted `src/plugin-sdk-internal/**` path.
- `apps/macos`: `AppLaunchPresentationPolicy` → `AppLaunchRuntimePlan`.
- Embedded runner: `sessionFile` → `sessionTarget`.
- `src/gateway/server-methods`: the raw JSONL transcript warning (transcripts are SQLite); its live `appendMessageAsync` rule moved to `src/agents`. The stale `server-methods/CLAUDE.md` entries in `.gitattributes` and `.oxfmtrc.jsonc` are removed.
- `docs`: the "up to 30 pages" preview claim does not exist in `scripts/docs-dev.mjs`.

**Conflicts with root (resolved toward root):**
- acpx "restart the gateway" → validate in an isolated Gateway.
- Telegram "bot-to-bot QA lane" proof → the userbot e2e skill route in root.
- `scripts` and `apps/macos`: local `check-changed.mjs` suggestions removed (root: PR CI is the broad proof).
- `src/agents`: "avoid `importOriginal` partial mocks" → pass the real module or annotate `// mock-isolation:` (`check:test-mock-exports`).
- Embedded runner "prefer focused helper tests" → aligned with root end-to-end proof.

**Duplicates and owner moves:**
- `scripts/AGENTS.md` "Proof Rules" repeated root, the testing skill and `remote-gates.md`.
- Release mechanics in `apps/ios` and `apps/android` repeated each app's `VERSIONING.md`; guardrails stay.
- Rules that stylelint, lint scripts or tests already enforce now name the check instead of restating it.
- Core ingress-drain rules moved word for word from the Telegram guide to `src/channels/AGENTS.md`, since five channels share that monitor.
- `src/agents/tools/AGENTS.md` and `src/gateway/server-methods/AGENTS.md` deleted after moving their one live rule each into `src/agents/AGENTS.md`.
- SDK compatibility: one bullet keeps both meanings (internal callers removed freely; third-party exports need a deprecation window and maintainer approval).

**Test notes moved to their tests:** the per-test ownership notes in the litellm, lmstudio, ollama and vllm guides now sit as comments in the 20 test files they describe (several live outside the plugin folders, where those guides never loaded); the four guides are deleted. One vLLM note described a test deleted in #165813 and is dropped.

**Telegram test rules → test-audit:** the copied test-ownership rules point at the `test-audit` skill; the Telegram-specific crash-window/restart-replay rule stays.

**`openclaw-testing` skill:** the worktree hint no longer suggests local `check-changed.mjs`.

**One check instead of prose:** `scripts/check-test-helper-extension-import-boundary.mts` now also scans `src/channels/plugins/contracts/test-helpers` (zero violations today), so that guide no longer restates the boundary.

**Unchanged on purpose (recent maintainer decisions):** the Gateway session row projection contract, the UI session roster contract, the `NO_REPLY` reply rules, and the SDK SQLite removal date.

## Evidence

- Every relative link in the changed guides resolves; no file links to the deleted guides.
- `test/test-helper-extension-import-boundary.test.ts` passes; the script reports `[]` on the new root and flagged a temporary violating file during the check.
- `oxfmt` and `git diff --check` clean; the pre-commit hook ran on this commit, including the `AGENTS.md` size check.
- The 20 test files that received comments pass (318 tests, plus the shared SGLang discovery contract); comments only, no test logic changed.
- Diff: 57 files, +191/−441.

**Merge danger:** two-way door; a revert restores every guide. No runtime change. Blast radius: agent instructions for work in these directories, and one repository check that now scans one more test-helper directory.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 19, 2026
…les (openclaw#176320)

Related: openclaw#176053, openclaw#176308

## What Problem This Solves

Fixes: agents working in a subsystem load scoped `AGENTS.md` guides that name removed code and commands, repeat root rules, and in places contradict current root rules (restart the Gateway for proof, run `check-changed.mjs` locally, avoid `importOriginal` mocks that a check now requires).

## User Impact

No user-visible change. Agents get shorter scoped guides with current names and commands and one owner per rule. Scoped `AGENTS.md` total: 98,031 → 73,215 characters (−25%). Six guides with no remaining unique rule are deleted.

## Why This Change Was Made

Every line of the 28 scoped guides was checked against `origin/main` and its history. Edits only remove or rewrite lines that are stale, duplicated, behavior-free, or in conflict with root; conflicts resolve toward current root. Lines that encode a recent maintainer decision are unchanged.

**Stale (fixed):**
- Telegram: `createTelegramTransportIngressDrain` (removed in openclaw#111214) → the monitor in `telegram-ingress-drain-factory.ts`; throttle owner → `getOrCreateAccountThrottler` (openclaw#157349).
- `src/channels`: memory profile command → `pnpm test:extensions:memory`.
- `extensions`: removed the `src/plugin-sdk/<id>.ts` facade allowance (the SDK guide forbids new ones) and the deleted `src/plugin-sdk-internal/**` path.
- `apps/macos`: `AppLaunchPresentationPolicy` → `AppLaunchRuntimePlan`.
- Embedded runner: `sessionFile` → `sessionTarget`.
- `src/gateway/server-methods`: the raw JSONL transcript warning (transcripts are SQLite); its live `appendMessageAsync` rule moved to `src/agents`. The stale `server-methods/CLAUDE.md` entries in `.gitattributes` and `.oxfmtrc.jsonc` are removed.
- `docs`: the "up to 30 pages" preview claim does not exist in `scripts/docs-dev.mjs`.

**Conflicts with root (resolved toward root):**
- acpx "restart the gateway" → validate in an isolated Gateway.
- Telegram "bot-to-bot QA lane" proof → the userbot e2e skill route in root.
- `scripts` and `apps/macos`: local `check-changed.mjs` suggestions removed (root: PR CI is the broad proof).
- `src/agents`: "avoid `importOriginal` partial mocks" → pass the real module or annotate `// mock-isolation:` (`check:test-mock-exports`).
- Embedded runner "prefer focused helper tests" → aligned with root end-to-end proof.

**Duplicates and owner moves:**
- `scripts/AGENTS.md` "Proof Rules" repeated root, the testing skill and `remote-gates.md`.
- Release mechanics in `apps/ios` and `apps/android` repeated each app's `VERSIONING.md`; guardrails stay.
- Rules that stylelint, lint scripts or tests already enforce now name the check instead of restating it.
- Core ingress-drain rules moved word for word from the Telegram guide to `src/channels/AGENTS.md`, since five channels share that monitor.
- `src/agents/tools/AGENTS.md` and `src/gateway/server-methods/AGENTS.md` deleted after moving their one live rule each into `src/agents/AGENTS.md`.
- SDK compatibility: one bullet keeps both meanings (internal callers removed freely; third-party exports need a deprecation window and maintainer approval).

**Test notes moved to their tests:** the per-test ownership notes in the litellm, lmstudio, ollama and vllm guides now sit as comments in the 20 test files they describe (several live outside the plugin folders, where those guides never loaded); the four guides are deleted. One vLLM note described a test deleted in openclaw#165813 and is dropped.

**Telegram test rules → test-audit:** the copied test-ownership rules point at the `test-audit` skill; the Telegram-specific crash-window/restart-replay rule stays.

**`openclaw-testing` skill:** the worktree hint no longer suggests local `check-changed.mjs`.

**One check instead of prose:** `scripts/check-test-helper-extension-import-boundary.mts` now also scans `src/channels/plugins/contracts/test-helpers` (zero violations today), so that guide no longer restates the boundary.

**Unchanged on purpose (recent maintainer decisions):** the Gateway session row projection contract, the UI session roster contract, the `NO_REPLY` reply rules, and the SDK SQLite removal date.

## Evidence

- Every relative link in the changed guides resolves; no file links to the deleted guides.
- `test/test-helper-extension-import-boundary.test.ts` passes; the script reports `[]` on the new root and flagged a temporary violating file during the check.
- `oxfmt` and `git diff --check` clean; the pre-commit hook ran on this commit, including the `AGENTS.md` size check.
- The 20 test files that received comments pass (318 tests, plus the shared SGLang discovery contract); comments only, no test logic changed.
- Diff: 57 files, +191/−441.

**Merge danger:** two-way door; a revert restores every guide. No runtime change. Blast radius: agent instructions for work in these directories, and one repository check that now scans one more test-helper directory.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: telegram Channel integration: telegram merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. 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