~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
refactor(models): type library and Zotero ORM mappings (#5329)
LearningCircuitcbb473885ad0
diff --git a/src/local_deep_research/database/models/library.py b/src/local_deep_research/database/models/library.pyindex fcdfc2f27d..824ba9777e 100644--- a/src/local_deep_research/database/models/library.py+++ b/src/local_deep_research/database/models/library.py@@ -6,6 +6,7 @@ Collections organize documents, with "Library" as the default collection.import enumimport warnings+from datetime import datetimefrom sqlalchemy import (JSON,@@ -21,7 +22,7 @@ from sqlalchemy import (Text,UniqueConstraint,)-from sqlalchemy.orm import backref, relationship+from sqlalchemy.orm import Mapped, backref, mapped_column, relationshipfrom sqlalchemy_utc import UtcDateTime, utcnowfrom .base import Base@@ -417,22 +418,26 @@ class Collection(Base):__tablename__ = "collections"- id = Column(String(36), primary_key=True) # UUID as string- name = Column(String(255), nullable=False)- description = Column(Text)+ id: Mapped[str] = mapped_column(+ String(36), primary_key=True+ ) # UUID as string+ name: Mapped[str] = mapped_column(String(255), nullable=False)+ description: Mapped[str | None] = mapped_column(Text)# Collection type (default_library, user_collection, linked_folder)- collection_type = Column(String(50), default="user_collection")+ collection_type: Mapped[str | None] = mapped_column(+ String(50), default="user_collection"+ )# Is this the default library collection?- is_default = Column(Boolean, default=False)+ is_default: Mapped[bool | None] = mapped_column(Boolean, default=False)# Egress classification: is this collection's content non-sensitive# ("public") or sensitive ("private")? Defaults to private (False) — the# safe choice. A private collection is excluded under PUBLIC_ONLY scope# and forces local LLM/embeddings inference when used, so its chunks# never reach a cloud model. Operators flip it per-collection.- is_public = Column(Boolean, default=False)+ is_public: Mapped[bool | None] = mapped_column(Boolean, default=False)# Whether this collection is offered to the research agent (LangGraph) as a# specialized search tool. Defaults to True (available) so existing@@ -440,53 +445,61 @@ class Collection(Base):# agent's tool list when a collection isn't needed for agentic research.# Independent of is_public / egress scope — this is a usability switch, not# a security control.- agent_enabled = Column(Boolean, default=True)+ agent_enabled: Mapped[bool | None] = mapped_column(Boolean, default=True)# Embedding model used for this collection (stored when first indexed)- embedding_model = Column(+ embedding_model: Mapped[str | None] = mapped_column(String(100), nullable=True) # e.g., 'all-MiniLM-L6-v2', 'nomic-embed-text:latest'- embedding_model_type = Column(+ embedding_model_type: Mapped[EmbeddingProvider | None] = mapped_column(Enum(EmbeddingProvider,values_callable=lambda obj: [e.value for e in obj],),nullable=True,)- embedding_dimension = Column(Integer, nullable=True) # Vector dimension- chunk_size = Column(Integer, nullable=True) # Chunk size used- chunk_overlap = Column(Integer, nullable=True) # Chunk overlap used+ embedding_dimension: Mapped[int | None] = mapped_column(+ Integer, nullable=True+ ) # Vector dimension+ chunk_size: Mapped[int | None] = mapped_column(+ Integer, nullable=True+ ) # Chunk size used+ chunk_overlap: Mapped[int | None] = mapped_column(+ Integer, nullable=True+ ) # Chunk overlap used# Advanced embedding configuration options (Issue #1054)- splitter_type = Column(+ splitter_type: Mapped[str | None] = mapped_column(String(50), nullable=True) # Splitter type: 'recursive', 'semantic', 'token', 'sentence'- text_separators = Column(+ text_separators: Mapped[list[str] | None] = mapped_column(JSON, nullable=True) # Text separators for chunking, e.g., ["\n\n", "\n", ". ", " ", ""]- distance_metric = Column(+ distance_metric: Mapped[str | None] = mapped_column(String(50), nullable=True) # Distance metric: 'cosine', 'l2', 'dot_product'- normalize_vectors = Column(+ normalize_vectors: Mapped[bool | None] = mapped_column(Boolean, nullable=True) # Whether to normalize embeddings with L2- index_type = Column(+ index_type: Mapped[str | None] = mapped_column(String(50), nullable=True) # FAISS index type: 'flat', 'hnsw', 'ivf'# Timestamps- created_at = Column(UtcDateTime, default=utcnow(), nullable=False)- updated_at = Column(+ created_at: Mapped[datetime] = mapped_column(+ UtcDateTime, default=utcnow(), nullable=False+ )+ updated_at: Mapped[datetime] = mapped_column(UtcDateTime, default=utcnow(), onupdate=utcnow(), nullable=False)# Relationships- document_links = relationship(+ document_links: Mapped[list["DocumentCollection"]] = relationship("DocumentCollection",back_populates="collection",cascade="all, delete-orphan",)- linked_folders = relationship(+ linked_folders: Mapped[list["CollectionFolder"]] = relationship("CollectionFolder",back_populates="collection",cascade="all, delete-orphan",@@ -504,16 +517,18 @@ class DocumentCollection(Base):__tablename__ = "document_collections"- id = Column(Integer, primary_key=True, autoincrement=True)+ id: Mapped[int] = mapped_column(+ Integer, primary_key=True, autoincrement=True+ )# Foreign keys- document_id = Column(+ document_id: Mapped[str] = mapped_column(String(36),ForeignKey("documents.id", ondelete="CASCADE"),nullable=False,index=True,)- collection_id = Column(+ collection_id: Mapped[str] = mapped_column(String(36),ForeignKey("collections.id", ondelete="CASCADE"),nullable=False,@@ -521,20 +536,28 @@ class DocumentCollection(Base):)# Indexing status (per collection!)- indexed = Column(+ indexed: Mapped[bool | None] = mapped_column(Boolean, default=False) # Whether indexed for this collection- chunk_count = Column(+ chunk_count: Mapped[int | None] = mapped_column(Integer, default=0) # Number of chunks in this collection- last_indexed_at = Column(UtcDateTime, nullable=True)+ last_indexed_at: Mapped[datetime | None] = mapped_column(+ UtcDateTime, nullable=True+ )# Timestamps- added_at = Column(UtcDateTime, default=utcnow(), nullable=False)+ added_at: Mapped[datetime] = mapped_column(+ UtcDateTime, default=utcnow(), nullable=False+ )# Relationships- document = relationship("Document", back_populates="collections")- collection = relationship("Collection", back_populates="document_links")+ document: Mapped["Document"] = relationship(+ "Document", back_populates="collections"+ )+ collection: Mapped["Collection"] = relationship(+ "Collection", back_populates="document_links"+ )# Ensure one entry per document-collection pair__table_args__ = (@@ -747,73 +770,85 @@ class RAGIndex(Base):__tablename__ = "rag_indices"- id = Column(Integer, primary_key=True, autoincrement=True)+ id: Mapped[int] = mapped_column(+ Integer, primary_key=True, autoincrement=True+ )# Collection and model identification- collection_name = Column(+ collection_name: Mapped[str] = mapped_column(String(100), nullable=False, index=True) # 'collection_<uuid>'- embedding_model = Column(+ embedding_model: Mapped[str] = mapped_column(String(100), nullable=False) # e.g., 'all-MiniLM-L6-v2'- embedding_model_type = Column(+ embedding_model_type: Mapped[EmbeddingProvider] = mapped_column(Enum(EmbeddingProvider,values_callable=lambda obj: [e.value for e in obj],),nullable=False,)- embedding_dimension = Column(Integer, nullable=False) # Vector dimension+ embedding_dimension: Mapped[int] = mapped_column(+ Integer, nullable=False+ ) # Vector dimension# Index file location- index_path = Column(Text, nullable=False) # Path to .faiss file- index_hash = Column(+ index_path: Mapped[str] = mapped_column(+ Text, nullable=False+ ) # Path to .faiss file+ index_hash: Mapped[str] = mapped_column(String(64), nullable=False, unique=True, index=True) # SHA256 of collection+model for uniqueness# Chunking parameters used- chunk_size = Column(Integer, nullable=False)- chunk_overlap = Column(Integer, nullable=False)+ chunk_size: Mapped[int] = mapped_column(Integer, nullable=False)+ chunk_overlap: Mapped[int] = mapped_column(Integer, nullable=False)# Advanced embedding configuration options (Issue #1054)- splitter_type = Column(+ splitter_type: Mapped[str | None] = mapped_column(String(50), nullable=True) # Splitter type: 'recursive', 'semantic', 'token', 'sentence'- text_separators = Column(+ text_separators: Mapped[list[str] | None] = mapped_column(JSON, nullable=True) # Text separators for chunking, e.g., ["\n\n", "\n", ". ", " ", ""]- distance_metric = Column(+ distance_metric: Mapped[str | None] = mapped_column(String(50), nullable=True) # Distance metric: 'cosine', 'l2', 'dot_product'- normalize_vectors = Column(+ normalize_vectors: Mapped[bool | None] = mapped_column(Boolean, nullable=True) # Whether to normalize embeddings with L2- index_type = Column(+ index_type: Mapped[str | None] = mapped_column(String(50), nullable=True) # FAISS index type: 'flat', 'hnsw', 'ivf'# Index statistics- chunk_count = Column(Integer, default=0) # Number of chunks in this index- total_documents = Column(Integer, default=0) # Number of source documents+ chunk_count: Mapped[int | None] = mapped_column(+ Integer, default=0+ ) # Number of chunks in this index+ total_documents: Mapped[int | None] = mapped_column(+ Integer, default=0+ ) # Number of source documents# Status- status = Column(+ status: Mapped[RAGIndexStatus] = mapped_column(Enum(RAGIndexStatus, values_callable=lambda obj: [e.value for e in obj]),nullable=False,default=RAGIndexStatus.ACTIVE,)- is_current = Column(+ is_current: Mapped[bool | None] = mapped_column(Boolean, default=True) # Whether this is the current index for this collection# Timestamps- created_at = Column(UtcDateTime, default=utcnow(), nullable=False)- last_updated_at = Column(+ created_at: Mapped[datetime] = mapped_column(+ UtcDateTime, default=utcnow(), nullable=False+ )+ last_updated_at: Mapped[datetime] = mapped_column(UtcDateTime, default=utcnow(), onupdate=utcnow(), nullable=False)- last_used_at = Column(+ last_used_at: Mapped[datetime | None] = mapped_column(UtcDateTime, nullable=True) # Last time index was searcheddiff --git a/src/local_deep_research/database/models/zotero.py b/src/local_deep_research/database/models/zotero.pyindex 4eec467ea5..be584fbd69 100644--- a/src/local_deep_research/database/models/zotero.py+++ b/src/local_deep_research/database/models/zotero.py@@ -22,6 +22,8 @@ full-map comparison does."""+from datetime import datetime+from sqlalchemy import (Boolean,Column,@@ -31,6 +33,7 @@ from sqlalchemy import (Text,UniqueConstraint,)+from sqlalchemy.orm import Mapped, mapped_columnfrom sqlalchemy_utc import UtcDateTime, utcnowfrom .base import Base@@ -105,18 +108,24 @@ class ZoteroItemMap(Base):),)- id = Column(Integer, primary_key=True, autoincrement=True)+ id: Mapped[int] = mapped_column(+ Integer, primary_key=True, autoincrement=True+ )- ldr_collection_id = Column(+ ldr_collection_id: Mapped[str] = mapped_column(String(36),ForeignKey("collections.id", ondelete="CASCADE"),nullable=False,index=True,)# The Zotero (parent) item key this row tracks.- zotero_item_key = Column(String(16), nullable=False, index=True)+ zotero_item_key: Mapped[str] = mapped_column(+ String(16), nullable=False, index=True+ )# Zotero item version at last import — used for change detection.- zotero_version = Column(Integer, nullable=False, default=0)+ zotero_version: Mapped[int] = mapped_column(+ Integer, nullable=False, default=0+ )# The LDR document this item was imported as. SET NULL on document# deletion so a removed document doesn't dangle. A null document_id marks@@ -124,17 +133,23 @@ class ZoteroItemMap(Base):# locally); the sync service re-imports it only when the item's Zotero# version changes. A non-null document_id whose Document row went missing# IS re-imported on the next sync.- document_id = Column(+ document_id: Mapped[str | None] = mapped_column(String(36),ForeignKey("documents.id", ondelete="SET NULL"),nullable=True,index=True,)- has_pdf = Column(Boolean, nullable=False, default=False)+ has_pdf: Mapped[bool] = mapped_column(+ Boolean, nullable=False, default=False+ )- last_synced_at = Column(UtcDateTime, nullable=True)- created_at = Column(UtcDateTime, default=utcnow(), nullable=False)- updated_at = Column(+ last_synced_at: Mapped[datetime | None] = mapped_column(+ UtcDateTime, nullable=True+ )+ created_at: Mapped[datetime] = mapped_column(+ UtcDateTime, default=utcnow(), nullable=False+ )+ updated_at: Mapped[datetime] = mapped_column(UtcDateTime, default=utcnow(), onupdate=utcnow(), nullable=False)diff --git a/src/local_deep_research/research_library/services/library_rag_service.py b/src/local_deep_research/research_library/services/library_rag_service.pyindex 3e0fef8743..0d7eb88744 100644--- a/src/local_deep_research/research_library/services/library_rag_service.py+++ b/src/local_deep_research/research_library/services/library_rag_service.py@@ -32,6 +32,7 @@ from ...database.models.library import (DocumentCollection,Collection,RAGIndex,+ RAGIndexStatus,RagDocumentStatus,EmbeddingProvider,)@@ -737,7 +738,7 @@ class LibraryRAGService:index_type=self.index_type,chunk_count=0,total_documents=0,- status="active",+ status=RAGIndexStatus.ACTIVE,is_current=True,)session.add(rag_index)diff --git a/src/local_deep_research/vector_stores/legacy_rekey.py b/src/local_deep_research/vector_stores/legacy_rekey.pyindex c4834673d9..297458d574 100644--- a/src/local_deep_research/vector_stores/legacy_rekey.py+++ b/src/local_deep_research/vector_stores/legacy_rekey.py@@ -31,7 +31,7 @@ once the fleet has passed through the cutover once.import jsonimport timefrom pathlib import Path-from typing import Dict, Iterable, List, Optional, cast+from typing import Dict, Iterable, List, Optionalfrom loguru import logger@@ -464,12 +464,7 @@ def rekey_user_indexes(username: str, db_password: str) -> Dict[str, int]:# legacy file — withhold the marker and retry next login.try:params = _resolve_index_params(rag_index, settings)- # SQLAlchemy's legacy Column() declarative style types instance- # attribute access as Column[int] rather than int; cast() is a- # no-op at runtime.- _persist_rekeyed_config(- username, db_password, cast(int, rag_index.id), params- )+ _persist_rekeyed_config(username, db_password, rag_index.id, params)except Exception as exc:safe_msg = redact_secrets(str(exc), db_password)logger.warning(@@ -549,9 +544,7 @@ def rekey_user_indexes(username: str, db_password: str) -> Dict[str, int]:integrity_manager.record_file(faiss_path,related_entity_type="rag_index",- # cast(): rag_index.id is Column[int] under the legacy- # Column() declarative style; a no-op at runtime.- related_entity_id=cast(int, rag_index.id),+ related_entity_id=rag_index.id,)# Config was already pinned before the build (see above), so# Phase B only records integrity and drops the sidecar signal.diff --git a/tests/research_library/services/test_library_rag_service_coverage.py b/tests/research_library/services/test_library_rag_service_coverage.pyindex 3973e92d0e..9db825549f 100644--- a/tests/research_library/services/test_library_rag_service_coverage.py+++ b/tests/research_library/services/test_library_rag_service_coverage.py@@ -17,6 +17,8 @@ from unittest.mock import MagicMock, patchimport pytest+from local_deep_research.database.models.library import RAGIndexStatus+# ---------------------------------------------------------------------------# Module-level patch path prefix# ---------------------------------------------------------------------------@@ -183,6 +185,28 @@ class TestGetOrCreateRagIndex:mock_session.commit.assert_called_once()mock_session.refresh.assert_called_once()+ @patch(f"{_MOD}.get_cache_directory")+ @patch(f"{_MOD}.get_user_db_session")+ def test_new_index_constructs_enum_status(+ self, mock_session_ctx, mock_cache_dir, tmp_path+ ):+ mock_cache_dir.return_value = tmp_path+ svc = _make_service()+ svc.embedding_manager = MagicMock()+ svc.embedding_manager.embeddings.embed_query.return_value = [0.0] * 384++ mock_session = MagicMock()+ mock_session_ctx.return_value.__enter__ = MagicMock(+ return_value=mock_session+ )+ mock_session_ctx.return_value.__exit__ = MagicMock(return_value=None)+ mock_session.query.return_value.filter_by.return_value.first.return_value = None++ svc._get_or_create_rag_index("coll-status")++ created_index = mock_session.add.call_args.args[0]+ assert type(created_index.status) is RAGIndexStatus+@patch(f"{_MOD}.get_cache_directory")@patch(f"{_MOD}.get_user_db_session")def test_embeds_test_string_for_dimension(diff --git a/tests/vector_stores/test_migrate_legacy_index_files.py b/tests/vector_stores/test_migrate_legacy_index_files.pyindex 1c19924a2e..2757c4116e 100644--- a/tests/vector_stores/test_migrate_legacy_index_files.py+++ b/tests/vector_stores/test_migrate_legacy_index_files.py@@ -43,6 +43,7 @@ from local_deep_research.database.models import Basefrom local_deep_research.database.models.library import (EmbeddingProvider,RAGIndex,+ RAGIndexStatus,)from local_deep_research.research_library.services.library_rag_service import (LibraryRAGService,@@ -130,7 +131,7 @@ def _make_rag_index(session, index_path) -> RAGIndex:index_hash="a" * 64,chunk_size=500,chunk_overlap=50,- status="active",+ status=RAGIndexStatus.ACTIVE,is_current=True,)session.add(idx)