Skip to content

fix(daemon): let history backfill and first pages run next to catch-up - #36

Merged
neoromantic merged 19 commits into
mainfrom
fix/backfill-6
Oct 21, 2026
Merged

neoromantic merged 19 commits into
mainfrom
fix/backfill-6

Conversation

@neoromantic

@neoromantic neoromantic commented Oct 21, 2026 •

Copy link
Copy Markdown
Owner

What and why

History backfill and first pages never ran on a real account. refreshQueues queued a top-priority forward catch-up for every enabled chat on every refresh (every 30 loop ticks), and getNextPending ordered strictly by priority and age. With one job per 3 s, initial_load and backward_history never got a turn. A daemon run on an account with about 1,860 enabled chats completed 103 catch-ups and nothing else.

Related defects, also fixed here:

  • "Large groups and channels sync only on request" had no way to make the request: setSyncEnabled had no callers, and the dialog pass rewrote sync_enabled and nulled member_count on every start.
  • A group with no member count was treated as having fewer than 20 members.
  • AGENTS.md said groups of 20–100 members get the last 10 messages, while the code uses 100.
  • A chat whose first message arrived live never got a first page. An empty chat never got a cursor, so it was never caught up. The first page also counted live-cached messages a second time, and a page of only messageEmpty entries set backward_cursor to MAX_SAFE_INTEGER.
  • iterDialogs skipped archived chats.

Fixes #6

Design

Each commit stands alone and carries its own tests, docs and CHANGELOG entry.

  1. Policy. A group or supergroup whose member count is unknown (null, missing or 0) is off and Low, the same as a group over 100 members. The upsert keeps the stored count when a dialog leaves it out, and the pass computes the policy from the dialog's count or the stored one. A live message passes msg.chat.membersCount: basic groups always carry it, supergroups often don't. The rule for 20–100 members is now the same everywhere: the newest 100 messages, then history after the small chats.
  2. First page for every chat without a forward cursor. initial_load is due when sync_enabled = 1 AND forward_cursor IS NULL. It takes min and max from raw IDs, messageEmpty included, and counts only uncached messages. It writes both cursors, history_complete and the counter in one statement. An empty chat ends at cursor 0, and catch-up treats a stored 0 as a real cursor. A chat that already has a forward cursor never gets a first page again (Daemon loses messages that arrive while it is stopped #15).
  3. Catch-up only for chats that are behind. The new column chat_sync_state.top_message_id holds the newest message ID Telegram reported (NULL means unknown). A chat is due while that ID is NULL or above forward_cursor.
    • The dialog pass raises the ID from dialog.raw.topMessage on start and, in the background, after every reconnect (Reconnect doesn't restore real-time updates #16, guarded per account by dialogPassesInFlight). The first page raises it too.
    • A catch-up page that isn't full settles it with a compare-and-clear in the same UPDATE that moves the cursor. If a pass raised the ID during the fetch, the chat stays due.
    • Live updates never write the ID or the cursor.
    • On start, chats that no pass listed are marked caught up if every pass completed and every account connected. Otherwise they get NULL, so each gets one checking page. A reconnect pass that fails part-way does the same for the chats it didn't list.
    • Startup drops the pending catch-ups that 0.1.4 left.
    • The pass lists archived dialogs (archived: 'keep'). They update chats_cache but get no new sync state.
    • The PR fix(daemon): keep messages that arrive while the daemon is stopped #31 trade-off is accepted and documented. The cursor trails live messages, so the first catch-up after a restart or reconnect fetches them again, about one call per 100 messages per chat. There is no periodic catch-up.
  4. Lanes. Catch-up (forward_catchup), first page (initial_load) and history (backward_history, full_sync) take turns in the slot cycle catch-up, first page, catch-up, history. An empty lane's slot goes to the first lane with work.
    • getNextJob() stays a pure peek. processJobs calls the new recordJobRun(job) in finally after a job ran.
    • Every job's priority is its chat's tier. Jobs within a lane are ordered by priority, created_at, then id (new idx_sync_jobs_lane).
    • History is queued for every enabled tier once the chat has a cursor, and right after a first page with history left.
    • Queue methods skip disabled chats and chats without a state row. Startup drops their pending jobs and aligns the remaining priorities.
    • Rate limits are unchanged: one job per 3 s, and a FLOOD_WAIT stops every lane.
  5. PRAGMA busy_timeout = 5000 in initCacheSchema. A two-process test fails without it, both for a held write lock and for four processes migrating a 0.1.4 database at once.
  6. tg chats sync <chat> [--off | --auto] [--account <selector>] adds the column sync_mode (auto, on or off).
    • The upsert uses CASE on the mode for sync_enabled and sync_priority and never writes the mode, so the dialog pass and live updates can't undo the choice.
    • The command reads only the cache and needs no credentials. It accepts @username, the ID tg chats list shows, or a marked ID. The argument parser reads -100… as flags, so the command takes it from the raw arguments.
    • In one transaction it creates the state row if needed, sets the mode with the matching sync_enabled and sync_priority, and cancels pending jobs when the mode changed.
    • A chat turned on gets its first page at P0. A miss returns INVALID_ARGS with a suggestion; error() now takes the suggestion field that the error schema already documented.
  7. ROADMAP drops Backfill sync doesn't run #6, and the README's background sync row describes what the daemon does now.

Review fixes

  • tg chats sync runs its transaction as BEGIN IMMEDIATE. The deferred one read first, so a daemon commit after that read failed the write at once with SQLITE_BUSY_SNAPSHOT, which busy_timeout doesn't cover, and the command crashed outside the JSON error schema.
  • History takes its cursor from raw message IDs, so a full page of messageEmpty moves it instead of repeating forever. A page without any ID ends the history. The counter counts only uncached messages.
  • On an upgraded cache, a chat with a forward cursor but no backward cursor (or one above it) starts history at forward_cursor + 1, not below the oldest cached message, which left a permanent gap marked complete.
  • An unlisted chat with sync_mode = 'on' gets top_message_id = NULL after every pass, on start and on reconnect, so a public channel you haven't joined still gets new messages. The docs say so.
  • A live message from a chat without a chats_cache row caches the chat from the update (min peers skipped), so a new DM's or basic group's first page can build its InputPeer before the next dialog pass. tg chats get shares the mapper.
  • test-setup.ts imported src/db/index with hoisted static imports, so unit tests resolved the data dir before it was set and used ~/.telegram-sync-cli. On this branch the reconnect pass tests clear chat_sync_state, sync_jobs and chats_cache in that cache database. The pre-imports are now dynamic, the temp dir is forced, a test checks it, and the destructive beforeEach refuses to run outside a test data dir.
  • New tests: the reconnect pass's outer catch, and tg chats sync --account 99 plus a missing chat.
  • Docs: --off and the default policy control catch-up, first pages and history only, and live messages are cached in every chat. An archived chat starts syncing when a message arrives live. On a miss, the suggestion is now the daemon or tg chats get --id @username, because tg chats list --fresh skips archived chats and lists only the 200 newest.

Out of scope: retries and backoff (#9), the shared cache (#17), peer ID formats (#18), per-type counters in tg status, and getFullChannel for member counts.

How I checked it

  • bun run check, bun run test (1246 pass) and bun run test:e2e (113 pass) pass locally. check and test also pass at every commit on its own.

  • git diff origin/main -- src/__tests__/daemon-restart-gap.test.ts is empty, and its three cases pass.

  • New sync-fair-share.test.ts runs the real scheduler, sync worker and processJobs on 500 chats, with a fake history routed on request.peer:

    • Of the first 40 jobs, 20 are catch-up, 10 are first pages and 10 are history. The first history job is the 4th.
    • The 100 caught-up chats get no requests, and exactly 400 catch-up rows exist.
    • The queue drains in 1,000 jobs. Every chat ends with both cursors and complete history, and every gap chat has messages 1001–1150 cached with cursor = top = 1150.
    • A FLOOD_WAIT during history stops every lane until it expires. History then resumes from cursor 301. A chat turned --off mid-chain stops after its running page.
  • Against origin/main's src/daemon and src/db, the 500-chat test fails while seeding: raiseTopMessageId doesn't exist there. With that method stubbed as a no-op, it fails the first-40 assertion with 40 catch-ups.

  • New daemon-bootstrap.test.ts covers archived dialogs, MAX semantics for the newest message ID, modes kept through a pass, stored member counts, and the unvisited-chat rules. daemon-scheduler.test.ts covers the reconnect pass and one pass per account. New chats-sync.e2e.test.ts runs without credentials.

  • Not run: the live checks (a 5-minute daemon run on a copy of the test data dir, the restart catch-up of Saved Messages, the opt-in of a channel) and bun run test:integration. The smoke test now also waits for a completed initial_load. Please run it after merging, since this changes when the daemon calls Telegram. The risk to measure there is how many supergroups the unknown-count rule turns off.

  • 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 19 commits October 21, 2026 17:26
Telegram often leaves participants_count out of a supergroup's dialog.
determineSyncPolicy treated a missing count as "under 20 members", so
a group of any size could get a full-history sync. A group whose
count is unknown (null, missing or 0) is now off and Low, like a group
over 100 members.

The dialog pass also overwrote member_count with NULL whenever a
dialog left it out, so a chat could flip on and off between starts.
The upsert now keeps the stored count, and the pass computes the
policy from the dialog's count or, failing that, the stored one. A
live message in a chat the daemon hasn't seen yet passes its chat's
member count too: basic groups always carry it, so a new small group
gets its tier, while a supergroup without a count starts off.

AGENTS.md said groups of 20-100 members get the last 10 messages,
while the code and docs/sync-strategy.md use one page of 100. The code
is right: they get the newest 100 messages, then history after the
small chats. AGENTS.md and the sync strategy now say so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
refreshQueues queued initial_load only for chats with synced_messages
= 0. A chat whose first message arrived live had a counted message, so
it never got its first page: it had no backward cursor and no
history, and its forward cursor came only from the null-cursor
catch-up that the next commit stops polling for.

The first page is now due for every enabled chat whose forward_cursor
is NULL, and queueBackwardHistory queues it instead of history for
such a chat, because the first page sets both cursors.

processInitialLoadReal also had three bugs. It counted messages that
live updates had already cached. It took the cursors from parsed
messages only, so a page of messageEmpty entries left backward_cursor
at MAX_SAFE_INTEGER. And an empty chat was marked complete without a
cursor, so nothing ever caught it up. It now counts only uncached
messages, takes the cursors from raw IDs as catch-up does, writes
both cursors, history_complete and the counter in one statement, and
leaves an empty chat at cursor 0. Catch-up treats a stored 0 as a real
cursor and pages up from it. A chat that already has a forward cursor
never gets a first page again, because moving the cursor to the
newest message could skip messages below it (#15).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…every 30 seconds

refreshQueues queued a top-priority forward_catchup for every enabled
chat on every refresh, every 30 loop ticks. With one job per 3 s, an
account with ~1,860 enabled chats spent its whole budget polling chats
that had nothing new, and history never got a turn (#6).

Catch-up is now queued only for chats that are behind. A new
chat_sync_state column, top_message_id, holds the newest message ID
Telegram reported, and a chat is due while it is NULL (unknown) or
above forward_cursor. The dialog pass raises it to each dialog's
topMessage, on start and now also after every reconnect (#16), in the
background and one pass per account at a time. The first page raises
it to its newest message. A catch-up page that isn't full reached the
newest message, so the same UPDATE that moves the cursor settles the
top at the new cursor, unless a dialog pass raised it during the
fetch. Live updates never write it, so the #15 rule holds: only sync
jobs move forward_cursor, and catch-up pages up from it.

Chats that no pass lists are left, deleted or migrated. After complete
passes on every account they are marked caught up; otherwise each gets
one checking page. A reconnect pass that fails part-way does the
latter for the chats it didn't list. Startup also drops the pending
catch-up that 0.1.4 left for every chat. The pass now lists archived
dialogs too, so chats_cache can build an InputPeer for them, but it
creates no sync state for an archived chat that has none.

The trade-off from #15 is accepted: live updates don't move the
cursor, so the first catch-up after a restart or reconnect fetches the
messages received live again, about one call per 100 messages per
chat. The upsert doesn't duplicate them and only uncached messages are
counted. There is no periodic catch-up.

The column is added with ALTER TABLE when missing; "duplicate column
name" is ignored, because the CLI and the daemon can race on the
first start. Older binaries ignore it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
getNextPending ordered all pending jobs by priority and age, and the
daemon runs one job every 3 s. Catch-up was queued at P0, first pages
at the chat's tier and history at P4, so on any account with a steady
supply of catch-up work, initial_load and backward_history never ran.
History was also only queued for chats in the High and Medium tiers.

Jobs now run in three lanes: catch-up (forward_catchup), first page
(initial_load) and history (backward_history, full_sync). The lanes
take turns in the slot cycle catch-up, first page, catch-up, history,
which is 50/25/25 when every lane has work; an empty lane's slot goes
to the first lane with work. getNextJob stays a pure peek, and
processJobs calls the new recordJobRun after a job ran, so a tick
without a job or a worker uses no slot. The position is in memory and
starts over on restart. Inside a lane, jobs run by priority, age and
id; the priority is the chat's tier for every job type, so small
chats go before medium groups. SyncJobsService gets
getNextPendingOfTypes and idx_sync_jobs_lane, and every pending-job
ORDER BY ends with id.

History is queued for every enabled chat that had its first page,
in any tier, and right after a first page with history left. The
queue methods skip disabled chats and chats without a state row, and
startup drops such chats' pending jobs and moves the rest to their
chat's tier.

The rate limits don't change: one getHistory budget and one job per
3 s, and a FLOOD_WAIT stops every lane until it expires. Retries with
backoff stay with #9. sync-fair-share.test.ts runs the real
scheduler, worker and job loop on 500 chats: of the first 40 jobs, 20
are catch-up, 10 first pages and 10 history, and chats that are
caught up get no requests. Against main's scheduler the first 40 are
all catch-up. The live smoke test now waits for a completed
initial_load.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bun:sqlite opens databases with busy_timeout 0, so a write that
arrives while another connection holds the write lock fails at once
with "database is locked". The CLI and the daemon write cache.db at
the same time: tg send and tg chats list --fresh already write it,
the next commit adds tg chats sync, and on the first start of this
version both run the migration. A test with a second process holding
the lock for one second shows the write failing at once without a
busy timeout, and four processes migrating a 0.1.4 database at the
same time fail with SQLITE_BUSY in the ALTER TABLE.

initCacheSchema now sets PRAGMA busy_timeout = 5000 first, so a
write waits up to 5 s for the lock.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Large groups, groups of unknown size and channels are off by
default and were documented to sync "on request", but nothing could
turn them on: setSyncEnabled had no callers, and the startup dialog
pass rewrote sync_enabled from the policy on every start.

A new chat_sync_state column, sync_mode ('auto', 'on' or 'off'),
holds the user's choice. Only tg chats sync writes it. The upsert
used by the dialog pass and the live handler keeps sync_enabled at 1
for 'on' and 0 for 'off' and sync_priority at High for 'on', and
never writes the mode, so a pass can't undo the choice, even when the
command lands between the pass's read and its write.

tg chats sync <chat> [--off | --auto] [--account <selector>] finds
the chat in the cache by @username, by the ID tg chats list shows or
by a marked ID (-100..., -N; the argument parser reads those as
flags, so the command picks them up from the raw arguments), then by
a chat's sync state. It needs no credentials. In one transaction it
creates the state row if needed, stores the mode with the
sync_enabled and sync_priority it means and, if the mode changed,
cancels the chat's pending jobs, so the daemon queues them again at
the right priority at its next refresh. A chat turned on gets its
first page at P0. A chat that isn't cached fails with INVALID_ARGS
and a suggestion; error() now takes the suggestion the documented
error schema already had.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The README comparison's background sync row now says what the daemon
does instead of linking the issue.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The command's transaction read the chat's state before it wrote. A
deferred transaction in WAL mode that reads first can't wait for the
write lock: if the daemon commits after that read, the write fails at
once with SQLITE_BUSY_SNAPSHOT, and busy_timeout doesn't apply. The
daemon writes the cache almost all the time during a dialog pass, which
is when the not-found suggestion sends the user back to retry. The
command then died with a stack trace and exit 1 instead of the JSON
error schema.

BEGIN IMMEDIATE takes the write lock before the first read, so the
command waits under busy_timeout like any other write. The new lock
test fails at once with "database is locked" on the deferred version.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
History still took its cursor from parsed messages, and parsing drops
messageEmpty. On a full page of empty messages the backward cursor
stayed where it was (or became MAX_SAFE_INTEGER from a cursor of 0),
the page counted as full, and the job queued the same page again, one
getHistory call per history turn, for good. The first page had the
same bug and was fixed earlier in this branch; history now runs for
every enabled chat, so the history path is reachable too.

The cursor now comes from the raw message IDs, as on the first page,
and a page without any ID ends the history instead of repeating. The
counter counts only uncached messages: a first page can overwrite an
older backward cursor, so a history page may overlap rows that are
already cached.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
0.1.4's catch-up set a forward cursor without a backward one, and in
0.1.3 and earlier every live message moved the forward cursor. Such a
chat counts as having had its first page, so it never gets one; history
started at MIN(message_id) of the cache instead. Messages between the
oldest cached (often live) message and the forward cursor were never
fetched: catch-up pages up from the cursor and history paged down from
below them. History then marked itself complete, breaking the rule
that every message up to the forward cursor is cached. History used to
be starved, so nearly every upgraded cache would hit this now.

When the backward cursor is unset, or above the forward cursor (an
older first page of only empty messages set it to MAX_SAFE_INTEGER),
history now starts at forward_cursor + 1 and pages down from there.
The oldest cached message is used only when neither cursor is set.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
markUnvisitedChats assumed that a complete dialog pass lists every chat
the user is in, and marked every other enabled chat caught up. That
doesn't hold for tg chats sync: tg chats get caches a public channel
the user hasn't joined, with its access hash, and tg chats sync turns
it on. It got its first page and history, but at every later start the
complete pass didn't list it, so its top was set to the cursor. A
non-member gets no live updates, and a complete reconnect pass marked
nothing, so the channel stayed frozen at its first page with no error.

An unlisted chat with sync_mode 'on' now gets top_message_id = NULL
after every pass, complete or not, on start and on reconnect: one
checking page each time, which pages up from the cursor. Other
unlisted chats keep the old rules.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The first page of a chat first seen live needs an InputPeer, and the
sync jobs build it from chats_cache. Only dialog passes, tg chats list
--fresh and tg chats get write that table, so a chat new to this run
had no row: a DM fell back to inputPeerUser with access hash 0, and a
basic group got no InputPeer at all. Its first page then failed at
every refresh until a restart or a reconnect pass cached the chat.

The live handler now caches the chat from the update when chats_cache
has no row for it: users through userToPrivateChatCacheInput, basic
groups and channels through rawChatToCacheInput, moved out of
tg chats get so both share it. Min users and channels are skipped,
because their access hash works only in the update that carried it.
A row a dialog pass wrote is never overwritten.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
attemptReconnect starts the reconnect pass with `void
rebuildSyncWorker(...)`, so nothing awaits it. Its outer catch is all
that stands between a throw in markUnvisitedChats, refreshQueues or
getCacheDb and an unhandled rejection in the daemon, yet deleting it
broke no test: the inner catch in syncAccountDialogs absorbed every
failure the tests used.

The new case makes refreshQueues throw and checks that the pass
resolves, logs the warning and clears the account's in-flight mark.
It fails with the outer catch removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
test-setup.ts set TELEGRAM_SYNC_CLI_DATA_DIR to a temp dir and then
pre-imported src/db/index with static imports. Static imports are
hoisted above the module body, so src/db/index loaded first, read the
data dir while it was still unset and opened ~/.telegram-sync-cli: its
data.db at load time, its cache.db on the first getCacheDb(). With the
variable exported in the shell, the tests used that dir instead. Every
unit test that touches the file-backed cache database wrote to the
developer's real one, and the reconnect dialog pass tests added on this
branch clear chat_sync_state, sync_jobs and chats_cache there before
each case.

The pre-imports are now dynamic, so they run after the environment is
set, and the temp dir is set unconditionally: a data dir from the shell
or .env (a copy of a real one, say) never reaches the tests. A new test
checks that src/db/index resolved the temp dir; it fails on the old
setup. The destructive beforeEach also refuses to run outside a test
data dir.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Removing the --account check from tg chats sync broke no test, and the
"Missing chat" error was untested too. It matters because the
positional is declared optional and filled from the raw arguments, so
the parser no longer rejects a missing chat on its own.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The not-found suggestion led with `tg chats list --fresh`, which lists
only the 200 newest dialogs and leaves archived ones out (mtcute's
default). Archived channels are among the chats people are most
likely to turn on, and for them, or for anything older than the newest
200 dialogs, following that advice gave the same error again. Only the
daemon's dialog pass (archived included, no limit) or
`tg chats get --id @username` caches them, so the suggestion and the
docs now say that.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The help text said --off would "stop syncing the chat", and the docs
said large groups and channels sync only on request. sync_mode and
sync_enabled gate only the job queue: catch-up, first pages and
history. The live handler caches every incoming message in any chat,
including one turned off and any channel the policy leaves out. Someone
who turns a chat off to keep it out of the local cache would still find
its new messages in tg sql and tg messages search while the daemon
runs.

The help text, cli-commands, sync-strategy, AGENTS.md, the README and
the CHANGELOG entry now say what the mode controls and that live
messages are cached in every chat. Not caching them for an "off" chat
would be a behaviour change and is left out of this PR.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The CHANGELOG, sync-strategy and the dialog pass comment said archived
chats "don't start syncing on their own". Only the dialog pass skips
creating their state. The live handler creates a state row from the
policy for any chat that gets a message, archived or not, so a muted
archived DM or small group starts its first page and full history as
soon as one message arrives, and later passes keep it. cli-commands
said DMs sync by default without mentioning archived ones, which don't
until then.

The update doesn't carry the archive state, so changing the handler
would be a larger change than this; the three places and cli-commands
now describe what the code does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The fix for chats first seen live depends on setupEventHandlers passing
a chats cache and the update's raw chat to the update handlers, but only
the handlers were tested. Dropping either line left every test green,
and a new DM's first page would then build an InputPeer with access
hash 0 and fail at every refresh until the next dialog pass.

The new test emits a live DM from a chat with no chats_cache row through
the daemon's event handlers and checks that the row and its access hash
reach buildInputPeer. It fails if either line is removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@neoromantic
neoromantic merged commit 95a6265 into main Oct 21, 2026
5 checks passed
@neoromantic
neoromantic deleted the fix/backfill-6 branch October 21, 2026 15:22
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.

Backfill sync doesn't run

1 participant