Skip to content

fix(daemon): keep session files open until the daemon closes its clients - #65

Merged
neoromantic merged 5 commits into
mainfrom
fix/daemon-stop-writes-56
Oct 22, 2026
Merged

neoromantic merged 5 commits into
mainfrom
fix/daemon-stop-writes-56

Conversation

@neoromantic

@neoromantic neoromantic commented Oct 22, 2026 •

Copy link
Copy Markdown
Owner

Problem

On SIGTERM or SIGINT, @mtcute/bun's exit hook (registered through platform.beforeExit by the session storage and its sqlite driver) saved and closed every session file at once, under clients that were still running, then sent the signal again. Until the daemon's own shutdown ran:

Reordering listeners can't fix this: they all run synchronously in one emit, so mtcute's synchronous db.close() always ran before our async destroy() could save anything.

Fix

  • New src/daemon/daemon-platform.ts: DaemonPlatform extends BunPlatform and overrides only beforeExit (with override, so a rename in mtcute fails tsc). Callbacks go into a set that one lazily installed process.once('exit') listener runs. No signal listeners, so the daemon's own handler is the only one. Device model, logger and log level are inherited, so the session's entry in Telegram's active sessions doesn't change. This uses the public platform client option; mtcute is not patched and session.db is untouched.
  • createDaemonClient passes platform: daemonPlatform (covers connect and reconnect). CLI clients keep the stock platform.
  • The stop now runs as designed: the main loop finishes its job, disconnectAllAccounts calls destroy(), which stops the updates loop, saves the update state and peers and closes the session file. If the shutdown times out (process.exit(1)), the exit listener still saves the queued writes.
  • releaseClient removes the update handlers only after destroy() resolves, so a message in the batch the updates loop was dispatching when it was stopped still reaches the cache.
  • isClosedSessionError and its debug branch are gone: any destroy() failure is again the warning "Failed to close client (...)".
  • Dialog pass: the closed session file used to abort a startup pass at its next page by accident. Now the pass checks the stop flag at each dialog. A stopped pass marks nothing for chats it didn't reach and skips the remaining accounts. A pass that completes just before the stop still marks unvisited chats. The reconnect pass doesn't start once the daemon is stopping, and a stopped one refreshes no queues. A dialog page that fails during a stop and a reconnect pass that fails during one are logged at debug. A failed save in the startup pass stays a warning even during a stop: that pass runs before the main loop and the cleanup, so a stop closes nothing under it and such an error is a real cache fault.
  • docs/daemon.md (shutdown bullet) and docs/testing.md describe the new behaviour.

Not fixed: a FLOOD_WAIT still holds the stop

A FLOOD_WAIT already being waited out in the dialog pass or in a sync job (up to 5 min) still holds the stop past tg daemon stop's 10 s timeout, exactly as before. iterDialogs and the job requests take no per-call abort signal, so the only way to cut them short is tearing the client down, which needs its own design. Filed as #64.

Tests

  • daemon-platform.test.ts (new) runs a real mtcute client on a temp session file in a child process (helpers/session-exit-child.ts). Only prepare() runs, so there's no network.
    • signal: 0 SIGTERM and SIGINT listeners from mtcute, the test's handler runs once, self.store() and setChannelPts() after the signal and destroy() don't throw, and a reopening child reads pts 31337 and self user 4242. Neither child prints "Database has closed".
    • exit: a queued setChannelPts(1, 4242) followed by process.exit(1) without destroy() is read back as 4242.
    • Red check, done once by hand with new BunPlatform() in the child (not committed): mtcuteListeners {SIGTERM: 1, SIGINT: 1}, handlerRuns: 2, errors store: Database has closed and destroy: Database has closed, and the reopened file has pts: null, selfUserId: null.
  • daemon-accounts.connect.test.ts: clients from connectAccount and attemptReconnect get options.platform === daemonPlatform. A message emitted inside destroy() lands in the account's cache: 1 handler during destroy, 0 after. The "already closed at debug" test is deleted, and the remaining close-failure test checks for the "Failed to close client (shutdown)" warning.
  • daemon-bootstrap.test.ts: a stop after the first dialog caches only that chat, logs no warning, never lists account 2, and leaves an unlisted synced chat's sync state as it was. A stop right after a complete pass still marks the left chat caught up and skips account 2. A page that fails after the stop signal is logged at debug and marks nothing; a chats save that fails after it is still the warning "Failed to bootstrap dialogs".
  • daemon-scheduler.test.ts: a stopped reconnect pass marks nothing, calls no refreshQueues and logs only debug after its start line. No reconnect pass starts once stopping.
  • The new tests fail against the old daemon-accounts.ts and daemon-bootstrap.ts.
  • Live: the daemon smoke test now waits for pending or running sync_jobs before tg daemon stop. It asserts exit 0, exactly one "Received SIGTERM", no updates-loop error, failed save or closed-database error on stdout, and no close or closed-database error on stderr. Live checks run when this ships.

bun run check, bun run test (1687 pass) and bun run test:e2e (242 pass) are green locally.

Risks

  • The fix relies on mtcute registering its storage cleanup only through platform.beforeExit (the ICorePlatform contract in 0.32.6). The child test (0 listeners), the live single-SIGTERM assertion and override would catch a change.
  • tg daemon stop --force (SIGKILL) now loses session writes since the last save. Before, they were saved at the signal. The loop saves per batch and peers are saved per call, so only the 30 s buffer of peers with an unchanged access hash is at risk.

Fixes #56

🤖 Generated with Claude Code

@neoromantic
neoromantic force-pushed the fix/per-account-cache-17 branch from 66cb137 to 3c13b0f Compare October 22, 2026 09:48
Base automatically changed from fix/per-account-cache-17 to main October 22, 2026 09:51
@neoromantic
neoromantic changed the base branch from main to stack/pr59-base October 22, 2026 09:54
neoromantic and others added 5 commits October 22, 2026 14:22
mtcute's Bun platform turns the session storage cleanup into SIGINT and
SIGTERM listeners. On a stop they saved and closed every session file
at once, under clients that were still running, and sent the signal
again, so the daemon logged "Received SIGTERM" twice. Until the daemon's
own shutdown ran, the updates loop failed to save its state and
restarted, peers seen by a running sync job weren't saved, and destroy()
failed with "Database has closed".

The daemon's clients now use a platform that runs these cleanups only
on process exit. The stop closes every client, and destroy() stops the
updates loop, saves the update state and peers and closes the session
file. The exit fallback still saves queued writes when the shutdown
times out. The update handlers stay on until destroy() returns, so a
message in the batch the updates loop was handling still reaches the
cache. The workaround that logged the closed-session error at debug is
gone.

The closed session file used to abort a startup dialog pass at its next
page by accident. Without that, a stop now ends the pass at the next
dialog, marks nothing for the chats it didn't reach and skips the
remaining accounts. A FLOOD_WAIT already in progress still holds the
stop (#64).

Fixes #56

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A background reconnect pass is what usually sees the stop: closing its
client aborts the page it waits for, so iterDialogs throws instead of
yielding. The stop tests only reached the break between dialogs. Without
`stopped = true` in the catch, that pass would mark every chat it didn't
reach unknown and refresh the queues during the stop, and turning its
debug logs back into warnings went unnoticed too.

The new cases fail a page after the stop signal on start and after a
reconnect, and close the account's cache under a reconnect pass. They
check that nothing above debug is logged, that the unlisted chats keep
their newest message ID and that no queues are refreshed or other
accounts listed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The fix for #56 dropped the branch that logged "Database has closed" at
debug, but the close-failure tests threw other errors, so putting it
back passed every test. The daemon runs without --verbose, so a
regression would go quiet again. The test now throws the #56 error and
expects the warning.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
"If the shutdown times out" read like the timeout of `tg daemon stop`,
whose error suggests --force. That sends SIGKILL, which skips the exit
save. Only the daemon's own 30-second cleanup timeout saves the queued
writes. The shutdown note now names it and says what `tg daemon stop`
reports while a FLOOD_WAIT holds the stop (#64).

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

The startup pass runs before the main loop and the cleanup, so a stop
never closes a client or a cache under it. After the signal, the only
errors that reach bootstrapDialogs' own catch are real cache faults: a
failed chats or users save, or a failed markUnvisitedChats. They must
stay warnings, since the daemon runs without --verbose. The stop tests
only covered the page that fails inside the pass, so logging these at
debug passed every test. The new case makes the chats save fail after
the stop signal and expects the warning.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@neoromantic
neoromantic force-pushed the fix/daemon-stop-writes-56 branch from d71450b to 6147cd3 Compare October 22, 2026 10:23
@neoromantic
neoromantic changed the base branch from stack/pr59-base to main October 22, 2026 10:23
@neoromantic
neoromantic merged commit 8f54e2c into main Oct 22, 2026
5 checks passed
@neoromantic
neoromantic deleted the fix/daemon-stop-writes-56 branch October 22, 2026 10:53
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 loses writes queued between the stop signal and its shutdown

1 participant