From f9a92106458e66a3e0016dc30e6f15f081383d81 Mon Sep 17 00:00:00 2001 From: Pouri <94605698+erfnzdeh@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:23:52 +0330 Subject: [PATCH 1/5] Catch up after Telethon's automatic reconnect: hook the sender's callback 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 --- tests/test_account_session.py | 31 ++++++++++++++++++++++++ tests/test_telethon_compat.py | 44 +++++++++++++++++++++++++++++++++++ tlgr/core/telethon_compat.py | 39 +++++++++++++++++++++++-------- 3 files changed, 104 insertions(+), 10 deletions(-) diff --git a/tests/test_account_session.py b/tests/test_account_session.py index 237f412..f1fa9d1 100644 --- a/tests/test_account_session.py +++ b/tests/test_account_session.py @@ -327,3 +327,34 @@ async def test_one_bad_account_does_not_block_the_others(self, tlgr_home, stub_a assert results["broken"].startswith("error:") finally: await manager.stop_all() + + +class TestReconnect: + """tlgrcli/tlgr#60: catch-up after reconnect, and who owns the backoff.""" + + async def test_telethons_automatic_reconnect_triggers_a_catch_up(self, tlgr_home, world): + """The hook must sit where `MTProtoSender` calls it, not on the client.""" + from types import SimpleNamespace + + def factory(path, options): + client = FakeTelegramClient(world, session=path) + client._sender = SimpleNamespace(_auto_reconnect_callback=None) + return client + + session = AccountSession( + "work", + session_path=tlgr_home / "session", + lock_path=tlgr_home / "session.lock", + options=ClientOptions(api_id=1, api_hash="x"), + client_factory=factory, + ) + await session.start() + try: + await _wait_for(lambda: session.state == SessionState.ONLINE) + before = world.catch_ups + # What `MTProtoSender._reconnect` does after it reconnects. + await session.client._sender._auto_reconnect_callback() + assert world.catch_ups == before + 1 + assert session.reconnects == 1 + finally: + await session.stop() diff --git a/tests/test_telethon_compat.py b/tests/test_telethon_compat.py index 617cf28..294f3f3 100644 --- a/tests/test_telethon_compat.py +++ b/tests/test_telethon_compat.py @@ -54,3 +54,47 @@ def test_one_clients_hook_does_not_fire_for_another(self): assert seen == [] assert type(plain._message_box) is MessageBox + + +def _real_client(session: object = None): + """A real, never-connected `TelegramClient`. Nothing here touches the network.""" + from telethon import TelegramClient + from telethon.sessions import MemorySession + + return TelegramClient(session if session is not None else MemorySession(), 1, "x") + + +class TestReconnectHook: + """tlgrcli/tlgr#60: the hook must reach the callback the sender actually runs.""" + + async def test_the_senders_reconnect_callback_reaches_tlgr(self): + client = _real_client() + calls: list[str] = [] + + async def on_reconnect() -> None: + calls.append("reconnected") + + assert compat.install_reconnect_hook(client, on_reconnect) + # `MTProtoSender._reconnect` runs exactly this after a successful + # reconnect. Telethon's own handler inside it calls `get_me()`, which + # fails here (never connected) and is logged by Telethon itself. + await client._sender._auto_reconnect_callback() + assert calls == ["reconnected"] + + async def test_telethons_own_handler_still_runs_first(self, monkeypatch): + client = _real_client() + order: list[str] = [] + + async def telethon_handler() -> None: + order.append("telethon") + + monkeypatch.setattr(client._sender, "_auto_reconnect_callback", telethon_handler) + compat.install_reconnect_hook(client, lambda: order.append("tlgr")) + await client._sender._auto_reconnect_callback() + assert order == ["telethon", "tlgr"] + + def test_a_client_without_a_sender_degrades(self): + class Bare: + pass + + assert compat.install_reconnect_hook(Bare(), lambda: None) is False diff --git a/tlgr/core/telethon_compat.py b/tlgr/core/telethon_compat.py index a4ed4a6..3e2ec295 100644 --- a/tlgr/core/telethon_compat.py +++ b/tlgr/core/telethon_compat.py @@ -110,19 +110,36 @@ def install_reconnect_hook(client: Any, callback: Callable[[], Any]) -> bool: Telethon's `_handle_auto_reconnect` re-runs `get_me()` and nothing else, so an account that dropped for ten minutes comes back with a stale `pts` and - silently misses everything that happened (checklist 1/2). Wrapping it is - the only hook there is; when it is gone the supervisor's own reconnect path - still calls `catch_up()`, so this is an optimisation, not a requirement. + silently misses everything that happened (checklist 1/2). + + The callback Telethon actually runs is the one `MTProtoSender` was given + in `TelegramClient.__init__`: it keeps the bound method as + `_auto_reconnect_callback` and never reads the client attribute again. So + replacing `client._handle_auto_reconnect` alone (what this did until + tlgrcli/tlgr#60) installed a wrapper nothing called, and missed updates + waited for Telethon's 15 minute no-updates timer. The wrapper goes on the + sender; the client attribute is updated too so both agree. + + When the sender attribute is gone the supervisor's own reconnect path + still calls `catch_up()`, so this degrades rather than fails. """ - original = getattr(client, "_handle_auto_reconnect", None) - if not callable(original): - _warn_once("_handle_auto_reconnect") + sender = getattr(client, "_sender", None) + if sender is None or not hasattr(sender, "_auto_reconnect_callback"): + _warn_once("MTProtoSender._auto_reconnect_callback") return False + original = getattr(sender, "_auto_reconnect_callback", None) + if original is None: + original = getattr(client, "_handle_auto_reconnect", None) async def wrapper() -> Any: - result = original() - if hasattr(result, "__await__"): - result = await result + result = None + if callable(original): + try: + result = original() + if hasattr(result, "__await__"): + result = await result + except Exception as exc: # pragma: no cover - Telethon logs its own + log.debug("telethon reconnect handler failed: %s", exc) try: outcome = callback() if hasattr(outcome, "__await__"): @@ -131,7 +148,9 @@ async def wrapper() -> Any: log.debug("reconnect hook failed: %s", exc) return result - client._handle_auto_reconnect = wrapper + sender._auto_reconnect_callback = wrapper + with contextlib.suppress(AttributeError): + client._handle_auto_reconnect = wrapper return True From e53e5e6b45eb2a558c08f56aa6e758f7067eff6e Mon Sep 17 00:00:00 2001 From: Pouri <94605698+erfnzdeh@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:27:14 +0330 Subject: [PATCH 2/5] Let the supervisor own reconnect backoff: give Telethon a finite retry 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 --- tests/test_account_session.py | 138 ++++++++++++++++++++++++++++++++++ tests/test_telethon_compat.py | 65 ++++++++++++++++ tlgr/core/telethon_compat.py | 64 +++++++++++++++- tlgr/daemon/session.py | 65 ++++++++++++++-- 4 files changed, 323 insertions(+), 9 deletions(-) diff --git a/tests/test_account_session.py b/tests/test_account_session.py index f1fa9d1..3afb4b0 100644 --- a/tests/test_account_session.py +++ b/tests/test_account_session.py @@ -329,9 +329,106 @@ async def test_one_bad_account_does_not_block_the_others(self, tlgr_home, stub_a await manager.stop_all() +def _refused_connection(): + """A Telethon connection class whose every connect is refused, instantly. + + What a laptop with no network looks like to Telethon: `_try_connect` + catches the `OSError`, sleeps `retry_delay` and tries again. + """ + from telethon.network.connection import ConnectionTcpFull + + class Refused(ConnectionTcpFull): + async def _connect(self, timeout=None, ssl=None): + raise ConnectionRefusedError("network is unreachable (test)") + + return Refused + + +def _seed_update_state(path: Path, pts: int) -> None: + import datetime + + from telethon.sessions import SQLiteSession + from telethon.tl import types + + session = SQLiteSession(str(path)) + stamp = datetime.datetime(2026, 11, 1, tzinfo=datetime.timezone.utc) + session.set_update_state(0, types.updates.State(pts, 7, stamp, 3, 0)) + session.save() + session.close() + + +def _saved_pts(path: Path) -> int: + from telethon.sessions import SQLiteSession + + session = SQLiteSession(str(path)) + try: + state = session.get_update_state(0) + return int(state.pts) if state is not None else -1 + finally: + session.close() + + class TestReconnect: """tlgrcli/tlgr#60: catch-up after reconnect, and who owns the backoff.""" + def test_telethon_gets_a_finite_retry_count(self, tlgr_home): + """`None` is Telethon's "retry forever", not "off".""" + from tlgr.daemon.session import build_client + + client = build_client(tlgr_home / "work", ClientOptions(api_id=1, api_hash="x")) + try: + retries = client._sender._retries + assert isinstance(retries, int) and 0 <= retries <= 5 + finally: + client.session.close() + + async def test_starting_offline_degrades_instead_of_hanging(self, tlgr_home): + """A real Telethon client with every connect refused. + + With `connection_retries=None` `client.connect()` never returned and + the account sat in `starting` for as long as the network was down. + """ + from tlgr.daemon.session import build_client + + session = AccountSession( + "work", + session_path=tlgr_home / "work", + lock_path=tlgr_home / "session.lock", + options=ClientOptions(api_id=1, api_hash="x", connection=_refused_connection()), + client_factory=build_client, + ) + await session.start() + try: + await _wait_for(lambda: session.state == SessionState.DEGRADED, timeout=15.0) + assert "ConnectionError" in session.reason + finally: + await session.stop() + + async def test_stopping_before_the_first_connect_keeps_the_saved_update_state(self, tlgr_home): + """Telethon would store its empty `MessageBox` as `pts=0`. + + The next start would then begin from "now" and drop everything that + arrived while the daemon was down. + """ + from tlgr.daemon.session import build_client + + path = tlgr_home / "work" + _seed_update_state(path, 4242) + session = AccountSession( + "work", + session_path=path, + lock_path=tlgr_home / "session.lock", + options=ClientOptions( + api_id=1, api_hash="x", connection=_refused_connection(), connection_retries=0 + ), + client_factory=build_client, + ) + await session.start() + await asyncio.sleep(0.5) + await session.stop() + + assert _saved_pts(path) == 4242 + async def test_telethons_automatic_reconnect_triggers_a_catch_up(self, tlgr_home, world): """The hook must sit where `MTProtoSender` calls it, not on the client.""" from types import SimpleNamespace @@ -358,3 +455,44 @@ def factory(path, options): assert session.reconnects == 1 finally: await session.stop() + + async def test_telethon_giving_up_is_a_drop_and_is_caught_up(self, tlgr_home, world): + """Telethon resolves `disconnected` with the last error when its retries run out.""" + session = _session(tlgr_home, world) + await session.start() + try: + await _wait_for(lambda: session.state == SessionState.ONLINE) + first = world.catch_ups + client = session.client + client._connected = False + client.disconnected.set_exception(ConnectionError("Connection to Telegram failed")) + await _wait_for(lambda: session.state == SessionState.ONLINE and world.connects >= 2) + assert session.reconnects == 1 + assert world.catch_ups > first + finally: + await session.stop() + + async def test_the_dead_connection_is_torn_down_before_reconnecting(self, tlgr_home, world): + """Otherwise Telethon's stale update loop would run next to a new one.""" + session = _session(tlgr_home, world) + await session.start() + try: + await _wait_for(lambda: session.state == SessionState.ONLINE) + client = session.client + order: list[str] = [] + real_disconnect, real_connect = client.disconnect, client.connect + + async def disconnect(): + order.append("disconnect") + await real_disconnect() + + async def connect(): + order.append("connect") + return await real_connect() + + client.disconnect, client.connect = disconnect, connect + client.drop() + await _wait_for(lambda: session.state == SessionState.ONLINE and world.connects >= 2) + assert order[:2] == ["disconnect", "connect"] + finally: + await session.stop() diff --git a/tests/test_telethon_compat.py b/tests/test_telethon_compat.py index 294f3f3..47349be 100644 --- a/tests/test_telethon_compat.py +++ b/tests/test_telethon_compat.py @@ -98,3 +98,68 @@ class Bare: pass assert compat.install_reconnect_hook(Bare(), lambda: None) is False + + +class TestStateGuard: + """Telethon writes an empty `MessageBox` over the session's update state.""" + + @staticmethod + def _seed(path) -> None: + import datetime + + from telethon.sessions import SQLiteSession + + session = SQLiteSession(str(path)) + stamp = datetime.datetime(2026, 11, 1, tzinfo=datetime.timezone.utc) + session.set_update_state(0, types.updates.State(100, 7, stamp, 3, 0)) + session.save() + session.close() + + @staticmethod + def _pts(path) -> int: + from telethon.sessions import SQLiteSession + + session = SQLiteSession(str(path)) + try: + state = session.get_update_state(0) + return int(state.pts) if state is not None else -1 + finally: + session.close() + + async def test_disconnecting_a_never_connected_client_keeps_the_saved_pts(self, tmp_path): + path = tmp_path / "work" + self._seed(path) + client = _real_client(str(path)) + assert compat.install_state_guard(client) + assert not compat.update_state_loaded(client) + + await client.disconnect() + + assert self._pts(path) == 100 + + async def test_save_state_skips_an_empty_box(self, tmp_path): + path = tmp_path / "work" + self._seed(path) + client = _real_client(str(path)) + + assert await compat.save_state(client) is False + client.session.close() + + assert self._pts(path) == 100 + + async def test_a_loaded_box_is_saved(self, tmp_path): + """The guard must not stop the real periodic save.""" + from telethon._updates.session import SessionState + + path = tmp_path / "work" + self._seed(path) + client = _real_client(str(path)) + compat.install_state_guard(client) + client._message_box.load(SessionState(0, 0, False, 250, 7, 1_790_000_000, 3, None), []) + assert compat.update_state_loaded(client) + + await client._save_states_and_entities() + client.session.save() + client.session.close() + + assert self._pts(path) == 250 diff --git a/tlgr/core/telethon_compat.py b/tlgr/core/telethon_compat.py index 3e2ec295..427f77f 100644 --- a/tlgr/core/telethon_compat.py +++ b/tlgr/core/telethon_compat.py @@ -28,12 +28,14 @@ "TOO_LONG_GLOBAL", "entity_count", "install_reconnect_hook", + "install_state_guard", "install_too_long_hook", "probe", "save_state", "session_state", "set_session_state", "telethon_version", + "update_state_loaded", ] TOO_LONG_GLOBAL = "global" @@ -79,10 +81,19 @@ async def save_state(client: Any) -> bool: the session file last held — in v1, from the last clean shutdown, which could be days. Called every `[daemon] state_save_interval` seconds and on every shutdown path. + + Nothing is written while the client's `MessageBox` is still empty, which + is the case until the first successful connect loads it from the session. + Telethon would write that empty box as `pts=0`, overwriting the state the + session held, and the next start would begin from "now" and drop every + update missed while down. An account that starts offline and is stopped + before it ever connects must leave its session's update state alone. """ ok = True saver = getattr(client, "_save_states_and_entities", None) - if callable(saver): + if not update_state_loaded(client): + ok = False + elif callable(saver): try: result = saver() if hasattr(result, "__await__"): @@ -105,6 +116,57 @@ async def save_state(client: Any) -> bool: return ok +def update_state_loaded(client: Any) -> bool: + """Has this client's `MessageBox` been loaded with an update state yet? + + False only when the box exists and says it is empty, which is the case + until the first successful connect. When the box cannot be inspected the + answer is True, so callers keep Telethon's own behaviour. + """ + box = getattr(client, "_message_box", None) + is_empty = getattr(box, "is_empty", None) + if not callable(is_empty): + return True + try: + return not is_empty() + except Exception: # pragma: no cover - defensive + return True + + +def install_state_guard(client: Any) -> bool: + """Stop Telethon from writing an empty update state over the session's. + + `TelegramClient.disconnect()` and its keepalive loop both call + `_save_states_and_entities()` unconditionally. Before the first successful + connect the `MessageBox` is empty, and that call stores it as `pts=0`, + erasing the state the session held. The next start then begins from "now" + and every update missed while the daemon was down is lost. An account that + starts while the network is down and is stopped (or restarted) before it + ever connected hits exactly that. The guard makes the save a no-op until + the box has been loaded. + """ + saver = getattr(client, "_save_states_and_entities", None) + if not callable(saver): + _warn_once("_save_states_and_entities") + return False + + async def guarded() -> Any: + if not update_state_loaded(client): + log.debug("skipping update state save: nothing loaded yet") + return None + result = saver() + if hasattr(result, "__await__"): + result = await result + return result + + try: + client._save_states_and_entities = guarded + except AttributeError: # pragma: no cover - TelegramClient has no slots + _warn_once("_save_states_and_entities assignment") + return False + return True + + def install_reconnect_hook(client: Any, callback: Callable[[], Any]) -> bool: """Call *callback* after Telethon finishes an automatic reconnect. diff --git a/tlgr/daemon/session.py b/tlgr/daemon/session.py index 4718149..647d470 100644 --- a/tlgr/daemon/session.py +++ b/tlgr/daemon/session.py @@ -9,9 +9,13 @@ The rules it enforces: -* **the supervisor owns backoff**, not Telethon (`connection_retries=None`), - so a drop is a state transition rather than an exception thrown at whoever - happened to be making a request; +* **the supervisor owns backoff**, not Telethon. Telethon gets one quick + retry (`connection_retries=1`) to ride out a reset connection, then + gives up and resolves `disconnected`, and the supervisor's jittered backoff + takes over, so a drop is a state transition rather than an exception thrown + at whoever happened to be making a request. `None` is not "off": Telethon + reads it as retry forever, once a second, which hid every drop from the + supervisor and left an account that started offline in `starting` for good; * **`catch_up()` runs after every reconnect**, not only at construction. Telethon's own reconnect handler calls `get_me()` and nothing else, so an account that was down for ten minutes silently misses everything that @@ -63,6 +67,13 @@ #: The belt-and-braces resync interval for an account that has heard nothing. _SILENCE_CATCHUP_SECONDS = 900.0 +#: How many times Telethon itself retries a dropped or failed connection before +#: it gives up and the supervisor's backoff takes over. Small and finite on +#: purpose: `None` means retry forever inside Telethon. Telethon nests the +#: count: a reconnect makes `retries` rounds of `retries + 1` connection +#: attempts, so 1 means two attempts for a first connect and for a reconnect. +_TELETHON_CONNECTION_RETRIES = 1 + class SessionState: STARTING = "starting" @@ -93,6 +104,7 @@ class ClientOptions: api_hash: str entity_cache_limit: int = 20000 request_retries: int = 5 + connection_retries: int = _TELETHON_CONNECTION_RETRIES connect_timeout: int = 10 flood_sleep_threshold: int = 120 device_model: str = "" @@ -109,9 +121,12 @@ class ClientOptions: def build_client(session_path: Path, options: ClientOptions) -> Any: """Construct the Telethon client tlgr wants (§6.2). - `connection_retries=None` is the load-bearing argument: it means "retry - forever inside Telethon" is *off*, and the supervisor below decides what a - disconnection means. + `connection_retries` is the load-bearing argument. It must be a small + finite number: Telethon treats `None` (and any negative value) as retry + forever at a fixed one-second delay, so `disconnected` never resolves, the + supervisor below never sees the drop, and `connect()` on a machine with no + network never returns. With a finite count Telethon absorbs a reset + connection and then hands the outage to the supervisor. """ from telethon import TelegramClient @@ -120,7 +135,7 @@ def build_client(session_path: Path, options: ClientOptions) -> Any: "sequential_updates": True, "raise_last_call_error": True, "entity_cache_limit": int(options.entity_cache_limit), - "connection_retries": None, + "connection_retries": max(0, int(options.connection_retries)), "retry_delay": 1, "request_retries": int(options.request_retries), "auto_reconnect": True, @@ -311,6 +326,8 @@ async def _connect_once(self) -> None: self.client = self._factory(self.session_path, self.options) await self._client_built() self._install_hooks() + elif self.connected_since is not None and not self.client.is_connected(): + await self._discard_dead_connection() await self.client.connect() if not await self.client.is_user_authorized(): @@ -327,7 +344,38 @@ async def _connect_once(self) -> None: disconnected = getattr(self.client, "disconnected", None) if disconnected is None: return - await disconnected + try: + await disconnected + except asyncio.CancelledError: + raise + except Exception as exc: + # Telethon ran out of its own reconnect attempts and resolved the + # future with the last error. That is a dropped connection, the + # same as a clean resolve, unless the error says the session is + # gone for good. + if is_fatal_auth(exc): + raise + log.warning( + "account %s lost its connection: %s: %s", + self.alias, + type(exc).__name__, + exc, + extra={"account": self.alias}, + ) + + async def _discard_dead_connection(self) -> None: + """Tear down what is left of a connection Telethon gave up on. + + When Telethon's own reconnect attempts run out it closes the sender, + but the client's update loop can stay parked on the update queue for + up to fifteen minutes. A `connect()` on top of that would start a + second update loop next to the stale one, and both would apply the + same differences. A full `disconnect()` cancels both loops and saves + the update state (the box was loaded by the earlier connect, so that + write is correct); the session file reopens on the next `connect()`. + """ + with contextlib.suppress(Exception): + await self.client.disconnect() async def _after_connect(self) -> None: """Warm the entity cache, then catch up (§6.3). @@ -399,6 +447,7 @@ async def _client_built(self) -> None: ) def _install_hooks(self) -> None: + compat.install_state_guard(self.client) compat.install_reconnect_hook(self.client, self._on_reconnect) compat.install_too_long_hook(self.client, self._on_too_long) From 5d406c718590e396146728382090489b93778ad1 Mon Sep 17 00:00:00 2001 From: Pouri <94605698+erfnzdeh@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:24:33 +0330 Subject: [PATCH 3/5] Warm the dialog cache in the background once the account is online _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 --- tests/test_account_session.py | 89 +++++++++++++++++++++++++++++++++++ tlgr/daemon/session.py | 42 ++++++++++++++--- 2 files changed, 125 insertions(+), 6 deletions(-) diff --git a/tests/test_account_session.py b/tests/test_account_session.py index 3afb4b0..96e302a 100644 --- a/tests/test_account_session.py +++ b/tests/test_account_session.py @@ -496,3 +496,92 @@ async def connect(): assert order[:2] == ["disconnect", "connect"] finally: await session.stop() + + +class _BlockingDialogs: + """An `iter_dialogs` that does not finish until the test says so.""" + + def __init__(self) -> None: + self.release = asyncio.Event() + self.started = 0 + self.fail = False + + def __call__(self, limit=None, **_): + self.started += 1 + return self._iterate() + + async def _iterate(self): + await self.release.wait() + if self.fail: + raise ConnectionError("dropped mid-sweep") + yield object() + + +class TestDialogWarmup: + """tlgrcli/tlgr#60: the dialog sweep must not gate `online`.""" + + def _session(self, tmp: Path, world: World, dialogs: _BlockingDialogs) -> AccountSession: + def factory(path, options): + client = FakeTelegramClient(world, session=path) + client.iter_dialogs = dialogs + return client + + return AccountSession( + "work", + session_path=tmp / "session", + lock_path=tmp / "session.lock", + options=ClientOptions(api_id=1, api_hash="x"), + client_factory=factory, + ) + + async def test_the_account_is_online_while_the_sweep_runs(self, tlgr_home, world): + dialogs = _BlockingDialogs() + session = self._session(tlgr_home, world, dialogs) + await session.start() + try: + await _wait_for(lambda: session.state == SessionState.ONLINE) + assert world.catch_ups >= 1 + await _wait_for(lambda: dialogs.started == 1) + assert await session.acquire(timeout=0.1) is session.client + dialogs.release.set() + await _wait_for(lambda: session._warmed) + finally: + await session.stop() + + async def test_a_finished_sweep_is_not_repeated_after_a_reconnect(self, tlgr_home, world): + dialogs = _BlockingDialogs() + dialogs.release.set() + session = self._session(tlgr_home, world, dialogs) + await session.start() + try: + await _wait_for(lambda: session._warmed) + session.client.drop() + await _wait_for(lambda: session.state == SessionState.ONLINE and world.connects >= 2) + assert dialogs.started == 1 + finally: + await session.stop() + + async def test_a_failed_sweep_runs_again_on_the_next_connect(self, tlgr_home, world): + dialogs = _BlockingDialogs() + dialogs.fail = True + dialogs.release.set() + session = self._session(tlgr_home, world, dialogs) + await session.start() + try: + await _wait_for(lambda: session._warmup is not None and session._warmup.done()) + assert not session._warmed + dialogs.fail = False + session.client.drop() + await _wait_for(lambda: session._warmed) + assert dialogs.started == 2 + finally: + await session.stop() + + async def test_stop_cancels_a_running_sweep(self, tlgr_home, world): + dialogs = _BlockingDialogs() + session = self._session(tlgr_home, world, dialogs) + await session.start() + await _wait_for(lambda: session._warmup is not None) + task = session._warmup + await session.stop() + assert task is not None and task.cancelled() diff --git a/tlgr/daemon/session.py b/tlgr/daemon/session.py index 647d470..e688aff 100644 --- a/tlgr/daemon/session.py +++ b/tlgr/daemon/session.py @@ -206,6 +206,8 @@ def __init__( self._ready = asyncio.Event() self._supervisor: asyncio.Task[None] | None = None self._tickers: list[asyncio.Task[None]] = [] + self._warmup: asyncio.Task[None] | None = None + self._warmed = False self._job_client: Any = None self._flood_budgets: list[int] = [] @@ -266,6 +268,11 @@ async def stop(self, *, timeout: float = 10.0) -> None: for task in self._tickers: task.cancel() self._tickers = [] + if self._warmup is not None: + self._warmup.cancel() + with contextlib.suppress(asyncio.CancelledError, Exception): + await self._warmup + self._warmup = None if self._supervisor is not None: self._supervisor.cancel() with contextlib.suppress(asyncio.CancelledError, Exception): @@ -340,6 +347,7 @@ async def _connect_once(self) -> None: await self._after_connect() self._set_state(SessionState.ONLINE) self._start_tickers() + self._start_warmup() disconnected = getattr(self.client, "disconnected", None) if disconnected is None: @@ -378,17 +386,38 @@ async def _discard_dead_connection(self) -> None: await self.client.disconnect() async def _after_connect(self) -> None: - """Warm the entity cache, then catch up (§6.3). - - The warm-up is not an optimisation: `catch_up()` skips channels whose - `pts` it has never seen, so without one `iter_dialogs` pass a fresh - session silently gets no channel updates at all. + """Catch up, then announce presence (§6.3). + + The dialog warm-up used to run here, before the account went online, + so a large account was unusable for minutes after every restart. It + now runs in the background once the account is online + (`_start_warmup`). Catch-up does not depend on it: channels whose + `pts` the session already holds are caught up from that state, and a + channel the session has never seen has no `pts` to catch up from + whichever runs first. """ - await self._warm_entity_cache() await self.catch_up() if self.presence == "online": await self._set_presence(offline=False) + def _start_warmup(self) -> None: + """Run the dialog sweep in the background, once per session. + + One `iter_dialogs` pass seeds access hashes into Telethon's session and + `pts` for channels the update state has never seen, so their later + gaps can be fetched. Nothing waits for it: a request for a peer the + sweep has not reached yet resolves it the way it always could (session + cache, then the network, then the resolver's own dialog scan). The + client and its caches survive reconnects, so a sweep that finished is + not repeated; one that failed or was cut off by a drop runs again on + the next connect. + """ + if self._warmed or (self._warmup is not None and not self._warmup.done()): + return + self._warmup = asyncio.create_task( + self._warm_entity_cache(), name=f"tlgr-warmup-{self.alias}" + ) + async def _warm_entity_cache(self) -> None: iterator = getattr(self.client, "iter_dialogs", None) if iterator is None: @@ -402,6 +431,7 @@ async def _warm_entity_cache(self) -> None: except Exception as exc: log.debug("entity cache warm-up failed for %s: %s", self.alias, exc) else: + self._warmed = True log.debug("warmed %d dialogs for %s", count, self.alias) async def catch_up(self) -> None: From 760adf6283a0989b6d74673d9c3e7d5dbde29ed9 Mon Sep 17 00:00:00 2001 From: Pouri <94605698+erfnzdeh@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:24:52 +0330 Subject: [PATCH 4/5] Add [daemon] catch_up_interval for an optional periodic catch-up 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 --- tests/test_account_session.py | 59 +++++++++++++++++++++++++++++++++++ tlgr/core/config.py | 3 ++ tlgr/daemon/session.py | 44 +++++++++++++++++++++++++- tlgr/daemon/sessions.py | 1 + tlgr/ops/config.py | 11 +++++++ 5 files changed, 117 insertions(+), 1 deletion(-) diff --git a/tests/test_account_session.py b/tests/test_account_session.py index 96e302a..11610b4 100644 --- a/tests/test_account_session.py +++ b/tests/test_account_session.py @@ -585,3 +585,62 @@ async def test_stop_cancels_a_running_sweep(self, tlgr_home, world): task = session._warmup await session.stop() assert task is not None and task.cancelled() + + +class TestPeriodicCatchUp: + """`[daemon] catch_up_interval`, off by default, floored at 30 s.""" + + def test_the_interval_is_off_by_default_and_floored(self): + from tlgr.core.config import DaemonConfig + from tlgr.daemon.session import MIN_CATCH_UP_INTERVAL, normalise_catch_up_interval + + assert DaemonConfig().catch_up_interval == 0 + assert MIN_CATCH_UP_INTERVAL == 30 + assert normalise_catch_up_interval(0) == 0 + assert normalise_catch_up_interval(-5) == 0 + assert normalise_catch_up_interval(None) == 0 + assert normalise_catch_up_interval(1) == 30 + assert normalise_catch_up_interval(45) == 45 + + async def test_no_timer_runs_when_it_is_off(self, tlgr_home, world): + session = _session(tlgr_home, world) + await session.start() + try: + await _wait_for(lambda: session.state == SessionState.ONLINE) + names = {task.get_name() for task in session._tickers} + assert names + assert "tlgr-catchup-work" not in names + finally: + await session.stop() + + async def test_the_timer_catches_up_while_online(self, tlgr_home, world): + session = _session(tlgr_home, world, catch_up_interval=45) + assert session.catch_up_interval == 45 + # The floor protects Telegram, not the test: shorten it after construction. + session.catch_up_interval = 0.02 + await session.start() + try: + await _wait_for(lambda: session.state == SessionState.ONLINE) + first = world.catch_ups + await _wait_for(lambda: world.catch_ups >= first + 2) + finally: + await session.stop() + + async def test_the_session_manager_passes_the_config_through(self, tlgr_home, stub_account): + from fake_telethon import fake_client_factory + + from tlgr.core.config import load_app_config + from tlgr.core.paths import TlgrPaths + from tlgr.daemon.sessions import SessionManager + + (tlgr_home / "config.toml").write_text("[daemon]\ncatch_up_interval = 10\n") + manager = SessionManager( + TlgrPaths(tlgr_home), + load_app_config(tlgr_home), + client_factory=fake_client_factory(World()), + ) + try: + session = await manager.ensure(stub_account) + assert session.catch_up_interval == 30 + finally: + await manager.stop_all() diff --git a/tlgr/core/config.py b/tlgr/core/config.py index 75f27f7..5711b60 100644 --- a/tlgr/core/config.py +++ b/tlgr/core/config.py @@ -90,6 +90,9 @@ class DaemonConfig(_Section): event_workers: int = 8 resync_depth: int = 50 state_save_interval: int = 60 + #: Seconds between forced catch-ups (one `getDifference` each); 0 is off. + #: Positive values below 30 are raised to 30. + catch_up_interval: int = 0 class IdentityConfig(_Section): diff --git a/tlgr/daemon/session.py b/tlgr/daemon/session.py index e688aff..dcdafa4 100644 --- a/tlgr/daemon/session.py +++ b/tlgr/daemon/session.py @@ -53,7 +53,13 @@ log = logging.getLogger("tlgr.daemon.session") -__all__ = ["AccountSession", "SessionState", "backoff_delays"] +__all__ = [ + "MIN_CATCH_UP_INTERVAL", + "AccountSession", + "SessionState", + "backoff_delays", + "normalise_catch_up_interval", +] #: 1, 2, 4, 8, 16, 32, 60, 60… with ±20 % jitter, capped at a minute (§6.3). _BACKOFF_CAP = 60.0 @@ -74,6 +80,10 @@ #: attempts, so 1 means two attempts for a first connect and for a reconnect. _TELETHON_CONNECTION_RETRIES = 1 +#: The floor for `[daemon] catch_up_interval`. Each catch-up is one +#: `updates.getDifference`; more often than this is load without benefit. +MIN_CATCH_UP_INTERVAL = 30 + class SessionState: STARTING = "starting" @@ -96,6 +106,19 @@ def backoff_delays(attempt: int, *, cap: float = _BACKOFF_CAP) -> float: return base * (1.0 + random.uniform(-_JITTER, _JITTER)) +def normalise_catch_up_interval(seconds: float | None) -> int: + """`[daemon] catch_up_interval` as the supervisor uses it. + + Zero or less (or unset) is off. A positive value below + `MIN_CATCH_UP_INTERVAL` is raised to it, so a typo cannot turn the timer + into a stream of `getDifference` calls. + """ + value = int(seconds or 0) + if value <= 0: + return 0 + return max(MIN_CATCH_UP_INTERVAL, value) + + @dataclass class ClientOptions: """Everything `TelegramClient(...)` needs that is not the session path.""" @@ -174,6 +197,7 @@ def __init__( resync_depth: int = 50, peers_path: Path | None = None, dialog_scan_max: int = 5000, + catch_up_interval: int = 0, ) -> None: self.alias = alias self.session_path = session_path @@ -188,6 +212,7 @@ def __init__( self.resync_depth = resync_depth self.peers_path = peers_path self.dialog_scan_max = dialog_scan_max + self.catch_up_interval = normalise_catch_up_interval(catch_up_interval) self._resolver: Any = None self.client: Any = None @@ -510,6 +535,10 @@ def _start_tickers(self) -> None: asyncio.create_task(self._state_saver(), name=f"tlgr-state-{self.alias}"), asyncio.create_task(self._clock_watcher(), name=f"tlgr-clock-{self.alias}"), ] + if self.catch_up_interval: + self._tickers.append( + asyncio.create_task(self._periodic_catch_up(), name=f"tlgr-catchup-{self.alias}") + ) async def _state_saver(self) -> None: while not self._stopping: @@ -550,6 +579,19 @@ async def _clock_watcher(self) -> None: await self.catch_up() quiet_since = time.monotonic() + async def _periodic_catch_up(self) -> None: + """`[daemon] catch_up_interval`: ask for missed updates on a timer. + + Off by default. Telethon fetches a difference on its own only after + fifteen minutes without updates; on a flaky network this bounds how + late a missed update can reach `watch`, webhooks and jobs. When nothing + was missed the server answers with an empty difference. + """ + while not self._stopping: + await asyncio.sleep(self.catch_up_interval) + if self.connected and self.state == SessionState.ONLINE: + await self.catch_up() + async def _set_presence(self, *, offline: bool) -> None: """`account.updateStatus`. Telethon never sends it, so tlgr reads as offline.""" try: diff --git a/tlgr/daemon/sessions.py b/tlgr/daemon/sessions.py index e51c1be..3bf1eae 100644 --- a/tlgr/daemon/sessions.py +++ b/tlgr/daemon/sessions.py @@ -135,6 +135,7 @@ def on_state(state: str, reason: str, user_id: int | None) -> None: on_state=on_state, on_client=self._on_client, state_save_interval=self.config.daemon.state_save_interval, + catch_up_interval=self.config.daemon.catch_up_interval, presence=self.config.presence.mode, resync_depth=self.config.daemon.resync_depth, peers_path=self.paths.peers_db(alias), diff --git a/tlgr/ops/config.py b/tlgr/ops/config.py index 322eeb6..9df3eb7 100644 --- a/tlgr/ops/config.py +++ b/tlgr/ops/config.py @@ -245,6 +245,17 @@ def _key( 50, "Messages re-read per channel after a differenceTooLong.", ), + _key( + "daemon.catch_up_interval", + "daemon", + "catch_up_interval", + "int", + 0, + "Seconds between forced catch-ups (one getDifference each) while an " + "account is online; 0 is off. Values below 30 are raised to 30. Bounds " + "how late an update missed on a flaky network can arrive.", + restart=True, + ), # -- flood ------------------------------------------------------------- _key( "flood.sleep_threshold", From fcdfb0ed7851d3d0de33b930803927b5463bf29c Mon Sep 17 00:00:00 2001 From: Pouri <94605698+erfnzdeh@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:25:09 +0330 Subject: [PATCH 5/5] docs: reconnect catch-up, finite Telethon retries and catch_up_interval 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 --- CHANGELOG.md | 20 ++++++++++++++++++++ docs/design/ARCHITECTURE.md | 12 ++++++++---- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 52e8cf2..4e952ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,11 @@ codes documented in `AGENT.md` are the public API. ### Added +- **`[daemon] catch_up_interval`: a periodic catch-up.** Off by default + (`0`). When set, each online account asks for missed updates (one + `getDifference`) every that many seconds, which bounds how late an update + missed on a flaky network can reach `watch`, webhooks and jobs. Values + below 30 are raised to 30. - **`tlgr batch`: many operations from one process.** Reads JSONL (`{"op": "message.send", "params": {...}, "account": "...", "id": ...}`) from stdin or a file, runs the lines in order over the existing transport, @@ -110,6 +115,21 @@ codes documented in `AGENT.md` are the public API. ### Fixed +- **Updates missed during a connection drop arrive right after the + reconnect.** The catch-up hook wrapped `client._handle_auto_reconnect`, but + Telethon's sender keeps the method it was given at construction, so the + hook never ran and missed messages waited up to 15 minutes for Telethon's + no-updates timer. It now wraps the callback the sender calls. The client + was also built with `connection_retries=None`, which Telethon reads as + retry forever once a second: the supervisor's backoff never ran, a drop + never showed as `degraded`, and a daemon started without network stayed + in `starting`. Telethon now retries once and then hands the outage to the + supervisor, which tears down the dead connection before reconnecting and + catches up. Stopping an account that never connected no longer overwrites + the session's saved update state with zeros (which made the next start + skip everything missed while down). The full dialog sweep now runs in the + background once the account is online, instead of holding a large account + in `starting` for minutes after every restart. - **`tlgr daemon restart` completes, and the stopped daemon exits.** With a `tlgr watch` (or any `events.watch` stream) attached, a stop drained for the config's `drain_seconds` (30s) instead of the `--grace` the client diff --git a/docs/design/ARCHITECTURE.md b/docs/design/ARCHITECTURE.md index 8db9901..eca7a15 100644 --- a/docs/design/ARCHITECTURE.md +++ b/docs/design/ARCHITECTURE.md @@ -1363,7 +1363,8 @@ TelegramClient( sequential_updates=True, # ordered dispatch into the bus raise_last_call_error=True, # real RPC errors, not ValueError('unsuccessful 5 times') entity_cache_limit=int(cfg.limits.entity_cache), # default 20_000 - connection_retries=None, # our supervisor owns backoff (checklist 3) + connection_retries=1, # one quick retry, then the (checklist 3) + # supervisor owns backoff; None = forever retry_delay=1, request_retries=cfg.limits.request_retries, auto_reconnect=True, timeout=cfg.network.connect_timeout, flood_sleep_threshold=cfg.flood.sleep_threshold, @@ -1390,10 +1391,11 @@ while not stopping: await client.connect() if not await client.is_user_authorized(): -> needs_login; return me = await client.get_me() - await warm_entity_cache() # one iter_dialogs pass: seeds access hashes AND - # channel pts, without which catch_up skips channels await client.catch_up() # checklist 1 & 2 state = online; backoff.reset() + spawn(warm_entity_cache()) # one iter_dialogs pass in the background, once per + # session: seeds access hashes and pts for channels + # the update state has never seen await client.disconnected # resolves on drop or fatal error except Exception as e: cls = classify_auth(e) # core/errors.py @@ -1404,7 +1406,8 @@ while not stopping: Additional triggers for `catch_up()`: -* after **every** successful reconnect (Telethon's `_handle_auto_reconnect` only calls `get_me()`) — implemented by wrapping the client's reconnect callback in `core/telethon_compat.py`; +* after **every** successful reconnect (Telethon's `_handle_auto_reconnect` only calls `get_me()`): implemented by wrapping the callback the client's `MTProtoSender` holds (`_auto_reconnect_callback`, captured at construction) in `core/telethon_compat.py`. When Telethon's own retries run out, `disconnected` resolves and the supervisor reconnects and catches up itself; +* every `[daemon] catch_up_interval` seconds while online, when set (off by default, floor 30 s); * on a **wall-clock jump** > 60 s (laptop sleep): a 30 s ticker comparing `time.time()` deltas to `time.monotonic()` deltas; * on a `DifferenceTooLong` / `ChannelDifferenceTooLong` observation (below); * every 15 min of complete silence, as a belt-and-braces backstop, and after `getDifference` failures with 2→64 s backoff (checklist 10); @@ -1762,6 +1765,7 @@ event_buffer = 4096 # per-account ring buffer event_workers = 8 # bounded pool; per-chat order preserved resync_depth = 50 # messages re-read per dialog after *TooLong state_save_interval = 60 +catch_up_interval = 0 # seconds between forced catch-ups; 0 = off, floor 30 log_level = "info" [identity] # honest initConnection strings; stable across restarts