Skip to content

fix(cache)!: store marked peer IDs in every cache table - #43

Merged
neoromantic merged 14 commits into
mainfrom
fix/peer-id-format-18
Oct 21, 2026
Merged

neoromantic merged 14 commits into
mainfrom
fix/peer-id-format-18

Conversation

@neoromantic

@neoromantic neoromantic commented Oct 21, 2026 •

Copy link
Copy Markdown
Owner

What and why

messages_cache and the sync tables stored marked peer IDs (-100… for supergroups and channels, -N for basic groups), but chats_cache stored groups and channels under bare positive IDs. Every join between them missed those chats: tg messages search printed null for the title, username and type of every group and channel result, --chat @username and SQL joins found nothing, and the search index had no group or channel titles. User N and basic group N also shared one chats_cache key and overwrote each other. History pages, tg send and live forwards also stored group and channel senders under bare IDs, so a channel posting as itself got the name of an unrelated user.

Fixes #18

Design

  • One format everywhere: marked peer IDs, as mtcute uses. src/utils/telegram-peer-ids.ts is the only module that converts them (new toPeerIdFromRawChat, toRawPeerId, toInputPeerFromPeerId, legacyChatIdCandidates; getCandidateChatIds and toChannelIdFromPeerId are gone). Tests cross-check it against mtcute's getMarkedPeerId and parseMarkedPeerId.
  • Writers: dialogToCacheInput and rawChatToCacheInput store marked IDs (a community chat gets its channel ID from the raw peer, not from type). Senders and forward sources go through toPeerIdFromRawPeer.
  • Readers: buildInputPeer, the peer resolver, tg chats get and tg chats sync do one exact lookup. A positive ID is a user first everywhere: tg chats get and tg chats sync share findCachedChatById, which takes a positive number the cache knows as a user (private chat, users_cache, DM sync state or cached messages) as that user, as the peer resolver does. Only otherwise does a bare positive ID from 0.2.0 resolve through ChatsCache.getByLegacyId (cache only); one that names both a cached basic group and a cached channel is INVALID_ARGS (exit 3) with the input under the command's key (to, chat, identifier) and both marked IDs in details.candidates.
  • tg chats get --id <ID> that the cache doesn't hold is INVALID_ARGS ("not in the cache") before any account or credentials are needed. tg chats sync <marked ID> --format pretty takes the marked ID, not pretty.
  • Migration (src/db/peer-id-migration.ts), run at the end of initSyncSchema, recorded in PRAGMA user_version:
    • step 1 re-keys bare chats_cache rows from their raw_json (dialog peer or raw chat) or their type, merges a chat cached under both IDs (newer fetched_at wins, a missing access hash is filled), and rebuilds the search index once; SEARCH_INDEX_VERSION stays 1, so 0.2.0 doesn't rebuild it back
    • step 2 marks from_id and forward_from_id of group and channel senders whose raw_json names them; the update trigger re-indexes those rows
    • one BEGIN IMMEDIATE transaction with a 60 s busy timeout; a failure rolls back everything, user_version included, and the next open retries
    • the re-key also runs on any later open that finds a bare row, so rows a still-running 0.2.0 daemon writes get repaired; opens with nothing to do only read
    • on 200k synthetic messages the migration took about 1.5 s
  • Output: id in tg chats list, get, search and sync becomes the marked ID (documented as Breaking in CHANGELOG, with the upgrade note: stop the daemon, upgrade, start it). peerId stays and equals id. fromId, sender.id and forwardFromId of group and channel senders become marked IDs too, also Breaking: --sender takes the marked ID for them.
  • Docs: database-schema.md (Peer IDs section, Migrations with user_version 1 and 2), sql.md (messages per chat with titles, with the CAST join), search.md, cli-commands.md, api-design.md, caching.md, testing.md, AGENTS.md. ROADMAP drops Messages and chats are cached with different peer ID formats #18; README is unchanged.

How I checked it

  • bun run check, bun run test (1545 pass) and bun run test:e2e (191 pass)

  • New peer-id-migration.test.ts: re-key from raw_json or type (community stored as group gets -100…), duplicate merge both ways, other tables untouched, a second run changes nothing (sqlite_master, rows, user_version, total_changes()), a failing trigger rolls back and the next open migrates, title search works with index version still 1, a late bare row gets re-keyed, sender and forward IDs marked while {} and malformed raw_json are left alone

  • Rollback is proven for every step: a failing sender update (the last step) and a throwing index rebuild leave chats_cache, message_search, messages_cache and user_version as they were; the migration runs with busy_timeout 60000 and restores 5000; a stored sender that isn't the bare ID of the peer raw_json names stays

  • cache-db-lock.test.ts: four processes open one 0.2.0 cache at once while another writer holds the lock; opening a migrated cache stays lock-free (under 500 ms while another process holds the write lock); getCacheDb retries after a failed migration

  • Test helpers: helpers/legacy-cache.ts builds the 0.2.0 layout, helpers/peer-id-invariants.ts asserts one format after the bootstrap, handler, send-cache and e2e flows, including a bare group or channel ID in chat_sync_state, messages_cache, sync_jobs or history_ranges; fixtures are seeded through the production mappers

  • e2e: ambiguous-ids.e2e.test.ts pins the ambiguous-ID error of tg chats get, chats sync, messages list and messages get; search results carry chat titles for a supergroup, a basic group, a channel and a DM, and their IDs equal what tg chats list prints; the first run on a 0.2.0 cache shows titles, lists marked IDs, finds a message by its chat's title and leaves no orphan in a SQL join; tg chats get, tg chats sync and tg messages list accept marked and 0.2.0 IDs; the docs/sql.md join example returns titles

  • The live daemon test now opens the cache file after the dialog bootstrap and expects no group or channel under a positive ID, and a chats_cache row for every group or channel with sync state

  • Not run here: the live Telegram checks (bun run test:integration, the migration on a copy of the test data dir)

  • Tests pass locally and use made-up data only

  • README, docs and affected demos follow the product content standard

  • Title follows the repo's commit style: Conventional Commits (feat: …, fix: …) unless AGENTS.md says otherwise

🤖 Generated with Claude Code

neoromantic and others added 14 commits October 21, 2026 22:28
messages_cache and the sync tables store marked peer IDs (-100... for
supergroups and channels, -N for basic groups), but chats_cache stored
groups and channels under bare IDs. Every join between them missed those
chats: tg messages search printed null titles, --chat @username and SQL
joins found nothing, and the search index had no group or channel titles.
User N and basic group N also shared one chats_cache key and overwrote
each other.

chats_cache now uses marked IDs like every other table, and all ID
conversions go through src/utils/telegram-peer-ids.ts. A migration run by
initSyncSchema re-keys existing rows from their raw_json or type, merges
duplicates and rebuilds the search index once, recorded in PRAGMA
user_version. It runs in one write transaction, so a failure rolls back
and the next open retries. Bare rows that an older daemon writes later are
re-keyed on the next open. Bare group and channel IDs from 0.2.0 still
resolve when the cache knows the chat.

Fixes #18

BREAKING CHANGE: `id` in tg chats list, get, search and sync, and
chats_cache.chat_id in tg sql, are now marked peer IDs (-100... for
supergroups and channels, -N for basic groups). `peerId` stays and equals
`id`. Stop the daemon before upgrading and start it after.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
History pages, tg send and live forwards stored a group or channel sender
in messages_cache.from_id and forward_from_id under its bare ID, while
live messages stored the marked one. The same channel had two IDs, and a
channel posting as itself matched the user whose ID equals its bare one,
so search results and the search index gave it that user's name.

Senders and forward sources now go through toPeerIdFromRawPeer like chat
IDs. Migration step 2 (user_version 2) converts cached rows whose raw_json
names a group or channel with the stored bare ID, in the same transaction
as the chats_cache re-key; rows with empty or malformed raw_json stay as
they are. The update trigger re-indexes each changed row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A positive marked ID is a user, and tg send --to resolves one that way:
the user's private chat, a cached user, then messages cached under it, and
only then a group or channel ID as 0.2.0 printed it. tg chats get and tg
chats sync went from the exact chats_cache row straight to that legacy
lookup. With DM N known only from users_cache or its sync state and a
cached basic group -N, tg chats get --id N showed the group and tg chats
sync N changed the group's mode and cleared its failed jobs, so the same
input named different chats in different commands.

Both commands now share findCachedChatById: a marked ID matches exactly, a
positive one matches only a private chat, a number the cache knows as a
user (users_cache, chat_sync_state or messages_cache) names that user, and
only otherwise is it a 0.2.0 group or channel ID. tg chats sync then falls
back to sync state, as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
citty doesn't declare the global --format on the subcommand and reads a
marked ID such as -4242 as flags, so in `tg chats sync -4242 --format
pretty` the positional got `pretty`, and the command took it over the
marked ID it found in rawArgs. It failed with "Chat not found in the
cache: pretty". Since tg chats list now prints only negative IDs for
groups and channels, copying one from it and adding --format pretty (or
-f pretty) failed for every group and channel.

A marked ID in rawArgs now wins over the positional.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
tg chats get fetches from Telegram by @username only, and the docs now
say an ID works for any cached chat. On a cache miss, run() built the
client before it checked the identifier, so `tg chats get --id
-1001234567890` on an empty cache failed with TELEGRAM_ERROR "No active
account", or with a credentials error when TELEGRAM_API_ID was unset.
Neither said the ID isn't cached, and an ID lookup can't use the API
anyway, so the cache-only path needed credentials.

The identifier is checked first. A miss is INVALID_ARGS "Chat <ID> is not
in the cache; fetching by ID is not supported yet" with a suggestion to
start the daemon or use @username; with --fresh it says --fresh needs
@username.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A bare 0.2.0 ID that names a cached basic group and a cached channel must
fail with INVALID_ARGS and both marked IDs. That was tested only for tg
send (unit) and tg chats sync (e2e): making tg chats get return the first
legacy match, or dropping the AmbiguousPeerError branch of
reportHistoryError so messages list and get fell through to the generic
TELEGRAM_ERROR, passed every suite.

One e2e file now runs tg chats get, chats sync, messages list and messages
get on a cache with group -4242 and channel -1000000004242 and pins the
exit code, the message and the details: the input under each command's own
key (identifier, chat) and candidates. cli-commands.md documents those
details for every command, send's `to` included.

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

The rollback test failed the re-key in step a, before the search index
rebuild and the sender update ran, so it proved the "a failure rolls back
everything, user_version included" guarantee only for that step. Running
markSenderIds after the commit (user_version 2 committed, the failure
never retried) or the rebuild after the commit passed every test. So did
dropping the check that a stored sender is the bare ID of the peer
raw_json names, and dropping the 60 s busy_timeout or its restore.

New cases: a trigger fails the sender update, the last step, and
chats_cache, message_search, messages_cache and user_version stay as they
were until a retry succeeds; a throwing rebuild leaves chats_cache bare; an
injected rebuild sees busy_timeout 60000 and the open's 5000 is back after
a failure and after a success; a stored 444 whose raw_json names channel
333 or group 222 stays 444. The two-connection test is renamed: it opens
the cache one connection after the other.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Nothing showed that opening an already migrated cache stays lock-free.
Deleting the unlocked needsMigration pre-check made every open take BEGIN
IMMEDIATE with a 60 s busy timeout, and all tests still passed: the
"changes nothing" case compares total_changes(), which an empty write
transaction leaves alone. With that change every tg read command would
wait behind a daemon write batch. Reverting getCacheDb's close-and-retry
after a failed init also passed, though the next call would then return
an unmigrated connection. And the four-process test had no lock holder,
so the processes may never have overlapped.

New cases: while another process holds the write lock, initCacheSchema
plus initSyncSchema on a migrated cache finish in under 500 ms and leave
busy_timeout at 5000; a child process whose first getCacheDb fails on a
trigger gets a migrated cache from the second call; and the four
processes start while another writer holds the lock, so they queue for it
behind the one that migrates.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
assertPeerIdInvariants checked messages_cache, chat_sync_state, sync_jobs
and history_ranges only for an ID mtcute can parse. A bare positive
channel ID parses as a user, so chat_sync_state(1234567890, 'supergroup')
passed, though it is exactly the bug class of #18. The bootstrap, handler
and e2e tests that call the helper guarded only chats_cache.

chat_sync_state is now checked like chats_cache, its chat_type against
the parsed kind. In the other tables a positive chat ID that
chat_sync_state or chats_cache knows as a group or channel is flagged. A
self-test of the helper pins both checks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
resolveCachedId accepts a positive chats_cache hit only when it is a
private chat: a group row under a positive ID is a bare row that a 0.2.0
binary wrote after this process opened the cache. Changing the check back
to any row passed every test, and then tg send --to 4242 would build
inputPeerUser 4242 with access hash 0 for basic group 4242.

The new case caches such a row without migrating and expects the group
peer, with no API call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
After the live dialog bootstrap the daemon test checked only counts, so
nothing proved that real dialogs are stored under marked IDs (#18), and the
manual steps (orphans, chats list IDs against types) were not automated. A
check through tg sql would hide a regression, since every CLI open re-keys
bare rows first.

After "Bootstrapped N dialogs" the test opens the cache file read-only and
expects no group or channel row in chats_cache under a positive ID, and a
chats_cache row under the same ID for every group or channel in
chat_sync_state.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The rule for #18 is that JSON output IDs stay stable or the change is
documented as breaking. fromId, sender.id and forwardFromId in tg messages
search, list and get change from bare positive IDs to marked negative ones
for group and channel senders, on every history-fetched or forwarded row,
and the migration rewrites the cached ones. The CHANGELOG bullet sat under
Changed without the Breaking prefix the id change has, and the commit that
made the change had no BREAKING CHANGE footer. A script that filters
--sender 333 or matches fromId against a channel's bare ID would stop
matching without warning.

The bullet is now Breaking and says --sender takes the marked ID for such
a sender; docs/search.md says the same.

BREAKING CHANGE: fromId, sender.id and forwardFromId in tg messages
search, list and get, and messages_cache.from_id and forward_from_id, hold
the marked ID (-N, -100...) of a group or channel sender or forward
source. tg messages search --sender takes that marked ID.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
tg chats get and tg chats sync took a positive ID that has sync state for
a DM as that user, but tg send --to and tg messages list/get checked only
users_cache, a private chats_cache row and cached messages. With basic
group -N cached and the DM of user N seen only live, tg chats sync N
reached the DM while tg messages list --chat N and tg send --to N reached
the group.

Both paths now ask one check, isKnownUserId, so every command names the
same chat, as the CHANGELOG entry for #18 already says. A unit test and
an e2e case for tg messages list cover the sync-state case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The chats_cache re-key checks the data on every open, so it repairs rows
that a 0.2.0 binary still running writes later. The sender and forward ID
step runs once: finding bare sender IDs means reading the raw_json of
every message, too costly for each open. A 0.2.0 daemon left running, or
a second 0.2.0 install, still caches bare group and channel senders after
the upgrade, and the upgrade note said only that its chats are converted.
The CHANGELOG, the schema doc and the migration comment now say that such
senders keep their bare IDs until the message is fetched again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@neoromantic
neoromantic merged commit ccbf8c9 into main Oct 21, 2026
5 checks passed
@neoromantic
neoromantic deleted the fix/peer-id-format-18 branch October 21, 2026 19:52
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.

Messages and chats are cached with different peer ID formats

1 participant