diff --git a/CHANGELOG.md b/CHANGELOG.md index 734e32a..52e8cf2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -110,6 +110,21 @@ codes documented in `AGENT.md` are the public API. ### Fixed +- **`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 + asked for (10s), so the restart reported "did not stop within 10s"; then + the IPC server waited aiohttp's 60s, twice, for the stream handler, which + never noticed the bus had closed its subscription, and the process stayed + up with every account stopped. Now live streams end with an `end` frame + (`reason: shutdown`, as ARCHITECTURE §6.11 always said) as soon as the + stop begins, the drain waits only for requests that finish on their own + and never past the requested `drain_s`, a job action stuck on Telegram + gets 2s and goes back to `pending.json`, a request the drain gives up on + is answered `RETRYABLE` rather than dropped, and the server cleanup waits + 2s at most. A signal that arrives while a stop is under way exits at once. + `daemon stop` waits the grace plus 15s for the teardown before falling + back to SIGTERM. - **`require_account` refuses a command without an explicit account.** It used to fall back to `[accounts] default` and then the active alias, and refused only when nothing resolved at all, so the rail passed on exactly diff --git a/tests/test_daemon_shutdown.py b/tests/test_daemon_shutdown.py new file mode 100644 index 0000000..51d7ac0 --- /dev/null +++ b/tests/test_daemon_shutdown.py @@ -0,0 +1,347 @@ +"""A stop finishes in seconds, whatever is still connected, and the process exits. + +Production, 2026-11-21: `tlgr daemon restart` failed with "the daemon did not +stop within 10s". The daemon spent twenty more seconds draining after the +restart client had given up, and then never exited: every account reported +stopped and the process sat in `S` until launchd killed it. Two things held +it, and both are reproduced here with the fake client: + +* the drain waited for requests that never end on their own (an open + `events.watch` stream, a job action stuck on Telegram), for the config's + `drain_seconds` rather than the `drain_s` the stopping client asked for; +* the IPC server's cleanup waited aiohttp's default 60 seconds for a stream + handler that did not notice the bus had closed its subscription. + +Every test bounds the stop with `STOP_BUDGET_S`. Before the fix each of them +ran into that bound (a 30 second drain plus a 60 second server cleanup). +""" + +from __future__ import annotations + +import asyncio +import json +import os +import signal +import subprocess +import sys +import textwrap +import time +from pathlib import Path + +import aiohttp +from fake_telethon import fake_client_factory, make_user +from job_helpers import ALICE, private_update + +#: How long a stop may take with something still connected. The restart +#: client waits 10 seconds; this leaves the daemon well inside that. +STOP_BUDGET_S = 5.0 + + +async def _until(predicate, timeout: float = 5.0) -> None: + deadline = asyncio.get_running_loop().time() + timeout + while not predicate(): + if asyncio.get_running_loop().time() > deadline: + raise AssertionError("condition never became true") + await asyncio.sleep(0.02) + + +def _hang_reads(world) -> asyncio.Event: + """Make every `ReadHistoryRequest` wait until the returned event is set. + + This is a Telegram call that does not come back: the shape of an action + stuck behind a slow DC or an updates difference, in flight when the stop + arrives. + """ + release = asyncio.Event() + + async def hang(request): + await release.wait() + return None + + world.raw["ReadHistoryRequest"] = hang + return release + + +def _session(daemon) -> aiohttp.ClientSession: + return aiohttp.ClientSession(connector=aiohttp.UnixConnector(path=str(daemon.paths.socket))) + + +async def _start(daemon) -> asyncio.Task: + runner = asyncio.create_task(daemon.run()) + await _until(lambda: daemon.ready) + return runner + + +async def _stopped_within(runner: asyncio.Task, budget: float = STOP_BUDGET_S) -> float: + started = time.monotonic() + try: + await asyncio.wait_for(runner, timeout=budget) + except (TimeoutError, asyncio.TimeoutError): + raise AssertionError(f"the daemon was still stopping after {budget}s") from None + return time.monotonic() - started + + +class TestTheDrain: + async def test_admin_stop_drains_for_the_time_the_caller_asked_for( + self, tlgr_home: Path, stub_account: str, world + ): + """`daemon stop --grace 10` waits 10s; the daemon used to drain for 30.""" + from tlgr.daemon.app import Daemon + + world.add_user(make_user(ALICE, username="alice")) + release = _hang_reads(world) + daemon = Daemon(tlgr_home, client_factory=fake_client_factory(world)) + assert daemon.config.daemon.drain_seconds > STOP_BUDGET_S + runner = await _start(daemon) + try: + async with _session(daemon) as http: + stuck = asyncio.create_task( + http.post( + "http://tlgr/v1/op", + json={ + "op": "message.read", + "account": stub_account, + "request": {"chat": str(ALICE)}, + }, + ) + ) + await _until(lambda: daemon.activity.in_flight >= 1) + async with http.post("http://tlgr/v1/admin/stop", json={"drain_s": 0.5}) as reply: + assert (await reply.json())["stopping"] is True + elapsed = await _stopped_within(runner) + # The request that never finished was cancelled, not left + # holding the socket, and its caller is told to retry rather + # than seeing the connection drop. + response = await asyncio.wait_for(stuck, timeout=STOP_BUDGET_S) + body = await response.json() + assert body["ok"] is False + assert body["error"]["code"] == "RETRYABLE", body + assert elapsed < STOP_BUDGET_S + assert not daemon.paths.socket.exists() + finally: + release.set() + if not runner.done(): + runner.cancel() + + async def test_a_walk_cut_off_by_the_drain_ends_with_a_retryable_frame( + self, tlgr_home: Path, stub_account: str, world + ): + """A `--all` stream the drain gives up on says so in its own framing.""" + from tlgr.daemon.app import Daemon + + release = asyncio.Event() + + async def hang(request): + await release.wait() + + world.raw["GetDialogsRequest"] = hang + daemon = Daemon(tlgr_home, client_factory=fake_client_factory(world)) + runner = await _start(daemon) + try: + async with _session(daemon) as http: + walk = await http.post( + "http://tlgr/v1/op", + json={"op": "chat.list", "account": stub_account, "all": True}, + ) + assert walk.status == 200 + await _until(lambda: daemon.activity.in_flight >= 1) + async with http.post("http://tlgr/v1/admin/stop", json={"drain_s": 0.2}): + pass + elapsed = await _stopped_within(runner) + lines = [json.loads(line) for line in (await walk.text()).splitlines() if line] + assert elapsed < STOP_BUDGET_S + assert lines[-1]["type"] == "end", lines + assert lines[-1]["ok"] is False + assert lines[-1]["error"]["code"] == "RETRYABLE" + finally: + release.set() + if not runner.done(): + runner.cancel() + + async def test_a_job_action_stuck_on_telegram_does_not_hold_the_stop( + self, tlgr_home: Path, stub_account: str, world + ): + """The gateway scheduler's in-flight action is cut short and kept for next time.""" + from tlgr.daemon.app import Daemon + + world.add_user(make_user(ALICE, username="alice")) + release = _hang_reads(world) + (tlgr_home / "jobs.yaml").write_text( + textwrap.dedent( + f"""\ + jobs: + - name: autoread + account: {stub_account} + filters: {{chat_type: private}} + actions: + - read: {{}} + """ + ) + ) + daemon = Daemon(tlgr_home, client_factory=fake_client_factory(world)) + runner = await _start(daemon) + try: + await _until(lambda: any(job.get("running") for job in daemon.list_jobs())) + scheduler = daemon.schedulers[stub_account] + session = daemon.sessions.get(stub_account) + await session.client.feed(private_update(10)) + await _until(lambda: bool(scheduler._running)) + assert daemon.activity.in_flight >= 1 + + # The signal path: no drain_s, so the config's 30s default applies. + daemon.request_shutdown() + elapsed = await _stopped_within(runner) + assert elapsed < STOP_BUDGET_S + finally: + release.set() + if not runner.done(): + runner.cancel() + + # Cut short, not lost: the action resumes at the next start. + saved = json.loads((tlgr_home / "accounts" / stub_account / "pending.json").read_text()) + assert [item["msg_id"] for item in saved["items"]] == [10] + + +class TestOpenStreams: + async def test_an_open_event_stream_ends_cleanly_and_the_daemon_stops( + self, tlgr_home: Path, stub_account: str, world + ): + """`tlgr watch` held the drain for 30s and the server cleanup for 60s more.""" + from tlgr.daemon.app import Daemon + + daemon = Daemon(tlgr_home, client_factory=fake_client_factory(world)) + runner = await _start(daemon) + frames: list[dict] = [] + try: + async with _session(daemon) as http: + response = await http.get( + "http://tlgr/v1/events", + params={"account": stub_account, "heartbeat": "1"}, + timeout=aiohttp.ClientTimeout(total=None, sock_read=None), + ) + assert response.status == 200 + + async def read_all() -> None: + async for line in response.content: + if line.strip(): + frames.append(json.loads(line)) + + reader = asyncio.create_task(read_all()) + await _until(lambda: any(f.get("type") == "watching" for f in frames)) + + daemon.request_shutdown() + elapsed = await _stopped_within(runner) + await asyncio.wait_for(reader, timeout=STOP_BUDGET_S) + assert elapsed < STOP_BUDGET_S + # Ended with the stream's own `end` frame, so a client can tell a + # stop from a dropped connection. + assert frames[-1]["type"] == "end", frames + assert frames[-1].get("ok") is True + assert frames[-1].get("reason") == "shutdown" # ARCHITECTURE §6.11 step 2 + assert daemon.activity.event_streams == 0 + finally: + if not runner.done(): + runner.cancel() + + +class TestSignals: + async def test_a_second_signal_stops_without_waiting_for_the_teardown( + self, tlgr_home: Path, stub_account: str, world + ): + """An operator who signals twice gets an exit, not another 60s wait.""" + from tlgr.daemon import main as daemon_main + from tlgr.daemon.app import Daemon + + daemon = Daemon(tlgr_home, client_factory=fake_client_factory(world)) + hung = asyncio.Event() + + async def a_teardown_that_never_ends(*, drain=None) -> None: + hung.set() + await asyncio.Event().wait() + + daemon.shutdown = a_teardown_that_never_ends # type: ignore[method-assign] + runner = asyncio.create_task(daemon_main.run(daemon)) + try: + await _until(lambda: daemon.ready) + os.kill(os.getpid(), signal.SIGTERM) + await asyncio.wait_for(hung.wait(), timeout=STOP_BUDGET_S) + os.kill(os.getpid(), signal.SIGTERM) + await _stopped_within(runner, budget=2.0) + finally: + if not runner.done(): + runner.cancel() + await asyncio.gather(runner, return_exceptions=True) + + +_WATCHER = """\ +import sys +from tlgr.transport.client import DaemonClient + +client = DaemonClient(sys.argv[1], auto_start=False) +for frame in client.stream("GET", "/v1/events", params={"account": "all", "heartbeat": 1}): + print(frame.get("type"), flush=True) +""" + + +def _alive(pid: int) -> bool: + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + return True + + +def test_a_real_daemon_with_a_watcher_attached_stops_with_one_command(tlgr_home: Path): + """The whole restart path in real processes: one `daemon stop`, then no process. + + Before the fix this is the production failure exactly: `daemon stop` + reports "did not stop within 10s" and the process outlives it. + """ + from tlgr.core.process import read_pid + from tlgr.transport.client import DaemonClient + + status = DaemonClient(tlgr_home, auto_start=True).status() + pid = int(status["daemon"]["pid"]) + assert read_pid(tlgr_home) == pid # ours: started under this temp home + env = {**os.environ, "TLGR_HOME": str(tlgr_home)} + watcher = subprocess.Popen( + [sys.executable, "-c", _WATCHER, str(tlgr_home)], + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + try: + assert watcher.stdout is not None + for _ in range(3): + if watcher.stdout.readline().strip() == "watching": + break + else: + raise AssertionError("the watcher never started streaming") + + started = time.monotonic() + stop = subprocess.run( + [sys.executable, "-m", "tlgr", "--json", "daemon", "stop"], + env=env, + capture_output=True, + text=True, + timeout=60, + ) + elapsed = time.monotonic() - started + assert stop.returncode == 0, stop.stdout + stop.stderr + assert elapsed < STOP_BUDGET_S, f"daemon stop took {elapsed:.1f}s" + for _ in range(40): + if not _alive(pid): + break + time.sleep(0.05) + assert not _alive(pid), "the daemon process outlived `daemon stop`" + # The watcher saw a clean end, not a reset, and exited on its own. + out, err = watcher.communicate(timeout=STOP_BUDGET_S) + assert watcher.returncode == 0, err + assert out.split()[-1:] == ["end"], out + finally: + if watcher.poll() is None: + watcher.kill() + watcher.wait() + if _alive(pid) and read_pid(tlgr_home) == pid: + os.kill(pid, signal.SIGKILL) diff --git a/tlgr/daemon/app.py b/tlgr/daemon/app.py index 7a9bd76..2c7a5e2 100644 --- a/tlgr/daemon/app.py +++ b/tlgr/daemon/app.py @@ -62,6 +62,22 @@ _V1_PREFIX = "/v1/" +#: How long the IPC server waits for a request handler that is still running +#: once everything else has stopped, before cancelling it. aiohttp's default is +#: 60 seconds, applied twice (wait, then cancel and wait again), and a handler +#: blocked on something that will never answer kept a stopped daemon alive for +#: all of it while the restart client had long given up. +SERVER_SHUTDOWN_GRACE_S = 2.0 + +#: How long a job action already talking to Telegram may run on at shutdown. +#: It is cut short after this, not lost: the scheduler puts it back in the +#: queue and `pending.json` resumes it at the next start. +JOB_ACTION_GRACE_S = 2.0 + +#: How long a live stream has to write its `end` frame once the shutdown has +#: told it to stop. +STREAM_CLOSE_GRACE_S = 1.0 + def _stamp(value: float | None) -> str | None: if not value: @@ -120,6 +136,13 @@ def __init__( self.ready = False self.shutting_down = asyncio.Event() self._shutdown_event = asyncio.Event() + #: The drain the stopping client asked for (`daemon stop --grace`), or + #: None for the config's `drain_seconds`. + self._requested_drain: float | None = None + #: The task of every IPC request whose handler is still running, and + #: the ones the shutdown cancelled because the drain ran out. + self._request_tasks: set[asyncio.Task[Any]] = set() + self._abandoned: set[asyncio.Task[Any]] = set() self._start_time = time.time() self._runner: web.AppRunner | None = None self._idle_task: asyncio.Task[None] | None = None @@ -340,9 +363,24 @@ async def reload_jobs(self) -> dict[str, Any]: "problems": list(jobs_file.problems), } - def request_shutdown(self) -> None: + def request_shutdown(self, drain: float | None = None) -> None: + """Ask `run()` to stop, draining for *drain* seconds if given. + + A client that says how long it will wait has to be given at most that + long: `daemon stop --grace 10` asked for ten seconds and the daemon used + to drain for the config's thirty, so the client gave up and reported a + failure while the daemon was still on its way down. + """ + if drain is not None: + drain = max(0.0, float(drain)) + if self._requested_drain is None or drain < self._requested_drain: + self._requested_drain = drain self._shutdown_event.set() + @property + def stop_requested(self) -> bool: + return self._shutdown_event.is_set() + # -- the v2 status ----------------------------------------------------- def v1_status(self) -> dict[str, Any]: @@ -391,7 +429,7 @@ def write_state(self) -> None: async def bind(self) -> web.AppRunner: """Bind the socket and start serving with `ready: false` (ROB-07).""" app = build_app(self) - runner = web.AppRunner(app, access_log=None) + runner = web.AppRunner(app, access_log=None, shutdown_timeout=SERVER_SHUTDOWN_GRACE_S) await runner.setup() site = web.UnixSite(runner, str(self.paths.socket)) await site.start() @@ -431,7 +469,7 @@ async def run(self) -> None: self._idle_task = asyncio.create_task(self._idle_monitor(), name="tlgr-idle") self._jobs_task = asyncio.create_task(self._start_jobs(), name="tlgr-jobs") await self._shutdown_event.wait() - await self.shutdown() + await self.shutdown(drain=self._requested_drain) async def _start_jobs(self) -> None: """Load `jobs.yaml` and start every enabled job, once accounts are up. @@ -467,7 +505,16 @@ async def _idle_monitor(self) -> None: return async def shutdown(self, *, drain: float | None = None) -> None: - """The ordered teardown of §6.11.""" + """The ordered teardown of §6.11, bounded so a restart can rely on it. + + Setting `shutting_down` first is what ends the live streams + (`events.watch`, `job test`, `daemon logs --follow`): each one is + racing this event and closes with its `end` frame. They are not + drained, because they never finish on their own; neither are job + actions, which are cut short after `JOB_ACTION_GRACE_S` and resume from + `pending.json`. The drain waits only for client requests that will + finish, and never past *drain*. + """ if self.shutting_down.is_set(): return self.shutting_down.set() @@ -490,8 +537,17 @@ async def shutdown(self, *, drain: float | None = None) -> None: # Wait for in-flight requests rather than cancelling them: a ten # minute scan that is killed at second 599 has cost the account the # requests it already made and produced nothing (COR-11). - while self.activity.in_flight > 0 and time.monotonic() < deadline: + # Only the requests that end on their own count here: an open event + # stream or a job action stuck on Telegram used to hold the drain to + # its deadline on every stop. + while self.activity.draining > 0 and time.monotonic() < deadline: await asyncio.sleep(0.05) + # The live streams were told to stop when `shutting_down` was set; + # this is only the moment they need to write their `end` frame. + streams_by = time.monotonic() + STREAM_CLOSE_GRACE_S + while self.activity.event_streams > 0 and time.monotonic() < streams_by: + await asyncio.sleep(0.02) + await self._cancel_requests() with contextlib.suppress(Exception): await self._job_runner.stop_all() @@ -501,7 +557,7 @@ async def shutdown(self, *, drain: float | None = None) -> None: for scheduler in list(self._schedulers.values()): self.bus.remove_handler(scheduler.on_bus) with contextlib.suppress(Exception): - await scheduler.stop(timeout=min(5.0, max(0.5, deadline - time.monotonic()))) + await scheduler.stop(timeout=JOB_ACTION_GRACE_S) # A half-written download keeps its `.part` file, so the next # `media download --resume` continues where the shutdown stopped it. with contextlib.suppress(Exception): @@ -519,6 +575,43 @@ async def shutdown(self, *, drain: float | None = None) -> None: path.unlink(missing_ok=True) log.info("daemon stopped") + async def _cancel_requests(self) -> None: + """Cancel the requests the drain gave up on, so each caller hears why. + + A request waiting on something that will never answer (a flood-wait + sleep, an account that is not coming back) otherwise outlives the + drain, and the IPC server's cleanup then waits for it while every + account already reports stopped. Cancelled here, the caller gets a + RETRYABLE answer (see `activity_middleware`) instead of a reset. + """ + left = [task for task in self._request_tasks if not task.done()] + if not left: + return + log.info( + "cancelling %d request(s) still running after the drain", + len(left), + extra={"count": len(left)}, + ) + for task in left: + self._abandoned.add(task) + task.cancel() + await asyncio.wait(left, timeout=SERVER_SHUTDOWN_GRACE_S) + + def absorb_shutdown_cancel(self) -> bool: + """True when the current request was cancelled by `_cancel_requests`. + + The caller then answers instead of re-raising; the cancellation is + cleared so the task can finish writing that answer. + """ + task = asyncio.current_task() + if task is None or task not in self._abandoned: + return False + self._abandoned.discard(task) + uncancel = getattr(task, "uncancel", None) + if uncancel is not None: + uncancel() + return True + # --------------------------------------------------------------------------- # Middleware @@ -673,6 +766,11 @@ async def flood_budget_middleware(request: web.Request, handler: Any) -> web.Str return await handler(request) +def _stopped_mid_request() -> RetryableError: + """What a request cancelled by the shutdown is answered with.""" + return RetryableError("the daemon stopped before this request finished; retry") + + @web.middleware async def activity_middleware(request: web.Request, handler: Any) -> web.StreamResponse: """Count the request, and refuse new work while shutting down (§6.11).""" @@ -681,10 +779,24 @@ async def activity_middleware(request: web.Request, handler: Any) -> web.StreamR return _error_response( request, RetryableError("the daemon is shutting down; retry in a moment") ) + task = asyncio.current_task() daemon.activity.begin_request() + if task is not None: + daemon._request_tasks.add(task) try: return await handler(request) + except asyncio.CancelledError: + if not daemon.absorb_shutdown_cancel(): + raise + # The shutdown cancelled it after the drain ran out. Answer, rather + # than drop the connection: "retry once the daemon is back" is the + # truth, and a reset reads as a crash. (A stream answers in its own + # framing, in `_handle_op_stream`, before it gets here.) + return _error_response(request, _stopped_mid_request()) finally: + if task is not None: + daemon._request_tasks.discard(task) + daemon._abandoned.discard(task) daemon.activity.end_request() @@ -729,6 +841,12 @@ async def _handle_op_stream( return _error_response(request, exc, op=op_request.op) await stream.prepare(op=spec.id, account=op_request.account, request_id=op_request.request_id) started = time.monotonic() + live = "live-stream" in spec.tags + # A live stream is open-ended, so it is counted as a stream rather than as + # a request the shutdown drain should wait for. + if live: + daemon.activity.begin_stream() + stopped = False try: # `spec` is the same object `resolve_spec` returned above; the # execute() call is what runs the policy/account/timeout prologue. @@ -739,11 +857,13 @@ async def _handle_op_stream( # frames would make a heartbeat indistinguishable from an event # for anybody reading the stream one line at a time. count = 0 - async for frame in result: + frames = _until_shutdown(daemon, result) if live else result + async for frame in frames: if not isinstance(frame, dict): # pragma: no cover - impl contract continue await stream.write(frame) count += 1 + stopped = live and daemon.shutting_down.is_set() elif hasattr(result, "__aiter__"): # A `--all` walk paces itself against the account's own limiter, # inside the daemon: v1 looped in the client and hammered the @@ -753,11 +873,57 @@ async def _handle_op_stream( ) else: count = await _stream_result(stream, result) + except asyncio.CancelledError: + if not daemon.absorb_shutdown_cancel(): + raise + # The response is already started, so the answer is the stream's own + # failing `end` frame rather than an error body. + return await stream.fail(_stopped_mid_request(), account=op_request.account) except Exception as exc: return await stream.fail(exc, account=op_request.account) - return await stream.end( - ok=True, count=count, elapsed_ms=int((time.monotonic() - started) * 1000) - ) + finally: + if live: + daemon.activity.end_stream() + end: dict[str, Any] = {"ok": True, "count": count} + if stopped: + # Told apart from the stream ending on its own terms, so a watcher + # knows to reconnect (and resume with `--since`) rather than stop. + end["reason"] = "shutdown" + return await stream.end(**end, elapsed_ms=int((time.monotonic() - started) * 1000)) + + +async def _until_shutdown(daemon: Daemon, frames: Any) -> Any: + """Yield from *frames* until the daemon starts shutting down. + + `events.watch` waits on its bus subscription with no deadline but its + `--follow-for`, and the bus closing that subscription at shutdown does not + wake it. Without this race an open `tlgr watch` kept the shutdown drain + busy to its deadline and then held the IPC server's cleanup until aiohttp + gave up on it, so the daemon reported every account stopped and never + exited. Closing the generator runs its own `finally` (the unsubscribe). + """ + iterator = frames.__aiter__() + stopping = asyncio.ensure_future(daemon.shutting_down.wait()) + try: + while True: + step = asyncio.ensure_future(iterator.__anext__()) + await asyncio.wait({step, stopping}, return_when=asyncio.FIRST_COMPLETED) + if not step.done(): + step.cancel() + with contextlib.suppress(asyncio.CancelledError, StopAsyncIteration, Exception): + await step + return + try: + frame = step.result() + except StopAsyncIteration: + return + yield frame + finally: + stopping.cancel() + aclose = getattr(iterator, "aclose", None) + if aclose is not None: + with contextlib.suppress(Exception): + await aclose() async def _stream_result(stream: NdjsonResponse, result: Any) -> int: @@ -829,11 +995,8 @@ async def handle_events(request: web.Request) -> web.StreamResponse: protocol=PROTOCOL, stream=True, ) - daemon.activity.begin_stream() - try: - return await _handle_op_stream(request, daemon, op_request) - finally: - daemon.activity.end_stream() + # Counted as a stream by `_handle_op_stream`, like any live stream. + return await _handle_op_stream(request, daemon, op_request) async def handle_status(request: web.Request) -> web.Response: @@ -868,8 +1031,9 @@ async def handle_admin(request: web.Request) -> web.Response: if action == "stop": drain = float(body.get("drain_s", daemon.config.daemon.drain_seconds)) # Answer first, then stop: a caller that never hears "stopping" cannot - # tell a graceful shutdown from a crash. - asyncio.get_running_loop().call_later(0.01, daemon.request_shutdown) + # tell a graceful shutdown from a crash. The drain is the one the caller + # asked for, because the caller is waiting exactly that long. + asyncio.get_running_loop().call_later(0.01, daemon.request_shutdown, drain) result = {"stopping": True, "drain_s": drain} elif action == "reload": result = await _reload(daemon, body.get("what") or ["config", "jobs", "policy"]) diff --git a/tlgr/daemon/dispatch.py b/tlgr/daemon/dispatch.py index 4deeb7a..0b7f98b 100644 --- a/tlgr/daemon/dispatch.py +++ b/tlgr/daemon/dispatch.py @@ -444,3 +444,18 @@ def in_flight(daemon: Daemon) -> Any: yield finally: daemon.activity.end_request() + + +@contextlib.contextmanager +def job_action(daemon: Daemon) -> Any: + """Count a job action: busy for the idle monitor, but not drained at shutdown. + + The shutdown gives a running action a short grace and then cancels it; the + scheduler requeues it and `pending.json` resumes it at the next start, so + holding the whole drain for one stuck on Telegram buys nothing. + """ + daemon.activity.begin_job_action() + try: + yield + finally: + daemon.activity.end_job_action() diff --git a/tlgr/daemon/idle.py b/tlgr/daemon/idle.py index 5cd4654..53310e6 100644 --- a/tlgr/daemon/idle.py +++ b/tlgr/daemon/idle.py @@ -29,6 +29,8 @@ class ActivityTracker: in_flight: int = 0 event_streams: int = 0 + #: The part of `in_flight` that is job actions (a gateway read, react, …). + job_actions: int = 0 transfers: int = 0 pending_logins: int = 0 webhook_enabled: bool = False @@ -58,6 +60,14 @@ def end_stream(self) -> None: self.event_streams = max(0, self.event_streams - 1) self.touch() + def begin_job_action(self) -> None: + self.job_actions += 1 + self.begin_request() + + def end_job_action(self) -> None: + self.job_actions = max(0, self.job_actions - 1) + self.end_request() + def begin_transfer(self) -> None: self.transfers += 1 self.touch() @@ -79,6 +89,17 @@ def busy(self) -> bool: or self.webhook_enabled ) + @property + def draining(self) -> int: + """The in-flight requests a shutdown drain should wait for. + + Event streams never end on their own (the shutdown closes them), and a + job action can be cut short and resumed from `pending.json`. Waiting + for either only ever ran the drain to its deadline, which is how a + restart came to wait thirty seconds for nothing. + """ + return max(0, self.in_flight - self.event_streams - self.job_actions) + def idle_seconds(self) -> float: if self.busy: return 0.0 diff --git a/tlgr/daemon/main.py b/tlgr/daemon/main.py index 45a7de9..ea9b0ad 100644 --- a/tlgr/daemon/main.py +++ b/tlgr/daemon/main.py @@ -44,15 +44,34 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: async def run(daemon: Daemon) -> None: - """Install signal handlers and run until told to stop.""" + """Install signal handlers and run until told to stop. + + The first SIGTERM/SIGINT asks for the graceful, bounded teardown. A signal + that arrives once a stop is already under way (a second signal, or the + SIGTERM `daemon stop` falls back to after its wait) means whoever is + waiting has run out of patience: the teardown is cancelled and the process + exits now. Before this the second signal set an event that was already + set, and the daemon went on waiting for whatever held it. + """ loop = asyncio.get_running_loop() + main_task = asyncio.current_task() + forced = False # A task with no reference can be garbage-collected mid-flight, which is # COR-41: a SIGHUP reload that vanished halfway through. pending: set[asyncio.Task[None]] = set() def request_stop() -> None: - log.info("shutdown requested") - daemon.request_shutdown() + nonlocal forced + if not daemon.stop_requested: + log.info("shutdown requested") + daemon.request_shutdown() + return + if forced: + return + forced = True + log.warning("shutdown requested again; exiting without finishing the teardown") + if main_task is not None: + main_task.cancel() def request_reload() -> None: log.info("reload requested (SIGHUP)") @@ -60,13 +79,29 @@ def request_reload() -> None: pending.add(task) task.add_done_callback(pending.discard) + installed: list[signal.Signals] = [] for sig in (signal.SIGTERM, signal.SIGINT): with contextlib.suppress(NotImplementedError): loop.add_signal_handler(sig, request_stop) + installed.append(sig) with contextlib.suppress(NotImplementedError, AttributeError): loop.add_signal_handler(signal.SIGHUP, request_reload) + installed.append(signal.SIGHUP) - await daemon.run() + try: + await daemon.run() + except asyncio.CancelledError: + if not forced: + raise + # 3.11+: clear the cancellation we asked for, so `asyncio.run` sees a + # task that finished rather than one still being cancelled. + uncancel = getattr(main_task, "uncancel", None) + if uncancel is not None: + uncancel() + finally: + for sig in installed: + with contextlib.suppress(Exception): + loop.remove_signal_handler(sig) async def _reload(daemon: Daemon) -> None: diff --git a/tlgr/gateway/executor.py b/tlgr/gateway/executor.py index 697eb3f..4b0999d 100644 --- a/tlgr/gateway/executor.py +++ b/tlgr/gateway/executor.py @@ -49,8 +49,8 @@ async def __call__(self, op: str, request: dict[str, Any]) -> Any: protocol=PROTOCOL, flood_wait_max=JOB_FLOOD_WAIT_MAX, ) - # Counted as a request, so the shutdown drain waits for an action - # that is half way through instead of cutting it off. - with dispatch.in_flight(self.daemon): + # Counted for idle accounting. The shutdown drain does not wait for it: + # the scheduler gives it a short grace, then cancels and requeues it. + with dispatch.job_action(self.daemon): _, _, result = await dispatch.execute(self.daemon, op_request) return to_builtins(result) if result is not None else None diff --git a/tlgr/ops/daemon.py b/tlgr/ops/daemon.py index 32d5bdc..598e4dc 100644 --- a/tlgr/ops/daemon.py +++ b/tlgr/ops/daemon.py @@ -317,6 +317,13 @@ def _start_environment(req: DaemonStartReq) -> str: ) +#: How long `daemon stop` waits past the grace before it falls back to SIGTERM. +#: The daemon's teardown after the drain is bounded (each account's disconnect, +#: a short grace for job actions and for requests the drain gave up on); this +#: is that bound with room to spare, not a guess at how slow it usually is. +STOP_TEARDOWN_S = 15.0 + + class DaemonStopReq(Request): timeout: Annotated[ int, @@ -341,7 +348,11 @@ async def daemon_stop(ctx: OpContext, req: DaemonStopReq) -> LifecycleResult: with contextlib.suppress(Exception): _admin("stop", {"drain_s": float(req.timeout)}) - deadline = time.monotonic() + max(1.0, float(req.timeout)) + # The grace is the drain the daemon was asked for; the disconnects and the + # socket teardown come after it. Waiting for the grace alone signalled a + # daemon that was still stopping exactly as asked. + waited = max(1.0, float(req.timeout)) + STOP_TEARDOWN_S + deadline = time.monotonic() + waited while time.monotonic() < deadline: if read_pid(base) is None: return LifecycleResult(stopped=True, pid=pid) @@ -349,12 +360,14 @@ async def daemon_stop(ctx: OpContext, req: DaemonStopReq) -> LifecycleResult: from tlgr.core.process import stop_daemon + # A SIGTERM while a stop is under way makes the daemon exit without + # finishing its teardown. stop_daemon(base) for _ in range(20): time.sleep(0.25) if read_pid(base) is None: return LifecycleResult(stopped=True, pid=pid) - raise DaemonError(f"the daemon (pid {pid}) did not stop within {req.timeout}s") + raise DaemonError(f"the daemon (pid {pid}) did not stop within {int(waited) + 5}s") SPEC_DAEMON_STOP = OperationSpec(