From 35f7c4a4e40df7b1d031f89f134bc5bf2bf80218 Mon Sep 17 00:00:00 2001 From: dawn <90008@klbr.net> Date: Mon, 16 Nov 2026 13:50:56 +0300 Subject: [PATCH] search: narrow a cross-session query to sessions a trigram index says may hold it Signed-off-by: dawn <90008@klbr.net> --- robot-docs/agent-sessions.md | 13 ++ robot-docs/extensions.md | 18 +-- robot-docs/migrations.md | 14 +- src/albedo/daemon/conversation.gleam | 2 +- src/albedo/daemon/maintenance.gleam | 7 + src/albedo/daemon/migrations.gleam | 7 +- src/albedo/daemon/registry.gleam | 5 + src/albedo/daemon/transcript_text.gleam | 125 ++++++++++++++++++ src/albedo/daemon/transfer.gleam | 4 + .../harness/extensions/agents/sessions.gleam | 30 +++-- src/albedo/harness/sdk/capability.gleam | 2 + src/albedo/harness/sdk/search.gleam | 70 ++++++++++ test/daemon/transcript_text_test.gleam | 124 +++++++++++++++++ test/harness/extension_capability_test.gleam | 2 + test/harness/retrieval_performance_test.gleam | 30 +++++ 15 files changed, 426 insertions(+), 27 deletions(-) create mode 100644 src/albedo/daemon/transcript_text.gleam create mode 100644 test/daemon/transcript_text_test.gleam diff --git a/robot-docs/agent-sessions.md b/robot-docs/agent-sessions.md index 750a36325..8b55d4c68 100644 --- a/robot-docs/agent-sessions.md +++ b/robot-docs/agent-sessions.md @@ -59,6 +59,19 @@ through 100. See the [Python binding](../priv/python/albedo_plugins/agents.py) and [`agents/sessions.gleam`](../src/albedo/harness/extensions/agents/sessions.gleam). +A query reads the messages only of sessions that may hold it. The +[text index](../src/albedo/daemon/transcript_text.gleam) keeps the trigrams of +each row's text, lowercased, in an FTS5 table that stores no text and no +positions. `search.candidates` asks it for the rows holding every trigram of the +query and adds the rows it has not read yet, which wait in +`transcript_text_pending`. Waiting rows are indexed newest first, in store turns +bounded by rows and payload bytes: all of them by a drain the registry starts +when it opens, then those written since by each maintenance sweep, for up to two +seconds. Triggers on `transcript` send a rewritten row back to wait and drop a +deleted one, under any build, so the index only narrows a search and its results +are those of reading every message. A query shorter than three code points has +no trigram and reads every session. + `resources.query` reports process and session resource observations through the [Python binding](../priv/python/albedo_plugins/agents.py). Its host implementation is diff --git a/robot-docs/extensions.md b/robot-docs/extensions.md index ef89ed53c..925b23471 100644 --- a/robot-docs/extensions.md +++ b/robot-docs/extensions.md @@ -663,8 +663,8 @@ caller's own data. `capability.functions` lists them with the capability whose authority they grant. The rule for `Sessions` is that a function which answers the ID of a session other than one its caller passed in needs it: -- listings: `history.sessions`, `family.children`, `resources.recorded_kernels`, - `sessions.all`, and `mail.requested`; +- listings: `history.sessions`, `search.candidates`, `family.children`, + `resources.recorded_kernels`, `sessions.all`, and `mail.requested`; - a name resolved to an ID: `family.resolve`, `family.locate`, `family.remote`, and `sessions.find`; - a related session's ID: `family.get`, which names the parent, and @@ -675,12 +675,14 @@ the ID of a session other than one its caller passed in needs it: `sessions.occupied` answers no ID, but it tells whether any session works in a workspace, so it needs `Sessions` too. `family.set_role` and `family.set_verifier` change another session's family row, so they need -`SessionControl`. `mail.requested` is listed under `Mail` and `Sessions`, -because it reads a session's letters and answers their recipients. -`mail.statuses_in`, `queued_in`, `undelivered_in`, `delivered_in`, and `file_in` -read or file letters in the inbox, so they need `Inbox`, which posts them. A -function listed more than once needs every capability listed for it. These mail -functions also keep the session rule below. +`SessionControl`. `search.candidates` is listed under both `Sessions` and +`History`, because it finds other sessions by what their messages say. +`mail.requested` is listed under `Mail` and `Sessions`, because it reads a +session's letters and answers their recipients. `mail.statuses_in`, `queued_in`, +`undelivered_in`, `delivered_in`, and `file_in` read or file letters in the +inbox, so they need `Inbox`, which posts them. A function listed more than once +needs every capability listed for it. These mail functions also keep the session +rule below. Holding another session's ID, from a letter, a webhook, or a tool argument the model supplied, does not let an extension read that session's history. diff --git a/robot-docs/migrations.md b/robot-docs/migrations.md index cbd9f21a3..6aafcaf18 100644 --- a/robot-docs/migrations.md +++ b/robot-docs/migrations.md @@ -12,18 +12,19 @@ extension data migrations. `server.start` calls `registry.prepare_storage` before serving sessions. [Core migrations.run](../src/albedo/daemon/migrations.gleam) runs image storage, transcript classification, transcript row kinds, session profiles, prompts, -prompt context blocks, titles, usage-hour, waiting-input, and effort-name -upgrades in that order, each declared with its compatibility (see -[Downgrades](#downgrades)). Each result is checked, so an error stops the +prompt context blocks, titles, usage-hour, waiting-input, effort-name, and +transcript text upgrades in that order, each declared with its compatibility +(see [Downgrades](#downgrades)). Each result is checked, so an error stops the sequence. The waiting-input upgrade moves inputs from the retired `pending_inputs` table into the [inbox](inbox.md). [`effort_names`](../src/albedo/daemon/migrations/effort_names.gleam) renames sessions' saved `extra-low` effort to `minimal`, the name [`types.Effort`](../src/albedo/openai_api/types.gleam) gives Antigravity's lowest tier; [account migration](../src/albedo/harness/account_migration.gleam) -renames a profile's at each startup. Startup prints -`migration : rows` for each core, kernel, and extension migration -that rewrote rows. +renames a profile's at each startup. The transcript text upgrade creates the +[text index](agent-sessions.md#messages-and-resources) with every row waiting +for it. Startup prints `migration : rows` for each core, kernel, +and extension migration that rewrote rows. After the core upgrades, `prepare_storage` runs the kernel's [`cell_images`](../src/albedo/harness/kernel/migrations/cell_images.gleam) @@ -209,6 +210,7 @@ refusal protects only rollbacks to builds that include it. | `session_titles` | core | Additive | Sets `auto_title_attempted`, which every build with the column reads the same way. | | `usage_hours` | core | Additive | A new table, filled once and kept by a trigger on rows every build writes. | | `pending_inputs_inbox` | core | Breaking | Moves waiting inputs out of `pending_inputs`, and later inputs never go there. | +| `transcript_text` | core | Additive | A new index, kept by triggers on rows every build writes. | | `cell_images` | kernel | Breaking | Cell outputs keep references to images moved into `images`. | | `coding_lcm_name` | coding-lcm | Breaking | Renames the `lcm` extension in settings and session choices. | | `paperclips_title`, `paperclips_reply`, `paperclips_resolution`, `paperclips_revision` | paperclips | Additive | Defaulted columns. | diff --git a/src/albedo/daemon/conversation.gleam b/src/albedo/daemon/conversation.gleam index 843b2e8dd..1e8037a1a 100644 --- a/src/albedo/daemon/conversation.gleam +++ b/src/albedo/daemon/conversation.gleam @@ -3315,7 +3315,7 @@ fn record_usage_in( /// For rows read only for their text, inside the store (which a real reader /// would call back into). -fn unread(_hash: String) -> Result(String, Nil) { +pub fn unread(_hash: String) -> Result(String, Nil) { Error(Nil) } diff --git a/src/albedo/daemon/maintenance.gleam b/src/albedo/daemon/maintenance.gleam index 96fb3bb1c..bf4328f5b 100644 --- a/src/albedo/daemon/maintenance.gleam +++ b/src/albedo/daemon/maintenance.gleam @@ -15,6 +15,7 @@ import albedo/daemon/session import albedo/daemon/session_deletion import albedo/daemon/session_namespace import albedo/daemon/state_expiry +import albedo/daemon/transcript_text import albedo/harness/kernel as python import albedo/harness/runtime import albedo/harness/sdk/store @@ -80,9 +81,15 @@ pub fn run(sweep: Sweep) -> Nil { } False -> Nil } + let deadline = clock.monotonic_ms() + text_index_ms + transcript_text.drain(sweep.ledger, fn() { clock.monotonic_ms() < deadline }) host_memory.collect_idle() } +/// How long a sweep spends indexing the transcript rows written since the +/// last one. The backlog of a home from before the index drains at startup. +const text_index_ms = 2000 + /// Tool-output images older than the retention go the way compaction sends /// evicted ones; a session loaded right now keeps them until a later sweep. fn expire_images(sweep: Sweep) -> Nil { diff --git a/src/albedo/daemon/migrations.gleam b/src/albedo/daemon/migrations.gleam index f44943b77..8990d485d 100644 --- a/src/albedo/daemon/migrations.gleam +++ b/src/albedo/daemon/migrations.gleam @@ -10,6 +10,7 @@ import albedo/daemon/migrations/session_titles import albedo/daemon/migrations/transcript_classes import albedo/daemon/migrations/transcript_kinds import albedo/daemon/migrations/usage_hours +import albedo/daemon/transcript_text import albedo/harness/sdk/migration.{type Compatibility, Additive, Breaking} import albedo/harness/sdk/store import gleam/list @@ -35,8 +36,8 @@ pub const retired: List(String) = [] /// Upgrade image storage, classify transcript rows and record their kinds, /// note which profiles wrote each session's rows, move session prompts to /// their own table and store their context as blocks, move waiting inputs -/// into the inbox, then rename saved `extra-low` efforts to `minimal`. -/// Each step's compatibility says why. +/// into the inbox, rename saved `extra-low` efforts to `minimal`, then index +/// transcript text. Each step's compatibility says why. fn steps() -> List(Step) { [ // Rows keep references to images moved out of them. @@ -63,6 +64,8 @@ fn steps() -> List(Step) { Step("pending_inputs_inbox", Breaking, rowless(pending_inputs_inbox.run)), // Saved efforts are rewritten to a name older builds do not know. Step("effort_names", Breaking, rowless(effort_names.run)), + // A new index, kept by triggers on the rows every build writes. + Step("transcript_text", Additive, rowless(transcript_text.install)), ] } diff --git a/src/albedo/daemon/registry.gleam b/src/albedo/daemon/registry.gleam index 6ae4bcf33..6b7457aaa 100644 --- a/src/albedo/daemon/registry.gleam +++ b/src/albedo/daemon/registry.gleam @@ -39,6 +39,7 @@ import albedo/daemon/session_preferences import albedo/daemon/session_provider import albedo/daemon/state_expiry import albedo/daemon/terminals +import albedo/daemon/transcript_text import albedo/daemon/transfer as core_transfer import albedo/daemon/transfers import albedo/daemon/turn @@ -802,6 +803,10 @@ pub fn start( Open -> { let _ = clock.send_after(self, sweep_interval(config), Sweep) let _ = clock.send_after(self, config.tick_ms, ScheduleTick) + // The backlog of a home from before the text index. + process.spawn_unlinked(fn() { + transcript_text.drain(ledger, fn() { True }) + }) // Letters left from before a restart go out now, not a tick later. process.send(self, MailWaiting) // A parent idle on children the restart resumes waits on them. diff --git a/src/albedo/daemon/transcript_text.gleam b/src/albedo/daemon/transcript_text.gleam new file mode 100644 index 000000000..6441013bc --- /dev/null +++ b/src/albedo/daemon/transcript_text.gleam @@ -0,0 +1,125 @@ +//// A trigram index of each transcript row's text, so a search across +//// sessions reads only those that may hold its needle. Rows wait in +//// `transcript_text_pending` until the maintenance sweep indexes them, and +//// triggers send a row back there whenever its payload changes, under any +//// build, so the index never claims a row's text that it does not hold. + +import albedo/daemon/conversation +import albedo/harness/sdk/store +import albedo/harness/sdk/tool +import albedo/harness/sdk/transcript_codec as codec +import gleam/dynamic/decode +import gleam/io +import gleam/list +import gleam/result +import gleam/string +import sqlight + +/// The index holds only trigrams and the rows they occur in: no copy of the +/// text and no positions, which a candidate filter does not need. Merging +/// eight segments at a time rather than four cuts the backfill by about a +/// third, for a few percent more index. +const schema = + "CREATE VIRTUAL TABLE transcript_text USING fts5(text,tokenize='trigram',detail='none',content='',contentless_delete=1); +INSERT INTO transcript_text(transcript_text,rank) VALUES('automerge',8); +CREATE TABLE IF NOT EXISTS transcript_text_pending(seq INTEGER PRIMARY KEY); +INSERT INTO transcript_text_pending(seq) SELECT seq FROM transcript; +CREATE TRIGGER IF NOT EXISTS transcript_text_insert AFTER INSERT ON transcript BEGIN INSERT OR IGNORE INTO transcript_text_pending(seq) VALUES(NEW.seq); END; +CREATE TRIGGER IF NOT EXISTS transcript_text_update AFTER UPDATE OF payload ON transcript BEGIN DELETE FROM transcript_text WHERE rowid=OLD.seq; INSERT OR IGNORE INTO transcript_text_pending(seq) VALUES(NEW.seq); END; +CREATE TRIGGER IF NOT EXISTS transcript_text_delete AFTER DELETE ON transcript BEGIN DELETE FROM transcript_text WHERE rowid=OLD.seq; DELETE FROM transcript_text_pending WHERE seq=OLD.seq; END;" + +/// Creates the index with every existing row pending, once. The tables and +/// triggers go in one transaction, so an interrupted start does it again. +pub fn install(ledger: store.Store) -> Result(Nil, String) { + store.query(ledger, fn(db) { + store.transaction(db, fn() { + use installed <- result.try(store.one( + db, + "SELECT COUNT(*) FROM sqlite_master WHERE name='transcript_text'", + [], + decode.field(0, decode.int, decode.success), + "schema unreadable", + )) + case installed { + 0 -> store.exec(db, schema) + _ -> Ok(Nil) + } + }) + }) +} + +/// Indexes the text of pending rows, newest first, in one store turn, and +/// answers how many it indexed: up to `rows` of them, stopping before the +/// payloads read pass `bytes`, though a turn always takes one. A row that +/// does not decode is indexed as no text, as search reads it. A pending row +/// has no entry to replace, since the triggers drop it with the row's text. +pub fn index( + ledger: store.Store, + rows: Int, + bytes: Int, +) -> Result(Int, String) { + store.query(ledger, fn(db) { + store.transaction(db, fn() { + use pending <- result.try( + store.rows( + db, + "SELECT seq,payload FROM transcript WHERE seq IN (SELECT seq FROM (SELECT seq,size,SUM(size) OVER (ORDER BY seq DESC) AS through FROM (SELECT p.seq,length(t.payload) AS size FROM transcript_text_pending p JOIN transcript t ON t.seq=p.seq ORDER BY p.seq DESC LIMIT ?)) WHERE through-size Ok(0) + Ok(#(oldest, _)) -> { + let values = + list.flat_map(pending, fn(row) { + let text = + codec.unpack(row.1, conversation.unread) + |> result.map(tool.row_text) + |> result.unwrap("") + [sqlight.int(row.0), sqlight.text(string.lowercase(text))] + }) + use _ <- result.try(store.run( + db, + "INSERT INTO transcript_text(rowid,text) VALUES " + <> list.repeat("(?,?)", list.length(pending)) + |> string.join(","), + values, + )) + // The turn took every pending row from `oldest` on. + use _ <- result.map( + store.run(db, "DELETE FROM transcript_text_pending WHERE seq>=?", [ + sqlight.int(oldest), + ]), + ) + list.length(pending) + } + } + }) + }) +} + +/// Indexes pending rows one bounded turn after another while `more()` holds, +/// until none is left or the store closes. Each turn queues behind the writes +/// already waiting. +pub fn drain(ledger: store.Store, more: fn() -> Bool) -> Nil { + case index(ledger, turn_rows, turn_bytes) { + Ok(0) -> Nil + Ok(_) -> + case more() { + True -> drain(ledger, more) + False -> Nil + } + Error(error) -> io.println_error("transcript text index failed: " <> error) + } +} + +/// Rows and payload bytes per store turn: one turn holds the store for a +/// fraction of a second even when its rows are large. +const turn_rows = 256 + +const turn_bytes = 262_144 diff --git a/src/albedo/daemon/transfer.gleam b/src/albedo/daemon/transfer.gleam index 718b301bf..9aacb2aeb 100644 --- a/src/albedo/daemon/transfer.gleam +++ b/src/albedo/daemon/transfer.gleam @@ -172,6 +172,10 @@ pub fn adapter() -> transfer.Adapter { "transcript_links", "the transcript row from which this daemon records first_sent_by; the target keeps its own", ), + transfer.Excluded( + "transcript_text_pending", + "rows waiting for this home's text index; the target's triggers queue the rows it receives", + ), transfer.Excluded( "session_preferences_import", "a one-time marker of this home's preference import", diff --git a/src/albedo/harness/extensions/agents/sessions.gleam b/src/albedo/harness/extensions/agents/sessions.gleam index 043375176..7c9b2de20 100644 --- a/src/albedo/harness/extensions/agents/sessions.gleam +++ b/src/albedo/harness/extensions/agents/sessions.gleam @@ -6,7 +6,9 @@ import albedo/harness/sdk/search import albedo/harness/sdk/storage import gleam/bool import gleam/list +import gleam/option import gleam/result +import gleam/set import gleam/string /// One message row that contains the query, with the text around it. @@ -27,8 +29,9 @@ const hits_per_session = 3 /// opened in `cwd` ("" for all), most recently active first. A nonblank /// `query` keeps those whose title, given name, or family name contains it /// case-insensitively, and those whose messages do; sessions are searched in -/// order until the page is full. The caller's own messages are not searched: -/// they would always hold the query. +/// order until the page is full, skipping those the text index rules out. +/// The caller's own messages are not searched: they would always hold the +/// query. pub fn find( db: storage.Storage, caller: String, @@ -47,16 +50,23 @@ pub fn find( |> Ok _ -> { use needle <- result.try(search.needle(query)) - matching(db, caller, needle, listed, offset + limit, []) + use candidates <- result.try(search.candidates(db, needle)) + let searched = fn(session) { + session != caller + && option.map(candidates, set.contains(_, session)) + |> option.unwrap(True) + } + matching(db, searched, needle, listed, offset + limit, []) |> result.map(list.drop(_, offset)) } } } -/// The first `count` of `listed` whose names or messages hold `needle`. +/// The first `count` of `listed` whose names or messages hold `needle`, +/// reading the messages only of sessions `searched` keeps. fn matching( db: storage.Storage, - caller: String, + searched: fn(String) -> Bool, needle: String, listed: List(#(conversation.Info, String)), count: Int, @@ -64,13 +74,13 @@ fn matching( ) -> Result(List(Found), String) { case listed { [#(info, name), ..rest] if count > 0 -> { - use hits <- result.try(hits(db, caller, info.id, needle)) + use hits <- result.try(hits(db, searched, info.id, needle)) let named = string.contains(string.lowercase(info.title <> "\n" <> name), needle) case hits, named { - [], False -> matching(db, caller, needle, rest, count, found) + [], False -> matching(db, searched, needle, rest, count, found) _, _ -> - matching(db, caller, needle, rest, count - 1, [ + matching(db, searched, needle, rest, count - 1, [ Found(info, hits), ..found ]) @@ -82,11 +92,11 @@ fn matching( fn hits( db: storage.Storage, - caller: String, + searched: fn(String) -> Bool, session: String, needle: String, ) -> Result(List(Hit), String) { - use <- bool.guard(session == caller, Ok([])) + use <- bool.guard(!searched(session), Ok([])) use matches <- result.map(search.newest(db, session, needle, hits_per_session)) list.map(matches, fn(match) { Hit(match.seq, search.preview(match.text, needle)) diff --git a/src/albedo/harness/sdk/capability.gleam b/src/albedo/harness/sdk/capability.gleam index f8db4a48f..5f99d82ea 100644 --- a/src/albedo/harness/sdk/capability.gleam +++ b/src/albedo/harness/sdk/capability.gleam @@ -122,6 +122,8 @@ pub const fields = [ /// plain, so finding another session's ID takes one of these. pub const functions = [ #("albedo/harness/sdk/history", "sessions", Sessions), + #("albedo/harness/sdk/search", "candidates", Sessions), + #("albedo/harness/sdk/search", "candidates", History), #("albedo/harness/sdk/family", "children", Sessions), #("albedo/harness/sdk/family", "get", Sessions), #("albedo/harness/sdk/family", "started_by", Sessions), diff --git a/src/albedo/harness/sdk/search.gleam b/src/albedo/harness/sdk/search.gleam index 85bf37bf0..f8085ef28 100644 --- a/src/albedo/harness/sdk/search.gleam +++ b/src/albedo/harness/sdk/search.gleam @@ -18,6 +18,7 @@ import gleam/json import gleam/list import gleam/option.{type Option, None, Some} import gleam/result +import gleam/set.{type Set} import gleam/string import sqlight @@ -61,6 +62,75 @@ pub fn newest( |> result.map(list.reverse) } +/// The sessions that may hold a row whose text contains `needle`: those +/// with a row whose indexed text holds each of its trigrams, or a row the +/// index has not read yet. None when `needle` is shorter than a trigram, +/// which the index cannot look up, or when more than `candidate_rows` rows +/// may hold it, since walking the sessions fills a page sooner than +/// gathering that many. +pub fn candidates( + ledger: storage.Storage, + needle: String, +) -> Result(Option(Set(String)), String) { + use _ <- result.try(storage.permit( + ledger, + "albedo/harness/sdk/search", + "candidates", + )) + case list.unique(trigrams(string.to_utf_codepoints(needle))) { + [] -> Ok(None) + trigrams -> { + let query = + list.map(trigrams, fn(trigram) { + "\"" <> string.replace(trigram, "\"", "\"\"") <> "\"" + }) + |> string.join(" AND ") + use count <- result.try(storage.read( + ledger, + "SELECT COUNT(*) FROM (" <> candidate_rows_sql <> " LIMIT ?)", + [sqlight.text(query), sqlight.int(candidate_rows + 1)], + decode.field(0, decode.int, decode.success), + )) + case count { + [count] if count <= candidate_rows -> + storage.read( + ledger, + // The session index is smaller than the rows it would otherwise + // look up one by one. + "SELECT DISTINCT session FROM transcript INDEXED BY transcript_session WHERE seq IN (" + <> candidate_rows_sql + <> ")", + [sqlight.text(query)], + decode.field(0, decode.string, decode.success), + ) + |> result.map(fn(sessions) { Some(set.from_list(sessions)) }) + _ -> Ok(None) + } + } + } +} + +const candidate_rows = 50_000 + +const candidate_rows_sql = + "SELECT rowid FROM transcript_text WHERE transcript_text MATCH ? UNION ALL SELECT seq FROM transcript_text_pending" + +/// Each run of three code points in `points`, as the trigram tokenizer +/// splits text. +fn trigrams(points: List(UtfCodepoint)) -> List(String) { + case points { + [first, ..rest] -> + case rest { + [second, third, ..] -> [ + string.from_utf_codepoints([first, second, third]), + ..trigrams(rest) + ] + _ -> [] + } + [] -> [] + } +} + type Scan(a) { Scan( ledger: storage.Storage, diff --git a/test/daemon/transcript_text_test.gleam b/test/daemon/transcript_text_test.gleam new file mode 100644 index 000000000..14c231110 --- /dev/null +++ b/test/daemon/transcript_text_test.gleam @@ -0,0 +1,124 @@ +//// The text index may only narrow a search: every session with a row whose +//// text holds the needle stays a candidate however rows are written, +//// rewritten, indexed, or removed. + +import albedo/daemon/conversation +import albedo/daemon/transcript_text +import albedo/harness/runtime +import albedo/harness/sdk/search +import albedo/harness/sdk/session_info +import albedo/harness/sdk/storage +import albedo/harness/sdk/store +import albedo/harness/sdk/transcript_codec +import albedo/openai_api/types +import gleam/dynamic/decode +import gleam/list +import gleam/option.{type Option, None, Some} +import gleam/set +import gleam/string +import gleeunit/should +import sqlight + +pub fn the_index_narrows_a_search_without_losing_a_match_test() -> Nil { + let #(host, ledger) = fixture() + insert(ledger, "a", 1, "pushed to GIT.KLBR.NET just now") + insert(ledger, "b", 2, "nothing to see") + let assert Ok(_) = transcript_text.install(ledger) + // Rows from before the index wait for it, so every session stays a + // candidate. + candidates(ledger, "git.klbr.net") |> should.equal(Some(["a", "b"])) + transcript_text.drain(ledger, fn() { True }) + candidates(ledger, "git.klbr.net") |> should.equal(Some(["a"])) + candidates(ledger, "never said") |> should.equal(Some([])) + // A needle shorter than a trigram cannot be looked up. + candidates(ledger, "<3") |> should.equal(None) + + // Rows written later wait until they are indexed. A turn over its byte + // budget still indexes its newest row, and leaves the rest waiting. + insert(ledger, "b", 3, "an older git.klbr.net mention") + insert(ledger, "c", 5, "Café ÜNÏCODE") + candidates(ledger, "ünï") |> should.equal(Some(["b", "c"])) + transcript_text.index(ledger, 256, 1) |> should.equal(Ok(1)) + candidates(ledger, "ünï") |> should.equal(Some(["b", "c"])) + candidates(ledger, "git.klbr.net") |> should.equal(Some(["a", "b"])) + let assert Ok(_) = + store.write(ledger, "DELETE FROM transcript WHERE seq=3", []) + transcript_text.drain(ledger, fn() { True }) + candidates(ledger, "café ünï") |> should.equal(Some(["c"])) + + // A rewritten row is read again, under any build: the trigger, not the + // writer, sends it back. + let assert Ok(_) = + store.write(ledger, "UPDATE transcript SET payload=? WHERE seq=2", [ + sqlight.blob(transcript_codec.pack(types.User("now git.klbr.net too"))), + ]) + candidates(ledger, "git.klbr.net") |> should.equal(Some(["a", "b"])) + transcript_text.drain(ledger, fn() { True }) + candidates(ledger, "git.klbr.net") |> should.equal(Some(["a", "b"])) + candidates(ledger, "nothing to see") |> should.equal(Some([])) + + // A removed row leaves the index, and so does one still waiting for it. + insert(ledger, "a", 4, "git.klbr.net again") + let assert Ok(_) = + store.write(ledger, "DELETE FROM transcript WHERE seq IN (1,4)", []) + candidates(ledger, "git.klbr.net") |> should.equal(Some(["b"])) + let assert Ok(left) = + store.query(ledger, fn(db) { + store.rows( + db, + "SELECT rowid FROM transcript_text WHERE transcript_text MATCH '\"klb\"' UNION ALL SELECT seq FROM transcript_text_pending", + [], + decode.field(0, decode.int, decode.success), + ) + }) + left |> should.equal([2]) + runtime.stop(host) +} + +fn fixture() -> #(runtime.Runtime, store.Store) { + let assert Ok(host) = runtime.start_with_extensions(":memory:", []) + let ledger = runtime.ledger(host) + let assert Ok(_) = conversation.initialise(ledger) + list.each(["a", "b", "c"], fn(session) { + let assert Ok(_) = + conversation.create( + ledger, + session_info.Info( + session, + "fixture", + "/tmp", + "fixture", + "fixture", + types.Responses, + session_info.Idle, + None, + None, + False, + None, + ), + ) + }) + #(host, ledger) +} + +fn insert(ledger: store.Store, session: String, seq: Int, text: String) -> Nil { + let assert Ok(_) = + store.write( + ledger, + "INSERT INTO transcript(seq,session,payload,row_class) VALUES(?,?,?,'user')", + [ + sqlight.int(seq), + sqlight.text(session), + sqlight.blob(transcript_codec.pack(types.User(text))), + ], + ) + Nil +} + +fn candidates(ledger: store.Store, pattern: String) -> Option(List(String)) { + let assert Ok(needle) = search.needle(pattern) + let assert Ok(found) = search.candidates(storage.host(ledger), needle) + option.map(found, fn(sessions) { + set.to_list(sessions) |> list.sort(string.compare) + }) +} diff --git a/test/harness/extension_capability_test.gleam b/test/harness/extension_capability_test.gleam index 768dc9eb3..7877098ec 100644 --- a/test/harness/extension_capability_test.gleam +++ b/test/harness/extension_capability_test.gleam @@ -8,6 +8,7 @@ import albedo/daemon/conversation import albedo/daemon/mail import albedo/daemon/moves +import albedo/daemon/transcript_text import albedo/harness/extension/composition import albedo/harness/extensions/agents/sessions as agent_sessions import albedo/harness/extensions/lcm/graph @@ -1277,6 +1278,7 @@ pub fn every_state_operation_is_classified_test() -> Nil { pub fn searching_every_session_needs_sessions_and_history_test() -> Nil { let ledger = history_ledger() let assert Ok(_) = family.initialise(storage.host(ledger)) + let assert Ok(_) = transcript_text.install(ledger) let find = fn(handle) { agent_sessions.find(handle, "own", "needle", "", 0, 100) |> result.map( diff --git a/test/harness/retrieval_performance_test.gleam b/test/harness/retrieval_performance_test.gleam index 89673d3cc..2f5615b59 100644 --- a/test/harness/retrieval_performance_test.gleam +++ b/test/harness/retrieval_performance_test.gleam @@ -4,6 +4,7 @@ import albedo/harness/sdk/session_info import albedo/daemon/conversation +import albedo/daemon/transcript_text import albedo/harness/extensions/agents/sessions import albedo/harness/extensions/lcm/graph import albedo/harness/runtime @@ -42,6 +43,7 @@ fn fixture() -> #(runtime.Runtime, store.Store) { let assert Ok(_) = conversation.initialise(ledger) let assert Ok(_) = graph.initialise(lcm_storage(ledger)) let assert Ok(_) = family.initialise(storage.host(ledger)) + let assert Ok(_) = transcript_text.install(ledger) let _ = list.each(["wanted", "other"], fn(session) { let assert Ok(_) = @@ -218,6 +220,34 @@ pub fn session_search_stops_once_the_page_is_full_test() -> Nil { runtime.stop(host) } +pub fn an_indexed_search_reads_only_sessions_that_may_match_test() -> Nil { + let #(host, ledger) = fixture() + let _ = + list.each( + list.index_map(list.repeat(Nil, 2200), fn(_, index) { index + 1 }), + fn(seq) { insert(ledger, "wanted", seq, "chatter") }, + ) + insert(ledger, "other", 2201, "pushed to git.klbr.net") + let found = fn() { + measure(store.owner(ledger), fn() { + sessions.find(storage.host(ledger), "caller", "git.klbr.net", "", 0, 5) + }) + } + // Unindexed rows are read as before: both sessions, the busy one in two + // pages. + let #(result, counts) = found() + let assert Ok([sessions.Found(info, [hit])]) = result + #(info.id, hit.seq) |> should.equal(#("other", 2201)) + counts.pages |> should.equal(3) + transcript_text.drain(ledger, fn() { True }) + let #(result, counts) = found() + let assert Ok([sessions.Found(info, [hit])]) = result + #(info.id, hit.seq) |> should.equal(#("other", 2201)) + counts.pages |> should.equal(1) + counts.decoded |> should.equal(1) + runtime.stop(host) +} + /// LCM's own handle on `ledger`, as its owner lcm-memory receives it. fn lcm_storage(ledger: store.Store) -> storage.Storage { storage.new(ledger, "lcm-memory", graph.tables) -- knotmirror 0.0.1