Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(storage): repair scope id nullability drift (#2721)
Max8de82713f78f
diff --git a/docs/plans/2026-10-16-scope-id-nullability-drift-repair.md b/docs/plans/2026-10-16-scope-id-nullability-drift-repair.mdnew file mode 100644index 000000000..c63b7702d--- /dev/null+++ b/docs/plans/2026-10-16-scope-id-nullability-drift-repair.md@@ -0,0 +1,44 @@+# Scope ID Nullability Drift Repair++## Background++Some long-lived SQLite databases were stamped past+`20260723_0032_session_visibility` without running it. Their Alembic revision is+current, but `messages.scope_id`, `agent_events.scope_id`, and+`media_objects.scope_id` are still `NOT NULL`, and+`ix_agent_sessions_visibility` may be absent.++The affected tables can be large and have inbound foreign keys. Rebuilding them+would copy all rows and can trigger `ON DELETE` behavior while foreign-key+enforcement is enabled.++## Goal++Add a replay-safe migration after the current head that:++- removes only the three stale `NOT NULL` constraints;+- restores the visibility index when it is missing;+- performs no table DDL on a correctly migrated database;+- preserves every row and inbound foreign-key value; and+- leaves downgrade as a no-op because tightening the columns again cannot+ represent scope-less Sessions safely.++## Solution++Use SQLite's in-place schema-edit procedure for the three column constraints:+preflight the rewritten `CREATE TABLE` SQL, update `sqlite_schema` under+`PRAGMA writable_schema`, increment `schema_version`, and verify SQLite reports+the repaired columns as nullable. This keeps each table's root page and every+row unchanged, so it is constant-space and avoids a full table copy.++Create `ix_agent_sessions_visibility` separately with idempotent index DDL.++## Validation++- Upgrade a drifted previous-head fixture with rows and inbound references.+- Materialize a scope-less Delivery after repair.+- Prove a correct previous-head database keeps identical schema SQL, root+ pages, and schema version.+- Replay the repair through the head-shaped unversioned stamp path.+- Run focused migration tests, Ruff, the migration release guard, and the+ exact-head PR review and CI gates.diff --git a/storage/alembic/versions/20261016_0069_repair_scope_id_nullability.py b/storage/alembic/versions/20261016_0069_repair_scope_id_nullability.pynew file mode 100644index 000000000..5ee433a6e--- /dev/null+++ b/storage/alembic/versions/20261016_0069_repair_scope_id_nullability.py@@ -0,0 +1,291 @@+"""repair scope_id nullability skipped by a historical schema stamp++Some head-shaped databases were stamped past 20260723_0032 without running its+table alterations. Rebuilding these tables now would copy large histories and+temporarily delete referenced rows under SQLite batch mode. Instead, remove only+the stale ``NOT NULL`` tokens from SQLite's stored CREATE TABLE statements,+increment ``schema_version``, and leave every table root page and row untouched.++Downgrade is deliberately a no-op. Scope-less Sessions can create rows after+this repair, so tightening the columns again would require deleting valid data+or make the downgrade fail.++Revision ID: 20261016_0069+Revises: 20261016_0068+Create Date: 2026-10-16+"""++from __future__ import annotations++import sqlite3++from alembic import op++revision = "20261016_0069"+down_revision = "20261016_0068"+branch_labels = None+depends_on = None+MIGRATION_SAFETY = "additive"++_SCOPE_ID_TABLES = ("messages", "agent_events", "media_objects")+_VISIBILITY_INDEX = "ix_agent_sessions_visibility"+_VISIBILITY_INDEX_SQL = (+ f"create index {_VISIBILITY_INDEX} on agent_sessions (visibility)"+)+++def _tables(bind) -> set[str]:+ return {+ str(row[0])+ for row in bind.exec_driver_sql(+ "select name from sqlite_schema where type = 'table'"+ )+ }+++def _columns(bind, table: str) -> dict[str, tuple]:+ return {+ str(row[1]): tuple(row)+ for row in bind.exec_driver_sql(f'pragma table_info("{table}")').fetchall()+ }+++def _indexes(bind, table: str) -> set[str]:+ return {+ str(row[1])+ for row in bind.exec_driver_sql(f'pragma index_list("{table}")').fetchall()+ }+++def _table_item_spans(sql: str) -> list[tuple[int, int]]:+ """Return top-level column/constraint spans from one CREATE TABLE statement."""++ spans: list[tuple[int, int]] = []+ depth = 0+ item_start: int | None = None+ quote_end: str | None = None+ index = 0+ while index < len(sql):+ char = sql[index]+ if quote_end is not None:+ if char == quote_end:+ if index + 1 < len(sql) and sql[index + 1] == quote_end:+ index += 2+ continue+ quote_end = None+ index += 1+ continue+ if char in {"'", '"', "`"}:+ quote_end = char+ elif char == "[":+ quote_end = "]"+ elif char == "(":+ depth += 1+ if depth == 1:+ item_start = index + 1+ elif char == ")":+ if depth == 1:+ if item_start is None:+ raise RuntimeError("CREATE TABLE body has no item start")+ spans.append((item_start, index))+ return spans+ depth -= 1+ elif char == "," and depth == 1:+ if item_start is None:+ raise RuntimeError("CREATE TABLE body has no item start")+ spans.append((item_start, index))+ item_start = index + 1+ index += 1+ raise RuntimeError("CREATE TABLE statement has no complete body")+++def _leading_identifier(item: str) -> tuple[str, int]:+ index = 0+ while index < len(item) and item[index].isspace():+ index += 1+ if index == len(item):+ return "", index++ opener = item[index]+ quote_end = {'"': '"', "`": "`", "[": "]"}.get(opener)+ if quote_end is not None:+ index += 1+ value: list[str] = []+ while index < len(item):+ char = item[index]+ if char == quote_end:+ if index + 1 < len(item) and item[index + 1] == quote_end:+ value.append(char)+ index += 2+ continue+ return "".join(value), index + 1+ value.append(char)+ index += 1+ raise RuntimeError("unterminated quoted identifier in CREATE TABLE")++ start = index+ while index < len(item) and (+ item[index].isalnum() or item[index] in {"_", "$"}+ ):+ index += 1+ return item[start:index], index+++def _top_level_words(item: str, start: int) -> list[tuple[str, int, int]]:+ words: list[tuple[str, int, int]] = []+ depth = 0+ quote_end: str | None = None+ index = start+ while index < len(item):+ char = item[index]+ if quote_end is not None:+ if char == quote_end:+ if index + 1 < len(item) and item[index + 1] == quote_end:+ index += 2+ continue+ quote_end = None+ index += 1+ continue+ if char in {"'", '"', "`"}:+ quote_end = char+ index += 1+ continue+ if char == "[":+ quote_end = "]"+ index += 1+ continue+ if char == "(":+ depth += 1+ index += 1+ continue+ if char == ")":+ depth -= 1+ index += 1+ continue+ if depth == 0 and (char.isalpha() or char == "_"):+ word_start = index+ index += 1+ while index < len(item) and (+ item[index].isalnum() or item[index] in {"_", "$"}+ ):+ index += 1+ words.append((item[word_start:index].casefold(), word_start, index))+ continue+ index += 1+ return words+++def _make_scope_id_nullable(table: str, sql: str) -> str:+ for start, end in _table_item_spans(sql):+ item = sql[start:end]+ identifier, identifier_end = _leading_identifier(item)+ if identifier.casefold() != "scope_id":+ continue++ words = _top_level_words(item, identifier_end)+ pairs = [+ (first[1], second[2])+ for first, second in zip(+ words,+ words[1:],+ strict=False,+ )+ if first[0] == "not" and second[0] == "null"+ ]+ if len(pairs) != 1:+ raise RuntimeError(+ f"{table}.scope_id is NOT NULL but its stored definition "+ f"contains {len(pairs)} top-level NOT NULL clauses"+ )+ remove_start, remove_end = pairs[0]+ while remove_start > identifier_end and item[remove_start - 1].isspace():+ remove_start -= 1+ updated_item = item[:remove_start] + item[remove_end:]+ return sql[:start] + updated_item + sql[end:]+ raise RuntimeError(f"{table} has no scope_id column definition")+++def _table_info_from_sql(table: str, sql: str) -> list[tuple]:+ with sqlite3.connect(":memory:") as conn:+ conn.execute(sql)+ return conn.execute(f'pragma table_info("{table}")').fetchall()+++def _preflight_schema_edit(table: str, old_sql: str, new_sql: str) -> None:+ old_columns = _table_info_from_sql(table, old_sql)+ new_columns = _table_info_from_sql(table, new_sql)+ expected = [+ tuple((*row[:3], 0, *row[4:])) if row[1] == "scope_id" else tuple(row)+ for row in old_columns+ ]+ if new_columns != expected:+ raise RuntimeError(+ f"{table}.scope_id repair would change more than its NOT NULL flag"+ )+++def _rewrite_drifted_tables(bind, drifted: list[str]) -> None:+ rewrites: dict[str, tuple[str, str]] = {}+ for table in drifted:+ row = bind.exec_driver_sql(+ "select sql from sqlite_schema where type = 'table' and name = ?",+ (table,),+ ).one_or_none()+ if row is None or not row[0]:+ raise RuntimeError(f"cannot read stored CREATE TABLE SQL for {table}")+ old_sql = str(row[0])+ new_sql = _make_scope_id_nullable(table, old_sql)+ _preflight_schema_edit(table, old_sql, new_sql)+ rewrites[table] = (old_sql, new_sql)++ schema_version = int(+ bind.exec_driver_sql("pragma schema_version").scalar_one()+ )+ bind.exec_driver_sql("pragma writable_schema = on")+ try:+ for table, (old_sql, new_sql) in rewrites.items():+ bind.exec_driver_sql(+ "update sqlite_schema set sql = ? "+ "where type = 'table' and name = ? and sql = ?",+ (new_sql, table, old_sql),+ )+ stored = bind.exec_driver_sql(+ "select sql from sqlite_schema where type = 'table' and name = ?",+ (table,),+ ).scalar_one()+ if stored != new_sql:+ raise RuntimeError(f"stored CREATE TABLE SQL changed concurrently for {table}")+ bind.exec_driver_sql(f"pragma schema_version = {schema_version + 1}")+ finally:+ bind.exec_driver_sql("pragma writable_schema = off")++ for table in drifted:+ if _columns(bind, table)["scope_id"][3]:+ raise RuntimeError(f"{table}.scope_id remained NOT NULL after repair")+++def upgrade() -> None:+ bind = op.get_bind()+ tables = _tables(bind)+ drifted = [+ table+ for table in _SCOPE_ID_TABLES+ if table in tables+ and "scope_id" in _columns(bind, table)+ and _columns(bind, table)["scope_id"][3]+ ]+ if drifted:+ _rewrite_drifted_tables(bind, drifted)++ if (+ "agent_sessions" in tables+ and "visibility" in _columns(bind, "agent_sessions")+ and _VISIBILITY_INDEX not in _indexes(bind, "agent_sessions")+ ):+ bind.exec_driver_sql(_VISIBILITY_INDEX_SQL)+++def downgrade() -> None:+ """Preserve scope-less rows; reapplying NOT NULL would be destructive."""++ returndiff --git a/tests/test_agent_context_seq_migration.py b/tests/test_agent_context_seq_migration.pyindex eddeaa974..a669ee513 100644--- a/tests/test_agent_context_seq_migration.py+++ b/tests/test_agent_context_seq_migration.py@@ -56,7 +56,7 @@ def test_context_seq_upgrade_and_downgrade_keep_released_rows(tmp_path):migrations.run_migrations(path)with sqlite3.connect(path) as conn:- assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261016_0068",)+ assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261016_0069",)assert_released_rows_unchanged(conn)assert _index_sql(conn, "ix_agent_events_turn_sequence_id") is not Nonefor table, (first, same_session, other_session) in _IDS.items():diff --git a/tests/test_skill_observability_migration.py b/tests/test_skill_observability_migration.pyindex fb6179068..155f6b398 100644--- a/tests/test_skill_observability_migration.py+++ b/tests/test_skill_observability_migration.py@@ -35,7 +35,7 @@ def test_skill_schema_upgrade_downgrade_preserves_existing_events(tmp_path):migrations.run_migrations(path)with sqlite3.connect(path) as conn:assert conn.execute(f"SELECT {columns} FROM agent_events ORDER BY id").fetchall() == original- assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261016_0068",)+ assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261016_0069",)assert conn.execute("SELECT count(*) FROM skill_usage_daily").fetchone() == (0,)assert {row[2] for row in conn.execute("PRAGMA foreign_key_list(skill_usage_daily)")} == {"scopes",diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex dc29af1c2..ca9c18765 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -38,7 +38,9 @@ from vibe.message_types import build_partial_index_predicatepytestmark = pytest.mark.no_sqlite_template-HEAD_REVISION = "20261016_0068"+HEAD_REVISION = "20261016_0069"+PREVIOUS_HEAD_REVISION = "20261016_0068"+_SCOPE_ID_DRIFT_TABLES = ("messages", "agent_events", "media_objects")# ``storage.models`` builds a bare ``MetaData()``, so its foreign keys are unnamed and# Alembic cannot re-emit them when batch mode recreates a table. Every migration that# rebuilds one therefore passes this convention; the rebuild simulated below has to pass@@ -3426,6 +3428,400 @@ def test_session_visibility_migration_reparents_legacy_runs_and_self_anchors(tmpassert promoted.session_key.thread_id is None+def _restore_scope_id_not_null_drift(conn: sqlite3.Connection) -> None:+ """Recreate the released head-shaped drift without copying any table."""++ schema_version = conn.execute("pragma schema_version").fetchone()[0]+ conn.execute("pragma writable_schema = on")+ try:+ for table in _SCOPE_ID_DRIFT_TABLES:+ sql = conn.execute(+ "select sql from sqlite_schema where type = 'table' and name = ?",+ (table,),+ ).fetchone()[0]+ drifted_sql = sql.replace(+ "scope_id VARCHAR,",+ "scope_id VARCHAR NOT NULL,",+ 1,+ )+ assert drifted_sql != sql, f"{table} fixture did not find scope_id"+ conn.execute(+ "update sqlite_schema set sql = ? where type = 'table' and name = ?",+ (drifted_sql, table),+ )+ conn.execute(f"pragma schema_version = {schema_version + 1}")+ finally:+ conn.execute("pragma writable_schema = off")+ conn.execute("drop index if exists ix_agent_sessions_visibility")+ conn.commit()+ assert all(+ {+ row[1]: row[3]+ for row in conn.execute(f'pragma table_info("{table}")')+ }["scope_id"]+ for table in _SCOPE_ID_DRIFT_TABLES+ )+++def _insert_current_session(+ conn,+ *,+ session_id: str,+ scope_id: str | None,+ now: str,+) -> None:+ conn.exec_driver_sql(+ """+ insert into agent_sessions (+ id, scope_id, agent_name, agent_backend, agent_variant,+ session_anchor, workdir, native_session_id, status, visibility,+ pinned, agent_status, metadata_json, created_at, updated_at,+ last_active_at+ ) values (+ ?, ?, 'codex', 'codex', 'codex', ?, '/tmp', '', 'active',+ 'foreground', 0, 'idle', '{}', ?, ?, ?+ )+ """,+ (session_id, scope_id, session_id, now, now, now),+ )+++def _materialize_test_message(+ conn,+ *,+ session_id: str,+ scope_id: str | None,+ message_id: str,+ now: str,+) -> None:+ delivery = message_deliveries.insert_delivery(+ conn,+ delivery_id=message_id,+ session_id=session_id,+ priority="p3",+ state="reserved",+ snapshot=message_deliveries.message_snapshot(+ scope_id=scope_id,+ session_id=session_id,+ platform="avibe",+ author="user",+ source="user",+ message_type="user",+ text=message_id,+ ),+ dispatch_text=message_id,+ now=now,+ )+ claimed = message_deliveries.claim_start_batch(+ conn,+ turn_id=f"turn_{message_id}",+ session_id=session_id,+ backend="codex",+ deliveries=[delivery],+ dispatch_text=message_id,+ )+ turn = message_deliveries.bind_native_start(+ conn,+ f"turn_{message_id}",+ expected_version=int(claimed["turn"]["version"]),+ runtime_key=f"runtime_{message_id}",+ runtime_turn_id=f"runtime_turn_{message_id}",+ native_turn_id=f"native_turn_{message_id}",+ )+ assert turn is not None+ assert message_deliveries.materialize_start_acceptance(+ conn,+ turn_id=f"turn_{message_id}",+ evidence={"kind": "migration_test"},+ )+++def _inbound_foreign_key_tables(target: str) -> set[str]:+ return {+ table.name+ for table in metadata.tables.values()+ for constraint in table.foreign_key_constraints+ if constraint.referred_table.name == target+ }+++def test_scope_id_nullability_repair_preserves_rows_and_references(+ tmp_path: Path,+) -> None:+ db_path = tmp_path / "vibe.sqlite"+ run_migrations(db_path, revision=PREVIOUS_HEAD_REVISION)+ engine = create_sqlite_engine(db_path)+ now = "2026-10-16T00:00:00Z"+ with engine.begin() as conn:+ scope_id = upsert_scope(+ conn,+ platform="avibe",+ scope_type="project",+ native_id="scope-repair",+ now=now,+ )+ _insert_current_session(+ conn,+ session_id="ses_scope_repair",+ scope_id=scope_id,+ now=now,+ )+ _materialize_test_message(+ conn,+ session_id="ses_scope_repair",+ scope_id=scope_id,+ message_id="msg_scope_repair",+ now=now,+ )+ conn.exec_driver_sql(+ """+ insert into agent_events (+ id, scope_id, session_id, platform, event_type, content_json,+ metadata_json, created_at, updated_at+ ) values (+ 'evt_scope_repair', ?, 'ses_scope_repair', 'avibe', 'tool_call',+ '{}', '{}', ?, ?+ )+ """,+ (scope_id, now, now),+ )+ conn.exec_driver_sql(+ """+ insert into media_objects (+ token, scope_id, session_id, message_id, kind, source,+ local_path, created_at+ ) values (+ 'media_scope_repair', ?, 'ses_scope_repair', 'msg_scope_repair',+ 'file', 'user_upload', '/tmp/scope-repair.txt', ?+ )+ """,+ (scope_id, now),+ )+ conn.exec_driver_sql(+ """+ insert into media_object_references (token, session_id, created_at)+ values ('media_scope_repair', 'ses_scope_repair', ?)+ """,+ (now,),+ )+ conn.exec_driver_sql(+ """+ insert into show_session_events (+ id, session_id, event_type, actor, scope, anchor_json,+ payload_json, message_id, delivery_id, created_at+ ) values (+ 'show_scope_repair', 'ses_scope_repair', 'input', 'user',+ 'session', '{}', '{}', 'msg_scope_repair',+ 'msg_scope_repair', ?+ )+ """,+ (now,),+ )+ engine.dispose()++ assert _inbound_foreign_key_tables("messages") == {+ "message_deliveries",+ "media_objects",+ "show_session_events",+ }+ assert _inbound_foreign_key_tables("media_objects") == {+ "media_object_references"+ }+ assert _inbound_foreign_key_tables("agent_events") == set()++ with sqlite3.connect(db_path) as conn:+ _restore_scope_id_not_null_drift(conn)+ before_counts = {+ table: conn.execute(f'select count(*) from "{table}"').fetchone()[0]+ for table in (+ *_SCOPE_ID_DRIFT_TABLES,+ "message_deliveries",+ "show_session_events",+ "media_object_references",+ )+ }+ before_rootpages = {+ row[0]: row[1]+ for row in conn.execute(+ "select name, rootpage from sqlite_schema "+ "where type = 'table' and name in (?, ?, ?)",+ _SCOPE_ID_DRIFT_TABLES,+ )+ }++ run_migrations(db_path)++ with sqlite3.connect(db_path) as conn:+ nullable = {+ table: {+ row[1]: row[3]+ for row in conn.execute(f'pragma table_info("{table}")')+ }["scope_id"]+ for table in _SCOPE_ID_DRIFT_TABLES+ }+ after_counts = {+ table: conn.execute(f'select count(*) from "{table}"').fetchone()[0]+ for table in before_counts+ }+ after_rootpages = {+ row[0]: row[1]+ for row in conn.execute(+ "select name, rootpage from sqlite_schema "+ "where type = 'table' and name in (?, ?, ?)",+ _SCOPE_ID_DRIFT_TABLES,+ )+ }+ refs = (+ conn.execute(+ "select message_id from message_deliveries "+ "where id = 'msg_scope_repair'"+ ).fetchone(),+ conn.execute(+ "select message_id from media_objects "+ "where token = 'media_scope_repair'"+ ).fetchone(),+ conn.execute(+ "select message_id from show_session_events "+ "where id = 'show_scope_repair'"+ ).fetchone(),+ conn.execute(+ "select token from media_object_references "+ "where token = 'media_scope_repair'"+ ).fetchone(),+ )+ indexes = {+ row[1] for row in conn.execute("pragma index_list(agent_sessions)")+ }+ foreign_key_errors = conn.execute("pragma foreign_key_check").fetchall()+ integrity = conn.execute("pragma integrity_check").fetchall()++ assert nullable == {table: 0 for table in _SCOPE_ID_DRIFT_TABLES}+ assert after_counts == before_counts+ assert after_rootpages == before_rootpages+ assert refs == (+ ("msg_scope_repair",),+ ("msg_scope_repair",),+ ("msg_scope_repair",),+ ("media_scope_repair",),+ )+ assert "ix_agent_sessions_visibility" in indexes+ assert foreign_key_errors == []+ assert integrity == [("ok",)]++ engine = create_sqlite_engine(db_path)+ with engine.begin() as conn:+ _insert_current_session(+ conn,+ session_id="ses_scope_less",+ scope_id=None,+ now=now,+ )+ _materialize_test_message(+ conn,+ session_id="ses_scope_less",+ scope_id=None,+ message_id="msg_scope_less",+ now=now,+ )+ scope_id = conn.exec_driver_sql(+ "select scope_id from messages where id = 'msg_scope_less'"+ ).scalar_one()+ engine.dispose()+ assert scope_id is None++ command.downgrade(+ migrations.alembic_config(db_path),+ PREVIOUS_HEAD_REVISION,+ )+ with sqlite3.connect(db_path) as conn:+ assert {+ table: {+ row[1]: row[3]+ for row in conn.execute(f'pragma table_info("{table}")')+ }["scope_id"]+ for table in _SCOPE_ID_DRIFT_TABLES+ } == {table: 0 for table in _SCOPE_ID_DRIFT_TABLES}+ assert conn.execute(+ "select scope_id from messages where id = 'msg_scope_less'"+ ).fetchone() == (None,)+ assert "ix_agent_sessions_visibility" in {+ row[1] for row in conn.execute("pragma index_list(agent_sessions)")+ }+ assert conn.execute("pragma foreign_key_check").fetchall() == []++ run_migrations(db_path)+ with sqlite3.connect(db_path) as conn:+ assert conn.execute(+ "select version_num from alembic_version"+ ).fetchone() == (HEAD_REVISION,)+++def test_scope_id_nullability_repair_is_noop_on_correct_schema(+ tmp_path: Path,+) -> None:+ db_path = tmp_path / "vibe.sqlite"+ run_migrations(db_path, revision=PREVIOUS_HEAD_REVISION)+ with sqlite3.connect(db_path) as conn:+ before = conn.execute(+ "select type, name, tbl_name, sql, rootpage from sqlite_schema "+ "where name <> 'alembic_version' order by type, name"+ ).fetchall()+ before_schema_version = conn.execute(+ "pragma schema_version"+ ).fetchone()[0]++ run_migrations(db_path)++ with sqlite3.connect(db_path) as conn:+ after = conn.execute(+ "select type, name, tbl_name, sql, rootpage from sqlite_schema "+ "where name <> 'alembic_version' order by type, name"+ ).fetchall()+ after_schema_version = conn.execute(+ "pragma schema_version"+ ).fetchone()[0]+ version = conn.execute(+ "select version_num from alembic_version"+ ).fetchone()++ assert after == before+ assert after_schema_version == before_schema_version+ assert version == (HEAD_REVISION,)+++def test_scope_id_nullability_repair_replays_after_head_shape_stamp(+ tmp_path: Path,+) -> None:+ db_path = tmp_path / "vibe.sqlite"+ engine = create_sqlite_engine(db_path)+ try:+ metadata.create_all(engine)+ finally:+ engine.dispose()+ with sqlite3.connect(db_path) as conn:+ _restore_scope_id_not_null_drift(conn)+ assert conn.execute(+ "select name from sqlite_schema where name = 'alembic_version'"+ ).fetchone() is None++ run_migrations(db_path)++ with sqlite3.connect(db_path) as conn:+ assert {+ table: {+ row[1]: row[3]+ for row in conn.execute(f'pragma table_info("{table}")')+ }["scope_id"]+ for table in _SCOPE_ID_DRIFT_TABLES+ } == {table: 0 for table in _SCOPE_ID_DRIFT_TABLES}+ assert "ix_agent_sessions_visibility" in {+ row[1] for row in conn.execute("pragma index_list(agent_sessions)")+ }+ assert conn.execute(+ "select version_num from alembic_version"+ ).fetchone() == (HEAD_REVISION,)++def test_run_migrations_serializes_alembic_context(monkeypatch, tmp_path: Path) -> None:first_entered = threading.Event()second_entered = threading.Event()diff --git a/tests/test_web_push_provider_invalidation_migration.py b/tests/test_web_push_provider_invalidation_migration.pyindex 1b8c08120..2f60a6ce3 100644--- a/tests/test_web_push_provider_invalidation_migration.py+++ b/tests/test_web_push_provider_invalidation_migration.py@@ -69,7 +69,7 @@ def test_upgrade_keeps_legacy_disabled_failure_opted_out(tmp_path):web_push_service.mark_send_failure(conn, endpoint=enabled["endpoint"], disable=True)with sqlite3.connect(path) as conn:assert conn.execute("select version_num from alembic_version").fetchone() == (- "20261016_0068",+ "20261016_0069",)command.downgrade(migrations.alembic_config(path), "20260907_0061")