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.

fix: Use context managers for SQLAlchemy session management (issue #592) (#622)

LearningCircuitf8b3a337cddd
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 205ed5d5a0..d1b9bf45a1 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -65,3 +65,9 @@ repos:
language: script
files: \.py$
description: "Ensure all SQLAlchemy DateTime columns have timezone=True"
+ - id: check-session-context-manager
+ name: Check for try/finally session patterns
+ entry: .pre-commit-hooks/check-session-context-manager.py
+ language: script
+ files: \.py$
+ description: "Ensure SQLAlchemy sessions use context managers instead of try/finally blocks"
diff --git a/.pre-commit-hooks/check-session-context-manager.py b/.pre-commit-hooks/check-session-context-manager.py
new file mode 100755
index 0000000000..75f1c46a6e
--- /dev/null
+++ b/.pre-commit-hooks/check-session-context-manager.py
@@ -0,0 +1,188 @@
+#!/usr/bin/env python3
+"""
+Pre-commit hook to detect try/finally session patterns and suggest context managers.
+
+This hook checks for SQLAlchemy session management patterns that use try/finally
+blocks and suggests replacing them with context managers for better resource
+management and cleaner code.
+"""
+
+import ast
+import sys
+from pathlib import Path
+from typing import List, Tuple
+
+
+class SessionPatternChecker(ast.NodeVisitor):
+ """AST visitor to detect try/finally session patterns."""
+
+ def __init__(self, filename: str):
+ self.filename = filename
+ self.issues: List[Tuple[int, str]] = []
+ self.functions_and_methods = []
+
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
+ """Visit function definitions to check for session patterns."""
+ self._check_function_for_pattern(node)
+ self.generic_visit(node)
+
+ def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
+ """Visit async function definitions to check for session patterns."""
+ self._check_function_for_pattern(node)
+ self.generic_visit(node)
+
+ def _check_function_for_pattern(self, func_node) -> None:
+ """Check a function body for try/finally session patterns."""
+ # Look for session = Session() followed by try/finally
+ for i, stmt in enumerate(func_node.body):
+ # Check if this is a session assignment
+ if isinstance(stmt, ast.Assign):
+ session_var = self._get_session_var_from_assign(stmt)
+ if session_var:
+ # Look for a try/finally block that follows
+ for next_stmt in func_node.body[
+ i + 1 : i + 3
+ ]: # Check next 2 statements
+ if (
+ isinstance(next_stmt, ast.Try)
+ and next_stmt.finalbody
+ ):
+ # Check if finally has session.close()
+ if self._has_session_close_in_finally(
+ next_stmt.finalbody, session_var
+ ):
+ self.issues.append(
+ (
+ stmt.lineno,
+ f"Found try/finally session pattern. Consider using 'with self.Session() as {session_var}:' instead",
+ )
+ )
+ break
+
+ def _get_session_var_from_assign(self, assign_node: ast.Assign) -> str:
+ """Check if an assignment is creating a session and return the variable name."""
+ if isinstance(assign_node.value, ast.Call) and self._is_session_call(
+ assign_node.value
+ ):
+ if assign_node.targets and isinstance(
+ assign_node.targets[0], ast.Name
+ ):
+ return assign_node.targets[0].id
+ return None
+
+ def _is_session_call(self, call_node: ast.Call) -> bool:
+ """Check if a call node is creating a SQLAlchemy session."""
+ # Check for self.Session() pattern
+ if isinstance(call_node.func, ast.Attribute):
+ if call_node.func.attr in (
+ "Session",
+ "get_session",
+ "create_session",
+ ):
+ return True
+ # Check for Session() pattern
+ elif isinstance(call_node.func, ast.Name):
+ if call_node.func.id in (
+ "Session",
+ "get_session",
+ "create_session",
+ ):
+ return True
+ return False
+
+ def _has_session_close_in_finally(
+ self, finalbody: List[ast.stmt], session_var: str
+ ) -> bool:
+ """Check if finally block contains session.close()."""
+ for stmt in finalbody:
+ if isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Call):
+ # Check for session.close() pattern
+ if (
+ isinstance(stmt.value.func, ast.Attribute)
+ and stmt.value.func.attr == "close"
+ ):
+ # Check if it's our session variable
+ if (
+ isinstance(stmt.value.func.value, ast.Name)
+ and stmt.value.func.value.id == session_var
+ ):
+ return True
+ return False
+
+
+def check_file(filepath: Path) -> List[Tuple[str, int, str]]:
+ """Check a single Python file for try/finally session patterns."""
+ issues = []
+
+ try:
+ content = filepath.read_text()
+ tree = ast.parse(content, filename=str(filepath))
+
+ checker = SessionPatternChecker(str(filepath))
+ checker.visit(tree)
+
+ for line_no, message in checker.issues:
+ issues.append((str(filepath), line_no, message))
+
+ except SyntaxError as e:
+ # Skip files with syntax errors
+ print(f"Syntax error in {filepath}: {e}", file=sys.stderr)
+ except Exception as e:
+ print(f"Error checking {filepath}: {e}", file=sys.stderr)
+
+ return issues
+
+
+def main():
+ """Main entry point for the pre-commit hook."""
+ # Get list of files to check from command line arguments
+ files_to_check = sys.argv[1:] if len(sys.argv) > 1 else []
+
+ if not files_to_check:
+ print("No files to check")
+ return 0
+
+ all_issues = []
+
+ for filepath_str in files_to_check:
+ filepath = Path(filepath_str)
+
+ # Skip non-Python files
+ if not filepath.suffix == ".py":
+ continue
+
+ # Skip test files and migration files
+ if "test" in filepath.parts or "migration" in filepath.parts:
+ continue
+
+ issues = check_file(filepath)
+ all_issues.extend(issues)
+
+ # Report issues
+ if all_issues:
+ print(
+ "\n❌ Found try/finally session patterns that should use context managers:\n"
+ )
+ for filepath, line_no, message in all_issues:
+ print(f" {filepath}:{line_no}: {message}")
+
+ print("\n💡 Tip: Replace try/finally blocks with context managers:")
+ print(" Before:")
+ print(" session = self.Session()")
+ print(" try:")
+ print(" # operations")
+ print(" session.commit()")
+ print(" finally:")
+ print(" session.close()")
+ print("\n After:")
+ print(" with self.Session() as session:")
+ print(" # operations")
+ print(" session.commit()")
+ print("\n")
+ return 1
+
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/src/local_deep_research/utilities/search_cache.py b/src/local_deep_research/utilities/search_cache.py
index 771e0b789e..88d31eec32 100644
--- a/src/local_deep_research/utilities/search_cache.py
+++ b/src/local_deep_research/utilities/search_cache.py
@@ -91,8 +91,7 @@ class SearchCache:
"""Remove expired entries from database."""
try:
current_time = int(time.time())
- session = self.Session()
- try:
+ with self.Session() as session:
deleted = (
session.query(SearchCacheModel)
.filter(SearchCacheModel.expires_at < current_time)
@@ -101,8 +100,6 @@ class SearchCache:
session.commit()
if deleted > 0:
logger.debug(f"Cleaned up {deleted} expired cache entries")
- finally:
- session.close()
except Exception:
logger.exception("Failed to cleanup expired cache entries")
@@ -151,8 +148,7 @@ class SearchCache:
# Check database cache
try:
- session = self.Session()
- try:
+ with self.Session() as session:
cache_entry = (
session.query(SearchCacheModel)
.filter(
@@ -182,8 +178,6 @@ class SearchCache:
f"Cache hit (database) for query: {query[:50]}..."
)
return results
- finally:
- session.close()
except Exception:
logger.exception("Failed to retrieve from search cache")
@@ -219,8 +213,7 @@ class SearchCache:
try:
# Store in database
- session = self.Session()
- try:
+ with self.Session() as session:
# Check if entry exists
existing = (
session.query(SearchCacheModel)
@@ -250,8 +243,6 @@ class SearchCache:
session.add(cache_entry)
session.commit()
- finally:
- session.close()
# Store in memory cache
self._memory_cache[query_hash] = {
@@ -278,16 +269,13 @@ class SearchCache:
self._access_times.pop(query_hash, None)
# Remove from database
- session = self.Session()
- try:
+ with self.Session() as session:
deleted = (
session.query(SearchCacheModel)
.filter_by(query_hash=query_hash)
.delete()
)
session.commit()
- finally:
- session.close()
logger.debug(f"Invalidated cache for query: {query[:50]}...")
return deleted > 0
@@ -302,12 +290,9 @@ class SearchCache:
self._memory_cache.clear()
self._access_times.clear()
- session = self.Session()
- try:
+ with self.Session() as session:
session.query(SearchCacheModel).delete()
session.commit()
- finally:
- session.close()
logger.info("Cleared all search cache")
return True
@@ -320,8 +305,7 @@ class SearchCache:
"""Get cache statistics."""
try:
current_time = int(time.time())
- session = self.Session()
- try:
+ with self.Session() as session:
# Total entries
total_entries = (
session.query(SearchCacheModel)
@@ -345,20 +329,18 @@ class SearchCache:
.scalar()
)
avg_access = avg_access_result or 0
- finally:
- session.close()
-
- return {
- "total_valid_entries": total_entries,
- "expired_entries": expired_entries,
- "memory_cache_size": len(self._memory_cache),
- "average_access_count": round(avg_access, 2),
- "cache_hit_potential": (
- f"{(total_entries / (total_entries + 1)) * 100:.1f}%"
- if total_entries > 0
- else "0%"
- ),
- }
+
+ return {
+ "total_valid_entries": total_entries,
+ "expired_entries": expired_entries,
+ "memory_cache_size": len(self._memory_cache),
+ "average_access_count": round(avg_access, 2),
+ "cache_hit_potential": (
+ f"{(total_entries / (total_entries + 1)) * 100:.1f}%"
+ if total_entries > 0
+ else "0%"
+ ),
+ }
except Exception as e:
logger.exception("Failed to get cache stats")
diff --git a/tests/api_tests/fix_search_engines.py b/tests/api_tests/fix_search_engines.py
index fbd7496f5b..0b026fd345 100644
--- a/tests/api_tests/fix_search_engines.py
+++ b/tests/api_tests/fix_search_engines.py
@@ -28,50 +28,53 @@ def fix_search_engines_for_user(username: str, password: str):
return False
# Get database session
- db_session = db_manager.get_session(username)
- if not db_session:
- logger.error("Failed to get database session")
+ Session = db_manager.Session
+ if not Session:
+ logger.error("Failed to get database session factory")
return False
- try:
- # Create settings manager
- settings_manager = SettingsManager(db_session)
-
- # Check if we need to load defaults
- from src.local_deep_research.database.models import Setting
-
- search_engine_count = (
- db_session.query(Setting)
- .filter(Setting.key.like("search.engine.%.display_name"))
- .count()
- )
-
- if search_engine_count == 0:
- logger.info("No search engine settings found. Loading defaults...")
- settings_manager.load_from_defaults_file(commit=True)
- logger.info("Default settings loaded successfully")
- else:
- logger.info(f"Found {search_engine_count} search engine settings")
-
- # Verify settings were loaded
- search_engines = (
- db_session.query(Setting)
- .filter(Setting.key.like("search.engine.%.display_name"))
- .all()
- )
-
- logger.info(f"Search engines after fix: {len(search_engines)}")
- for engine in search_engines[:5]: # Show first 5
- logger.info(f" - {engine.key}: {engine.value}")
-
- return True
-
- except Exception:
- logger.exception("Failed to fix search engines")
- db_session.rollback()
- return False
- finally:
- db_session.close()
+ with Session() as db_session:
+ try:
+ # Create settings manager
+ settings_manager = SettingsManager(db_session)
+
+ # Check if we need to load defaults
+ from src.local_deep_research.database.models import Setting
+
+ search_engine_count = (
+ db_session.query(Setting)
+ .filter(Setting.key.like("search.engine.%.display_name"))
+ .count()
+ )
+
+ if search_engine_count == 0:
+ logger.info(
+ "No search engine settings found. Loading defaults..."
+ )
+ settings_manager.load_from_defaults_file(commit=True)
+ logger.info("Default settings loaded successfully")
+ else:
+ logger.info(
+ f"Found {search_engine_count} search engine settings"
+ )
+
+ # Verify settings were loaded
+ search_engines = (
+ db_session.query(Setting)
+ .filter(Setting.key.like("search.engine.%.display_name"))
+ .all()
+ )
+
+ logger.info(f"Search engines after fix: {len(search_engines)}")
+ for engine in search_engines[:5]: # Show first 5
+ logger.info(f" - {engine.key}: {engine.value}")
+
+ return True
+
+ except Exception:
+ logger.exception("Failed to fix search engines")
+ db_session.rollback()
+ return False
if __name__ == "__main__":
diff --git a/tests/ui_tests/test_direct_uuid_insert.py b/tests/ui_tests/test_direct_uuid_insert.py
index e3e94eaf06..20231bc7cc 100644
--- a/tests/ui_tests/test_direct_uuid_insert.py
+++ b/tests/ui_tests/test_direct_uuid_insert.py
@@ -60,59 +60,59 @@ def test_direct_uuid_insertion():
for col in columns:
print(f" {col['name']}: {col['type']}")
- # Get session
- session = db_manager.get_session(username)
-
- try:
- # Create a new research with UUID
- research_id = str(uuid.uuid4())
- print(f"\nCreating research with UUID: {research_id}")
-
- research = ResearchHistory(
- id=research_id,
- query="Direct UUID test",
- mode="quick",
- status="in_progress",
- created_at=datetime.utcnow().isoformat(),
- progress_log=[
- {"time": datetime.utcnow().isoformat(), "progress": 0}
- ],
- research_meta={"test": "direct_uuid"},
- )
-
- session.add(research)
- session.commit()
-
- print("✅ Successfully created research with UUID!")
-
- # Verify it was saved
- saved_research = (
- session.query(ResearchHistory).filter_by(id=research_id).first()
- )
- if saved_research:
- print("\nVerified in database:")
- print(f" ID: {saved_research.id}")
- print(f" Type: {type(saved_research.id).__name__}")
- print(f" Query: {saved_research.query}")
-
- # List all research entries
- all_research = session.query(ResearchHistory).all()
- print(f"\nTotal research entries: {len(all_research)}")
- for r in all_research:
- print(f" - {r.id} ({type(r.id).__name__}): {r.query}")
-
- return True
-
- except Exception as e:
- print(f"❌ Error creating research: {e}")
- import traceback
-
- traceback.print_exc()
- session.rollback()
- return False
- finally:
- session.close()
- db_manager.close_user_database(username)
+ # Get session factory
+ Session = db_manager.Session
+
+ with Session() as session:
+ try:
+ # Create a new research with UUID
+ research_id = str(uuid.uuid4())
+ print(f"\nCreating research with UUID: {research_id}")
+
+ research = ResearchHistory(
+ id=research_id,
+ query="Direct UUID test",
+ mode="quick",
+ status="in_progress",
+ created_at=datetime.utcnow().isoformat(),
+ progress_log=[
+ {"time": datetime.utcnow().isoformat(), "progress": 0}
+ ],
+ research_meta={"test": "direct_uuid"},
+ )
+
+ session.add(research)
+ session.commit()
+
+ print("✅ Successfully created research with UUID!")
+
+ # Verify it was saved
+ saved_research = (
+ session.query(ResearchHistory).filter_by(id=research_id).first()
+ )
+ if saved_research:
+ print("\nVerified in database:")
+ print(f" ID: {saved_research.id}")
+ print(f" Type: {type(saved_research.id).__name__}")
+ print(f" Query: {saved_research.query}")
+
+ # List all research entries
+ all_research = session.query(ResearchHistory).all()
+ print(f"\nTotal research entries: {len(all_research)}")
+ for r in all_research:
+ print(f" - {r.id} ({type(r.id).__name__}): {r.query}")
+
+ return True
+
+ except Exception as e:
+ print(f"❌ Error creating research: {e}")
+ import traceback
+
+ traceback.print_exc()
+ session.rollback()
+ return False
+
+ db_manager.close_user_database(username)
if __name__ == "__main__":