Python
fix(memhub): drop grant triggers that read a table the cutover dropped
alvinfei47e938da1b6a
diff --git a/memhub/apps/core/src/one_memory/api.py b/memhub/apps/core/src/one_memory/api.pyindex 30ab808..cb516f7 100644--- a/memhub/apps/core/src/one_memory/api.py+++ b/memhub/apps/core/src/one_memory/api.py@@ -922,6 +922,16 @@ def create_app()except sqlite3.Error as error:app.state.memory_visibility_error = str(error)+ else:+ # A home an earlier build migrated still carries the grant+ # triggers whose body reads a dropped table (#233).+ try:+ await asyncio.to_thread(+ memory_visibility.drop_stale_triggers,+ database_path,+ )+ except sqlite3.Error as error:+ app.state.memory_visibility_error = str(error)model_request_budget = (ModelRequestBudget(database_path,diff --git a/memhub/apps/core/src/one_memory/memory_visibility.py b/memhub/apps/core/src/one_memory/memory_visibility.pyindex bb3bfb4..5476bb0 100644--- a/memhub/apps/core/src/one_memory/memory_visibility.py+++ b/memhub/apps/core/src/one_memory/memory_visibility.py@@ -160,7 +160,7 @@ def pending(db: sqlite3.Connection, *, limit: int = 100) -> list[str]:def _trigger_sql() -> list[tuple[str, str]]:- """(table it depends on, statement) for each trigger."""+ """(table it is on, statement) for each trigger."""return [("evidence",@@ -303,9 +303,61 @@ def install_triggers(db: sqlite3.Connection) -> None:for table, statement in _trigger_sql():if table not in present:continue+ if not _body_tables(statement) <= present:+ # SQLite resolves a trigger body only when it fires, so a body+ # naming a dropped table fails the write it rides on (#233: the+ # SDK cutover drops `governed_memory_evidence`, and every grant+ # write then failed). Not installed, and an old copy is removed.+ cursor.execute(f"DROP TRIGGER IF EXISTS {_trigger_name(statement)}")+ continuecursor.execute(statement)+def _trigger_name(statement: str) -> str:+ return statement.split("IF NOT EXISTS", 1)[1].split()[0]+++def _body_tables(statement: str) -> set[str]:+ """Tables the trigger body reads or writes besides the one it is on."""+ _head, _begin, body = statement.partition("BEGIN")+ words = body.replace("(", " ").replace(")", " ").split()+ return {+ name+ for keyword, name in zip(words, words[1:], strict=False)+ if keyword.upper() in {"FROM", "JOIN", "INTO"}+ }+++def drop_stale_triggers(database_path: Path) -> tuple[str, ...]:+ """Drop this module's triggers whose body names a table that is gone.++ Startup on SDK authority does not install the cache (it is read only on+ legacy authority), but a home migrated by an earlier build still carries+ the triggers it installed. One whose body reads a dropped table fails+ every write to the table it is on, so it is dropped here. Idempotent.+ """+ with main_database(database_path).write() as db, db:+ cursor = db.cursor()+ cursor.row_factory = sqlite3.Row+ present = {+ str(row["name"])+ for row in cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")+ }+ installed = {+ str(row["name"])+ for row in cursor.execute("SELECT name FROM sqlite_master WHERE type='trigger'")+ }+ dropped = tuple(+ name+ for _table, statement in _trigger_sql()+ if (name := _trigger_name(statement)) in installed+ and not _body_tables(statement) <= present+ )+ for name in dropped:+ cursor.execute(f"DROP TRIGGER IF EXISTS {name}")+ return dropped++def startup(database_path: Path) -> None:"""Idempotent: create the derived tables and triggers. No version change.diff --git a/memhub/apps/core/src/one_memory/sdk_migration_runner.py b/memhub/apps/core/src/one_memory/sdk_migration_runner.pyindex 2dc0263..e4a7da3 100644--- a/memhub/apps/core/src/one_memory/sdk_migration_runner.py+++ b/memhub/apps/core/src/one_memory/sdk_migration_runner.py@@ -457,13 +457,17 @@ def resume_legacy_cleanup(*, data_dir: Path, database_path: Path) -> tuple[str,bundle_id=marker.backup_bundle_id,)from one_memory.hy_runtime_config import HY_MEMORY_NAMESPACE+ from one_memory.memory_visibility import drop_stale_triggersrecover_abandoned_staging(data_dir=data_dir,database_path=database_path,namespace=HY_MEMORY_NAMESPACE,)- return drop_legacy_tables(database_path)+ dropped = drop_legacy_tables(database_path)+ # The visibility cache's grant triggers read a table just dropped (#233).+ drop_stale_triggers(database_path)+ return droppedMIGRATION_PREFIX = "sdk-authority-v2"diff --git a/memhub/apps/core/tests/test_memory_visibility.py b/memhub/apps/core/tests/test_memory_visibility.pyindex 9a7028f..908f9d4 100644--- a/memhub/apps/core/tests/test_memory_visibility.py+++ b/memhub/apps/core/tests/test_memory_visibility.py@@ -611,3 +611,58 @@ def test_granting_a_source_repeatedly_does_not_raise(library):with main_database_read(database) as db:assert memory.memory_id in pending(db)+++def test_grant_writes_still_work_after_the_cutover_drops_the_link_table(library):+ """#233: the grant triggers read `governed_memory_evidence`.++ The SDK cutover drops it, and SQLite resolves a trigger body only when it+ fires, so every grant, revoke and connect then failed with "no such+ table". A trigger whose body names a missing table is not installed, and+ the copy an earlier startup installed is dropped.+ """+ database, *_ = library+ from one_memory.imports.candidates import RootCandidateKind+ from one_memory.imports.grants import SourceGrantStore+ from one_memory.memory_visibility import drop_stale_triggers++ startup(database)+ with sqlite3.connect(database) as db:+ db.execute("DROP TABLE governed_memory_evidence")++ def grant_triggers() -> set[str]:+ with sqlite3.connect(database) as db:+ return {+ str(row[0])+ for row in db.execute(+ "SELECT name FROM sqlite_master "+ "WHERE type='trigger' AND tbl_name='source_grants'"+ )+ }++ assert grant_triggers() == {+ "memory_visibility_dirty_on_grants",+ "memory_visibility_dirty_on_grants_update",+ }+ # The `evidence` triggers read the dropped table too; the cutover drops+ # `evidence` as well, which takes them with it.+ assert {+ "memory_visibility_dirty_on_grants",+ "memory_visibility_dirty_on_grants_update",+ } <= set(drop_stale_triggers(database))+ assert grant_triggers() == set()+ assert drop_stale_triggers(database) == ()+ # Installing again on this shape skips them instead of bringing them back.+ startup(database)+ assert grant_triggers() == set()++ folder = database.parent / "cursor"+ folder.mkdir(exist_ok=True)+ store = SourceGrantStore(database, home=database.parent)+ store.grant(+ user_id="local",+ source_id="cursor",+ root=folder,+ candidate_kind=RootCandidateKind.DEFAULT,+ )+ assert store.revoke(user_id="local", source_id="cursor").revoked_at is not Nonediff --git a/memhub/apps/core/tests/test_multi_user_runtime.py b/memhub/apps/core/tests/test_multi_user_runtime.pyindex 878f3f7..84cd52a 100644--- a/memhub/apps/core/tests/test_multi_user_runtime.py+++ b/memhub/apps/core/tests/test_multi_user_runtime.py@@ -650,6 +650,75 @@ def test_two_hermes_grants_each_read_their_own_root_into_separate_batches(tmp_paasyncio.run(scenario())+def test_a_migrated_home_with_the_old_grant_triggers_can_connect_and_revoke(tmp_path) -> None:+ """#233: a home an earlier build migrated kept two `source_grants` triggers+ whose body reads the dropped `governed_memory_evidence`. Every grant write+ then failed, so connecting and revoking answered 503. Startup drops them.+ """+ stale = """+ CREATE TRIGGER memory_visibility_dirty_on_grants{suffix}+ AFTER {event} ON source_grants+ BEGIN+ INSERT INTO memory_visibility_dirty (memory_id)+ SELECT DISTINCT link.memory_id+ FROM governed_memory_evidence link+ JOIN evidence e ON e.evidence_id = link.evidence_id+ WHERE e.source_id = NEW.source_id+ ON CONFLICT(memory_id) DO NOTHING;+ END;"""++ async def scenario():+ home = tmp_path / "home"+ _hermes, wife = _hermes_homes(home)+ app = application(tmp_path, home=home)+ async with app.router.lifespan_context(app):+ database = app.state.settings.data_dir / "one-memory.sqlite3"+ with sqlite3.connect(database) as db:+ db.execute("CREATE TABLE IF NOT EXISTS memory_visibility_dirty (memory_id TEXT)")+ db.execute(stale.format(suffix="", event="INSERT"))+ db.execute(stale.format(suffix="_update", event="UPDATE"))++ app = application(tmp_path, home=home)+ async with app.router.lifespan_context(app), client_for(app) as client:+ location = (await client.post("/api/v1/sources/hermes/location")).json()+ local = await client.post(+ "/api/v1/sources/connect",+ json={+ "source_ids": ["hermes"],+ "request_id": str(uuid4()),+ "source_roots": {"hermes": location["root_id"]},+ },+ )+ assert local.status_code == 200, local.text+ profile = await client.post(+ "/api/v1/sources/connect",+ json={+ "source_ids": ["hermes"],+ "request_id": str(uuid4()),+ "user_id": "wife",+ "root": str(wife),+ },+ )+ assert profile.status_code == 200, profile.text+ for user_id in ("wife", "local"):+ revoked = await client.post(+ "/api/v1/sources/hermes/revoke", params={"user_id": user_id}+ )+ assert revoked.status_code == 200, revoked.text+ assert revoked.json()["revoked_at"] is not None+ with sqlite3.connect(database) as db:+ assert (+ db.execute(+ "SELECT COUNT(*) FROM sqlite_master "+ "WHERE type='trigger' AND tbl_name='source_grants'"+ ).fetchone()[0]+ == 0+ )++ asyncio.run(scenario())++@pytest.mark.fresh_sdkdef test_only_hermes_takes_another_user_or_a_custom_root(tmp_path) -> None:async def scenario():