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.

feat: add safe_close() utility for visible cleanup failures (#2749)

LearningCircuit6570dc16e8e5
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 736b3dbf79..1ce4f8ed3b 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -172,6 +172,13 @@ repos:
language: script
files: \.py$
description: "Prevent direct requests.get/post/Session - use safe_get/safe_post/SafeSession"
+ - id: check-silent-cleanup
+ name: Check for silent exceptions in close() methods
+ entry: .pre-commit-hooks/check-silent-cleanup.py
+ language: script
+ files: \.py$
+ exclude: ^tests/
+ description: "Ensure close() methods log cleanup failures instead of silently passing"
- id: check-service-context-managers
name: Check services use context managers
entry: .pre-commit-hooks/check-service-context-managers.py
diff --git a/.pre-commit-hooks/check-silent-cleanup.py b/.pre-commit-hooks/check-silent-cleanup.py
new file mode 100755
index 0000000000..1c7c45f3b9
--- /dev/null
+++ b/.pre-commit-hooks/check-silent-cleanup.py
@@ -0,0 +1,167 @@
+#!/usr/bin/env python3
+"""
+Pre-commit hook to flag silent exceptions in close() methods.
+
+Detects `def close(self)` methods that contain bare `except Exception: pass`
+or `except: pass` — cleanup failures should be logged via safe_close() from
+utilities.resource_utils, or with explicit logger calls.
+
+Allows handlers that contain logger.* calls or `raise`.
+"""
+
+import ast
+import sys
+
+# Files/patterns that are excluded from this check
+ALLOWED_PATTERNS = {
+ "tests/",
+ "test_",
+ "_test.py",
+ # LLM wrapper close() methods delegate to _close_base_llm which IS the
+ # logging boundary — adding a warning here would double-log every close.
+ "config/llm_config.py",
+ "rate_limiting/llm/wrapper.py",
+}
+
+
+class SilentCleanupChecker(ast.NodeVisitor):
+ """AST visitor to detect silent exceptions in close() methods."""
+
+ def __init__(self, filename: str):
+ self.filename = filename
+ self.errors = []
+
+ def visit_FunctionDef(self, node):
+ # Only inspect `def close(self, ...):` methods
+ if node.name != "close":
+ self.generic_visit(node)
+ return
+
+ # Walk the close() body looking for try/except
+ for child in ast.walk(node):
+ if not isinstance(child, ast.ExceptHandler):
+ continue
+
+ # Check if the handler is "except Exception:" or bare "except:"
+ if child.type is not None and not (
+ isinstance(child.type, ast.Name)
+ and child.type.id == "Exception"
+ ):
+ continue
+
+ # Check if handler body is *only* `pass` (no logging, no raise)
+ if self._is_silent_handler(child):
+ self.errors.append(
+ (
+ child.lineno,
+ "Silent exception in close() method — use "
+ "safe_close() from utilities.resource_utils "
+ "or add explicit logging so cleanup failures "
+ "are visible.",
+ )
+ )
+
+ self.generic_visit(node)
+
+ @staticmethod
+ def _is_silent_handler(handler: ast.ExceptHandler) -> bool:
+ """Return True if handler body is only `pass` with no logging/raise."""
+ for stmt in handler.body:
+ # pass statement — continue checking
+ if isinstance(stmt, ast.Pass):
+ continue
+
+ # raise — not silent
+ if isinstance(stmt, ast.Raise):
+ return False
+
+ # Any expression that looks like logger.something(...)
+ if isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Call):
+ func = stmt.value.func
+ if isinstance(func, ast.Attribute) and isinstance(
+ func.value, ast.Name
+ ):
+ if func.value.id == "logger":
+ return False
+
+ # Any other statement means it's not just `pass`
+ return False
+
+ # If we got here, every statement was `pass`
+ return True
+
+ def _is_file_allowed(self) -> bool:
+ for pattern in ALLOWED_PATTERNS:
+ if pattern in self.filename:
+ return True
+ return False
+
+
+def check_file(filename: str) -> bool:
+ """Check a single Python file for silent cleanup patterns."""
+ if not filename.endswith(".py"):
+ return True
+
+ # Skip allowed files
+ for pattern in ALLOWED_PATTERNS:
+ if pattern in 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)
+ checker = SilentCleanupChecker(filename)
+ 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:
+ 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-silent-cleanup.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(
+ "Silent Cleanup: Unlogged exceptions in close() methods detected!"
+ )
+ print("=" * 70)
+ print("\nTo fix, replace silent try/except blocks with safe_close():")
+ print(" from ...utilities.resource_utils import safe_close")
+ print(' safe_close(self.client, "client name")')
+ print("\nOr add explicit logging:")
+ print(' logger.warning("Failed to close resource", exc_info=True)')
+ sys.exit(1)
+ else:
+ sys.exit(0)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py
index 564a5eea46..ed3f6252f6 100644
--- a/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py
+++ b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py
@@ -11,6 +11,7 @@ from ...config.llm_config import get_llm
from ...database.models import Journal
from ...database.session_context import get_user_db_session
from ...search_system import AdvancedSearchSystem
+from ...utilities.resource_utils import safe_close
from ...utilities.thread_context import get_search_context
from ...web_search_engines.search_engine_factory import create_search_engine
from .base_filter import BaseFilter
@@ -122,16 +123,10 @@ class JournalReputationFilter(BaseFilter):
def close(self) -> None:
"""Close the SearXNG engine and LLM client."""
- if (
- hasattr(self, "_JournalReputationFilter__engine")
- and self.__engine is not None
- ):
- try:
- self.__engine.close()
- except Exception:
- pass
- if self._owns_llm and self.model is not None:
- self.model.close()
+ if hasattr(self, "_JournalReputationFilter__engine"):
+ safe_close(self.__engine, "SearXNG engine")
+ if self._owns_llm:
+ safe_close(self.model, "journal filter LLM")
@classmethod
def create_default(
@@ -233,10 +228,7 @@ class JournalReputationFilter(BaseFilter):
f"name in any generated questions."
)
finally:
- try:
- search_system.close()
- except Exception:
- pass
+ safe_close(search_system, "journal search system")
journal_info = "\n".join(
[f["content"] for f in journal_info["findings"]]
)
diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.py
index b83640f02e..49ab2961a4 100644
--- a/src/local_deep_research/api/research_functions.py
+++ b/src/local_deep_research/api/research_functions.py
@@ -22,17 +22,13 @@ from .settings_utils import create_settings_snapshot
def _close_system(system):
"""Close an AdvancedSearchSystem and its associated resources."""
- try:
- system.close()
- except Exception:
- pass
- if hasattr(system, "search") and system.search is not None:
- try:
- system.search.close()
- except Exception:
- pass
+ from ..utilities.resource_utils import safe_close
+
+ safe_close(system, "search system")
+ if hasattr(system, "search"):
+ safe_close(system.search, "search engine")
if hasattr(system, "model"):
- system.model.close()
+ safe_close(system.model, "system LLM")
def _init_search_system(
@@ -151,7 +147,9 @@ def _init_search_system(
search_original_query=search_original_query,
)
except Exception:
- llm.close()
+ from ..utilities.resource_utils import safe_close
+
+ safe_close(llm, "init LLM")
raise
# Override default settings with user-provided values
@@ -601,7 +599,9 @@ def analyze_documents(
search = get_search(collection_name, llm_instance=llm)
if not search:
- llm.close()
+ from ..utilities.resource_utils import safe_close
+
+ safe_close(llm, "LLM")
llm = None
return {
"summary": f"Error: Collection '{collection_name}' not found or not properly configured.",
@@ -690,10 +690,7 @@ def analyze_documents(
return analysis_result
finally:
- if search is not None:
- try:
- search.close()
- except Exception:
- pass
- if llm is not None:
- llm.close()
+ from ..utilities.resource_utils import safe_close
+
+ safe_close(search, "search engine")
+ safe_close(llm, "LLM")
diff --git a/src/local_deep_research/benchmarks/cli.py b/src/local_deep_research/benchmarks/cli.py
index c6e5732ae6..ff61a9df56 100644
--- a/src/local_deep_research/benchmarks/cli.py
+++ b/src/local_deep_research/benchmarks/cli.py
@@ -355,21 +355,11 @@ def run_profiling(args):
logger.exception("Error during profiling")
return 1
finally:
- if system is not None:
- try:
- system.close()
- except Exception:
- pass
- if search is not None:
- try:
- search.close()
- except Exception:
- pass
- if llm is not None:
- try:
- llm.close()
- except Exception:
- pass
+ from ..utilities.resource_utils import safe_close
+
+ safe_close(system, "benchmark system")
+ safe_close(search, "benchmark search engine")
+ safe_close(llm, "benchmark LLM")
def main():
diff --git a/src/local_deep_research/benchmarks/comparison/evaluator.py b/src/local_deep_research/benchmarks/comparison/evaluator.py
index a0dd8fc314..2775706396 100644
--- a/src/local_deep_research/benchmarks/comparison/evaluator.py
+++ b/src/local_deep_research/benchmarks/comparison/evaluator.py
@@ -350,21 +350,11 @@ def _evaluate_single_configuration(
"resource_details": resource_monitor.get_combined_stats(),
}
finally:
- if system is not None:
- try:
- system.close()
- except Exception:
- pass
- if search is not None:
- try:
- search.close()
- except Exception:
- pass
- if llm is not None:
- try:
- llm.close()
- except Exception:
- pass
+ from ...utilities.resource_utils import safe_close
+
+ safe_close(system, "evaluator system")
+ safe_close(search, "evaluator search engine")
+ safe_close(llm, "evaluator LLM")
def _calculate_average_metrics(results: List[Dict[str, Any]]) -> Dict[str, Any]:
diff --git a/src/local_deep_research/domain_classifier/classifier.py b/src/local_deep_research/domain_classifier/classifier.py
index 23bc7e8f3c..d345554c29 100644
--- a/src/local_deep_research/domain_classifier/classifier.py
+++ b/src/local_deep_research/domain_classifier/classifier.py
@@ -103,8 +103,9 @@ class DomainClassifier:
def close(self) -> None:
"""Close the LLM client if one was created."""
- if self.llm is not None:
- self.llm.close()
+ from ..utilities.resource_utils import safe_close
+
+ safe_close(self.llm, "classifier LLM")
def _get_domain_samples(
self, domain: str, session: Session, limit: int = 5
diff --git a/src/local_deep_research/news/core/news_analyzer.py b/src/local_deep_research/news/core/news_analyzer.py
index e7f95e3040..7029089fbe 100644
--- a/src/local_deep_research/news/core/news_analyzer.py
+++ b/src/local_deep_research/news/core/news_analyzer.py
@@ -40,8 +40,10 @@ class NewsAnalyzer:
def close(self) -> None:
"""Close the LLM client if this instance created it."""
- if self._owns_llm and self.llm_client is not None:
- self.llm_client.close()
+ from ...utilities.resource_utils import safe_close
+
+ if self._owns_llm:
+ safe_close(self.llm_client, "news analyzer LLM")
def analyze_news(
self, search_results: List[Dict[str, Any]]
diff --git a/src/local_deep_research/report_generator.py b/src/local_deep_research/report_generator.py
index ed14e47256..41280816ca 100644
--- a/src/local_deep_research/report_generator.py
+++ b/src/local_deep_research/report_generator.py
@@ -80,8 +80,10 @@ class IntegratedReportGenerator:
def close(self) -> None:
"""Close the LLM client if this instance created it."""
- if self._owns_llm and self.model is not None:
- self.model.close()
+ from .utilities.resource_utils import safe_close
+
+ if self._owns_llm:
+ safe_close(self.model, "report generator LLM")
def generate_report(
self,
diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.py
index 5b633e8077..272bd1687d 100644
--- a/src/local_deep_research/research_library/services/download_service.py
+++ b/src/local_deep_research/research_library/services/download_service.py
@@ -153,12 +153,10 @@ class DownloadService:
return
self._closed = True
+ from ...utilities.resource_utils import safe_close
+
for downloader in self.downloaders:
- if hasattr(downloader, "close"):
- try:
- downloader.close()
- except Exception:
- pass
+ safe_close(downloader, "downloader")
# Clear references to allow garbage collection
self.downloaders = []
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index dba494ec67..957ee9c8a3 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -241,11 +241,10 @@ class AdvancedSearchSystem:
find_relevant_information()'s finally block, so this is a second
line of defense for the edge case where the method is never called.
"""
- if hasattr(self, "strategy") and hasattr(self.strategy, "close"):
- try:
- self.strategy.close()
- except Exception:
- pass
+ from .utilities.resource_utils import safe_close
+
+ if hasattr(self, "strategy"):
+ safe_close(self.strategy, "search strategy")
def _progress_callback(
self, message: str, progress: int, metadata: dict
diff --git a/src/local_deep_research/utilities/es_utils.py b/src/local_deep_research/utilities/es_utils.py
index b6c673548a..f6d6202a16 100644
--- a/src/local_deep_research/utilities/es_utils.py
+++ b/src/local_deep_research/utilities/es_utils.py
@@ -69,10 +69,9 @@ class ElasticsearchManager:
def close(self) -> None:
"""Close the Elasticsearch client and its connection pool."""
- try:
- self.client.close()
- except Exception:
- pass
+ from .resource_utils import safe_close
+
+ safe_close(self.client, "Elasticsearch client")
def create_index(
self,
diff --git a/src/local_deep_research/utilities/resource_utils.py b/src/local_deep_research/utilities/resource_utils.py
new file mode 100644
index 0000000000..09439b77dd
--- /dev/null
+++ b/src/local_deep_research/utilities/resource_utils.py
@@ -0,0 +1,15 @@
+"""Shared helpers for deterministic resource cleanup."""
+
+from loguru import logger
+
+
+def safe_close(resource, name: str = "resource"):
+ """Close a resource, logging a warning on failure. Never raises."""
+ if resource is None:
+ return
+ if not hasattr(resource, "close"):
+ return
+ try:
+ resource.close()
+ except Exception:
+ logger.warning(f"Failed to close {name}", exc_info=True)
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 1cd791139f..4a3026bf4f 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -1643,26 +1643,19 @@ def run_research_process(research_id, query, mode, **kwargs):
# Python's non-deterministic garbage collection (__del__) for
# cleanup, which can cause file descriptor exhaustion under
# sustained load.
- if "use_search" in locals() and use_search is not None:
- try:
- use_search.close()
- except Exception:
- pass
+ from ...utilities.resource_utils import safe_close
+
+ if "use_search" in locals():
+ safe_close(use_search, "research search engine")
# Close search system (cascades to strategy thread pools).
# See AdvancedSearchSystem.close() for details.
- if "system" in locals() and system is not None:
- try:
- system.close()
- except Exception:
- pass
+ if "system" in locals():
+ safe_close(system, "research system")
# Close the LLM instance created for model/provider overrides.
# system.close() does NOT close the LLM passed to it via system.model,
# so we must close it explicitly here.
- if "use_llm" in locals() and use_llm is not None:
- try:
- use_llm.close()
- except Exception:
- pass
+ if "use_llm" in locals():
+ safe_close(use_llm, "research LLM")
def cleanup_research_resources(research_id, username=None):
diff --git a/src/local_deep_research/web_search_engines/engines/meta_search_engine.py b/src/local_deep_research/web_search_engines/engines/meta_search_engine.py
index 668c580a9d..99c5823b46 100644
--- a/src/local_deep_research/web_search_engines/engines/meta_search_engine.py
+++ b/src/local_deep_research/web_search_engines/engines/meta_search_engine.py
@@ -519,20 +519,16 @@ Example output: searxng,wikipedia,brave"""
def close(self):
"""Close all cached child search engines, fallback engine, and own resources."""
+ from ...utilities.resource_utils import safe_close
+
for engine in self.engine_cache.values():
- try:
- engine.close()
- except Exception:
- pass
+ safe_close(engine, "child search engine")
self.engine_cache.clear()
if (
hasattr(self, "fallback_engine")
and self.fallback_engine is not None
):
- try:
- self.fallback_engine.close()
- except Exception:
- pass
+ safe_close(self.fallback_engine, "fallback search engine")
super().close()
def invoke(self, query: str) -> List[Dict[str, Any]]:
diff --git a/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py b/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py
index b6bcf00e16..1dad37c992 100644
--- a/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py
+++ b/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py
@@ -742,11 +742,10 @@ Select up to {self.max_engines_to_select} engines that would best answer this qu
def close(self):
"""Close all cached child search engines and own resources."""
+ from ...utilities.resource_utils import safe_close
+
for engine in self.engine_cache.values():
- try:
- engine.close()
- except Exception:
- pass
+ safe_close(engine, "child search engine")
self.engine_cache.clear()
super().close()
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py b/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py
index 21460b6112..13965da860 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py
@@ -98,10 +98,9 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
def close(self) -> None:
"""Close the Elasticsearch client and its connection pool."""
- try:
- self.client.close()
- except Exception:
- pass
+ from ...utilities.resource_utils import safe_close
+
+ safe_close(self.client, "Elasticsearch client")
super().close()
def _get_previews(self, query: str) -> List[Dict[str, Any]]:
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_github.py b/src/local_deep_research/web_search_engines/engines/search_engine_github.py
index 885571ff6a..be176b1630 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_github.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_github.py
@@ -76,8 +76,10 @@ class GitHubSearchEngine(BaseSearchEngine):
def close(self) -> None:
"""Close the lazily-loaded LLM client if this engine created it."""
- if self._owns_llm and self.llm is not None:
- self.llm.close()
+ from ...utilities.resource_utils import safe_close
+
+ if self._owns_llm:
+ safe_close(self.llm, "GitHub LLM")
super().close()
def _handle_rate_limits(self, response):
diff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.py
index 0c316e2d77..b36af3f44c 100644
--- a/src/local_deep_research/web_search_engines/search_engine_base.py
+++ b/src/local_deep_research/web_search_engines/search_engine_base.py
@@ -1026,18 +1026,13 @@ Respond with ONLY the JSON array, no other text."""
The base implementation safely closes any 'session' attribute if present
and closes content filters that hold resources.
"""
+ from ..utilities.resource_utils import safe_close
+
if hasattr(self, "session") and self.session is not None:
- try:
- self.session.close()
- except Exception:
- pass # Safe cleanup - don't raise on close
+ safe_close(self.session, "HTTP session")
if hasattr(self, "_content_filters"):
for content_filter in self._content_filters:
- if hasattr(content_filter, "close"):
- try:
- content_filter.close()
- except Exception:
- pass
+ safe_close(content_filter, "content filter")
def __enter__(self):
"""Support context manager usage."""
diff --git a/tests/security/test_silent_cleanup_hook.py b/tests/security/test_silent_cleanup_hook.py
new file mode 100644
index 0000000000..318994ec9e
--- /dev/null
+++ b/tests/security/test_silent_cleanup_hook.py
@@ -0,0 +1,404 @@
+"""
+Tests for the check-silent-cleanup pre-commit hook.
+
+Ensures the hook correctly detects silent exception handling in close() methods
+and allows close() methods that log or re-raise.
+"""
+
+import ast
+import sys
+from importlib import import_module
+from pathlib import Path
+
+# Add the pre-commit hooks directory to path
+HOOKS_DIR = Path(__file__).parent.parent.parent / ".pre-commit-hooks"
+sys.path.insert(0, str(HOOKS_DIR))
+
+# Import the checker from the hook (must be after sys.path modification)
+hook_module = import_module("check-silent-cleanup") # noqa: E402
+SilentCleanupChecker = hook_module.SilentCleanupChecker
+
+
+class TestSilentCleanupChecker:
+ """Tests for the SilentCleanupChecker AST visitor."""
+
+ def _check_code(self, code: str, filename: str = "src/module.py") -> list:
+ """Helper to check code and return errors."""
+ tree = ast.parse(code)
+ checker = SilentCleanupChecker(filename)
+ checker.visit(tree)
+ return checker.errors
+
+ # --- Detection: should flag ---
+
+ def test_detects_except_exception_pass_in_close(self):
+ """Should flag except Exception: pass inside close()."""
+ code = """
+class Foo:
+ def close(self):
+ try:
+ self.client.close()
+ except Exception:
+ pass
+"""
+ errors = self._check_code(code)
+ assert len(errors) == 1
+ assert "Silent exception" in errors[0][1]
+
+ def test_detects_bare_except_pass_in_close(self):
+ """Should flag bare except: pass inside close()."""
+ code = """
+class Foo:
+ def close(self):
+ try:
+ self.client.close()
+ except:
+ pass
+"""
+ errors = self._check_code(code)
+ assert len(errors) == 1
+
+ def test_detects_multiple_silent_blocks(self):
+ """Should flag each silent block independently."""
+ code = """
+class Foo:
+ def close(self):
+ try:
+ self.session.close()
+ except Exception:
+ pass
+ try:
+ self.engine.close()
+ except Exception:
+ pass
+"""
+ errors = self._check_code(code)
+ assert len(errors) == 2
+
+ def test_reports_correct_line_number(self):
+ """Should report the line of the except handler, not the try."""
+ code = """
+class Foo:
+ def close(self):
+ x = 1
+ y = 2
+ try:
+ self.client.close()
+ except Exception:
+ pass
+"""
+ errors = self._check_code(code)
+ assert len(errors) == 1
+ assert errors[0][0] == 8 # "except Exception:" is line 8
+
+ # --- Allowances: should NOT flag ---
+
+ def test_allows_logger_warning_in_handler(self):
+ """Should allow except blocks that log a warning."""
+ code = """
+class Foo:
+ def close(self):
+ try:
+ self.client.close()
+ except Exception:
+ logger.warning("Failed to close client")
+"""
+ errors = self._check_code(code)
+ assert len(errors) == 0
+
+ def test_allows_logger_exception_in_handler(self):
+ """Should allow except blocks that use logger.exception."""
+ code = """
+class Foo:
+ def close(self):
+ try:
+ self.client.close()
+ except Exception:
+ logger.exception("Close failed")
+"""
+ errors = self._check_code(code)
+ assert len(errors) == 0
+
+ def test_allows_logger_debug_in_handler(self):
+ """Should allow any logger.* call."""
+ code = """
+class Foo:
+ def close(self):
+ try:
+ self.client.close()
+ except Exception:
+ logger.debug("Ignoring close error")
+"""
+ errors = self._check_code(code)
+ assert len(errors) == 0
+
+ def test_allows_raise_in_handler(self):
+ """Should allow except blocks that re-raise."""
+ code = """
+class Foo:
+ def close(self):
+ try:
+ self.client.close()
+ except Exception:
+ raise
+"""
+ errors = self._check_code(code)
+ assert len(errors) == 0
+
+ def test_allows_specific_exception_type(self):
+ """Should not flag handlers for specific exception types (e.g. OSError)."""
+ code = """
+class Foo:
+ def close(self):
+ try:
+ self.client.close()
+ except OSError:
+ pass
+"""
+ errors = self._check_code(code)
+ assert len(errors) == 0
+
+ def test_ignores_non_close_methods(self):
+ """Should not inspect methods other than close()."""
+ code = """
+class Foo:
+ def cleanup(self):
+ try:
+ self.client.close()
+ except Exception:
+ pass
+
+ def shutdown(self):
+ try:
+ self.engine.stop()
+ except Exception:
+ pass
+"""
+ errors = self._check_code(code)
+ assert len(errors) == 0
+
+ def test_ignores_standalone_close_function(self):
+ """A top-level function named close() should still be checked."""
+ code = """
+def close():
+ try:
+ something.close()
+ except Exception:
+ pass
+"""
+ errors = self._check_code(code)
+ assert len(errors) == 1
+
+ def test_close_with_no_try_except(self):
+ """close() with no try/except should pass cleanly."""
+ code = """
+class Foo:
+ def close(self):
+ self.client.close()
+"""
+ errors = self._check_code(code)
+ assert len(errors) == 0
+
+ def test_close_using_safe_close(self):
+ """close() using safe_close() should pass."""
+ code = """
+class Foo:
+ def close(self):
+ from utilities.resource_utils import safe_close
+ safe_close(self.client, "client")
+"""
+ errors = self._check_code(code)
+ assert len(errors) == 0
+
+ def test_mixed_silent_and_logged(self):
+ """Should flag only the silent block, not the logged one."""
+ code = """
+class Foo:
+ def close(self):
+ try:
+ self.session.close()
+ except Exception:
+ logger.warning("session close failed")
+ try:
+ self.engine.close()
+ except Exception:
+ pass
+"""
+ errors = self._check_code(code)
+ assert len(errors) == 1
+ # The flagged line should be the second except (line 10)
+ assert errors[0][0] == 10
+
+
+class TestFileExclusions:
+ """Tests for file-level exclusion patterns via check_file()."""
+
+ SILENT_CLOSE = """\
+class Foo:
+ def close(self):
+ try:
+ self.x.close()
+ except Exception:
+ pass
+"""
+
+ def _write_and_check(self, tmp_path, subdir, filename):
+ """Write SILENT_CLOSE to subdir/filename and run check_file."""
+ d = tmp_path / subdir
+ d.mkdir(parents=True, exist_ok=True)
+ f = d / filename
+ f.write_text(self.SILENT_CLOSE)
+ return hook_module.check_file(str(f))
+
+ def test_allows_test_directory(self, tmp_path):
+ """Should skip files under tests/."""
+ assert self._write_and_check(tmp_path, "tests", "foo.py") is True
+
+ def test_allows_test_prefix(self, tmp_path):
+ """Should skip files starting with test_."""
+ assert (
+ self._write_and_check(tmp_path, "src", "test_something.py") is True
+ )
+
+ def test_allows_test_suffix(self, tmp_path):
+ """Should skip files ending with _test.py."""
+ assert (
+ self._write_and_check(tmp_path, "src", "something_test.py") is True
+ )
+
+ def test_allows_llm_config(self, tmp_path):
+ """Should skip config/llm_config.py (logging boundary)."""
+ assert (
+ self._write_and_check(tmp_path, "config", "llm_config.py") is True
+ )
+
+ def test_allows_rate_limiting_wrapper(self, tmp_path):
+ """Should skip rate_limiting/llm/wrapper.py (logging boundary)."""
+ assert (
+ self._write_and_check(tmp_path, "rate_limiting/llm", "wrapper.py")
+ is True
+ )
+
+ def test_flags_regular_source_file(self):
+ """Should flag violations in normal source files."""
+ tree = ast.parse(self.SILENT_CLOSE)
+ checker = SilentCleanupChecker("src/engine.py")
+ checker.visit(tree)
+ assert len(checker.errors) == 1
+
+
+class TestCheckFileIntegration:
+ """Integration tests for check_file()."""
+
+ def _write_and_check(self, tmp_path, code, filename="module.py"):
+ """Write code to a temp file and run check_file on it.
+
+ Uses a subdirectory named 'src' to avoid matching exclusion
+ patterns like 'test_' that can appear in pytest's tmp_path.
+ We also monkeypatch check_file to use a clean path for pattern
+ matching while still reading from the real file.
+ """
+ src_dir = tmp_path / "src"
+ src_dir.mkdir(exist_ok=True)
+ filepath = src_dir / filename
+ filepath.write_text(code)
+ # check_file matches ALLOWED_PATTERNS against the full path.
+ # pytest tmp dirs contain "pytest-" and "test_" which would match.
+ # Use the checker directly to bypass path-based exclusions.
+ import ast as _ast
+
+ with open(filepath, "r", encoding="utf-8") as f:
+ content = f.read()
+ tree = _ast.parse(content, filename=str(filepath))
+ checker = SilentCleanupChecker("src/" + filename)
+ checker.visit(tree)
+ return len(checker.errors) == 0
+
+ def test_clean_file_passes(self, tmp_path):
+ code = """
+class Foo:
+ def close(self):
+ from utils import safe_close
+ safe_close(self.client, "client")
+"""
+ assert self._write_and_check(tmp_path, code) is True
+
+ def test_violation_fails(self, tmp_path):
+ code = """
+class Foo:
+ def close(self):
+ try:
+ self.client.close()
+ except Exception:
+ pass
+"""
+ assert self._write_and_check(tmp_path, code) is False
+
+ def test_non_python_file_passes(self, tmp_path):
+ src_dir = tmp_path / "src"
+ src_dir.mkdir()
+ txt = src_dir / "readme.txt"
+ txt.write_text("not python")
+ assert hook_module.check_file(str(txt)) is True
+
+ def test_syntax_error_passes(self, tmp_path):
+ """Files with syntax errors are skipped (other tools handle them)."""
+ src_dir = tmp_path / "src"
+ src_dir.mkdir()
+ bad = src_dir / "broken.py"
+ bad.write_text("def close(self:\n pass")
+ assert hook_module.check_file(str(bad)) is True
+
+ def test_nonexistent_file_fails(self):
+ assert hook_module.check_file("/nonexistent/path/module.py") is False
+
+ def test_empty_file_passes(self, tmp_path):
+ src_dir = tmp_path / "src"
+ src_dir.mkdir()
+ empty = src_dir / "empty.py"
+ empty.write_text("")
+ assert hook_module.check_file(str(empty)) is True
+
+
+class TestIsSilentHandler:
+ """Unit tests for _is_silent_handler static method."""
+
+ def _make_handler(self, body_code):
+ """Parse an except handler from code."""
+ code = f"""
+try:
+ pass
+except Exception:
+{body_code}
+"""
+ tree = ast.parse(code)
+ for node in ast.walk(tree):
+ if isinstance(node, ast.ExceptHandler):
+ return node
+ raise ValueError("No ExceptHandler found")
+
+ def test_pass_only_is_silent(self):
+ handler = self._make_handler(" pass")
+ assert SilentCleanupChecker._is_silent_handler(handler) is True
+
+ def test_multiple_pass_is_silent(self):
+ handler = self._make_handler(" pass\n pass")
+ assert SilentCleanupChecker._is_silent_handler(handler) is True
+
+ def test_logger_call_is_not_silent(self):
+ handler = self._make_handler(' logger.warning("fail")')
+ assert SilentCleanupChecker._is_silent_handler(handler) is False
+
+ def test_raise_is_not_silent(self):
+ handler = self._make_handler(" raise")
+ assert SilentCleanupChecker._is_silent_handler(handler) is False
+
+ def test_assignment_is_not_silent(self):
+ """An assignment (any non-pass statement) is not silent."""
+ handler = self._make_handler(" x = 1")
+ assert SilentCleanupChecker._is_silent_handler(handler) is False
+
+ def test_print_call_is_not_silent(self):
+ """A print() call (non-logger, non-pass) is not silent."""
+ handler = self._make_handler(' print("error")')
+ assert SilentCleanupChecker._is_silent_handler(handler) is False