diff --git a/apps/admin_console/database/repositories/annotation_repository.py b/apps/admin_console/database/repositories/annotation_repository.py index 3f398bd4b..aa4aa2be4 100644 --- a/apps/admin_console/database/repositories/annotation_repository.py +++ b/apps/admin_console/database/repositories/annotation_repository.py @@ -12,13 +12,16 @@ from contextlib import closing from dataclasses import dataclass from pathlib import Path +import logging import sqlite3 import time import uuid from apps.admin_console.core import config from apps.admin_console.core.access_control import AdminAPIError -from artemis.data_engine import schema_revisions +from artemis.data_engine import run_catalog, schema_revisions + +logger = logging.getLogger(__name__) MODULE = "notes" DOCS = "https://github.com/cheese-work/artemis/blob/main/docs/board-api.md" @@ -111,7 +114,7 @@ class Comment: def migrate(db_path: str | Path) -> schema_revisions.RevisionReport: - """Apply pending ``notes`` revisions, then drop notes whose run is gone. + """Apply pending ``notes`` revisions, drop notes whose run is gone, then index note text. The previous binary deletes whole runs without knowing these tables; the next upgrade finishes that deletion (docs/board-operations.md, "Rollback"). @@ -122,6 +125,10 @@ def migrate(db_path: str | Path) -> schema_revisions.RevisionReport: conn.execute( f"DELETE FROM {table} WHERE session_id NOT IN (SELECT session_id FROM sessions)" ) + try: + run_catalog.migrate_notes(db_path) # note text joins the run search index + except sqlite3.Error: + logger.exception("Run search could not index notes for %s", db_path) return report diff --git a/apps/admin_console/database/repositories/run_catalog_repository.py b/apps/admin_console/database/repositories/run_catalog_repository.py index 59797d41f..bfba5dbda 100644 --- a/apps/admin_console/database/repositories/run_catalog_repository.py +++ b/apps/admin_console/database/repositories/run_catalog_repository.py @@ -314,6 +314,38 @@ def list_runs( ) return RunPage(runs, next_cursor, warnings, total) + def note_texts(self, session_ids: list[str]) -> dict[str, list[tuple[str, str]]]: + """``(field, body)`` comments and annotations per run, newest first. + + Only for runs the caller already passed through the visibility join; the + search index is never the source of a snippet. + """ + found: dict[str, list[tuple[str, str]]] = {} + if not session_ids: + return found + marks = ", ".join("?" for _ in session_ids) + with db_session(self.db_path) as conn: + tables = [ + (field, table) + for field, table in (("comment", "run_comments"), ("annotation", "run_annotations")) + if conn.execute( + "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?", (table,) + ).fetchone() + ] + if not tables: + return found + union = " UNION ALL ".join( + f"SELECT '{field}' AS field, session_id, body, created_at FROM {table} " + f"WHERE session_id IN ({marks})" + for field, table in tables + ) + rows = conn.execute( + f"{union} ORDER BY created_at DESC", session_ids * len(tables) + ).fetchall() + for row in rows: + found.setdefault(row["session_id"], []).append((row["field"], row["body"])) + return found + def get_run(self, session_id: str, *, prefix_owners: list[str] | None = None) -> RunLookup: """Resolve a full id or owner-filtered prefix, including the tombstone decision.""" session_id = run_catalog.validate_session_id(session_id, base_dir=self.traces_dir) diff --git a/apps/admin_console/routers/runs.py b/apps/admin_console/routers/runs.py index 528ae1739..00ebc11e6 100644 --- a/apps/admin_console/routers/runs.py +++ b/apps/admin_console/routers/runs.py @@ -170,6 +170,16 @@ async def list_runs( # Built from the presented page: visible runs only, prompt already redacted. for run in runs: run["snippet"] = run_catalog.search_snippet(run, q) + # A run found only by its notes: read them now, for these visible runs alone. + unmatched = [run for run in runs if run["snippet"] is None] + notes = await asyncio.to_thread( + run_catalog_repo.note_texts, [run["session_id"] for run in unmatched] + ) + for run in unmatched: + bodies = notes.get(run["session_id"], []) + if run["read_only"]: + bodies = [(name, redact_text(redact_image_data(body))) for name, body in bodies] + run["snippet"] = run_catalog.note_snippet(bodies, q) return { "runs": runs, "next_cursor": page.next_cursor, diff --git a/artemis/data_engine/run_catalog.py b/artemis/data_engine/run_catalog.py index af716b3cd..9f4386f5c 100644 --- a/artemis/data_engine/run_catalog.py +++ b/artemis/data_engine/run_catalog.py @@ -50,6 +50,11 @@ "run_catalog_meta_ad", ) _TRIGGERS_PLAIN = ("run_catalog_sessions_ai", "run_catalog_sessions_ad") +NOTES_MODULE = "run_catalog_notes" +_NOTES_TABLES = ("run_comments", "run_annotations") +_TRIGGERS_NOTES = tuple( + f"run_catalog_{table}_{event}" for table in _NOTES_TABLES for event in ("ai", "au", "ad") +) _TABLES_DDL = ( """ @@ -104,7 +109,7 @@ FTS_MODULE = "run_catalog_fts" FTS_RANK_COLUMNS = ( "(highlight(runs_fts, 0, char(1), char(2)) = runs_fts.prompt) AS goal_miss, " - "bm25(runs_fts, 10.0, 1.0) AS score, -m.rid AS sort_rid" + "bm25(runs_fts, 10.0, 1.0, 1.0) AS score, -m.rid AS sort_rid" ) FTS_RANK_ORDER = "goal_miss, score, sort_rid" @@ -117,19 +122,43 @@ def _device_ref_sql(column: str) -> str: ) -def _refresh(session_id: str, meta_text: str) -> str: +def _notes_text() -> str: + """Comment and annotation bodies of the run ``m`` (a ``run_meta`` row in scope).""" + return ( + "coalesce((SELECT group_concat(body, char(10)) FROM (" + "SELECT body FROM run_comments WHERE session_id = m.session_id " + "UNION ALL SELECT body FROM run_annotations WHERE session_id = m.session_id)), '')" + ) + + +def _index_row(meta_text: str, *, notes_col: bool, notes_text: bool) -> tuple[str, str]: + """Column list and select list of one ``runs_fts`` row (notes text only when installed).""" + if not notes_col: + return "rowid, prompt, meta", f"m.rid, coalesce(s.initial_goal, ''), {meta_text}" + notes = _notes_text() if notes_text else "''" + return ( + "rowid, prompt, meta, notes", + f"m.rid, coalesce(s.initial_goal, ''), {meta_text}, {notes}", + ) + + +def _refresh( + session_id: str, meta_text: str, *, notes_col: bool = False, notes_text: bool = False +) -> str: """Re-index one session; tombstoned or deleted runs end up out of the index.""" + columns, select = _index_row(meta_text, notes_col=notes_col, notes_text=notes_text) return ( f"DELETE FROM runs_fts WHERE rowid IN " f"(SELECT rid FROM run_meta WHERE session_id = {session_id}); " - f"INSERT INTO runs_fts (rowid, prompt, meta) " - f"SELECT m.rid, coalesce(s.initial_goal, ''), {meta_text} " + f"INSERT INTO runs_fts ({columns}) SELECT {select} " f"FROM run_meta m JOIN sessions s ON s.session_id = m.session_id " f"WHERE m.session_id = {session_id} AND m.deleted_at IS NULL;" ) -def _trigger_ddl(fts: bool, *, snapshots: bool = False) -> list[str]: +def _trigger_ddl( + fts: bool, *, snapshots: bool = False, notes_col: bool = False, notes_text: bool = False +) -> list[str]: # Not INSERT OR IGNORE: an outer INSERT OR REPLACE on sessions overrides the # conflict clause of statements inside a trigger and would replace run_meta. create_meta = ( @@ -142,8 +171,11 @@ def _trigger_ddl(fts: bool, *, snapshots: bool = False) -> list[str]: f"deleted_reason = coalesce(deleted_reason, 'session_deleted') " f"WHERE session_id = old.session_id;" ) + meta_text = META_TEXT if snapshots else _LEGACY_META_TEXT refresh = ( - _refresh("new.session_id", META_TEXT if snapshots else _LEGACY_META_TEXT) if fts else "" + _refresh("new.session_id", meta_text, notes_col=notes_col, notes_text=notes_text) + if fts + else "" ) ddl = [ "CREATE TRIGGER IF NOT EXISTS run_catalog_sessions_ai AFTER INSERT ON sessions BEGIN " @@ -175,25 +207,59 @@ def _trigger_ddl(fts: bool, *, snapshots: bool = False) -> list[str]: "CREATE TRIGGER IF NOT EXISTS run_catalog_meta_ad AFTER DELETE ON run_meta BEGIN " "DELETE FROM runs_fts WHERE rowid = old.rid; END", ] + if fts and notes_text: + # A run's note text is part of its index row, so any change to a note re-indexes the run. + for table in _NOTES_TABLES: + ddl += [ + f"CREATE TRIGGER IF NOT EXISTS run_catalog_{table}_ai AFTER INSERT ON {table} " + f"BEGIN {refresh} END", + f"CREATE TRIGGER IF NOT EXISTS run_catalog_{table}_au " + f"AFTER UPDATE OF body, session_id ON {table} BEGIN {refresh} END", + f"CREATE TRIGGER IF NOT EXISTS run_catalog_{table}_ad AFTER DELETE ON {table} " + f"BEGIN {_refresh('old.session_id', meta_text, notes_col=True, notes_text=True)} END", + ] return ddl -def _rebuild_ddl(meta_text: str) -> tuple[str, str]: +def _rebuild_ddl( + meta_text: str, *, notes_col: bool = False, notes_text: bool = False +) -> tuple[str, str]: + columns, select = _index_row(meta_text, notes_col=notes_col, notes_text=notes_text) return ( "DELETE FROM runs_fts", - f"INSERT INTO runs_fts (rowid, prompt, meta) " - f"SELECT m.rid, coalesce(s.initial_goal, ''), {meta_text} " + f"INSERT INTO runs_fts ({columns}) SELECT {select} " f"FROM run_meta m JOIN sessions s ON s.session_id = m.session_id " f"WHERE m.deleted_at IS NULL", ) +_DROP_FTS_TRIGGERS = tuple(f"DROP TRIGGER IF EXISTS {name}" for name in _TRIGGERS_FTS) +_DROP_NOTES_TRIGGERS = tuple(f"DROP TRIGGER IF EXISTS {name}" for name in _TRIGGERS_NOTES) + FTS_REVISIONS = ( ( - *(f"DROP TRIGGER IF EXISTS {name}" for name in _TRIGGERS_FTS), + *_DROP_FTS_TRIGGERS, *_trigger_ddl(fts=True, snapshots=True), *_rebuild_ddl(META_TEXT), ), + # FTS5 has no ADD COLUMN: recreate the index with a ``notes`` column (filled by NOTES_REVISIONS). + ( + *_DROP_FTS_TRIGGERS, + "DROP TABLE runs_fts", + "CREATE VIRTUAL TABLE runs_fts USING fts5(prompt, meta, notes)", + *_trigger_ddl(fts=True, snapshots=True, notes_col=True), + *_rebuild_ddl(META_TEXT, notes_col=True), + ), +) + +# Applied by ``migrate_notes`` once both the index column and the notes tables exist. +NOTES_REVISIONS = ( + ( + *_DROP_FTS_TRIGGERS, + *_DROP_NOTES_TRIGGERS, + *_trigger_ddl(fts=True, snapshots=True, notes_col=True, notes_text=True), + *_rebuild_ddl(META_TEXT, notes_col=True, notes_text=True), + ), ) @@ -232,8 +298,29 @@ def _snapshot_index_installed(conn: sqlite3.Connection) -> bool: ) +def _fts_columns(conn: sqlite3.Connection) -> set[str]: + return {row[1] for row in conn.execute("PRAGMA table_info(runs_fts)")} + + +def _notes_index_installed(conn: sqlite3.Connection) -> bool: + return ( + search_mode(conn) == "fts" + and "notes" in _fts_columns(conn) + and all(_has(conn, "table", table) for table in _NOTES_TABLES) + and _has(conn, "table", "schema_revisions") + and conn.execute( + "SELECT 1 FROM schema_revisions WHERE module = ? AND revision >= 1", (NOTES_MODULE,) + ).fetchone() + is not None + ) + + def _complete(conn: sqlite3.Connection, fts: bool) -> bool: wanted = _TRIGGERS_FTS if fts else _TRIGGERS_PLAIN + if fts and _notes_index_installed(conn): + wanted += _TRIGGERS_NOTES + if not fts and any(_has(conn, "trigger", name) for name in _TRIGGERS_NOTES): + return False # note triggers need runs_fts return ( _has(conn, "table", "run_meta") and _has(conn, "table", "run_link_shares") @@ -242,6 +329,15 @@ def _complete(conn: sqlite3.Connection, fts: bool) -> bool: ) +def _index_flags(conn: sqlite3.Connection, *, snapshots: bool) -> dict[str, bool]: + notes_col = search_mode(conn) == "fts" and "notes" in _fts_columns(conn) + return { + "snapshots": snapshots, + "notes_col": notes_col, + "notes_text": notes_col and _notes_index_installed(conn), + } + + def ensure_schema(conn: sqlite3.Connection) -> bool: """Idempotent: tables, index, triggers. False when there is no sessions table yet. @@ -266,12 +362,12 @@ def ensure_schema(conn: sqlite3.Connection) -> bool: conn.execute(statement) promoting = fts and not _has(conn, "table", "runs_fts") if promoting: - conn.execute("CREATE VIRTUAL TABLE runs_fts USING fts5(prompt, meta)") + conn.execute("CREATE VIRTUAL TABLE runs_fts USING fts5(prompt, meta, notes)") # Replace, never keep: triggers from a substring-mode install lack the index upkeep. - for name in dict.fromkeys(_TRIGGERS_FTS + _TRIGGERS_PLAIN): + for name in dict.fromkeys(_TRIGGERS_FTS + _TRIGGERS_PLAIN + _TRIGGERS_NOTES): conn.execute(f"DROP TRIGGER IF EXISTS {name}") snapshots = fts and _snapshot_index_installed(conn) and _has_snapshot_columns(conn) - for statement in _trigger_ddl(fts, snapshots=snapshots): + for statement in _trigger_ddl(fts, **_index_flags(conn, snapshots=snapshots)): conn.execute(statement) if promoting: rebuild(conn) # index the runs created while search was substring-only @@ -299,7 +395,12 @@ def rebuild(conn: sqlite3.Connection) -> int: if search_mode(conn) != "fts": return 0 snapshots = _snapshot_index_installed(conn) and _has_snapshot_columns(conn) - delete, insert = _rebuild_ddl(META_TEXT if snapshots else _LEGACY_META_TEXT) + flags = _index_flags(conn, snapshots=snapshots) + delete, insert = _rebuild_ddl( + META_TEXT if snapshots else _LEGACY_META_TEXT, + notes_col=flags["notes_col"], + notes_text=flags["notes_text"], + ) conn.execute(delete) cursor = conn.execute(insert) conn.commit() @@ -364,6 +465,24 @@ def _migrate_search(conn: sqlite3.Connection, db_path: str | Path) -> Path | Non return None +def migrate_notes(db_path: str | Path) -> schema_revisions.RevisionReport: + """Index comment and annotation text, once the index column and both notes tables exist. + + Called after the notes tables are created. Idempotent; a database without FTS5 (or + without the snapshot index) is left on the substring fallback, which does not search notes. + """ + with closing(sqlite3.connect(db_path, timeout=30.0)) as conn: + ready = ( + search_mode(conn) == "fts" + and "notes" in _fts_columns(conn) + and _has_snapshot_columns(conn) + and all(_has(conn, "table", table) for table in _NOTES_TABLES) + ) + if not ready: + return schema_revisions.RevisionReport((), None) + return schema_revisions.apply(db_path, NOTES_MODULE, NOTES_REVISIONS) + + # -- search ------------------------------------------------------------------- _TERM = re.compile(r"[^\W_]+") @@ -414,7 +533,7 @@ def search_snippet(run: dict[str, Any], text: str) -> dict[str, str] | None: never from the index, so it cannot expose a hidden run or unredacted goal text. Fields are tried in search priority order; the first one holding any term wins. """ - terms = [t.casefold() for t in _TERM.findall(text)][:_MAX_TERMS] + terms = _fold_terms(text) device = run.get("device_ref") fields = ( ("prompt", run.get("prompt")), @@ -429,21 +548,37 @@ def search_snippet(run: dict[str, Any], text: str) -> dict[str, str] | None: ("host_id", run.get("host_id")), ) for name, value in fields: - if not isinstance(value, str): - continue - hits = [i for t in terms if (i := value.casefold().find(t)) >= 0] - if hits: - start = max(0, min(hits) - _SNIPPET_RADIUS) - end = min(len(value), min(hits) + _SNIPPET_RADIUS) - return { - "field": name, - "text": ("…" if start else "") - + value[start:end] - + ("…" if end < len(value) else ""), - } + if isinstance(value, str) and (window := _window(value, terms)) is not None: + return {"field": name, "text": window} + return None + + +def note_snippet(notes: list[tuple[str, str]], text: str) -> dict[str, str] | None: + """First ``(field, body)`` note holding a search term, as a snippet. + + ``notes`` are the already-visible run's comments and annotations, newest first, + already redacted when the viewer is read-only; the field is ``comment`` or ``annotation``. + """ + terms = _fold_terms(text) + for name, body in notes: + if (window := _window(body, terms)) is not None: + return {"field": name, "text": window} return None +def _fold_terms(text: str) -> list[str]: + return [t.casefold() for t in _TERM.findall(text)][:_MAX_TERMS] + + +def _window(value: str, terms: list[str]) -> str | None: + hits = [i for t in terms if (i := value.casefold().find(t)) >= 0] + if not hits: + return None + start = max(0, min(hits) - _SNIPPET_RADIUS) + end = min(len(value), min(hits) + _SNIPPET_RADIUS) + return ("…" if start else "") + value[start:end] + ("…" if end < len(value) else "") + + def search_session_ids(conn: sqlite3.Connection, text: str) -> list[str]: """Live (not tombstoned) session ids matching ``text``, by FTS or substring.""" if search_mode(conn) == "fts": diff --git a/tests/unit/admin_console/test_run_annotations.py b/tests/unit/admin_console/test_run_annotations.py index 534ad2464..c321f9ea2 100644 --- a/tests/unit/admin_console/test_run_annotations.py +++ b/tests/unit/admin_console/test_run_annotations.py @@ -321,7 +321,9 @@ def test_migration_is_additive_and_records_its_revision(library): second = notes.migrate(library.db) after = _schema(library.db) - assert {name: after[name] for name in before} == before # nothing existing changed + # Nothing existing changed, except the catalog triggers that now also index note text. + changed = {name for name in before if after[name] != before[name]} + assert changed <= {name for name in before if name.startswith("run_catalog_")} assert {"schema_revisions", "run_annotations", "evidence_tombstones"} <= set(after) with sqlite3.connect(library.db) as conn: assert conn.execute( diff --git a/tests/unit/admin_console/test_run_comments.py b/tests/unit/admin_console/test_run_comments.py index ae1a35f80..087f2169f 100644 --- a/tests/unit/admin_console/test_run_comments.py +++ b/tests/unit/admin_console/test_run_comments.py @@ -39,7 +39,9 @@ def test_upgrade_from_revision_one_preserves_notes_for_the_old_reader(library): with closing(sqlite3.connect(library.db)) as conn: new_schema = dict(conn.execute("SELECT name, sql FROM sqlite_master")) - assert {name: new_schema[name] for name in old_schema} == old_schema + # Only the catalog triggers change: they now also index note text (CHE-1478). + changed = {name for name in old_schema if new_schema[name] != old_schema[name]} + assert changed <= {name for name in old_schema if name.startswith("run_catalog_")} assert conn.execute( "SELECT revision FROM schema_revisions WHERE module = 'notes'" ).fetchone() == (2,) diff --git a/tests/unit/admin_console/test_run_notes_search.py b/tests/unit/admin_console/test_run_notes_search.py new file mode 100644 index 000000000..df080ee07 --- /dev/null +++ b/tests/unit/admin_console/test_run_notes_search.py @@ -0,0 +1,242 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Run search over comment and annotation text (CHE-1478). + +The catalog index (`runs_fts.notes`) is kept current by triggers on the notes tables, so the +comment and annotation routes need no change. Snippets are built after the visibility join. +""" + +from contextlib import closing +import sqlite3 + +import pytest + +from apps.admin_console.database.repositories import annotation_repository as notes +from artemis.data_engine import run_catalog, schema_revisions + +AUTHOR = "prn_dev" +QA = "qa@example.com" + + +def _own(library, goal="plain goal", owner=QA, **kwargs) -> str: + run = library.seed(goal, **kwargs) + with sqlite3.connect(library.db) as conn: + conn.execute("UPDATE run_meta SET requested_by = ? WHERE session_id = ?", (owner, run)) + return run + + +def _comment(library, run, body): + with closing(sqlite3.connect(library.db)) as conn: + return notes.add_comment(conn, run, body, AUTHOR) + + +def _annotate(library, run, body): + step = library.step(run, 1) + with closing(sqlite3.connect(library.db)) as conn: + return notes.add_annotation( + conn, run, notes.StepAnchor(step), body=body, author_principal_id=AUTHOR + ) + + +def _sql(library, statement, *params): + with sqlite3.connect(library.db) as conn: + conn.execute(statement, params) + + +async def _search(qa, term, scope="mine"): + response = await qa.get("/api/runs", params={"q": term, "scope": scope}) + assert response.status_code == 200, response.text + return response.json() + + +@pytest.fixture +def indexed(library): + notes.migrate(library.db) + return library + + +@pytest.mark.asyncio +async def test_a_word_only_in_a_comment_finds_the_run_with_a_snippet(indexed, qa): + run = _own(indexed) + _own(indexed, "another goal") + _comment(indexed, run, "The keyboard covers the zebrafish button on small screens") + + body = await _search(qa, "zebrafish") + + assert [r["session_id"] for r in body["runs"]] == [run] and body["total"] == 1 + snippet = body["runs"][0]["snippet"] + assert snippet["field"] == "comment" and "zebrafish" in snippet["text"] + + +@pytest.mark.asyncio +async def test_a_word_only_in_an_annotation_finds_the_run_with_a_snippet(indexed, qa): + run = _own(indexed) + _annotate(indexed, run, "Spinner never stops: narwhalbug") + + body = await _search(qa, "narwhalbug") + + assert [r["session_id"] for r in body["runs"]] == [run] + assert body["runs"][0]["snippet"] == { + "field": "annotation", + "text": "Spinner never stops: narwhalbug", + } + + +@pytest.mark.asyncio +async def test_goal_matches_rank_before_note_matches(indexed, qa): + by_note = _own(indexed, "unrelated", age_days=0) + by_goal = _own(indexed, "open the okapi screen", age_days=5) + _comment(indexed, by_note, "okapi okapi okapi okapi") + + body = await _search(qa, "okapi") + + assert [r["session_id"] for r in body["runs"]] == [by_goal, by_note] + assert body["runs"][0]["snippet"]["field"] == "prompt" + + +@pytest.mark.asyncio +async def test_a_hidden_run_never_leaks_note_text(indexed, qa): + visible = _own(indexed) + hidden = _own(indexed, owner="qa2@example.com") + for run in (visible, hidden): + _comment(indexed, run, "quokka observation") + _annotate(indexed, run, "quokka-annotation-secret") + + for term in ("quokka", "quokka-annotation-secret"): + response = await qa.get("/api/runs", params={"q": term, "scope": "mine"}) + body = response.json() + assert [r["session_id"] for r in body["runs"]] == [visible] + assert body["total"] == len(body["runs"]) + assert hidden not in response.text + + # Another viewer's private note text never reaches an everyone-scope search either. + response = await qa.get("/api/runs", params={"q": "quokka", "scope": "everyone"}) + assert hidden not in response.text + + +@pytest.mark.asyncio +async def test_a_removed_run_note_text_is_not_returned(indexed, qa): + run = _own(indexed) + _comment(indexed, run, "wombat sighting") + _sql(indexed, "UPDATE run_meta SET deleted_at = 1 WHERE session_id = ?", run) + + assert (await _search(qa, "wombat"))["runs"] == [] + + +@pytest.mark.asyncio +async def test_a_read_only_run_note_snippet_is_redacted(indexed, qa): + run = _own(indexed, owner="someone@example.com") + _comment(indexed, run, "leaked sk-abcdefghijklmnop1234 gnu") + + response = await qa.get("/api/runs", params={"q": "gnu", "scope": "everyone"}) + + assert "sk-abcdefghijklmnop1234" not in response.text + + +def test_editing_and_deleting_notes_keeps_the_index_current(indexed): + run = _own(indexed) + comment = _comment(indexed, run, "ibex first") + annotation = _annotate(indexed, run, "lynx first") + + def found(term): + with sqlite3.connect(indexed.db) as conn: + return run_catalog.search_session_ids(conn, term) + + assert found("ibex") == [run] and found("lynx") == [run] + _sql( + indexed, + "UPDATE run_comments SET body = 'puma second' WHERE comment_id = ?", + comment.comment_id, + ) + _sql( + indexed, + "UPDATE run_annotations SET body = 'serval second' WHERE annotation_id = ?", + annotation.annotation_id, + ) + assert found("ibex") == [] and found("lynx") == [] + assert found("puma") == [run] and found("serval") == [run] + _sql(indexed, "DELETE FROM run_comments WHERE comment_id = ?", comment.comment_id) + assert found("puma") == [] and found("serval") == [run] + _sql(indexed, "DELETE FROM run_annotations WHERE annotation_id = ?", annotation.annotation_id) + assert found("serval") == [] + + +@pytest.mark.parametrize("how", ["session_delete", "tombstone"]) +def test_removing_a_run_removes_its_notes_from_the_index(indexed, how): + run = _own(indexed) + _comment(indexed, run, "tapir remark") + _annotate(indexed, run, "tapir mark") + statement = { + "session_delete": "DELETE FROM sessions WHERE session_id = ?", + "tombstone": "UPDATE run_meta SET deleted_at = 1 WHERE session_id = ?", + }[how] + + _sql(indexed, statement, run) + + with sqlite3.connect(indexed.db) as conn: + assert run_catalog.search_session_ids(conn, "tapir") == [] + assert conn.execute( + "SELECT count(*) FROM runs_fts WHERE runs_fts MATCH 'tapir'" + ).fetchone() == (0,) + + +def test_existing_database_upgrades_once_with_a_backup_and_a_rebuilt_index(library): + run = _own(library) + # Notes written before the index exists (old binary): tables only, no notes triggers. + schema_revisions.apply(library.db, "notes", notes.REVISIONS) + _comment(library, run, "pangolin legacy comment") + with sqlite3.connect(library.db) as conn: + assert run_catalog.search_session_ids(conn, "pangolin") == [] + + first = run_catalog.migrate_notes(library.db) + second = run_catalog.migrate_notes(library.db) + + assert first.applied == (1,) and first.backup_path is not None and first.backup_path.exists() + assert second.applied == () and second.backup_path is None + with sqlite3.connect(library.db) as conn: + assert run_catalog.search_session_ids(conn, "pangolin") == [run] + before = conn.execute("SELECT rowid, prompt, meta, notes FROM runs_fts").fetchall() + run_catalog.migrate_notes(library.db) + with sqlite3.connect(library.db) as conn: + assert conn.execute("SELECT rowid, prompt, meta, notes FROM runs_fts").fetchall() == before + + +def test_notes_migration_is_a_noop_before_the_notes_tables_exist(library): + _own(library) + + assert run_catalog.migrate_notes(library.db).applied == () + notes.migrate(library.db) + with sqlite3.connect(library.db) as conn: + assert conn.execute( + "SELECT revision FROM schema_revisions WHERE module = ?", (run_catalog.NOTES_MODULE,) + ).fetchone() == (1,) + + +@pytest.mark.asyncio +async def test_substring_fallback_still_searches_everything_but_notes(library, qa, monkeypatch): + run = _own(library, "fallback goal") + notes.migrate(library.db) + with sqlite3.connect(library.db) as conn: + for trigger in (*run_catalog._TRIGGERS_FTS, *run_catalog._TRIGGERS_NOTES): + conn.execute(f"DROP TRIGGER IF EXISTS {trigger}") + conn.execute("DROP TABLE runs_fts") + monkeypatch.setattr(run_catalog, "fts5_available", lambda conn: False) + run_catalog.migrate(library.db) + _comment(library, run, "added in fallback mode") # must not fail without runs_fts + + body = await _search(qa, "fallback goal") + + assert [r["session_id"] for r in body["runs"]] == [run] + assert body["warnings"] == ["search_fallback_substring"] diff --git a/tests/unit/data_engine/test_run_catalog_schema.py b/tests/unit/data_engine/test_run_catalog_schema.py index 4cc74a2fc..ffc035ba5 100644 --- a/tests/unit/data_engine/test_run_catalog_schema.py +++ b/tests/unit/data_engine/test_run_catalog_schema.py @@ -213,7 +213,7 @@ def test_snapshot_index_upgrade_rebuilds_old_rows_only_once(old_catalog, rc): before = conn.execute( "SELECT revision, updated_at FROM schema_revisions WHERE module = 'run_catalog_fts'" ).fetchone() - assert before is not None and before[0] == 1 + assert before is not None and before[0] == len(rc.FTS_REVISIONS) version = conn.execute("PRAGMA data_version").fetchone() assert rc.migrate(old_catalog).backup_path is None assert conn.execute("PRAGMA data_version").fetchone() == version