Skip to content

fix(telegram): prevent update loss and rebuild loops during polling recovery - #11637

Open
aloneangel45 wants to merge 3 commits into
AstrBotDevs:masterfrom
aloneangel45:fix/11636-telegram-polling-recovery
Open

aloneangel45 wants to merge 3 commits into
AstrBotDevs:masterfrom
aloneangel45:fix/11636-telegram-polling-recovery

Conversation

@aloneangel45

@aloneangel45 aloneangel45 commented Dec 3, 2026 •

Copy link
Copy Markdown

Summary

  1. Defer PTB update acknowledgement until �pplication.stop() finishes draining: In _shutdown_application(..., delete_commands=False), python-telegram-bot's Updater.stop() previously ran its get_updates(offset=_last_update_id, timeout=0) cleanup before �pplication.stop() drained update_queue (or even if �pplication.stop() raised because the application had not started). This PR defers that cleanup callback during client rebuilds and only executes it if �pplication.stop() completes and update_queue is empty, preventing fetched updates from being acknowledged on Telegram before dispatch.
  2. Apply the failure time window to _TelegramPollingRequest and make recovery tuning configurable: _TelegramPollingRequest now resets _consecutive_pool_timeouts when ailure_window elapses between httpx.PoolTimeout errors instead of accumulating indefinitely, and exposes configurable elegram_polling_recovery_threshold (default 5, up from 3) and elegram_polling_failure_window (default 60.0s).
  3. Add capped exponential backoff on rebuild/startup failure loops: Consecutive polling restarts in
    un() now apply exponential backoff (_next_restart_delay(), capped at max(delay, 60.0)) instead of hammering rebuilds at a fixed interval, and reset once polling runs cleanly past _polling_failure_window.

Fixes #11636

Verification

uff format --check astrbot/core/platform/sources/telegram/tg_adapter.py tests/test_telegram_adapter.py (passed)

uff check astrbot/core/platform/sources/telegram/tg_adapter.py tests/test_telegram_adapter.py (passed)

  • pytest tests/test_telegram_adapter.py -q (71 passed)

Summary by Sourcery

Prevent Telegram polling recovery from losing queued updates and reduce repeated rebuilds during persistent failures.

Bug Fixes:

  • Preserve pending Telegram updates during polling recovery by acknowledging them only after polling and application shutdown complete and the update queue is drained.

Enhancements:

  • Limit consecutive polling pool-timeout counts to a configurable time window and expose configurable recovery thresholds and failure-window settings, defaulting to 5 timeouts and 60 seconds.
  • Use capped exponential delays between polling restarts, with a longer cooldown for pool-timeout recovery and reset after a clean run.

Tests:

  • Add Telegram adapter tests for deferred acknowledgements, timeout-window behavior, recovery configuration, and restart backoff.

Chores:

  • Add localized dashboard configuration metadata for the new Telegram polling recovery settings.

…ecovery

Signed-off-by: aloneangel45 <aloneangel45@users.noreply.github.com>
@sourcery-ai

sourcery-ai Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Linked issues

Checked at commit abaf330

#11636 [Bug] Telegram 长轮询在代理抖动时反复重建 client,重建期间 mark-all-fetched-updates 导致消息丢失(4.30.2) · 2 of 4 met

# Requirement Status Notes
1 Make the polling recovery threshold and failure window configurable, and limit PoolTimeout counting to that window. 🟡 Partly met The adapter reads both settings and applies the time window, but the new keys are not added to Telegram's default settings or configuration metadata, so they are not exposed through the normal settings UI.
2 Increase the pool timeout or provide a longer cooldown specifically for PoolTimeout recovery. 🟡 Partly met The exponential restart delay slows repeated rebuilds, but the polling request still uses the default pool timeout and has no PoolTimeout-specific cooldown.
3 Drain fetched updates before acknowledging them during a rebuild, or avoid advancing their offset. ✅ Met The cleanup acknowledgement is deferred until application.stop() completes and the update queue is empty.
4 Use exponential backoff for repeated polling failures and reset it after polling runs cleanly. ✅ Met Restart delays increase exponentially up to a cap and reset after polling remains healthy for the failure window.

@sourcery-ai sourcery-ai Bot 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.

Hey - I've found 10 issues

Sourcery assessment

Needs a human reviewer. 10 findings to address first, and if application shutdown fails after some queued updates have already been handled, the deferred acknowledgement is skipped and Telegram can deliver those updates again. Handlers may send duplicate replies outside the team; reverting cannot retract messages already sent.

Blocking findings: astrbot/core/platform/sources/telegram/tg_adapter.py:311, astrbot/core/platform/sources/telegram/tg_adapter.py:341, astrbot/core/platform/sources/telegram/tg_adapter.py:341, astrbot/core/platform/sources/telegram/tg_adapter.py:235, astrbot/core/platform/sources/telegram/tg_adapter.py:249, and 5 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

update_queue = getattr(self.application, "update_queue", None)
if update_queue is None or update_queue.empty():
with suppress(Exception):
await deferred_ack_cb()

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.

🟡 Medium · Acknowledges while polling remains active

When updater.stop() fails while its polling task can still fetch updates, and the update queue is empty when checked, updater.stop() exceptions are suppressed without recording that the poller stopped, so a successful application.stop() and momentarily empty queue still allow deferred_ack_cb() to run. A still-active poller can fetch updates after the queue check and have them acknowledged before dispatch, losing those updates.

Only run the deferred acknowledgement after confirming updater.stop() completed successfully and the poller is no longer active.

Comment thread tests/test_telegram_adapter.py Resolved
Comment thread tests/test_telegram_adapter.py Resolved
@aloneangel45

Copy link
Copy Markdown
Author

Addressed the review feedback in abaf330:

  • Guarded _parse_positive_int_config / _parse_positive_float_config against bool, OverflowError, and non-finite values (e.g. inf / nan).
  • Uncapped the restart backoff scaling exponent up to 2^20 so small base delays still reach _polling_max_restart_delay (60s).
  • Logged deferred cleanup_cb acknowledgement failures instead of suppressing silently.
  • Updated the healthy polling reset check to clear restart attempts once _polling_failure_window elapses after the last failure even if a sub-threshold failure occurred earlier.
  • Strengthened the pool-timeout window test (verifying count reaches 2 before expiry) and added test_telegram_run_applies_exponential_backoff_on_restarts covering run().

Verified locally with ruff format --check, ruff check, and pytest tests/test_telegram_adapter.py -q (72 passed).

…k logging

Signed-off-by: aloneangel45 <aloneangel45@users.noreply.github.com>

@sourcery-ai sourcery-ai Bot 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.

New gaps against the linked issues

@aloneangel45

Copy link
Copy Markdown
Author

Addressed the remaining review feedback in 2bf975b:

  1. Defer polling ack regardless of delete_commands and verify updater.stop(): Removed the if not delete_commands: guard in _shutdown_application so pending updates stay unacknowledged until application.stop() drains update_queue, and tracked updater_stopped so deferred_ack_cb() is skipped if updater.stop() raises.
  2. PoolTimeout mitigation & cooldown: Increased _TelegramPollingRequest pool_timeout to 10.0s and applied a PoolTimeout-specific minimum cooldown (min(telegram_polling_restart_delay * 3.0, _polling_max_restart_delay), i.e. 15s at the 5s default) when rebuilding after repeated httpx.PoolTimeout errors.
  3. Default config & dashboard metadata: Added telegram_polling_recovery_threshold (5) and telegram_polling_failure_window (60.0) to astrbot/core/config/default.py and the en-US, zh-CN, ja-JP, and ru-RU config-metadata.json locales.
  4. Verification: Verified locally with ruff check, ruff format --check, JSON validation across the four locale files, and pytest tests/test_telegram_adapter.py -k 'polling or pool_timeout or shutdown or restart' (18 passed, 58 deselected).

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Telegram 长轮询在代理抖动时反复重建 client,重建期间 mark-all-fetched-updates 导致消息丢失(4.30.2)

1 participant