From 6f6297c4cd2405d7cd8ae350ca8dc5e2bbcd2eed Mon Sep 17 00:00:00 2001 From: leemour Date: Wed, 25 Nov 2026 02:27:06 +0100 Subject: [PATCH] perf(store): a history sync slows as the chat grows, and the fix Benchmark and results for tg-cli #917: saving a page of 100 messages took 78 ms at 10k stored messages and 919 ms at 90k, because the thread-child link scanned the whole chat once per message. cli-core #3333 runs it once per page (32-42 ms up to 60k), and an index in store version 73 keeps it flat. Co-Authored-By: Claude Opus 5.5 --- performance/store/README.md | 2 + performance/store/sync-growth/README.md | 65 ++++++++++++++++++++ performance/store/sync-growth/bench.test.ts | 68 +++++++++++++++++++++ 3 files changed, 135 insertions(+) create mode 100644 performance/store/sync-growth/README.md create mode 100644 performance/store/sync-growth/bench.test.ts diff --git a/performance/store/README.md b/performance/store/README.md index b8dd34f..71d2ff7 100644 --- a/performance/store/README.md +++ b/performance/store/README.md @@ -41,3 +41,5 @@ Measurements of the SQLite store that tg-cli, max-cli, memo and drive share thro chats in one read, at the owner's scale: 2 ms for 30 days, 31 ms for all time (2026-11-10). - [vector-purge](vector-purge/README.md) — dropping a rebuild's old vectors: the purge's two lookups by their index, a forum rebuild from 889 s to 52 s (2026-11-18). +- [sync-growth](sync-growth/README.md) — a history sync that slowed from 75 to 7 messages/s as the chat grew: one + thread-link scan per message, now one per page (2026-11-25). diff --git a/performance/store/sync-growth/README.md b/performance/store/sync-growth/README.md new file mode 100644 index 0000000..cb7bb13 --- /dev/null +++ b/performance/store/sync-growth/README.md @@ -0,0 +1,65 @@ +# A long sync slows down as the chat grows + +## Why it was run + +A tg-cli user reported that `messages sync` of a big group started at about 75 messages/s and fell to about 7 as the +store filled ([tg-cli #917](https://github.com/WireCatLabs/tg-cli/issues/917)). The question: is it Telegram, or the +store? And if the store, which statement grows with the chat? The answer decided cli-core +[#3333](https://github.com/WireCatLabs/cli-core/pull/3333), a code-only fix released on 0.x, and an index added to +store version 73 with cli-core 1.0. + +## Setup + +- Machine: AMD Ryzen AI 9 HX 370, 59 GB RAM, Linux 7.0, Node 24.19.0. +- Code: cli-core `main` at `4e62a357a` (before) and `feadb663b` from #3333 (after). +- Data: synthetic only. [`bench.test.ts`](bench.test.ts) opens an empty store, then saves one group chat in pages of + 100 messages from the newest id down, as a history sync does: `saveMessages` then `markRange` for each page. Every + fifth message replies to another. It prints the mean time per page for each 10,000 messages stored. +- The database is on tmpfs (`/dev/shm`), so the numbers leave out the fsync of each commit. On the sandbox's disk + that adds about 200 ms per commit, whatever the chat size. + +```sh +cp bench.test.ts /src/store/zz-bench-917.test.ts +cd +BENCH_DB=/dev/shm/bench917/m.db BENCH_TOTAL=90000 BENCH_OUT=$PWD/bench.txt pnpm exec vitest run src/store/zz-bench-917.test.ts +``` + +`BENCH_INDEX` takes SQL that runs on the new database before the first page, used here to try an index. + +## Results + +Time to save one page of 100 messages, by messages already stored in the chat: + +| Stored | Before | Index only | After (#3333) | +|---|---|---|---| +| 10,000 | 78 ms | 19 ms | 32 ms | +| 20,000 | 190 ms | 24.9 ms | 32.9 ms | +| 30,000 | 294 ms | 21.9 ms | 37.1 ms | +| 40,000 | 452 ms | 23.4 ms | 38.4 ms | +| 50,000 | 531 ms | — | 40.6 ms | +| 60,000 | 593 ms | — | 42.2 ms | +| 90,000 | 919 ms | — | — | + +`markRange` stayed under 1 ms per page in every run. + +"Index only" is the code before the fix, with +`CREATE INDEX bench_thread ON messages (chat_id, thread_external_id) WHERE thread_root_id IS NULL AND thread_external_id IS NOT NULL`. + +## What it showed + +- The store is the cause. A CPU profile of the "before" run put 85% of the time in SQL inside `upsertMessage`. +- The statement that grows is the one that links replies saved before their thread's root: + `UPDATE messages SET thread_root_id=? WHERE chat_id=? AND thread_external_id=? AND thread_root_id IS NULL`. No + index covers `thread_external_id`, so SQLite's plan is `SEARCH messages USING INDEX messages_by_time (chat_id=?)`, + a scan of the whole chat. It ran once for each saved message. +- #3333 runs it once per page. That leaves one scan per page, so the time still grows slowly (32 → 42 ms over + 60,000 messages). The index removes the scan and keeps the time flat. It needs a store migration, so it ships in + version 73 with cli-core 1.0. + +## What was not measured + +- The "after" run was made on a busy machine (load average about 25). The "before" and "index only" runs were made + earlier the same night under unknown load. Compare the trend, not the exact milliseconds. +- Telegram's own speed, flood waits and media downloads. The benchmark only covers the store. +- The fix and the index together. +- Chats beyond 90,000 messages. diff --git a/performance/store/sync-growth/bench.test.ts b/performance/store/sync-growth/bench.test.ts new file mode 100644 index 0000000..cf2620c --- /dev/null +++ b/performance/store/sync-growth/bench.test.ts @@ -0,0 +1,68 @@ +import { appendFileSync, mkdtempSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { it } from "vitest" +import type { Message } from "../domain/models.js" +import { openStore } from "./store.js" + +const account = { provider: "telegram", account: "500" } +const TOTAL = Number(process.env.BENCH_TOTAL ?? 60_000) +const PAGE = 100 +const TOP = 2_000_000 + +const message = (id: number): Message => ({ + id: String(id), + chatId: "-100777", + senderId: String(1000 + (id % 300)), + senderName: `Member ${id % 300}`, + timestamp: new Date(Date.UTC(2024, 0, 1) + id * 60_000).toISOString(), + editedAt: null, + text: `message ${id} about the release, ping @member${id % 300} and see https://example.com/${id}`, + outgoing: false, + attachments: [], + replyTo: null, + ...(id % 5 === 0 ? { replyToId: String(id + 3) } : {}), + forwardedFrom: null, + reactions: null, +}) + +it("bench", { timeout: 3_600_000 }, async () => { + const store = await openStore({ + path: process.env.BENCH_DB ?? join(mkdtempSync(join(tmpdir(), "bench917-")), "m.db"), + }) + if (process.env.BENCH_INDEX) { + const { DatabaseSync } = await import("node:sqlite") + const side = new DatabaseSync(process.env.BENCH_DB as string) + side.exec(process.env.BENCH_INDEX) + side.close() + } + await store.chats.saveChats(account, [ + { + id: "-100777", + title: "Big group", + kind: "group", + unreadCount: 0, + lastMessageAt: null, + participantsCount: 300, + }, + ]) + let window = { save: 0, mark: 0, pages: 0 } + for (let held = 0; held < TOTAL; held += PAGE) { + const top = TOP - held + const page = Array.from({ length: PAGE }, (_, i) => message(top - i)) + const a = performance.now() + await store.messages.saveMessages(account, "-100777", page, { via: "history", seenAt: Date.now() }) + const b = performance.now() + await store.sync.markRange(account, "-100777", top - PAGE + 1, TOP) + const c = performance.now() + window = { save: window.save + b - a, mark: window.mark + c - b, pages: window.pages + 1 } + if ((held + PAGE) % 10_000 === 0) { + appendFileSync( + process.env.BENCH_OUT ?? "/dev/null", + `held ${held + PAGE}: save ${(window.save / window.pages).toFixed(1)} ms/page, mark ${(window.mark / window.pages).toFixed(1)} ms/page\n`, + ) + window = { save: 0, mark: 0, pages: 0 } + } + } + await store.close() +})