Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
12 changes: 8 additions & 4 deletions docs/design/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand All @@ -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);
Expand Down Expand Up @@ -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
Expand Down
317 changes: 317 additions & 0 deletions tests/test_account_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,3 +327,320 @@ 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()


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

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()

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()


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()


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()
Loading
Loading