Skip to content

feat(db): cache size reporting, retention pruning, tg db vacuum and a contentless search index - #79

Merged
neoromantic merged 13 commits into
mainfrom
feat/cache-size-management-1
Oct 22, 2026
Merged

neoromantic merged 13 commits into
mainfrom
feat/cache-size-management-1

Conversation

@neoromantic

@neoromantic neoromantic commented Oct 22, 2026 •

Copy link
Copy Markdown
Owner

Problem

Nothing kept a cache from growing (#1). No code ran VACUUM or set auto_vacuum. api_activity and rate_limits had prune functions that nothing called, and the window prune would have dropped a FLOOD_WAIT that was still running. Only finished sync jobs were cleaned, after a hardcoded 24 hours. tg status showed no sizes. message_search also kept a full copy of every message's text, sender and chat that search never reads.

Change

Four feature commits, each with its docs and tests, then review fixes:

  1. feat(daemon): retention. pruneCache (src/db/cache-maintenance.ts) deletes old api_activity, rate_limits windows and completed and failed sync_jobs in batches of 5,000 rows. It keeps a FLOOD_WAIT that is still running, the current 60 s window, and every pending or running job. The daemon runs it for every open account on its existing cleanup schedule (cleanupOldJobs; only its body changed). Retention lives in config.json under cache.retention.{apiActivity,rateLimits,completedJobs,failedJobs}, with defaults 7d, 1h, 24h and 24h, and a value of 0 is rejected. The daemon reads these keys once at start and never strictly: a bad value logs one warning and uses the default. The unused RateLimitsService.pruneOldWindows/pruneOldActivity are removed.

  2. feat(status): cache size. accounts.accounts[].cache.size gives file_bytes, wal_bytes, page counts, free_pages/free_bytes and auto_vacuum. storage.cache_bytes sums the accounts in scope. --sizes adds bytes per table from dbstat, with indexes and FTS5 shadow tables counted under their table. It is opt-in because dbstat reads every page. Pretty output shows a Cache Size section and suggests tg db vacuum when more than 10% of a file is free.

  3. feat(db): tg db vacuum [--account]. It prunes first, then compacts:

    • With the daemon stopped it runs a full VACUUM, which also switches the file to incremental auto_vacuum. If the rewrite moved messages_cache rowids, it rebuilds the search index.
    • With the daemon running it runs incremental_vacuum in short steps.
    • On an older cache that has no auto_vacuum while the daemon runs, it returns DAEMON_ALREADY_RUNNING before writing anything.
    • Busy and full-disk errors map to GENERAL_ERROR with details.reason set to cache_busy or disk_full. The prune commits as it goes, so errors after it carry details.pruned, and disk_full says the VACUUM was rolled back, not that the cache is unchanged.
    • Both modes end with a TRUNCATE checkpoint. While the daemon runs it has no busy wait, so a reader on an old snapshot makes it report checkpointed: false instead of holding the daemon's writes.
    • When the daemon runs and a cache has no auto_vacuum, the status hint is tg daemon stop && tg db vacuum --account <id> && tg daemon start.

    New cache files get auto_vacuum = INCREMENTAL. It is set only on an empty file, because on an existing one the pragma waits for the write lock, and opening a cache must not wait. Every connection sets journal_size_limit to 64 MB.

  4. feat(search): contentless index. Where sqlite_version() >= 3.43.0, message_search is fts5(text, sender, chat, files, content='', contentless_delete=1, tokenize='unicode61'). The first open migrates an existing cache inside the existing locked transaction, which now waits up to 60 s for the lock. SEARCH_INDEX_VERSION stays 1, so a 0.4.x tg on the same SQLite still works. An older SQLite drops only the three triggers and marks the index stale, so message writes keep working. A newer SQLite rebuilds the index on its next open. The search query does not change: it already joins messages_cache by rowid, and nothing uses snippet, highlight or bm25.

Upgrading: stop the daemon before you upgrade. Then run tg db vacuum once with the daemon stopped. This gives the old index's pages back to the disk and switches the cache to incremental mode, after which tg db vacuum also works while the daemon runs. tg sql queries that read message_search's own columns (text, sender, chat, files, or snippet()/highlight() over it) now get NULL; join messages_cache by rowid for the text, as tg messages search does.

Measurements (made-up data)

A throwaway script, not committed, wrote 20,000 synthetic messages to a temp file through initCacheSchema + initSyncSchema + createMessagesCache().upsertBatch. It used 50 made-up users, 20 made-up groups, 3–32 words per message with Latin and Cyrillic, and mtcute-shaped raw_json. Each write took about 0.5–0.7 s. Bytes per message come from dbstat, with indexes counted under their table:

Mix messages_cache message_search regular message_search contentless file regular file contentless saving
text only 910 330 100 1,253 1,023 18.3%
1 in 10 with a photo 1,736 318 98 2,066 1,846 10.6%
  • raw_json is 43% of the file for text only (538 B/msg) and 61% with photos (1,252 B/msg). It is not compressed in this change.
  • Follow-up idea for raw_json: a synthetic photo message's raw_json is about 7.7 KB, because Uint8Array fields (fileReference, the stripped thumbnail) serialize as objects with one key per byte. Base64 earlier took such a message from 7,141 to 1,330 B. Per-row gzip helped little (706 to 448 B).
  • sqlite_version() with ENABLE_FTS5 and ENABLE_DBSTAT_VTAB was 3.54.0 both from bun run (Bun 1.4.3, macOS) and from a bun build --compile binary, and contentless_delete=1 worked in both.

Tests

  • Unit:
    • cache-maintenance.test.ts: prune by retention, flood waits, the current window, batches, sizes, auto_vacuum, full and incremental vacuum, the rowid guard.
    • config.test.ts: the retention keys, loadRetentionConfig fallbacks.
    • daemon-scheduler.test.ts and daemon-loop.test.ts: every runtime pruned, one failing account only warns.
    • sync-schema.test.ts: contentless DDL, the migration once, the old-SQLite fallback and recovery.
    • messages-search.test.ts: deep-equal results on regular and contentless indexes for text, Cyrillic, sender and chat queries, and an edited message.
    • status-accounts.test.ts.
  • E2E: db.e2e.test.ts (new), status.e2e.test.ts, help.e2e.test.ts, config.e2e.test.ts, multi-account.e2e.test.ts, messages.e2e.test.ts, sql.e2e.test.ts.
  • bun run check and bun run test (1,783 tests) pass locally. The live integration suite was not run.

Fixes #1

🤖 Generated with Claude Code

neoromantic and others added 13 commits October 22, 2026 22:10
…configurable retention

Nothing deleted api_activity or rate_limits rows: their prune functions in
RateLimitsService had no callers, and the window prune would also have
dropped a FLOOD_WAIT that was still running. Only completed and failed sync
jobs were cleaned, after a hardcoded 24 hours, and only for accounts with a
scheduler.

The new pruneCache in src/db/cache-maintenance.ts deletes old activity,
rate-limit windows (keeping running flood waits and the current window)
and finished jobs in short batches, so a first prune of a large table
never holds the write lock for long. The daemon runs it for every open
account on its existing cleanup schedule. How long each table keeps its
rows is set under cache.retention in config.json; the daemon reads it
once at start and only warns about a bad value, so a broken config still
never stops it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Nothing showed how big a cache had grown or how much of it was free
pages, so there was no way to tell when the cache needed attention.

tg status now reports each account's file, WAL and free pages and its
auto_vacuum mode, plus storage.cache_bytes over the accounts in scope.
--sizes adds bytes per table from dbstat, with indexes and FTS5 shadow
tables folded into their table. It is opt-in because dbstat reads every
page, and plain tg status runs on every agent call. Pretty output shows
the sizes and suggests tg db vacuum when over 10% of a file is free.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A cache never gave space back to the disk: nothing ran VACUUM or set
auto_vacuum, so pages freed by pruning or by a rebuilt index stayed in the
file, and a WAL that grew during a long write kept its size.

tg db vacuum prunes the account's cache by cache.retention, then compacts
it. With the daemon stopped it runs a full VACUUM, which also switches the
file to incremental auto_vacuum and rebuilds the search index if the
rewrite moved message rowids (messages_cache has a composite key, so
SQLite doesn't promise to keep them). With the daemon running it releases
free pages in short incremental_vacuum steps, and on an older cache
without auto_vacuum it refuses with DAEMON_ALREADY_RUNNING before writing
anything. New cache files get incremental auto_vacuum, and every
connection sets journal_size_limit to 64 MB so checkpoints shrink the WAL.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
message_search kept its own copy of every message's text, sender, chat
and files next to the index, although search never reads those columns:
it joins messages_cache by rowid for the text. Measured on 20,000 made-up
messages, the index took about 320 bytes per message; as a contentless
table with contentless_delete=1 it takes about 100, and the file gets
11-18% smaller. Results stay the same.

contentless_delete needs SQLite 3.43, and on macOS Bun uses the system
libsqlite3, so the kind is chosen by sqlite_version(). The first open on a
new enough SQLite drops the full-content table and rebuilds the index
inside the existing locked transaction, now waiting up to a minute for
the lock like an index build. SEARCH_INDEX_VERSION stays 1, so a 0.4.x tg
on the same SQLite reads the table as current. An older SQLite can't open
the contentless table, so it drops only the three triggers and marks the
index stale: message writes keep working, and a newer SQLite recreates the
triggers and rebuilds the index on its next open.

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

A TRUNCATE checkpoint takes the WAL write lock and keeps it while the busy
handler waits for readers on an older snapshot. At the connection's 5 s
busy_timeout, a slow reader next to `tg db vacuum` stopped the running
daemon from writing, and a reader slower than 5 s made its writes fail
with SQLITE_BUSY. With the daemon running the checkpoint now runs with no
busy wait and reports checkpointed: false instead; the full vacuum, where
the daemon is stopped, still waits.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The prune runs before the VACUUM and commits batch by batch, so when the
VACUUM then hits a full disk, the bookkeeping rows past their retention are
already gone. The disk_full message and the docs said the cache was
unchanged. They now say the VACUUM was rolled back and the messages are
intact, and every error after the prune carries details.pruned, so an agent
can see what was deleted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The command reports through success() and error(), which follow the
global --format, so `tg db vacuum -f pretty --json` still printed pretty
output while the help promised JSON. The global --format already covers
it. The e2e tests passed --json only because JSON is the default.

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

The e2e cache had no bookkeeping rows, so `pruned` was all zeros: dropping
the prune from tg db vacuum, or moving the daemon refusal below it, would
have passed every test. The cache now gets one API activity row far past
its retention; the vacuum must report it pruned, and the refusal must
leave it in place.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The tests covered a running FLOOD_WAIT (kept) and none at all (deleted),
but not one that ended. Losing `flood_wait_until <= now` from the prune's
condition would keep every window that ever had a FLOOD_WAIT forever, the
unbounded growth this prune exists to stop, and no test would fail.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The cleanupOldJobs test set ctx.retention to the default and used rows
ten days old, which the 7-day default prunes anyway, so a daemon that
ignored the configured retention would still pass. The test now sets
one day and uses rows two days old, which only the configured value
deletes.

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

The pretty status always suggested `tg db vacuum --account <id>` once free
pages passed 10%. Its most common trigger is a cache of an older version
right after the upgrade: no auto_vacuum, the old search index's pages
free, and usually the daemon running, so the suggested command failed with
DAEMON_ALREADY_RUNNING. For such a cache while the daemon runs, the hint
now stops and restarts the daemon around the vacuum.

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

A refused `tg db vacuum --account 2` suggested `tg db vacuum` with no
--account. Run as given, that vacuums the active account, leaves account 2
uncompacted and restarts the daemon for nothing. The suggestion now carries
the resolved account id, like the hint in `tg status`.

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

The pruning tests set ctx.retention by hand, so dropping the line that
copies config.retention into the context left every test green while the
daemon pruned by the defaults and ignored cache.retention.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@neoromantic
neoromantic force-pushed the feat/cache-size-management-1 branch from e56dd11 to 075eeb5 Compare October 22, 2026 18:11
@neoromantic
neoromantic merged commit 4314749 into main Oct 22, 2026
5 checks passed
@neoromantic
neoromantic deleted the feat/cache-size-management-1 branch October 22, 2026 18:15
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.

Figure out database storage size management

1 participant