Skip to content

feat(cache): base64 byte fields in raw_json, no rewrite or re-index of unchanged messages - #106

Merged
neoromantic merged 4 commits into
mainfrom
feat/raw-json-bytes-and-refetch-writes
Oct 28, 2026
Merged

neoromantic merged 4 commits into
mainfrom
feat/raw-json-bytes-and-refetch-writes

Conversation

@neoromantic

Copy link
Copy Markdown
Owner

Fixes #86
Fixes #87

Problem

  • mtcute gives byte fields (fileReference, a photo's stripped thumbnail) as Uint8Array, and JSON.stringify wrote each one as an object with a key per byte. Every raw_json writer had its own JSON.stringify (raw_json: store byte arrays as base64 #86).
  • A message fetched again was rewritten in full, and messages_cache_au deleted and re-inserted its search index row even when nothing changed. Catch-up after every restart or reconnect fetches the live-arrived messages again, and marking a message deleted re-indexed it too. idx_messages_cache_fetched served no query (A re-fetched message is rewritten and re-indexed even when nothing changed #87).

Change

  • src/utils/raw-json.ts: toRawJson() is now the only raw_json serializer: a byte array (Buffer and subarrays included) becomes base64 and a bigint a decimal string. Everything else is written as JSON.stringify writes it. Every writer uses it: history pages, live updates, the sync worker, tg send, dialogs/chats/users. bigIntReplacer is gone. Existing rows are not rewritten. The stripped thumbnail stays in raw_json.
  • The messages_cache upsert has DO UPDATE ... WHERE with null-safe IS NOT over every column except fetched_at/updated_at (raw_json included), so an unchanged re-fetch writes nothing.
  • messages_cache_au is now AFTER UPDATE OF text, from_id, media_path ... WHEN old.x IS NOT new.x (any of the three). The WHEN is needed: UPDATE OF fires whenever the column is in the SET list, and the upsert sets every column, so without it a raw_json-only change (channel views and reactions) would still re-index. The same rule applies to both the contentless and the full-content index. Peer-ID migrations 2 and 3 change from_id, so they still re-index.
  • Existing caches: on first open, the old trigger (found by its SQL in sqlite_master) is replaced and idx_messages_cache_fetched is dropped. Both happen in one BEGIN IMMEDIATE transaction with the 60 s busy timeout, checked again inside it. An open with nothing to do only reads. New caches never create the index.
  • Behaviour note: until now a re-fetch also refreshed the sender and chat names in the index as a side effect. Now names in the index refresh only when the message's text or sender changes. Results still show the current names. Proper re-indexing after a rename is Search: re-index older messages after a person or chat is renamed #93.
  • Docs: docs/database-schema.md (how raw_json stores bytes, a json_extract example, migrations, the index list, capacity notes), docs/search.md "Triggered Indexing", raw_json/fetched_at/updated_at annotations for tg sql print-schema, CHANGELOG. ROADMAP gets the follow-up issues of the storage discussion.

Sizes (#86)

The made-up photo message in src/__tests__/helpers/photo-message.ts (30-byte fileReference, 1,000-byte stripped thumbnail, two Long IDs, three sizes) takes 10,213 bytes with plain JSON.stringify and 1,896 bytes with toRawJson. The test asserts > 7,000 and < 2,000.

EXPLAIN QUERY PLAN (#87)

Every query on messages_cache in src/ was run on a cache that still had idx_messages_cache_fetched (2,000 made-up rows, ANALYZE, SQLite 3.54.0). None filters or orders by fetched_at. Three full scans picked the index only because it is the narrowest covering index. Without it they pick idx_messages_cache_message_id, which is just as narrow. Every other plan is the same with or without the index.

Query Plan with the index Plan without
messages-cache get, markDeleted, updateText SEARCH USING INDEX sqlite_autoindex_messages_cache_1 (chat_id=? AND message_id=?) same
messages-cache listByChatId, listByChatIdIncludeDeleted, countByChatId SEARCH USING INDEX idx_messages_cache_date (chat_id=?) same
messages-cache countByChatIdAll SEARCH USING COVERING INDEX idx_messages_cache_date (chat_id=?) same
messages-cache getLatestMessageId, getOldestMessageId SEARCH USING COVERING INDEX sqlite_autoindex_messages_cache_1 (chat_id=?) same
messages-cache findChatIdsByMessageId SEARCH USING INDEX idx_messages_cache_message_id (message_id=?) same
history-ranges hasMessageFrom SEARCH USING COVERING INDEX sqlite_autoindex_messages_cache_1 (chat_id=? AND message_id>?) same
messages-history list before/after, getMany SEARCH m USING INDEX sqlite_autoindex_messages_cache_1 (chat_id=? AND message_id…) same
messages-search search SCAN message_search VIRTUAL TABLE; SEARCH m USING INTEGER PRIMARY KEY (rowid=?) same
sync-schema rebuildMessageSearchIndex, peer-ID migration 2/3 selects SCAN same
peer-ID migration 2/3 updates SEARCH USING INTEGER PRIMARY KEY (rowid=?) same
upsert (INSERT … ON CONFLICT) no plan rows same
cache-maintenance rowid check (COUNT/MIN/MAX(rowid)) SCAN USING COVERING INDEX idx_messages_cache_fetched SCAN USING COVERING INDEX idx_messages_cache_message_id
cache-layout has-rows (SELECT 1 … LIMIT 1) SCAN USING COVERING INDEX idx_messages_cache_fetched SCAN USING COVERING INDEX idx_messages_cache_message_id
status COUNT(*) SCAN USING COVERING INDEX idx_messages_cache_fetched SCAN USING COVERING INDEX idx_messages_cache_message_id

Tests

  • src/__tests__/raw-json.test.ts: base64 fields decode to the same bytes, size bound, Buffer and subarray, bigint, and the history-page mapper stores toRawJson output.
  • src/__tests__/peer-id-migration.test.ts: a photo message with base64 byte fields still gets its channel sender's marked ID. One test that forced a re-index with UPDATE messages_cache SET text = text now calls rebuildMessageSearchIndex, because that statement no longer re-indexes.
  • src/__tests__/messages-cache.test.ts: an unchanged re-fetch writes nothing (total_changes(), row with updated_at equal) and leaves the index alone. A raw_json change updates the row but not the index. An edit, a sender change and a live edit re-index. markDeleted does not. The "index alone" checks rename the sender in users_cache first, and the new name must not become searchable. Three of these tests fail on main.
  • src/__tests__/sync-schema.test.ts: a cache with the 0.5.0 trigger and the index, contentless and full-content, gets the new trigger and loses the index on first open. Search and edits still work there. A second open on a read-only connection succeeds with the same schema, so it only reads (a read-only open of an un-upgraded cache throws).
  • bun run check, bun run test (1855 pass). bun run test:e2e: 283 pass. The 3 failures are API-fetch tests that time out because the local sandbox blocks the network, and they pass outside it.

🤖 Generated with Claude Code

neoromantic and others added 4 commits October 28, 2026 18:19
Every raw_json write goes through one serializer, toRawJson: a byte array
(Uint8Array, Buffer included) is a base64 string and a bigint a decimal
string. Plain JSON.stringify wrote a Uint8Array as an object with a key per
byte, so a made-up photo message's raw_json drops from 10,213 to 1,896
bytes. The stripped thumbnail stays; rows cached before keep the old form.

Refs #86

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The messages_cache upsert updates a row only when a column other than
fetched_at and updated_at differs, so a message fetched again unchanged
(catch-up after every restart or reconnect) costs no write. The update
trigger fires only when text, from_id or media_path changes (AFTER UPDATE
OF plus WHEN, since an upsert sets every column), so a raw_json-only change
or marking a message deleted no longer re-indexes it. The first open of a
cache from 0.5.0 replaces its trigger under the write lock; later opens
only read.

A re-fetch no longer refreshes sender and chat names in the index as a side
effect (#93 tracks re-indexing after a rename).

Refs #87

Co-Authored-By: Claude Opus 5.5 <[email protected]>
No query filters or orders messages by fetched_at: EXPLAIN QUERY PLAN over
every query on messages_cache shows only three full scans (COUNT(*), the
rowid check after VACUUM, the has-rows check) picking it as the narrowest
covering index, and without it they pick idx_messages_cache_message_id, as
narrow. New caches don't create it; the first open of an existing cache
drops it in the same locked one-time step as the trigger upgrade.

Refs #87

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@neoromantic
neoromantic merged commit 50d7897 into main Oct 28, 2026
5 checks passed
@neoromantic
neoromantic deleted the feat/raw-json-bytes-and-refetch-writes branch October 28, 2026 16:41
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.

A re-fetched message is rewritten and re-indexed even when nothing changed raw_json: store byte arrays as base64

1 participant