Skip to content

Catch up after reconnects, let the supervisor own backoff, warm dialogs in the background - #67

Open
erfnzdeh wants to merge 5 commits into
mainfrom
fix/reconnect-catch-up
Open

erfnzdeh wants to merge 5 commits into
mainfrom
fix/reconnect-catch-up

Conversation

@erfnzdeh

Copy link
Copy Markdown
Collaborator

Closes #60

What was wrong

Line numbers at 2f303da.

  • The reconnect hook never ran. tlgr/core/telethon_compat.py:134 replaced client._handle_auto_reconnect, but Telethon 1.44 hands the bound method to MTProtoSender(auto_reconnect_callback=self._handle_auto_reconnect) in TelegramClient.__init__ (telethon/client/telegrambaseclient.py:444), and MTProtoSender._reconnect calls self._auto_reconnect_callback() (telethon/network/mtprotosender.py:410-411). The client attribute is never read again, so the wrapper was dead code. Updates missed during a blip arrived only when Telethon's 15 minute no-updates timer fired.
  • connection_retries=None is "forever", not "off". tlgr/daemon/session.py:123 passed None. helpers.retry_range(None) is infinite (telethon/helpers.py:140-154), at a fixed 1 s delay. So disconnected never resolved on a drop, the supervisor's backoff and degraded were never reached for drops, and client.connect() with no network never returned: the account sat in starting. Reproduced on main with a real Telethon client whose connections are refused: still starting after the test's 15 s.
  • Stopping an account that never connected erased its update state (found while testing the above). Before the first successful connect the MessageBox is empty. _graceful_client_shutdown (session.py:266-270) calls compat.save_state and client.disconnect(), and both end in Telethon's _save_states_and_entities(), which writes the empty box as pts=0. The next start then loads nothing, calls getState, and starts from "now": everything missed while down is gone. Reproduced on main: a session seeded with pts=4242, started offline, stopped, reads back pts=0.
  • The full dialog sweep gated online. _connect_once awaited _after_connect (session.py:323), which ran iter_dialogs(limit=None) (session.py:339) before catch_up and before ONLINE, on every connect.

Changes

  • telethon_compat.install_reconnect_hook wraps client._sender._auto_reconnect_callback (the callback the sender actually runs). Telethon's own handler still runs first, then tlgr's _on_reconnect (counts the reconnect and calls session.catch_up(), the same path daemon.resync and sync catch-up use, so events go through the bus with normal seq). Warns once and degrades if the attribute is gone.
  • build_client passes a finite connection_retries (new ClientOptions.connection_retries, default 1). Telethon nests the count (a reconnect makes retries rounds of retries + 1 attempts), so 1 means two connection attempts for a first connect and two for a reconnect; then it resolves disconnected with the last error.
  • _connect_once treats an error from disconnected as a dropped connection (fatal auth errors still go to needs_login), so the supervisor counts the reconnect, goes degraded, backs off and reconnects. Before reconnecting a client that was connected before, it calls client.disconnect() so Telethon's stale update loop (which can stay parked on the update queue for up to 15 minutes) is cancelled instead of running next to the new one.
  • New telethon_compat.install_state_guard / update_state_loaded: _save_states_and_entities is a no-op until the MessageBox has been loaded; save_state skips it too.
  • The dialog sweep runs as a background task after ONLINE, once per session (the client and its caches survive reconnects). A failed or interrupted sweep runs again on the next connect; stop() cancels a running one. Nothing depended on it for correctness: the peer resolver falls back to the session cache, the network and its own dialog scan, and channels the session knows are caught up from its stored state.
  • New [daemon] catch_up_interval (int seconds, default 0 = off, positive values below 30 raised to 30), exposed as daemon.catch_up_interval in tlgr config. When set, each online account calls catch_up() on that timer.
  • ARCHITECTURE 6.2/6.3 and the config sample updated; CHANGELOG entries.

Tests

Test What it reproduces Fails on main?
test_telethon_compat.py::TestReconnectHook::test_the_senders_reconnect_callback_reaches_tlgr Real TelegramClient: calling the sender's stored callback must reach tlgr yes
TestReconnectHook::test_telethons_own_handler_still_runs_first Telethon's handler, then tlgr's yes
TestReconnectHook::test_a_client_without_a_sender_degrades probe and degrade no
TestStateGuard::test_disconnecting_a_never_connected_client_keeps_the_saved_pts Real SQLite session: disconnect() before any connect keeps pts yes
TestStateGuard::test_save_state_skips_an_empty_box compat.save_state on an empty box does not write yes
TestStateGuard::test_a_loaded_box_is_saved the guard does not stop real saves yes (new API)
test_account_session.py::TestReconnect::test_telethon_gets_a_finite_retry_count client._sender._retries is a small int, not None yes
TestReconnect::test_starting_offline_degrades_instead_of_hanging Real Telethon client, every connect refused: reaches degraded yes (stays starting)
TestReconnect::test_stopping_before_the_first_connect_keeps_the_saved_update_state Real client offline, start then stop: seeded pts survives yes (pts becomes 0)
TestReconnect::test_telethons_automatic_reconnect_triggers_a_catch_up sender callback, then catch_up() and reconnects == 1 yes
TestReconnect::test_telethon_giving_up_is_a_drop_and_is_caught_up disconnected raising is counted as a drop and caught up yes
TestReconnect::test_the_dead_connection_is_torn_down_before_reconnecting disconnect() before the reconnect's connect() yes
TestDialogWarmup::test_the_account_is_online_while_the_sweep_runs blocked iter_dialogs: account is online and serves requests yes
TestDialogWarmup::test_a_finished_sweep_is_not_repeated_after_a_reconnect one sweep per session yes
TestDialogWarmup::test_a_failed_sweep_runs_again_on_the_next_connect retry after failure yes
TestDialogWarmup::test_stop_cancels_a_running_sweep no task left behind yes
TestPeriodicCatchUp::test_the_interval_is_off_by_default_and_floored default 0, floor 30 yes
TestPeriodicCatchUp::test_no_timer_runs_when_it_is_off no ticker by default no
TestPeriodicCatchUp::test_the_timer_catches_up_while_online the ticker calls catch_up() yes
TestPeriodicCatchUp::test_the_session_manager_passes_the_config_through config.toml value reaches the session (10 raised to 30) yes

Not changed, and why

  • The finding about the hook was verified, not assumed: read in the installed Telethon 1.44.0 (telegrambaseclient.py:435-445, mtprotosender.py:51-61, 354-421) and covered by a test against a real client.
  • No 30 s cache of a failed reconnect (telegram-mcp's ensure_connected): tlgr's request gate already answers RETRYABLE from the session state while degraded, so queued callers do not each run their own reconnect.
  • connection_retries is not a config key. It is an internal contract between Telethon and the supervisor; the user-facing knob for patience is the supervisor's backoff. Kept in ClientOptions so it can be changed in one place.
  • No extra catch_up() after the background sweep. A channel first seen by the sweep gets its current pts, so there is nothing to fetch for it; channels already in the session are caught up before online.
  • TLGR_CATCH_UP=0 (set by tlgr daemon start --no-catch-up) is not read anywhere in the daemon. Out of scope; noted for a follow-up.

Not verified

  • Not run against real Telegram (by design). The drop paths are exercised with the fake client and, for connect failure and state persistence, with a real Telethon client whose transport refuses every connection. Telethon's internal reconnect itself (MTProtoSender._reconnect) is not driven end to end; the test calls the callback exactly as _reconnect does.
  • How long Telethon now takes to give up depends on the failure: a refused connection takes about 2 s (two attempts, 1 s apart); a black-holed one up to two connect timeouts plus delays, about 22 s with defaults, before the supervisor takes over.

make check: passed (lint, typecheck, 13670 tests, docs, parity).

…back

install_reconnect_hook replaced client._handle_auto_reconnect, but
MTProtoSender keeps the bound method it was given in TelegramClient.__init__
as _auto_reconnect_callback and never reads the client attribute again, so
the wrapper never ran and updates missed during a drop waited for Telethon's
15 minute no-updates timer. Wrap the sender's callback instead.

Refs #60
…y count

build_client passed connection_retries=None to turn Telethon's retry loop
off, but Telethon reads None as retry forever at a fixed one second delay.
The disconnected future never resolved, so a drop never reached the
supervisor's jittered backoff or the degraded state, and connect() on a
machine without network never returned, leaving the account in starting.

Telethon now gets connection_retries=1 (two connection attempts for a first
connect and for a reconnect) and then resolves disconnected with the last
error, which the supervisor treats as a dropped connection (fatal auth
errors stay terminal). Before reconnecting it disconnects the dead client
so Telethon's stale update loop cannot run next to the new one.

Starting offline exposed a second fault: Telethon's disconnect() and
keepalive loop save the MessageBox unconditionally, and before the first
successful connect the box is empty, so stopping such an account wrote
pts=0 over the session's update state and the next start skipped everything
missed while down. A compat guard skips that save until the box is loaded.

Refs #60
_after_connect ran a full iter_dialogs(limit=None) before the account went
online, on every connect. On a large account that is about a hundred
getDialogs calls, so requests waited 10s and got RETRYABLE for minutes
after each restart. Catch-up does not need the sweep (channels the session
knows are caught up from its own state), so it now runs as a background
task after online, once per session: a finished sweep is not repeated after
a reconnect, a failed one runs again on the next connect, and stop cancels
a running one.

Refs #60
Off by default. When set, each online account calls catch_up() (one
getDifference) every that many seconds, which bounds how late an update
missed on a flaky network reaches watch, webhooks and jobs. Positive values
below 30 are raised to 30 so a typo cannot turn it into a stream of
getDifference calls. Exposed as daemon.catch_up_interval in tlgr config.

Refs #60
ARCHITECTURE 6.2 and 6.3 described connection_retries=None as turning
Telethon's retry loop off and the dialog sweep as gating online. Record
what the code does now, add catch_up_interval to the config sample, and
add the changelog entries.

Refs #60

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.

Missed updates are not caught up after a reconnect

1 participant