Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

messageSearchIndex.ts

205 lines8.8 KB

1import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations";
2import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
3import * as Effect from "effect/Effect";
4import type * as SqlClient from "effect/sql/SqlClient";
5​
6// SQLite's ltrim needs the characters matched by isAttachmentOnlyBootstrapPrompt's \s explicitly.
7const BOOTSTRAP_PREFIX_WHITESPACE =
8 "\t\n\v\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff";
9​
10export const nonPlaceholderMessageCondition = (sql: SqlClient.SqlClient, row = "messages") =>
11 sql.literal(`
12 CASE
13 WHEN NOT json_valid(${row}.payload_json) THEN NULL
14 WHEN substr(json_extract(${row}.payload_json, '$.text'), 1, 11) = 'Ultrathink:' COLLATE NOCASE
15 THEN ltrim(substr(json_extract(${row}.payload_json, '$.text'), 12), '${BOOTSTRAP_PREFIX_WHITESPACE}')
16 ELSE json_extract(${row}.payload_json, '$.text')
17 END COLLATE BINARY <> '${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT.replaceAll("'", "''")}'
18`);
19​
20/**
21 * Exclude attachment placeholders, generated notices and subagent threads. ACP subagents
22 * rewrite their finished answer while it streams.
23 * Migration triggers, backfill, rebuild and scans share this predicate; `row` may be `new`.
24 */
25export const indexedMessageCondition = (sql: SqlClient.SqlClient, row = "messages") =>
26 sql`
27 ${sql.literal(`
28 ${row}.streaming = 0
29 AND json_valid(${row}.payload_json)
30 AND (
31 ${row}.role = 'assistant'
32 OR (
33 ${row}.role = 'user'
34 AND COALESCE(json_extract(${row}.payload_json, '$.createdBy'), 'user') = 'user'
35 )
36 )
37 AND NOT EXISTS (
38 SELECT 1 FROM orchestration_v2_projection_threads AS subagent_threads
39 WHERE subagent_threads.thread_id = ${row}.thread_id
40 AND json_valid(subagent_threads.payload_json)
41 AND json_extract(subagent_threads.payload_json, '$.lineage.relationshipToParent') = 'subagent'
42 )
43`)}
44 AND ${nonPlaceholderMessageCondition(sql, row)}
45`;
46​
47// Curly apostrophes straight, as search folds a query, since iOS keyboards
48// type "’" and others type "'".
49const foldApostrophes = (text: string) => `replace(replace(${text}, '’', ''''), '‘', '''')`;
50​
51const readableText = (row: string) =>
52 `COALESCE(${row}.search_text, json_extract(${row}.payload_json, '$.text'))`;
53​
54// A file mention stores `__init__.py` as `[\_\_init\_\_.py](...)`; the index
55// holds the label as it reads, so search can find the name as typed. As CommonMark allows, a label
56// may hold balanced brackets, an address balanced or escaped parentheses, or spaces inside <...>
57// (as file citations and image embeds write it), and either address may carry a "title".
58export const MARKDOWN_LINK =
59 /(!?\[)((?:[^[\]\n]|\[[^[\]\n]*\])*)(\]\((?:<(?:\\.|[^<>\\\n])*>|(?:\\\S|[^()\s\\]|\([^()\s]*\))*)(?:[ \t]+(?:"[^"\n]*"|'[^'\n]*'|\((?:\\.|[^()\\\n])*\)))?[ \t]*\))/g;
60​
61/**
62 * What search_text holds for a message: its text as it reads, a quote's
63 * percent-encoded link replaced by its words and comment. NULL when that is
64 * the stored text, so most messages store nothing extra.
65 */
66export const readableSearchText = (text: string) => {
67 const readable = assistantCitationsToPlainText(text).replace(
68 MARKDOWN_LINK,
69 (link, _open: string, label: string) => {
70 const decoded = label.replace(
71 /\\([\\*_~&])|&#9(1|3);/g,
72 (_match, escaped?: string, code?: string) => escaped ?? (code === "1" ? "[" : "]"),
73 );
74 return decoded === label ? link : decoded;
75 },
76 );
77 return readable === text ? null : readable;
78};
79​
80/** A message's text as it reads, for thread search. */
81export const messageSearchText = (sql: SqlClient.SqlClient) =>
82 sql.literal(readableText("messages"));
83​
84/** What the index stores for a message, so a scan matches the folded query as the index does. */
85export const foldedMessageSearchText = (sql: SqlClient.SqlClient, row = "messages") =>
86 sql.literal(foldApostrophes(readableText(row)));
87​
88/**
89 * A message's stored text with apostrophes folded, what the index held before
90 * migration 81. Migration 69's backfill uses it. `payload` is the message's
91 * JSON column.
92 */
93export const indexedMessageText = (sql: SqlClient.SqlClient, payload: string) =>
94 sql.literal(foldApostrophes(`json_extract(${payload}, '$.text')`));
95​
96// What the index stores: a message's readable text with apostrophes folded.
97// Migrations 69 and 74 create the triggers before migration 81 adds
98// search_text, and `t3 doctor` can rebuild a database that has not migrated,
99// so those fall back to the stored text.
100const indexedText = Effect.fn("MessageSearchIndex.indexedText")(function* (
101 sql: SqlClient.SqlClient,
102) {
103 const column = yield* sql`
104 SELECT 1 FROM pragma_table_info('orchestration_v2_projection_messages')
105 WHERE name = 'search_text'
106 `;
107 return column.length > 0
108 ? (row: string) => foldedMessageSearchText(sql, row)
109 : (row: string) => indexedMessageText(sql, `${row}.payload_json`);
110});
111​
112export const createMessageSearchTriggers = Effect.fn("MessageSearchIndex.createTriggers")(
113 function* (sql: SqlClient.SqlClient) {
114 const text = yield* indexedText(sql);
115 yield* sql`
116 CREATE TRIGGER orchestration_v2_message_search_insert
117 AFTER INSERT ON orchestration_v2_projection_messages
118 WHEN ${indexedMessageCondition(sql, "new")}
119 BEGIN
120 INSERT INTO orchestration_v2_message_search (rowid, text)
121 SELECT new.rowid, ${text("new")}
122 WHERE json_extract(new.payload_json, '$.text') IS NOT NULL;
123 END
124 `;
125 // Streaming deltas rewrite the row many times a second; skip them until the
126 // message settles. Upserts rewrite every column, so re-index only when what
127 // the index stores changed; migration 81's backfill writes only search_text.
128 // Deleting a rowid the index never held is a no-op.
129 yield* sql`
130 CREATE TRIGGER orchestration_v2_message_search_update
131 AFTER UPDATE ON orchestration_v2_projection_messages
132 WHEN (old.streaming = 0 OR new.streaming = 0)
133 AND (
134 old.streaming IS NOT new.streaming
135 OR old.role IS NOT new.role
136 OR NOT (json_valid(old.payload_json) AND json_valid(new.payload_json))
137 OR ${text("old")} IS NOT ${text("new")}
138 OR json_extract(old.payload_json, '$.createdBy')
139 IS NOT json_extract(new.payload_json, '$.createdBy')
140 )
141 BEGIN
142 DELETE FROM orchestration_v2_message_search WHERE rowid = old.rowid AND old.streaming = 0;
143 INSERT INTO orchestration_v2_message_search (rowid, text)
144 SELECT new.rowid, ${text("new")}
145 WHERE ${indexedMessageCondition(sql, "new")}
146 AND json_extract(new.payload_json, '$.text') IS NOT NULL;
147 END
148 `;
149 yield* sql`
150 CREATE TRIGGER orchestration_v2_message_search_delete
151 AFTER DELETE ON orchestration_v2_projection_messages
152 WHEN old.streaming = 0
153 BEGIN
154 DELETE FROM orchestration_v2_message_search WHERE rowid = old.rowid;
155 END
156 `;
157 },
158);
159​
160/** Replaces the search triggers with their current definition, where the index exists. */
161export const recreateMessageSearchTriggers = Effect.fn("MessageSearchIndex.recreateTriggers")(
162 function* (sql: SqlClient.SqlClient) {
163 const index = yield* sql`
164 SELECT 1 FROM sqlite_master WHERE name = 'orchestration_v2_message_search'
165 `;
166 if (index.length === 0) return;
167 yield* sql`DROP TRIGGER orchestration_v2_message_search_insert`;
168 yield* sql`DROP TRIGGER orchestration_v2_message_search_update`;
169 yield* sql`DROP TRIGGER orchestration_v2_message_search_delete`;
170 yield* createMessageSearchTriggers(sql);
171 },
172);
173​
174/**
175 * Refills the search index from the messages table. The index is keyed by
176 * message rowid, so anything that may renumber or copy rows (VACUUM, a dev
177 * database copy) rebuilds it instead of trusting it. Databases from before
178 * migration 69, or on an SQLite without FTS5 trigrams, have no index.
179 */
180export const rebuildMessageSearch = Effect.fn("MessageSearchIndex.rebuild")(function* (
181 sql: SqlClient.SqlClient,
182) {
183 const index = yield* sql`
184 SELECT 1 FROM sqlite_master WHERE name = 'orchestration_v2_message_search'
185 `;
186 if (index.length === 0) return;
187 const text = yield* indexedText(sql);
188 // One transaction: an interrupt between clear and refill would leave an
189 // empty index that nothing repairs, since search only checks the table exists.
190 yield* sql.withTransaction(
191 Effect.gen(function* () {
192 yield* sql`
193 INSERT INTO orchestration_v2_message_search (orchestration_v2_message_search)
194 VALUES ('delete-all')
195 `;
196 yield* sql`
197 INSERT INTO orchestration_v2_message_search (rowid, text)
198 SELECT messages.rowid, ${text("messages")}
199 FROM orchestration_v2_projection_messages AS messages
200 WHERE ${indexedMessageCondition(sql)}
201 AND json_extract(messages.payload_json, '$.text') IS NOT NULL
202 `;
203 }),
204 );
205});