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.

chore(db): drop orphaned cache tables, remove dead Cache/SearchCache models (#4641)

LearningCircuit93dc8332992f
diff --git a/docs/architecture/DATABASE_SCHEMA.md b/docs/architecture/DATABASE_SCHEMA.md
index 4142c7891c..5a5ad82ba2 100644
--- a/docs/architecture/DATABASE_SCHEMA.md
+++ b/docs/architecture/DATABASE_SCHEMA.md
@@ -16,7 +16,6 @@ This document describes the database models and their relationships in Local Dee
- [News System](#news-system)
- [Benchmarking](#benchmarking)
- [Rate Limiting](#rate-limiting)
- - [Caching](#caching)
- [File Integrity](#file-integrity)
---
@@ -556,37 +555,6 @@ Learned rate limit estimates.
---
-### Caching
-
-Result caching for performance.
-
-#### SearchCache
-
-Cached search results.
-
-| Column | Type | Description |
-|--------|------|-------------|
-| `id` | Integer | Primary key |
-| `query_hash` | String(64) | Query hash (indexed) |
-| `engine` | String(50) | Search engine |
-| `results` | JSON | Cached results |
-| `expires_at` | DateTime | Cache expiration |
-| `created_at` | DateTime | When cached |
-
-#### Cache
-
-General-purpose cache.
-
-| Column | Type | Description |
-|--------|------|-------------|
-| `id` | Integer | Primary key |
-| `key` | String(255) | Cache key (unique) |
-| `value` | Text | Cached value |
-| `expires_at` | DateTime | Expiration time |
-| `created_at` | DateTime | When created |
-
----
-
### File Integrity
File verification for security.
diff --git a/src/local_deep_research/database/migrations/versions/0016_drop_orphaned_cache_tables.py b/src/local_deep_research/database/migrations/versions/0016_drop_orphaned_cache_tables.py
new file mode 100644
index 0000000000..e7b8d7dbbf
--- /dev/null
+++ b/src/local_deep_research/database/migrations/versions/0016_drop_orphaned_cache_tables.py
@@ -0,0 +1,65 @@
+"""Drop the orphaned ``search_cache`` and ``cache`` tables.
+
+Background
+==========
+Both tables were dead code:
+
+* ``search_cache`` (model ``SearchCache``) was read/written only by the
+ ``utilities/search_cache.py`` cache utility, removed in #4621 — its sole
+ consumer, an experimental search strategy, had already been deleted in
+ #4420, and ``get_or_fetch`` was never wired into the live search path.
+* ``cache`` (model ``Cache``) was *dead on arrival*: introduced together
+ with its tests but never imported, instantiated, or queried by any
+ production code. The table existed only as a ``Base.metadata``
+ side-effect and was always empty.
+
+Both models have now been removed from ``database/models``, so fresh
+databases no longer create either table. This migration drops them from
+existing databases. Neither table held production data.
+
+What this migration does
+========================
+Drops ``search_cache`` and ``cache`` if present. The ``has_table`` guard
+makes it a no-op on fresh databases (created after the models were removed,
+where the tables never existed) and on any database where they are already
+absent. Removal tracked in #4620.
+
+Revision ID: 0016
+Revises: 0015
+Create Date: 2026-06-18
+
+Renumbered from 0015 to 0016: a separate 0015 (``0015_drop_document_notes``)
+landed on main concurrently, so this migration now chains after it.
+"""
+
+from __future__ import annotations
+
+from alembic import op
+from loguru import logger
+from sqlalchemy import inspect
+
+revision = "0016"
+down_revision = "0015"
+branch_labels = None
+depends_on = None
+
+ORPHANED_TABLES = ("search_cache", "cache")
+
+
+def upgrade() -> None:
+ conn = op.get_bind()
+ inspector = inspect(conn)
+
+ for table in ORPHANED_TABLES:
+ if inspector.has_table(table):
+ op.drop_table(table)
+ logger.info("Dropped orphaned '{}' table.", table)
+
+
+def downgrade() -> None:
+ """No-op.
+
+ Both tables were orphaned dead code holding no data, and their models
+ have been removed, so there is nothing meaningful to recreate. Mirrors
+ the no-op downgrade in migration 0013.
+ """
diff --git a/src/local_deep_research/database/models/__init__.py b/src/local_deep_research/database/models/__init__.py
index b8e13daf04..586267928c 100644
--- a/src/local_deep_research/database/models/__init__.py
+++ b/src/local_deep_research/database/models/__init__.py
@@ -14,7 +14,6 @@ from .benchmark import (
BenchmarkStatus,
DatasetType,
)
-from .cache import Cache, SearchCache
from .chat import (
ChatMessage,
ChatMessageType,
@@ -113,9 +112,6 @@ __all__ = [
"BenchmarkResult",
"BenchmarkConfig",
"BenchmarkProgress",
- # Cache
- "Cache",
- "SearchCache",
# Papers (deduplicated academic papers)
"Paper",
"PaperAppearance",
diff --git a/src/local_deep_research/database/models/cache.py b/src/local_deep_research/database/models/cache.py
deleted file mode 100644
index 8ca505eb8b..0000000000
--- a/src/local_deep_research/database/models/cache.py
+++ /dev/null
@@ -1,109 +0,0 @@
-"""
-Cache model for storing expensive operation results.
-"""
-
-from datetime import datetime, timedelta, UTC
-from functools import partial
-
-from sqlalchemy import JSON, Column, Index, Integer, String, Text
-from sqlalchemy_utc import UtcDateTime
-
-from .base import Base
-
-
-class Cache(Base):
- """
- Cache for API responses and expensive operations.
- Helps reduce API calls and improve performance.
- """
-
- __tablename__ = "cache"
-
- id = Column(Integer, primary_key=True)
- cache_key = Column(String(255), unique=True, nullable=False, index=True)
- cache_value = Column(JSON) # For structured data
- cache_text = Column(Text) # For large text content
-
- # Cache metadata
- cache_type = Column(
- String(50)
- ) # api_response, computation, search_result, etc.
- source = Column(String(100)) # openai, google, computation, etc.
- size_bytes = Column(Integer) # Size of cached data
-
- # Expiration
- ttl_seconds = Column(Integer) # Time to live in seconds
- expires_at = Column(UtcDateTime, index=True)
-
- # Usage tracking
- hit_count = Column(Integer, default=0)
- created_at = Column(UtcDateTime, default=partial(datetime.now, UTC))
- accessed_at = Column(UtcDateTime, default=partial(datetime.now, UTC))
-
- # Indexes for performance
- __table_args__ = (
- Index("idx_type_expires", "cache_type", "expires_at"),
- Index("idx_source_key", "source", "cache_key"),
- )
-
- def is_expired(self) -> bool:
- """Check if cache entry has expired."""
- if not self.expires_at:
- return False
-
- # Handle both timezone-aware and naive datetimes
- now = datetime.now(UTC)
- expires = self.expires_at
-
- # If expires_at is naive, make it aware (assuming UTC)
- if expires.tzinfo is None:
- expires = expires.replace(tzinfo=UTC)
-
- return now > expires
-
- def set_ttl(self, seconds: int):
- """Set time to live for cache entry."""
- self.ttl_seconds = seconds
- self.expires_at = datetime.now(UTC) + timedelta(seconds=seconds)
-
- def record_hit(self):
- """Record a cache hit."""
- self.hit_count += 1
- self.accessed_at = datetime.now(UTC)
-
- def __repr__(self):
- expired = " (expired)" if self.is_expired() else ""
- return f"<Cache(key='{self.cache_key}', type='{self.cache_type}', hits={self.hit_count}{expired})>"
-
-
-class SearchCache(Base):
- """Search cache for storing query results with TTL and LRU eviction.
-
- .. deprecated::
- ORPHANED — the ``SearchCache`` utility class that read/wrote this
- table was removed as dead code (its only consumer, an experimental
- search strategy, was deleted in #4420). Nothing reads from or writes
- to this table any longer. The model/table is retained for now to
- avoid a schema migration; removal is tracked in #4620. Do not add new
- users — see the issue before relying on it.
- """
-
- __tablename__ = "search_cache"
-
- query_hash = Column(String, primary_key=True)
- query_text = Column(Text, nullable=False)
- results = Column(
- JSON, nullable=False
- ) # JSON column for automatic serialization
- created_at = Column(Integer, nullable=False) # Unix timestamp
- expires_at = Column(Integer, nullable=False) # Unix timestamp
- access_count = Column(Integer, default=1)
- last_accessed = Column(Integer, nullable=False) # Unix timestamp
-
- __table_args__ = (
- Index("idx_expires_at", "expires_at"),
- Index("idx_last_accessed", "last_accessed"),
- )
-
- def __repr__(self):
- return f"<SearchCache(query_text='{self.query_text[:50]}...', expires_at={self.expires_at})>"
diff --git a/src/local_deep_research/database/models/journal.py b/src/local_deep_research/database/models/journal.py
index decfbe4545..fbe68a4e5e 100644
--- a/src/local_deep_research/database/models/journal.py
+++ b/src/local_deep_research/database/models/journal.py
@@ -59,8 +59,8 @@ class Journal(Base):
quality_model = Column(String(255), nullable=True, index=True)
# Unix timestamp (seconds, not milliseconds) of last analysis — used
# for the TTL / reanalysis_period freshness check. Read/write via
- # ``int(time.time())``; an Integer column (matching SearchCache) is
- # cheaper on the cache hot path than UtcDateTime would be.
+ # ``int(time.time())``; a plain Integer column is cheaper on the
+ # freshness-check hot path than UtcDateTime would be.
quality_analysis_time = Column(Integer, nullable=False)
__table_args__ = (
diff --git a/tests/database/test_alembic_migrations.py b/tests/database/test_alembic_migrations.py
index 8889b6b7c6..ea72d7f0dc 100644
--- a/tests/database/test_alembic_migrations.py
+++ b/tests/database/test_alembic_migrations.py
@@ -127,7 +127,6 @@ class TestAlembicRunner:
"journals",
"app_logs",
"queued_researches",
- "search_cache",
"token_usage",
"research_ratings",
"task_metadata",
@@ -684,6 +683,8 @@ class TestMigrationChain:
"0012_add_collection_agent_enabled.py",
"0013_remove_meta_search_engines.py",
"0014_benchmark_run_version_and_snapshot.py",
+ "0015_drop_document_notes.py",
+ "0016_drop_orphaned_cache_tables.py",
]
for filename in expected_files:
@@ -6043,6 +6044,9 @@ class TestMigrationSafetyGuards:
# 0013: restoring 'auto'/'parallel' references would recreate
# broken state — those engines no longer exist in the codebase.
"0013_remove_meta_search_engines.py",
+ # 0016: the dropped cache tables were orphaned dead code holding no
+ # data, and their models are removed — nothing to recreate.
+ "0016_drop_orphaned_cache_tables.py",
}
# Migrations whose downgrade is intentionally NotImplementedError
@@ -6129,8 +6133,6 @@ class TestMigrationSafetyGuards:
"report_sections",
"app_logs",
"provider_models",
- "search_cache",
- "cache",
"documents",
"collections",
}
diff --git a/tests/database/test_cache_models.py b/tests/database/test_cache_models.py
deleted file mode 100644
index 0324a72316..0000000000
--- a/tests/database/test_cache_models.py
+++ /dev/null
@@ -1,353 +0,0 @@
-"""Tests for cache-related database models."""
-
-import hashlib
-import json
-import time
-from datetime import datetime, timedelta, timezone, UTC
-
-import pytest
-from sqlalchemy import create_engine
-from sqlalchemy.orm import sessionmaker
-
-from local_deep_research.database.models import Base, Cache, SearchCache
-
-
-class TestCacheModels:
- """Test suite for cache-related models."""
-
- @pytest.fixture
- def engine(self):
- """Create an in-memory SQLite database for testing."""
- engine = create_engine("sqlite:///:memory:")
- Base.metadata.create_all(engine)
- yield engine
- engine.dispose()
-
- @pytest.fixture
- def session(self, engine):
- """Create a database session for testing."""
- Session = sessionmaker(bind=engine)
- session = Session()
- yield session
- session.close()
-
- def test_cache_creation(self, session):
- """Test creating basic cache entries."""
- cache_entry = Cache(
- cache_key="llm_response_12345",
- cache_text="This is the cached LLM response for the query about quantum physics.",
- cache_type="llm_response",
- source="openai",
- ttl_seconds=86400, # 24 hours
- expires_at=datetime.now(UTC) + timedelta(hours=24),
- cache_value={
- "model": "gpt-4",
- "temperature": 0.7,
- "query": "explain quantum entanglement",
- },
- size_bytes=1024,
- )
-
- session.add(cache_entry)
- session.commit()
-
- # Verify cache entry
- saved = session.query(Cache).first()
- assert saved is not None
- assert saved.cache_key == "llm_response_12345"
- assert "quantum physics" in saved.cache_text
- assert saved.cache_type == "llm_response"
- assert saved.cache_value["model"] == "gpt-4"
- assert saved.hit_count == 0
- assert saved.size_bytes == 1024
-
- def test_cache_expiration(self, session):
- """Test cache expiration functionality."""
- now = datetime.now(UTC)
-
- # Create expired cache
- expired = Cache(
- cache_key="expired_cache",
- cache_text="Old data",
- cache_type="test",
- expires_at=now - timedelta(hours=1),
- )
-
- # Create valid cache
- valid = Cache(
- cache_key="valid_cache",
- cache_text="Fresh data",
- cache_type="test",
- expires_at=now + timedelta(hours=1),
- )
-
- # Create non-expiring cache
- permanent = Cache(
- cache_key="permanent_cache",
- cache_text="Never expires",
- cache_type="test",
- expires_at=None,
- )
-
- session.add_all([expired, valid, permanent])
- session.commit()
-
- # Test is_expired method
- assert expired.is_expired() is True
- assert valid.is_expired() is False
- assert permanent.is_expired() is False
-
- # Query non-expired entries
- non_expired = (
- session.query(Cache)
- .filter((Cache.expires_at.is_(None)) | (Cache.expires_at > now))
- .all()
- )
-
- assert len(non_expired) == 2
- keys = [c.cache_key for c in non_expired]
- assert "valid_cache" in keys
- assert "permanent_cache" in keys
-
- def test_search_cache(self, session):
- """Test search-specific cache functionality."""
- query = "quantum physics research"
- query_hash = hashlib.sha256(query.encode()).hexdigest()
-
- current_time = int(time.time())
- search_cache = SearchCache(
- query_hash=query_hash,
- query_text=query,
- results=json.dumps(
- [
- {
- "title": "Quantum Mechanics",
- "url": "https://example.com/qm",
- },
- {"title": "Physics Today", "url": "https://example.com/pt"},
- ]
- ),
- created_at=current_time,
- expires_at=current_time + 21600, # 6 hours
- last_accessed=current_time,
- access_count=1,
- )
-
- session.add(search_cache)
- session.commit()
-
- # Verify search cache
- saved = (
- session.query(SearchCache).filter_by(query_hash=query_hash).first()
- )
- assert saved is not None
- assert saved.query_text == query
- results = json.loads(saved.results)
- assert len(results) == 2
- assert saved.access_count == 1
-
- def test_cache_categories(self, session):
- """Test different cache categories."""
- categories = [
- ("llm_response", "AI generated content", "openai"),
- ("search_result", "Search engine results", "google"),
- ("api_response", "External API response", "external"),
- ("computation", "Expensive computation result", "local"),
- ]
-
- for cache_type, value, source in categories:
- cache = Cache(
- cache_key=f"{cache_type}_test",
- cache_text=value,
- cache_type=cache_type,
- source=source,
- expires_at=datetime.now(UTC) + timedelta(hours=1),
- )
- session.add(cache)
-
- session.commit()
-
- # Query by category
- llm_caches = (
- session.query(Cache).filter_by(cache_type="llm_response").all()
- )
- assert len(llm_caches) == 1
- assert llm_caches[0].cache_text == "AI generated content"
- assert llm_caches[0].source == "openai"
-
- def test_cache_hit_tracking(self, session):
- """Test cache hit counting and access time updates."""
- cache = Cache(
- cache_key="hit_test",
- cache_text="Test content",
- cache_type="test",
- hit_count=0,
- )
-
- session.add(cache)
- session.commit()
-
- # Record multiple hits
- original_accessed = cache.accessed_at
- for i in range(5):
- cache.record_hit()
- session.commit()
-
- assert cache.hit_count == 5
- assert cache.accessed_at > original_accessed
-
- def test_search_cache_deduplication(self, session):
- """Test that identical queries produce the same hash."""
- query1 = "machine learning algorithms"
- query2 = "machine learning algorithms" # Same query
- query3 = "Machine Learning Algorithms" # Different case
-
- hash1 = hashlib.sha256(query1.encode()).hexdigest()
- hash2 = hashlib.sha256(query2.encode()).hexdigest()
- hash3 = hashlib.sha256(query3.encode()).hexdigest()
-
- assert hash1 == hash2
- assert hash1 != hash3 # Different case produces different hash
-
- def test_cache_size_management(self, session):
- """Test tracking cache entry sizes."""
- large_text = "x" * 10000
- small_text = "small"
-
- large_cache = Cache(
- cache_key="large_entry",
- cache_text=large_text,
- cache_type="test",
- size_bytes=len(large_text.encode()),
- )
-
- small_cache = Cache(
- cache_key="small_entry",
- cache_text=small_text,
- cache_type="test",
- size_bytes=len(small_text.encode()),
- )
-
- session.add_all([large_cache, small_cache])
- session.commit()
-
- # Query total cache size - sum all sizes
- from sqlalchemy import func
-
- total_size = (
- session.query(func.sum(Cache.size_bytes))
- .filter(Cache.size_bytes.isnot(None))
- .scalar()
- or 0
- )
-
- assert large_cache.size_bytes > small_cache.size_bytes
- assert total_size > 10000
-
- def test_cache_metadata_usage(self, session):
- """Test storing and retrieving cache metadata."""
- metadata = {
- "model": "gpt-4",
- "temperature": 0.7,
- "max_tokens": 1000,
- "timestamp": "2024-01-01T00:00:00Z",
- }
-
- cache = Cache(
- cache_key="metadata_test",
- cache_text="Response text",
- cache_type="llm_response",
- cache_value=metadata,
- )
-
- session.add(cache)
- session.commit()
-
- saved = session.query(Cache).first()
- assert saved.cache_value == metadata
- assert saved.cache_value["model"] == "gpt-4"
-
- def test_search_cache_with_filters(self, session):
- """Test search cache with various filter parameters."""
- current_time = int(time.time())
-
- # Add multiple search caches
- queries = [
- ("python tutorials", current_time - 3600), # 1 hour ago
- ("javascript frameworks", current_time - 7200), # 2 hours ago
- ("rust programming", current_time - 86400), # 1 day ago
- ]
-
- for query, created in queries:
- query_hash = hashlib.sha256(query.encode()).hexdigest()
- cache = SearchCache(
- query_hash=query_hash,
- query_text=query,
- results=json.dumps([{"title": f"Result for {query}"}]),
- created_at=created,
- expires_at=created + 86400, # 24 hour TTL
- last_accessed=created,
- access_count=1,
- )
- session.add(cache)
-
- session.commit()
-
- # Query recent caches (last 3 hours)
- recent_threshold = current_time - 10800
- recent_caches = (
- session.query(SearchCache)
- .filter(SearchCache.created_at >= recent_threshold)
- .all()
- )
-
- assert len(recent_caches) == 2
-
- def test_cache_cleanup_old_entries(self, session):
- """Test cleanup of expired cache entries."""
- now = datetime.now(timezone.utc)
-
- # Create caches with different expiration times
- for i in range(10):
- cache = Cache(
- cache_key=f"cache_{i}",
- cache_text=f"Content {i}",
- cache_type="test",
- expires_at=now - timedelta(hours=i), # Some expired, some not
- )
- session.add(cache)
-
- session.commit()
-
- # Delete expired entries
- session.query(Cache).filter(Cache.expires_at < now).delete()
- session.commit()
-
- # Verify cleanup
- remaining = session.query(Cache).count()
- assert remaining == 1 # Only cache_0 should remain (expires_at = now)
-
- def test_cache_update_operations(self, session):
- """Test updating cache entries."""
- cache = Cache(
- cache_key="update_test",
- cache_text="Original content",
- cache_type="test",
- ttl_seconds=3600,
- )
- cache.set_ttl(3600) # Set TTL
-
- session.add(cache)
- session.commit()
-
- # Update content
- cache.cache_text = "Updated content"
- cache.cache_value = {"version": 2}
- session.commit()
-
- # Verify updates
- saved = session.query(Cache).filter_by(cache_key="update_test").first()
- assert saved.cache_text == "Updated content"
- assert saved.cache_value["version"] == 2
- assert saved.ttl_seconds == 3600
- assert saved.expires_at is not None
diff --git a/tests/database/test_database_init.py b/tests/database/test_database_init.py
index a2e589c964..29689c3a74 100644
--- a/tests/database/test_database_init.py
+++ b/tests/database/test_database_init.py
@@ -63,7 +63,6 @@ class TestDatabaseInitialization:
assert "settings" in tables
assert "research_resources" in tables
assert "token_usage" in tables
- assert "search_cache" in tables
engine.dispose()
diff --git a/tests/database/test_encrypted_database_orm.py b/tests/database/test_encrypted_database_orm.py
index fefd2cb41a..8c0f1bcf94 100644
--- a/tests/database/test_encrypted_database_orm.py
+++ b/tests/database/test_encrypted_database_orm.py
@@ -22,7 +22,6 @@ from local_deep_research.database.models import (
ResearchLog,
ResearchResource,
ResearchTask,
- SearchCache,
SearchQuery,
SearchResult,
UserSettings,
@@ -297,63 +296,6 @@ class TestEncryptedDatabaseORM:
)
assert len(high_relevance) == 2
- def test_search_cache_operations(self, test_user_session):
- """Test search cache storage and expiry."""
- session = test_user_session
- import time
- import json
-
- current_time = int(time.time())
-
- # Add cache entries
- cache_entries = [
- SearchCache(
- query_hash="hash_ai_safety",
- query_text="AI safety research",
- results=json.dumps(
- {
- "results": [
- {
- "title": "AI Safety Paper 1",
- "url": "https://example.com/1",
- },
- {
- "title": "AI Safety Paper 2",
- "url": "https://example.com/2",
- },
- ]
- }
- ),
- created_at=current_time,
- expires_at=current_time + 3600, # 1 hour
- last_accessed=current_time,
- ),
- SearchCache(
- query_hash="hash_expired",
- query_text="old query",
- results=json.dumps({"results": []}),
- created_at=current_time - 7200,
- expires_at=current_time - 3600, # Expired 1 hour ago
- last_accessed=current_time - 7200,
- ),
- ]
-
- session.add_all(cache_entries)
- session.commit()
-
- # Query non-expired entries
- valid_cache = (
- session.query(SearchCache)
- .filter(SearchCache.expires_at > current_time)
- .all()
- )
- assert len(valid_cache) == 1
- assert valid_cache[0].query_text == "AI safety research"
-
- # Parse cached results
- cached_data = json.loads(valid_cache[0].results)
- assert len(cached_data["results"]) == 2
-
def test_research_logs(self, test_user_session):
"""Test research logging functionality."""
session = test_user_session
diff --git a/tests/database/test_migration_0015_drop_document_notes.py b/tests/database/test_migration_0015_drop_document_notes.py
index 1c08ec6579..e8ed4a1246 100644
--- a/tests/database/test_migration_0015_drop_document_notes.py
+++ b/tests/database/test_migration_0015_drop_document_notes.py
@@ -6,8 +6,9 @@ Covers:
- Idempotency (re-run, and tables that never had the column).
- Missing-table guard.
- Downgrade re-adds ``notes`` as nullable Text, and a round-trip is stable.
-- Head-alignment: 0015 is the latest revision (the guard lives in the newest
- migration's test file; 0014 took it from 0013, 0015 takes it from 0014).
+
+(The head-alignment guard moved to the newer 0016 migration's test file, per
+the convention that it lives in the newest migration's tests.)
Note on test setup
==================
@@ -25,7 +26,6 @@ from sqlalchemy import create_engine, inspect, text
from local_deep_research.database.alembic_runner import (
get_alembic_config,
- get_head_revision,
stamp_database,
)
@@ -188,8 +188,3 @@ class TestMigration0015Downgrade:
text("SELECT COUNT(*) FROM documents")
).scalar()
assert count == 1
-
-
-class TestMigration0015HeadAlignment:
- def test_head_revision_is_0015(self):
- assert get_head_revision() == "0015"
diff --git a/tests/database/test_migration_0016_drop_orphaned_cache_tables.py b/tests/database/test_migration_0016_drop_orphaned_cache_tables.py
new file mode 100644
index 0000000000..58d2350b2a
--- /dev/null
+++ b/tests/database/test_migration_0016_drop_orphaned_cache_tables.py
@@ -0,0 +1,232 @@
+"""Dedicated tests for migration 0016 (drop orphaned ``cache`` + ``search_cache``).
+
+Mirrors the 0013/0014 convention: seed the pre-0016 state, run the upgrade,
+and assert the destructive effect.
+
+This file exists because the ``Cache``/``SearchCache`` models were removed in
+the same PR, so no other test (and no migration) ever creates these tables.
+Without this file, migration 0016 always reaches ``inspector.has_table()`` as
+False in the test suite and its ``op.drop_table`` branch — the only code that
+runs against real user databases — is never exercised. Here we recreate the
+legacy tables at the revision before 0016 to simulate an existing user DB that
+still carries them, then prove the upgrade drops them.
+
+(0016 was renumbered from 0015 after a separate 0015_drop_document_notes
+landed on main; it now chains after that revision.)
+"""
+
+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,
+)
+from local_deep_research.database.encrypted_db import DatabaseManager
+
+# DDL for the two tables as they existed before this migration (created via
+# Base.metadata from the now-removed ORM models). Recreated here so the test
+# can simulate a pre-existing user database that still carries them, including
+# every index the models declared.
+_SEARCH_CACHE_DDL = [
+ """
+ CREATE TABLE search_cache (
+ query_hash VARCHAR NOT NULL PRIMARY KEY,
+ query_text TEXT NOT NULL,
+ results JSON NOT NULL,
+ created_at INTEGER NOT NULL,
+ expires_at INTEGER NOT NULL,
+ access_count INTEGER,
+ last_accessed INTEGER NOT NULL
+ )
+ """,
+ "CREATE INDEX idx_expires_at ON search_cache (expires_at)",
+ "CREATE INDEX idx_last_accessed ON search_cache (last_accessed)",
+]
+
+_CACHE_DDL = [
+ """
+ CREATE TABLE cache (
+ id INTEGER NOT NULL PRIMARY KEY,
+ cache_key VARCHAR(255) NOT NULL,
+ cache_value JSON,
+ cache_text TEXT,
+ cache_type VARCHAR(50),
+ source VARCHAR(100),
+ size_bytes INTEGER,
+ ttl_seconds INTEGER,
+ expires_at DATETIME,
+ hit_count INTEGER,
+ created_at DATETIME,
+ accessed_at DATETIME
+ )
+ """,
+ "CREATE UNIQUE INDEX ix_cache_cache_key ON cache (cache_key)",
+ "CREATE INDEX ix_cache_expires_at ON cache (expires_at)",
+ "CREATE INDEX idx_type_expires ON cache (cache_type, expires_at)",
+ "CREATE INDEX idx_source_key ON cache (source, cache_key)",
+]
+
+_CACHE_INDEXES = {
+ "idx_expires_at",
+ "idx_last_accessed",
+ "ix_cache_cache_key",
+ "ix_cache_expires_at",
+ "idx_type_expires",
+ "idx_source_key",
+}
+
+
+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 _create_legacy_cache_tables(engine, *, populate):
+ with engine.begin() as conn:
+ for stmt in _SEARCH_CACHE_DDL + _CACHE_DDL:
+ conn.execute(text(stmt))
+ if populate:
+ conn.execute(
+ text(
+ "INSERT INTO search_cache "
+ "(query_hash, query_text, results, created_at, "
+ " expires_at, access_count, last_accessed) "
+ "VALUES ('h1', 'q', '[]', 1, 2, 1, 1)"
+ )
+ )
+ conn.execute(
+ text(
+ "INSERT INTO cache (cache_key, cache_text, hit_count) "
+ "VALUES ('k1', 'v', 0)"
+ )
+ )
+
+
+def _tables(engine):
+ return set(inspect(engine).get_table_names())
+
+
+def _index_names(engine):
+ with engine.begin() as conn:
+ rows = conn.execute(
+ text("SELECT name FROM sqlite_master WHERE type = 'index'")
+ ).fetchall()
+ return {r[0] for r in rows}
+
+
+def migrated_to_0015_engine(tmp_path):
+ """A database upgraded through 0015 (the revision before 0016).
+
+ At 0015 the cache/search_cache tables do NOT exist (their models were
+ removed, so 0001's metadata-based create never produces them); tests that
+ need the legacy tables add them explicitly.
+ """
+ engine = create_engine(f"sqlite:///{tmp_path / 'test_0016.db'}")
+ _run_upgrade_to(engine, "0015")
+ yield engine
+ engine.dispose()
+
+
+class TestMigration0016:
+ def test_drops_both_tables_even_when_populated(
+ self, migrated_to_0015_engine
+ ):
+ """Destructive path: tables present (with rows) at 0015 -> gone at 0016."""
+ engine = migrated_to_0015_engine
+ _create_legacy_cache_tables(engine, populate=True)
+ assert {"cache", "search_cache"} <= _tables(engine)
+
+ _run_upgrade_to(engine, "0016")
+
+ remaining = _tables(engine)
+ assert "cache" not in remaining
+ assert "search_cache" not in remaining
+
+ def test_indexes_dropped_with_tables(self, migrated_to_0015_engine):
+ """Dropping the tables removes their indexes too (SQLite behavior)."""
+ engine = migrated_to_0015_engine
+ _create_legacy_cache_tables(engine, populate=False)
+ assert _CACHE_INDEXES <= _index_names(engine)
+
+ _run_upgrade_to(engine, "0016")
+
+ assert not (_CACHE_INDEXES & _index_names(engine))
+
+ def test_clean_noop_when_tables_absent(self, migrated_to_0015_engine):
+ """Fresh-install / idempotent path: tables never existed -> clean no-op.
+
+ This is exactly the state every fresh DB reaches (models removed, so
+ 0001 never creates the tables). The has_table guard must skip the drop
+ without raising.
+ """
+ engine = migrated_to_0015_engine
+ assert "cache" not in _tables(engine)
+ assert "search_cache" not in _tables(engine)
+
+ _run_upgrade_to(engine, "0016") # must not raise
+
+ remaining = _tables(engine)
+ assert "cache" not in remaining
+ assert "search_cache" not in remaining
+
+ def test_0016_chains_to_0015_as_single_head(self, migrated_to_0015_engine):
+ from alembic.script import ScriptDirectory
+
+ cfg = 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:
+ """0016 must drop the tables on a real SQLCipher-encrypted user DB.
+
+ Per-user encrypted databases are the production database type. The DDL is
+ dialect-agnostic, but exercising the drop through the actual SQLCipher
+ engine and the real DatabaseManager creation path guards against any
+ encryption/connection-layer surprise. Skips only if a functional SQLCipher
+ backend is genuinely unavailable.
+ """
+
+ def test_drops_tables_on_encrypted_user_db(self, tmp_path, monkeypatch):
+ monkeypatch.setattr(
+ "local_deep_research.database.encrypted_db.get_data_directory",
+ lambda: tmp_path,
+ )
+ manager = DatabaseManager()
+ if not manager.has_encryption:
+ pytest.skip("Functional SQLCipher backend not available")
+
+ username, password = "encuser", "TestPassword123!"
+ engine = manager.create_user_database(username, password)
+ try:
+ # create_user_database migrated to head; roll the recorded version
+ # back to 0015 and add the legacy tables to simulate a pre-0016
+ # encrypted user DB that still carries them.
+ stamp_database(engine, "0015")
+ _create_legacy_cache_tables(engine, populate=True)
+ assert {"cache", "search_cache"} <= _tables(engine)
+
+ _run_upgrade_to(engine, "0016")
+
+ remaining = _tables(engine)
+ assert "cache" not in remaining
+ assert "search_cache" not in remaining
+ finally:
+ 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_orm_conversions.py b/tests/database/test_orm_conversions.py
index 5591345f57..71e9140129 100644
--- a/tests/database/test_orm_conversions.py
+++ b/tests/database/test_orm_conversions.py
@@ -18,7 +18,6 @@ from local_deep_research.database.models import (
ResearchHistory,
ResearchLog,
ResearchResource,
- SearchCache,
)
@@ -205,63 +204,6 @@ def test_research_log_orm_queries(test_db):
print("✓ ResearchLog ORM queries work correctly")
-def test_search_cache_orm_operations(test_db):
- """Test SearchCache ORM operations."""
- import json
- import time
-
- current_time = int(time.time())
-
- # Add cache entries
- cache1 = SearchCache(
- query_hash="hash123",
- query_text="quantum computing",
- results=json.dumps({"results": ["result1", "result2"]}),
- created_at=current_time,
- expires_at=current_time + 3600, # 1 hour
- last_accessed=current_time,
- )
- cache2 = SearchCache(
- query_hash="hash456",
- query_text="machine learning",
- results=json.dumps({"results": ["result3"]}),
- created_at=current_time + 60,
- expires_at=current_time + 3660,
- last_accessed=current_time + 60,
- )
-
- test_db.add_all([cache1, cache2])
- test_db.commit()
-
- # Query by hash
- found = test_db.query(SearchCache).filter_by(query_hash="hash123").first()
- assert found is not None
- assert found.query_text == "quantum computing"
- assert json.loads(found.results) == {"results": ["result1", "result2"]}
-
- # Query non-expired entries
- non_expired = (
- test_db.query(SearchCache)
- .filter(SearchCache.expires_at > current_time)
- .all()
- )
- assert len(non_expired) == 2
-
- # Test cache ordering by last accessed
- all_cache = (
- test_db.query(SearchCache)
- .order_by(SearchCache.last_accessed.desc())
- .all()
- )
- assert len(all_cache) == 2
- assert (
- all_cache[0].query_text == "machine learning"
- ) # Most recently accessed
- assert all_cache[0].query_hash == "hash456" # Most recent first
-
- print("✓ SearchCache ORM operations work correctly")
-
-
if __name__ == "__main__":
# Create in-memory database for testing
engine = create_engine("sqlite:///:memory:")
@@ -273,7 +215,6 @@ if __name__ == "__main__":
test_research_history_orm_queries(session)
test_research_resource_orm_operations(session)
test_research_log_orm_queries(session)
- test_search_cache_orm_operations(session)
print("\n✅ All ORM conversion tests passed!")
finally:
session.close()
diff --git a/tests/database/test_schema_migrations.py b/tests/database/test_schema_migrations.py
index 31eb32d440..7909e6f010 100644
--- a/tests/database/test_schema_migrations.py
+++ b/tests/database/test_schema_migrations.py
@@ -24,14 +24,12 @@ class TestSchemaMigrations:
from local_deep_research.database.models import auth
from local_deep_research.database.models import research
from local_deep_research.database.models import settings
- from local_deep_research.database.models import cache
from local_deep_research.database.models import metrics
from local_deep_research.database.models import queue
assert auth is not None
assert research is not None
assert settings is not None
- assert cache is not None
assert metrics is not None
assert queue is not None
@@ -73,15 +71,6 @@ class TestSchemaMigrations:
assert "key" in columns
assert "value" in columns
- def test_cache_model_schema(self):
- """Test cache model schema"""
- from local_deep_research.database.models.cache import Cache
-
- columns = Cache.__table__.columns.keys()
-
- assert "id" in columns
- assert "cache_key" in columns # Actual column name
-
def test_metrics_model_schema(self):
"""Test metrics model schema"""
from local_deep_research.database.models.metrics import TokenUsage
diff --git a/tests/database/test_schema_stability.py b/tests/database/test_schema_stability.py
index 7ce35d2104..1fbbcd3340 100644
--- a/tests/database/test_schema_stability.py
+++ b/tests/database/test_schema_stability.py
@@ -18,9 +18,6 @@ EXPECTED_TABLES = {
"api_keys",
"settings",
"user_settings",
- # Cache
- "cache",
- "search_cache",
# Queue
"queue_status",
"task_metadata",
diff --git a/tests/security/test_egress_cache_and_fullsearch.py b/tests/security/test_egress_fullsearch.py
similarity index 100%
rename from tests/security/test_egress_cache_and_fullsearch.py
rename to tests/security/test_egress_fullsearch.py
diff --git a/tests/test_database_initialization.py b/tests/test_database_initialization.py
index 906f222d75..1d30a8d180 100644
--- a/tests/test_database_initialization.py
+++ b/tests/test_database_initialization.py
@@ -54,7 +54,6 @@ class TestDatabaseInitialization:
"journals",
"app_logs", # Correct table name
"queued_researches", # Correct table name
- "search_cache",
"token_usage",
"research_ratings",
]