Repository navigation
Fix daemon shutdown: honour the requested drain and exit after stopping - #56
Merged
Merged
Conversation
`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.
# Conflicts: # CHANGELOG.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What happened
tlgr daemon restarton a production daemon (26h uptime, 8 accounts, one gateway job) failed withDAEMON_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 stateSuntillaunchctl kickstart -k.Root causes (line numbers at cf6e85f)
1. The stall before the jobs are cancelled
tlgr/daemon/app.py:869-872:/v1/admin/stopreadsdrain_sfrom the client but callsrequest_shutdown()without it, sorun()(app.py:434) drains for[daemon] drain_seconds, 30s by default.daemon stop(tlgr/ops/daemon.py:342-357) sendsdrain_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 foractivity.in_flight == 0, andin_flightincludes requests that never end on their own: every streaming request (activity_middleware,app.py:684), so an openevents.watchkeeps 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: theevents.watchfollow loop waits onsub.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.AppRunneruses aiohttp's defaultshutdown_timeout=60, sorunner.cleanup()waits 60s for that still-running handler, cancels it, and waits up to 60s more. That is where shutdown hung: aftersessions.stop_all()("account ... is stopped") and beforelog.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 afterkickstart -kwas 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'sdrain_sthrough.live-streamtag:events.watch,job test,daemon logs) raceshutting_downin_handle_op_streamand 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 newdispatch.job_action()counter (still "busy" for the idle monitor), getJOB_ACTION_GRACE_S(2s) inscheduler.stop, and are requeued topending.jsonas before.RETRYABLE("the daemon stopped before this request finished; retry"): an error body for a plain request, a failingendframe 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 SIGTERMdaemon stopfalls back to) cancels the teardown and exits. Signal handlers are removed whenrun()returns.daemon stop/restart: wait the grace plusSTOP_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_admin_stop_drains_for_the_time_the_caller_asked_formessage.readwhoseReadHistoryRequestnever returns, then/v1/admin/stop {"drain_s": 0.5}; main drains 30s. Also checks the stuck caller getsRETRYABLE.test_a_walk_cut_off_by_the_drain_ends_with_a_retryable_framechat.list --allstream hung onGetDialogsRequest; ends with a failingendframe.test_a_job_action_stuck_on_telegram_does_not_hold_the_stopreadjob whose scheduled action hangs in flight; signal path (config drain 30s). Checks the action is saved topending.json.test_an_open_event_stream_ends_cleanly_and_the_daemon_stopsGET /v1/eventsstream; main holds the drain and then the server cleanup.test_a_second_signal_stops_without_waiting_for_the_teardownmain.run()with a teardown that never ends.test_a_real_daemon_with_a_watcher_attached_stops_with_one_commandpython -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)/v1/eventswatcher attachedmake check: lint, typecheck, 13627 tests, docs and parity all pass.Not verified
events.watchstream 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.kickstart -k,ExitTimeOut). The plist sets noExitTimeOut, so launchd's default applies; a 30sdrain_secondson the SIGTERM path is still longer than launchd's default 20s, but the drain now only waits for genuine client requests.