~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(db): unblock multi-migration upgrades blocked by FK mismatch + orphan _alembic_tmp_* tables (#4000)
LearningCircuitc2a47a83b309
diff --git a/src/local_deep_research/database/alembic_runner.py b/src/local_deep_research/database/alembic_runner.pyindex e8f38d8352..32bf081def 100644--- a/src/local_deep_research/database/alembic_runner.py+++ b/src/local_deep_research/database/alembic_runner.py@@ -16,7 +16,7 @@ from alembic.config import Configfrom alembic.runtime.migration import MigrationContextfrom alembic.script import ScriptDirectoryfrom loguru import logger-from sqlalchemy import Engine, inspect+from sqlalchemy import Connection, Engine, inspectfrom sqlalchemy.exc import IntegrityError, OperationalError@@ -223,6 +223,80 @@ def stamp_database(engine: Engine, revision: str = "head") -> None:logger.info(f"Stamped database at revision: {revision}")+def _drop_orphan_alembic_temp_tables(conn: Connection) -> None:+ """Drop leftover ``_alembic_tmp_<table>`` tables from prior failed+ batch_alter_table runs (issue #3817).++ ``op.batch_alter_table`` rebuilds a table by creating+ ``_alembic_tmp_<table>``, copying data, dropping the original, and+ renaming. On a clean run alembic drops the temp table automatically.+ If a previous attempt failed in a way that bypassed transaction+ rollback (e.g., an older migration runner that auto-committed each+ migration, or a process killed mid-DDL on a non-transactional+ sqlite build), the temp table persists. The next attempt then fails+ at ``op.batch_alter_table`` with ``table _alembic_tmp_* already exists``.++ This runs in autocommit mode at the SQLite level — each ``DROP TABLE``+ briefly takes the file write lock and releases it. If a concurrent+ migration is mid-batch_alter_table on the same table, our DROP blocks+ on the SQLite write lock (busy_timeout=10000); by the time we+ acquire it, the concurrent migration's rename has consumed the temp+ table and our DROP IF EXISTS is a no-op. The race is benign.+ """+ inspector = inspect(conn)+ temp_tables = [+ name+ for name in inspector.get_table_names()+ if name.startswith("_alembic_tmp_")+ ]+ if not temp_tables:+ return+ logger.warning(+ f"Found {len(temp_tables)} orphan alembic temp table(s) from a "+ f"prior failed migration: {sorted(temp_tables)}. Dropping before retry."+ )+ for name in temp_tables:+ # Identifier is constrained to the ``_alembic_tmp_`` prefix + a+ # parent table name from ``inspector.get_table_names()``; both+ # come from the database's own catalog and cannot contain+ # injection vectors.+ conn.exec_driver_sql(f'DROP TABLE IF EXISTS "{name}"') # noqa: S608 # bearer:disable python_lang_sql_injection+++def _disable_fk_for_migration(conn: Connection) -> None:+ """Disable FK enforcement on the migration connection BEFORE any+ transaction opens (issue #3990).++ ``apply_performance_pragmas`` set ``PRAGMA foreign_keys = ON`` at+ connect. SQLite then *silently ignores* further toggles of+ ``foreign_keys`` once any transaction (explicit or driver-implicit)+ is active. The sqlite3/sqlcipher3 driver auto-begins on the first+ DML; PRAGMA itself isn't DML, so issuing the PRAGMA before any DML+ is the only window where it actually takes effect.++ With multi-migration upgrades (revision 0001 → 0009), the first+ migration to issue DML auto-begins the driver transaction and+ freezes FK in the connect-time ON state for the rest of the upgrade.+ That defeats migration 0007's defensive PRAGMA OFF and makes its+ orphan-scrub DELETE fail with ``foreign key mismatch`` on tables+ whose FK target lacks a UNIQUE backing — exactly the broken-schema+ state migration 0007 is meant to repair.++ The caller is responsible for re-enabling FK after the migration+ transaction commits, BEFORE returning the connection to the pool —+ see ``run_migrations``.+ """+ conn.exec_driver_sql("PRAGMA foreign_keys = OFF")+ # ``exec_driver_sql`` triggers SQLAlchemy autobegin even though no+ # sqlite-level transaction was opened (PRAGMA isn't DML, so the+ # driver doesn't auto-begin). Roll back the no-op SQLAlchemy+ # transaction so the caller's ``conn.begin()`` is allowed to start+ # a fresh one. ``PRAGMA foreign_keys`` is connection-level state and+ # survives ROLLBACK at the SQLite level — see+ # https://www.sqlite.org/pragma.html#pragma_foreign_keys.+ conn.rollback()++def run_migrations(engine: Engine, target: str = "head") -> None:"""Run pending migrations on a database.@@ -240,10 +314,17 @@ def run_migrations(engine: Engine, target: str = "head") -> None:- Migration directory path is within expected package boundary- Migration files are not world-writable- On failure, the transaction is automatically rolled back by- ``engine.begin()``'s context manager — the database stays at its- previous revision. The original exception is re-raised so callers- can decide how to handle it.+ Pre-upgrade hygiene (run outside the migration transaction):+ - Drop orphan ``_alembic_tmp_*`` tables from prior failed+ ``batch_alter_table`` runs (issue #3817).+ - Disable ``PRAGMA foreign_keys`` so 0007's orphan scrub can run+ (issue #3990). Re-enabled after a successful upgrade, before the+ connection returns to the pool.++ On failure inside the migration transaction, the inner+ ``conn.begin()`` rolls back automatically — the database stays at+ its previous revision. The original exception is re-raised so+ callers can decide how to handle it.Args:engine: SQLAlchemy engine to migrate@@ -346,9 +427,22 @@ def run_migrations(engine: Engine, target: str = "head") -> None:config = get_alembic_config(engine)try:- with engine.begin() as conn:- config.attributes["connection"] = conn- command.upgrade(config, target)+ with engine.connect() as conn:+ _drop_orphan_alembic_temp_tables(conn)+ _disable_fk_for_migration(conn)+ with conn.begin():+ config.attributes["connection"] = conn+ command.upgrade(config, target)+ # Re-enable FK on this connection BEFORE it returns to the+ # pool so subsequent checkouts see the production-default ON+ # state. The migration transaction has just committed, so we+ # are back outside any active transaction — PRAGMA toggles+ # work again. We can't rely on ``engine.dispose()`` to force+ # a fresh connection because engines built with ``creator=``+ # have ``url.database is None``, which fails the dispose+ # guard below and leaves FK=OFF leaking into the pool.+ conn.exec_driver_sql("PRAGMA foreign_keys = ON")+ conn.rollback()except Exception:logger.exception("Database migration failed — database remains at previous "@@ -356,14 +450,14 @@ def run_migrations(engine: Engine, target: str = "head") -> None:)raise- # Migrations may toggle connection-level PRAGMAs (e.g. 0007 disables- # foreign_keys to scrub the pre-fix download_tracker schema). PRAGMA- # changes inside a transaction cannot be reliably reverted from within- # the same transaction in SQLite, so we discard pooled connections after- # a successful upgrade. The next checkout will fire the connect-time- # ``apply_performance_pragmas`` hook and start with the production- # PRAGMA set. Skip for ``:memory:`` engines — those use a single shared- # connection and disposing it would destroy the just-migrated database.+ # Belt-and-suspenders: dispose pooled connections after a successful+ # upgrade. With FK explicitly re-enabled above this is no longer+ # load-bearing for FK state, but it forces the next checkout through+ # ``apply_performance_pragmas`` which also resets temp_store, cache_size,+ # journal_mode, etc. — protecting against any future migration that+ # touches connection-level PRAGMAs not handled by the FK fix-up.+ # Skip for ``:memory:`` engines — those use a single shared connection+ # and disposing it would destroy the just-migrated database.db_name = engine.url.databaseif db_name and db_name != ":memory:":engine.dispose()diff --git a/src/local_deep_research/database/migrations/versions/0007_backfill_missing_indexes.py b/src/local_deep_research/database/migrations/versions/0007_backfill_missing_indexes.pyindex 6b31c87d0e..78c0b6814e 100644--- a/src/local_deep_research/database/migrations/versions/0007_backfill_missing_indexes.py+++ b/src/local_deep_research/database/migrations/versions/0007_backfill_missing_indexes.py@@ -153,12 +153,18 @@ def upgrade() -> None:# SQLite raises ``foreign key mismatch`` on any DML touching a table whose# FK target column lacks a UNIQUE backing — which is exactly the pre-fix# state of every existing user DB this migration is meant to repair.- # Disable FK enforcement for the scrub + UNIQUE-index creation. PRAGMA- # ``foreign_keys`` lands here because no DML has opened the implicit- # transaction yet; once that happens, further toggles are silently- # ignored. ``alembic_runner.run_migrations`` disposes the connection pool- # after the upgrade commits, so the next checkout is a fresh connection- # with FK re-enabled by ``apply_performance_pragmas``.+ #+ # The actual FK toggle that takes effect is in+ # ``alembic_runner._disable_fk_for_migration``, run BEFORE the migration+ # transaction opens — SQLite silently ignores ``PRAGMA foreign_keys``+ # once any transaction is active, and earlier migrations in this same+ # upgrade chain may have already issued DML, auto-beginning the driver+ # transaction. Issuing the PRAGMA again here is a defensive belt-and-+ # suspenders no-op when the runner has already disabled FK; it preserves+ # the migration's contract for any caller that runs it outside the+ # standard ``run_migrations`` path. The runner re-enables FK on the+ # same connection after the upgrade commits, before returning the+ # connection to the pool.bind.execute(text("PRAGMA foreign_keys = OFF"))_scrub_download_tracker_duplicates(bind)diff --git a/tests/database/test_alembic_migrations.py b/tests/database/test_alembic_migrations.pyindex 9a3f355f2f..bf659a92a0 100644--- a/tests/database/test_alembic_migrations.py+++ b/tests/database/test_alembic_migrations.py@@ -4688,6 +4688,277 @@ class TestUpgradeFromBuggyV16xUserDatabase:)+class TestUpgradeFromBuggyV16xUserDbProductionEngine:+ """Regression for #3990 — multi-migration upgrade fails with FK mismatch.++ The existing ``TestUpgradeFromBuggyV16xUserDatabase`` covers the same+ schema corruption but stamps at revision 0006, so migration 0007 is the+ first to run any DML in the upgrade transaction — which lets 0007's+ own ``PRAGMA foreign_keys = OFF`` actually take effect (no auto-begun+ transaction yet).++ Real production users (issue #3990) upgrade from 0001 to head. Migrations+ 0002–0006 run DML before 0007, auto-beginning the sqlite3 driver+ transaction. ``PRAGMA foreign_keys`` is silently a no-op once a+ transaction is active (per sqlite.org/pragma.html#pragma_foreign_keys),+ so 0007's defensive PRAGMA never lands and the orphan-scrub DELETE+ fails with ``foreign key mismatch``.++ The fix (in ``alembic_runner.run_migrations``) issues PRAGMA OFF+ *before* opening the migration transaction. This test reproduces the+ production failure exactly: ``isolation_level=""`` (matching the+ sqlcipher3 engine in ``encrypted_db.py``) + FK ON at connect via the+ same event handler ``apply_performance_pragmas`` installs.+ """++ @pytest.fixture+ def buggy_v16x_production_engine(self, tmp_path):+ """Mirror the production engine: isolation_level="" + FK ON at+ connect, with the buggy v1.6.x schema stamped at revision 0005.++ Stamping at 0005 (not 0006) means migration 0006's data backfill+ (``UPDATE journals SET name_lower = ...``) runs DML before 0007,+ auto-beginning the driver transaction and freezing FK in the+ connect-time ON state for the rest of the upgrade.+ """+ import sqlite3++ from sqlalchemy import event++ db_path = tmp_path / "buggy_v16x_prod.db"+ # Seed the buggy v1.6.x schema with FK off (raw connection, no+ # FK target validation needed — the schema deliberately reflects+ # the pre-fix shape with no UNIQUE backing on download_tracker.url_hash).+ raw = sqlite3.connect(db_path)+ raw.execute("PRAGMA foreign_keys = OFF")+ raw.executescript(+ """+ CREATE TABLE alembic_version (version_num VARCHAR(32) PRIMARY KEY);+ INSERT INTO alembic_version VALUES ('0005');+ CREATE TABLE download_tracker (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ url TEXT NOT NULL,+ url_hash VARCHAR(64) NOT NULL,+ first_resource_id INTEGER,+ is_downloaded BOOLEAN,+ file_hash VARCHAR(64),+ file_path TEXT,+ file_name VARCHAR(255),+ file_size INTEGER,+ is_accessible BOOLEAN,+ first_seen TIMESTAMP,+ downloaded_at TIMESTAMP,+ last_checked TIMESTAMP,+ library_document_id INTEGER+ );+ CREATE TABLE download_attempts (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ url_hash VARCHAR(64) NOT NULL,+ attempt_number INTEGER,+ succeeded BOOLEAN,+ attempted_at TIMESTAMP,+ FOREIGN KEY (url_hash) REFERENCES download_tracker(url_hash)+ );+ CREATE TABLE download_duplicates (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ url_hash VARCHAR(64) NOT NULL,+ resource_id INTEGER,+ research_id VARCHAR(36),+ added_at TIMESTAMP,+ FOREIGN KEY (url_hash) REFERENCES download_tracker(url_hash)+ );+ CREATE TABLE journals (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ name VARCHAR(500) NOT NULL,+ quality INTEGER,+ quality_analysis_time TIMESTAMP+ );+ INSERT INTO journals (name, quality) VALUES ('Nature', 100), ('NATURE', 95);+ """+ )+ raw.execute(+ "INSERT INTO download_tracker (id, url, url_hash, first_resource_id) "+ "VALUES (1, 'a', 'HASH1', 1), (2, 'a-dup', 'HASH1', 2), (3, 'b', 'HASH2', 3)"+ )+ raw.execute(+ "INSERT INTO download_attempts (url_hash, attempt_number) "+ "VALUES ('HASH1', 1), ('HASH_ORPHAN', 1)"+ )+ raw.execute(+ "INSERT INTO download_duplicates (url_hash, resource_id, research_id) "+ "VALUES ('HASH_ORPHAN', 99, 'r1')"+ )+ raw.commit()+ raw.close()++ # Production-shape engine: deferred isolation_level + FK ON at connect.+ def _create_conn():+ conn = sqlite3.connect(+ str(db_path),+ isolation_level="",+ check_same_thread=False,+ )+ conn.execute("PRAGMA foreign_keys = ON")+ return conn++ engine = create_engine("sqlite://", creator=_create_conn)++ @event.listens_for(engine, "connect")+ def _enable_fk(dbapi_conn, _):+ # Defensive: also fire on any pooled re-checkouts that bypass+ # the creator (matches encrypted_db's apply_performance_pragmas).+ dbapi_conn.execute("PRAGMA foreign_keys = ON")++ yield engine+ engine.dispose()++ def test_run_migrations_succeeds_through_full_chain(+ self, buggy_v16x_production_engine+ ):+ """Without the runner-level FK toggle, this fails with+ ``foreign key mismatch`` at 0007's orphan scrub."""+ run_migrations(buggy_v16x_production_engine)+ assert (+ get_current_revision(buggy_v16x_production_engine)+ == get_head_revision()+ )++ with buggy_v16x_production_engine.connect() as conn:+ # FK is back ON for the next checkout (engine was disposed).+ assert conn.execute(text("PRAGMA foreign_keys")).scalar() == 1+ # No FK violations remain in the repaired DB.+ assert (+ conn.execute(text("PRAGMA foreign_key_check")).fetchall() == []+ )+ # Orphan rows were scrubbed.+ attempt_hashes = {+ r[0]+ for r in conn.execute(+ text("SELECT url_hash FROM download_attempts")+ ).fetchall()+ }+ assert attempt_hashes == {"HASH1"}+ duplicate_count = conn.execute(+ text("SELECT COUNT(*) FROM download_duplicates")+ ).scalar()+ assert duplicate_count == 0+++class TestOrphanAlembicTempTableCleanup:+ """Regression for #3817 — ``table _alembic_tmp_journals already exists``.++ ``op.batch_alter_table`` rebuilds a table by creating+ ``_alembic_tmp_<table>``, copying data, dropping the original, and+ renaming. On a clean run alembic drops the temp table automatically.+ If a previous attempt failed in a way that bypassed transaction+ rollback (e.g., an older runner that auto-committed each migration),+ the temp table persists. The next ``batch_alter_table`` on the same+ parent fails with ``table _alembic_tmp_* already exists`` — even if+ the broader transaction would roll it back, alembic checks for+ pre-existing temp tables before creating its own.++ The fix drops orphan ``_alembic_tmp_*`` tables in+ ``alembic_runner.run_migrations`` before opening the migration+ transaction.+ """++ @pytest.fixture+ def db_with_orphan_temp_table(self, tmp_path):+ """Build a buggy v1.6.x DB at revision 0005 with an orphan+ ``_alembic_tmp_journals`` table left over from a prior crash."""+ import sqlite3++ db_path = tmp_path / "with_orphan_tmp.db"+ raw = sqlite3.connect(db_path)+ raw.execute("PRAGMA foreign_keys = OFF")+ raw.executescript(+ """+ CREATE TABLE alembic_version (version_num VARCHAR(32) PRIMARY KEY);+ INSERT INTO alembic_version VALUES ('0005');+ CREATE TABLE download_tracker (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ url TEXT, url_hash VARCHAR(64) NOT NULL,+ first_resource_id INTEGER, is_downloaded BOOLEAN,+ file_hash VARCHAR(64), file_path TEXT, file_name VARCHAR(255),+ file_size INTEGER, is_accessible BOOLEAN,+ first_seen TIMESTAMP, downloaded_at TIMESTAMP,+ last_checked TIMESTAMP, library_document_id INTEGER+ );+ CREATE TABLE download_attempts (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ url_hash VARCHAR(64) NOT NULL,+ attempt_number INTEGER, succeeded BOOLEAN, attempted_at TIMESTAMP,+ FOREIGN KEY (url_hash) REFERENCES download_tracker(url_hash)+ );+ CREATE TABLE download_duplicates (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ url_hash VARCHAR(64) NOT NULL,+ resource_id INTEGER, research_id VARCHAR(36), added_at TIMESTAMP,+ FOREIGN KEY (url_hash) REFERENCES download_tracker(url_hash)+ );+ CREATE TABLE journals (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ name VARCHAR(500) NOT NULL,+ quality INTEGER,+ quality_analysis_time TIMESTAMP+ );+ -- The smoking gun: a leftover batch_alter_table temp table+ -- from a prior crashed migration attempt. The schema can be+ -- arbitrary — alembic only checks the name.+ CREATE TABLE _alembic_tmp_journals (+ id INTEGER PRIMARY KEY,+ stale_marker TEXT+ );+ """+ )+ raw.commit()+ raw.close()++ def _create_conn():+ conn = sqlite3.connect(+ str(db_path), isolation_level="", check_same_thread=False+ )+ conn.execute("PRAGMA foreign_keys = ON")+ return conn++ engine = create_engine("sqlite://", creator=_create_conn)+ yield engine+ engine.dispose()++ def test_run_migrations_drops_orphan_temp_table(+ self, db_with_orphan_temp_table+ ):+ """Without the cleanup, migration 0006's batch_alter_table fails+ with ``table _alembic_tmp_journals already exists``."""+ # Sanity check: the orphan is present before the run.+ with db_with_orphan_temp_table.connect() as conn:+ tables = {+ r[0]+ for r in conn.execute(+ text("SELECT name FROM sqlite_master WHERE type='table'")+ ).fetchall()+ }+ assert "_alembic_tmp_journals" in tables++ run_migrations(db_with_orphan_temp_table)++ assert (+ get_current_revision(db_with_orphan_temp_table)+ == get_head_revision()+ )++ # The orphan was dropped; alembic's own temp tables (if any from+ # this run) were also cleaned up by alembic itself.+ with db_with_orphan_temp_table.connect() as conn:+ tables_after = {+ r[0]+ for r in conn.execute(+ text("SELECT name FROM sqlite_master WHERE type='table'")+ ).fetchall()+ }+ assert not any(t.startswith("_alembic_tmp_") for t in tables_after)++class TestPreAlembicDatabaseHotfix:"""Regression tests for bug #3747 — pre-Alembic DB login failure.diff --git a/tests/database/test_no_raw_sql.py b/tests/database/test_no_raw_sql.pyindex 4737ec66a5..22a8e383ed 100644--- a/tests/database/test_no_raw_sql.py+++ b/tests/database/test_no_raw_sql.py@@ -29,6 +29,7 @@ def check_file_for_raw_sql(filepath):"thread_local_session.py","queue/processor.py","database/initialize.py", # Schema migrations using DDL+ "alembic_runner.py", # Migration runner: drops orphan _alembic_tmp_* tables (#3817), toggles foreign_keys (#3990)"auth_db.py", # SQLAlchemy DDL (CreateTable/CreateIndex), not raw SQL"backup_service.py", # SQLCipher ATTACH/DETACH/export operations"journal_quality/db.py", # Read-only SQLite DB build + PRAGMA user_version