Skip to content

Fix daemon shutdown: honour the requested drain and exit after stopping - #56

Merged
erfnzdeh merged 2 commits into
mainfrom
fix/daemon-shutdown
Nov 21, 2026
Merged

erfnzdeh merged 2 commits into
mainfrom
fix/daemon-shutdown

Conversation

@erfnzdeh

Copy link
Copy Markdown
Collaborator

What happened

tlgr daemon restart on a production daemon (26h uptime, 8 accounts, one gateway job) failed with DAEMON_ERROR: the daemon (pid 2055) did not stop within 10s. The log shows the job cancelled 20s after the first logged "shutdown requested", every account stopped, then nothing: no "daemon stopped", process alive in state S until launchctl kickstart -k.

Root causes (line numbers at cf6e85f)

1. The stall before the jobs are cancelled

  • tlgr/daemon/app.py:869-872: /v1/admin/stop reads drain_s from the client but calls request_shutdown() without it, so run() (app.py:434) drains for [daemon] drain_seconds, 30s by default. daemon stop (tlgr/ops/daemon.py:342-357) sends drain_s=10, waits 10s, sends SIGTERM (that is the "shutdown requested" line, 10s after the real start), waits 5s and gives up. 30s after the admin stop is exactly when the job was cancelled.
  • app.py:493: the drain waits for activity.in_flight == 0, and in_flight includes requests that never end on their own: every streaming request (activity_middleware, app.py:684), so an open events.watch keeps it above zero, and job actions (tlgr/gateway/executor.py:54), so an action stuck on Telegram does too. The drain therefore always ran to its deadline.

2. The process that does not exit

  • tlgr/ops/events.py:953-967: the events.watch follow loop waits on sub.queue.get() and never checks whether its subscriber was closed. EventBus.stop() closes subscribers (tlgr/daemon/events.py:520-521), but nothing wakes the waiter, and the heartbeat keeps it looping until --follow-for (3600s).
  • app.py:394 + app.py:515: web.AppRunner uses aiohttp's default shutdown_timeout=60, so runner.cleanup() waits 60s for that still-running handler, cancels it, and waits up to 60s more. That is where shutdown hung: after sessions.stop_all() ("account ... is stopped") and before log.info("daemon stopped"), which never appeared.
  • tlgr/daemon/main.py:53-55: a second SIGTERM only sets an event that is already set, so it changes nothing. The exit after kickstart -k was not this code path (most likely launchd's own escalation, or the watcher going away; I could not confirm which from the log).

No non-daemon thread or executor was involved: shutdown never reached the end of Daemon.shutdown().

Changes

  • request_shutdown(drain=...); admin stop passes the client's drain_s through.
  • Live streams (live-stream tag: events.watch, job test, daemon logs) race shutting_down in _handle_op_stream and end with {"type": "end", "ok": true, "reason": "shutdown"}, which is what ARCHITECTURE 6.11 step 2 already specifies. They are counted as streams, not as drainable requests.
  • ActivityTracker.draining = in-flight requests minus live streams minus job actions; the drain waits only for that. Job actions use a new dispatch.job_action() counter (still "busy" for the idle monitor), get JOB_ACTION_GRACE_S (2s) in scheduler.stop, and are requeued to pending.json as before.
  • Requests still running when the drain ends are cancelled (6.11 step 3) and answered RETRYABLE ("the daemon stopped before this request finished; retry"): an error body for a plain request, a failing end frame for a stream.
  • AppRunner(shutdown_timeout=2.0) as a backstop.
  • main.run(): a signal that arrives while a stop is already under way (a second signal, or the SIGTERM daemon stop falls back to) cancels the teardown and exits. Signal handlers are removed when run() returns.
  • daemon stop/restart: wait the grace plus STOP_TEARDOWN_S (15s) before the SIGTERM fallback, since the teardown after the drain is bounded but not zero. With the daemon fixed, the default 10s grace is no longer the binding limit, so I left it alone.

Tests

tests/test_daemon_shutdown.py, all six fail on main and pass here (each bounded at 5s, the file runs in about 6s):

test reproduces
test_admin_stop_drains_for_the_time_the_caller_asked_for a message.read whose ReadHistoryRequest never returns, then /v1/admin/stop {"drain_s": 0.5}; main drains 30s. Also checks the stuck caller gets RETRYABLE.
test_a_walk_cut_off_by_the_drain_ends_with_a_retryable_frame a chat.list --all stream hung on GetDialogsRequest; ends with a failing end frame.
test_a_job_action_stuck_on_telegram_does_not_hold_the_stop a gateway read job whose scheduled action hangs in flight; signal path (config drain 30s). Checks the action is saved to pending.json.
test_an_open_event_stream_ends_cleanly_and_the_daemon_stops an open GET /v1/events stream; main holds the drain and then the server cleanup.
test_a_second_signal_stops_without_waiting_for_the_teardown two real SIGTERMs to main.run() with a teardown that never ends.
test_a_real_daemon_with_a_watcher_attached_stops_with_one_command real daemon process + a watcher process + python -m tlgr daemon stop. On main this prints the production error verbatim: the daemon (pid N) did not stop within 10s.

Measured (real daemon process, temp home, /v1/admin/stop {"drain_s": 10} until the pid is gone)

no watcher /v1/events watcher attached
main 0.07s still running after 120s (killed)
this branch 0.10s 0.10s

make check: lint, typecheck, 13627 tests, docs and parity all pass.

Not verified

  • What held the production daemon's drain. An open events.watch stream fits both symptoms exactly, but I did not inspect the production socket; the fix also covers a stuck plain request and a stuck job action.
  • Behaviour under launchd itself (kickstart -k, ExitTimeOut). The plist sets no ExitTimeOut, so launchd's default applies; a 30s drain_seconds on the SIGTERM path is still longer than launchd's default 20s, but the drain now only waits for genuine client requests.

`tlgr daemon restart` failed in production with "the daemon did not stop
within 10s", and the stopped daemon never exited until launchd killed it.

Defect 1, the stall before jobs are cancelled: `/v1/admin/stop` ignored
the `drain_s` the client sent and the shutdown drained for the config's
`drain_seconds` (30s) while `daemon stop` waited 10s. The drain also
counted requests that never end on their own (an open `events.watch`
stream, a job action stuck on Telegram), so it always ran to its deadline.

Defect 2, the process that does not exit: `events.watch` never noticed
the bus closing its subscription, so its handler kept running, and
`AppRunner.cleanup()` waited aiohttp's default 60s for it, then cancelled
and waited up to 60s more. "daemon stopped" was never logged. A second
SIGTERM only set an event that was already set.

Changes:
- request_shutdown() takes the drain; admin stop passes `drain_s` through.
- Live streams race `shutting_down` and end with an `end` frame carrying
  `reason: shutdown` (ARCHITECTURE 6.11 step 2), counted as streams.
- The drain waits only for client requests (`ActivityTracker.draining`);
  job actions are counted separately, get a 2s grace and are requeued
  to `pending.json`.
- Requests still running after the drain are cancelled and answered
  RETRYABLE (an error body, or a failing `end` frame for a stream).
- AppRunner shutdown_timeout is 2s.
- A signal arriving while a stop is under way cancels the teardown and
  exits; signal handlers are removed when run() returns.
- `daemon stop` waits the grace plus 15s before falling back to SIGTERM.

tests/test_daemon_shutdown.py reproduces each case with the fake client
and a real daemon process; all six fail on main and pass here.
@erfnzdeh
erfnzdeh merged commit 2f303da into main Nov 21, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant