Repository navigation
Conversation
…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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #60
What was wrong
Line numbers at 2f303da.
tlgr/core/telethon_compat.py:134replacedclient._handle_auto_reconnect, but Telethon 1.44 hands the bound method toMTProtoSender(auto_reconnect_callback=self._handle_auto_reconnect)inTelegramClient.__init__(telethon/client/telegrambaseclient.py:444), andMTProtoSender._reconnectcallsself._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=Noneis "forever", not "off".tlgr/daemon/session.py:123passedNone.helpers.retry_range(None)is infinite (telethon/helpers.py:140-154), at a fixed 1 s delay. Sodisconnectednever resolved on a drop, the supervisor's backoff anddegradedwere never reached for drops, andclient.connect()with no network never returned: the account sat instarting. Reproduced on main with a real Telethon client whose connections are refused: stillstartingafter the test's 15 s.MessageBoxis empty._graceful_client_shutdown(session.py:266-270) callscompat.save_stateandclient.disconnect(), and both end in Telethon's_save_states_and_entities(), which writes the empty box aspts=0. The next start then loads nothing, callsgetState, and starts from "now": everything missed while down is gone. Reproduced on main: a session seeded withpts=4242, started offline, stopped, reads backpts=0.online._connect_onceawaited_after_connect(session.py:323), which raniter_dialogs(limit=None)(session.py:339) beforecatch_upand beforeONLINE, on every connect.Changes
telethon_compat.install_reconnect_hookwrapsclient._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 callssession.catch_up(), the same pathdaemon.resyncandsync catch-upuse, so events go through the bus with normalseq). Warns once and degrades if the attribute is gone.build_clientpasses a finiteconnection_retries(newClientOptions.connection_retries, default 1). Telethon nests the count (a reconnect makesretriesrounds ofretries + 1attempts), so 1 means two connection attempts for a first connect and two for a reconnect; then it resolvesdisconnectedwith the last error._connect_oncetreats an error fromdisconnectedas a dropped connection (fatal auth errors still go toneeds_login), so the supervisor counts the reconnect, goesdegraded, backs off and reconnects. Before reconnecting a client that was connected before, it callsclient.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.telethon_compat.install_state_guard/update_state_loaded:_save_states_and_entitiesis a no-op until theMessageBoxhas been loaded;save_stateskips it too.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.[daemon] catch_up_interval(int seconds, default 0 = off, positive values below 30 raised to 30), exposed asdaemon.catch_up_intervalintlgr config. When set, each online account callscatch_up()on that timer.Tests
test_telethon_compat.py::TestReconnectHook::test_the_senders_reconnect_callback_reaches_tlgrTelegramClient: calling the sender's stored callback must reach tlgrTestReconnectHook::test_telethons_own_handler_still_runs_firstTestReconnectHook::test_a_client_without_a_sender_degradesTestStateGuard::test_disconnecting_a_never_connected_client_keeps_the_saved_ptsdisconnect()before any connect keepsptsTestStateGuard::test_save_state_skips_an_empty_boxcompat.save_stateon an empty box does not writeTestStateGuard::test_a_loaded_box_is_savedtest_account_session.py::TestReconnect::test_telethon_gets_a_finite_retry_countclient._sender._retriesis a small int, notNoneTestReconnect::test_starting_offline_degrades_instead_of_hangingdegradedstarting)TestReconnect::test_stopping_before_the_first_connect_keeps_the_saved_update_stateptssurvivesptsbecomes 0)TestReconnect::test_telethons_automatic_reconnect_triggers_a_catch_upcatch_up()andreconnects == 1TestReconnect::test_telethon_giving_up_is_a_drop_and_is_caught_updisconnectedraising is counted as a drop and caught upTestReconnect::test_the_dead_connection_is_torn_down_before_reconnectingdisconnect()before the reconnect'sconnect()TestDialogWarmup::test_the_account_is_online_while_the_sweep_runsiter_dialogs: account isonlineand serves requestsTestDialogWarmup::test_a_finished_sweep_is_not_repeated_after_a_reconnectTestDialogWarmup::test_a_failed_sweep_runs_again_on_the_next_connectTestDialogWarmup::test_stop_cancels_a_running_sweepTestPeriodicCatchUp::test_the_interval_is_off_by_default_and_flooredTestPeriodicCatchUp::test_no_timer_runs_when_it_is_offTestPeriodicCatchUp::test_the_timer_catches_up_while_onlinecatch_up()TestPeriodicCatchUp::test_the_session_manager_passes_the_config_throughconfig.tomlvalue reaches the session (10 raised to 30)Not changed, and why
telegrambaseclient.py:435-445,mtprotosender.py:51-61, 354-421) and covered by a test against a real client.ensure_connected): tlgr's request gate already answersRETRYABLEfrom the session state while degraded, so queued callers do not each run their own reconnect.connection_retriesis 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 inClientOptionsso it can be changed in one place.catch_up()after the background sweep. A channel first seen by the sweep gets its currentpts, so there is nothing to fetch for it; channels already in the session are caught up beforeonline.TLGR_CATCH_UP=0(set bytlgr daemon start --no-catch-up) is not read anywhere in the daemon. Out of scope; noted for a follow-up.Not verified
MTProtoSender._reconnect) is not driven end to end; the test calls the callback exactly as_reconnectdoes.make check: passed (lint, typecheck, 13670 tests, docs, parity).