Repository navigation
fix(daemon): keep session files open until the daemon closes its clients - #65
Merged
Merged
Conversation
neoromantic
force-pushed
the
fix/per-account-cache-17
branch
from
October 22, 2026 09:48
66cb137 to
3c13b0f
Compare
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
force-pushed
the
fix/daemon-stop-writes-56
branch
from
October 22, 2026 10:23
d71450b to
6147cd3
Compare
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.
Problem
On SIGTERM or SIGINT,
@mtcute/bun's exit hook (registered throughplatform.beforeExitby 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:destroy()failed with "Database has closed" (logged at debug since Daemon doesn't close clients on shutdown or after a failed first connect #34);Reordering listeners can't fix this: they all run synchronously in one emit, so mtcute's synchronous
db.close()always ran before our asyncdestroy()could save anything.Fix
src/daemon/daemon-platform.ts:DaemonPlatform extends BunPlatformand overrides onlybeforeExit(withoverride, so a rename in mtcute fails tsc). Callbacks go into a set that one lazily installedprocess.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 publicplatformclient option; mtcute is not patched andsession.dbis untouched.createDaemonClientpassesplatform: daemonPlatform(covers connect and reconnect). CLI clients keep the stock platform.disconnectAllAccountscallsdestroy(), 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.releaseClientremoves the update handlers only afterdestroy()resolves, so a message in the batch the updates loop was dispatching when it was stopped still reaches the cache.isClosedSessionErrorand its debug branch are gone: anydestroy()failure is again the warning "Failed to close client (...)".docs/daemon.md(shutdown bullet) anddocs/testing.mddescribe 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.iterDialogsand 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). Onlyprepare()runs, so there's no network.self.store()andsetChannelPts()after the signal anddestroy()don't throw, and a reopening child reads pts 31337 and self user 4242. Neither child prints "Database has closed".setChannelPts(1, 4242)followed byprocess.exit(1)withoutdestroy()is read back as 4242.new BunPlatform()in the child (not committed):mtcuteListeners {SIGTERM: 1, SIGINT: 1},handlerRuns: 2, errorsstore: Database has closedanddestroy: Database has closed, and the reopened file haspts: null, selfUserId: null.daemon-accounts.connect.test.ts: clients fromconnectAccountandattemptReconnectgetoptions.platform === daemonPlatform. A message emitted insidedestroy()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 norefreshQueuesand logs only debug after its start line. No reconnect pass starts once stopping.daemon-accounts.tsanddaemon-bootstrap.ts.sync_jobsbeforetg 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) andbun run test:e2e(242 pass) are green locally.Risks
platform.beforeExit(theICorePlatformcontract in 0.32.6). The child test (0 listeners), the live single-SIGTERM assertion andoverridewould 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