Repository navigation
feat(cache): base64 byte fields in raw_json, no rewrite or re-index of unchanged messages - #106
Merged
Merged
Conversation
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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.
Fixes #86
Fixes #87
Problem
fileReference, a photo's stripped thumbnail) asUint8Array, andJSON.stringifywrote each one as an object with a key per byte. Everyraw_jsonwriter had its ownJSON.stringify(raw_json: store byte arrays as base64 #86).messages_cache_audeleted 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_fetchedserved 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 onlyraw_jsonserializer: a byte array (Buffer and subarrays included) becomes base64 and abiginta decimal string. Everything else is written asJSON.stringifywrites it. Every writer uses it: history pages, live updates, the sync worker,tg send, dialogs/chats/users.bigIntReplaceris gone. Existing rows are not rewritten. The stripped thumbnail stays inraw_json.messages_cacheupsert hasDO UPDATE ... WHEREwith null-safeIS NOTover every column exceptfetched_at/updated_at(raw_jsonincluded), so an unchanged re-fetch writes nothing.messages_cache_auis nowAFTER UPDATE OF text, from_id, media_path ... WHEN old.x IS NOT new.x(any of the three). TheWHENis needed:UPDATE OFfires whenever the column is in theSETlist, and the upsert sets every column, so without it araw_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 changefrom_id, so they still re-index.sqlite_master) is replaced andidx_messages_cache_fetchedis dropped. Both happen in oneBEGIN IMMEDIATEtransaction with the 60 s busy timeout, checked again inside it. An open with nothing to do only reads. New caches never create the index.docs/database-schema.md(howraw_jsonstores bytes, ajson_extractexample, migrations, the index list, capacity notes),docs/search.md"Triggered Indexing",raw_json/fetched_at/updated_atannotations fortg 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-bytefileReference, 1,000-byte stripped thumbnail, twoLongIDs, three sizes) takes 10,213 bytes with plainJSON.stringifyand 1,896 bytes withtoRawJson. The test asserts > 7,000 and < 2,000.EXPLAIN QUERY PLAN (#87)
Every query on
messages_cacheinsrc/was run on a cache that still hadidx_messages_cache_fetched(2,000 made-up rows,ANALYZE, SQLite 3.54.0). None filters or orders byfetched_at. Three full scans picked the index only because it is the narrowest covering index. Without it they pickidx_messages_cache_message_id, which is just as narrow. Every other plan is the same with or without the index.get,markDeleted,updateTextlistByChatId,listByChatIdIncludeDeleted,countByChatIdcountByChatIdAllgetLatestMessageId,getOldestMessageIdfindChatIdsByMessageIdhasMessageFromgetManysearchrebuildMessageSearchIndex, peer-ID migration 2/3 selectsINSERT … ON CONFLICT)COUNT/MIN/MAX(rowid))SELECT 1 … LIMIT 1)COUNT(*)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 storestoRawJsonoutput.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 withUPDATE messages_cache SET text = textnow callsrebuildMessageSearchIndex, because that statement no longer re-indexes.src/__tests__/messages-cache.test.ts: an unchanged re-fetch writes nothing (total_changes(), row withupdated_atequal) and leaves the index alone. Araw_jsonchange updates the row but not the index. An edit, a sender change and a live edit re-index.markDeleteddoes not. The "index alone" checks rename the sender inusers_cachefirst, and the new name must not become searchable. Three of these tests fail onmain.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