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.

Merge dev and address djpetti's PR feedback

LearningCircuit082906fc2e79
diff --cc .gitleaks.toml
index cc43a077c1,3c98d87780..53027fb9d3
--- a/.gitleaks.toml
+++ b/.gitleaks.toml
@@@ -82,11 -82,7 +82,12 @@@ paths =
'''.*example.*\.py$''',
'''mock.*\.py$''',
'''fixture.*\.py$''',
+ '''src/local_deep_research/security/file_integrity/.*\.py$''',
+ '''src/local_deep_research/library/download_management/.*\.py$''',
+ '''src/local_deep_research/research_library/services/download_service\.py$''',
+ '''src/local_deep_research/research_library/routes/library_routes\.py$''',
- '''src/local_deep_research/news/subscription_manager/scheduler\.py$'''
++ '''src/local_deep_research/news/subscription_manager/scheduler\.py$''',
+ '''pdm\.lock$''' # Contains SHA256 package hashes (not secrets)
]
files = [
"\\.env\\.example$",
@@@ -108,30 -106,14 +113,38 @@@ regexes =
# Allow comments that explain API key usage but don't contain actual keys
'''# API_KEY: OpenRouter API key''',
'''OPENROUTER_API_KEY''',
+ # Password parameters and variable assignments (not actual secrets)
+ '''self\.password = password''',
+ '''self\.username = username''',
+ '''password: Optional\[str\]''',
+ '''username: str, password: Optional''',
+ # Database session context - parameter passing
+ '''get_user_db_session\(self\.username, self\.password\)''',
+ '''get_user_db_session\(username, password\)''',
+ '''username=username, password=password''',
+ # Session password storage (encrypted in session)
+ '''user_password = session_password_store''',
+ '''get_session_password''',
+ '''user_password = getattr''',
+ # Allow variable names containing password/secret (not actual values)
+ '''user_password\s*=''',
+ '''password\s*:\s*Optional''',
+ '''password\s*:\s*str''',
+ '''session_password_store''',
+ '''password\)\s*:''',
+ # Allow parameter names and type hints
+ '''\bpassword:\s*Optional\[str\]''',
+ '''\bpassword:\s*str\b''',
+ # Allow getattr patterns for password retrieval
- '''getattr\(g,\s*["']user_password["']'''
++ '''getattr\(g,\s*["']user_password["']''',
+ # Allow user_password parameter names (not actual passwords)
+ '''user_password\s*=\s*user_password''',
+ '''user_password=user_password''',
+ # Allow SHA256 hashes in pdm.lock (package integrity hashes)
+ '''hash\s*=\s*"sha256:[a-fA-F0-9]{64}"''',
+ '''content_hash\s*=\s*"sha256:[a-fA-F0-9]{64}"''',
+ # Allow CSRF token meta tag selectors (JavaScript, not actual secrets)
+ '''csrf_token\s*=\s*document\.querySelector'''
]
# Target specific files for scanning
diff --cc src/local_deep_research/database/models/library.py
index 94cb4b62e9,c2e6409628..82893f9bc4
--- a/src/local_deep_research/database/models/library.py
+++ b/src/local_deep_research/database/models/library.py
@@@ -33,78 -32,13 +33,130 @@@ class RAGIndexStatus(enum.Enum)
DEPRECATED = "deprecated"
-class LibraryDocument(Base):
+class DocumentStatus(enum.Enum):
+ """Status values for document processing and downloads."""
+
+ PENDING = "pending"
+ PROCESSING = "processing"
+ COMPLETED = "completed"
+ FAILED = "failed"
+
+
+class EmbeddingProvider(enum.Enum):
+ """Embedding model provider types."""
+
+ SENTENCE_TRANSFORMERS = "sentence_transformers"
+ OLLAMA = "ollama"
+
+
++class ExtractionMethod(str, enum.Enum):
++ """Methods used to extract text from documents."""
++
++ PDF_EXTRACTION = "pdf_extraction"
++ NATIVE_API = "native_api"
++ UNKNOWN = "unknown"
++
++
++class ExtractionSource(str, enum.Enum):
++ """Sources used for text extraction."""
++
++ ARXIV_API = "arxiv_api"
++ PUBMED_API = "pubmed_api"
++ PDFPLUMBER = "pdfplumber"
++ PDFPLUMBER_FALLBACK = "pdfplumber_fallback"
++ LOCAL_PDF = "local_pdf"
++ LEGACY_FILE = "legacy_file"
++
++
++class ExtractionQuality(str, enum.Enum):
++ """Quality levels for extracted text."""
++
++ HIGH = "high"
++ MEDIUM = "medium"
++ LOW = "low"
++
++
++class DistanceMetric(str, enum.Enum):
++ """Distance metrics for vector similarity search."""
++
++ COSINE = "cosine"
++ L2 = "l2"
++ DOT_PRODUCT = "dot_product"
++
++
++class IndexType(str, enum.Enum):
++ """FAISS index types for RAG."""
++
++ FLAT = "flat"
++ HNSW = "hnsw"
++ IVF = "ivf"
++
++
++class SplitterType(str, enum.Enum):
++ """Text splitter types for chunking."""
++
++ RECURSIVE = "recursive"
++ SEMANTIC = "semantic"
++ TOKEN = "token"
++ SENTENCE = "sentence"
++
++
+class SourceType(Base):
+ """
+ Document source types (research_download, user_upload, manual_entry, etc.).
+ Normalized table for consistent categorization.
+ """
+
+ __tablename__ = "source_types"
+
+ id = Column(String(36), primary_key=True) # UUID
+ name = Column(String(50), nullable=False, unique=True, index=True)
+ display_name = Column(String(100), nullable=False)
+ description = Column(Text)
+ icon = Column(String(50)) # Icon name for UI
+
+ # Timestamps
+ created_at = Column(UtcDateTime, default=utcnow(), nullable=False)
+
+ def __repr__(self):
+ return (
+ f"<SourceType(name='{self.name}', display='{self.display_name}')>"
+ )
+
+
+class UploadBatch(Base):
+ """
+ Tracks batches of user-uploaded files.
+ Groups uploads for traceability and batch operations.
+ """
+
+ __tablename__ = "upload_batches"
+
+ id = Column(String(36), primary_key=True) # UUID
+ collection_id = Column(
+ String(36),
+ ForeignKey("collections.id", ondelete="CASCADE"),
+ nullable=False,
+ index=True,
+ )
+ uploaded_at = Column(UtcDateTime, default=utcnow(), nullable=False)
+ file_count = Column(Integer, default=0)
+ total_size = Column(Integer, default=0) # Total bytes
+
+ # Relationships
+ collection = relationship("Collection", backref="upload_batches")
+ documents = relationship("Document", backref="upload_batch")
+
+ def __repr__(self):
+ return f"<UploadBatch(id='{self.id}', files={self.file_count}, size={self.total_size})>"
+
+
+class Document(Base):
"""
- Documents downloaded and stored in the user's library.
- Links to ResearchResource entries.
+ Unified document table for all documents (research downloads + user uploads).
"""
- __tablename__ = "library_documents"
+ __tablename__ = "documents"
id = Column(String(36), primary_key=True) # UUID as string
diff --cc src/local_deep_research/defaults/settings_document_scheduler.json
index 5f23e18d0c,0000000000..f15f440209
mode 100644,000000..100644
--- a/src/local_deep_research/defaults/settings_document_scheduler.json
+++ b/src/local_deep_research/defaults/settings_document_scheduler.json
@@@ -1,72 -1,0 +1,72 @@@
+{
+ "document_scheduler.enabled": {
+ "category": "document_scheduler",
+ "description": "Enable automatic document processing from research history",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Enable Document Scheduler",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": true
+ },
+ "document_scheduler.interval_seconds": {
+ "category": "document_scheduler",
+ "description": "How often to process new research (seconds)",
+ "editable": true,
+ "max_value": 86400,
+ "min_value": 60,
+ "name": "Processing Interval (seconds)",
+ "options": null,
+ "step": 60,
+ "type": "APP",
+ "ui_element": "number",
+ "value": 1800,
+ "visible": true
+ },
+ "document_scheduler.download_pdfs": {
+ "category": "document_scheduler",
- "description": "Automatically download PDF files during scheduled document processing. Files will be stored on disk (requires storage space).",
++ "description": "Automatically download PDF files during scheduled document processing. Files will be stored on disk (requires storage space). WARNING: Downloaded files are stored unencrypted on disk.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Auto-Download PDFs (Scheduler)",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
+ },
+ "document_scheduler.extract_text": {
+ "category": "document_scheduler",
+ "description": "Extract text content to database (minimal space usage)",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Extract Text to Database",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": true
+ },
+ "document_scheduler.generate_rag": {
+ "category": "document_scheduler",
+ "description": "Generate RAG embeddings for semantic search",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Generate RAG Embeddings",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
+ }
+}
diff --cc src/local_deep_research/library/download_management/filters/resource_filter.py
index 5e562be8cb,0000000000..b865c04493
mode 100644,000000..100644
--- a/src/local_deep_research/library/download_management/filters/resource_filter.py
+++ b/src/local_deep_research/library/download_management/filters/resource_filter.py
@@@ -1,164 -1,0 +1,164 @@@
+"""
+Resource Filter
+
+Smart filtering logic for downloadable resources based on failure history,
+cooldowns, and retry policies. Replaces simple file existence checks with
+intelligent retry management.
+"""
+
+from typing import List, Optional
+
+from loguru import logger
+
+from ..retry_manager import RetryManager, ResourceFilterResult, FilterSummary
+
+
+class ResourceFilter:
+ """Filter resources for download based on history and policies"""
+
+ def __init__(self, username: str, password: Optional[str] = None):
+ """
+ Initialize the resource filter.
+
+ Args:
+ username: Username for database access
+ password: Optional password for encrypted database
+ """
+ self.username = username
+ self.retry_manager = RetryManager(username, password)
+ logger.info(f"Initialized for user: {username}")
+
+ def filter_downloadable_resources(
+ self, resources: List, check_files: bool = True
+ ) -> List[ResourceFilterResult]:
+ """
+ Filter resources that are available for download.
+
+ Args:
+ resources: List of ResearchResource objects to filter
+ check_files: Whether to also check for existing text files (legacy behavior)
+
+ Returns:
+ List of ResourceFilterResult objects with retry decisions
+ """
- logger.info(f"[RESOURCE_FILTER] Filtering {len(resources)} resources")
++ logger.info(f"Filtering {len(resources)} resources")
+
+ # Use retry manager to filter based on failure history
+ results = self.retry_manager.filter_resources(resources)
+
+ # Optional legacy file existence check
+ if check_files:
+ results = self._apply_legacy_file_check(results)
+
+ return results
+
+ def _apply_legacy_file_check(
+ self, results: List[ResourceFilterResult]
+ ) -> List[ResourceFilterResult]:
+ """
+ Apply legacy file existence checking to filter results.
+
+ Args:
+ results: Existing filter results to modify
+
+ Returns:
+ Updated filter results with file existence check
+ """
+ # This would get the download service instance to check for existing files
+ # For now, we'll skip this as the retry manager handles the main logic
+ return results
+
+ def get_filter_summary(
+ self, resources: List, check_files: bool = True
+ ) -> FilterSummary:
+ """
+ Get a summary of filtering results.
+
+ Args:
+ resources: List of resources that were filtered
+ check_files: Whether file existence checking was applied
+
+ Returns:
+ FilterSummary object with detailed counts
+ """
+ results = self.filter_downloadable_resources(resources, check_files)
+ return self.retry_manager.get_filter_summary(results)
+
+ def get_skipped_resources_info(self, resources: List) -> dict:
+ """
+ Get detailed information about skipped resources for UI display.
+
+ Args:
+ resources: List of all resources
+
+ Returns:
+ Dictionary with detailed skip information
+ """
+ results = self.filter_downloadable_resources(resources)
+
+ skipped_resources = []
+ for result in results:
+ if not result.can_retry:
+ status_info = (
+ self.retry_manager.status_tracker.get_resource_status(
+ result.resource_id
+ )
+ )
+ skipped_resources.append(
+ {
+ "resource_id": result.resource_id,
+ "status": result.status,
+ "reason": result.reason,
+ "estimated_wait_minutes": result.estimated_wait.total_seconds()
+ // 60
+ if result.estimated_wait
+ else None,
+ "status_info": status_info,
+ }
+ )
+
+ return {
+ "total_skipped": len(skipped_resources),
+ "permanently_failed": [
+ r
+ for r in skipped_resources
+ if r["status"] == "permanently_failed"
+ ],
+ "temporarily_failed": [
+ r
+ for r in skipped_resources
+ if r["status"] == "temporarily_failed"
+ ],
+ "other_skipped": [
+ r
+ for r in skipped_resources
+ if r["status"]
+ not in ["permanently_failed", "temporarily_failed"]
+ ],
+ "skipped_resources": skipped_resources,
+ }
+
+ def should_skip_resource(self, resource_id: int) -> tuple[bool, str]:
+ """
+ Quick check if a specific resource should be skipped.
+
+ Args:
+ resource_id: Resource identifier
+
+ Returns:
+ Tuple of (should_skip, reason)
+ """
+ decision = self.retry_manager.should_retry_resource(resource_id)
+ return (
+ not decision.can_retry,
+ decision.reason or "Resource not available for retry",
+ )
+
+ def get_retry_statistics(self) -> dict:
+ """
+ Get retry statistics for monitoring and debugging.
+
+ Returns:
+ Dictionary with retry statistics
+ """
+ return self.retry_manager.get_retry_statistics()
diff --cc src/local_deep_research/library/download_management/models/__init__.py
index 0b830b9b7a,0000000000..144839b4ae
mode 100644,000000..100644
--- a/src/local_deep_research/library/download_management/models/__init__.py
+++ b/src/local_deep_research/library/download_management/models/__init__.py
@@@ -1,66 -1,0 +1,74 @@@
+"""
+Database Models for Download Management
+
+Contains ORM models for tracking resource download status and retry logic.
+"""
+
+from datetime import datetime, UTC
+from enum import Enum
+from functools import partial
+from sqlalchemy import Column, Integer, String, Text, DateTime
+from sqlalchemy.ext.declarative import declarative_base
+
+Base = declarative_base()
+
+
+class FailureType(str, Enum):
+ """Enum for failure types - ensures consistency across the codebase"""
+
+ NOT_FOUND = "not_found"
+ FORBIDDEN = "forbidden"
+ GONE = "gone"
+ RATE_LIMITED = "rate_limited"
+ SERVER_ERROR = "server_error"
+ RECAPTCHA_PROTECTION = "recaptcha_protection"
+ INCOMPATIBLE_FORMAT = "incompatible_format"
+ TIMEOUT = "timeout"
+ NETWORK_ERROR = "network_error"
+ UNKNOWN_ERROR = "unknown_error"
+
+
++class DownloadStatus(str, Enum):
++ """Status values for resource download tracking."""
++
++ AVAILABLE = "available"
++ TEMPORARILY_FAILED = "temporarily_failed"
++ PERMANENTLY_FAILED = "permanently_failed"
++
++
+class ResourceDownloadStatus(Base):
+ """Database model for tracking resource download status"""
+
+ __tablename__ = "resource_download_status"
+
+ id = Column(Integer, primary_key=True)
+ resource_id = Column(Integer, unique=True, nullable=False, index=True)
+
+ # Status tracking
+ status = Column(
+ String(50), nullable=False, default="available"
+ ) # available, temporarily_failed, permanently_failed
+ failure_type = Column(String(100)) # not_found, rate_limited, timeout, etc.
+ failure_message = Column(Text)
+
+ # Retry timing
+ retry_after_timestamp = Column(
+ DateTime
+ ) # When this can be retried (NULL = permanent)
+ last_attempt_at = Column(DateTime)
+ permanent_failure_at = Column(DateTime) # When permanently failed
+
+ # Statistics
+ total_retry_count = Column(Integer, default=0)
+ today_retry_count = Column(Integer, default=0)
+
+ # Timestamps
+ created_at = Column(DateTime, default=partial(datetime.now, UTC))
+ updated_at = Column(
+ DateTime,
+ default=partial(datetime.now, UTC),
+ onupdate=partial(datetime.now, UTC),
+ )
+
+ def __repr__(self):
+ return f"<ResourceDownloadStatus(resource_id={self.resource_id}, status='{self.status}', failure_type='{self.failure_type}')>"
diff --cc src/local_deep_research/research_library/downloaders/arxiv.py
index 4067b65172,2a99869fad..53e97f63c1
--- a/src/local_deep_research/research_library/downloaders/arxiv.py
+++ b/src/local_deep_research/research_library/downloaders/arxiv.py
@@@ -7,8 -7,7 +7,7 @@@ from typing import Optiona
from urllib.parse import urlparse
from loguru import logger
--from .base import BaseDownloader, ContentType, DownloadResult
- from ...__version__ import __version__
++from .base import BaseDownloader, ContentType, DownloadResult, USER_AGENT
class ArxivDownloader(BaseDownloader):
@@@ -102,17 -101,7 +101,17 @@@
pdf_url = f"https://arxiv.org/pdf/{arxiv_id}.pdf"
logger.info(f"Downloading arXiv PDF: {arxiv_id}")
- return super()._download_pdf(pdf_url)
+
+ # Use honest user agent - arXiv supports academic tools with proper identification
+ enhanced_headers = {
- "User-Agent": f"Local-Deep-Research/{__version__} (Academic Research Tool; https://github.com/LearningCircuit/local-deep-research)",
++ "User-Agent": USER_AGENT,
+ "Accept": "application/pdf,application/octet-stream,*/*",
+ "Accept-Language": "en-US,en;q=0.9",
+ "Accept-Encoding": "gzip, deflate, br",
+ "Connection": "keep-alive",
+ }
+
+ return super()._download_pdf(pdf_url, headers=enhanced_headers)
def _download_text(self, url: str) -> Optional[bytes]:
"""Get full text content from arXiv PDF (with metadata from API)."""
diff --cc src/local_deep_research/research_library/downloaders/base.py
index d9a45d3818,d9a45d3818..aee43c1af6
--- a/src/local_deep_research/research_library/downloaders/base.py
+++ b/src/local_deep_research/research_library/downloaders/base.py
@@@ -13,6 -13,6 +13,11 @@@ from loguru import logge
from ...web_search_engines.rate_limiting import (
AdaptiveRateLimitTracker,
)
++from ...__version__ import __version__
++
++# Centralized User-Agent for academic content downloads
++# Using honest identification as recommended by academic sources
++USER_AGENT = f"Local-Deep-Research/{__version__} (Academic Research Tool; https://github.com/LearningCircuit/local-deep-research)"
class ContentType(Enum):
@@@ -42,11 -42,11 +47,7 @@@ class BaseDownloader(ABC)
"""
self.timeout = timeout
self.session = requests.Session()
-- self.session.headers.update(
-- {
-- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
-- }
-- )
++ self.session.headers.update({"User-Agent": USER_AGENT})
# Initialize rate limiter for PDF downloads
# We'll use domain-specific rate limiting
diff --cc src/local_deep_research/research_library/routes/library_routes.py
index dfd415c9f4,2fa7c8d038..a8126be4f5
--- a/src/local_deep_research/research_library/routes/library_routes.py
+++ b/src/local_deep_research/research_library/routes/library_routes.py
@@@ -133,6 -126,6 +133,59 @@@ def is_downloadable_domain(url: str) -
return False
++def get_authenticated_user_password(
++ username: str, flask_session_id: str = None
++):
++ """
++ Get authenticated user password from session store with fallback to g.user_password.
++
++ Args:
++ username: The username to get password for
++ flask_session_id: Optional Flask session ID. If not provided, uses session.get("_id")
++
++ Returns:
++ tuple: (password, error_response) where error_response is None on success,
++ or a Flask response tuple on failure
++ """
++ from ...database.session_passwords import session_password_store
++
++ session_id = flask_session_id or session.get("_id")
++
++ # Try session password store first
++ try:
++ user_password = session_password_store.get_session_password(
++ username, session_id
++ )
++ if user_password:
++ logger.debug(
++ f"Retrieved user password from session store for user {username}"
++ )
++ return user_password, None
++ except Exception:
++ logger.exception("Failed to get user password from session store")
++
++ # Fallback to g.user_password (set by middleware if temp_auth was used)
++ user_password = getattr(g, "user_password", None)
++ if user_password:
++ logger.debug(
++ f"Retrieved user password from g.user_password fallback for user {username}"
++ )
++ return user_password, None
++
++ # No password available
++ logger.error(f"No user password available for user {username}")
++ error_response = (
++ jsonify(
++ {
++ "status": "error",
++ "message": "Authentication required: Please refresh the page and log in again to access encrypted database features.",
++ }
++ ),
++ 401,
++ )
++ return None, error_response
++
++
# ============= Page Routes =============
@@@ -685,41 -623,11 +738,21 @@@ def download_bulk()
if not research_ids:
return jsonify({"error": "No research IDs provided"}), 400
+ # Capture Flask session ID to avoid scoping issues in nested function
+ flask_session_id = session.get("_id")
+
def generate():
"""Generate progress updates as Server-Sent Events."""
- download_service = DownloadService(username)
- library_service = LibraryService(username)
+ # Get user password for database operations
- try:
- from ...database.session_passwords import session_password_store
-
- user_password = session_password_store.get_session_password(
- username, flask_session_id
- )
- logger.debug(
- f"[LIBRARY_ROUTES] Retrieved user password from session store: {'***' if user_password else 'None'} for user {username}"
- )
- except Exception:
- logger.exception("[LIBRARY_ROUTES] Failed to get user password")
- user_password = None
-
- # Fallback to g.user_password (set by middleware if temp_auth was used)
- if not user_password:
- user_password = getattr(g, "user_password", None)
- logger.debug(
- f"[LIBRARY_ROUTES] Retrieved user password from g.user_password fallback: {'***' if user_password else 'None'} for user {username}"
- )
-
++ user_password, _ = get_authenticated_user_password(
++ username, flask_session_id
++ )
+ if user_password is None:
- logger.error(
- f"[LIBRARY_ROUTES] No user password available for user {username}"
- )
+ return
+
+ download_service = DownloadService(username, user_password)
+ # Count total pending queue items across all research IDs
total = 0
current = 0
@@@ -980,55 -858,6 +1013,24 @@@ def queue_all_undownloaded()
logger.info(f"Found {len(undownloaded)} total undownloaded resources")
- # Get user password from session password store for encrypted database access
- from ...database.session_passwords import session_password_store
-
- try:
- user_password = session_password_store.get_session_password(
- username, session.get("_id")
- )
- logger.info(
- f"[LIBRARY_ROUTES] Retrieved user password from session store: {'***' if user_password else 'None'} for user {username}"
- )
- except Exception as e:
- logger.exception(
- f"[LIBRARY_ROUTES] Failed to get user password: {e}"
- )
- user_password = None
-
- # Fallback to g.user_password (set by middleware if temp_auth was used)
- if not user_password:
- user_password = getattr(g, "user_password", None)
- logger.info(
- f"[LIBRARY_ROUTES] Retrieved user password from g.user_password fallback: {'***' if user_password else 'None'} for user {username}"
- )
-
- # Use smart filtering to decide which resources should be retried
- if user_password is None:
- logger.error(
- f"[LIBRARY_ROUTES] Cannot proceed with downloads: no password available for user {username}"
- )
- return (
- jsonify(
- {
- "status": "error",
- "message": "Authentication required: Please refresh the page and log in again to access encrypted database features.",
- }
- ),
- 401,
- )
++ # Get user password for encrypted database access
++ user_password, error_response = get_authenticated_user_password(
++ username
++ )
++ if error_response:
++ return error_response
+
+ resource_filter = ResourceFilter(username, user_password)
+ filter_results = resource_filter.filter_downloadable_resources(
+ undownloaded
+ )
+
+ # Get detailed filtering summary
+ filter_summary = resource_filter.get_filter_summary(undownloaded)
+ skipped_info = resource_filter.get_skipped_resources_info(undownloaded)
+
+ logger.info(f"Filter results: {filter_summary.to_dict()}")
+
queued_count = 0
research_ids = set()
skipped_count = 0
diff --cc src/local_deep_research/research_library/routes/rag_routes.py
index 4cf7c95f20,e7d9040479..57f264c389
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@@ -36,131 -30,26 +36,135 @@@ from ...database.models.library import
rag_bp = Blueprint("rag", __name__, url_prefix="/library")
-def get_rag_service() -> LibraryRAGService:
- """Get RAG service instance with current user's settings."""
+def get_rag_service(collection_id: Optional[str] = None) -> LibraryRAGService:
+ """
+ Get RAG service instance with appropriate settings.
+
+ If collection_id is provided:
+ - Uses collection's stored settings if they exist
+ - Uses current defaults for new collections (and stores them)
+
+ If no collection_id:
+ - Uses current default settings
+ """
+ from ...database.session_context import get_user_db_session
+
settings = get_settings_manager()
+ username = session["username"]
- # Get embedding configuration from settings or use defaults
- embedding_model = settings.get_setting(
+ # Get current default settings
+ default_embedding_model = settings.get_setting(
"local_search_embedding_model", "all-MiniLM-L6-v2"
)
- embedding_provider = settings.get_setting(
+ default_embedding_provider = settings.get_setting(
"local_search_embedding_provider", "sentence_transformers"
)
- chunk_size = int(settings.get_setting("local_search_chunk_size", 1000))
- chunk_overlap = int(settings.get_setting("local_search_chunk_overlap", 200))
+ default_chunk_size = int(
+ settings.get_setting("local_search_chunk_size", 1000)
+ )
+ default_chunk_overlap = int(
+ settings.get_setting("local_search_chunk_overlap", 200)
+ )
+
+ # Get new advanced configuration settings (Issue #1054)
+ import json
+
+ default_splitter_type = settings.get_setting(
+ "local_search_splitter_type", "recursive"
+ )
+ default_text_separators = settings.get_setting(
+ "local_search_text_separators", '["\n\n", "\n", ". ", " ", ""]'
+ )
+ # Parse JSON string to list
+ if isinstance(default_text_separators, str):
+ try:
+ default_text_separators = json.loads(default_text_separators)
+ except json.JSONDecodeError:
++ logger.warning(
++ f"Invalid JSON for local_search_text_separators setting: {default_text_separators!r}. "
++ "Using default separators."
++ )
+ default_text_separators = ["\n\n", "\n", ". ", " ", ""]
+ default_distance_metric = settings.get_setting(
+ "local_search_distance_metric", "cosine"
+ )
+ default_normalize_vectors = settings.get_setting(
+ "local_search_normalize_vectors", "true"
+ )
+ # Convert string "true"/"false" to boolean
+ if isinstance(default_normalize_vectors, str):
+ default_normalize_vectors = default_normalize_vectors.lower() == "true"
+ default_index_type = settings.get_setting("local_search_index_type", "flat")
+ # If collection_id provided, check for stored settings
+ if collection_id:
+ with get_user_db_session(username) as db_session:
+ collection = (
+ db_session.query(Collection).filter_by(id=collection_id).first()
+ )
+
+ if collection and collection.embedding_model:
+ # Use collection's stored settings
+ logger.info(
+ f"Using stored settings for collection {collection_id}: "
+ f"{collection.embedding_model_type.value}/{collection.embedding_model}"
+ )
+ return LibraryRAGService(
+ username=username,
+ embedding_model=collection.embedding_model,
+ embedding_provider=collection.embedding_model_type.value,
+ chunk_size=collection.chunk_size or default_chunk_size,
+ chunk_overlap=collection.chunk_overlap
+ or default_chunk_overlap,
+ splitter_type=collection.splitter_type
+ or default_splitter_type,
+ text_separators=collection.text_separators
+ or default_text_separators,
+ distance_metric=collection.distance_metric
+ or default_distance_metric,
+ normalize_vectors=collection.normalize_vectors
+ if collection.normalize_vectors is not None
+ else default_normalize_vectors,
+ index_type=collection.index_type or default_index_type,
+ )
+ elif collection:
+ # New collection - use defaults and store them
+ logger.info(
+ f"New collection {collection_id}, using and storing default settings"
+ )
+
+ # Create service with defaults
+ service = LibraryRAGService(
+ username=username,
+ embedding_model=default_embedding_model,
+ embedding_provider=default_embedding_provider,
+ chunk_size=default_chunk_size,
+ chunk_overlap=default_chunk_overlap,
+ splitter_type=default_splitter_type,
+ text_separators=default_text_separators,
+ distance_metric=default_distance_metric,
+ normalize_vectors=default_normalize_vectors,
+ index_type=default_index_type,
+ )
+
+ # Store settings on collection (will be done during indexing)
+ # Note: We don't store here because we don't have embedding_dimension yet
+ # It will be stored in index_collection when first document is indexed
+
+ return service
+
+ # No collection or fallback - use current defaults
return LibraryRAGService(
- username=session["username"],
- embedding_model=embedding_model,
- embedding_provider=embedding_provider,
- chunk_size=chunk_size,
- chunk_overlap=chunk_overlap,
+ username=username,
+ embedding_model=default_embedding_model,
+ embedding_provider=default_embedding_provider,
+ chunk_size=default_chunk_size,
+ chunk_overlap=default_chunk_overlap,
+ splitter_type=default_splitter_type,
+ text_separators=default_text_separators,
+ distance_metric=default_distance_metric,
+ normalize_vectors=default_normalize_vectors,
+ index_type=default_index_type,
)
@@@ -301,23 -91,6 +305,27 @@@ def get_current_settings()
try:
settings = get_settings_manager()
+ # Get text separators and parse if needed
+ text_separators = settings.get_setting(
+ "local_search_text_separators", '["\n\n", "\n", ". ", " ", ""]'
+ )
+ if isinstance(text_separators, str):
+ try:
+ text_separators = json_lib.loads(text_separators)
+ except json_lib.JSONDecodeError:
++ logger.warning(
++ f"Invalid JSON for local_search_text_separators setting: {text_separators!r}. "
++ "Using default separators."
++ )
+ text_separators = ["\n\n", "\n", ". ", " ", ""]
+
+ # Get normalize_vectors and convert to boolean if needed
+ normalize_vectors = settings.get_setting(
+ "local_search_normalize_vectors", "true"
+ )
+ if isinstance(normalize_vectors, str):
+ normalize_vectors = normalize_vectors.lower() == "true"
+
return jsonify(
{
"success": True,
diff --cc src/local_deep_research/research_library/services/library_rag_service.py
index 60cf545b26,4a21aea99a..2f8caded89
--- a/src/local_deep_research/research_library/services/library_rag_service.py
+++ b/src/local_deep_research/research_library/services/library_rag_service.py
@@@ -12,20 -12,17 +12,21 @@@ Handles indexing and searching library
from pathlib import Path
from typing import Any, Dict, List, Optional
-from langchain_core.documents import Document
-from langchain_text_splitters import RecursiveCharacterTextSplitter
+from langchain_core.documents import Document as LangchainDocument
from loguru import logger
+from sqlalchemy import func
from ...database.models.library import (
+ Document,
DocumentChunk,
- LibraryTextDocument,
+ DocumentCollection,
+ Collection,
RAGIndex,
++ RagDocumentStatus,
+ EmbeddingProvider,
)
from ...database.session_context import get_user_db_session
+from ...embeddings.splitters import get_text_splitter
from ...web_search_engines.engines.search_engine_local import (
LocalEmbeddingManager,
)
@@@ -551,72 -379,19 +552,68 @@@ class LibraryRAGService
self.faiss_index.save_local(
str(index_path.parent), index_name=index_path.stem
)
- logger.info(f"Saved FAISS index to {index_path}")
+ # Record file integrity
+ self.integrity_manager.record_file(
+ index_path,
+ related_entity_type="rag_index",
+ related_entity_id=self.rag_index_record.id,
+ )
+ logger.info(
+ f"Saved FAISS index to {index_path} with integrity tracking"
+ )
- # Update LibraryTextDocument with RAG status
- # CRITICAL: Re-merge the object into the session since it might have been detached
- # by nested session contexts (e.g., from _store_chunks_to_db using same thread-local session)
- text_doc = session.merge(text_doc)
+ from datetime import datetime, UTC
+ from sqlalchemy import text
- was_already_indexed = (
- text_doc.rag_indexed
- ) # Check BEFORE updating
- text_doc.rag_indexed = True
- text_doc.chunk_count = len(chunks)
- text_doc.last_indexed_at = datetime.now(UTC)
+ # Check if document was already indexed (for stats update)
- was_already_indexed = (
- session.execute(
- text("""
- SELECT 1 FROM rag_document_status
- WHERE document_id = :doc_id AND collection_id = :coll_id
- LIMIT 1
- """),
- {"doc_id": document_id, "coll_id": collection_id},
- ).first()
- is not None
++ existing_status = (
++ session.query(RagDocumentStatus)
++ .filter_by(
++ document_id=document_id, collection_id=collection_id
++ )
++ .first()
+ )
++ was_already_indexed = existing_status is not None
+
+ # Mark document as indexed using rag_document_status table
+ # Row existence = indexed, simple and clean
+ timestamp = datetime.now(UTC)
++
++ # Using raw SQL for INSERT OR REPLACE as SQLite-specific optimization
++ # This atomically upserts the record without separate query+insert logic
+ session.execute(
+ text("""
+ INSERT OR REPLACE INTO rag_document_status
+ (document_id, collection_id, rag_index_id, chunk_count, indexed_at)
+ VALUES (:doc_id, :coll_id, :index_id, :chunk_count, :timestamp)
+ """),
+ {
+ "doc_id": document_id,
+ "coll_id": collection_id,
+ "index_id": self.rag_index_record.id,
+ "chunk_count": len(chunks),
+ "timestamp": timestamp,
+ },
+ )
+
+ logger.info(
+ f"Marked document as indexed in rag_document_status: doc_id={document_id}, coll_id={collection_id}, chunks={len(chunks)}"
+ )
+
+ # Also update DocumentCollection table for backward compatibility
- session.execute(
- text("""
- UPDATE document_collections
- SET indexed = 1, chunk_count = :chunk_count, last_indexed_at = :timestamp
- WHERE document_id = :doc_id AND collection_id = :coll_id
- """),
++ session.query(DocumentCollection).filter_by(
++ document_id=document_id, collection_id=collection_id
++ ).update(
+ {
- "doc_id": document_id,
- "coll_id": collection_id,
++ "indexed": True,
+ "chunk_count": len(chunks),
- "timestamp": timestamp,
- },
++ "last_indexed_at": timestamp,
++ }
+ )
+
+ logger.info(
+ "Also updated DocumentCollection.indexed for backward compatibility"
+ )
# Update RAGIndex statistics (only if not already indexed)
rag_index_obj = (
@@@ -632,38 -407,15 +629,18 @@@
f"Updated RAGIndex stats: chunk_count +{len(chunks)}, total_documents +1"
)
- # Commit the changes
+ # Flush ORM changes to database before commit
+ session.flush()
+ logger.info(f"Flushed ORM changes for document {document_id}")
+
+ # Commit the transaction
session.commit()
- # CRITICAL: Expire all cached objects in this thread-local session
- # so subsequent operations in the same thread see fresh data
- session.expire_all()
+ # WAL checkpoint after commit to ensure persistence
+ session.execute(text("PRAGMA wal_checkpoint(FULL)"))
- logger.info(
- f"Committed and checkpointed changes for document {document_id}"
- )
-
- # Verify the update was persisted
- verification = session.execute(
- text("""
- SELECT chunk_count FROM rag_document_status
- WHERE document_id = :doc_id AND collection_id = :coll_id
- """),
- {"doc_id": document_id, "coll_id": collection_id},
- ).first()
- logger.info(
- f"Post-commit verification: doc={document_id}, indexed={verification is not None}, chunks={verification[0] if verification else 0}"
- )
-
- logger.info(
- f"Indexed document {document_id} with {len(chunks)} chunks"
- )
-
logger.info(
- f"Successfully indexed document {text_doc_id} "
+ f"Successfully indexed document {document_id} for collection {collection_id} "
f"with {len(chunks)} chunks"
)
diff --cc src/local_deep_research/security/__init__.py
index aa78120c18,5cc8ab55c3..5893ca0396
--- a/src/local_deep_research/security/__init__.py
+++ b/src/local_deep_research/security/__init__.py
@@@ -1,22 -1,13 +1,28 @@@
"""Security utilities for Local Deep Research."""
-from .path_validator import PathValidator
+from .data_sanitizer import DataSanitizer, redact_data, sanitize_data
+from .file_integrity import FileIntegrityManager, FAISSIndexVerifier
+ from .notification_validator import (
+ NotificationURLValidator,
+ NotificationURLValidationError,
+ )
+# PathValidator requires werkzeug (Flask dependency), import conditionally
+try:
+ from .path_validator import PathValidator
+
+ _has_path_validator = True
+except ImportError:
+ PathValidator = None # type: ignore
+ _has_path_validator = False
+
__all__ = [
"PathValidator",
+ "DataSanitizer",
+ "sanitize_data",
+ "redact_data",
+ "FileIntegrityManager",
+ "FAISSIndexVerifier",
+ "NotificationURLValidator",
+ "NotificationURLValidationError",
]