Skip to content

fix(telegram): restore retry behaviour for 429 rate-limit and failed-after network errors - #40383

Closed
amittell wants to merge 4 commits into
openclaw:mainfrom
amittell:fix/telegram-retry-regressions
Closed

amittell wants to merge 4 commits into
openclaw:mainfrom
amittell:fix/telegram-retry-regressions

Conversation

@amittell

@amittell amittell commented Mar 9, 2026

Copy link
Copy Markdown
Contributor

Problem

Two retry regressions introduced by recent upstream refactors:

  • 3987ca409 (refactor(retry): simplify telegram shouldRetry composition) changed the retry path used by createTelegramNonIdempotentRequestWithDiag, which calls isSafeToRetrySendError with strictShouldRetry: true. This bypasses the TELEGRAM_RETRY_RE regex fallback and only checked PRE_CONNECT_ERROR_CODES — missing two safe-to-retry cases.
  • 59895f9c5 (fix: narrow Telegram failed-after retry match) narrowed the failed-after match too aggressively.

Both caused previously-passing tests in send.test.ts to fail.

Root cause

isSafeToRetrySendError was missing two cases:

  1. 429 + retry_after — Telegram rate-limit, message was rejected not delivered → safe to retry. Fixed by adding hasTelegramRetryAfterParameter() check.
  2. "Network request for X failed after N attempts" — grammY transport failure, request never reached Telegram → safe to retry. Fixed by adding GRAMMY_NETWORK_REQUEST_FAILED_AFTER_RE message match.

Files changed

  • src/telegram/network-errors.ts — added both missing retry classifications

Test results

  • send.test.ts: 64/64 ✅ (both previously-failing retry tests now pass)

Related

Companion to the empty-text silent-skip PR (opening simultaneously).

…after network errors

Two retry regressions introduced by recent upstream refactors:
- 3987ca4 broke 429+retry_after classification in shouldRetry
- 59895f9 narrowed failed-after regex too aggressively

Both caused by createTelegramNonIdempotentRequestWithDiag using
isSafeToRetrySendError with strictShouldRetry:true, which bypasses
the TELEGRAM_RETRY_RE fallback. isSafeToRetrySendError only checked
PRE_CONNECT_ERROR_CODES, missing:
1. 429 rate-limit errors with retry_after (safe: Telegram rejected
   without delivering)
2. grammY 'Network request for X failed after N attempts' (safe:
   transport-level failure, never reached Telegram)

Expand isSafeToRetrySendError to cover both cases. All 64 send tests pass.
Copilot AI review requested due to automatic review settings March 9, 2026 00:19
@openclaw-barnacle openclaw-barnacle Bot added channel: telegram Channel integration: telegram size: XS labels Mar 9, 2026
@greptile-apps

greptile-apps Bot commented Mar 9, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR restores two retry-safety behaviours that were inadvertently dropped by recent upstream refactors: Telegram 429 rate-limit errors (where parameters.retry_after confirms the request was never delivered) and grammY transport-level "failed after N attempts" errors are now correctly classified as safe to retry in isSafeToRetrySendError.

  • The new hasTelegramRetryAfterParameter helper correctly type-guards the parameters.retry_after field but does not enforce that the value is positive — Telegram's API always returns a positive integer, but an explicit > 0 guard would make the contract clearer.
  • The grammY failed-after path reuses the module-level GRAMMY_NETWORK_REQUEST_FAILED_AFTER_RE regex (good for consistency), but applies a redundant .toLowerCase() before testing against a regex that already carries the i flag.
  • The two new branches in isSafeToRetrySendError are indirectly validated by send.test.ts, but have no dedicated unit tests in network-errors.test.ts alongside the existing isSafeToRetrySendError suite, which is the natural home for them.

Confidence Score: 4/5

  • Safe to merge — the fix correctly restores two lost retry paths with no risk of introducing duplicate message delivery.
  • The regression is well-diagnosed, the implementation is targeted, and the new code paths are covered end-to-end in send.test.ts. The only observations are minor style points (positive retry_after guard, redundant .toLowerCase()) and a suggestion to add direct unit tests in network-errors.test.ts, none of which affect correctness.
  • No files require special attention.

Comments Outside Diff (1)

  1. src/telegram/network-errors.ts, line 124-148 (link)

    Missing unit tests for the two new isSafeToRetrySendError cases

    network-errors.test.ts has a dedicated describe("isSafeToRetrySendError", ...) block (line 110) but it only covers the PRE_CONNECT_ERROR_CODES path. The two new branches added here (429 retry_after and grammY failed-after message) have no direct unit tests in that block.

    The PR description says the tests live in send.test.ts, but it's conventional to test the observable behaviour of each exported function in its own test file. Two small additions would pin these cases to this module:

    it("allows retry for 429 rate-limit with retry_after parameter", () => {
      const err = Object.assign(new Error("Too Many Requests"), {
        parameters: { retry_after: 30 },
      });
      expect(isSafeToRetrySendError(err)).toBe(true);
    });
    
    it("allows retry for grammY failed-after transport error", () => {
      const err = new Error("Network request for 'sendMessage' failed after 3 attempts.");
      expect(isSafeToRetrySendError(err)).toBe(true);
    });
    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: src/telegram/network-errors.ts
    Line: 124-148
    
    Comment:
    **Missing unit tests for the two new `isSafeToRetrySendError` cases**
    
    `network-errors.test.ts` has a dedicated `describe("isSafeToRetrySendError", ...)` block (line 110) but it only covers the `PRE_CONNECT_ERROR_CODES` path. The two new branches added here (429 `retry_after` and grammY failed-after message) have no direct unit tests in that block.
    
    The PR description says the tests live in `send.test.ts`, but it's conventional to test the observable behaviour of each exported function in its own test file. Two small additions would pin these cases to this module:
    
    ```ts
    it("allows retry for 429 rate-limit with retry_after parameter", () => {
      const err = Object.assign(new Error("Too Many Requests"), {
        parameters: { retry_after: 30 },
      });
      expect(isSafeToRetrySendError(err)).toBe(true);
    });
    
    it("allows retry for grammY failed-after transport error", () => {
      const err = new Error("Network request for 'sendMessage' failed after 3 attempts.");
      expect(isSafeToRetrySendError(err)).toBe(true);
    });
    ```
    
    How can I resolve this? If you propose a fix, please make it concise.

    Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Last reviewed commit: 9530f87

Copilot AI left a comment

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.

Pull request overview

This PR fixes two retry regressions in Telegram send operations caused by recent upstream refactors. The isSafeToRetrySendError function (used for non-idempotent send operations like sendMessage) was missing two safe-to-retry error classifications: HTTP 429 rate-limit errors with retry_after parameters, and grammY transport-level "failed after N attempts" errors. Both error types guarantee the message was not delivered.

Changes:

  • Added hasTelegramRetryAfterParameter helper to detect Telegram 429 rate-limit errors by checking for a valid parameters.retry_after numeric field.
  • Extended isSafeToRetrySendError with two new retry-eligible conditions: 429 rate-limit errors and grammY "Network request for X failed after N attempts" transport failures.

Comment on lines +133 to +145

// 429 rate-limit with retry_after: Telegram explicitly rejected the
// request without delivering it — safe to retry after the indicated delay.
if (hasTelegramRetryAfterParameter(candidate)) {
return true;
}

// grammY "Network request for X failed after N attempts" indicates a
// transport-level failure — the request never reached Telegram.
const message = formatErrorMessage(candidate).trim().toLowerCase();
if (message && GRAMMY_NETWORK_REQUEST_FAILED_AFTER_RE.test(message)) {
return true;
}

Copilot AI Mar 9, 2026

Copy link

Choose a reason for hiding this comment

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

The isSafeToRetrySendError test suite in network-errors.test.ts does not cover the two new retry cases added here — the 429 retry_after parameter check and the grammY "failed after" message match. While send.test.ts has integration-level coverage, unit tests should be added to network-errors.test.ts for both cases to match the pattern of existing tests and guard against future regressions. For example:

  1. A test with an error that has { parameters: { retry_after: 1 } } should return true.
  2. A test with new Error("Network request for 'sendMessage' failed after 2 attempts.") should return true.
  3. A negative test with { parameters: {} } (no retry_after) should return false.

Copilot uses AI. Check for mistakes.

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.

Implemented in commit 55ceb98 — added three unit tests to the isSafeToRetrySendError describe block in network-errors.test.ts: 429+retry_after returns true, no retry_after returns false, and grammY failed-after returns true.

Comment on lines +134 to +138
// 429 rate-limit with retry_after: Telegram explicitly rejected the
// request without delivering it — safe to retry after the indicated delay.
if (hasTelegramRetryAfterParameter(candidate)) {
return true;
}

Copilot AI Mar 9, 2026

Copy link

Choose a reason for hiding this comment

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

The inline comment correctly notes that Telegram "explicitly rejected the request without delivering it," but this contradicts the function's docstring (line 118-119) which states it "Only matches errors that are guaranteed to have occurred before the request reached Telegram's servers." A 429 with retry_after is a response from Telegram — the request did reach the server, it was just rejected. Consider updating the docstring to say something like "Only matches errors where the message is guaranteed not to have been delivered" to accurately cover both pre-connect failures and server-side rejections like 429.

Copilot uses AI. Check for mistakes.

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.

Fixed in commit 55ceb98 — docstring updated to: 'Only matches errors where the message is guaranteed not to have been delivered — either before reaching Telegram's servers (pre-connect errors) or server-side rejections that explicitly indicate no delivery occurred (e.g. 429 rate-limit with retry_after).'

Comment on lines +105 to +113
function hasTelegramRetryAfterParameter(err: unknown): boolean {
if (!err || typeof err !== "object") {
return false;
}
if ("parameters" in err && err.parameters && typeof err.parameters === "object") {
const retryAfter = (err.parameters as { retry_after?: unknown }).retry_after;
return typeof retryAfter === "number" && Number.isFinite(retryAfter);
}
return false;

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.

retry_after could be non-positive

Number.isFinite returns true for any finite number, including negative values (e.g. -1). While Telegram's API documents retry_after as a positive integer (seconds to wait), validating positivity here makes the intent explicit and guards against malformed responses:

Suggested change
function hasTelegramRetryAfterParameter(err: unknown): boolean {
if (!err || typeof err !== "object") {
return false;
}
if ("parameters" in err && err.parameters && typeof err.parameters === "object") {
const retryAfter = (err.parameters as { retry_after?: unknown }).retry_after;
return typeof retryAfter === "number" && Number.isFinite(retryAfter);
}
return false;
return typeof retryAfter === "number" && Number.isFinite(retryAfter) && retryAfter > 0;
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/telegram/network-errors.ts
Line: 105-113

Comment:
**`retry_after` could be non-positive**

`Number.isFinite` returns `true` for any finite number, including negative values (e.g. `-1`). While Telegram's API documents `retry_after` as a positive integer (seconds to wait), validating positivity here makes the intent explicit and guards against malformed responses:

```suggestion
    return typeof retryAfter === "number" && Number.isFinite(retryAfter) && retryAfter > 0;
```

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.

Implemented in commit 55ceb98 — added && retryAfter > 0 guard.

Comment thread src/telegram/network-errors.ts Outdated

// grammY "Network request for X failed after N attempts" indicates a
// transport-level failure — the request never reached Telegram.
const message = formatErrorMessage(candidate).trim().toLowerCase();

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.

Redundant .toLowerCase() with i flag

GRAMMY_NETWORK_REQUEST_FAILED_AFTER_RE is already defined with the i (case-insensitive) flag at line 55, so .toLowerCase() has no effect. This is the same pattern as in isRecoverableTelegramNetworkError (line 173) which also lowercases before testing against the same regex. The redundancy is harmless but slightly misleading about the regex's own case-insensitivity.

Suggested change
const message = formatErrorMessage(candidate).trim().toLowerCase();
const message = formatErrorMessage(candidate).trim();
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/telegram/network-errors.ts
Line: 142

Comment:
**Redundant `.toLowerCase()` with `i` flag**

`GRAMMY_NETWORK_REQUEST_FAILED_AFTER_RE` is already defined with the `i` (case-insensitive) flag at line 55, so `.toLowerCase()` has no effect. This is the same pattern as in `isRecoverableTelegramNetworkError` (line 173) which also lowercases before testing against the same regex. The redundancy is harmless but slightly misleading about the regex's own case-insensitivity.

```suggestion
    const message = formatErrorMessage(candidate).trim();
```

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.

Fixed in commit 55ceb98 — removed .toLowerCase(), now just formatErrorMessage(candidate).trim().

- Add unit tests to network-errors.test.ts for isSafeToRetrySendError
  (429+retry_after and grammY failed-after paths)
- Update isSafeToRetrySendError docstring to accurately describe coverage
- Add retryAfter > 0 guard in hasTelegramRetryAfterParameter
- Remove redundant .toLowerCase() before case-insensitive regex test
@amittell

amittell commented Mar 9, 2026

Copy link
Copy Markdown
Contributor Author

All review feedback addressed in commit 55ceb98:

  • Unit tests added to network-errors.test.ts for both new isSafeToRetrySendError branches (429+retry_after and grammY failed-after)
  • retryAfter > 0 guard added to hasTelegramRetryAfterParameter
  • Redundant .toLowerCase() removed before case-insensitive regex test
  • Docstring updated to accurately reflect coverage

@aisle-research-bot

aisle-research-bot Bot commented Mar 10, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 1 potential security issue(s) in this PR:

# Severity Title
1 🟡 Medium Unsafe retries for non-idempotent Telegram sends due to overly broad error classification

1. 🟡 Unsafe retries for non-idempotent Telegram sends due to overly broad error classification

Property Value
Severity Medium
CWE CWE-670
Location src/telegram/network-errors.ts:136-146

Description

isSafeToRetrySendError is intended to only return true when a sendMessage-like request is guaranteed not to have been delivered (to avoid duplicate visible messages). The update broadens the retry classification in ways that can be incorrect:

  • parameters.retry_after is accepted without verifying the error is a Telegram 429 API error (e.g., checking error_code === 429, HTTP status 429, or that the error is a grammY Telegram API error type). Any thrown object in the error graph that happens to include { parameters: { retry_after: <number> } } will be treated as safe to retry.
  • The grammY envelope message regex is used as a “safe to retry send” signal, but a message like "Network request for 'sendMessage' failed after N attempts" does not guarantee the request was never received/processed by Telegram (transport failures can occur after the request is sent but before the response is read). Retrying non-idempotent sends in such cases can result in duplicate message delivery.

Vulnerable code:

​// 429 rate-limit with retry_after ...
if (hasTelegramRetryAfterParameter(candidate)) {
  return true;
}

​// grammY "Network request ... failed after N attempts" ...
const message = formatErrorMessage(candidate).trim();
if (message && GRAMMY_NETWORK_REQUEST_FAILED_AFTER_RE.test(message)) {
  return true;
}

Impact:

  • Duplicate messages delivered to chats when transient/ambiguous network failures are misclassified as “safe to retry”.
  • Potential amplification/spam if callers configure higher retry attempts, or if grammY already performed internal retries before surfacing the envelope error.

Recommendation

Tighten retry classification for non-idempotent Telegram sends:

  1. Only treat retry_after as safe when you can positively identify a Telegram Bot API 429 error (and ideally only when it comes from grammY’s Telegram API error type).
  2. Do not treat the grammY “failed after N attempts” envelope message as proof of non-delivery. If you want to retry some envelope errors, only do so when the root cause is a pre-connect error code (DNS/connection refused/unreachable), not based on the envelope message string.

Example safer approach (structure may need adjustment based on grammY error types used in this repo):

function isTelegram429WithRetryAfter(err: unknown): boolean {
  if (!err || typeof err !== "object") return false;
  const anyErr = err as any;
  const retryAfter = anyErr?.parameters?.retry_after;
  const errorCode = anyErr?.error_code; // Telegram Bot API field
  const status = anyErr?.status ?? anyErr?.response?.status;

  return (
    (errorCode === 429 || status === 429) &&
    typeof retryAfter === "number" &&
    Number.isFinite(retryAfter) &&
    retryAfter > 0
  );
}

export function isSafeToRetrySendError(err: unknown): boolean {
  for (const candidate of collectTelegramErrorCandidates(err)) {
    const code = normalizeCode(getErrorCode(candidate));
    if (code && PRE_CONNECT_ERROR_CODES.has(code)) return true;

    if (isTelegram429WithRetryAfter(candidate)) return true;

    ​// Avoid message-regex classification for non-idempotent sends.
  }
  return false;
}

Additionally:

  • Consider bounding/clamping retry_after to a reasonable maximum (even though maxDelayMs clamps the delay, it’s better to validate semantics).
  • Add negative tests ensuring parameters.retry_after does not trigger retries unless the error is confirmed to be a Telegram 429 response.

Analyzed PR: #40383 at commit f978432

Last updated on: 2026-03-10T20:36:59Z

…FromEntrySchema/buildCatchallMultiAccountChannelSchema from channel-plugin-common

Fix lint:plugins:no-monolithic-plugin-sdk-entry-imports CI failures:
- All extension files using 'openclaw/plugin-sdk' monolithic import now use scoped subpaths
- createPluginRuntimeStore → openclaw/plugin-sdk/runtime-store
- createScopedChannelConfigBase → openclaw/plugin-sdk/channel-config-helpers
- AllowFromEntrySchema + buildCatchallMultiAccountChannelSchema → openclaw/plugin-sdk/channel-plugin-common
- Added the latter two exports to channel-plugin-common.ts
@openclaw-barnacle openclaw-barnacle Bot added channel: bluebubbles Channel integration: bluebubbles channel: discord Channel integration: discord channel: googlechat Channel integration: googlechat channel: imessage Channel integration: imessage channel: line Channel integration: line channel: matrix Channel integration: matrix channel: mattermost Channel integration: mattermost channel: msteams Channel integration: msteams channel: nextcloud-talk Channel integration: nextcloud-talk channel: nostr Channel integration: nostr channel: signal Channel integration: signal channel: slack Channel integration: slack channel: tlon Channel integration: tlon channel: whatsapp-web Channel integration: whatsapp-web channel: zalo Channel integration: zalo channel: zalouser Channel integration: zalouser labels Mar 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: bluebubbles Channel integration: bluebubbles channel: discord Channel integration: discord channel: feishu Channel integration: feishu channel: googlechat Channel integration: googlechat channel: imessage Channel integration: imessage channel: irc channel: line Channel integration: line channel: matrix Channel integration: matrix channel: mattermost Channel integration: mattermost channel: msteams Channel integration: msteams channel: nextcloud-talk Channel integration: nextcloud-talk channel: nostr Channel integration: nostr channel: signal Channel integration: signal channel: slack Channel integration: slack channel: telegram Channel integration: telegram channel: tlon Channel integration: tlon channel: twitch Channel integration: twitch channel: whatsapp-web Channel integration: whatsapp-web channel: zalo Channel integration: zalo channel: zalouser Channel integration: zalouser size: S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants