Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

perf: 为近期回复查询添加部分索引

Zhehui Bi88b5b81c05a5
diff --git a/server/message-db.test.ts b/server/message-db.test.ts
index b114db8f9a..7073315b6f 100644
--- a/server/message-db.test.ts
+++ b/server/message-db.test.ts
@@ -21,6 +21,7 @@ import { closeMessageDb,
LATEST_SAID_BY_BOT_SQL,
latestSaidByBot,
markNotificationLogRead,
+ prepared,
readMessageText,
recentMessages,
recentNotificationLog,
@@ -267,6 +268,7 @@ describe("message-db", () => {
const now = Date.UTC(2026, 8, 16, 12);
const hour = 3_600_000;
insertMessage("dm", msg("d1", "I started the invoice run", { role: "bot", at: now - 3 * hour }));
+ insertMessage("dm", msg("d0", "A reply with the same timestamp", { role: "bot", at: now - hour }));
insertMessage("dm", msg("d2", "Sent the three flagged invoices.\n\nAnything else?", { role: "bot", at: now - hour }));
insertMessage("dm", msg("d3", "thanks", { role: "user", at: now - hour + 1 }));
insertMessage("room", msg("r1", "I can take the deploy", { role: "bot", at: now - 2 * hour, from: { botId: "me", name: "Me", color: "#000" } }));
@@ -471,14 +473,14 @@ describe("latestPersonLineAts", () => {
});
});
-describe("messages_thread_at", () => {
+describe("thread time indexes", () => {
beforeEach(() => {
closeMessageDb();
rmSync(DATA_DIR, { recursive: true, force: true });
mkdirSync(DATA_DIR, { recursive: true });
});
- it("plans a thread's latest rows on messages_thread_at", () => {
+ it("adds the bot text index on reopen and uses it only for recent replies", () => {
for (let thread = 0; thread < 4; thread += 1) {
for (let n = 0; n < 50; n += 1) {
insertMessage(`thread-${thread}`, msg(`m-${thread}-${n}`, "hello from the bot", { role: "bot", at: n }));
@@ -486,19 +488,23 @@ describe("messages_thread_at", () => {
}
closeMessageDb();
const raw = new DatabaseSync(join(DATA_DIR, "messages.db"));
- const planOf = (sql: string) => raw.prepare(`EXPLAIN QUERY PLAN ${sql}`).all()
- .map((row) => String((row as { detail: string }).detail))
- .join("\n");
try {
- const said = planOf(LATEST_SAID_BY_BOT_SQL.replace("json_each(?)", "json_each('[\"thread-0\"]')"));
- const ats = planOf("SELECT value AS thread_id, (SELECT MAX(at) FROM messages WHERE thread_id = value ) AS at FROM json_each(?)");
- expect(said).toContain("SEARCH m2 USING INDEX messages_thread_at");
- expect(said).toContain("SEARCH m USING INDEX sqlite_autoindex_messages_1");
- expect(said.split("\n")).not.toContain("SCAN m");
- expect(ats).toContain("messages_thread_at");
+ raw.exec("DROP INDEX IF EXISTS messages_thread_bot_text");
} finally {
raw.close();
}
+
+ expect(latestSaidByBot(["thread-0"], "bot", 0).map((row) => row.messageId)).toEqual(["m-0-49"]);
+ const planOf = (sql: string, ...params: (string | number)[]) => prepared(`EXPLAIN QUERY PLAN ${sql}`).all(...params)
+ .map((row) => String((row as { detail: string }).detail))
+ .join("\n");
+ const threads = JSON.stringify(["thread-0"]);
+ const said = planOf(LATEST_SAID_BY_BOT_SQL, 0, "bot", threads, 10);
+ const ats = planOf("SELECT value AS thread_id, (SELECT MAX(at) FROM messages WHERE thread_id = value) AS at FROM json_each(?)", threads);
+ expect(said).toContain("SEARCH m2 USING INDEX messages_thread_bot_text");
+ expect(said).toContain("SEARCH m USING INDEX sqlite_autoindex_messages_1");
+ expect(said.split("\n")).not.toContain("SCAN m");
+ expect(ats).toContain("messages_thread_at");
});
});
diff --git a/server/message-db.ts b/server/message-db.ts
index a4ddb664ca..39e7a023a2 100644
--- a/server/message-db.ts
+++ b/server/message-db.ts
@@ -59,11 +59,10 @@ function open(): DatabaseSync {
PRIMARY KEY (thread_id, id)
);
CREATE INDEX IF NOT EXISTS messages_thread ON messages(thread_id);
- -- at is not part of the primary key, so newest-per-thread reads cannot
- -- walk these rows in time order on messages_thread. Created on every
- -- open, including a database that already has messages.
+ -- The primary key has no time column, so newest-per-thread reads need this index.
CREATE INDEX IF NOT EXISTS messages_thread_at ON messages(thread_id, at);
-- Partial, so no other query's plan can move onto them: only a statement that repeats the WHERE may use one.
+ CREATE INDEX IF NOT EXISTS messages_thread_bot_text ON messages(thread_id, at) WHERE kind = 'text' AND role = 'bot' AND text IS NOT NULL;
CREATE INDEX IF NOT EXISTS messages_thread_order ON messages(thread_id, ${ORDERING_AT}) WHERE ${ORDERING_ROW};
CREATE INDEX IF NOT EXISTS messages_work_at ON messages(kind, at) WHERE ${WORK_KINDS};
CREATE INDEX IF NOT EXISTS messages_cards_at ON messages(kind, at) WHERE ${CARD_KINDS};
@@ -902,7 +901,7 @@ export interface ThreadLatest {
head: string;
}
-/** CROSS JOIN pins the order: the list, then messages_thread_at per thread, then the primary key (thread_id, id). `id` alone has no index. */
+/** CROSS JOIN pins the order: the list, then a seek in each thread's bot text, then the primary key (thread_id, id). `id` alone has no index. */
export const LATEST_SAID_BY_BOT_SQL =
"WITH latest(thread_id, id) AS MATERIALIZED (" +
"SELECT j.value, (SELECT m2.id FROM messages m2 " +