~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
fix: complete file descriptor leak fixes for DownloadService and LibraryRAGService (#1856)
LearningCircuitcb20473e50dc
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex b13811946f..df0fbb1d04 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -159,3 +159,9 @@ repos:language: scriptfiles: \.py$description: "Prevent direct requests.get/post/Session - use safe_get/safe_post/SafeSession"+ - id: check-service-context-managers+ name: Check services use context managers+ entry: .pre-commit-hooks/check-service-context-managers.py+ language: script+ files: \.py$+ description: "Ensure DownloadService, LibraryRAGService, LocalEmbeddingManager use context managers"diff --git a/.pre-commit-hooks/check-service-context-managers.py b/.pre-commit-hooks/check-service-context-managers.pynew file mode 100755index 0000000000..f160489d46--- /dev/null+++ b/.pre-commit-hooks/check-service-context-managers.py@@ -0,0 +1,418 @@+#!/usr/bin/env python3+"""+Pre-commit hook to detect services with close() methods that are instantiated+without context managers.++Services like DownloadService, LibraryRAGService, and LocalEmbeddingManager+hold resources (file handles, connections, models) that need to be released.+They should be used with context managers (with statements) to ensure cleanup.++Exceptions:+- Factory functions that return services (caller is responsible for cleanup)+- Services passed to other objects (dependency injection)+- try/finally with explicit close()+"""++import ast+import sys+from typing import List, Optional, Set, Tuple+++# Services that require context manager usage+SERVICES_REQUIRING_CONTEXT = {+ "DownloadService",+ "LibraryRAGService",+ "LocalEmbeddingManager",+}++# Files/patterns where direct instantiation is allowed+ALLOWED_PATTERNS = {+ "tests/", # Test files often mock or need special handling+ "test_", # Test files+ "_test.py", # Test files+ # The service implementations themselves+ "download_service.py",+ "library_rag_service.py",+ "search_engine_local.py",+}+++def is_file_allowed(filename: str) -> bool:+ """Check if this file is allowed to use services without context managers."""+ for pattern in ALLOWED_PATTERNS:+ if pattern in filename:+ return True+ return False+++def get_service_name(node: ast.expr) -> Optional[str]:+ """Check if an expression is a service instantiation."""+ if not isinstance(node, ast.Call):+ return None++ # Check for ServiceName() pattern+ if isinstance(node.func, ast.Name):+ if node.func.id in SERVICES_REQUIRING_CONTEXT:+ return node.func.id++ # Check for module.ServiceName() pattern+ if isinstance(node.func, ast.Attribute):+ if node.func.attr in SERVICES_REQUIRING_CONTEXT:+ return node.func.attr++ return None+++class FunctionScopeAnalyzer(ast.NodeVisitor):+ """Analyze patterns within a function scope."""++ def __init__(self):+ self.close_vars: Set[str] = set() # Variables with try/finally close()+ self.safe_with_lines: Set[int] = set() # Lines in with context+ self.returned_vars: Set[str] = set() # Variables that are returned+ self.passed_to_args_vars: Set[str] = (+ set()+ ) # Variables passed as arguments++ def visit_Try(self, node: ast.Try) -> None:+ """Find variables that are closed in finally blocks within this scope."""+ if node.finalbody:+ for stmt in node.finalbody:+ if isinstance(stmt, ast.Expr) and isinstance(+ stmt.value, ast.Call+ ):+ call = stmt.value+ if (+ isinstance(call.func, ast.Attribute)+ and call.func.attr == "close"+ and isinstance(call.func.value, ast.Name)+ ):+ self.close_vars.add(call.func.value.id)+ self.generic_visit(node)++ def visit_With(self, node: ast.With) -> None:+ """Mark with statements that use services as context managers."""+ for item in node.items:+ service_name = get_service_name(item.context_expr)+ if service_name:+ self.safe_with_lines.add(item.context_expr.lineno)+ self.generic_visit(node)++ def visit_AsyncWith(self, node: ast.AsyncWith) -> None:+ """Mark async with statements that use services as context managers."""+ for item in node.items:+ service_name = get_service_name(item.context_expr)+ if service_name:+ self.safe_with_lines.add(item.context_expr.lineno)+ self.generic_visit(node)++ def visit_Return(self, node: ast.Return) -> None:+ """Track variables that are returned (factory function pattern)."""+ if node.value and isinstance(node.value, ast.Name):+ self.returned_vars.add(node.value.id)+ # Also handle direct service returns+ if node.value and get_service_name(node.value):+ # This is a direct return of a service - mark the line as safe+ self.safe_with_lines.add(node.value.lineno)+ self.generic_visit(node)++ def visit_Call(self, node: ast.Call) -> None:+ """Track variables passed as arguments to other functions."""+ # Check all arguments+ for arg in node.args:+ if isinstance(arg, ast.Name):+ self.passed_to_args_vars.add(arg.id)+ # Check keyword arguments+ for kwarg in node.keywords:+ if isinstance(kwarg.value, ast.Name):+ self.passed_to_args_vars.add(kwarg.value.id)+ self.generic_visit(node)+++class ServiceContextChecker(ast.NodeVisitor):+ """Check for service instantiations that aren't properly managed."""++ def __init__(self):+ self.errors: List[Tuple[int, str]] = []++ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:+ """Analyze a function for improper service usage."""+ self._check_function_body(node)+ self.generic_visit(node)++ def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:+ """Analyze an async function for improper service usage."""+ self._check_function_body(node)+ self.generic_visit(node)++ def visit_Module(self, node: ast.Module) -> None:+ """Also check module-level code."""+ # Create a fake function body from module-level statements+ # that aren't inside functions+ module_stmts = []+ for stmt in node.body:+ if not isinstance(+ stmt, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)+ ):+ module_stmts.append(stmt)++ if module_stmts:+ self._check_statements(module_stmts)++ self.generic_visit(node)++ def _check_function_body(self, func_node) -> None:+ """Check a function body for improper service usage."""+ self._check_statements(func_node.body)++ def _check_statements(self, statements: List[ast.stmt]) -> None:+ """Check a list of statements for improper service usage."""+ # First, analyze this scope for patterns+ analyzer = FunctionScopeAnalyzer()+ for stmt in statements:+ analyzer.visit(stmt)++ # Now check each statement for service assignments+ self._check_statements_recursive(+ statements,+ analyzer.close_vars,+ analyzer.safe_with_lines,+ analyzer.returned_vars,+ analyzer.passed_to_args_vars,+ )++ def _check_statements_recursive(+ self,+ statements: List[ast.stmt],+ close_vars: Set[str],+ safe_with_lines: Set[int],+ returned_vars: Set[str],+ passed_to_args_vars: Set[str],+ ) -> None:+ """Recursively check statements for service assignments."""+ for stmt in statements:+ if isinstance(stmt, ast.Assign):+ self._check_assign(+ stmt,+ close_vars,+ safe_with_lines,+ returned_vars,+ passed_to_args_vars,+ )+ elif isinstance(stmt, ast.With):+ self._check_statements_recursive(+ stmt.body,+ close_vars,+ safe_with_lines,+ returned_vars,+ passed_to_args_vars,+ )+ elif isinstance(stmt, ast.AsyncWith):+ self._check_statements_recursive(+ stmt.body,+ close_vars,+ safe_with_lines,+ returned_vars,+ passed_to_args_vars,+ )+ elif isinstance(stmt, ast.If):+ self._check_statements_recursive(+ stmt.body,+ close_vars,+ safe_with_lines,+ returned_vars,+ passed_to_args_vars,+ )+ self._check_statements_recursive(+ stmt.orelse,+ close_vars,+ safe_with_lines,+ returned_vars,+ passed_to_args_vars,+ )+ elif isinstance(stmt, ast.For):+ self._check_statements_recursive(+ stmt.body,+ close_vars,+ safe_with_lines,+ returned_vars,+ passed_to_args_vars,+ )+ self._check_statements_recursive(+ stmt.orelse,+ close_vars,+ safe_with_lines,+ returned_vars,+ passed_to_args_vars,+ )+ elif isinstance(stmt, ast.While):+ self._check_statements_recursive(+ stmt.body,+ close_vars,+ safe_with_lines,+ returned_vars,+ passed_to_args_vars,+ )+ self._check_statements_recursive(+ stmt.orelse,+ close_vars,+ safe_with_lines,+ returned_vars,+ passed_to_args_vars,+ )+ elif isinstance(stmt, ast.Try):+ self._check_statements_recursive(+ stmt.body,+ close_vars,+ safe_with_lines,+ returned_vars,+ passed_to_args_vars,+ )+ for handler in stmt.handlers:+ self._check_statements_recursive(+ handler.body,+ close_vars,+ safe_with_lines,+ returned_vars,+ passed_to_args_vars,+ )+ self._check_statements_recursive(+ stmt.orelse,+ close_vars,+ safe_with_lines,+ returned_vars,+ passed_to_args_vars,+ )+ self._check_statements_recursive(+ stmt.finalbody,+ close_vars,+ safe_with_lines,+ returned_vars,+ passed_to_args_vars,+ )++ def _check_assign(+ self,+ node: ast.Assign,+ close_vars: Set[str],+ safe_with_lines: Set[int],+ returned_vars: Set[str],+ passed_to_args_vars: Set[str],+ ) -> None:+ """Check an assignment for improper service usage."""+ service_name = get_service_name(node.value)+ if not service_name:+ return++ # Get the variable name being assigned+ var_name = None+ if node.targets and isinstance(node.targets[0], ast.Name):+ var_name = node.targets[0].id++ # Check if this is a safe instantiation+ if node.value.lineno in safe_with_lines:+ # Inside a with statement as context manager - safe+ return++ if var_name and var_name in close_vars:+ # Has explicit try/finally with close() in the same function - acceptable+ return++ if var_name and var_name in returned_vars:+ # Variable is returned (factory function pattern) - caller responsible+ return++ if var_name and var_name in passed_to_args_vars:+ # Variable is passed to another function (dependency injection) - receiver responsible+ return++ # Not safe - flag this+ self.errors.append(+ (+ node.lineno,+ f"{service_name} should be used with a context manager "+ f"('with {service_name}(...) as var:') to ensure proper cleanup.",+ )+ )+++def check_file(filename: str) -> bool:+ """Check a single Python file for service context manager usage."""+ if not filename.endswith(".py"):+ return True++ if is_file_allowed(filename):+ return True++ try:+ with open(filename, "r", encoding="utf-8") as f:+ content = f.read()+ except Exception as e:+ print(f"Error reading {filename}: {e}")+ return False++ try:+ tree = ast.parse(content, filename=filename)++ # Check for service instantiations+ checker = ServiceContextChecker()+ checker.visit(tree)++ if checker.errors:+ print(f"\n{filename}:")+ for line_num, error in checker.errors:+ print(f" Line {line_num}: {error}")+ return False++ except SyntaxError:+ # Skip files with syntax errors (let other tools handle that)+ pass+ except Exception as e:+ print(f"Error parsing {filename}: {e}")+ return False++ return True+++def main():+ """Main function to check all provided Python files."""+ if len(sys.argv) < 2:+ print("Usage: check-service-context-managers.py <file1> <file2> ...")+ sys.exit(1)++ files_to_check = sys.argv[1:]+ has_errors = False++ for filename in files_to_check:+ if not check_file(filename):+ has_errors = True++ if has_errors:+ print("\n" + "=" * 70)+ print("Resource Leak Prevention: Services need context managers!")+ print("=" * 70)+ print("\nServices like DownloadService, LibraryRAGService, and")+ print("LocalEmbeddingManager hold resources that need cleanup.")+ print("\nTo fix, use context managers:")+ print(" # Before (leaks resources):")+ print(" service = DownloadService()")+ print(" result = service.download(...)")+ print()+ print(" # After (proper cleanup):")+ print(" with DownloadService() as service:")+ print(" result = service.download(...)")+ print("\nAlternatively, use try/finally with explicit close():")+ print(" service = DownloadService()")+ print(" try:")+ print(" result = service.download(...)")+ print(" finally:")+ print(" service.close()")+ print("\nNote: Factory functions that return services are allowed,")+ print("as the caller is responsible for cleanup.")+ sys.exit(1)+ else:+ sys.exit(0)+++if __name__ == "__main__":+ main()diff --git a/src/local_deep_research/research_library/deletion/utils/cascade_helper.py b/src/local_deep_research/research_library/deletion/utils/cascade_helper.pyindex 5429b672f0..05bf4d7dc2 100644--- a/src/local_deep_research/research_library/deletion/utils/cascade_helper.py+++ b/src/local_deep_research/research_library/deletion/utils/cascade_helper.py@@ -352,18 +352,20 @@ class CascadeHelper:True if successful"""try:- from ..services.library_rag_service import LibraryRAGService+ from ...services.library_rag_service import LibraryRAGService- rag_service = LibraryRAGService(+ with LibraryRAGService(username=username,collection_name=collection_name,- )-- # This uses the existing remove functionality- if hasattr(rag_service, "faiss_index") and rag_service.faiss_index:- if hasattr(rag_service.faiss_index, "delete"):- rag_service.faiss_index.delete(chunk_ids)- return True+ ) as rag_service:+ # This uses the existing remove functionality+ if (+ hasattr(rag_service, "faiss_index")+ and rag_service.faiss_index+ ):+ if hasattr(rag_service.faiss_index, "delete"):+ rag_service.faiss_index.delete(chunk_ids)+ return Trueexcept Exception:logger.exception("Failed to remove chunks from FAISS index")return Falsediff --git a/src/local_deep_research/research_library/routes/library_routes.py b/src/local_deep_research/research_library/routes/library_routes.pyindex c56587208e..5a6ae3ec73 100644--- a/src/local_deep_research/research_library/routes/library_routes.py+++ b/src/local_deep_research/research_library/routes/library_routes.py@@ -625,19 +625,21 @@ def download_single_resource(resource_id):"""Download a single resource."""username = session.get("username")user_password = get_authenticated_user_password(username)- service = DownloadService(username, user_password)- success, error = service.download_resource(resource_id)- if success:- return jsonify({"success": True})- else:- logger.warning(f"Download failed for resource {resource_id}: {error}")- return jsonify(- {- "success": False,- "error": "Download failed. Please try again or contact support.",- }- ), 500+ with DownloadService(username, user_password) as service:+ success, error = service.download_resource(resource_id)+ if success:+ return jsonify({"success": True})+ else:+ logger.warning(+ f"Download failed for resource {resource_id}: {error}"+ )+ return jsonify(+ {+ "success": False,+ "error": "Download failed. Please try again or contact support.",+ }+ ), 500@library_bp.route("/api/download-text/<int:resource_id>", methods=["POST"])@@ -647,21 +649,21 @@ def download_text_single(resource_id):try:username = session.get("username")user_password = get_authenticated_user_password(username)- service = DownloadService(username, user_password)- success, error = service.download_as_text(resource_id)+ with DownloadService(username, user_password) as service:+ success, error = service.download_as_text(resource_id)- # Sanitize error message - don't expose internal details- if not success:- if error:- logger.warning(- f"Download as text failed for resource {resource_id}: {error}"+ # Sanitize error message - don't expose internal details+ if not success:+ if error:+ logger.warning(+ f"Download as text failed for resource {resource_id}: {error}"+ )+ return jsonify(+ {"success": False, "error": "Failed to download resource"})- return jsonify(- {"success": False, "error": "Failed to download resource"}- )- return jsonify({"success": True, "error": None})+ return jsonify({"success": True, "error": None})except Exception as e:return handle_api_error(f"downloading resource {resource_id} as text", e@@ -689,73 +691,79 @@ def download_all_text():returndownload_service = DownloadService(username, user_password)-- # Get all undownloaded resources- with get_user_db_session(username) as session:- # Get resources that don't have text files yet- resources = session.query(ResearchResource).all()-- # Filter resources that need text extraction- txt_path = Path(download_service.library_root) / "txt"- resources_to_process = []-- for resource in resources:- # Check if text file already exists- if txt_path.exists():- existing = list(txt_path.glob(f"*_{resource.id}.txt"))- if not existing:+ try:+ # Get all undownloaded resources+ with get_user_db_session(username) as session:+ # Get resources that don't have text files yet+ resources = session.query(ResearchResource).all()++ # Filter resources that need text extraction+ txt_path = Path(download_service.library_root) / "txt"+ resources_to_process = []++ for resource in resources:+ # Check if text file already exists+ if txt_path.exists():+ existing = list(txt_path.glob(f"*_{resource.id}.txt"))+ if not existing:+ resources_to_process.append(resource)+ else:resources_to_process.append(resource)- else:- resources_to_process.append(resource)-- total = len(resources_to_process)- current = 0- logger.info(f"Found {total} resources needing text extraction")+ total = len(resources_to_process)+ current = 0- for resource in resources_to_process:- current += 1- progress = int((current / total) * 100) if total > 0 else 100+ logger.info(f"Found {total} resources needing text extraction")- file_name = (- resource.title[:50]- if resource- else f"document_{current}.txt"- )+ for resource in resources_to_process:+ current += 1+ progress = (+ int((current / total) * 100) if total > 0 else 100+ )- try:- success, error = download_service.download_as_text(- resource.id+ file_name = (+ resource.title[:50]+ if resource+ else f"document_{current}.txt")- if success:- status = "success"- error_msg = None- else:+ try:+ success, error = download_service.download_as_text(+ resource.id+ )++ if success:+ status = "success"+ error_msg = None+ else:+ status = "failed"+ error_msg = error or "Text extraction failed"++ except Exception as e:+ logger.exception(+ f"Error extracting text for resource {resource.id}"+ )status = "failed"- error_msg = error or "Text extraction failed"+ error_msg = (+ f"Text extraction failed - {type(e).__name__}"+ )- except Exception as e:- logger.exception(- f"Error extracting text for resource {resource.id}"- )- status = "failed"- error_msg = f"Text extraction failed - {type(e).__name__}"-- # Send update- update = {- "progress": progress,- "current": current,- "total": total,- "file": file_name,- "url": resource.url, # Add the URL for UI display- "status": status,- "error": error_msg,- }- yield f"data: {json.dumps(update)}\n\n"+ # Send update+ update = {+ "progress": progress,+ "current": current,+ "total": total,+ "file": file_name,+ "url": resource.url, # Add the URL for UI display+ "status": status,+ "error": error_msg,+ }+ yield f"data: {json.dumps(update)}\n\n"- # Send completion- yield f"data: {json.dumps({'complete': True, 'total': total})}\n\n"+ # Send completion+ yield f"data: {json.dumps({'complete': True, 'total': total})}\n\n"+ finally:+ download_service.close()return Response(stream_with_context(generate()), mimetype="text/event-stream"@@ -768,19 +776,19 @@ def download_research_pdfs(research_id):"""Queue all PDFs from a research session for download."""username = session.get("username")user_password = get_authenticated_user_password(username)- service = DownloadService(username, user_password)- # Get optional collection_id from request body- data = request.json or {}- collection_id = data.get("collection_id")+ with DownloadService(username, user_password) as service:+ # Get optional collection_id from request body+ data = request.json or {}+ collection_id = data.get("collection_id")- queued = service.queue_research_downloads(research_id, collection_id)+ queued = service.queue_research_downloads(research_id, collection_id)- # Start processing queue (in production, this would be a background task)- # For now, we'll process synchronously- # TODO: Integrate with existing queue processor+ # Start processing queue (in production, this would be a background task)+ # For now, we'll process synchronously+ # TODO: Integrate with existing queue processor- return jsonify({"success": True, "queued": queued})+ return jsonify({"success": True, "queued": queued})@library_bp.route("/api/download-bulk", methods=["POST"])@@ -814,200 +822,208 @@ def download_bulk():returndownload_service = DownloadService(username, user_password)+ try:+ # Count total pending queue items across all research IDs+ total = 0+ current = 0- # Count total pending queue items across all research IDs- total = 0- current = 0-- with get_user_db_session(username) as session:- for research_id in research_ids:- count = (- session.query(LibraryDownloadQueue)- .filter_by(- research_id=research_id, status=DocumentStatus.PENDING- )- .count()- )- total += count- logger.debug(- f"[PROGRESS_DEBUG] Research {research_id}: {count} pending items in queue"- )-- logger.info(- f"[PROGRESS_DEBUG] Total pending downloads across all research: {total}"- )- yield f"data: {json.dumps({'progress': 0, 'current': 0, 'total': total})}\n\n"-- # Process each research- for research_id in research_ids:- # Get queued downloads for this researchwith get_user_db_session(username) as session:- # Get pending queue items for this research- queue_items = (- session.query(LibraryDownloadQueue)- .filter_by(- research_id=research_id, status=DocumentStatus.PENDING- )- .all()- )-- # If no items queued yet, queue them now- if not queue_items:- try:- download_service.queue_research_downloads(- research_id, collection_id- )- # Re-fetch queue items- queue_items = (- session.query(LibraryDownloadQueue)- .filter_by(- research_id=research_id, status="pending"- )- .all()- )- except Exception:- logger.exception(- f"Error queueing downloads for research {research_id}"+ for research_id in research_ids:+ count = (+ session.query(LibraryDownloadQueue)+ .filter_by(+ research_id=research_id,+ status=DocumentStatus.PENDING,)- # Continue with empty queue_items- queue_items = []-- # Process each queued item- for queue_item in queue_items:- logger.debug(- f"[PROGRESS_DEBUG] Before increment: current={current} (type: {type(current)}), total={total} (type: {type(total)})"+ .count())- current += 1+ total += countlogger.debug(- f"[PROGRESS_DEBUG] After increment: current={current} (type: {type(current)})"+ f"[PROGRESS_DEBUG] Research {research_id}: {count} pending items in queue")- # Check for division issues- if total is None:- logger.error(- "[PROGRESS_DEBUG] ERROR: total is None! Setting to 0 to avoid crash"- )- total = 0-- progress = (- int((current / total) * 100) if total > 0 else 100- )- logger.debug(- f"[PROGRESS_DEBUG] Calculated progress: {progress}%"- )-- # Get resource info- resource = session.query(ResearchResource).get(- queue_item.resource_id- )- file_name = (- resource.title[:50]- if resource- else f"document_{current}.pdf"- )-- # Attempt actual download with error handling- skip_reason = None- status = "skipped" # Default to skipped- success = False- error_msg = None+ logger.info(+ f"[PROGRESS_DEBUG] Total pending downloads across all research: {total}"+ )+ yield f"data: {json.dumps({'progress': 0, 'current': 0, 'total': total})}\n\n"- try:- logger.debug(- f"Attempting {'PDF download' if mode == 'pdf' else 'text extraction'} for resource {queue_item.resource_id}"+ # Process each research+ for research_id in research_ids:+ # Get queued downloads for this research+ with get_user_db_session(username) as session:+ # Get pending queue items for this research+ queue_items = (+ session.query(LibraryDownloadQueue)+ .filter_by(+ research_id=research_id,+ status=DocumentStatus.PENDING,)+ .all()+ )- # Call appropriate service method based on mode- if mode == "pdf":- result = download_service.download_resource(- queue_item.resource_id+ # If no items queued yet, queue them now+ if not queue_items:+ try:+ download_service.queue_research_downloads(+ research_id, collection_id+ )+ # Re-fetch queue items+ queue_items = (+ session.query(LibraryDownloadQueue)+ .filter_by(+ research_id=research_id, status="pending"+ )+ .all())- else: # text_only- result = download_service.download_as_text(- queue_item.resource_id+ except Exception:+ logger.exception(+ f"Error queueing downloads for research {research_id}")+ # Continue with empty queue_items+ queue_items = []- # Handle new tuple return format- if isinstance(result, tuple):- success, skip_reason = result- else:- success = result- skip_reason = None+ # Process each queued item+ for queue_item in queue_items:+ logger.debug(+ f"[PROGRESS_DEBUG] Before increment: current={current} (type: {type(current)}), total={total} (type: {type(total)})"+ )+ current += 1+ logger.debug(+ f"[PROGRESS_DEBUG] After increment: current={current} (type: {type(current)})"+ )- status = "success" if success else "skipped"- if skip_reason and not success:- error_msg = skip_reason- logger.info(- f"{'Download' if mode == 'pdf' else 'Text extraction'} skipped for resource {queue_item.resource_id}: {skip_reason}"+ # Check for division issues+ if total is None:+ logger.error(+ "[PROGRESS_DEBUG] ERROR: total is None! Setting to 0 to avoid crash")+ total = 0+ progress = (+ int((current / total) * 100) if total > 0 else 100+ )logger.debug(- f"{'Download' if mode == 'pdf' else 'Text extraction'} result: success={success}, status={status}, skip_reason={skip_reason}"+ f"[PROGRESS_DEBUG] Calculated progress: {progress}%")- except Exception as e:- # Log error but continue processing- error_msg = str(e)- error_type = type(e).__name__- logger.info(- f"CAUGHT Download exception for resource {queue_item.resource_id}: {error_type}: {error_msg}"++ # Get resource info+ resource = session.query(ResearchResource).get(+ queue_item.resource_id)- # Check if this is a skip reason (not a real error)- # Use error category + categorized message for user display- if any(- phrase in error_msg.lower()- for phrase in [- "paywall",- "subscription",- "not available",- "not found",- "no free",- "embargoed",- "forbidden",- "not accessible",- ]- ):- status = "skipped"- skip_reason = f"Document not accessible (paywall or access restriction) - {error_type}"- elif any(- phrase in error_msg.lower()- for phrase in [- "failed to download",- "could not",- "invalid",- "server",- ]- ):- status = "failed"- skip_reason = f"Download failed - {error_type}"- else:- status = "failed"- skip_reason = f"Processing failed - {error_type}"+ file_name = (+ resource.title[:50]+ if resource+ else f"document_{current}.pdf"+ )++ # Attempt actual download with error handling+ skip_reason = None+ status = "skipped" # Default to skippedsuccess = False+ error_msg = None- # Ensure skip_reason is set if we have an error message- if error_msg and not skip_reason:- skip_reason = f"Processing failed - {error_type}"- logger.debug(- f"Setting skip_reason from error_msg: {error_msg}"- )+ try:+ logger.debug(+ f"Attempting {'PDF download' if mode == 'pdf' else 'text extraction'} for resource {queue_item.resource_id}"+ )- # Send progress update- update_data = {- "progress": progress,- "current": current,- "total": total,- "file": file_name,- "status": status,- }- # Add skip reason if available- if skip_reason:- update_data["error"] = skip_reason- logger.info(f"Sending skip reason to UI: {skip_reason}")+ # Call appropriate service method based on mode+ if mode == "pdf":+ result = download_service.download_resource(+ queue_item.resource_id+ )+ else: # text_only+ result = download_service.download_as_text(+ queue_item.resource_id+ )++ # Handle new tuple return format+ if isinstance(result, tuple):+ success, skip_reason = result+ else:+ success = result+ skip_reason = None++ status = "success" if success else "skipped"+ if skip_reason and not success:+ error_msg = skip_reason+ logger.info(+ f"{'Download' if mode == 'pdf' else 'Text extraction'} skipped for resource {queue_item.resource_id}: {skip_reason}"+ )++ logger.debug(+ f"{'Download' if mode == 'pdf' else 'Text extraction'} result: success={success}, status={status}, skip_reason={skip_reason}"+ )+ except Exception as e:+ # Log error but continue processing+ error_msg = str(e)+ error_type = type(e).__name__+ logger.info(+ f"CAUGHT Download exception for resource {queue_item.resource_id}: {error_type}: {error_msg}"+ )+ # Check if this is a skip reason (not a real error)+ # Use error category + categorized message for user display+ if any(+ phrase in error_msg.lower()+ for phrase in [+ "paywall",+ "subscription",+ "not available",+ "not found",+ "no free",+ "embargoed",+ "forbidden",+ "not accessible",+ ]+ ):+ status = "skipped"+ skip_reason = f"Document not accessible (paywall or access restriction) - {error_type}"+ elif any(+ phrase in error_msg.lower()+ for phrase in [+ "failed to download",+ "could not",+ "invalid",+ "server",+ ]+ ):+ status = "failed"+ skip_reason = f"Download failed - {error_type}"+ else:+ status = "failed"+ skip_reason = (+ f"Processing failed - {error_type}"+ )+ success = False++ # Ensure skip_reason is set if we have an error message+ if error_msg and not skip_reason:+ skip_reason = f"Processing failed - {error_type}"+ logger.debug(+ f"Setting skip_reason from error_msg: {error_msg}"+ )++ # Send progress update+ update_data = {+ "progress": progress,+ "current": current,+ "total": total,+ "file": file_name,+ "status": status,+ }+ # Add skip reason if available+ if skip_reason:+ update_data["error"] = skip_reason+ logger.info(+ f"Sending skip reason to UI: {skip_reason}"+ )- logger.info(f"Update data being sent: {update_data}")- yield f"data: {json.dumps(update_data)}\n\n"+ logger.info(f"Update data being sent: {update_data}")+ yield f"data: {json.dumps(update_data)}\n\n"- yield f"data: {json.dumps({'progress': 100, 'current': total, 'total': total, 'complete': True})}\n\n"+ yield f"data: {json.dumps({'progress': 100, 'current': total, 'total': total, 'complete': True})}\n\n"+ finally:+ download_service.close()return Response(stream_with_context(generate()),@@ -1370,11 +1386,13 @@ def download_source():db_session.commit()# Start download immediately- service = DownloadService(username, user_password)- success, message = service.download_resource(resource.id)+ with DownloadService(username, user_password) as service:+ success, message = service.download_resource(resource.id)- if success:- return jsonify({"success": True, "message": "Download completed"})- else:- # Log internal message, but show only generic message to user- return jsonify({"success": False, "message": "Download failed"})+ if success:+ return jsonify(+ {"success": True, "message": "Download completed"}+ )+ else:+ # Log internal message, but show only generic message to user+ return jsonify({"success": False, "message": "Download failed"})diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.pyindex d246f986da..2541de2ee9 100644--- a/src/local_deep_research/research_library/routes/rag_routes.py+++ b/src/local_deep_research/research_library/routes/rag_routes.py@@ -853,7 +853,7 @@ def configure_rag():# If collection_id is provided, update that collection's configurationif collection_id:# Create new RAG service with new configuration- new_rag_service = LibraryRAGService(+ with LibraryRAGService(username=session["username"],embedding_model=embedding_model,embedding_provider=embedding_provider,@@ -866,18 +866,19 @@ def configure_rag():distance_metric=distance_metric,normalize_vectors=normalize_vectors,index_type=index_type,- )-- # Get or create new index with this configuration- rag_index = new_rag_service._get_or_create_rag_index(collection_id)+ ) as new_rag_service:+ # Get or create new index with this configuration+ rag_index = new_rag_service._get_or_create_rag_index(+ collection_id+ )- return jsonify(- {- "success": True,- "message": "Configuration updated for collection. You can now index documents with the new settings.",- "index_hash": rag_index.index_hash,- }- )+ return jsonify(+ {+ "success": True,+ "message": "Configuration updated for collection. You can now index documents with the new settings.",+ "index_hash": rag_index.index_hash,+ }+ )else:# Just saving default settings without updating a specific collectionreturn jsonify(@@ -2349,27 +2350,28 @@ def _auto_index_documents_worker(try:# Create RAG service (thread-safe, no Flask context needed)- rag_service = _get_rag_service_for_thread(+ with _get_rag_service_for_thread(collection_id, username, db_password- )-- indexed_count = 0- for doc_id in document_ids:- try:- result = rag_service.index_document(- doc_id, collection_id, force_reindex=False- )- if result.get("status") == "success":- indexed_count += 1- logger.debug(f"Auto-indexed document {doc_id}")- elif result.get("status") == "skipped":- logger.debug(f"Document {doc_id} already indexed, skipped")- except Exception:- logger.exception(f"Failed to auto-index document {doc_id}")+ ) as rag_service:+ indexed_count = 0+ for doc_id in document_ids:+ try:+ result = rag_service.index_document(+ doc_id, collection_id, force_reindex=False+ )+ if result.get("status") == "success":+ indexed_count += 1+ logger.debug(f"Auto-indexed document {doc_id}")+ elif result.get("status") == "skipped":+ logger.debug(+ f"Document {doc_id} already indexed, skipped"+ )+ except Exception:+ logger.exception(f"Failed to auto-index document {doc_id}")- logger.info(- f"Auto-indexing complete: {indexed_count}/{len(document_ids)} documents indexed"- )+ logger.info(+ f"Auto-indexing complete: {indexed_count}/{len(document_ids)} documents indexed"+ )except Exception:logger.exception("Auto-indexing worker failed")@@ -2390,131 +2392,136 @@ def _background_index_worker(try:# Create RAG service (thread-safe, no Flask context needed)- rag_service = _get_rag_service_for_thread(+ with _get_rag_service_for_thread(collection_id, username, db_password- )-- with get_user_db_session(username, db_password) as db_session:- # Get collection- collection = (- db_session.query(Collection).filter_by(id=collection_id).first()- )-- if not collection:- _update_task_status(- username,- db_password,- task_id,- status="failed",- error_message="Collection not found",- )- return-- # Store embedding metadata if first time- if collection.embedding_model is None:- collection.embedding_model = rag_service.embedding_model- collection.embedding_model_type = EmbeddingProvider(- rag_service.embedding_provider- )- collection.chunk_size = rag_service.chunk_size- collection.chunk_overlap = rag_service.chunk_overlap- collection.splitter_type = rag_service.splitter_type- collection.text_separators = rag_service.text_separators- collection.distance_metric = rag_service.distance_metric- collection.normalize_vectors = bool(- rag_service.normalize_vectors+ ) as rag_service:+ with get_user_db_session(username, db_password) as db_session:+ # Get collection+ collection = (+ db_session.query(Collection)+ .filter_by(id=collection_id)+ .first())- collection.index_type = rag_service.index_type- db_session.commit()-- # Get documents to index- query = (- db_session.query(DocumentCollection, Document)- .join(Document)- .filter(DocumentCollection.collection_id == collection_id)- )- if not force_reindex:- query = query.filter(DocumentCollection.indexed == False) # noqa: E712+ if not collection:+ _update_task_status(+ username,+ db_password,+ task_id,+ status="failed",+ error_message="Collection not found",+ )+ return- doc_links = query.all()+ # Store embedding metadata if first time+ if collection.embedding_model is None:+ collection.embedding_model = rag_service.embedding_model+ collection.embedding_model_type = EmbeddingProvider(+ rag_service.embedding_provider+ )+ collection.chunk_size = rag_service.chunk_size+ collection.chunk_overlap = rag_service.chunk_overlap+ collection.splitter_type = rag_service.splitter_type+ collection.text_separators = rag_service.text_separators+ collection.distance_metric = rag_service.distance_metric+ collection.normalize_vectors = bool(+ rag_service.normalize_vectors+ )+ collection.index_type = rag_service.index_type+ db_session.commit()- if not doc_links:- _update_task_status(- username,- db_password,- task_id,- status="completed",- progress_message="No documents to index",+ # Get documents to index+ query = (+ db_session.query(DocumentCollection, Document)+ .join(Document)+ .filter(DocumentCollection.collection_id == collection_id))- return- total = len(doc_links)- results = {"successful": 0, "skipped": 0, "failed": 0}+ if not force_reindex:+ query = query.filter(DocumentCollection.indexed == False) # noqa: E712- # Update task with total count- _update_task_status(- username,- db_password,- task_id,- progress_total=total,- progress_message=f"Indexing {total} documents",- )+ doc_links = query.all()- for idx, (link, doc) in enumerate(doc_links, 1):- # Check if cancelled- if _is_task_cancelled(username, db_password, task_id):+ if not doc_links:_update_task_status(username,db_password,task_id,- status="cancelled",- progress_message=f"Cancelled after {idx - 1}/{total} documents",+ status="completed",+ progress_message="No documents to index",)- logger.info(f"Indexing task {task_id} was cancelled")return- filename = doc.filename or doc.title or "Unknown"+ total = len(doc_links)+ results = {"successful": 0, "skipped": 0, "failed": 0}- # Update progress with filename+ # Update task with total count_update_task_status(username,db_password,task_id,- progress_current=idx,- progress_message=f"Indexing {idx}/{total}: {filename}",+ progress_total=total,+ progress_message=f"Indexing {total} documents",)- try:- result = rag_service.index_document(- document_id=doc.id,- collection_id=collection_id,- force_reindex=force_reindex,+ for idx, (link, doc) in enumerate(doc_links, 1):+ # Check if cancelled+ if _is_task_cancelled(username, db_password, task_id):+ _update_task_status(+ username,+ db_password,+ task_id,+ status="cancelled",+ progress_message=f"Cancelled after {idx - 1}/{total} documents",+ )+ logger.info(f"Indexing task {task_id} was cancelled")+ return++ filename = doc.filename or doc.title or "Unknown"++ # Update progress with filename+ _update_task_status(+ username,+ db_password,+ task_id,+ progress_current=idx,+ progress_message=f"Indexing {idx}/{total}: {filename}",)- if result.get("status") == "success":- results["successful"] += 1- elif result.get("status") == "skipped":- results["skipped"] += 1- else:- results["failed"] += 1+ try:+ result = rag_service.index_document(+ document_id=doc.id,+ collection_id=collection_id,+ force_reindex=force_reindex,+ )- except Exception:- results["failed"] += 1- logger.exception(f"Error indexing document {idx}/{total}")+ if result.get("status") == "success":+ results["successful"] += 1+ elif result.get("status") == "skipped":+ results["skipped"] += 1+ else:+ results["failed"] += 1- db_session.commit()+ except Exception:+ results["failed"] += 1+ logger.exception(+ f"Error indexing document {idx}/{total}"+ )- # Mark as completed- _update_task_status(- username,- db_password,- task_id,- status="completed",- progress_current=total,- progress_message=f"Completed: {results['successful']} indexed, {results['failed']} failed, {results['skipped']} skipped",- )- logger.info(f"Background indexing task {task_id} completed: {results}")+ db_session.commit()++ # Mark as completed+ _update_task_status(+ username,+ db_password,+ task_id,+ status="completed",+ progress_current=total,+ progress_message=f"Completed: {results['successful']} indexed, {results['failed']} failed, {results['skipped']} skipped",+ )+ logger.info(+ f"Background indexing task {task_id} completed: {results}"+ )except Exception as e:logger.exception(f"Background indexing task {task_id} failed")diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_collection.py b/src/local_deep_research/web_search_engines/engines/search_engine_collection.pyindex f79b7f6392..261410ae89 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_collection.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_collection.py@@ -158,85 +158,84 @@ class CollectionSearchEngine(LibraryRAGSearchEngine):chunk_overlap = rag_index.chunk_overlap or self.chunk_overlap# Create RAG service with collection's embedding settings- rag_service = LibraryRAGService(+ with LibraryRAGService(username=self.username,embedding_model=embedding_model,embedding_provider=embedding_provider,chunk_size=chunk_size,chunk_overlap=chunk_overlap,- )+ ) as rag_service:+ # Check if there are indexed documents+ stats = rag_service.get_rag_stats(self.collection_id)+ if stats.get("indexed_documents", 0) == 0:+ logger.info(+ f"No documents indexed in collection '{self.collection_name}'"+ )+ return []- # Check if there are indexed documents- stats = rag_service.get_rag_stats(self.collection_id)- if stats.get("indexed_documents", 0) == 0:- logger.info(- f"No documents indexed in collection '{self.collection_name}'"+ # Load and search the FAISS index for this collection+ vector_store = rag_service.load_or_create_faiss_index(+ self.collection_id)- return []- # Load and search the FAISS index for this collection- vector_store = rag_service.load_or_create_faiss_index(- self.collection_id- )+ docs_with_scores = vector_store.similarity_search_with_score(+ query, k=limit+ )- docs_with_scores = vector_store.similarity_search_with_score(- query, k=limit- )+ if not docs_with_scores:+ logger.info(+ f"No results found in collection '{self.collection_name}'"+ )+ return []- if not docs_with_scores:- logger.info(- f"No results found in collection '{self.collection_name}'"- )- return []+ # Convert to search result format+ results = []+ for doc, score in docs_with_scores:+ metadata = doc.metadata or {}- # Convert to search result format- results = []- for doc, score in docs_with_scores:- metadata = doc.metadata or {}+ # Get document ID+ doc_id = metadata.get("source_id") or metadata.get(+ "document_id"+ )- # Get document ID- doc_id = metadata.get("source_id") or metadata.get(- "document_id"- )+ # Get title+ title = (+ metadata.get("document_title")+ or metadata.get("title")+ or (f"Document {doc_id}" if doc_id else "Untitled")+ )- # Get title- title = (- metadata.get("document_title")- or metadata.get("title")- or (f"Document {doc_id}" if doc_id else "Untitled")- )+ # Create snippet from content+ snippet = (+ doc.page_content[:500] + "..."+ if len(doc.page_content) > 500+ else doc.page_content+ )- # Create snippet from content- snippet = (- doc.page_content[:500] + "..."- if len(doc.page_content) > 500- else doc.page_content- )+ # Generate document URL+ document_url = self._get_document_url(doc_id)- # Generate document URL- document_url = self._get_document_url(doc_id)-- # Add collection info to metadata- metadata["collection_id"] = self.collection_id- metadata["collection_name"] = self.collection_name-- result = {- "title": title,- "snippet": snippet,- "url": document_url,- "link": document_url,- "source": "library",- "relevance_score": float(1 / (1 + score)),- "metadata": metadata,- }- results.append(result)-- logger.info(- f"Collection '{self.collection_name}' search returned "- f"{len(results)} results for query: {query[:50]}..."- )+ # Add collection info to metadata+ metadata["collection_id"] = self.collection_id+ metadata["collection_name"] = self.collection_name++ result = {+ "title": title,+ "snippet": snippet,+ "url": document_url,+ "link": document_url,+ "source": "library",+ "relevance_score": float(1 / (1 + score)),+ "metadata": metadata,+ }+ results.append(result)++ logger.info(+ f"Collection '{self.collection_name}' search returned "+ f"{len(results)} results for query: {query[:50]}..."+ )- return results+ return resultsexcept Exception:logger.exception(diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_library.py b/src/local_deep_research/web_search_engines/engines/search_engine_library.pyindex f0f2b8c37e..4f5babc85c 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_library.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_library.py@@ -151,43 +151,42 @@ class LibraryRAGSearchEngine(BaseSearchEngine):)# Create RAG service with the collection's embedding settings- rag_service = LibraryRAGService(+ with LibraryRAGService(username=self.username,embedding_model=embedding_model,embedding_provider=embedding_provider,chunk_size=chunk_size,chunk_overlap=chunk_overlap,- )+ ) as rag_service:+ # Get RAG stats to check if there are any indexed documents+ stats = rag_service.get_rag_stats(collection_id)+ if stats.get("indexed_documents", 0) == 0:+ logger.debug(+ f"No documents indexed in collection {collection_id}"+ )+ continue- # Get RAG stats to check if there are any indexed documents- stats = rag_service.get_rag_stats(collection_id)- if stats.get("indexed_documents", 0) == 0:- logger.debug(- f"No documents indexed in collection {collection_id}"+ # Load the FAISS index for this collection+ vector_store = rag_service.load_or_create_faiss_index(+ collection_id)- continue- # Load the FAISS index for this collection- vector_store = rag_service.load_or_create_faiss_index(- collection_id- )-- # Search this collection's index- docs_with_scores = (- vector_store.similarity_search_with_score(- query, k=limit+ # Search this collection's index+ docs_with_scores = (+ vector_store.similarity_search_with_score(+ query, k=limit+ ))- )- # Add collection info to metadata and append to results- for doc, score in docs_with_scores:- if not doc.metadata:- doc.metadata = {}- doc.metadata["collection_id"] = collection_id- doc.metadata["collection_name"] = collection.get(- "name", "Unknown"- )- all_docs_with_scores.append((doc, score))+ # Add collection info to metadata and append to results+ for doc, score in docs_with_scores:+ if not doc.metadata:+ doc.metadata = {}+ doc.metadata["collection_id"] = collection_id+ doc.metadata["collection_name"] = collection.get(+ "name", "Unknown"+ )+ all_docs_with_scores.append((doc, score))except Exception as e:logger.warning(diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_local.py b/src/local_deep_research/web_search_engines/engines/search_engine_local.pyindex 081ecb57a8..657f56463c 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_local.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_local.py@@ -166,6 +166,29 @@ class LocalEmbeddingManager:# Vector store cacheself.vector_stores = {}+ # Track if this manager has been closed+ self._closed = False++ def close(self):+ """Release embedding model resources."""+ if self._closed:+ return+ self._closed = True+ # Clear embedding model reference to allow garbage collection+ self._embeddings = None+ # Clear vector store cache+ self.vector_stores.clear()+ logger.debug("LocalEmbeddingManager closed")++ def __enter__(self):+ """Context manager entry."""+ return self++ def __exit__(self, exc_type, exc_val, exc_tb):+ """Context manager exit - ensures resources are released."""+ self.close()+ return False+@propertydef embeddings(self):"""diff --git a/tests/library/test_auto_indexing.py b/tests/library/test_auto_indexing.pyindex 5f4b42ab63..3884e643e7 100644--- a/tests/library/test_auto_indexing.py+++ b/tests/library/test_auto_indexing.py@@ -553,7 +553,11 @@ class TestAutoIndexDocumentsWorker:) as mock_get_service:mock_rag_service = MagicMock()mock_rag_service.index_document.return_value = {"status": "success"}- mock_get_service.return_value = mock_rag_service+ # Configure context manager behavior+ mock_get_service.return_value.__enter__.return_value = (+ mock_rag_service+ )+ mock_get_service.return_value.__exit__.return_value = None_auto_index_documents_worker(document_ids=["doc1", "doc2", "doc3"],@@ -590,7 +594,11 @@ class TestAutoIndexDocumentsWorker:{"status": "skipped"},{"status": "success"},]- mock_get_service.return_value = mock_rag_service+ # Configure context manager behavior+ mock_get_service.return_value.__enter__.return_value = (+ mock_rag_service+ )+ mock_get_service.return_value.__exit__.return_value = None# Should not raise_auto_index_documents_worker(@@ -616,7 +624,11 @@ class TestAutoIndexDocumentsWorker:mock_rag_service.index_document.side_effect = Exception("Index failed")- mock_get_service.return_value = mock_rag_service+ # Configure context manager behavior+ mock_get_service.return_value.__enter__.return_value = (+ mock_rag_service+ )+ mock_get_service.return_value.__exit__.return_value = None# Should not raise, even with exception_auto_index_documents_worker(@@ -642,7 +654,11 @@ class TestAutoIndexDocumentsWorker:Exception("Index failed"),{"status": "success"},]- mock_get_service.return_value = mock_rag_service+ # Configure context manager behavior+ mock_get_service.return_value.__enter__.return_value = (+ mock_rag_service+ )+ mock_get_service.return_value.__exit__.return_value = None# Should not raise_auto_index_documents_worker(@@ -666,7 +682,11 @@ class TestAutoIndexDocumentsWorker:) as mock_get_service:mock_rag_service = MagicMock()mock_rag_service.index_document.return_value = {"status": "success"}- mock_get_service.return_value = mock_rag_service+ # Configure context manager behavior+ mock_get_service.return_value.__enter__.return_value = (+ mock_rag_service+ )+ mock_get_service.return_value.__exit__.return_value = None_auto_index_documents_worker(document_ids=["doc1"],@@ -689,7 +709,11 @@ class TestAutoIndexDocumentsWorker:"local_deep_research.research_library.routes.rag_routes._get_rag_service_for_thread") as mock_get_service:mock_rag_service = MagicMock()- mock_get_service.return_value = mock_rag_service+ # Configure context manager behavior+ mock_get_service.return_value.__enter__.return_value = (+ mock_rag_service+ )+ mock_get_service.return_value.__exit__.return_value = None# Should not raise with empty list_auto_index_documents_worker(@@ -762,7 +786,11 @@ class TestAutoIndexIntegration:with patch("local_deep_research.research_library.routes.rag_routes._get_rag_service_for_thread") as mock_get_service:- mock_get_service.return_value = mock_rag_service+ # Configure context manager behavior+ mock_get_service.return_value.__enter__.return_value = (+ mock_rag_service+ )+ mock_get_service.return_value.__exit__.return_value = Nonetrigger_auto_index(document_ids=["doc1"],@@ -817,7 +845,11 @@ class TestAutoIndexIntegration:with patch("local_deep_research.research_library.routes.rag_routes._get_rag_service_for_thread") as mock_get_service:- mock_get_service.return_value = mock_rag_service+ # Configure context manager behavior+ mock_get_service.return_value.__enter__.return_value = (+ mock_rag_service+ )+ mock_get_service.return_value.__exit__.return_value = None# Trigger multiple times concurrentlyfor i in range(expected_count):diff --git a/tests/web_search_engines/engines/test_search_engine_collection.py b/tests/web_search_engines/engines/test_search_engine_collection.pyindex 8934adf9aa..5c37a64e67 100644--- a/tests/web_search_engines/engines/test_search_engine_collection.py+++ b/tests/web_search_engines/engines/test_search_engine_collection.py@@ -311,9 +311,17 @@ class TestSearch:with patch("local_deep_research.web_search_engines.engines.search_engine_collection.LibraryRAGService") as mock_rag_service:- mock_rag_service.return_value.get_rag_stats.return_value = {+ # Set up mock RAG service instance for context manager+ mock_rag_instance = Mock()+ mock_rag_instance.get_rag_stats.return_value = {"indexed_documents": 0}+ mock_rag_service.return_value.__enter__.return_value = (+ mock_rag_instance+ )+ mock_rag_service.return_value.__exit__.return_value = (+ None+ )engine = CollectionSearchEngine(collection_id="abc123",@@ -363,14 +371,22 @@ class TestSearch:with patch("local_deep_research.web_search_engines.engines.search_engine_collection.LibraryRAGService") as mock_rag_service:- mock_rag_service.return_value.get_rag_stats.return_value = {+ # Set up mock RAG service instance for context manager+ mock_rag_instance = Mock()+ mock_rag_instance.get_rag_stats.return_value = {"indexed_documents": 1}mock_vector_store = Mock()mock_vector_store.similarity_search_with_score.return_value = [(mock_doc, 0.5)]- mock_rag_service.return_value.load_or_create_faiss_index.return_value = mock_vector_store+ mock_rag_instance.load_or_create_faiss_index.return_value = mock_vector_store+ mock_rag_service.return_value.__enter__.return_value = (+ mock_rag_instance+ )+ mock_rag_service.return_value.__exit__.return_value = (+ None+ )with patch.object(CollectionSearchEngine,@@ -421,12 +437,20 @@ class TestSearch:with patch("local_deep_research.web_search_engines.engines.search_engine_collection.LibraryRAGService") as mock_rag_service:- mock_rag_service.return_value.get_rag_stats.return_value = {+ # Set up mock RAG service instance for context manager+ mock_rag_instance = Mock()+ mock_rag_instance.get_rag_stats.return_value = {"indexed_documents": 1}mock_vector_store = Mock()mock_vector_store.similarity_search_with_score.return_value = []- mock_rag_service.return_value.load_or_create_faiss_index.return_value = mock_vector_store+ mock_rag_instance.load_or_create_faiss_index.return_value = mock_vector_store+ mock_rag_service.return_value.__enter__.return_value = (+ mock_rag_instance+ )+ mock_rag_service.return_value.__exit__.return_value = (+ None+ )engine = CollectionSearchEngine(collection_id="abc123",diff --git a/tests/web_search_engines/engines/test_search_engine_library.py b/tests/web_search_engines/engines/test_search_engine_library.pyindex cfaec0b9b7..2ae349ec20 100644--- a/tests/web_search_engines/engines/test_search_engine_library.py+++ b/tests/web_search_engines/engines/test_search_engine_library.py@@ -193,14 +193,19 @@ class TestSearch:with patch("local_deep_research.web_search_engines.engines.search_engine_library.LibraryRAGService") as mock_rag_service:- mock_rag_service.return_value.get_rag_stats.return_value = {+ # Set up mock RAG service instance for context manager+ mock_rag_instance = Mock()+ mock_rag_instance.get_rag_stats.return_value = {"indexed_documents": 1}mock_vector_store = Mock()mock_vector_store.similarity_search_with_score.return_value = [(mock_doc, 0.5)]- mock_rag_service.return_value.load_or_create_faiss_index.return_value = mock_vector_store+ mock_rag_instance.load_or_create_faiss_index.return_value = mock_vector_store+ # Configure context manager behavior+ mock_rag_service.return_value.__enter__.return_value = mock_rag_instance+ mock_rag_service.return_value.__exit__.return_value = Noneengine = LibraryRAGSearchEngine(settings_snapshot=settings