Skip to content

fix!: keep each account's cache in its own database - #59

Merged
neoromantic merged 26 commits into
mainfrom
fix/per-account-cache-17
Oct 22, 2026
Merged

neoromantic merged 26 commits into
mainfrom
fix/per-account-cache-17

Conversation

@neoromantic

@neoromantic neoromantic commented Oct 21, 2026 •

Copy link
Copy Markdown
Owner

Problem

Every account shared one cache.db, and no cache, sync-state or job table had an account column. With two accounts, chats list, contacts list, messages search and tg sql mixed both accounts' data; message IDs and basic group IDs collided; the daemon ran any job on the first connected client (selectAvailableWorker) with the other account's access hashes; tg send resolved peers with foreign hashes; a FLOOD_WAIT one account recorded blocked every account (a shorter one that mtcute sleeps through still holds the daemon's single job loop: #60). This fixes #17.

Closes #17

Design

  • Layout: <dataDir>/accounts/<id>/cache.db per account (directory mode 0700), <id> being accounts.id in data.db. data.db, session_<id>.db, config.json and daemon.pid stay at the root. A directory keeps one account's files together (backup, delete, later per-account media) and the move is still one rename. Tables are unchanged; the file is the account. A new cache_meta table stamps account_id and user_id, and a file stamped for another account fails with CACHE_UNAVAILABLE (owner_mismatch); a file of an account that is gone, stamped for the same Telegram user, is taken by that user's new account, so a re-login can get its cache back by renaming the directory.
  • Account resolution: resolveAccount: --account, else the active account, else the only one. No account gives AUTH_REQUIRED (exit 2); several and none active give NO_ACTIVE_ACCOUNT (exit 1) with details.accounts. Every cache command (chats, contacts, messages, send, me, user, api, sql) opens that account's cache before its try block, and passes the same ID to the client and the rate limits.
  • Migration of the shared cache of 0.3 and older (src/db/cache-layout.ts): under data.db's write lock, fold the WAL with journal_mode = DELETE (which also proves no older process holds the file), then adopt it for a single account (every cursor, history range, job, retry and rate limit carries over), set it aside as shared-cache.db / shared-cache-2.db (never overwritten, never merged) for zero or several accounts, or delete it when empty. A held file blocks adopting with CACHE_UNAVAILABLE (shared_cache_in_use) and only defers setting aside; any other error but a file that is not a database (read-only, full disk) does the same with move_failed, so a single account never loses its cache to a transient error. tg auth login/login-qr, logout and tg accounts remove run the move before they change the account count, and fail with CACHE_UNAVAILABLE and change no account while it is blocked or deferred, whatever the count, so a later run can't adopt a file that other accounts wrote. Rename only, never copy.
  • Daemon: one runtime per account (cache, status service, scheduler, sync worker). The job loop takes turns between accounts, one job per tick, each account with its own 3 s delay; a disconnected or flood-waiting account is skipped, and one account's failed scheduler start never stops the others. Live updates, deletes without chat context, and dialog passes land only in the receiving account's cache. daemon_status rows are per account; readers count only rows from the live PID in daemon.pid.
  • Rate limits: rate_limits and api_activity live in each account's file.
  • tg sql --account; tg sql print-schema reads an in-memory schema and needs no account.
  • tg status: totals over the accounts' caches (never creating one), account_id on every listed job, sample chat and flood wait, a storage section, then per-account cache, connection, sync, progress, rate_limits, and tg status --account. tg daemon status keeps its keys as sums and adds accounts[] and storage. Pretty tg status --account names the scoped account.
  • After a reconnect, a complete dialog pass now marks that account's unlisted chats caught up, since each pass covers its own cache.

Upgrade notes

  • Stop the daemon before upgrading. With one account the old cache becomes that account's and nothing re-syncs. With several, the old file is kept as shared-cache.db (one stderr line, listed in tg status) and each account syncs again; it can be handed to one account by hand, but only when a single account synced into it (docs/configuration.md, "Upgrading to per-account caches").
  • Going back to 0.3 after the move is not supported. Scripts that open cache.db directly must open accounts/<id>/cache.db or use tg sql --account.

Tests

  • New: multi-account.e2e (two accounts, message ID 7 in both with different text; isolation per --account 2, @beta_test, work and the active account; accounts switch; chats sync --account 2 touches only file 2; zero, one and several accounts; status breakdown; no root cache.db), cache-layout.e2e (0.2.0 cache adopted and migrated, rows still in the WAL moved to account 3, parked with one notice and none with --format quiet, empty file deleted, CACHE_UNAVAILABLE while held and adopted after, owner mismatch), cache-layout, cache-meta, daemon-start-caches.
  • Two-account variants in the scheduler (job on its own client, disconnected account's jobs stay pending, FLOOD_WAIT isolation, turns with per-account delay), bootstrap, update handlers, rate limits, daemon loop and status, restart gap (Daemon loses messages that arrive while it is stopped #15), fair share (Backfill sync doesn't run #6) and failing chats (Retry failed sync jobs with backoff #9); four processes adopting one shared cache at once.
  • Review follow-ups: fold errors (read-only file, unwritable data dir), failed mkdir/rename/delete roll back, stray sidecars, a -wal written after the fold; a scheduler start that fails for one account; stopped-daemon last_update; a cache that fails a query in tg status; tg send --account 2 and tg user --fresh --account 2 on account 2's client, hashes and api_activity only; chats get, contacts get/search, user, me with --account; commands that leave a held shared cache alone; login and remove moving the cache first, and changing no account while an older tg holds it; re-login taking an old cache back; job picking that one account's failing cache can't stall; tg status totals over two accounts' rate limits, flood waits and sample chats; the owner check of a stamped cache timed under the write lock.
  • bun run check, bun run test (1676) and bun run test:e2e (242) pass locally, and lint, typecheck and unit tests pass on every commit.
  • Live: the smoke suite passes (6 tests, daemon included). A shared cache.db written by a 2-minute daemon run of main moved to accounts/1/cache.db on the first command: tg messages search, tg chats list and tg sql (messages, sync state, history ranges, jobs, counts) returned the same data as before, and the daemon then ran 2 minutes on the new layout and stopped cleanly with tg daemon stop. Multi-account separation is covered by the seeded e2e tests, not live.

🤖 Generated with Claude Code

neoromantic and others added 26 commits October 22, 2026 13:38
Every account shared one cache.db with no account column, so chats list,
contacts list, messages search and tg sql mixed accounts, message and
basic group IDs of two accounts collided, and the daemon ran a job on the
first connected client with another account's access hashes. AGENTS.md
promises one database per account; this makes it true.

Each account now has accounts/<id>/cache.db with the same tables, and
data.db keeps only the accounts. A directory rather than cache_<id>.db
keeps one account's files together for backup and later per-account
media, and the move is still one rename. Commands resolve one account
(--account, else the active one, else the only one) before opening its
cache, and rate limits and api_activity live in that file, so one
account's FLOOD_WAIT no longer blocks another. The daemon keeps a runtime
per account (cache, scheduler, worker, status rows) and takes turns
between accounts, each with its own inter-job delay.

The first command that needs a cache moves the shared cache of 0.3 and
older under data.db's write lock, after folding its WAL with
journal_mode=DELETE, which also proves no older process holds it. One
account adopts it with every cursor, job and rate limit; with several the
rows can't be split, so the file is set aside as shared-cache*.db and
never overwritten; an empty one is deleted. A cache_meta stamp keeps a
file from being opened for another account.

The reconnect dialog pass still marks no left chat caught up; the next
commit changes that now that each pass covers its own cache.

BREAKING CHANGE: the cache moves to accounts/<id>/cache.db on first use;
stop the daemon before upgrading and don't go back to 0.3. With several
accounts the old cache is set aside and each account syncs again. Cache
commands fail with AUTH_REQUIRED without an account and with
NO_ACTIVE_ACCOUNT when several exist and none is active. Scripts that open
cache.db directly must use accounts/<id>/cache.db or tg sql --account.

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

While every account shared one cache, a chat that one account's reconnect
pass didn't list could belong to another account, so a complete pass
marked none of them caught up and an unknown top cost a checking page.
Each pass now covers its own account's cache only, so a complete one can
mark the chats it didn't list caught up, as the startup pass does. Chats
turned on with tg chats sync still get their checking page, and another
account's cache is untouched.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test read the file with no busy timeout while the process that held
the lock could still be closing its connection, which may checkpoint the
WAL under an exclusive lock, so a busy full run failed it now and then
with "database is locked".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With one cache per account, tg status and tg daemon status only gave
totals, so a stuck account hid behind a healthy one. Each account entry
now carries its cache state, live connection, job counts, progress and
rate limits, pretty output prints them under each account, and
tg status --account scopes the report to one account (account_id says
which). tg daemon status lists the same per account.

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

The fold took every SQLite error that wasn't SQLITE_BUSY as "unreadable".
A read-only cache.db (SQLITE_IOERR_LOCK), a full disk, SQLITE_CANTOPEN or
an I/O error then set the only account's shared cache aside as
shared-cache.db, printed that it "can't be split by account", and the
account started from an empty cache.

Only SQLITE_NOTADB and SQLITE_CORRUPT now mean unreadable. Any other error
is a new `error` fold state, which blocks the only account with
move_failed (strict commands fail with CACHE_UNAVAILABLE, and no empty
per-account cache gets created first) and defers setting the file aside
for several accounts. An adopter no longer runs the data-table probe, so a
failing probe can't redirect its file either.

The tests cover a read-only file, a fold that can't write its journal
files, a failed mkdir, rename and delete (each rolls back), stray sidecars
of a missing per-account cache, and a -wal written after the fold.

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

initializeScheduler awaited each account's initializeForStartup with no
try per account. If one threw (its cache still SQLITE_BUSY after the 5 s
busy_timeout, a full disk, a corrupt page), the loop stopped, and every
later account kept scheduler = null for the whole run: pickNextJob skipped
it and rebuildSyncWorker returned early, even after reconnects. The shared
scheduler of 0.3 had been created before its startup pass, so a failure
there never stopped jobs.

Each account now has its own try. A failed startup pass is logged and the
account keeps its scheduler and worker, as in 0.3: it runs its pending jobs
and the next refresh queues the rest. An account whose scheduler can't be
created at all is logged and left out with both set to null.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
summarizeDaemonStatus derived lastUpdate only from the rows whose
daemon_pid is the live daemon's. setDaemonStopped deletes daemon_pid, so
with the daemon stopped `daemon.last_update` was always null and the pretty
output lost its "Last Update" row, which 0.3 printed.

With a live daemon lastUpdate still comes from its own rows. Without one it
is the newest last_update over every account's rows; the connection and
message counts keep the live-pid filter.

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

setDaemonRunning wrote the new daemon_pid but kept connection_status,
last_update and the job counts of the previous run, and the first
writeTick ran only in the main loop, after the connections, the whole
dialog pass and the scheduler start. Because daemon_pid matched, tg status
took those rows as live: after a crash it counted an account as connected
while it was still connecting or failing, and after a clean stop it showed
an account that was already connected as disconnected, for as long as the
dialog pass took.

A start now marks each account `connecting`, drops its last error and job
counts and stamps last_update. The daemon then writes every account's tick
right after connecting and again after the schedulers start.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
readAccountStatus caught only the open of an account's cache. A cache that
opened but failed a later query (countJobs, the rate limits, the progress
counts, SQLITE_CORRUPT in an index page) threw out of collectStatus, so
tg status and tg daemon status died with an uncaught exception instead of
the JSON error shape, and every account's figures were lost. 0.3 wrapped
these reads in a try with defaults.

Every query now runs inside the same guard as the open: such an account
reads as `cache: { status: 'error', error }` with zeroed figures, and the
other accounts and the daemon section still report.

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

send.test.ts gave every account the same cache and a client that ignored
the account ID, so nothing proved the Fixed entry "tg send resolved
recipients with access hashes that another account cached", or that the
same account ID reaches the cache, the client and the rate limits. A
regression to getClientForAccount(undefined), or resolving the recipient
from the active account's cache, would send from the wrong account and
every test would still pass.

send.test.ts and user.test.ts now back the db mock with one cache per
account and hand out one client per account. `tg send --account 2` must
call only account 2's client, with the access hash account 2 cached, and
log the call in account 2's api_activity; without --account the active
account does all of it. `tg user 202 --fresh --account 2` must fetch on
account 2's client and cache the user only in account 2's cache.

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

In "writes each account's tick to its own cache", account 1 has no
scheduler, so its tick takes the raw COUNT over sync_jobs. Its cache had no
jobs, so `pendingJobs: 0` held whatever that query returned: a fallback
that always returned 0 passed, while tg daemon status would show nothing
queued for a disconnected account with a backlog.

Account 1's cache now has a pending, a running, a failed and a completed
job, and its tick must report one pending and one running.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
statusCommand called collectStorageStatus and threw the result away. The
most common blocked upgrade is a 0.3 daemon still running after
`brew upgrade`: daemon.pid is live, the adopt is blocked as
shared_cache_in_use, no accounts/<id>/cache.db exists yet, and every
account reads empty. tg daemon status then printed `running` with every
figure at 0 and nothing that said the cache waits to move or that
`tg daemon stop` fixes it.

The output now has `storage`, the same { legacy_caches, migration } as
tg status. An e2e case holds the root cache.db open behind a live
daemon.pid and expects migration.reason shared_cache_in_use.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
snapshot() covered chats list and search, contacts list, messages search
and sql. tg chats get, contacts get, contacts search, tg user and tg me
were switched to openAccountCache too, but none ran with --account against
two caches: one that dropped args.account would silently read the active
account and no test would fail.

The snapshot now also runs those five, and each account's cache holds its
own user for tg me. --account 2, @beta_test and work must see account 2's
chat, contact and user; without --account account 1 must not.

A cache-layout case pins down that --version, --help, accounts list and
config path exit 0 and leave a held shared cache.db untouched, so they keep
working while an older daemon has it open.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The adopt-or-set-aside decision counts the accounts the first time a
command needs a cache, and tg auth login, tg accounts and tg config never
made it. A single-account user who upgraded and then added a second account
before any cache command lost the adoption: the next command set the
shared cache aside as shared-cache.db and account 1 started empty, though
the docs promise that one account keeps everything. Removing an account
had the mirror problem: with two accounts, `tg accounts remove` left one,
and the next command handed that account the rows both had written.

tg auth login and login-qr now run the move in strict mode before anything
else, so with one account the file becomes its cache first, and while an
older tg still holds it the login fails with CACHE_UNAVAILABLE and adds no
account. tg auth logout and tg accounts remove run it in report mode
before they delete the row. accounts list, config, daemon stop, --help and
--version still leave the file alone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
tg auth logout and tg accounts remove delete the account row, so the next
tg auth login gets a new AUTOINCREMENT ID and the same Telegram user
starts an empty accounts/<new>/cache.db, re-syncing everything; the shared
cache of 0.3 survived a re-login. The obvious recovery, renaming
accounts/<old>/ to accounts/<new>/, failed with owner_mismatch, because
the stamped account_id was compared before the user, and the suggestion
to put it back under its account was impossible since that account was
gone.

checkCacheOwner now stamps such a file for the account that opens it when
the stamped user_id is that account's user and the stamped account ID is
gone from data.db or now belongs to another user (a recreated data.db).
A file of another Telegram user, or one without a user stamp, is still
refused. configuration.md, auth.md and the CHANGELOG describe the re-login
flow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Pretty output never showed `account_id`. With --account,
accounts.accounts holds one entry, so the `length <= 1` early return
dropped the per-account line too, and the Accounts section still showed
the overall Total and the active account. `tg status --account work
--format pretty` with two accounts printed account 2's Sync Jobs, Progress
and Rate Limits under "Total 2 / Active +1…0001", so they read as totals
for every account.

A line under the title now names the scoped account and says the Daemon
section covers every account, and the early return looks at
accounts.total, so the scoped account's own line still prints.
cli-commands.md says accounts.total stays the overall count.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The one-time stderr notice pointed to "Upgrading to per-account caches" in
docs/configuration.md, and the pretty Storage section to
docs/configuration.md. Users of the Homebrew binary or the npm package have
no docs/ directory next to them.

Both now print the full GitHub URL of that section, from one constant in
cache-layout.ts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
configuration.md and database-schema.md explained how to hand
shared-cache.db to one account by hand, but not that with several
accounts the file holds all of their chats, users, messages and jobs. tg
stamps the handed-over file for the target account and then serves the
other accounts' rows as its own, foreign access hashes for tg send
included: the mixing #17 removes.

Both now say to hand it over only when a single account synced into it,
and otherwise to keep it as an archive and read it with sqlite3.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
daemon.md said one account's FLOOD_WAIT doesn't stop the others, and the
CHANGELOG said one account's FLOOD_WAIT no longer blocks every account.
That holds only for a wait long enough to be recorded in the account's
rate_limits (over 60 s in the CLI, 5 minutes in the daemon). A shorter
one, which mtcute's flood waiter sleeps through inside the job, still
holds the daemon's single job loop and so every account, as
rate-limiting.md's note and #60 say.

daemon.md, rate-limiting.md, database-schema.md, the CHANGELOG and a code
comment now draw that line and link #60, and ROADMAP.md lists #60 under
Reliability.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
tg accounts remove and tg auth logout ran the move in report mode and
deleted the row whatever it returned. With two accounts and an older tg
still holding the shared cache.db, the move is deferred, so the removal
went ahead and left one account. Once the older tg exited, the next
command saw one account and no per-account cache and adopted the shared
file, handing account 1 account 2's messages and access hashes. A login
with no accounts had the same gap: strict mode only threw for a blocked
adoption, so it added account 1, and the next run adopted a file that
removed accounts had written.

The move decides by the account count when it runs, so any account change
while it waits decides for it later. tg auth login, login-qr, logout and
tg accounts remove now fail with CACHE_UNAVAILABLE and change no account
while the file is held or can't be moved, whatever the count. The strict
and report distinction for these commands went away with it. The in-use
message no longer says the file moves "to its account", which was wrong
when it is set aside.

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

pickNextJob read each account's rate_limits (canMakeApiCall) and sync_jobs
(getNextJob) with no try per account. A corrupt page, an I/O error or a
lock held past busy_timeout in one cache threw out of processJobs, and the
main loop only logged "Error processing jobs". lastJobAccountId moves only
when a job runs, so every tick started the walk at the same account: if
the failing account came first, the others never got a turn. Every other
per-account path in the daemon already catches its own errors.

Each account's checks now have their own try. A failure is logged as that
account's, and the account waits out its 3-second delay before it is tried
again, so it neither stalls the others nor floods the log every tick. The
in-memory delay check now runs before the cache reads.

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

The case ran tg chats sync 202 without --account. 202 is Bob, a users_cache
row in account 2 with no private chat row, so the lookup misses in either
cache and fails with the same INVALID_ARGS whichever cache it reads. Only
the account_id in the details carried weight: chats sync reading account
2's cache, or both, without --account would still have passed.

It now syncs Book Club (-4242), which only account 2's chats_cache holds
and --account 2 syncs in the case before. Account 1, the active one, must
reject it and get no sync state for it.

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

collectStatus sums api_calls_last_minute, merges calls_by_method, joins
both accounts' flood waits with account_id and sorts sample_chats into an
overall top 5. cli-commands.md documents all of it, but no test had a
call, a flood wait or an enabled chat in either cache: a broken merge, a
flood wait without account_id or a wrong order would have passed, and so
would a missing acct:<id> tag in pretty output.

A new block seeds calls of the same method in both caches, a flood wait in
account 2 and three enabled chats per account, then checks the sums, the
flood wait's account, the cross-account order and cap, the --account
scope and the pretty lines. The calls are stamped with the current second,
not the minute's start, so a minute boundary can't drop them.

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

checkCacheOwner only reads a file that is already stamped, so opening a
cache never waits for the daemon's write lock. The test that pins that
down timed only initCacheSchema and initSyncSchema, not the owner check
that every getAccountCacheDb now runs: one that always took the write lock
would queue every CLI command behind daemon write batches, and no test
would fail.

The file is now stamped for its account before the holder takes the lock,
and the timed section includes checkCacheOwner. Making the check always
take the lock fails it at about 1.5 s against the 500 ms bound.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI failed "lets several processes move a shared cache to its only account
at once": two of the four processes got "database is locked" within
250 ms, far inside busy_timeout. The move folds the shared cache to
journal_mode = DELETE, so every process that opens the moved file runs
PRAGMA journal_mode = WAL on a file that is not in WAL. SQLite gives all
but one of them SQLITE_BUSY at once, without the busy handler, because
waiting could deadlock. A new file opened by several processes at once
does the same. A probe of six processes per file failed about one open in
five on macOS and Linux, so the daemon and a command started right after
an upgrade or a first login could fail to open the cache.

enableWal tries the switch again every 10 ms for up to 5 s while it gets
SQLITE_BUSY; the cache schema and data.db use it. A new test opens new and
folded files from six processes at once in three rounds each; it fails
every run without the retry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s open a cache at once

The test added with the WAL retry, six processes opening a new cache at
once, still failed about one run in six. ensureMessageSearchIndex decided
from plain reads and then dropped, created and filled message_search
statement by statement. A process that read the table while another was
creating it could find no columns, drop the triggers and the table the
other one was filling, and fail with "vtable constructor failed" or "no
such table"; the rebuild's deferred transaction read first and could then
fail to take the lock with "database is locked". The daemon and a command
started right after the first login open a new cache this way, and any two
processes do after a search index version bump.

The check still runs as a read, so an up-to-date index never waits for the
lock. When there is work, it runs in one immediate transaction and is
checked again there, the way the peer ID migration does: one process
builds the index while the others wait and then find nothing left. A new
test has four processes queue behind a held lock on an index without the
files column; it failed three runs in four before and passes every run
now, as does the six-process test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@neoromantic
neoromantic force-pushed the fix/per-account-cache-17 branch from 66cb137 to 3c13b0f Compare October 22, 2026 09:48
@neoromantic
neoromantic merged commit f4f0ac5 into main Oct 22, 2026
5 checks passed
@neoromantic
neoromantic deleted the fix/per-account-cache-17 branch October 22, 2026 09:51
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.

All accounts share one cache database

1 participant