diff --git a/changes/fix-sync-thread-link-per-page.md b/changes/fix-sync-thread-link-per-page.md new file mode 100644 index 000000000..3e0614952 --- /dev/null +++ b/changes/fix-sync-thread-link-per-page.md @@ -0,0 +1,5 @@ +### Fixed + +- **A long sync stays fast as the chat grows.** Each saved message looked through the whole chat for replies + waiting for it as their thread's root, so a page of 100 took 78 ms at 10,000 stored messages and 919 ms at 90,000. + That search now runs once per page (tg-cli [#917](https://github.com/WireCatLabs/tg-cli/issues/917)). diff --git a/src/store/messages.ts b/src/store/messages.ts index 2a26fe28e..93de596e5 100644 --- a/src/store/messages.ts +++ b/src/store/messages.ts @@ -181,6 +181,11 @@ export const accountMessagesOver = (context: StoreContext): AccountMessages => { if (upsertMessage(key, accountKey, chatKey, message, via, seenAt) && countUnread) messageWrites.countUnread(context, chatKey, message) } + messageWrites.linkThreadChildren( + context, + chatKey, + messages.filter((message) => message.scheduledFor === undefined).map((message) => message.id), + ) for (const { messageId, vote } of votes) messageWrites.saveVote(context, accountKey, key.provider, chatKey, messageId, vote) for (const { messageId, reaction } of reactions) diff --git a/src/store/messaging.test.ts b/src/store/messaging.test.ts index 723c5b202..56655bc30 100644 --- a/src/store/messaging.test.ts +++ b/src/store/messaging.test.ts @@ -54,6 +54,16 @@ it("stores scoped nested chats and connects a reply thread when its root arrives ) .get()?.external_id, ).toBe("root") + await store.messages.saveMessages(account, "room", [message("late", { threadId: "early" }), message("early")], { + via: "history", + }) + expect( + db + .prepare( + "SELECT root.external_id FROM messages reply JOIN messages root ON root.id=reply.thread_root_id WHERE reply.external_id='late'", + ) + .get()?.external_id, + ).toBe("early") expect( db .prepare( @@ -65,7 +75,7 @@ it("stores scoped nested chats and connects a reply thread when its root arrives scope: "personal", parentChatId: "parent", }) - expect(db.prepare("SELECT message_count FROM chats WHERE external_id='room'").get()?.message_count).toBe(2) + expect(db.prepare("SELECT message_count FROM chats WHERE external_id='room'").get()?.message_count).toBe(4) await store.messages.markDeleted(account, ["root"], { chatId: "room" }) await store.messages.keepTranscript(account, "room", "root", "Late transcript", "synthetic") expect(await store.messages.transcript(account, "room", "root")).toBeUndefined() diff --git a/src/store/sqlite/messages.ts b/src/store/sqlite/messages.ts index cc3e805ae..f0b6b2897 100644 --- a/src/store/sqlite/messages.ts +++ b/src/store/sqlite/messages.ts @@ -149,6 +149,21 @@ const fieldsOf = (message: Message, sender: number | null): Fields => ({ normalizerVersion: NORMALIZER_VERSION, }) +/** + * Points replies saved before their thread's root at it. Run once per page: no index covers `thread_external_id`, + * so each run reads the whole chat, and once per message made a sync slow down as the chat grew (tg-cli #917). + */ +export const linkThreadChildren = (context: StoreContext, chatKey: number, rootIds: readonly Id[]): void => { + if (rootIds.length === 0) return + context.database + .prepare( + `UPDATE messages SET thread_root_id=(SELECT root.id FROM messages root + WHERE root.chat_id=messages.chat_id AND root.external_id=messages.thread_external_id) + WHERE chat_id=? AND thread_root_id IS NULL AND thread_external_id IN (SELECT value FROM json_each(?))`, + ) + .run(chatKey, JSON.stringify(rootIds.map(String))) +} + export const upsertMessage = ( context: StoreContext, key: AccountKey, @@ -277,9 +292,6 @@ export const upsertMessage = ( ) .run(chatKey, root, pk) } - context.database - .prepare("UPDATE messages SET thread_root_id=? WHERE chat_id=? AND thread_external_id=? AND thread_root_id IS NULL") - .run(pk, chatKey, message.id) const heardFirst = context.database .prepare( "UPDATE message_transcripts SET message_id=? WHERE chat_id=? AND message_external_id=? AND message_id IS NULL", diff --git a/src/store/sqlite/record-projectors-phone.ts b/src/store/sqlite/record-projectors-phone.ts index 93cd3a6f2..0d2653bcd 100644 --- a/src/store/sqlite/record-projectors-phone.ts +++ b/src/store/sqlite/record-projectors-phone.ts @@ -9,7 +9,7 @@ import { calendarWritesOver } from "./calendar.js" import { chatPkFor, findChatPk, raiseLastMessageAt, upsertChat, writeMembers } from "./chats.js" import { seenIdentity } from "./identities.js" import { COUNTERPART_ROLE, linkKind } from "./link-kinds.js" -import { tombstone, upsertMessage } from "./messages.js" +import { linkThreadChildren, tombstone, upsertMessage } from "./messages.js" import { requiredThing } from "./notes.js" import type { StoreContext } from "./open.js" import { e164Of } from "./person-matcher.js" @@ -124,6 +124,7 @@ const saveSms = (projection: Projection, tools: ProjectionTools, revive = false) importedBy(source).source, revive ? context.now() + 1 : undefined, ) + linkThreadChildren(context, chatKey, [message.id]) raiseLastMessageAt(context, chatKey, sentAt) return formatReference({ type: "message",