~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
feat: add file integrity verification system for FAISS indexes
LearningCircuit0631ab6994bc
diff --git a/src/local_deep_research/database/models/__init__.py b/src/local_deep_research/database/models/__init__.pyindex 0ec8a8555d..fa416ab3da 100644--- a/src/local_deep_research/database/models/__init__.py+++ b/src/local_deep_research/database/models/__init__.py@@ -69,6 +69,12 @@ from .download_tracker import (DownloadAttempt,)+# Import File Integrity models+from ...security.file_integrity.models import (+ FileIntegrityRecord,+ FileVerificationFailure,+)+__all__ = [# Base"Base",@@ -152,4 +158,7 @@ __all__ = ["DownloadTracker","DownloadDuplicates","DownloadAttempt",+ # File Integrity Models+ "FileIntegrityRecord",+ "FileVerificationFailure",]diff --git a/src/local_deep_research/library/download_management/retry_manager.py b/src/local_deep_research/library/download_management/retry_manager.pyindex 00ed9375bc..0213b2986f 100644--- a/src/local_deep_research/library/download_management/retry_manager.py+++ b/src/local_deep_research/library/download_management/retry_manager.py@@ -114,6 +114,7 @@ class RetryManager:status_code: Optional[int] = None,url: str = "",details: str = "",+ session=None,) -> None:"""Record a download attempt result.@@ -124,12 +125,13 @@ class RetryManager:status_code: HTTP status code if availableurl: URL that was attempteddetails: Additional error details+ session: Optional database session to reuse"""success, error_message = resultif success:# Successful download- self.status_tracker.mark_success(resource_id)+ self.status_tracker.mark_success(resource_id, session=session)logger.info(f"[RETRY_MANAGER] Resource {resource_id} marked as successful")@@ -144,7 +146,9 @@ class RetryManager:details=details or (error_message or "Unknown error"),)- self.status_tracker.mark_failure(resource_id, failure)+ self.status_tracker.mark_failure(+ resource_id, failure, session=session+ )logger.info(f"[RETRY_MANAGER] Resource {resource_id} marked as failed: {failure.error_type}")diff --git a/src/local_deep_research/library/download_management/status_tracker.py b/src/local_deep_research/library/download_management/status_tracker.pyindex 0cf1cf72da..245cd58687 100644--- a/src/local_deep_research/library/download_management/status_tracker.py+++ b/src/local_deep_research/library/download_management/status_tracker.py@@ -45,15 +45,23 @@ class ResourceStatusTracker:"""Get a database session"""return self.Session()- def mark_failure(self, resource_id: int, failure) -> None:+ def mark_failure(+ self, resource_id: int, failure, session: Optional[Session] = None+ ) -> None:"""Mark a resource as failed with classification.Args:resource_id: Resource identifierfailure: Classified failure object+ session: Optional existing database session to reuse"""- with self._get_session() as session:+ # Use provided session or create new one+ should_close = session is None+ if session is None:+ session = self._get_session()++ try:# Get or create status recordstatus = (session.query(ResourceDownloadStatus)@@ -108,19 +116,32 @@ class ResourceStatusTracker:else:status.today_retry_count = 1- session.commit()+ # Only commit if we created the session+ if should_close:+ session.commit()logger.debug(f"[STATUS_TRACKER] Updated failure status for resource {resource_id}")+ finally:+ if should_close:+ session.close()- def mark_success(self, resource_id: int) -> None:+ def mark_success(+ self, resource_id: int, session: Optional[Session] = None+ ) -> None:"""Mark a resource as successfully downloaded.Args:resource_id: Resource identifier+ session: Optional existing database session to reuse"""- with self._get_session() as session:+ # Use provided session or create new one+ should_close = session is None+ if session is None:+ session = self._get_session()++ try:status = (session.query(ResourceDownloadStatus).filter_by(resource_id=resource_id)@@ -137,7 +158,12 @@ class ResourceStatusTracker:f"[STATUS_TRACKER] Marked resource {resource_id} as successfully completed")- session.commit()+ # Only commit if we created the session+ if should_close:+ session.commit()+ finally:+ if should_close:+ session.close()def can_retry(self, resource_id: int) -> tuple[bool, Optional[str]]:"""diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.pyindex 63b8d82273..0c963d51cc 100644--- a/src/local_deep_research/research_library/services/download_service.py+++ b/src/local_deep_research/research_library/services/download_service.py@@ -375,6 +375,7 @@ class DownloadService:or ("Successfully downloaded" if success else "Download failed"),+ session=session,)# Update queue status if existsdiff --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 a113d1dd3f..547808f4e9 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@@ -26,8 +26,8 @@ from ...database.session_context import get_user_db_sessionfrom ...web_search_engines.engines.search_engine_local import (LocalEmbeddingManager,)+from ...security.file_integrity import FileIntegrityManager, FAISSIndexVerifierimport hashlib-import jsonfrom faiss import IndexFlatL2from langchain_community.vectorstores import FAISSfrom langchain_community.docstore.in_memory import InMemoryDocstore@@ -95,6 +95,10 @@ class LibraryRAGService:self.faiss_index = Noneself.rag_index_record = None+ # Initialize file integrity manager for FAISS indexes+ self.integrity_manager = FileIntegrityManager(username)+ self.integrity_manager.register_verifier(FAISSIndexVerifier())+def _get_index_hash(self,collection_name: str,@@ -159,65 +163,6 @@ class LibraryRAGService:return rag_index- def _calculate_index_checksum(self, index_path: Path) -> str:- """Calculate SHA256 checksum of FAISS index file."""- sha256_hash = hashlib.sha256()- with open(index_path, "rb") as f:- # Read in chunks to handle large files- for byte_block in iter(lambda: f.read(4096), b""):- sha256_hash.update(byte_block)- return sha256_hash.hexdigest()-- def _save_index_checksum(self, index_path: Path, checksum: str):- """Save checksum to metadata file."""- checksum_path = index_path.parent / f"{index_path.stem}.checksum"- checksum_data = {- "checksum": checksum,- "algorithm": "sha256",- "created_at": datetime.now(UTC).isoformat(),- }- with open(checksum_path, "w") as f:- json.dump(checksum_data, f)-- def _verify_index_checksum(self, index_path: Path) -> bool:- """Verify FAISS index checksum. Returns True if valid, False otherwise."""- checksum_path = index_path.parent / f"{index_path.stem}.checksum"-- if not checksum_path.exists():- logger.warning(- f"No checksum file found for {index_path}, creating one"- )- # Calculate and save checksum for existing index- try:- checksum = self._calculate_index_checksum(index_path)- self._save_index_checksum(index_path, checksum)- return True- except Exception:- logger.exception("Failed to create checksum")- return False-- try:- with open(checksum_path, "r") as f:- checksum_data = json.load(f)-- stored_checksum = checksum_data["checksum"]- current_checksum = self._calculate_index_checksum(index_path)-- if stored_checksum != current_checksum:- logger.error(- f"SECURITY: Checksum mismatch for {index_path}! "- f"Expected: {stored_checksum}, Got: {current_checksum}. "- f"Index may be corrupted or tampered with."- )- return False-- logger.debug(f"Checksum verified for {index_path}")- return True-- except Exception:- logger.exception("Failed to verify checksum")- return False-def load_or_create_faiss_index(self) -> FAISS:"""Load existing FAISS index or create new one.@@ -231,11 +176,12 @@ class LibraryRAGService:index_path = Path(rag_index.index_path)if index_path.exists():- # Verify checksum before loading- if not self._verify_index_checksum(index_path):+ # Verify integrity before loading+ verified, reason = self.integrity_manager.verify_file(index_path)+ if not verified:logger.error(- f"Checksum verification failed for {index_path}, refusing to load. "- f"Creating new index."+ f"Integrity verification failed for {index_path}: {reason}. "+ f"Refusing to load. Creating new index.")# Remove corrupted indextry:@@ -451,10 +397,15 @@ class LibraryRAGService:self.faiss_index.save_local(str(index_path.parent), index_name=index_path.stem)- # Calculate and save checksum for security- checksum = self._calculate_index_checksum(index_path)- self._save_index_checksum(index_path, checksum)- logger.info(f"Saved FAISS index to {index_path} with checksum")+ # 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# Re-query to ensure we have fresh object in this session@@ -939,10 +890,15 @@ class LibraryRAGService:self.faiss_index.save_local(str(index_path.parent), index_name=index_path.stem)- # Calculate and save checksum for security- checksum = self._calculate_index_checksum(index_path)- self._save_index_checksum(index_path, checksum)- logger.info(f"Saved FAISS index to {index_path} with checksum")+ # 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"+ )logger.info(f"Successfully indexed local file {file_path} with {len(chunks)} chunks"@@ -1078,9 +1034,12 @@ class LibraryRAGService:self.faiss_index.save_local(str(index_path.parent), index_name=index_path.stem)- # Calculate and save checksum for security- checksum = self._calculate_index_checksum(index_path)- self._save_index_checksum(index_path, checksum)+ # 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"Successfully indexed user document {user_doc.filename} with {len(chunks)} chunks"@@ -1152,11 +1111,12 @@ class LibraryRAGService:str(index_path.parent),index_name=index_path.stem,)- # Calculate and save checksum for security- checksum = self._calculate_index_checksum(- 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,)- self._save_index_checksum(index_path, checksum)except Exception as e:logger.warning(f"Could not delete chunks from FAISS: {e}"diff --git a/src/local_deep_research/security/__init__.py b/src/local_deep_research/security/__init__.pyindex c23676f647..67e948390d 100644--- a/src/local_deep_research/security/__init__.py+++ b/src/local_deep_research/security/__init__.py@@ -2,5 +2,13 @@from .data_sanitizer import DataSanitizer, redact_data, sanitize_datafrom .path_validator import PathValidator+from .file_integrity import FileIntegrityManager, FAISSIndexVerifier-__all__ = ["PathValidator", "DataSanitizer", "sanitize_data", "redact_data"]+__all__ = [+ "PathValidator",+ "DataSanitizer",+ "sanitize_data",+ "redact_data",+ "FileIntegrityManager",+ "FAISSIndexVerifier",+]diff --git a/src/local_deep_research/security/file_integrity/__init__.py b/src/local_deep_research/security/file_integrity/__init__.pynew file mode 100644index 0000000000..0435e8bb8a--- /dev/null+++ b/src/local_deep_research/security/file_integrity/__init__.py@@ -0,0 +1,44 @@+"""+File Integrity System - Reusable file integrity verification with audit trail.++Provides:+- Smart verification (only verify when files change)+- Embedded statistics (low overhead)+- Sparse failure logging (audit trail)+- Extensible verifier system (support multiple file types)++Example usage:+ from local_deep_research.security.file_integrity import (+ FileIntegrityManager,+ FAISSIndexVerifier+ )++ # Initialize manager+ manager = FileIntegrityManager(username, password)+ manager.register_verifier(FAISSIndexVerifier())++ # Record file+ manager.record_file(path, related_type='rag_index', related_id=123)++ # Verify file+ passed, reason = manager.verify_file(path)+ if not passed:+ print(f"Verification failed: {reason}")+"""++from .models import FileIntegrityRecord, FileVerificationFailure+from .base_verifier import BaseFileVerifier+from .integrity_manager import FileIntegrityManager+from .verifiers import FAISSIndexVerifier++__all__ = [+ # Models+ "FileIntegrityRecord",+ "FileVerificationFailure",+ # Base classes+ "BaseFileVerifier",+ # Main service+ "FileIntegrityManager",+ # Verifiers+ "FAISSIndexVerifier",+]diff --git a/src/local_deep_research/security/file_integrity/base_verifier.py b/src/local_deep_research/security/file_integrity/base_verifier.pynew file mode 100644index 0000000000..21f36dff86--- /dev/null+++ b/src/local_deep_research/security/file_integrity/base_verifier.py@@ -0,0 +1,87 @@+"""+Abstract base class for file integrity verifiers.++Defines the interface for file-type-specific integrity verification.+Concrete implementations specify which files to verify and policies.+"""++from abc import ABC, abstractmethod+from pathlib import Path+import hashlib+++class BaseFileVerifier(ABC):+ """+ Base class for file integrity verification.++ Subclasses implement file-type-specific logic for:+ - Identifying which files they handle+ - Defining verification policies+ - Optionally customizing checksum algorithms+ """++ @abstractmethod+ def should_verify(self, file_path: Path) -> bool:+ """+ Determine if this verifier handles the given file.++ Args:+ file_path: Path to file to check++ Returns:+ True if this verifier should handle this file type+ """+ pass++ @abstractmethod+ def get_file_type(self) -> str:+ """+ Get the file type identifier for this verifier.++ Returns:+ String identifier (e.g., 'faiss_index', 'pdf', 'export')+ """+ pass++ @abstractmethod+ def allows_modifications(self) -> bool:+ """+ Whether this file type can be legitimately modified by users.++ Returns:+ True if users can modify files (e.g., PDFs with annotations)+ False if files should never be manually modified (e.g., FAISS indexes)+ """+ pass++ def calculate_checksum(self, file_path: Path) -> str:+ """+ Calculate SHA256 checksum of file.++ Can be overridden by subclasses for different algorithms.++ Args:+ file_path: Path to file to checksum++ Returns:+ Hex string of checksum++ Raises:+ FileNotFoundError: If file doesn't exist+ IOError: If file can't be read+ """+ sha256_hash = hashlib.sha256()+ with open(file_path, "rb") as f:+ # Read in chunks to handle large files efficiently+ for byte_block in iter(lambda: f.read(4096), b""):+ sha256_hash.update(byte_block)+ return sha256_hash.hexdigest()++ def get_algorithm(self) -> str:+ """+ Get the checksum algorithm name.++ Returns:+ Algorithm identifier (default: 'sha256')+ """+ return "sha256"diff --git a/src/local_deep_research/security/file_integrity/integrity_manager.py b/src/local_deep_research/security/file_integrity/integrity_manager.pynew file mode 100644index 0000000000..d596d27249--- /dev/null+++ b/src/local_deep_research/security/file_integrity/integrity_manager.py@@ -0,0 +1,558 @@+"""+File Integrity Manager - Main service for file integrity verification.++Provides smart verification with embedded statistics and sparse failure logging.+"""++from datetime import datetime, UTC+from pathlib import Path+from typing import Optional, Tuple, List+from loguru import logger++from .base_verifier import BaseFileVerifier+from .models import FileIntegrityRecord, FileVerificationFailure+from ...database.session_context import get_user_db_session+++class FileIntegrityManager:+ """+ Central service for file integrity verification.++ Features:+ - Smart verification (only verify if file modified)+ - Embedded statistics (low overhead)+ - Sparse failure logging (audit trail)+ - Multi-verifier support (different file types)+ - Automatic cleanup of old failure records+ """++ # Configuration for automatic cleanup+ MAX_FAILURES_PER_FILE = 100 # Keep at most this many failures per file+ MAX_TOTAL_FAILURES = 10000 # Global limit across all files++ def __init__(self, username: str, password: Optional[str] = None):+ """+ Initialize file integrity manager.++ Args:+ username: Username for database access+ password: Optional password for encrypted database+ """+ self.username = username+ self.password = password+ self.verifiers: List[BaseFileVerifier] = []++ # Run startup cleanup to remove old failures+ try:+ deleted = self.cleanup_all_old_failures()+ if deleted > 0:+ logger.info(+ f"[FILE_INTEGRITY] Startup cleanup: removed {deleted} old failure records"+ )+ except Exception as e:+ logger.warning(f"[FILE_INTEGRITY] Startup cleanup failed: {e}")++ def register_verifier(self, verifier: BaseFileVerifier) -> None:+ """+ Register a file type verifier.++ Args:+ verifier: Verifier instance to register+ """+ self.verifiers.append(verifier)+ logger.debug(+ f"[FILE_INTEGRITY] Registered verifier for type: {verifier.get_file_type()}"+ )++ def record_file(+ self,+ file_path: Path,+ related_entity_type: Optional[str] = None,+ related_entity_id: Optional[int] = None,+ ) -> FileIntegrityRecord:+ """+ Create or update integrity record for a file.++ Args:+ file_path: Path to file to record+ related_entity_type: Optional related entity type (e.g., 'rag_index')+ related_entity_id: Optional related entity ID++ Returns:+ FileIntegrityRecord instance++ Raises:+ FileNotFoundError: If file doesn't exist+ ValueError: If no verifier handles this file type+ """+ if not file_path.exists():+ raise FileNotFoundError(f"File not found: {file_path}")++ verifier = self._get_verifier_for_file(file_path)+ if not verifier:+ raise ValueError(f"No verifier registered for file: {file_path}")++ # Calculate checksum and get file stats+ checksum = verifier.calculate_checksum(file_path)+ file_stat = file_path.stat()++ with get_user_db_session(self.username, self.password) as session:+ # Check if record exists+ record = (+ session.query(FileIntegrityRecord)+ .filter_by(file_path=str(file_path))+ .first()+ )++ if record:+ # Update existing record+ record.checksum = checksum+ record.file_size = file_stat.st_size+ record.file_mtime = file_stat.st_mtime+ record.algorithm = verifier.get_algorithm()+ record.updated_at = datetime.now(UTC)+ logger.info(f"[FILE_INTEGRITY] Updated record for: {file_path}")+ else:+ # Create new record+ record = FileIntegrityRecord(+ file_path=str(file_path),+ file_type=verifier.get_file_type(),+ checksum=checksum,+ algorithm=verifier.get_algorithm(),+ file_size=file_stat.st_size,+ file_mtime=file_stat.st_mtime,+ verify_on_load=True,+ allow_modifications=verifier.allows_modifications(),+ related_entity_type=related_entity_type,+ related_entity_id=related_entity_id,+ total_verifications=0,+ consecutive_successes=0,+ consecutive_failures=0,+ )+ session.add(record)+ logger.info(+ f"[FILE_INTEGRITY] Created record for: {file_path} (type: {verifier.get_file_type()})"+ )++ session.commit()+ session.refresh(record)+ return record++ def verify_file(+ self, file_path: Path, force: bool = False+ ) -> Tuple[bool, Optional[str]]:+ """+ Verify file integrity with smart checking.++ Only verifies if:+ - File modification time changed since last verification, OR+ - force=True++ Args:+ file_path: Path to file to verify+ force: Force verification even if file hasn't changed++ Returns:+ Tuple of (success, reason_if_failed)+ """+ with get_user_db_session(self.username, self.password) as session:+ record = (+ session.query(FileIntegrityRecord)+ .filter_by(file_path=str(file_path))+ .first()+ )++ if not record:+ logger.warning(+ f"[FILE_INTEGRITY] No record found for {file_path}, creating one"+ )+ # Create record if it doesn't exist+ try:+ # Need to commit and return since we're in a different session+ session.close()+ self.record_file(file_path)+ return True, None+ except Exception as e:+ logger.exception(+ f"[FILE_INTEGRITY] Failed to create record: {e}"+ )+ return False, f"Failed to create integrity record: {str(e)}"++ # Check if verification needed+ if not force and not self._needs_verification(record, file_path):+ logger.debug(+ f"[FILE_INTEGRITY] Skipping verification for {file_path} (unchanged)"+ )+ return True, None++ # Perform verification+ passed, reason = self._do_verification(record, file_path, session)++ # Update statistics+ self._update_stats(record, passed, session)++ # Log failure if needed+ if not passed:+ self._log_failure(+ record, file_path, reason or "Unknown failure", session+ )++ session.commit()++ if passed:+ logger.info(+ f"[FILE_INTEGRITY] Verification passed: {file_path}"+ )+ else:+ logger.error(+ f"[FILE_INTEGRITY] Verification FAILED: {file_path} - {reason}"+ )++ return passed, reason++ def update_checksum(self, file_path: Path) -> None:+ """+ Update checksum after legitimate file modification.++ Use this when you know a file was legitimately modified+ and want to update the baseline checksum.++ Args:+ file_path: Path to file++ Raises:+ FileNotFoundError: If file doesn't exist+ ValueError: If no record exists for file+ """+ if not file_path.exists():+ raise FileNotFoundError(f"File not found: {file_path}")++ verifier = self._get_verifier_for_file(file_path)+ if not verifier:+ raise ValueError(f"No verifier registered for file: {file_path}")++ checksum = verifier.calculate_checksum(file_path)+ file_stat = file_path.stat()++ with get_user_db_session(self.username, self.password) as session:+ record = (+ session.query(FileIntegrityRecord)+ .filter_by(file_path=str(file_path))+ .first()+ )++ if not record:+ raise ValueError(f"No integrity record exists for: {file_path}")++ record.checksum = checksum+ record.file_size = file_stat.st_size+ record.file_mtime = file_stat.st_mtime+ record.updated_at = datetime.now(UTC)++ session.commit()+ logger.info(f"[FILE_INTEGRITY] Updated checksum for: {file_path}")++ def get_file_stats(self, file_path: Path) -> Optional[dict]:+ """+ Get verification statistics for a file.++ Args:+ file_path: Path to file++ Returns:+ Dictionary of stats or None if no record exists+ """+ with get_user_db_session(self.username, self.password) as session:+ record = (+ session.query(FileIntegrityRecord)+ .filter_by(file_path=str(file_path))+ .first()+ )++ if not record:+ return None++ return {+ "total_verifications": record.total_verifications,+ "last_verified_at": record.last_verified_at,+ "last_verification_passed": record.last_verification_passed,+ "consecutive_successes": record.consecutive_successes,+ "consecutive_failures": record.consecutive_failures,+ "file_type": record.file_type,+ "created_at": record.created_at,+ }++ def get_failure_history(+ self, file_path: Path, limit: int = 100+ ) -> List[FileVerificationFailure]:+ """+ Get failure history for a file.++ Args:+ file_path: Path to file+ limit: Maximum number of failures to return++ Returns:+ List of failure records+ """+ with get_user_db_session(self.username, self.password) as session:+ record = (+ session.query(FileIntegrityRecord)+ .filter_by(file_path=str(file_path))+ .first()+ )++ if not record:+ return []++ failures = (+ session.query(FileVerificationFailure)+ .filter_by(file_record_id=record.id)+ .order_by(FileVerificationFailure.verified_at.desc())+ .limit(limit)+ .all()+ )++ # Detach from session+ for f in failures:+ session.expunge(f)++ return failures++ # Internal methods++ def _get_verifier_for_file(+ self, file_path: Path+ ) -> Optional[BaseFileVerifier]:+ """Find verifier that handles this file type."""+ for verifier in self.verifiers:+ if verifier.should_verify(file_path):+ return verifier+ return None++ def _needs_verification(+ self, record: FileIntegrityRecord, file_path: Path+ ) -> bool:+ """+ Check if file needs verification.++ Only verify if file modification time changed since last verification.+ """+ if not file_path.exists():+ return True # File missing needs verification++ if not record.last_verified_at:+ return True # Never verified++ current_mtime = file_path.stat().st_mtime++ # Compare with stored mtime+ if record.file_mtime is None:+ return True # No mtime stored++ # Verify if file was modified (allow small floating point differences)+ return abs(current_mtime - record.file_mtime) > 0.001++ def _do_verification(+ self, record: FileIntegrityRecord, file_path: Path, session+ ) -> Tuple[bool, Optional[str]]:+ """+ Perform actual verification.++ Returns:+ Tuple of (success, reason_if_failed)+ """+ # Check file exists+ if not file_path.exists():+ return False, "file_missing"++ # Get verifier+ verifier = self._get_verifier_for_file(file_path)+ if not verifier:+ return False, "no_verifier"++ # Calculate current checksum+ try:+ current_checksum = verifier.calculate_checksum(file_path)+ except Exception as e:+ logger.exception(+ f"[FILE_INTEGRITY] Failed to calculate checksum: {e}"+ )+ return False, f"checksum_calculation_failed: {str(e)}"++ # Compare checksums+ if current_checksum != record.checksum:+ return False, "checksum_mismatch"++ # Update file mtime in record+ record.file_mtime = file_path.stat().st_mtime++ return True, None++ def _update_stats(+ self, record: FileIntegrityRecord, passed: bool, session+ ) -> None:+ """Update verification statistics."""+ record.total_verifications += 1+ record.last_verified_at = datetime.now(UTC)+ record.last_verification_passed = passed++ if passed:+ record.consecutive_successes += 1+ record.consecutive_failures = 0+ else:+ record.consecutive_failures += 1+ record.consecutive_successes = 0++ def _log_failure(+ self,+ record: FileIntegrityRecord,+ file_path: Path,+ reason: str,+ session,+ ) -> None:+ """Log verification failure to audit trail."""+ # Get current checksum if possible+ actual_checksum = None+ file_size = None++ if file_path.exists():+ try:+ verifier = self._get_verifier_for_file(file_path)+ if verifier:+ actual_checksum = verifier.calculate_checksum(file_path)+ file_size = file_path.stat().st_size+ except Exception:+ pass # Checksum calculation failed, leave as None++ failure = FileVerificationFailure(+ file_record_id=record.id,+ expected_checksum=record.checksum,+ actual_checksum=actual_checksum,+ file_size=file_size,+ failure_reason=reason,+ )+ session.add(failure)++ logger.warning(+ f"[FILE_INTEGRITY] Logged failure for {file_path}: {reason}"+ )++ # Cleanup old failures for this file+ self._cleanup_old_failures(record, session)++ # Periodically check if global cleanup needed (every 100th file to avoid overhead)+ if record.id % 100 == 0:+ self._check_global_cleanup_needed(session)++ def _cleanup_old_failures(+ self, record: FileIntegrityRecord, session+ ) -> None:+ """+ Clean up old failure records to prevent unbounded growth.++ Keeps only the most recent MAX_FAILURES_PER_FILE failures per file.+ """+ # Count failures for this file+ failure_count = (+ session.query(FileVerificationFailure)+ .filter_by(file_record_id=record.id)+ .count()+ )++ if failure_count > self.MAX_FAILURES_PER_FILE:+ # Delete oldest failures, keeping only the most recent MAX_FAILURES_PER_FILE+ failures_to_delete = (+ session.query(FileVerificationFailure)+ .filter_by(file_record_id=record.id)+ .order_by(FileVerificationFailure.verified_at.asc())+ .limit(failure_count - self.MAX_FAILURES_PER_FILE)+ .all()+ )++ for failure in failures_to_delete:+ session.delete(failure)++ logger.info(+ f"[FILE_INTEGRITY] Cleaned up {len(failures_to_delete)} old failures for file_record {record.id}"+ )++ def _check_global_cleanup_needed(self, session) -> None:+ """+ Check if global cleanup is needed and run it if threshold exceeded.++ Only runs cleanup if failure count exceeds MAX_TOTAL_FAILURES by 20%.+ This prevents constant cleanup while allowing some buffer.+ """+ threshold = int(self.MAX_TOTAL_FAILURES * 1.2) # 20% over limit+ total_failures = session.query(FileVerificationFailure).count()++ if total_failures > threshold:+ logger.info(+ f"[FILE_INTEGRITY] Global failure count ({total_failures}) exceeds threshold ({threshold}), "+ f"running cleanup..."+ )++ # Delete oldest failures to get under limit+ failures_to_delete_count = total_failures - self.MAX_TOTAL_FAILURES++ failures_to_delete = (+ session.query(FileVerificationFailure)+ .order_by(FileVerificationFailure.verified_at.asc())+ .limit(failures_to_delete_count)+ .all()+ )++ for failure in failures_to_delete:+ session.delete(failure)++ logger.info(+ f"[FILE_INTEGRITY] Threshold cleanup: deleted {len(failures_to_delete)} old failures"+ )++ def cleanup_all_old_failures(self) -> int:+ """+ Global cleanup of failure records across all files.++ Enforces MAX_TOTAL_FAILURES limit by removing oldest failures.++ Returns:+ Number of records deleted+ """+ with get_user_db_session(self.username, self.password) as session:+ total_failures = session.query(FileVerificationFailure).count()++ if total_failures <= self.MAX_TOTAL_FAILURES:+ return 0++ # Delete oldest failures to get under limit+ failures_to_delete_count = total_failures - self.MAX_TOTAL_FAILURES++ failures_to_delete = (+ session.query(FileVerificationFailure)+ .order_by(FileVerificationFailure.verified_at.asc())+ .limit(failures_to_delete_count)+ .all()+ )++ for failure in failures_to_delete:+ session.delete(failure)++ session.commit()++ logger.info(+ f"[FILE_INTEGRITY] Global cleanup: deleted {len(failures_to_delete)} old failures "+ f"(total was {total_failures}, now {total_failures - len(failures_to_delete)})"+ )++ return len(failures_to_delete)++ def get_total_failure_count(self) -> int:+ """+ Get total number of failure records across all files.++ Returns:+ Total count of failure records+ """+ with get_user_db_session(self.username, self.password) as session:+ return session.query(FileVerificationFailure).count()diff --git a/src/local_deep_research/security/file_integrity/models.py b/src/local_deep_research/security/file_integrity/models.pynew file mode 100644index 0000000000..9e9c057e71--- /dev/null+++ b/src/local_deep_research/security/file_integrity/models.py@@ -0,0 +1,128 @@+"""+Database models for file integrity tracking.++Provides efficient storage of file checksums and verification statistics+with sparse logging of failures for audit trail.+"""++from datetime import datetime, UTC+from sqlalchemy import (+ Column,+ Integer,+ String,+ Text,+ Boolean,+ Float,+ DateTime,+ ForeignKey,+)+from sqlalchemy.orm import relationship++from ...database.models.base import Base+++class FileIntegrityRecord(Base):+ """+ Track file integrity with embedded statistics.++ Stores current checksum and verification stats for files.+ Only failures are logged to separate table for efficiency.+ """++ __tablename__ = "file_integrity_records"++ # Identity+ id = Column(Integer, primary_key=True, autoincrement=True)+ file_path = Column(Text, nullable=False, unique=True, index=True)+ file_type = Column(+ String(50), nullable=False, index=True+ ) # 'faiss_index', 'pdf', 'export'++ # Current state+ checksum = Column(String(64), nullable=False) # SHA256 hash+ algorithm = Column(String(20), default="sha256")+ file_size = Column(Integer, nullable=True)+ file_mtime = Column(+ Float, nullable=True+ ) # OS modification time for smart verification++ # Policy+ verify_on_load = Column(+ Boolean, default=True+ ) # Should this file be verified before use?+ allow_modifications = Column(+ Boolean, default=False+ ) # Can file be legitimately modified? (PDFs=True, FAISS=False)++ # Embedded statistics (for efficiency)+ total_verifications = Column(Integer, default=0)+ last_verified_at = Column(DateTime, nullable=True)+ last_verification_passed = Column(Boolean, default=True)+ consecutive_successes = Column(Integer, default=0)+ consecutive_failures = Column(Integer, default=0)++ # Timestamps+ created_at = Column(DateTime, default=lambda: datetime.now(UTC))+ updated_at = Column(DateTime, onupdate=lambda: datetime.now(UTC))++ # Polymorphic relationship - can link to any entity+ related_entity_type = Column(+ String(50), nullable=True+ ) # 'rag_index', 'library_document', etc.+ related_entity_id = Column(Integer, nullable=True)++ # Sparse history - only failures logged+ verification_failures = relationship(+ "FileVerificationFailure",+ back_populates="file_record",+ cascade="all, delete-orphan",+ )++ def __repr__(self):+ return (+ f"<FileIntegrityRecord(id={self.id}, "+ f"path={self.file_path}, "+ f"type={self.file_type}, "+ f"verifications={self.total_verifications})>"+ )+++class FileVerificationFailure(Base):+ """+ Audit trail of file integrity verification failures.++ Only failures are logged to keep storage efficient.+ Provides debugging trail for corruption/tampering incidents.+ """++ __tablename__ = "file_verification_failures"++ id = Column(Integer, primary_key=True, autoincrement=True)+ file_record_id = Column(+ Integer,+ ForeignKey("file_integrity_records.id"),+ index=True,+ nullable=False,+ )++ verified_at = Column(DateTime, default=lambda: datetime.now(UTC))+ expected_checksum = Column(String(64), nullable=False)+ actual_checksum = Column(+ String(64), nullable=True+ ) # Null if file missing/unreadable+ file_size = Column(Integer, nullable=True)+ failure_reason = Column(+ Text, nullable=False+ ) # "checksum_mismatch", "file_missing", etc.++ file_record = relationship(+ "FileIntegrityRecord", back_populates="verification_failures"+ )++ def __repr__(self):+ return (+ f"<FileVerificationFailure(id={self.id}, "+ f"file_record_id={self.file_record_id}, "+ f"reason={self.failure_reason}, "+ f"verified_at={self.verified_at})>"+ )diff --git a/src/local_deep_research/security/file_integrity/verifiers/__init__.py b/src/local_deep_research/security/file_integrity/verifiers/__init__.pynew file mode 100644index 0000000000..9d592d600f--- /dev/null+++ b/src/local_deep_research/security/file_integrity/verifiers/__init__.py@@ -0,0 +1,5 @@+"""File integrity verifiers for different file types."""++from .faiss_verifier import FAISSIndexVerifier++__all__ = ["FAISSIndexVerifier"]diff --git a/src/local_deep_research/security/file_integrity/verifiers/faiss_verifier.py b/src/local_deep_research/security/file_integrity/verifiers/faiss_verifier.pynew file mode 100644index 0000000000..6f1a1c8839--- /dev/null+++ b/src/local_deep_research/security/file_integrity/verifiers/faiss_verifier.py@@ -0,0 +1,51 @@+"""+FAISS Index Verifier - Integrity verification for FAISS vector indexes.++FAISS indexes should never be manually modified, making them ideal+candidates for strict integrity verification.+"""++from pathlib import Path++from ..base_verifier import BaseFileVerifier+++class FAISSIndexVerifier(BaseFileVerifier):+ """+ Verifier for FAISS index files.++ Policy:+ - Verifies all .faiss files+ - Does not allow modifications (FAISS indexes are binary, should never be manually edited)+ - Uses default SHA256 checksum algorithm+ """++ def should_verify(self, file_path: Path) -> bool:+ """+ Check if this is a FAISS index file.++ Args:+ file_path: Path to check++ Returns:+ True if file has .faiss extension+ """+ return file_path.suffix.lower() == ".faiss"++ def get_file_type(self) -> str:+ """+ Get file type identifier.++ Returns:+ 'faiss_index'+ """+ return "faiss_index"++ def allows_modifications(self) -> bool:+ """+ FAISS indexes should never be manually modified.++ Returns:+ False - FAISS indexes are binary and should only be generated programmatically+ """+ return False