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 the migration branch spliced behind live databases (#1556)
Call Whiteb69d287d32f6
diff --git a/storage/alembic/versions/20260725_0036_project_access_policies.py b/storage/alembic/versions/20260725_0036_project_access_policies.pyindex 60f1a8b18..5b3301b9e 100644--- a/storage/alembic/versions/20260725_0036_project_access_policies.py+++ b/storage/alembic/versions/20260725_0036_project_access_policies.py@@ -60,11 +60,16 @@ def upgrade() -> None:sa.PrimaryKeyConstraint("project_id"),sa.UniqueConstraint("scope_id", name="uq_project_access_policies_scope"),)- op.create_index(- "ix_project_access_policies_organization",- "project_access_policies",- ["organization_id"],- )+ # Outside the table guard on purpose. A run interrupted between the table and+ # its index leaves the table present, and a guard that covers both would then+ # skip the index forever -- permanently, once 20260819_0056 replays this+ # revision and stamps, because a stamped revision never runs again.+ op.create_index(+ "ix_project_access_policies_organization",+ "project_access_policies",+ ["organization_id"],+ if_not_exists=True,+ )tables = _tables(bind)if "project_access_bindings" not in tables:@@ -90,11 +95,12 @@ def upgrade() -> None:),sa.PrimaryKeyConstraint("project_id", "principal_kind", "principal_value"),)- op.create_index(- "ix_project_access_bindings_principal",- "project_access_bindings",- ["principal_kind", "principal_value"],- )+ op.create_index(+ "ix_project_access_bindings_principal",+ "project_access_bindings",+ ["principal_kind", "principal_value"],+ if_not_exists=True,+ )def downgrade() -> None:diff --git a/storage/alembic/versions/20260725_0037_media_object_references.py b/storage/alembic/versions/20260725_0037_media_object_references.pyindex bb4b004e4..b9e7d1534 100644--- a/storage/alembic/versions/20260725_0037_media_object_references.py+++ b/storage/alembic/versions/20260725_0037_media_object_references.py@@ -52,11 +52,16 @@ def upgrade() -> None:),sa.PrimaryKeyConstraint("token", "session_id"),)- op.create_index(- "ix_media_object_references_session",- "media_object_references",- ["session_id"],- )+ # Outside the table guard on purpose. A run interrupted between the table and+ # its index leaves the table present, and a guard that covers both would then+ # skip the index forever -- permanently, once 20260819_0056 replays this+ # revision and stamps, because a stamped revision never runs again.+ op.create_index(+ "ix_media_object_references_session",+ "media_object_references",+ ["session_id"],+ if_not_exists=True,+ )bind.exec_driver_sql("""diff --git a/storage/alembic/versions/20260725_0038_remote_access_authorizations.py b/storage/alembic/versions/20260725_0038_remote_access_authorizations.pyindex 9f9d1e0e8..f50ac64c6 100644--- a/storage/alembic/versions/20260725_0038_remote_access_authorizations.py+++ b/storage/alembic/versions/20260725_0038_remote_access_authorizations.py@@ -26,22 +26,26 @@ def _tables(bind) -> set[str]:def upgrade() -> None:- if "remote_access_authorizations" in _tables(op.get_bind()):- return- op.create_table(- "remote_access_authorizations",- sa.Column("id", sa.String(), nullable=False),- sa.Column("instance_id", sa.String(), nullable=False),- sa.Column("subject", sa.String(), nullable=False),- sa.Column("claims_json", sa.Text(), nullable=False),- sa.Column("expires_at", sa.Integer(), nullable=False),- sa.Column("created_at", sa.Integer(), nullable=False),- sa.PrimaryKeyConstraint("id"),- )+ if "remote_access_authorizations" not in _tables(op.get_bind()):+ op.create_table(+ "remote_access_authorizations",+ sa.Column("id", sa.String(), nullable=False),+ sa.Column("instance_id", sa.String(), nullable=False),+ sa.Column("subject", sa.String(), nullable=False),+ sa.Column("claims_json", sa.Text(), nullable=False),+ sa.Column("expires_at", sa.Integer(), nullable=False),+ sa.Column("created_at", sa.Integer(), nullable=False),+ sa.PrimaryKeyConstraint("id"),+ )+ # Outside the table guard on purpose -- this revision used to return early on+ # the table alone, which made the index unreachable in exactly the state that+ # needs it. A run interrupted between the two leaves the table present and the+ # index missing, and 20260819_0056 would then stamp over it permanently.op.create_index("ix_remote_access_authorizations_expires","remote_access_authorizations",["expires_at"],+ if_not_exists=True,)diff --git a/storage/alembic/versions/20260815_0054_remote_authorization_context.py b/storage/alembic/versions/20260815_0054_remote_authorization_context.pyindex ed59ba035..a1e5ef8f8 100644--- a/storage/alembic/versions/20260815_0054_remote_authorization_context.py+++ b/storage/alembic/versions/20260815_0054_remote_authorization_context.py@@ -25,6 +25,18 @@ def _columns() -> set[str]:}+def _table_exists() -> bool:+ return (+ op.get_bind()+ .exec_driver_sql(+ "select 1 from sqlite_master "+ "where type = 'table' and name = 'remote_access_authorizations'"+ )+ .first()+ is not None+ )++def _indexes() -> set[str]:return {str(row[1])@@ -35,6 +47,15 @@ def _indexes() -> set[str]:def upgrade() -> None:+ if not _table_exists():+ # The creating revision, 20260725_0038, sits on one side of the fork at+ # 20260724_0034. A database that reached the 20260804_0047 merge along the+ # other side crossed it with that side marked applied and its tables never+ # created, so this revision arrives with nothing to alter. Aborting here+ # strands such a database below head forever and takes every caller of+ # ensure_sqlite_state down with it; 20260819_0056 restores the table.+ return+columns = _columns()additions = (("email", sa.String()),@@ -82,6 +103,8 @@ def upgrade() -> None:def downgrade() -> None:+ if not _table_exists():+ returnif "ux_remote_access_authorizations_scope" in _indexes():op.drop_index("ux_remote_access_authorizations_scope",diff --git a/storage/alembic/versions/20260819_0056_repair_unapplied_branch_schema.py b/storage/alembic/versions/20260819_0056_repair_unapplied_branch_schema.pynew file mode 100644index 000000000..b6621c40f--- /dev/null+++ b/storage/alembic/versions/20260819_0056_repair_unapplied_branch_schema.py@@ -0,0 +1,105 @@+"""create the schema of a merged branch that was never applied++Revision ID: 20260819_0056+Revises: 20260817_0055+Create Date: 2026-08-19+"""++from __future__ import annotations++import importlib.util+from pathlib import Path+from types import ModuleType++from alembic import op++revision = "20260819_0056"+down_revision = "20260817_0055"+branch_labels = None+depends_on = None++# 20260724_0034 forks. One side creates the local access-control and remote+# authorization tables below; the other ends at 20260804_0046. 20260804_0047 merges+# them. A database that reached the merge along the other side alone crossed it with+# this side's revisions recorded as applied and its tables never created, and Alembic+# will not walk back below a merge it has passed. The gap stayed dormant until+# 20260815_0054 tried to alter one of the missing tables, which aborts the whole+# upgrade: those installs are pinned below head and every caller of+# ``ensure_sqlite_state`` fails, including the login that writes an authorization.+_UNAPPLIED_BRANCH = (+ "20260725_0035_resource_access_policies",+ "20260725_0036_project_access_policies",+ "20260725_0037_media_object_references",+ "20260725_0038_remote_access_authorizations",+ # Replayed last so a table restored above reaches the shape head expects+ # rather than the shape it had in July.+ "20260815_0054_remote_authorization_context",+)++_BRANCH_TABLES = (+ "resource_access_policies",+ "resource_access_groups",+ "project_access_policies",+ "project_access_bindings",+ "media_object_references",+ "remote_access_authorizations",+)+++def _revision_module(stem: str) -> ModuleType:+ path = Path(__file__).with_name(f"{stem}.py")+ spec = importlib.util.spec_from_file_location(f"_replay_{stem}", path)+ if spec is None or spec.loader is None: # pragma: no cover - packaging accident+ raise RuntimeError(f"cannot load migration {stem} for replay")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def _missing_tables() -> set[str]:+ present = {+ str(row[0])+ for row in op.get_bind().exec_driver_sql(+ "select name from sqlite_master where type = 'table'"+ )+ }+ return {table for table in _BRANCH_TABLES if table not in present}+++def upgrade() -> None:+ # Replayed unconditionally: presence is not completeness. A repair interrupted+ # after 20260725_0038 recreated remote_access_authorizations but before+ # 20260815_0054 replayed leaves all six tables present and that one short of+ # head, with Alembic still stamped below this revision. Skipping the replay on+ # "every table is there" would stamp 0056 over the short table, and a stamped+ # revision never runs again. Every revision below is already a no-op against the+ # objects it finds in place, so replaying always costs a few introspection+ # queries on the single upgrade that crosses this revision and removes the guess.+ #+ # Replay rather than copy their DDL: the repaired schema then equals a fresh+ # install's by construction instead of by a duplicate definition that can drift.+ for stem in _UNAPPLIED_BRANCH:+ _revision_module(stem).upgrade()++ # Replaying is not the same as repairing. 20260725_0037 returns silently when+ # media_objects or agent_sessions is absent, and a revision added to the branch+ # later can grow its own precondition, so the replay can leave a table behind+ # while reporting nothing. Failing here keeps the database below head, where the+ # next upgrade retries the repair; stamping this revision instead would record a+ # half-repaired schema as complete and surface it later as an unattributable+ # error at whichever call site touches the table that was never created.+ unrepaired = _missing_tables()+ if unrepaired:+ raise RuntimeError(+ "replaying the unapplied branch left these tables missing: "+ f"{', '.join(sorted(unrepaired))}; a replayed revision skipped itself "+ "because one of its preconditions is absent from this database"+ )+++def downgrade() -> None:+ # Deliberately empty. This revision creates only what is already missing, and+ # everything it creates is owned by revisions below it. Dropping those tables+ # here would delete the authorization and access-policy rows that a correctly+ # migrated database has held since July.+ returndiff --git a/storage/db.py b/storage/db.pyindex d6fc0525c..22b2d1220 100644--- a/storage/db.py+++ b/storage/db.py@@ -32,7 +32,16 @@ def sqlite_url(db_path: Path | None = None) -> str:def create_sqlite_engine(db_path: Path | None = None) -> Engine:path = _resolve_sqlite_path(db_path)path.parent.mkdir(parents=True, exist_ok=True)- engine = create_engine(sqlite_url(path), future=True)+ # ``hide_parameters`` keeps bound values out of ``str(exc)`` on every+ # SQLAlchemy error. Those values are the user's identity and access-control+ # data -- emails, subjects, instance and scope ids, serialized authorization+ # claims -- and any caller that logs a database failure with a traceback+ # otherwise writes them into the unrotated service log. Owning it here rather+ # than at each log site is what makes that true for callers not yet written:+ # this is the only ``create_engine`` in the codebase, so every engine+ # inherits it. The statement text, the traceback, and the underlying sqlite3+ # error all survive, which is what a diagnostic actually needs.+ engine = create_engine(sqlite_url(path), future=True, hide_parameters=True)@event.listens_for(engine, "connect")def _set_sqlite_pragmas(dbapi_connection, _connection_record) -> None:diff --git a/tests/test_oauth_callback_diagnostics.py b/tests/test_oauth_callback_diagnostics.pynew file mode 100644index 000000000..20be004eb--- /dev/null+++ b/tests/test_oauth_callback_diagnostics.py@@ -0,0 +1,139 @@+"""The OAuth callback keeps its failure cause attributable.++The callback is reachable without auth, so the error page deliberately says+almost nothing. That left the service log as the only place a real cause could+survive — and it did not: an internal fault reached both surfaces as a bare+exception class name, so `database is locked`, `disk I/O error`, and+`attempt to write a readonly database` were indistinguishable from each other+and from a bug.+"""++from __future__ import annotations++import logging+import sqlite3+from pathlib import Path++import pytest+from sqlalchemy import text++from storage.db import create_sqlite_engine+from vibe import remote_access, ui_server++[email protected](autouse=True)+def _clear_diag_rate_limit():+ ui_server._oauth_diag_log_state.clear()+ yield+ ui_server._oauth_diag_log_state.clear()+++def _warnings(caplog: pytest.LogCaptureFixture) -> list[logging.LogRecord]:+ return [record for record in caplog.records if record.levelno == logging.WARNING]+++def test_unexpected_failure_logs_the_real_cause(caplog: pytest.LogCaptureFixture) -> None:+ exc = sqlite3.OperationalError("database is locked")++ with caplog.at_level(logging.WARNING, logger=ui_server.logger.name):+ ui_server._log_oauth_callback_failure("session_cookie", exc)++ (record,) = _warnings(caplog)+ assert record.exc_info is not None+ assert "database is locked" in caplog.text+ assert "session_cookie" in record.getMessage()+++def test_expected_failure_logs_no_traceback(caplog: pytest.LogCaptureFixture) -> None:+ # An unauthenticated caller can produce this at will, and it already carries+ # its own reason and detail. A traceback per bad code is noise, not signal.+ exc = remote_access.OAuthCodeExchangeError("invalid_grant", "code already redeemed")++ with caplog.at_level(logging.WARNING, logger=ui_server.logger.name):+ ui_server._log_oauth_callback_failure("code_exchange", exc)++ (record,) = _warnings(caplog)+ assert record.exc_info is None+ assert "invalid_grant" in record.getMessage()+++def test_bad_codes_cannot_suppress_an_internal_fault(caplog: pytest.LogCaptureFixture) -> None:+ # Both branches once shared one rate-limit budget, so a flood of rejected+ # codes could swallow the one line naming a real fault. Each stage and kind+ # of failure gets its own budget instead.+ with caplog.at_level(logging.WARNING, logger=ui_server.logger.name):+ for _ in range(5):+ ui_server._log_oauth_callback_failure(+ "code_exchange", remote_access.OAuthCodeExchangeError("invalid_grant")+ )+ ui_server._log_oauth_callback_failure("code_exchange", sqlite3.OperationalError("disk I/O error"))+ ui_server._log_oauth_callback_failure("session_cookie", sqlite3.OperationalError("database is locked"))++ emitted = [record.getMessage() for record in _warnings(caplog)]+ # One rejected-code line (the rest are rate-limited away), plus both faults.+ assert len(emitted) == 3+ assert "disk I/O error" in caplog.text+ assert "database is locked" in caplog.text+++def test_repeat_of_the_same_failure_is_still_rate_limited(caplog: pytest.LogCaptureFixture) -> None:+ # The callback is unauthenticated and the service log is unrotated, so the+ # per-key budget has to survive the split above.+ with caplog.at_level(logging.WARNING, logger=ui_server.logger.name):+ for _ in range(4):+ ui_server._log_oauth_callback_failure("session_cookie", sqlite3.OperationalError("database is locked"))++ assert len(_warnings(caplog)) == 1+++def test_database_failure_logs_its_cause_without_the_bound_values(+ tmp_path: Path, caplog: pytest.LogCaptureFixture+) -> None:+ # Restoring the traceback made the log useful and, on a SQLAlchemy failure,+ # also made it a place the user's identity data gets written: a StatementError+ # renders its bound parameters into str(exc), and this callback binds the+ # subject and email it is in the middle of authenticating. The log is+ # unrotated and world-readable to anything on the machine, so the diagnostic+ # must keep the statement and the driver's reason and drop the values. Build+ # the failure from a real engine rather than a hand-made exception, so this+ # tracks how engines are actually configured instead of restating it.+ engine = create_sqlite_engine(tmp_path / "vibe.sqlite")+ secret = "[email protected]"+ try:+ with engine.connect() as conn:+ conn.execute(+ text("insert into remote_access_authorizations (subject) values (:subject)"),+ {"subject": secret},+ )+ except Exception as caught: # noqa: BLE001 - the failure is the fixture+ exc = caught+ finally:+ engine.dispose()++ with caplog.at_level(logging.WARNING, logger=ui_server.logger.name):+ ui_server._log_oauth_callback_failure("session_cookie", exc)++ (record,) = _warnings(caplog)+ assert record.exc_info is not None+ assert secret not in caplog.text+ # The value is gone; everything that makes the line actionable is not.+ assert "no such table" in caplog.text+ assert "remote_access_authorizations" in caplog.text+ # Pin it on the exception too, so a caller that renders it some other way --+ # a future log site, a bug report, an error path not yet written -- inherits+ # the same guarantee rather than having to remember to strip it.+ assert secret not in str(exc)+++def test_error_page_diagnostics_never_carry_the_traceback() -> None:+ # The log gets the cause; the unauthenticated page still gets only the class+ # name. This is the boundary the fix must not move.+ exc = sqlite3.OperationalError("attempt to write a readonly database")++ error, diagnostics = ui_server._oauth_exchange_error_diagnostics(exc)+ rendered = ui_server._oauth_error_diagnostics_text({"error": error} | diagnostics)++ assert error == "oauth_exchange_failed"+ assert diagnostics == {"reason": "OperationalError"}+ assert "readonly" not in rendered+ assert "Traceback" not in rendereddiff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex 1126927b0..4f6f67724 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -31,7 +31,7 @@ from vibe.message_types import build_partial_index_predicatepytestmark = pytest.mark.no_sqlite_template-HEAD_REVISION = "20260817_0055"+HEAD_REVISION = "20260819_0056"MESSAGE_PARTIAL_INDEX_PREDICATES = {"ix_messages_inbox_activity": ("session_id is not null and type in "@@ -608,6 +608,251 @@ def test_alembic_script_directory_has_exactly_one_head() -> None:assert heads[0] == HEAD_REVISION+# v3.0.11 added a branch under 20260724_0034 plus the 20260804_0047 merge, and+# repointed 20260806_0047 from 20260804_0046 onto that merge. 20260806_0047 shipped+# in v3.0.9, so every database already live had passed it. Alembic only walks+# forward from the revision a database is on and never applies an ancestor+# inserted behind it, so the whole branch was recorded as applied and none of its+# tables were ever created.+_SPLICE_POINT_REVISION = "20260806_0047"+_SPLICED_MERGE_REVISION = "20260804_0047"+_REPAIR_REVISION = "20260819_0056"+# Created by 20260725_0038 on the spliced branch and widened by 20260815_0054, so a+# replay interrupted between the two leaves it present and short of head.+_INTERRUPTED_TABLE = "remote_access_authorizations"+++def _schema_of(db_path: Path) -> set[tuple[str, str, str]]:+ with sqlite3.connect(db_path) as conn:+ return {+ (str(kind), str(name), re.sub(r"\s+", " ", str(sql or "")).strip())+ for kind, name, sql in conn.execute(+ "select type, name, sql from sqlite_master "+ "where name not like 'sqlite_%' and name != 'alembic_version'"+ )+ }+++def _upgraded_db(db_path: Path, revision: str) -> Path:+ command.upgrade(migrations.alembic_config(db_path), revision)+ return db_path+++def _revisions_the_repair_must_cover() -> list[str]:+ """Every released revision a database can still be sitting on below the repair.++ Read from the script directory rather than written down, so a revision added+ after this one is covered without editing the test.+ """++ script = ScriptDirectory.from_config(migrations.alembic_config())+ return [+ revision.revision+ for revision in script.iterate_revisions(+ _REPAIR_REVISION, _SPLICE_POINT_REVISION, inclusive=True+ )+ if revision.revision != _REPAIR_REVISION+ ]+++def test_repair_completes_a_replay_interrupted_between_two_branch_revisions(+ tmp_path: Path,+) -> None:+ # Every branch table being present does not mean the branch was applied. A repair+ # interrupted after 20260725_0038 recreated the table but before 20260815_0054+ # replayed leaves all six tables there, that one short of head, and Alembic still+ # stamped below the repair. Skipping the replay on a table-presence check would+ # stamp the repair over the short table, and a stamped revision never runs again:+ # the columns would then be missing for the life of the database.+ expected = {obj for obj in _schema_of(_upgraded_db(tmp_path / "fresh.sqlite", "head")) if obj[1] == _INTERRUPTED_TABLE}+ assert expected, "the interrupted table must exist at head"++ # Take the interrupted shape from the revision that creates it instead of writing+ # its DDL down here, so this stays the real pre-20260815_0054 table.+ scratch = _upgraded_db(tmp_path / "scratch.sqlite", _SPLICED_MERGE_REVISION)+ with sqlite3.connect(scratch) as conn:+ interrupted_ddl = [+ str(sql)+ for (sql,) in conn.execute(+ "select sql from sqlite_master where tbl_name = ? and sql is not null",+ (_INTERRUPTED_TABLE,),+ )+ ]+ assert interrupted_ddl++ db_path = _upgraded_db(tmp_path / "interrupted.sqlite", "20260817_0055")+ with sqlite3.connect(db_path) as conn:+ conn.execute("pragma foreign_keys = off")+ conn.execute(f'drop table "{_INTERRUPTED_TABLE}"')+ for statement in interrupted_ddl:+ conn.execute(statement)+ conn.commit()+ assert not expected <= _schema_of(db_path), "the seeded database must really be short of head"++ command.upgrade(migrations.alembic_config(db_path), "head")++ missing = expected - _schema_of(db_path)+ assert not missing, f"the repair left an interrupted table short of head: {sorted(missing)}"+ with sqlite3.connect(db_path) as conn:+ assert conn.execute("select version_num from alembic_version").fetchall() == [+ (HEAD_REVISION,)+ ]+++def test_repair_restores_branch_indexes_whose_tables_survived(tmp_path: Path) -> None:+ # A table is not the unit of interruption; a schema object is. Each branch+ # revision creates its table and then its index as two statements, so a run+ # interrupted between them leaves the table present and the index missing --+ # and a guard covering both reads the table as proof that neither is needed.+ # That state is exactly the one the repair exists to fix, and it is also the+ # one where skipping is permanent: the repair stamps, and a stamped revision+ # never runs again. Derive the objects from the two sides of the merge rather+ # than naming them, so an index added to the branch later is covered here+ # without editing the test.+ reference = _schema_of(_upgraded_db(tmp_path / "fresh.sqlite", "head"))+ without_branch = _schema_of(_upgraded_db(tmp_path / "pre-merge.sqlite", "20260804_0046"))+ with_branch = _schema_of(_upgraded_db(tmp_path / "merged.sqlite", _SPLICED_MERGE_REVISION))+ branch_names = {name for _, name, _ in with_branch} - {name for _, name, _ in without_branch}+ branch_indexes = {name for kind, name, _ in with_branch if kind == "index"} & branch_names+ assert branch_indexes, "the spliced branch must own at least one index"+ expected = {obj for obj in reference if obj[1] in branch_names}++ db_path = _upgraded_db(tmp_path / "indexless.sqlite", "20260817_0055")+ with sqlite3.connect(db_path) as conn:+ for name in sorted(branch_indexes):+ conn.execute(f'drop index "{name}"')+ conn.commit()+ surviving = {name for _, name, _ in _schema_of(db_path)}+ assert not branch_indexes & surviving, "the seeded database must really be missing the indexes"+ assert {name for kind, name, _ in with_branch if kind == "table"} & branch_names <= surviving, (+ "only the indexes may be missing -- a dropped table would let the table guard "+ "recreate the index and the test would pass without proving anything"+ )++ command.upgrade(migrations.alembic_config(db_path), "head")++ missing = expected - _schema_of(db_path)+ assert not missing, f"the repair left branch objects short of a fresh install: {sorted(missing)}"+ with sqlite3.connect(db_path) as conn:+ assert conn.execute("select version_num from alembic_version").fetchall() == [+ (HEAD_REVISION,)+ ]+++def test_replaying_the_branch_over_a_healthy_database_changes_nothing(tmp_path: Path) -> None:+ # The repair replays unconditionally, so every database that reaches head replays+ # the branch over a schema that already has it -- including the backfill in+ # 20260725_0037, which writes rows rather than DDL. That is only safe while every+ # replayed revision is a no-op against what it finds, so pin exactly that: same+ # schema, and a row the backfill would otherwise duplicate or overwrite left alone.+ db_path = _upgraded_db(tmp_path / "healthy.sqlite", "20260817_0055")+ with sqlite3.connect(db_path) as conn:+ conn.execute(+ "insert into media_objects (token, session_id, kind, source, local_path, created_at) "+ "values ('tok', 'ses', 'image', 'agent', '/tmp/tok.png', 'created')"+ )+ conn.execute(+ "insert into media_object_references (token, session_id, created_at) "+ "values ('tok', 'ses', 'original')"+ )+ conn.commit()+ before = _schema_of(db_path)++ command.upgrade(migrations.alembic_config(db_path), "head")++ assert _schema_of(db_path) == before+ with sqlite3.connect(db_path) as conn:+ assert conn.execute(+ "select token, session_id, created_at from media_object_references"+ ).fetchall() == [("tok", "ses", "original")]+ assert conn.execute("select version_num from alembic_version").fetchall() == [+ (HEAD_REVISION,)+ ]+++def test_repair_refuses_to_stamp_a_schema_it_could_not_restore(tmp_path: Path) -> None:+ # Two of the replayed revisions return silently when a table they reference is+ # absent, so "the replay ran" does not mean "the schema is repaired". The repair+ # must fail rather than record itself as applied over a schema that is still+ # short: a stamped half-repair can never re-run, and resurfaces later as an+ # unattributable error at whichever call site touches the missing table.+ db_path = _upgraded_db(tmp_path / "short.sqlite", "20260817_0055")+ with sqlite3.connect(db_path) as conn:+ conn.execute("pragma foreign_keys = off")+ for table in ("media_object_references", "media_objects"):+ conn.execute(f'drop table if exists "{table}"')+ conn.commit()++ with pytest.raises(RuntimeError, match="left these tables missing: media_object_references"):+ command.upgrade(migrations.alembic_config(db_path), "head")++ with sqlite3.connect(db_path) as conn:+ # Still below head, so the next upgrade retries the repair instead of+ # skipping it forever.+ assert conn.execute("select version_num from alembic_version").fetchall() == [+ ("20260817_0055",)+ ]+++def test_spliced_branch_schema_is_restored_from_every_released_revision(tmp_path: Path) -> None:+ # The property: whatever released revision a database is on, upgrading to head+ # leaves every schema object the spliced branch owns in the shape a fresh install+ # has. Deriving that set from the two sides of the merge, instead of sharing a+ # hand-written list with the migration, means a table added to the branch later+ # cannot fall out of both at once.+ reference = _schema_of(_upgraded_db(tmp_path / "fresh.sqlite", "head"))+ without_branch = _schema_of(_upgraded_db(tmp_path / "pre-merge.sqlite", "20260804_0046"))+ with_branch = _schema_of(_upgraded_db(tmp_path / "merged.sqlite", _SPLICED_MERGE_REVISION))++ # Compare by name: an object's recorded DDL text also varies with the rebuild+ # path a table took, which says nothing about who created it.+ branch_names = {name for _, name, _ in with_branch} - {name for _, name, _ in without_branch}+ branch_tables = {name for kind, name, _ in with_branch if kind == "table"} & branch_names+ expected = {obj for obj in reference if obj[1] in branch_names}+ assert branch_tables, "the spliced branch must own at least one table"+ assert expected, "the branch's objects must survive to head"++ # The repair's postcondition reads a literal tuple, because a migration cannot+ # learn what its replayed revisions create without running them. Pin that tuple to+ # two derivations it does not share: the merge boundary above, and the head table+ # set the rest of the codebase maintains. A table added to the branch later then+ # fails here, instead of slipping past the postcondition meant to catch it.+ script = ScriptDirectory.from_config(migrations.alembic_config())+ declared = set(script.get_revision(_REPAIR_REVISION).module._BRANCH_TABLES)+ assert declared == branch_tables+ assert declared <= migrations.HEAD_TABLES++ revisions = _revisions_the_repair_must_cover()+ assert _SPLICE_POINT_REVISION in revisions++ for seeded in revisions:+ db_path = tmp_path / f"stuck-{seeded}.sqlite"+ _upgraded_db(db_path, seeded)+ # Reproduce the splice rather than the fork: this database reached its+ # revision under a release where the branch did not exist at all.+ with sqlite3.connect(db_path) as conn:+ conn.execute("pragma foreign_keys = off")+ for table in branch_tables:+ conn.execute(f'drop table if exists "{table}"')+ conn.execute(+ "insert into state_meta (key, value_json, updated_at) "+ "values ('default_agent_name', '\"kept\"', 'before-upgrade')"+ )+ conn.commit()++ command.upgrade(migrations.alembic_config(db_path), "head")++ missing = expected - _schema_of(db_path)+ assert not missing, f"repair left {seeded} short of a fresh install: {sorted(missing)}"+ with sqlite3.connect(db_path) as conn:+ assert conn.execute(+ "select value_json from state_meta where key = 'default_agent_name'"+ ).fetchone() == ('"kept"',)+ assert conn.execute("select version_num from alembic_version").fetchall() == [+ (HEAD_REVISION,)+ ]++def test_message_transcript_order_upgrade_normalizes_and_indexes_exact_time(tmp_path: Path,) -> None:diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex e6b2a8e4d..7c702306a 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -2151,7 +2151,7 @@ _oauth_diag_log_lock = threading.Lock()_oauth_diag_log_state: dict[str, list[float]] = {}-def _log_oauth_diag(key: str, message: str, *args: Any) -> None:+def _log_oauth_diag(key: str, message: str, *args: Any, exc_info: BaseException | None = None) -> None:"""Emit an unauthenticated-reachable OAuth diagnostic at WARNING, rate-limitedper ``key`` (~once / ``_OAUTH_DIAG_LOG_INTERVAL_SECONDS``).@@ -2167,7 +2167,34 @@ def _log_oauth_diag(key: str, message: str, *args: Any) -> None:return_oauth_diag_log_state[key] = [now, 0]extra = f" [+{int(suppressed)} suppressed in {int(_OAUTH_DIAG_LOG_INTERVAL_SECONDS)}s]" if suppressed else ""- logger.warning(message + extra, *args)+ logger.warning(message + extra, *args, exc_info=exc_info)+++def _log_oauth_callback_failure(stage: str, exc: BaseException) -> None:+ """Log one failed OAuth callback stage so the cause stays attributable.++ ``OAuthCodeExchangeError`` is the expected shape: it carries its own reason+ and detail, and any unauthenticated caller can produce one at will. Anything+ else is a bug or an environment fault (a locked, full, or read-only database+ all arrive as a bare ``OperationalError``) whose only remaining description+ is the traceback. Those get one — in the service log, never in the response,+ which still exposes just the exception class name — plus a rate-limit budget+ of their own, so a flood of bad codes cannot suppress the line that matters.+ """++ from vibe import remote_access++ expected = isinstance(exc, remote_access.OAuthCodeExchangeError)+ reason = exc.reason if expected else exc.__class__.__name__+ _log_oauth_diag(+ f"{stage}_{'rejected' if expected else 'error'}",+ "vibe cloud oauth %s failed: reason=%s",+ stage,+ reason,+ # The exception object, not ``True``: ``True`` reads ambient+ # ``sys.exc_info()`` and silently logs nothing outside a live handler.+ exc_info=None if expected else exc,+ )def _oauth_callback_error_response(@@ -6876,8 +6903,7 @@ def remote_access_auth_callback():next_target = _strip_show_page_reauth_param(next_target)except Exception as exc:# Unauthenticated-reachable (valid handshake + bad code), so rate-limited.- reason = exc.reason if isinstance(exc, remote_access.OAuthCodeExchangeError) else exc.__class__.__name__- _log_oauth_diag("exchange_failed", "vibe cloud oauth code exchange failed: reason=%s", reason)+ _log_oauth_callback_failure("code_exchange", exc)error, diagnostics = _oauth_exchange_error_diagnostics(exc)return _oauth_callback_error_response(error, next_target=next_target, diagnostics=diagnostics)if claims.get("nonce") != handshake_nonce:@@ -6890,8 +6916,7 @@ def remote_access_auth_callback():session_claims=session_claims,)except Exception as exc:- reason = exc.reason if isinstance(exc, remote_access.OAuthCodeExchangeError) else exc.__class__.__name__- _log_oauth_diag("exchange_failed", "vibe cloud session cookie creation failed: reason=%s", reason)+ _log_oauth_callback_failure("session_cookie", exc)error, diagnostics = _oauth_exchange_error_diagnostics(exc)return _oauth_callback_error_response(error, next_target=next_target, diagnostics=diagnostics)response = Response(status=302)