~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 deprecated-DB hook path exemptions (#7084)
LearningCircuit098511455be1
diff --git a/.pre-commit-hooks/check-deprecated-db.py b/.pre-commit-hooks/check-deprecated-db.pyindex fbfa4baa48..55c06773fd 100755--- a/.pre-commit-hooks/check-deprecated-db.py+++ b/.pre-commit-hooks/check-deprecated-db.py@@ -7,6 +7,68 @@ Ensures code uses per-user database connections instead of the deprecated sharedimport sysimport reimport os+from pathlib import Path+++# Only these production modules own the raw-session or legacy-DB helpers.+# Match their complete repository path, never a substring of another name.+_SOURCE_EXEMPTIONS = (+ ("src", "local_deep_research", "web", "models", "database.py"),+ ("src", "local_deep_research", "database", "session_context.py"),+ ("src", "local_deep_research", "database", "encrypted_db.py"),+ ("src", "local_deep_research", "utilities", "db_utils.py"),+)+# A path is exempt when one of its directories has one of these exact names+# or is a test tree whose name ends in ``_tests`` (``release_tests``,+# ``ui_tests``). A directory name that merely contains "tests" (``contests``,+# ``tests_util``) stays checked.+_EXEMPT_DIRS = frozenset({"migrations", "tests", ".pre-commit-hooks"})+_TEST_TREE_SUFFIX = "_tests"+++def _committed_parts(filepath):+ """Return the checkout-relative components of ``filepath``, or None.++ Pre-commit passes each path relative to the checkout, exactly as+ committed. The exemption is decided on that path and never on a symlink+ target, because a link under ``src/`` that points into ``tests/`` is still+ production code. None means the path cannot earn an exemption, so the+ file is checked: it is empty, lies outside the checkout, contains ``..``,+ or is (or passes through) a symlink.+ """+ cwd = Path.cwd()+ path = Path(filepath)+ if path.anchor:+ try:+ path = path.relative_to(cwd)+ except ValueError:+ return None+ parts = path.parts+ if not parts or ".." in parts:+ return None+ for depth in range(1, len(parts) + 1):+ if cwd.joinpath(*parts[:depth]).is_symlink():+ return None+ return parts+++def _is_exempt_dir(name):+ return name in _EXEMPT_DIRS or name.endswith(_TEST_TREE_SUFFIX)+++def _is_exempt_path(filepath):+ """Exempt test, migration and hook trees, ``test_*`` files, and helpers.++ The helpers are the exact module paths in ``_SOURCE_EXEMPTIONS``.+ """+ parts = _committed_parts(filepath)+ if parts is None:+ return False+ if parts[-1].startswith("test_"):+ return True+ if any(_is_exempt_dir(name) for name in parts[:-1]):+ return True+ return any(parts == source_path for source_path in _SOURCE_EXEMPTIONS)def check_file(filepath):@@ -26,9 +88,11 @@ def check_file(filepath):)# Pattern to detect db_manager.get_session() — returns a raw QueuePool- # session that must be closed by the caller. Safe only inside- # inject_current_user / ensure_db_session (stored in g.db_session and- # cleaned up by teardown_appcontext). All other call sites should use+ # session that must be closed by the caller. utilities/db_utils.py, which+ # is exempt by path, keeps such sessions in a per-thread cache that the+ # worker's cleanup_current_thread() closes when the request or background+ # task finishes. Any other call site must close the session itself and+ # carry a raw-session noqa marker; everything else should use the# get_user_db_session() context manager instead.raw_session_pattern = re.compile(r"\bdb_manager\.get_session\s*\(")@@ -58,7 +122,7 @@ def check_file(filepath):f"{filepath}:{i}: Direct db_manager.get_session() call — ""returns an unmanaged QueuePool session that leaks FDs if not closed. ""Use 'with get_user_db_session(username) as session:' instead, "- "or add '# noqa: raw-session' if this is intentional (e.g. stored in g.db_session)"+ "or add '# noqa: raw-session' if this is intentional (e.g. the session is closed in a finally block)")# (The previous file-level "from ..web.models.database import get_db_connection"@@ -98,28 +162,7 @@ def main():all_issues = []for filepath in sys.argv[1:]:- # Skip the database.py file itself (it contains the deprecated function definition)- if "web/models/database.py" in filepath:- continue-- # Skip files that legitimately manage raw sessions (store in g.db_session- # or define the deprecated helpers themselves)- if any(- skip in filepath- for skip in [- "session_context.py", # ensure_db_session stores in g.db_session- "web/auth/decorators.py", # inject_current_user stores in g.db_session- "encrypted_db.py", # defines get_session()- "db_utils.py", # defines get_db_session() wrapper- ]- ):- continue-- # Skip migration scripts and test files that might legitimately need shared DB access- if any(- skip in filepath- for skip in ["migrations/", "tests/", "test_", ".pre-commit-hooks/"]- ):+ if _is_exempt_path(filepath):continueissues = check_file(filepath)@@ -143,11 +186,10 @@ def main():print(" cursor = conn.cursor()")print(" # ... SQL query execution ...")print()- print(" # New (correct):")- print(" from flask import session")- print(" username = session.get('username', 'anonymous')")- print(" with get_user_db_session(username) as db_session:")- print(" results = db_session.query(Model).filter(...).all()")+ print(" # New (correct), in a FastAPI route:")+ print(" def handler(username: Annotated[str, Depends(require_auth)]):")+ print(" with get_user_db_session(username) as db_session:")+ print(" results = db_session.query(Model).filter(...).all()")return 1return 0diff --git a/.pre-commit-hooks/check-no-flask.py b/.pre-commit-hooks/check-no-flask.pyindex 6d21a48df0..9f2ca81d72 100755--- a/.pre-commit-hooks/check-no-flask.py+++ b/.pre-commit-hooks/check-no-flask.py@@ -21,9 +21,8 @@ Rules:Detection is AST-based: 70+ files legitimately mention Flask incomments and docstrings narrating the migration, which a line regex-would flag (check-deprecated-db.py even *prints* "from flask import-session" in its fix guidance). Only files whose text contains the-token are parsed, so the full-tree scan stays fast.+would flag. Only files whose text contains the token are parsed, so+the full-tree scan stays fast."""from __future__ import annotationsdiff --git a/tests/hooks/test_check_deprecated_db.py b/tests/hooks/test_check_deprecated_db.pyindex 8f7b65fec1..cc370106ba 100644--- a/tests/hooks/test_check_deprecated_db.py+++ b/tests/hooks/test_check_deprecated_db.py@@ -6,6 +6,11 @@ Covers regressions:one correct call silently allowed raw sqlite3.connect elsewhere.- get_db_connection / import patterns had no comment/docstring skip — aTODO or migration note referencing the deprecated API was flagged.+- Path exemptions matched substrings, so production names such as+ ``request_test_handler.py`` skipped every check. They are now decided+ per component of the path as committed: a ``tests`` or ``*_tests``+ directory, ``migrations``, ``.pre-commit-hooks``, a ``test_*`` basename,+ or an exact helper path. A symlink or a ``..`` component never earns one.Note: SHARED_DB is built at runtime to avoid embedding the literalshared-database filename in this test file (a separate hook scans every@@ -17,6 +22,8 @@ import sysimport tempfilefrom pathlib import Path+import pytest+HOOK_SCRIPT = (Path(__file__).parent.parent.parent@@ -37,9 +44,10 @@ def _run_hook(path.parent.mkdir(parents=True, exist_ok=True)path.write_text(content)return subprocess.run(- [sys.executable, str(HOOK_SCRIPT), str(path)],+ [sys.executable, str(HOOK_SCRIPT), filename],capture_output=True,text=True,+ cwd=d,)@@ -99,24 +107,164 @@ class TestCommentSkip:class TestExistingAllowlistStillApplies:- """Filename-based exemptions must still work."""+ """The actual helper modules and test paths remain exempt."""- def test_encrypted_db_exempt(self):- """encrypted_db.py legitimately calls get_db_connection — the skip- list in main() must still exempt it."""- result = _run_hook(- "conn = get_db_connection()\n", filename="encrypted_db.py"- )+ @pytest.mark.parametrize(+ "filename",+ [+ "src/local_deep_research/web/models/database.py",+ "src/local_deep_research/database/session_context.py",+ "src/local_deep_research/database/encrypted_db.py",+ "src/local_deep_research/utilities/db_utils.py",+ ],+ )+ def test_exact_source_helper_exempt(self, filename):+ result = _run_hook("conn = get_db_connection()\n", filename=filename)assert result.returncode == 0- def test_session_context_exempt(self):+ @pytest.mark.parametrize(+ "filename",+ [+ "tests/fixtures.py",+ ".semgrep/tests/ldr-security.py",+ "release_tests/security/conftest.py",+ "ui_tests/helpers.py",+ "src/local_deep_research/test_helper.py",+ "migrations/versions/0001.py",+ ".pre-commit-hooks/example.py",+ ],+ )+ def test_test_and_tool_paths_exempt(self, filename):+ result = _run_hook("conn = get_db_connection()\n", filename=filename)+ assert result.returncode == 0, (filename, result.stdout, result.stderr)++ def test_release_test_tree_may_open_raw_sessions(self):+ """A pytest tree named ``*_tests`` is test code like ``tests/``.++ This mirrors a release-test conftest that opens a raw session and+ closes it with ``with session:``. The substring rule exempted it+ through "tests/", and an exact ``tests`` component alone would not.+ """+ content = (+ "def db(self):\n"+ " session = db_manager.get_session(self.username)\n"+ " with session:\n"+ " yield session\n"+ )result = _run_hook(- "conn = get_db_connection()\n", filename="session_context.py"+ content, filename="release_tests/security/conftest.py")- assert result.returncode == 0+ assert result.returncode == 0, (result.stdout, result.stderr)- def test_tests_path_exempt(self):- result = _run_hook(- f'sqlite3.connect("{SHARED_DB}")\n', filename="tests/fixtures.py"++class TestProductionPathsCannotInheritExemptions:+ """A substring in a production name must never bypass the real hook."""++ @pytest.mark.parametrize(+ "filename",+ [+ "src/local_deep_research/request_test_handler.py",+ "src/local_deep_research/mytests/service.py",+ "src/local_deep_research/migrations_helper.py",+ "src/local_deep_research/request_session_context.py",+ "src/local_deep_research/request_encrypted_db.py",+ "src/local_deep_research/request_db_utils.py",+ "src/local_deep_research/other/session_context.py",+ "src/local_deep_research/other/encrypted_db.py",+ "src/local_deep_research/other/db_utils.py",+ "src/local_deep_research/web/models/database.py_helper.py",+ "tests/../src/local_deep_research/service.py",+ "vendor/src/local_deep_research/utilities/db_utils.py",+ "src/local_deep_research/database/connection_helper.py",+ "src/local_deep_research/utilities/other.py",+ "src/local_deep_research/utilities/db_utils.py/nested.py",+ # "tests" inside a component, but not a test-tree name.+ "src/local_deep_research/contests/service.py",+ "src/local_deep_research/tests_util/service.py",+ "src/local_deep_research/release_tests_runner/service.py",+ "src/local_deep_research/release_tests.py",+ ],+ )+ def test_suspicious_production_path_is_checked(self, filename):+ result = _run_hook("conn = get_db_connection()\n", filename=filename)+ assert result.returncode == 1, (filename, result.stdout, result.stderr)+ assert "Usage of deprecated get_db_connection()" in result.stdout++ def test_absolute_file_outside_checkout_cannot_inherit_parent_exemption(+ self,+ ):+ with tempfile.TemporaryDirectory() as d:+ path = Path(d) / "tests" / "service.py"+ path.parent.mkdir()+ path.write_text("conn = get_db_connection()\n", encoding="utf-8")+ result = subprocess.run(+ [sys.executable, str(HOOK_SCRIPT), str(path)],+ cwd=HOOK_SCRIPT.parent.parent,+ capture_output=True,+ text=True,+ )+ assert result.returncode == 1+ assert "Usage of deprecated get_db_connection()" in result.stdout+++def _link(link: Path, target: str) -> None:+ link.parent.mkdir(parents=True, exist_ok=True)+ try:+ link.symlink_to(target)+ except (OSError, NotImplementedError) as exc:+ pytest.skip(f"cannot create symlinks here: {exc}")+++def _run_hook_on(root: Path, filename: str) -> subprocess.CompletedProcess:+ return subprocess.run(+ [sys.executable, str(HOOK_SCRIPT), filename],+ capture_output=True,+ text=True,+ cwd=root,+ )+++class TestExemptionUsesCommittedPath:+ """The committed path decides exemption, never a symlink target."""++ def _write(self, root: Path, filename: str) -> None:+ path = root / filename+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("conn = get_db_connection()\n", encoding="utf-8")++ def test_file_symlink_into_test_tree_is_checked(self, tmp_path):+ self._write(tmp_path, "tests/helper.py")+ _link(+ tmp_path / "src/local_deep_research/service.py",+ "../../tests/helper.py",)- assert result.returncode == 0+ result = _run_hook_on(tmp_path, "src/local_deep_research/service.py")+ assert result.returncode == 1, (result.stdout, result.stderr)+ assert "Usage of deprecated get_db_connection()" in result.stdout++ def test_directory_symlink_into_test_tree_is_checked(self, tmp_path):+ self._write(tmp_path, "tests/helper.py")+ _link(tmp_path / "src/local_deep_research/linked", "../../tests")+ result = _run_hook_on(+ tmp_path, "src/local_deep_research/linked/helper.py"+ )+ assert result.returncode == 1, (result.stdout, result.stderr)+ assert "Usage of deprecated get_db_connection()" in result.stdout++ def test_symlink_inside_test_tree_is_checked(self, tmp_path):+ self._write(tmp_path, "src/local_deep_research/service.py")+ _link(+ tmp_path / "tests/linked_service.py",+ "../src/local_deep_research/service.py",+ )+ result = _run_hook_on(tmp_path, "tests/linked_service.py")+ assert result.returncode == 1, (result.stdout, result.stderr)+ assert "Usage of deprecated get_db_connection()" in result.stdout++ def test_parent_traversal_into_test_tree_is_checked(self, tmp_path):+ """Pre-commit never passes ``..``; such a path earns no exemption."""+ self._write(tmp_path, "tests/fixtures.py")+ (tmp_path / "src").mkdir()+ result = _run_hook_on(tmp_path, "src/../tests/fixtures.py")+ assert result.returncode == 1, (result.stdout, result.stderr)+ assert "Usage of deprecated get_db_connection()" in result.stdout