From 35cce3151c74cf280e5fb2053e39353a1c619a9c Mon Sep 17 00:00:00 2001 From: xCyanGrizzly Date: Mon, 4 May 2026 19:58:30 +0200 Subject: [PATCH] perf: early-exit channel scan when all messages are below watermark searchChatMessages returns newest-first. Once the oldest message on a page is at or below the lastProcessedMessageId boundary, all remaining pages are even older. Stop scanning immediately instead of reading every message in the channel. This was already implemented for topic scans but missing from channel scans. On a test run, total messages scanned dropped from 3805 to 1615 (57% reduction) for an account with no new archives. Co-Authored-By: Claude Opus 4.6 (1M context) --- worker/src/tdlib/download.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/worker/src/tdlib/download.ts b/worker/src/tdlib/download.ts index 2e70389..dc31ae2 100644 --- a/worker/src/tdlib/download.ts +++ b/worker/src/tdlib/download.ts @@ -246,6 +246,11 @@ export async function getChannelMessages( fromMessageId = result.messages[result.messages.length - 1].id; if (result.messages.length < Math.min(limit, 100)) break; + // Early exit: searchChatMessages returns newest-first. Once the oldest + // message on this page is at or below the boundary, all remaining pages + // are even older — no new messages exist, stop scanning immediately. + if (boundary && fromMessageId <= boundary) break; + await sleep(config.apiDelayMs); } }