Skip to content

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

fix(message-db): attachment-name index answers threadsReferencing without a full-table scan (#6255)

CI fixture87246500e96e
diff --git a/scripts/testing/file-size-ratchet.test.ts b/scripts/testing/file-size-ratchet.test.ts
index 10a4ea7392..56945117d3 100644
--- a/scripts/testing/file-size-ratchet.test.ts
+++ b/scripts/testing/file-size-ratchet.test.ts
@@ -43,6 +43,7 @@ const LINES: Record<string, number> = {
"server/cli.ts": 1052,
"src/components/AttachmentPreview.tsx": 1017,
"server/meetings/meetbot.ts": 1047,
+ "server/message-db.ts": 1009, // the attachment-name index hooks (issue #6255): one line per message write, delete and reopen path
"electron/data-dir-lease.node-test.mjs": 846, // the data-folder lease's own tests: many platform cases (Windows probes in data-dir-lease-windows.node-test.mjs)
};
diff --git a/server/message-db-attachment-names.ts b/server/message-db-attachment-names.ts
new file mode 100644
index 0000000000..38a79c5800
--- /dev/null
+++ b/server/message-db-attachment-names.ts
@@ -0,0 +1,139 @@
+// Which conversations' messages name a stored upload (message-db.ts threadsReferencing). Asking SQLite once per name
+// (instr over every row's JSON) is a full read of messages.db per name, on the main thread: a 740k-row install held its
+// server for 79 s per refused hand-off file (issue #6255). This in-memory index answers the question per name without
+// reading any row.
+//
+// saveFile/saveImage/saveAudio only ever store `${uuid}${extension}`, so every name these queries ask for is one shape:
+// a lowercase uuid with an extension. threadsFor answers only that shape; anything else falls back to the SQL scan in
+// message-db.ts, which is the answer instr gives. Exactness rule: a name is indexed where it appears in a row's JSON as
+// a whole token (the character after the extension is not alphanumeric, as it never is in a path the server writes).
+// instr also matches a name inside a longer token (its ".png" inside a ".png2"); no reference the server writes does
+// that, so a lookup sees every row instr would.
+//
+// The index is built on the first uuid-shaped query: one pass over the rows, the read threadsReferencing already did,
+// with no write able to interleave (the build holds the only thread that writes). Rows written before it are covered by
+// the pass; rows written after go through written; row removals through threadsDeleted. A reopened database resets the
+// index, and the next query rebuilds it from the rows that are there then.
+import type { StatementSync } from "node:sqlite";
+
+const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}";
+
+/** A name saveFile/saveImage/saveAudio store: `${uuid}${extension}`. Uppercase uuids (a client may send one) never
+ * match here and take the scan, where instr is case-exact too. */
+export const STORED_UPLOAD_NAME = new RegExp(`^${UUID}\\.[A-Za-z0-9]{1,10}$`);
+
+const NAME_IN_JSON = new RegExp(`(?<![0-9A-Za-z])${UUID}\\.[A-Za-z0-9]{1,10}(?![A-Za-z0-9])`, "g");
+
+const ROWS_SQL = "SELECT rowid, thread_id, id, json FROM messages WHERE rowid > ? ORDER BY rowid LIMIT ?";
+/** Rows per build slice, so one pass never holds a large transcript's JSON in memory at once. */
+const ROWS_PER_PASS = 512;
+
+export interface AttachmentNameRow { rowid: number; thread_id: string; id: string; json: string }
+export type AttachmentNameRows = (after: number, limit: number) => readonly AttachmentNameRow[];
+
+export interface AttachmentNameIndex {
+ /** Records the names `json` holds now, replacing what this row held before. Nothing until the first build. */
+ written(threadId: string, messageId: string, json: string): void;
+ /** Forgets every row of the threads given. */
+ threadsDeleted(threadIds: readonly string[]): void;
+ /** The threads whose messages name `name`, a stored upload name; builds the index first. */
+ threadsFor(name: string): string[];
+ /** Forgets everything; the next query rebuilds from the rows that are there then. */
+ reset(): void;
+ /** Builds so far. */
+ readonly builds: number;
+}
+
+export function createAttachmentNameIndex(deps: { prepare: (sql: string) => StatementSync }): AttachmentNameIndex {
+ /** name → threadId → the message ids of that thread that hold the name. */
+ const byName = new Map<string, Map<string, Set<string>>>();
+ /** threadId → messageId → the names that message holds. */
+ const byThread = new Map<string, Map<string, ReadonlySet<string>>>();
+ let built = false;
+ let builds = 0;
+
+ function namesIn(json: string): ReadonlySet<string> {
+ const found = new Set<string>();
+ for (const match of json.matchAll(NAME_IN_JSON)) found.add(match[0]);
+ return found;
+ }
+
+ function drop(threadId: string, messageId: string, names: ReadonlySet<string>): void {
+ for (const name of names) {
+ const threads = byName.get(name)!;
+ const messages = threads.get(threadId)!;
+ messages.delete(messageId);
+ if (!messages.size) threads.delete(threadId);
+ if (!threads.size) byName.delete(name);
+ }
+ }
+
+ function record(threadId: string, messageId: string, names: ReadonlySet<string>): void {
+ const thread = byThread.get(threadId);
+ const previous = thread?.get(messageId);
+ if (previous) drop(threadId, messageId, previous);
+ if (!names.size) {
+ if (previous) {
+ thread!.delete(messageId);
+ if (!thread!.size) byThread.delete(threadId);
+ }
+ return;
+ }
+ const messages = thread ?? new Map<string, ReadonlySet<string>>();
+ if (!thread) byThread.set(threadId, messages);
+ messages.set(messageId, names);
+ for (const name of names) {
+ let threads = byName.get(name);
+ if (!threads) byName.set(name, threads = new Map());
+ let ids = threads.get(threadId);
+ if (!ids) threads.set(threadId, ids = new Set());
+ ids.add(messageId);
+ }
+ }
+
+ function build(): void {
+ byName.clear();
+ byThread.clear();
+ let first: StatementSync | undefined;
+ const read: AttachmentNameRows = (after, limit) => {
+ const statement = deps.prepare(ROWS_SQL);
+ if ((first ??= statement) !== statement) throw new Error("messages.db was reopened during the attachment-name index build");
+ return statement.all(after, limit) as unknown as AttachmentNameRow[];
+ };
+ let after = 0;
+ for (;;) {
+ const slice = read(after, ROWS_PER_PASS);
+ if (!slice.length) break;
+ for (const row of slice) record(row.thread_id, row.id, namesIn(row.json));
+ after = slice[slice.length - 1]!.rowid;
+ }
+ built = true;
+ builds++;
+ }
+
+ return {
+ written(threadId, messageId, json) {
+ if (!built) return;
+ record(threadId, messageId, namesIn(json));
+ },
+ threadsDeleted(threadIds) {
+ if (!built) return;
+ for (const threadId of threadIds) {
+ const thread = byThread.get(threadId);
+ if (!thread) continue;
+ for (const [messageId, names] of thread) drop(threadId, messageId, names);
+ byThread.delete(threadId);
+ }
+ },
+ threadsFor(name) {
+ if (!built) build();
+ return [...(byName.get(name)?.keys() ?? [])];
+ },
+ reset() {
+ built = false;
+ byName.clear();
+ byThread.clear();
+ },
+ get builds() { return builds; },
+ };
+}
diff --git a/server/message-db.test.ts b/server/message-db.test.ts
index 42fdff1d8d..bbcc695fea 100644
--- a/server/message-db.test.ts
+++ b/server/message-db.test.ts
@@ -33,6 +33,8 @@ import { closeMessageDb,
recallMessages,
searchMessages,
setActiveLeaf,
+ attachmentNameIndex,
+ threadsReferencing,
updateMessage, describeMissingFts5 } from "./message-db.ts";
import type { NotificationLogEntry } from "../shared/notification.ts";
import { withPeerProvenance } from "./peer-provenance.ts";
@@ -49,6 +51,14 @@ const msg = (id: string, text: string, extra: Partial<Message> = {}): Message =>
at: Date.now(),
...extra,
});
+const UPLOAD_A = "3f2b1c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d.png";
+const UPLOAD_B = "9e8d7c6b-5a49-4f3e-ab1a-0c9d8e7f6a5b.jpg";
+const storedUpload = (name: string): NonNullable<Message["attachments"]>[number] => ({
+ kind: "file",
+ path: join(DATA_DIR, "attachments", name),
+ mime: "application/pdf",
+ name: "notes.pdf",
+});
describe("message-db", () => {
beforeEach(() => {
@@ -188,6 +198,50 @@ describe("message-db", () => {
expect(counts.map((row) => ({ ...row }))).toEqual([{ thread_id: "r1", n: 1 }, { thread_id: "r2", n: 1 }]);
});
+ it("threadsReferencing answers a stored upload's name from the index: a patch-added name is found and a patch-removed one is not", () => {
+ insertMessage("t1", msg("m1", "hello", { attachments: [storedUpload(UPLOAD_B)] }));
+ expect(threadsReferencing(UPLOAD_A)).toEqual([]); // the first query builds the index from the rows
+ insertMessage("t1", msg("m2", "", { attachments: [storedUpload(UPLOAD_A)] }));
+ expect(threadsReferencing(UPLOAD_A)).toEqual(["t1"]);
+ // host/turn-attachments.ts patches attachments onto an existing reply, and the upsert keeps the row's old rowid:
+ updateMessage("t1", msg("m2", ""));
+ expect(threadsReferencing(UPLOAD_A)).toEqual([]);
+ expect(threadsReferencing(UPLOAD_B)).toEqual(["t1"]);
+ });
+
+ it("threadsReferencing stops finding a name once a thread that named it is deleted", () => {
+ insertMessage("t1", msg("m1", "", { attachments: [storedUpload(UPLOAD_A)] }));
+ insertMessage("t2", msg("m1", "", { attachments: [storedUpload(UPLOAD_A)] }));
+ expect(threadsReferencing(UPLOAD_A).sort()).toEqual(["t1", "t2"]);
+ deleteThread("t2");
+ expect(threadsReferencing(UPLOAD_A)).toEqual(["t1"]);
+ });
+
+ it("threadsReferencing rebuilds the attachment-name index when messages.db reopens, so it stays exact", () => {
+ insertMessage("t1", msg("m1", "", { attachments: [storedUpload(UPLOAD_A)] }));
+ expect(threadsReferencing(UPLOAD_A)).toEqual(["t1"]);
+ closeMessageDb();
+ insertMessage("t2", msg("m1", "", { attachments: [storedUpload(UPLOAD_A)] })); // the reopen resets the index; the write hook is quiet until the next build
+ expect(threadsReferencing(UPLOAD_A).sort()).toEqual(["t1", "t2"]);
+ expect(threadsReferencing(UPLOAD_B)).toEqual([]);
+ });
+
+ it("threadsReferencing reads the rows for a name no stored upload can have", () => {
+ insertMessage("t1", msg("m1", "saved it as my notes.txt in the folder"));
+ expect(threadsReferencing("my notes.txt")).toEqual(["t1"]);
+ expect(threadsReferencing("no-such-thing.txt")).toEqual([]);
+ });
+
+ it("builds the attachment-name index once, not per query or per write", () => {
+ const before = attachmentNameIndex.builds;
+ insertMessage("t1", msg("m1", "", { attachments: [storedUpload(UPLOAD_A)] }));
+ threadsReferencing(UPLOAD_A);
+ threadsReferencing(UPLOAD_A);
+ updateMessage("t1", msg("m1", "edited", { attachments: [storedUpload(UPLOAD_A)] }));
+ expect(threadsReferencing(UPLOAD_A)).toEqual(["t1"]);
+ expect(attachmentNameIndex.builds).toBe(before + 1);
+ });
+
it("recall ranks by relevance, scopes to the given threads, and survives updates and deletes", () => {
insertMessage("own-a", msg("m1", "The site audit found three broken links on the pricing page", { role: "bot" }));
insertMessage("own-a", msg("m2", "audit", { role: "user" }));
diff --git a/server/message-db.ts b/server/message-db.ts
index 266c49e8de..8d65bbc5c1 100644
--- a/server/message-db.ts
+++ b/server/message-db.ts
@@ -10,6 +10,7 @@ import type { Message } from "./store.ts";
import type { UsageTrigger } from "./usage-ledger.ts";
import { BOT_TEXT_MESSAGE_INDEXES_SQL } from "./message-db-bot-text-indexes.ts";
import { ensureMemoryIndex } from "./message-db-memory-index.ts";
+import { createAttachmentNameIndex, STORED_UPLOAD_NAME } from "./message-db-attachment-names.ts";
import { cjkSearchText, cjkTokenParts, ensureSearchIndex, ftsPhrase, hasCjk, withoutSearchMarks } from "./cjk-search.ts";
import { attentionSelect } from "./message-db-attention.ts";
import { MessageSearchWorker } from "./message-search-worker.ts"; import { messageWritten } from "./message-writes.ts";
@@ -153,6 +154,7 @@ function db(): DatabaseSync {
} catch {}
statements = new Map();
handle = open();
+ attachmentNameIndex.reset();
handlePath = file;
handleCheckedAt = Date.now();
return handle;
@@ -420,7 +422,7 @@ function importLegacy(threadId: string, legacyFile: string): ThreadRows {
const insert = db().prepare(UPSERT_MESSAGE);
db().exec("BEGIN");
try {
- for (const message of messages) insert.run(...messageRow(threadId, message));
+ for (const message of messages) { const row = messageRow(threadId, message); insert.run(...row); attachmentNameIndex.written(threadId, message.id, row[6]); }
setActiveLeaf(threadId, activeLeafId);
db().exec("COMMIT");
} catch (error) {
@@ -437,7 +439,7 @@ function importLegacy(threadId: string, legacyFile: string): ThreadRows {
}
export function insertMessage(threadId: string, message: Message): void {
- const row = messageRow(threadId, message); prepared(UPSERT_MESSAGE).run(...row); messageWritten(row[6]);
+ const row = messageRow(threadId, message); prepared(UPSERT_MESSAGE).run(...row); messageWritten(row[6]); attachmentNameIndex.written(threadId, message.id, row[6]);
}
/** `relinked`: adds `messages` to a conversation that has rows; each row it names changes only its parentId, and an id it already has fails the whole import. */
@@ -449,7 +451,7 @@ export function importThread(threadId: string, messages: Message[], activeLeafId
}
const insert = relinked && database.prepare("INSERT INTO messages (thread_id, id, at, role, kind, text, json, search_text) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
for (const message of messages) {
- if (insert) { const row = messageRow(threadId, message); insert.run(...row); messageWritten(row[6]); }
+ if (insert) { const row = messageRow(threadId, message); insert.run(...row); messageWritten(row[6]); attachmentNameIndex.written(threadId, message.id, row[6]); }
else insertMessage(threadId, message);
}
const link = database.prepare("UPDATE messages SET json = json_set(json, '$.parentId', ?) WHERE thread_id = ? AND id = ?");
@@ -466,7 +468,7 @@ export function appendMessage(threadId: string, message: Message): void {
}
export function updateMessage(threadId: string, message: Message): void {
- const json = JSON.stringify(message); prepared("UPDATE messages SET at = ?, role = ?, kind = ?, text = ?, json = ?, search_text = ? WHERE thread_id = ? AND id = ?").run(message.at, message.role, message.kind, message.text ?? null, json, cjkSearchText(message.text), threadId, message.id); messageWritten(json);
+ const json = JSON.stringify(message); prepared("UPDATE messages SET at = ?, role = ?, kind = ?, text = ?, json = ?, search_text = ? WHERE thread_id = ? AND id = ?").run(message.at, message.role, message.kind, message.text ?? null, json, cjkSearchText(message.text), threadId, message.id); messageWritten(json); attachmentNameIndex.written(threadId, message.id, json);
}
export function workingGoalRunMessages(): Array<{ threadId: string; message: Message }> {
@@ -663,6 +665,8 @@ export function deleteThreads(threadIds: readonly string[], beforeCommit?: () =>
for (const id of threadIds) for (const statement of statements) statement.run(id);
beforeCommit?.();
});
+ // After the commit: a rolled-back batch's rows stay, and the index must not forget them.
+ attachmentNameIndex.threadsDeleted(threadIds);
}
/** Option-card rows whose card names one of `tools`, oldest first; the caller judges each card itself. */
@@ -684,8 +688,13 @@ export function liveAppRows(limit = 100): Array<{ threadId: string; messageId: s
return db().prepare("SELECT thread_id AS threadId, id AS messageId FROM messages WHERE kind = 'app' AND json_extract(json, '$.app.live') = 1 ORDER BY rowid DESC LIMIT ?").all(limit) as Array<{ threadId: string; messageId: string }>;
}
+/** The attachment-name index (message-db-attachment-names.ts), which threadsReferencing answers stored upload names
+ * from; exported so tests can see how often it built. */
+export const attachmentNameIndex = createAttachmentNameIndex({ prepare: (sql) => prepared(sql) });
+
export function threadsReferencing(fragment: string): string[] {
if (!fragment) return [];
+ if (STORED_UPLOAD_NAME.test(fragment)) return attachmentNameIndex.threadsFor(fragment);
const rows = db().prepare("SELECT DISTINCT thread_id FROM messages WHERE instr(json, ?) > 0").all(fragment) as Array<{ thread_id: string }>;
return rows.map((row) => row.thread_id);
}