Skip to content

feat(db): background, resumable migrations; re-encode raw_json, backfill attachments - #116

Merged
neoromantic merged 3 commits into
mainfrom
feat/background-migrations
Oct 28, 2026
Merged

neoromantic merged 3 commits into
mainfrom
feat/background-migrations

Conversation

@neoromantic

Copy link
Copy Markdown
Owner

Fixes #89
Fixes #108
Fixes #95

Problem

One-time rewrites of every row ran in one BEGIN IMMEDIATE transaction on open, holding the write lock for seconds per 100k messages while the daemon waits only 5 s. Rows from older versions keep byte fields as per-byte objects, every row keeps mtcute Long values as {low, high, unsigned} objects and the expiring fileReference, older messages have no message_attachments row, and older history rows store videos, voices and stickers as document.

Change

  • Background migrations (src/db/background-migrations.ts, table cache_migrations): each batch is one short write (≤ 500 rows or ~50 ms) that rewrites rows and moves the rowid cursor in the same transaction. A stop resumes from the cursor; two runners (daemon and CLI) take turns without doing a row twice; another process's write waits one batch at most. A new cache registers migrations as done; opens that find every migration recorded only read. A full VACUUM restarts unfinished ones (rowids may move).
  • Daemon runs them after each tick's sync work, up to 250 ms per tick, yielding between batches; tg daemon stop starts no new batch; a failed batch waits a minute.
  • tg db migrate [--account] finishes them in the foreground (works while the daemon runs). tg status lists unfinished ones (migrations, accounts.accounts[].migrations) with done/total; pretty output shows a Migrations section and suggests tg db vacuum once a migration has freed space.
  • raw_json form (toRawJson): Long → decimal string (signed unless unsigned), no fileReference (raw_json: write Long values as decimal strings #108, raw_json: stop storing fileReference #95). Downloads already re-fetch the message for a fresh reference; nothing reads fileReference from the cache.
  • First migrations: messages_raw_json_v2 (re-encode, backfill message_attachments via extractAttachment, recompute message_type of media messages with the unified resolver, one parse per row; touches neither text, from_id, media_path nor updated_at, so the search index is untouched), users_raw_json_v2, chats_raw_json_v2. Old forms are detected strictly: a byte object has only keys "0".."n-1" with integers 0..255; a Long has exactly low, high, unsigned. Rows not needing changes are not written.
  • Docs: database-schema.md (raw_json form, background migrations, cache_migrations), cli-commands.md (tg db migrate, status fields), daemon.md, media.md, sql.md, schema annotations, AGENTS.md (Long line), README, CHANGELOG [Unreleased], ROADMAP.

Tests

  • src/__tests__/background-migrations.test.ts: a 0.5.0-form cache (per-byte objects, Long objects, fileReference, document for videos, no attachment rows) migrates to exactly what toRawJson writes now, with attachment rows and message_type as a new write gives; extractAttachment same before/after; search index pages unchanged; json_extract reads an access hash as a decimal string; a second run changes nothing; stop between batches and resume; a throw inside a batch rolls back, records last_error, resumes to the same state; two connections taking turns end in the same state; batch time limit with an injected clock; reopening with another process holding the write lock succeeds (open only reads); a writer on another connection with busy_timeout 1 s is never refused while a child process migrates 4,000 rows.
  • src/__tests__/daemon-migrations.test.ts: tick budget, stop, retry delay.
  • src/__e2e__/db-migrate.e2e.test.ts: tg status (JSON and pretty) and tg db migrate on a made-up cache; tg sql reads the hash; status of a migrated cache runs while another process holds the write lock.
  • Local: bun run check clean; bun run test 2101 pass / 0 fail; e2e db-migrate, db, status, sql, help, messages, media: 135 pass / 0 fail.

Measured (made-up cache, this Mac, default limits)

70,000 messages in the 0.5.0 form (6 of 7 with media) plus 5 users/chats, file DB in WAL mode, runMigrationBatch with 500 rows / 50 ms:

Run 1 Run 2
Rows/s 15,197 14,432
Max batch 47.6 ms 55.5 ms
Batches 142 144

raw_json bytes per message, average over the cache: 5,432 → 1,146 (media messages 6,314 → 1,315). Per made-up message, 0.5.0 form / 0.6.0–0.7.0 form / now: photo 10,215 / 1,898 / 1,776; video 8,506 / 1,826 / 1,673; voice 1,231 / 587 / 466; link preview 939 / 735 / 580. The fixture's stripped thumbnails (800–1,000 bytes) dominate; real sizes differ.

🤖 Generated with Claude Code

neoromantic and others added 3 commits October 29, 2026 03:20
toRawJson writes mtcute's Long objects (id, accessHash, groupedId and
others) as decimal strings, signed unless unsigned, as it already did for
bigint, so `json_extract(raw_json, '$.accessHash')` gives the hash. It
leaves out every fileReference: Telegram's file references expire, and a
download fetches the message again for a fresh one. extractAttachment
reads both forms. AGENTS.md no longer says Long values are BigInt.

Refs #108, #95

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

A rewrite of every row of a big cache now runs in small batches instead of
one transaction on open. cache_migrations records each migration's cursor
(the last rowid done); each batch rewrites at most 500 rows or 50 ms and
moves the cursor in the same short write, so a stop resumes, the daemon
and a CLI take turns without doing a row twice, and another process's
write waits one batch at most.

- The daemon runs pending migrations after each tick's sync work, up to
  250 ms a tick, yielding between batches; a stop starts no new batch.
- tg db migrate [--account] finishes them in the foreground, with or
  without the daemon.
- tg status lists unfinished ones with done/total and suggests
  tg db vacuum for the space they free.
- A full VACUUM starts unfinished migrations over; opens that find every
  migration recorded only read.

The first migrations rewrite raw_json of messages, users and chats into
the current form (base64 bytes, Long values as decimal strings, no
fileReference), and for media messages fill message_attachments and
recompute message_type, parsing each row once. Neither touches the
search index.

Fixes #89
Fixes #108
Fixes #95

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

A Long object is re-encoded only when both words are int32 and unsigned is
a boolean, a byte object only when every value is an integer 0..255: any
other object that looks like one is kept as it is, so the migration never
loses data it can't read. The message_type pass applies the resolver to
every row whose raw_json is a TL message, so a pending link preview, an
expired photo or unsupported media gets `text` as a new write gives it;
rows with `{}` or other raw_json keep theirs.

Refs #89

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@neoromantic
neoromantic merged commit a8c87e9 into main Oct 28, 2026
5 checks passed
@neoromantic
neoromantic deleted the feat/background-migrations branch October 28, 2026 23:43
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.

raw_json: write Long values as decimal strings raw_json: stop storing fileReference Background, resumable migrations for big caches

1 participant