Skip to content

fix(daemon): close clients on shutdown and after a failed first connect - #52

Merged
neoromantic merged 3 commits into
mainfrom
fix/daemon-close-clients-34
Oct 21, 2026
Merged

neoromantic merged 3 commits into
mainfrom
fix/daemon-close-clients-34

Conversation

@neoromantic

@neoromantic neoromantic commented Oct 21, 2026 •

Copy link
Copy Markdown
Owner

What and why

Fixes #34.

Problem. The daemon left Telegram clients open in two paths:

  • connectAccount kept the new client in a local variable until the connect succeeded. A failed start(), getMe() or startUpdatesLoop() left that client, its connection and its session file open until the daemon stopped.
  • disconnectAllAccounts (graceful shutdown: tg daemon stop, SIGTERM, SIGINT) only dropped its reference to each client. It never called destroy(), so the updates loops and Telegram connections were left to the process exit.

The session files themselves were not at risk: @mtcute/bun's exit hook already saves and closes every session file when SIGTERM or SIGINT arrives, and the updates loop saves its state after every batch. The issue text assumed otherwise.

Fix. Both paths now use the existing releaseClient helper (remove handlers, drop the sync worker, closeClientSafe → destroy()), as attemptReconnect already does:

  • connectAccount puts the client in the account state right after it creates it and releases it in its catch. The duplicate-account merge path also releases it through releaseClient, not a bare closeClientSafe.
  • disconnectAllAccounts releases every account in parallel, so one slow close doesn't use up the 30 s shutdown timeout for the others.
  • releaseClient takes the client out of the account state before it closes it. That's why each client closes exactly once: after the merge path, a reconnect or a failed connect, shutdown finds no client left to close. It now also catches a handler-removal error, the defensive try the old shutdown loop had, so that error can't skip the close.

Quiet stop. Because mtcute's exit hook closes the session files first, the shutdown destroy() runs against a closed database. When anything was queued after the signal (pts from an update batch, a peer seen by a sync job), it fails with "Database has closed". That only means mtcute got there first, so closeClientSafe logs that error at debug instead of warn; other close errors still warn. No supported mtcute option turns the sqlite driver's hook off. The writes lost in that window are older than this PR and tracked in #56.

The issue asked for both paths to go through closeClientSafe. They do, through releaseClient. That helper owns the "take it out of the state, then close it" step, so reusing it keeps the double-close guard in one place. The code diff stays inside src/daemon/daemon-accounts.ts and touches no DB access.

docs/daemon.md ("Error Handling & Resilience") now says the daemon closes a client right after a failed first connect, and that on shutdown it closes every client once, which stops its updates loop and closes its connections, while mtcute saves and closes the session files when the signal arrives.

How I checked it

The unit tests in src/__tests__/daemon-accounts.connect.test.ts use the mocked mtcute client. Seven of them fail without the change:

  • connectAccount closes the client when start, getMe or the updates loop fails: destroy() is called once, the handlers are gone and the state has no client. A later shutdown doesn't call it again.
  • disconnectAllAccounts closes every client once on shutdown: two connected accounts plus one whose connect failed. Each destroy() is called once, and a second shutdown call closes nothing.
  • disconnectAllAccounts still closes the other clients when one destroy() throws.
  • A "Database has closed" error on shutdown is logged at debug, with no warning.
  • In the reconnect test, shutdown closes the new client once and doesn't touch the old one again.
  • The duplicate-merge test now checks that destroy() is called exactly once, including after shutdown.

The exit-hook behaviour was reproduced offline with mtcute 0.32.6 and a temp session file: after a SIGTERM, destroy() succeeds when nothing was queued and throws "Database has closed" when a write was queued after the signal.

The live daemon smoke test (src/__integration__/telegram.integration.test.ts) now asserts that the daemon's stderr has no Failed to close client line after tg daemon stop. It passed against the real API with a copy of the test session.

Commands:

  • bun run check: clean

  • bun run test: 1561 pass (cache-db-lock.test.ts failed once in one run and passed on rerun; it doesn't touch the daemon)

  • bun run test:e2e: 193 pass

  • bun run test:integration -t "daemon connects": 1 pass

  • Tests pass locally and use made-up data only

  • README, docs and affected demos follow the product content standard

  • Title follows the repo's commit style: Conventional Commits (feat: …, fix: …) unless AGENTS.md says otherwise

🤖 Generated with Claude Code

neoromantic and others added 3 commits October 22, 2026 00:50
disconnectAllAccounts only dropped its reference to each client, so a
graceful stop never called destroy(): mtcute didn't save and close the
session files, and the next start could begin from stale update state.
connectAccount kept the client in a local variable until the connect
succeeded, so a failed start(), getMe() or updates loop left it open.

connectAccount now tracks the client in the account state right away and
releases it in its catch, like attemptReconnect does, and shutdown releases
every account through the same releaseClient. releaseClient takes the
client out of the account state before it closes it, so the duplicate
merge path, a reconnect and shutdown can't close one client twice. The
clients close in parallel, so one slow close doesn't use up the shutdown
timeout for the others, and a handler removal error no longer skips the
close.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…a stop

The shutdown bullet and the disconnectAllAccounts JSDoc said that closing
the clients makes mtcute save and close the session files, update state
included. It doesn't: @mtcute/bun's exit hook already saves and closes
every session file when SIGTERM or SIGINT arrives, before the daemon's
shutdown runs, and the updates loop saves its state after every batch.
Closing a client on shutdown stops its updates loop and closes its
Telegram connections. The failed-connect bullet now also names the
connection it no longer leaves open.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n a stop

mtcute's exit hook closes every session file when SIGTERM or SIGINT
arrives, so on a normal stop the daemon's destroy() runs against a closed
database. When anything was queued after the signal (pts from an update
batch, a peer seen during a sync job), destroy() fails with "Database has
closed", and the daemon logged "Failed to close client (shutdown)" as a
warning for every busy account on every tg daemon stop.

That error only means mtcute got there first, so closeClientSafe now logs
it at debug. Other close errors still warn. The live daemon smoke test
checks that a normal stop logs no close warning.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@neoromantic
neoromantic merged commit d85b645 into main Oct 21, 2026
5 checks passed
@neoromantic
neoromantic deleted the fix/daemon-close-clients-34 branch October 21, 2026 21:45
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.

Daemon doesn't close clients on shutdown or after a failed first connect

1 participant