Skip to content

~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.

Fix/createindex and download tracker fk (#3717)

LearningCircuitd50083bd549f
diff --git a/src/local_deep_research/database/alembic_runner.py b/src/local_deep_research/database/alembic_runner.py
index 4c21f9257c..95e01b155a 100644
--- a/src/local_deep_research/database/alembic_runner.py
+++ b/src/local_deep_research/database/alembic_runner.py
@@ -275,6 +275,18 @@ 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.
+ db_name = engine.url.database
+ if db_name and db_name != ":memory:":
+ engine.dispose()
+
new_revision = get_current_revision(engine)
elapsed_ms = (time.perf_counter() - migration_start) * 1000
if current != new_revision:
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.py
index f639b72bb2..6b31c87d0e 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
@@ -150,6 +150,17 @@ def _backfill_model_indexes(bind) -> None:
def upgrade() -> None:
bind = op.get_bind()
+ # 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``.
+ bind.execute(text("PRAGMA foreign_keys = OFF"))
+
_scrub_download_tracker_duplicates(bind)
_scrub_orphan_children(bind)
diff --git a/src/local_deep_research/database/models/download_tracker.py b/src/local_deep_research/database/models/download_tracker.py
index ebb1179177..922d54bd5a 100644
--- a/src/local_deep_research/database/models/download_tracker.py
+++ b/src/local_deep_research/database/models/download_tracker.py
@@ -31,8 +31,8 @@ class DownloadTracker(Base):
# URL tracking
url = Column(Text, nullable=False) # Original URL
url_hash = Column(
- String(64), nullable=False, index=True
- ) # SHA256 of normalized URL
+ String(64), nullable=False
+ ) # SHA256 of normalized URL — UNIQUE backing comes from __table_args__
# Resource tracking (can be multiple resources with same URL)
first_resource_id = Column(
diff --git a/tests/database/models/test_download_tracker_models.py b/tests/database/models/test_download_tracker_models.py
index ec34032146..c25c048529 100644
--- a/tests/database/models/test_download_tracker_models.py
+++ b/tests/database/models/test_download_tracker_models.py
@@ -5,7 +5,7 @@ Tests model structure, column constraints, default values, and __repr__ methods
WITHOUT requiring a real database -- uses direct attribute assignment on model instances.
"""
-from sqlalchemy import Boolean, Integer, String, Text
+from sqlalchemy import Boolean, Integer, String, Text, UniqueConstraint
from local_deep_research.database.models.download_tracker import (
DownloadAttempt,
@@ -54,13 +54,23 @@ class TestDownloadTrackerColumns:
assert isinstance(col.type, Text)
assert col.nullable is False
- def test_url_hash_is_string64_not_nullable_unique_indexed(self):
+ def test_url_hash_is_string64_not_nullable_with_table_level_unique(self):
col = _col(DownloadTracker, "url_hash")
assert isinstance(col.type, String)
assert col.type.length == 64
assert col.nullable is False
- assert col.unique is True
- assert col.index is True
+ # Uniqueness lives on a table-level UniqueConstraint named
+ # ``uq_download_tracker_url_hash`` (see model __table_args__) so the
+ # index lands inline in CREATE TABLE — required so SQLCipher accepts
+ # ``url_hash`` as a valid FK target for the child tables. Column-level
+ # ``unique=True``/``index=True`` would emit a separate CREATE UNIQUE
+ # INDEX which SQLCipher does not recognise as the FK target.
+ unique_cols = {
+ tuple(c.name for c in constraint.columns)
+ for constraint in DownloadTracker.__table__.constraints
+ if isinstance(constraint, UniqueConstraint)
+ }
+ assert ("url_hash",) in unique_cols
def test_first_resource_id_is_integer_not_nullable(self):
col = _col(DownloadTracker, "first_resource_id")
@@ -120,7 +130,11 @@ class TestDownloadTrackerColumns:
def test_library_document_id_is_nullable_with_fk(self):
col = _col(DownloadTracker, "library_document_id")
- assert isinstance(col.type, Integer)
+ # documents.id is String(36) UUID; column type matches PK type so
+ # SQLite doesn't silently coerce via type-affinity (which produced
+ # the original mismatched-FK bug, see #3697).
+ assert isinstance(col.type, String)
+ assert col.type.length == 36
assert col.nullable is True
fk_targets = [fk.target_fullname for fk in col.foreign_keys]
assert "documents.id" in fk_targets
diff --git a/tests/database/test_alembic_migrations.py b/tests/database/test_alembic_migrations.py
index eb38d63187..6292a2fa1b 100644
--- a/tests/database/test_alembic_migrations.py
+++ b/tests/database/test_alembic_migrations.py
@@ -4522,6 +4522,164 @@ class TestPreAlembicDatabaseUpgrade:
engine.dispose()
+class TestUpgradeFromBuggyV16xUserDatabase:
+ """Regression for #3697.
+
+ Pre-fix ``encrypted_db.create_user_database`` only emitted ``CreateTable``,
+ never ``CreateIndex``. Combined with v1.6.0 enabling ``PRAGMA
+ foreign_keys = ON``, every existing user DB has a mismatched FK
+ (``download_attempts.url_hash`` → ``download_tracker.url_hash`` with no
+ UNIQUE backing). On any DML touching those tables SQLite raises
+ ``foreign key mismatch``, which would abort migration 0007 itself before
+ it could repair the schema. Migration 0007 must therefore disable FK
+ enforcement around its scrub + UNIQUE-index creation.
+ """
+
+ @pytest.fixture
+ def buggy_v16x_engine(self, tmp_path):
+ """Build a DB that mirrors the pre-fix state of an existing user:
+ tables exist, but ``download_tracker.url_hash`` has no UNIQUE backing,
+ the alembic_version is at 0006, and FK enforcement is on for every
+ connection (mirroring ``apply_performance_pragmas``)."""
+ import sqlite3
+ from sqlalchemy import event
+
+ db_path = tmp_path / "buggy_v16x.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 ('0006');
+ 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)
+ );
+ """
+ )
+ # Seed: duplicate parent rows (HASH1) + valid child + orphan child.
+ 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()
+
+ engine = create_engine(f"sqlite:///{db_path}")
+
+ @event.listens_for(engine, "connect")
+ def _enable_fk(dbapi_conn, _):
+ dbapi_conn.execute("PRAGMA foreign_keys = ON")
+
+ yield engine
+ engine.dispose()
+
+ def test_migration_0007_succeeds_against_pre_fix_user_db(
+ self, buggy_v16x_engine
+ ):
+ """Without the FK toggle in 0007's upgrade(), the duplicate scrub
+ raises ``foreign key mismatch`` and the migration aborts at 0006."""
+ run_migrations(buggy_v16x_engine)
+ assert get_current_revision(buggy_v16x_engine) == "0007"
+
+ with buggy_v16x_engine.connect() as conn:
+ assert conn.execute(text("PRAGMA foreign_keys")).scalar() == 1
+ assert (
+ conn.execute(text("PRAGMA foreign_key_check")).fetchall() == []
+ )
+
+ indexes = {
+ row[1]
+ for row in conn.execute(
+ text("PRAGMA index_list(download_tracker)")
+ ).fetchall()
+ }
+ assert "uq_download_tracker_url_hash" in indexes
+
+ tracker_ids = sorted(
+ r[0]
+ for r in conn.execute(
+ text("SELECT id FROM download_tracker")
+ ).fetchall()
+ )
+ # Survivor of HASH1 group is min(id)=1; HASH2 unaffected.
+ assert tracker_ids == [1, 3]
+
+ attempt_hashes = {
+ r[0]
+ for r in conn.execute(
+ text("SELECT url_hash FROM download_attempts")
+ ).fetchall()
+ }
+ assert attempt_hashes == {"HASH1"} # orphan removed
+
+ duplicate_count = conn.execute(
+ text("SELECT COUNT(*) FROM download_duplicates")
+ ).scalar()
+ assert duplicate_count == 0 # orphan removed
+
+ def test_fk_enforcement_active_after_migration(self, buggy_v16x_engine):
+ """Once 0007 finishes, the repaired FK must actually reject inserts
+ with a non-existent ``url_hash`` — proving FK was re-enabled and the
+ UNIQUE backing is recognized."""
+ from sqlalchemy.exc import IntegrityError
+
+ run_migrations(buggy_v16x_engine)
+
+ with buggy_v16x_engine.begin() as conn:
+ conn.execute(
+ text(
+ "INSERT INTO download_attempts (url_hash, attempt_number) "
+ "VALUES ('HASH1', 2)"
+ )
+ )
+
+ with pytest.raises(IntegrityError):
+ with buggy_v16x_engine.begin() as conn:
+ conn.execute(
+ text(
+ "INSERT INTO download_attempts (url_hash, attempt_number) "
+ "VALUES ('NEW_ORPHAN', 1)"
+ )
+ )
+
+
class TestMigrationAppliesSchemaChanges:
"""Tests proving the migration machinery actually changes schema and ORM works.
diff --git a/tests/database/test_migration_0005_resource_document_id.py b/tests/database/test_migration_0005_resource_document_id.py
index 5770a714cd..4106ed266f 100644
--- a/tests/database/test_migration_0005_resource_document_id.py
+++ b/tests/database/test_migration_0005_resource_document_id.py
@@ -305,14 +305,14 @@ class TestMigration0005FromFreshDatabase:
columns = _get_columns(fresh_engine, "research_resources")
assert "document_id" in columns
- def test_head_revision_is_0006(self):
- """get_head_revision() should return '0006' (current head)."""
- assert get_head_revision() == "0006"
+ def test_head_revision_is_0007(self):
+ """get_head_revision() should return '0007' (current head)."""
+ assert get_head_revision() == "0007"
- def test_current_revision_is_0006_after_migrate(self, fresh_engine):
- """After full migration, current revision should be 0006."""
+ def test_current_revision_is_0007_after_migrate(self, fresh_engine):
+ """After full migration, current revision should be 0007."""
run_migrations(fresh_engine)
- assert get_current_revision(fresh_engine) == "0006"
+ assert get_current_revision(fresh_engine) == "0007"
def test_needs_migration_false_after_full_upgrade(self, fresh_engine):
"""After full migration, needs_migration() should return False."""
@@ -531,7 +531,7 @@ class TestMigration0005EdgeCases:
try:
run_migrations(engine)
- assert get_current_revision(engine) == "0006"
+ assert get_current_revision(engine) == "0007"
columns = _get_columns(engine, "research_resources")
assert "document_id" in columns
diff --git a/tests/database/test_migration_0006.py b/tests/database/test_migration_0006.py
index c9b07ba288..c6b5c460df 100644
--- a/tests/database/test_migration_0006.py
+++ b/tests/database/test_migration_0006.py
@@ -529,7 +529,7 @@ class TestMigration0006Idempotency:
run_migrations(fresh_engine)
# Second run should succeed silently.
run_migrations(fresh_engine)
- assert get_head_revision() == "0006"
+ assert get_head_revision() == "0007"
def test_rerun_recreates_dropped_papers_indexes(
self, migrated_to_0005_engine