Repository navigation
feat(db): cache size reporting, retention pruning, tg db vacuum and a contentless search index - #79
Merged
Merged
Conversation
neoromantic
force-pushed
the
feat/cache-size-management-1
branch
2 times, most recently
from
October 22, 2026 17:52
3252675 to
5190ef6
Compare
This was referenced Oct 22, 2026
Closed
…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
force-pushed
the
feat/cache-size-management-1
branch
from
October 22, 2026 18:11
e56dd11 to
075eeb5
Compare
This was referenced Oct 22, 2026
Merged
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
Nothing kept a cache from growing (#1). No code ran
VACUUMor setauto_vacuum.api_activityandrate_limitshad 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 statusshowed no sizes.message_searchalso 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:
feat(daemon): retention.
pruneCache(src/db/cache-maintenance.ts) deletes oldapi_activity,rate_limitswindows and completed and failedsync_jobsin 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 inconfig.jsonundercache.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 unusedRateLimitsService.pruneOldWindows/pruneOldActivityare removed.feat(status): cache size.
accounts.accounts[].cache.sizegivesfile_bytes,wal_bytes, page counts,free_pages/free_bytesandauto_vacuum.storage.cache_bytessums the accounts in scope.--sizesadds bytes per table fromdbstat, with indexes and FTS5 shadow tables counted under their table. It is opt-in becausedbstatreads every page. Pretty output shows a Cache Size section and suggeststg db vacuumwhen more than 10% of a file is free.feat(db):
tg db vacuum [--account]. It prunes first, then compacts:VACUUM, which also switches the file to incremental auto_vacuum. If the rewrite movedmessages_cacherowids, it rebuilds the search index.incremental_vacuumin short steps.DAEMON_ALREADY_RUNNINGbefore writing anything.GENERAL_ERRORwithdetails.reasonset tocache_busyordisk_full. The prune commits as it goes, so errors after it carrydetails.pruned, anddisk_fullsays the VACUUM was rolled back, not that the cache is unchanged.checkpointed: falseinstead of holding the daemon's writes.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 setsjournal_size_limitto 64 MB.feat(search): contentless index. Where
sqlite_version() >= 3.43.0,message_searchisfts5(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_VERSIONstays 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 joinsmessages_cacheby rowid, and nothing usessnippet,highlightorbm25.Upgrading: stop the daemon before you upgrade. Then run
tg db vacuumonce with the daemon stopped. This gives the old index's pages back to the disk and switches the cache to incremental mode, after whichtg db vacuumalso works while the daemon runs.tg sqlqueries that readmessage_search's own columns (text,sender,chat,files, orsnippet()/highlight()over it) now getNULL; joinmessages_cacheby rowid for the text, astg messages searchdoes.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-shapedraw_json. Each write took about 0.5–0.7 s. Bytes per message come fromdbstat, with indexes counted under their table:messages_cachemessage_searchregularmessage_searchcontentlessraw_jsonis 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.raw_json: a synthetic photo message'sraw_jsonis about 7.7 KB, becauseUint8Arrayfields (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()withENABLE_FTS5andENABLE_DBSTAT_VTABwas 3.54.0 both frombun run(Bun 1.4.3, macOS) and from abun build --compilebinary, andcontentless_delete=1worked in both.Tests
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,loadRetentionConfigfallbacks.daemon-scheduler.test.tsanddaemon-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.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 checkandbun run test(1,783 tests) pass locally. The live integration suite was not run.Fixes #1
🤖 Generated with Claude Code