~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
perf(db): add (research_id, status) composite index to download_queue (#4699)
LearningCircuit81c6bc1ab173
diff --git a/src/local_deep_research/database/migrations/versions/0017_download_queue_research_status_index.py b/src/local_deep_research/database/migrations/versions/0017_download_queue_research_status_index.pynew file mode 100644index 0000000000..60121ac20f--- /dev/null+++ b/src/local_deep_research/database/migrations/versions/0017_download_queue_research_status_index.py@@ -0,0 +1,98 @@+"""Add (research_id, status) composite index to download_queue++The ``documents`` table already has ``idx_research_documents`` covering the+``(research_id, status)`` filter pattern, but ``download_queue`` only had+a single-column index on ``research_id``. Every ``download_bulk``,+``queue_all_undownloaded``, and background-scheduler query filters+``LibraryDownloadQueue`` by both columns, so a composite index lets+SQLite/SQLCipher satisfy the filter in one seek.++Mirrors the model-level declaration added to ``DownloadQueue`` in the+same change.++Revision ID: 0017+Revises: 0016+Create Date: 2026-06-20++Index Added:+=============+download_queue:+- idx_download_queue_research_status (research_id, status)++Migration Notes:+===============+- Index creation/drop are native SQLite operations (no batch mode needed).+- Guarded with an existence check for idempotency: fresh databases+ created after the model change already have the index via+ ``Base.metadata.create_all()`` in 0001, and 0001 stops producing+ ``download_queue`` once the model declares the index.+- ``if_not_exists=True`` provides additional safety.++Downgrade Behavior:+==================+The downgrade() function removes the index. Table data is completely+preserved — only the index structure is removed.++Noted in review of #4685.+"""++from alembic import op+from sqlalchemy import inspect++# revision identifiers, used by Alembic.+revision = "0017"+down_revision = "0016"+branch_labels = None+depends_on = None++INDEX_NAME = "idx_download_queue_research_status"+TABLE_NAME = "download_queue"+COLUMNS = ["research_id", "status"]+++def _index_exists(index_name: str, table_name: str) -> bool:+ """Check if an index exists on a table.++ Creates a fresh inspector each call because inspector caches+ per-instance — reusing after DDL returns stale data.+ """+ bind = op.get_bind()+ inspector = inspect(bind)++ if not inspector.has_table(table_name):+ return False++ existing_indexes = inspector.get_indexes(table_name)+ return any(idx["name"] == index_name for idx in existing_indexes)+++def upgrade():+ """Add the composite (research_id, status) index to download_queue."""+ bind = op.get_bind()+ inspector = inspect(bind)++ if not inspector.has_table(TABLE_NAME):+ # Table doesn't exist yet, will be created by initial migration+ # with the index already in place via Base.metadata.create_all().+ return++ if not _index_exists(INDEX_NAME, TABLE_NAME):+ op.create_index(+ INDEX_NAME,+ TABLE_NAME,+ COLUMNS,+ unique=False,+ if_not_exists=True,+ )+++def downgrade():+ """Remove the composite (research_id, status) index from download_queue."""+ bind = op.get_bind()+ inspector = inspect(bind)++ if not inspector.has_table(TABLE_NAME):+ return++ if _index_exists(INDEX_NAME, TABLE_NAME):+ op.drop_index(INDEX_NAME, table_name=TABLE_NAME)diff --git a/src/local_deep_research/database/models/library.py b/src/local_deep_research/database/models/library.pyindex 500ea3afa9..663456d046 100644--- a/src/local_deep_research/database/models/library.py+++ b/src/local_deep_research/database/models/library.py@@ -675,6 +675,13 @@ class DownloadQueue(Base):resource = relationship("ResearchResource", backref="download_queue")collection = relationship("Collection", backref="download_queue_items")+ # Index for the common filter_by(research_id=..., status=...) query+ # pattern used by download_bulk, queue_all_undownloaded, and the+ # background scheduler. Mirrors Document.idx_research_documents.+ __table_args__ = (+ Index("idx_download_queue_research_status", "research_id", "status"),+ )+def __repr__(self):return f"<DownloadQueue(resource_id={self.resource_id}, status={self.status}, attempts={self.attempts})>"diff --git a/tests/database/test_migration_0016_drop_orphaned_cache_tables.py b/tests/database/test_migration_0016_drop_orphaned_cache_tables.pyindex 58d2350b2a..abbf7135fa 100644--- a/tests/database/test_migration_0016_drop_orphaned_cache_tables.py+++ b/tests/database/test_migration_0016_drop_orphaned_cache_tables.py@@ -21,7 +21,6 @@ from sqlalchemy import create_engine, inspect, textfrom local_deep_research.database.alembic_runner import (get_alembic_config,- get_head_revision,stamp_database,)from local_deep_research.database.encrypted_db import DatabaseManager@@ -175,14 +174,15 @@ class TestMigration0016:assert "cache" not in remainingassert "search_cache" not in remaining- def test_0016_chains_to_0015_as_single_head(self, migrated_to_0015_engine):+ def test_0016_chains_to_0015(self, migrated_to_0015_engine):+ # Head-alignment (which revision is the tip) is asserted in the newest+ # migration's test file; here we only guard 0016's own chain link.from alembic.script import ScriptDirectorycfg = get_alembic_config(migrated_to_0015_engine)script = ScriptDirectory.from_config(cfg)rev = script.get_revision("0016")assert rev.down_revision == "0015"- assert "0016" in script.get_heads()class TestMigration0016Encrypted:@@ -221,12 +221,3 @@ class TestMigration0016Encrypted:assert "search_cache" not in remainingfinally:manager.close_user_database(username)---class TestMigration0016HeadAlignment:- """Head-alignment guard, per the convention that it lives in the newest- migration's test file (moved here from 0015_drop_document_notes when 0016- was added on top)."""-- def test_head_revision_is_0016(self):- assert get_head_revision() == "0016"diff --git a/tests/database/test_migration_0017_download_queue_research_status_index.py b/tests/database/test_migration_0017_download_queue_research_status_index.pynew file mode 100644index 0000000000..c693695c8e--- /dev/null+++ b/tests/database/test_migration_0017_download_queue_research_status_index.py@@ -0,0 +1,147 @@+"""Tests for migration 0017: add (research_id, status) composite index to download_queue.++Covers:+- The upgrade adds the composite index to download_queue.+- Idempotency: re-running upgrade on a DB that already has the index is a no-op.+- Missing-table guard: upgrade is a no-op when download_queue doesn't exist.+- Downgrade removes the index; table data is preserved.+- Head-alignment: 0017 is the latest revision (the guard lives in the newest+ migration's test file; 0016 took it from 0015, 0017 takes it from 0016).+"""++import pytest+from alembic import command+from sqlalchemy import create_engine, inspect, text++from local_deep_research.database.alembic_runner import (+ get_alembic_config,+ get_head_revision,+ stamp_database,+)+++def _run_upgrade_to(engine, revision):+ config = get_alembic_config(engine)+ with engine.begin() as conn:+ config.attributes["connection"] = conn+ command.upgrade(config, revision)+++def _run_downgrade_to(engine, revision):+ config = get_alembic_config(engine)+ with engine.begin() as conn:+ config.attributes["connection"] = conn+ command.downgrade(config, revision)+++def _index_names(engine, table):+ insp = inspect(engine)+ if not insp.has_table(table):+ return set()+ return {idx["name"] for idx in insp.get_indexes(table) if idx["name"]}+++def legacy_engine(tmp_path):+ """A DB whose download_queue table lacks the composite index.++ Simulates an installation created before 0017. Stamped at 0016 so 0017's+ upgrade is a clean delta.+ """+ db_path = tmp_path / "legacy_pre_0017.db"+ engine = create_engine(f"sqlite:///{db_path}")++ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE download_queue ("+ "id INTEGER PRIMARY KEY AUTOINCREMENT, "+ "research_id INTEGER NOT NULL, "+ "status VARCHAR(50) NOT NULL DEFAULT 'pending', "+ "url TEXT NOT NULL, "+ "created_at TEXT NOT NULL"+ ")"+ )+ )+ conn.execute(+ text(+ "CREATE INDEX idx_download_queue_research_id "+ "ON download_queue (research_id)"+ )+ )+ conn.execute(+ text(+ "INSERT INTO download_queue "+ "(research_id, status, url, created_at) "+ "VALUES (1, 'pending', 'https://example.com', '2026-01-01 00:00:00')"+ )+ )++ stamp_database(engine, "0016")+ yield engine+ engine.dispose()+++class TestMigration0017Upgrade:+ def test_adds_composite_index(self, legacy_engine):+ engine = legacy_engine+ assert "idx_download_queue_research_status" not in _index_names(+ engine, "download_queue"+ )+ _run_upgrade_to(engine, "0017")+ assert "idx_download_queue_research_status" in _index_names(+ engine, "download_queue"+ )++ def test_preserves_row_data(self, legacy_engine):+ engine = legacy_engine+ _run_upgrade_to(engine, "0017")+ with engine.begin() as conn:+ count = conn.execute(+ text("SELECT COUNT(*) FROM download_queue")+ ).scalar()+ assert count == 1++ def test_upgrade_is_idempotent(self, legacy_engine):+ engine = legacy_engine+ _run_upgrade_to(engine, "0017")+ _run_upgrade_to(engine, "0017") # second run is a no-op, no error+ assert "idx_download_queue_research_status" in _index_names(+ engine, "download_queue"+ )++ def test_missing_table_does_not_crash(self, tmp_path):+ """Upgrade is a no-op when download_queue doesn't exist yet."""+ engine = create_engine(f"sqlite:///{tmp_path}/no_queue.db")+ stamp_database(engine, "0016")+ _run_upgrade_to(engine, "0017") # must not raise+ assert not inspect(engine).has_table("download_queue")+ engine.dispose()+++class TestMigration0017Downgrade:+ def test_downgrade_removes_index(self, legacy_engine):+ engine = legacy_engine+ _run_upgrade_to(engine, "0017")+ assert "idx_download_queue_research_status" in _index_names(+ engine, "download_queue"+ )+ _run_downgrade_to(engine, "0016")+ assert "idx_download_queue_research_status" not in _index_names(+ engine, "download_queue"+ )++ def test_downgrade_preserves_row_data(self, legacy_engine):+ engine = legacy_engine+ _run_upgrade_to(engine, "0017")+ _run_downgrade_to(engine, "0016")+ with engine.begin() as conn:+ count = conn.execute(+ text("SELECT COUNT(*) FROM download_queue")+ ).scalar()+ assert count == 1+++class TestMigration0017HeadAlignment:+ def test_head_revision_is_0017(self):+ assert get_head_revision() == "0017"