Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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").
Expand All @@ -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


Expand Down
32 changes: 32 additions & 0 deletions apps/admin_console/database/repositories/run_catalog_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
10 changes: 10 additions & 0 deletions apps/admin_console/routers/runs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
189 changes: 162 additions & 27 deletions artemis/data_engine/run_catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = (
"""
Expand Down Expand Up @@ -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"

Expand All @@ -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 = (
Expand All @@ -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 "
Expand Down Expand Up @@ -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),
),
)


Expand Down Expand Up @@ -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")
Expand All @@ -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.

Expand All @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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_]+")
Expand Down Expand Up @@ -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")),
Expand All @@ -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":
Expand Down
Loading
Loading