~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(ci): reduce actionable runtime warnings (#5217)
LearningCircuitffba6176baec
diff --git a/.github/workflows/docker-tests.yml b/.github/workflows/docker-tests.ymlindex 384d74cf65..9bdb33548d 100644--- a/.github/workflows/docker-tests.yml+++ b/.github/workflows/docker-tests.yml@@ -13,6 +13,11 @@ on:required: falsetype: booleandefault: true+ reusable-invocation:+ description: 'Internal marker that isolates reusable invocations from direct PR cancellation'+ required: false+ type: boolean+ default: truesecrets:OPENROUTER_API_KEY:required: false@@ -22,11 +27,13 @@ on:required: falseworkflow_dispatch:-# No concurrency group — intentionally omitted.-# This workflow triggers on both pull_request and workflow_call (from-# ci-gate.yml / release-gate.yml). A shared concurrency key would cause-# direct PR runs and workflow_call runs to cancel each other mid-flight.-# See #3554 (reverted in #3599) for context.+# Cancel an obsolete direct PR run before it can consume build/test capacity.+# Reusable invocations retain the caller's event context, so the explicit+# workflow_call marker keeps them on unique run-id groups instead of allowing+# them to cancel or queue behind the direct PR workflow.+concurrency:+ group: ${{ github.event_name == 'pull_request' && !inputs.reusable-invocation && format('docker-tests-direct-pr-{0}', github.event.pull_request.number) || format('docker-tests-isolated-run-{0}', github.run_id) }}+ cancel-in-progress: ${{ github.event_name == 'pull_request' && !inputs.reusable-invocation }}# Top-level permissions set to minimum (OSSF Scorecard Token-Permissions)permissions: {}@@ -154,7 +161,7 @@ jobs:needs: build-test-imageenvironment: cipermissions:- contents: write # Needed for gh-pages deployment+ contents: readpull-requests: write # Needed for PR commentssteps:@@ -165,7 +172,8 @@ jobs:- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0with:- persist-credentials: true # Needed for gh-pages push+ # Never expose a token to code exercised by the test suite.+ persist-credentials: false- name: Download Docker imageuses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1@@ -189,6 +197,7 @@ jobs:cd tests/infrastructure_tests && npm ci- name: Run all pytest tests with coverage+ id: main_pytest# Tests are always blocking - failures should not be silently ignored.# test_settings_routes_coverage.py is excluded here and run serially# in a dedicated step below — its 94 authenticated_client tests@@ -233,6 +242,7 @@ jobs:# the main run's .coverage file, and emits the final xml + html# reports + the 50% fail-under check after both runs have contributed.- name: Run test_settings_routes_coverage.py (serial, with coverage)+ id: serial_coverageenv:OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }}run: |@@ -291,27 +301,45 @@ jobs:run: |npm ci && npm test+ - name: Validate coverage data+ if: always()+ run: |+ docker run --rm \+ -v "$PWD":/app \+ -w /app \+ ${{ env.TEST_IMAGE }} \+ python scripts/ci/coverage_summary.py \+ coverage/coverage.xml coverage/coverage-summary.json+- name: Generate coverage summaryif: always()run: |{echo "## Coverage Report"echo ""- if [ -f coverage/coverage.xml ]; then- # Extract total coverage from XML- COVERAGE=$(python3 -c "import xml.etree.ElementTree as ET; tree = ET.parse('coverage/coverage.xml'); print(f\"{float(tree.getroot().get('line-rate', 0)) * 100:.1f}%\")" 2>/dev/null || echo "N/A")- echo "**Total Line Coverage: ${COVERAGE}**"- echo ""- echo "📊 **[View Full Coverage Report](${{ env.PAGES_URL }})** - Interactive HTML report with line-by-line details"+ if [ "${{ steps.main_pytest.outcome }}" != "success" ] || \+ [ "${{ steps.serial_coverage.outcome }}" != "success" ]; then+ echo "⚠️ Coverage run incomplete; no successful coverage result is available"echo ""- echo "_Note: Report updates after merge to main/dev branch._"+ echo "Main pytest: ${{ steps.main_pytest.outcome }}; serial coverage: ${{ steps.serial_coverage.outcome }}"+ elif [ -f coverage/coverage-summary.json ]; then+ COVERAGE=$(python3 -c "import json; data=json.load(open('coverage/coverage-summary.json', encoding='utf-8')); print(f\"{data['lineRate'] * 100:.1f}%\" if data.get('valid') else 'N/A')" 2>/dev/null || echo "N/A")+ if [ "$COVERAGE" = "N/A" ]; then+ echo "⚠️ Coverage report is missing or invalid"+ else+ echo "**Total Line Coverage: ${COVERAGE}**"+ echo ""+ echo "📊 **[View Full Coverage Report](${{ env.PAGES_URL }})** - Interactive HTML report with line-by-line details"+ echo ""+ echo "_Note: Report updates after merge to main/dev branch._"+ fielse- echo "⚠️ Coverage report not generated"+ echo "⚠️ Validated coverage summary not generated"fi} >> "$GITHUB_STEP_SUMMARY"- name: Upload coverage reports- if: always()+ if: always() && hashFiles('coverage/**') != ''uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1with:name: coverage-report@@ -337,63 +365,6 @@ jobs:echo "ERROR: coverage directory does not exist!"fi- # Deploy coverage HTML report to GitHub Pages- # Only deploys on main/dev branch pushes (not PRs)- # Note: continue-on-error prevents deployment failures from failing the tests badge- - name: Deploy coverage to GitHub Pages- continue-on-error: true- if: |- always() &&- github.ref == 'refs/heads/main' &&- github.event_name == 'push'- env:- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}- run: |- set -ex-- # Check source exists- if [ ! -d "coverage/htmlcov" ]; then- echo "ERROR: coverage/htmlcov does not exist"- exit 1- fi-- FILE_COUNT=$(find coverage/htmlcov -type f | wc -l)- echo "Found $FILE_COUNT files to deploy"-- if [ "$FILE_COUNT" -eq 0 ]; then- echo "ERROR: No files to deploy"- exit 1- fi-- # Copy to a fresh directory to avoid Docker volume/git issues- DEPLOY_DIR=$(mktemp -d)- cp -r coverage/htmlcov/* "$DEPLOY_DIR/"- cd "$DEPLOY_DIR"-- # Create .nojekyll to bypass Jekyll processing- touch .nojekyll-- # Debug: show what we have- echo "Files in deploy dir:"- find . -type f | head -10- echo "Total files: $(find . -type f | wc -l)"-- # Setup git- git init- git config user.name "github-actions[bot]"- git config user.email "github-actions[bot]@users.noreply.github.com"-- # Add all files and commit- git add -A- git status- git commit -m "docs: update coverage report ${{ github.sha }}"-- # Force push to gh-pages branch- git push --force "https://x-access-token:${GITHUB_TOKEN}@github.com/${{ github.repository }}.git" HEAD:gh-pages-- echo "Deployment complete!"- rm -rf "$DEPLOY_DIR"-# Add coverage summary as PR comment for easy visibility- name: Comment coverage on PRif: always() && github.event_name == 'pull_request'@@ -403,6 +374,13 @@ jobs:retries: 3script: |const fs = require('fs');+ const coverageGenerated = fs.existsSync('coverage/coverage.xml');+ const mainPytestOutcome = '${{ steps.main_pytest.outcome }}';+ const serialCoverageOutcome = '${{ steps.serial_coverage.outcome }}';+ const coverageComplete =+ mainPytestOutcome === 'success' &&+ serialCoverageOutcome === 'success';+ let coverageValid = false;let lineCoverage = 'N/A';let branchCoverage = 'N/A';@@ -412,48 +390,61 @@ jobs:let lowestCoverageFiles = [];try {- if (fs.existsSync('coverage/coverage.xml')) {- const xml = fs.readFileSync('coverage/coverage.xml', 'utf8');-- // Extract overall metrics- const lineMatch = xml.match(/line-rate="([^"]+)"/);- const branchMatch = xml.match(/branch-rate="([^"]+)"/);- const coveredMatch = xml.match(/lines-covered="([^"]+)"/);- const validMatch = xml.match(/lines-valid="([^"]+)"/);-- if (lineMatch) lineCoverage = (parseFloat(lineMatch[1]) * 100).toFixed(1) + '%';- if (branchMatch) branchCoverage = (parseFloat(branchMatch[1]) * 100).toFixed(1) + '%';- if (coveredMatch) linesCovered = parseInt(coveredMatch[1]);- if (validMatch) linesTotal = parseInt(validMatch[1]);-- // Extract per-file coverage to find lowest coverage files- const classMatches = xml.matchAll(/<class[^>]+filename="([^"]+)"[^>]+line-rate="([^"]+)"/g);- const fileCoverages = [];- for (const match of classMatches) {- const filename = match[1].replace(/^src\//, '').replace(/^local_deep_research\//, '');- const rate = parseFloat(match[2]) * 100;- fileCoverages.push({ filename, rate });- filesAnalyzed++;+ if (!fs.existsSync('coverage/coverage-summary.json')) {+ throw new Error('validated coverage summary was not generated');+ }+ const summary = JSON.parse(+ fs.readFileSync('coverage/coverage-summary.json', 'utf8')+ );+ if (summary.valid !== true) {+ if (summary.error) {+ console.log(`Coverage validation failed: ${summary.error}`);}-- // Sort by coverage (lowest first) and get bottom 5 with <50% coverage- lowestCoverageFiles = fileCoverages- .filter(f => f.rate < 50)- .sort((a, b) => a.rate - b.rate)- .slice(0, 5);+ } else {+ const ratesAreValid =+ Number.isFinite(summary.lineRate) &&+ summary.lineRate >= 0 && summary.lineRate <= 1 &&+ Number.isFinite(summary.branchRate) &&+ summary.branchRate >= 0 && summary.branchRate <= 1;+ const countsAreValid =+ Number.isInteger(summary.linesCovered) &&+ summary.linesCovered >= 0 &&+ Number.isInteger(summary.linesTotal) &&+ summary.linesTotal >= summary.linesCovered &&+ Number.isInteger(summary.filesAnalyzed) &&+ summary.filesAnalyzed >= 0;+ const filesAreValid =+ Array.isArray(summary.lowestCoverageFiles) &&+ summary.lowestCoverageFiles.every(file =>+ typeof file.filename === 'string' &&+ Number.isFinite(file.rate) &&+ file.rate >= 0 && file.rate <= 100+ );+ if (!ratesAreValid || !countsAreValid || !filesAreValid) {+ throw new Error('validated coverage summary has invalid fields');+ }+ lineCoverage = (summary.lineRate * 100).toFixed(1) + '%';+ branchCoverage = (summary.branchRate * 100).toFixed(1) + '%';+ linesCovered = summary.linesCovered;+ linesTotal = summary.linesTotal;+ filesAnalyzed = summary.filesAnalyzed;+ lowestCoverageFiles = summary.lowestCoverageFiles;+ coverageValid = true;}} catch (e) {- console.log('Could not parse coverage:', e);+ console.log('Could not load validated coverage:', e);}// Build the lowest coverage files sectionlet lowestFilesSection = '';if (lowestCoverageFiles.length > 0) {lowestFilesSection = '\n**Files needing attention** (<50% coverage):\n' +- lowestCoverageFiles.map(f => `- \`${f.filename}\`: ${f.rate.toFixed(1)}%`).join('\n');+ lowestCoverageFiles.map(f => `- <code>${f.filename}</code>: ${f.rate.toFixed(1)}%`).join('\n');}- const body = `## 📊 Coverage Report+ let body;+ if (coverageValid && coverageComplete) {+ body = `## 📊 Coverage Report| Metric | Value ||--------|-------|@@ -466,7 +457,7 @@ jobs:<details><summary>📉 Coverage Details</summary>- ${lowestFilesSection || '\n✅ All files have >50% coverage!'}+ ${lowestFilesSection || '\n✅ No files are below 50% coverage.'}---- Coverage is calculated from \`src/\` directory@@ -474,6 +465,36 @@ jobs:- Download artifacts for immediate detailed view</details>`;+ } else if (coverageValid) {+ body = `## 📊 Coverage Report++ ⚠️ Coverage XML was generated, but the coverage run was incomplete. These observed metrics are partial and are not a successful coverage result.++ | Step | Outcome |+ |------|---------|+ | Main pytest | ${mainPytestOutcome} |+ | Serial coverage | ${serialCoverageOutcome} |++ | Partial metric | Observed value |+ |----------------|----------------|+ | Line coverage | ${lineCoverage} |+ | Branch coverage | ${branchCoverage} |+ | Lines | ${linesCovered.toLocaleString()} / ${linesTotal.toLocaleString()} |++ See the **All Pytest Tests + Coverage** check for the failing step.`;+ } else if (coverageGenerated) {+ body = `## 📊 Coverage Report++ ⚠️ A coverage report was generated but could not be parsed, so no coverage claims are shown.++ See the **All Pytest Tests + Coverage** check for details.`;+ } else {+ body = `## 📊 Coverage Report++ ⚠️ Coverage was not generated because the pytest coverage run did not complete successfully.++ No coverage artifact or per-file report is available for this run. See the **All Pytest Tests + Coverage** check for details.`;+ }// Find existing comment. Paginate — on a long-lived PR the coverage// comment may be past the first page (listComments defaults to 30),@@ -485,10 +506,36 @@ jobs:per_page: 100,});+ const coverageMarker = '<!-- ldr-coverage-report -->';const botComment = comments.find(c =>- c.user.type === 'Bot' && c.body.includes('📊 Coverage Report')+ c.user.login === 'github-actions[bot]' &&+ (+ c.body.includes(coverageMarker) ||+ c.body.startsWith('## 📊 Coverage Report\n')+ ));+ // A slower run for an older synchronize event must never replace+ // the current head's coverage comment with stale results.+ const reviewedHead = context.payload.pull_request.head.sha;+ const currentPull = await github.rest.pulls.get({+ owner: context.repo.owner,+ repo: context.repo.repo,+ pull_number: context.issue.number,+ });+ if (currentPull.data.head.sha !== reviewedHead) {+ core.info(+ `Skipping stale coverage comment for ${reviewedHead}; ` ++ `current PR head is ${currentPull.data.head.sha}`+ );+ return;+ }+ const runUrl =+ `${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}`;+ body += `\n\n_Report for \`${reviewedHead.slice(0, 12)}\` · ` ++ `[workflow run](${runUrl})_`;+ body = `${coverageMarker}\n${body}`;+if (botComment) {await github.rest.issues.updateComment({owner: context.repo.owner,@@ -505,45 +552,121 @@ jobs:});}- # Coverage badge via GitHub Gist + shields.io (no third-party service needed)- # How it works:- # 1. We store a JSON file in a GitHub Gist (gist.github.com - GitHub's snippet/paste service)- # 2. shields.io reads that JSON to generate a badge image- # 3. README references the shields.io URL to display the badge- # Setup: Create a gist, add GIST_TOKEN (PAT with gist scope) and COVERAGE_GIST_ID secrets+ # Publish only a complete, validated report from the current direct main+ # push. Release-gate's nested strict-mode invocation produces its own+ # coverage artifact but must not race this job for gh-pages or the badge.+ publish-coverage:+ runs-on: ubuntu-latest+ name: Publish Coverage+ needs: pytest-tests+ if: >-+ ${{+ !cancelled() &&+ needs.pytest-tests.result == 'success' &&+ github.event_name == 'push' &&+ github.ref == 'refs/heads/main' &&+ inputs.strict-mode != true+ }}+ concurrency:+ group: coverage-publication-main+ cancel-in-progress: true+ environment: ci+ permissions:+ contents: write++ steps:+ - name: Harden the runner (Audit all outbound calls)+ uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0+ with:+ egress-policy: audit++ - name: Download validated coverage report+ uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1+ with:+ name: coverage-report+ path: coverage++ - name: Verify coverage artifact+ run: |+ set -euo pipefail+ python3 -c "import json; data=json.load(open('coverage/coverage-summary.json', encoding='utf-8')); assert data.get('valid') is True"+ test -d coverage/htmlcov+ FILE_COUNT="$(find coverage/htmlcov -type f | wc -l)"+ if [ "$FILE_COUNT" -eq 0 ]; then+ echo "Coverage HTML artifact is empty"+ exit 1+ fi+ echo "Validated $FILE_COUNT coverage HTML files"++ - name: Deploy coverage to GitHub Pages+ env:+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ run: |+ set -euo pipefail+ DEPLOY_DIR="$(mktemp -d)"+ trap 'rm -rf "$DEPLOY_DIR"' EXIT+ cp -a coverage/htmlcov/. "$DEPLOY_DIR/"+ cd "$DEPLOY_DIR"+ touch .nojekyll++ git init+ git config user.name "github-actions[bot]"+ git config user.email "github-actions[bot]@users.noreply.github.com"+ git add -A+ git commit -m "docs: update coverage report ${GITHUB_SHA}"++ # Recheck immediately before the write. A queued older run must not+ # overwrite coverage produced by a newer commit on main.+ CURRENT_MAIN_SHA="$(git ls-remote "https://github.com/${GITHUB_REPOSITORY}.git" refs/heads/main | awk '{print $1}')"+ if [ "$CURRENT_MAIN_SHA" != "$GITHUB_SHA" ]; then+ echo "Skipping stale Pages report for $GITHUB_SHA; main is $CURRENT_MAIN_SHA"+ exit 0+ fi++ git push --force "https://x-access-token:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" HEAD:gh-pages++ # Coverage badge via GitHub Gist + shields.io. The badge is derived only+ # from the parser-validated JSON above, never directly from XML.- name: Update coverage badge- if: always() && github.ref == 'refs/heads/main' && github.event_name == 'push'env:GIST_TOKEN: ${{ secrets.GIST_TOKEN }}+ COVERAGE_GIST_ID: ${{ secrets.COVERAGE_GIST_ID }}run: |- if [ -z "$GIST_TOKEN" ]; then- echo "GIST_TOKEN not set, skipping badge update"+ set -euo pipefail+ if [ -z "$GIST_TOKEN" ] || [ -z "$COVERAGE_GIST_ID" ]; then+ echo "Coverage gist credentials not set, skipping badge update"exit 0fi- if [ -f coverage/coverage.xml ]; then- COVERAGE=$(python3 -c "import xml.etree.ElementTree as ET; tree = ET.parse('coverage/coverage.xml'); print(f\"{float(tree.getroot().get('line-rate', 0)) * 100:.0f}\")" 2>/dev/null || echo "0")- # Determine color based on coverage- if [ "$COVERAGE" -ge 80 ]; then- COLOR="brightgreen"- elif [ "$COVERAGE" -ge 60 ]; then- COLOR="green"- elif [ "$COVERAGE" -ge 40 ]; then- COLOR="yellow"- else- COLOR="red"- fi- # Create badge JSON- echo "{\"schemaVersion\":1,\"label\":\"coverage\",\"message\":\"${COVERAGE}%\",\"color\":\"${COLOR}\"}" > coverage-badge.json- # Update gist (requires GIST_TOKEN secret and GIST_ID)- if [ -n "${{ secrets.COVERAGE_GIST_ID }}" ]; then- curl -s -X PATCH \- -H "Authorization: token ${GIST_TOKEN}" \- -H "Accept: application/vnd.github.v3+json" \- "https://api.github.com/gists/${{ secrets.COVERAGE_GIST_ID }}" \- -d "{\"files\":{\"coverage-badge.json\":{\"content\":$(jq -Rs . < coverage-badge.json)}}}"- fi++ CURRENT_MAIN_SHA="$(git ls-remote "https://github.com/${GITHUB_REPOSITORY}.git" refs/heads/main | awk '{print $1}')"+ if [ "$CURRENT_MAIN_SHA" != "$GITHUB_SHA" ]; then+ echo "Skipping stale coverage badge for $GITHUB_SHA; main is $CURRENT_MAIN_SHA"+ exit 0+ fi++ COVERAGE="$(python3 -c "import json; data=json.load(open('coverage/coverage-summary.json', encoding='utf-8')); print(f\"{data['lineRate'] * 100:.0f}\")")"+ if [ "$COVERAGE" -ge 80 ]; then+ COLOR="brightgreen"+ elif [ "$COVERAGE" -ge 60 ]; then+ COLOR="green"+ elif [ "$COVERAGE" -ge 40 ]; then+ COLOR="yellow"+ else+ COLOR="red"fi+ jq -n \+ --arg message "${COVERAGE}%" \+ --arg color "$COLOR" \+ '{schemaVersion: 1, label: "coverage", message: $message, color: $color}' \+ > coverage-badge.json+ PAYLOAD="$(jq -n --rawfile badge coverage-badge.json '{files: {"coverage-badge.json": {content: $badge}}}')"+ curl --fail-with-body --silent --show-error --request PATCH \+ --header "Authorization: token ${GIST_TOKEN}" \+ --header "Accept: application/vnd.github.v3+json" \+ "https://api.github.com/gists/${COVERAGE_GIST_ID}" \+ --data "$PAYLOAD"+# Run UI tests with Puppeteer## Runs as a 17-way matrix (one cell per shard). Each cell spins up its owndiff --git a/package.json b/package.jsonindex f3c085975c..b6fcc2e2e9 100644--- a/package.json+++ b/package.json@@ -46,6 +46,10 @@"vite": "^8.1.5","vitest": "^4.1.7"},+ "allowScripts": {+ "core-js": false,+ "fsevents": false+ },"overrides": {"postcss": "^8.5.10","ws": "^8.20.1"diff --git a/scripts/ci/coverage_summary.py b/scripts/ci/coverage_summary.pynew file mode 100644index 0000000000..9d5a72a968--- /dev/null+++ b/scripts/ci/coverage_summary.py@@ -0,0 +1,215 @@+#!/usr/bin/env python3+"""Validate Cobertura coverage XML and emit PR-comment data as JSON."""++from __future__ import annotations++import json+import math+import re+import sys+from html import escape+from pathlib import Path++from defusedxml import ElementTree+from defusedxml.common import DefusedXmlException+++_INTEGER = re.compile(r"[0-9]+")+_JS_MAX_SAFE_INTEGER = 2**53 - 1+_RATE_ROUNDING_TOLERANCE = 0.0000500000001+_MAX_DIAGNOSTIC_LENGTH = 1024+_ERROR_LOG_PREFIX = "Coverage report rejected: "+_MAX_ERROR_LENGTH = _MAX_DIAGNOSTIC_LENGTH - len(_ERROR_LOG_PREFIX)+++def _local_name(tag: str) -> str:+ """Return an XML tag without its optional namespace."""+ return tag.rsplit("}", 1)[-1]+++def _rate(attributes: dict[str, str], name: str) -> float:+ raw_value = attributes.get(name)+ if raw_value is None:+ raise ValueError(f"coverage.xml is missing {name!r}")+ value = float(raw_value)+ if not math.isfinite(value) or not 0 <= value <= 1:+ raise ValueError(f"coverage.xml has invalid {name!r}: {raw_value!r}")+ return value+++def _count(attributes: dict[str, str], name: str) -> int:+ raw_value = attributes.get(name)+ if raw_value is None or _INTEGER.fullmatch(raw_value) is None:+ raise ValueError(f"coverage.xml has invalid {name!r}: {raw_value!r}")+ value = int(raw_value)+ if value > _JS_MAX_SAFE_INTEGER:+ raise ValueError(+ f"coverage.xml has {name!r} above the JavaScript safe integer limit"+ )+ return value+++def _validate_rate(+ *,+ rate: float,+ covered: int,+ total: int,+ rate_name: str,+ covered_name: str,+) -> None:+ """Ensure a declared rate agrees with its coverage.py-rounded counts."""+ if covered > total:+ raise ValueError(+ f"coverage.xml {covered_name} exceeds its declared total"+ )+ if total == 0:+ # coverage.py emits 1 for an empty denominator. Other Cobertura+ # producers commonly emit 0, which is also an honest representation.+ if rate not in {0.0, 1.0}:+ raise ValueError(+ f"coverage.xml {rate_name!r} disagrees with its counts"+ )+ return++ expected_rate = covered / total+ if not math.isclose(+ rate,+ expected_rate,+ rel_tol=0.0,+ abs_tol=_RATE_ROUNDING_TOLERANCE,+ ):+ raise ValueError(+ f"coverage.xml {rate_name!r} disagrees with its counts"+ )+++def _bounded_error(error: BaseException) -> str:+ """Return a single-line diagnostic safe to publish in JSON and logs."""+ raw_message = f"{type(error).__name__}: {error}"+ printable_message = "".join(+ character if character.isprintable() else " "+ for character in raw_message+ )+ message = " ".join(printable_message.split())+ if len(message) > _MAX_ERROR_LENGTH:+ return f"{message[: _MAX_ERROR_LENGTH - 1]}…"+ return message+++def _display_filename(filename: str) -> str:+ """Return bounded HTML-safe text for the bot's ``<code>`` element."""+ printable = "".join(+ character if character.isprintable() else "�" for character in filename+ )+ if len(printable) > 300:+ printable = f"{printable[:299]}…"+ return (+ escape(printable, quote=True)+ .replace("@", "@")+ .replace("`", "`")+ )+++def _parse_summary(coverage_path: Path) -> dict[str, object]:+ root = ElementTree.parse(coverage_path).getroot()+ if _local_name(root.tag) != "coverage":+ raise ValueError("coverage.xml root element is not <coverage>")++ line_rate = _rate(root.attrib, "line-rate")+ branch_rate = _rate(root.attrib, "branch-rate")+ lines_covered = _count(root.attrib, "lines-covered")+ lines_total = _count(root.attrib, "lines-valid")+ branches_covered = _count(root.attrib, "branches-covered")+ branches_total = _count(root.attrib, "branches-valid")+ _validate_rate(+ rate=line_rate,+ covered=lines_covered,+ total=lines_total,+ rate_name="line-rate",+ covered_name="lines-covered",+ )+ _validate_rate(+ rate=branch_rate,+ covered=branches_covered,+ total=branches_total,+ rate_name="branch-rate",+ covered_name="branches-covered",+ )++ file_coverages: list[tuple[str, float]] = []+ for element in root.iter():+ if _local_name(element.tag) != "class":+ continue+ filename = element.attrib.get("filename")+ if not filename:+ raise ValueError("coverage.xml contains a class without a filename")+ normalized_filename = filename.removeprefix("src/").removeprefix(+ "local_deep_research/"+ )+ file_coverages.append(+ (+ _display_filename(normalized_filename),+ _rate(element.attrib, "line-rate") * 100,+ )+ )++ lowest_coverage_files = [+ {"filename": filename, "rate": rate}+ for filename, rate in sorted(+ (item for item in file_coverages if item[1] < 50),+ key=lambda item: item[1],+ )[:5]+ ]+ return {+ "generated": True,+ "valid": True,+ "lineRate": line_rate,+ "branchRate": branch_rate,+ "linesCovered": lines_covered,+ "linesTotal": lines_total,+ "filesAnalyzed": len(file_coverages),+ "lowestCoverageFiles": lowest_coverage_files,+ }+++def build_summary(coverage_path: Path) -> dict[str, object]:+ """Return validated coverage data or a non-valid diagnostic summary."""+ if not coverage_path.is_file():+ return {"generated": False, "valid": False}++ try:+ return _parse_summary(coverage_path)+ except (+ DefusedXmlException,+ ElementTree.ParseError,+ LookupError,+ OSError,+ ValueError,+ ) as error:+ return {+ "generated": True,+ "valid": False,+ "error": _bounded_error(error),+ }+++def main() -> int:+ if len(sys.argv) != 3:+ print(+ "usage: coverage_summary.py COVERAGE_XML OUTPUT_JSON",+ file=sys.stderr,+ )+ return 2++ summary = build_summary(Path(sys.argv[1]))+ Path(sys.argv[2]).write_text(+ json.dumps(summary, allow_nan=False, sort_keys=True),+ encoding="utf-8",+ )+ if error := summary.get("error"):+ print(f"{_ERROR_LOG_PREFIX}{error}", file=sys.stderr)+ return 0 if summary.get("valid") is True else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/src/local_deep_research/database/alembic_runner.py b/src/local_deep_research/database/alembic_runner.pyindex a8d94e03a1..32e3aaf733 100644--- a/src/local_deep_research/database/alembic_runner.py+++ b/src/local_deep_research/database/alembic_runner.py@@ -287,7 +287,11 @@ def _disable_fk_for_migration(conn: Connection) -> None:transaction commits, BEFORE returning the connection to the pool —see ``run_migrations``."""+ # Clear any DBAPI transaction a custom engine/event configuration may+ # already have opened. SQLite silently ignores the toggle in a transaction.+ conn.rollback()conn.exec_driver_sql("PRAGMA foreign_keys = OFF")+ fk_enabled = conn.exec_driver_sql("PRAGMA foreign_keys").scalar_one()# ``exec_driver_sql`` triggers SQLAlchemy autobegin even though no# sqlite-level transaction was opened (PRAGMA isn't DML, so the# driver doesn't auto-begin). Roll back the no-op SQLAlchemy@@ -296,6 +300,57 @@ def _disable_fk_for_migration(conn: Connection) -> None:# survives ROLLBACK at the SQLite level — see# https://www.sqlite.org/pragma.html#pragma_foreign_keys.conn.rollback()+ if fk_enabled != 0:+ raise RuntimeError(+ "SQLite foreign-key enforcement remained enabled; refusing to "+ "run migrations with an unsafe connection transaction state"+ )+++def _restore_fk_after_migration(conn: Connection) -> None:+ """Restore and verify FK enforcement before returning ``conn`` to its pool.++ SQLite silently ignores ``PRAGMA foreign_keys = ON`` while a DBAPI+ transaction is active. Merely executing the statement is therefore not+ enough: clear any transaction, enable the pragma, and read it back. If any+ part fails, invalidate the physical connection so an FK-disabled handle+ can never be reused.+ """+ try:+ conn.rollback()+ conn.exec_driver_sql("PRAGMA foreign_keys = ON")+ fk_enabled = conn.exec_driver_sql("PRAGMA foreign_keys").scalar_one()+ conn.rollback()+ except BaseException:+ logger.exception(+ "Failed to restore and verify foreign-key enforcement after "+ "migration"+ )+ try:+ conn.invalidate()+ except Exception:+ logger.exception(+ "Failed to invalidate migration connection after "+ "foreign-key restoration failure"+ )+ raise++ if fk_enabled != 1:+ logger.error(+ "SQLite foreign-key enforcement remained disabled after "+ "migration cleanup"+ )+ try:+ conn.invalidate()+ except Exception:+ logger.exception(+ "Failed to invalidate migration connection after "+ "foreign-key verification failure"+ )+ raise RuntimeError(+ "SQLite foreign-key enforcement remained disabled after "+ "migration cleanup"+ )def run_migrations(engine: Engine, target: str = "head") -> None:@@ -432,24 +487,33 @@ def run_migrations(engine: Engine, target: str = "head") -> None:try:with engine.connect() as conn:_drop_orphan_alembic_temp_tables(conn)- _disable_fk_for_migration(conn)- with conn.begin():- config.attributes["connection"] = conn- command.upgrade(config, target)- # Re-enable FK on this connection BEFORE it returns to the- # pool so subsequent checkouts see the production-default ON- # state. The migration transaction has just committed, so we- # are back outside any active transaction — PRAGMA toggles- # work again. We can't rely on ``engine.dispose()`` to force- # a fresh connection because engines built with ``creator=``- # have ``url.database is None``, which fails the dispose- # guard below and leaves FK=OFF leaking into the pool.- conn.exec_driver_sql("PRAGMA foreign_keys = ON")- conn.rollback()+ try:+ # Keep disabling inside the cleanup boundary: the helper can+ # raise after SQLite has already accepted PRAGMA ... = OFF.+ _disable_fk_for_migration(conn)+ with conn.begin():+ config.attributes["connection"] = conn+ command.upgrade(config, target)+ except BaseException:+ # Restore connection-local state on ordinary failures and+ # cancellation alike. Never hide the original migration error+ # if cleanup itself fails.+ try:+ _restore_fk_after_migration(conn)+ except Exception:+ logger.debug(+ "Foreign-key cleanup failure was already logged; "+ "preserving the original migration exception"+ )+ raise+ else:+ # We cannot rely on ``engine.dispose()`` below because+ # creator-backed engines have ``url.database is None``.+ _restore_fk_after_migration(conn)except Exception:logger.exception(- "Database migration failed — database remains at previous "- "revision (auto-rollback by transaction manager)"+ "Database migration failed — transaction rolled back where "+ "supported; SQLite DDL from a failed revision may require repair")raisediff --git a/src/local_deep_research/database/migrations/versions/0010_add_chat_tables.py b/src/local_deep_research/database/migrations/versions/0010_add_chat_tables.pyindex 41a47ef89e..8ce81cee13 100644--- a/src/local_deep_research/database/migrations/versions/0010_add_chat_tables.py+++ b/src/local_deep_research/database/migrations/versions/0010_add_chat_tables.py@@ -115,21 +115,160 @@ def _column_exists(table_name: str, column_name: str) -> bool:}-def _fk_exists(table_name: str, fk_name: str) -> bool:+def _sqlite_fk_signatures(bind, table_name: str) -> list[dict] | None:+ """Return SQLite FK signatures without using SQLAlchemy reflection.++ SQLAlchemy's SQLite reflector warns and collapses duplicate equivalent+ constraints. Reading ``PRAGMA foreign_key_list`` first lets the migration+ reject that ambiguous partial-upgrade state before reflection emits an+ ``SAWarning`` or hides one of the constraints.+ """+ dialect = getattr(bind, "dialect", None)+ if getattr(dialect, "name", None) != "sqlite":+ return None++ quoted_table = dialect.identifier_preparer.quote(table_name)+ # ``table_name`` is supplied by this migration and dialect-quoted.+ rows = bind.exec_driver_sql( # noqa: S608+ f"PRAGMA foreign_key_list({quoted_table})"+ ).mappings()+ grouped: dict[int, list] = {}+ for row in rows:+ grouped.setdefault(row["id"], []).append(row)++ signatures = []+ for fk_rows in grouped.values():+ ordered = sorted(fk_rows, key=lambda row: row["seq"])+ signatures.append(+ {+ "constrained_columns": [row["from"] for row in ordered],+ "referred_table": ordered[0]["table"],+ "referred_columns": [row["to"] for row in ordered],+ "ondelete": ordered[0]["on_delete"],+ }+ )+ return signatures+++def _fk_exists(+ table_name: str,+ fk_name: str,+ constrained_columns: list[str],+ referred_table: str,+ referred_columns: list[str],+ ondelete: str,+) -> bool:+ """Return whether the named or structurally equivalent FK exists.++ ``0001`` creates tables from the current ORM metadata, whose+ ``research_history.chat_session_id`` FK is unnamed. Checking only the+ name therefore caused ``0010`` to add the same FK a second time on fresh+ databases. Besides being redundant, duplicate equal FK signatures make+ SQLAlchemy's SQLite reflector emit an SAWarning because its signature map+ can represent only one of them. An unnamed FK is equivalent only when its+ endpoints and delete action match the constraint this migration requires.+ """bind = op.get_bind()inspector = inspect(bind)if not inspector.has_table(table_name):return False- return any(- fk.get("name") == fk_name- for fk in inspector.get_foreign_keys(table_name)- )++ # Validate every SQLite constraint that touches the expected local+ # columns, including unnamed constraints. Name-only validation misses an+ # unnamed FK to the wrong table and would add a second, incompatible FK.+ raw_foreign_keys = _sqlite_fk_signatures(bind, table_name)+ if raw_foreign_keys is not None:+ expected_local_columns = set(constrained_columns)+ relevant_foreign_keys = [+ fk+ for fk in raw_foreign_keys+ if expected_local_columns.intersection(fk["constrained_columns"])+ ]+ if len(relevant_foreign_keys) > 1:+ raise RuntimeError(+ f"0010: existing {table_name} has more than one foreign key "+ f"involving {constrained_columns!r}. Recreate the database "+ "before running migrations."+ )+ if relevant_foreign_keys:+ raw_fk = relevant_foreign_keys[0]+ endpoints_match = (+ raw_fk["constrained_columns"] == constrained_columns+ and raw_fk["referred_table"] == referred_table+ and raw_fk["referred_columns"] == referred_columns+ )+ if not endpoints_match:+ raise RuntimeError(+ f"0010: existing {table_name} foreign key involving "+ f"{constrained_columns!r} has the wrong endpoints; "+ f"expected {constrained_columns!r} -> "+ f"{referred_table}.{referred_columns!r}. Recreate the "+ "database before running migrations."+ )+ actual_ondelete = raw_fk["ondelete"]+ if not (+ isinstance(actual_ondelete, str)+ and actual_ondelete.strip().upper() == ondelete.strip().upper()+ ):+ raise RuntimeError(+ f"0010: existing {table_name} foreign key for "+ f"{constrained_columns!r} uses ON DELETE "+ f"{actual_ondelete or 'NO ACTION'}; expected {ondelete}. "+ "Recreate the database before running migrations."+ )++ matching_signature = False+ for fk in inspector.get_foreign_keys(table_name):+ endpoints_match = (+ fk.get("constrained_columns") == constrained_columns+ and fk.get("referred_table") == referred_table+ and fk.get("referred_columns") == referred_columns+ )+ if fk.get("name") == fk_name and not endpoints_match:+ raise RuntimeError(+ f"0010: existing foreign key named {fk_name!r} on "+ f"{table_name} has the wrong endpoints; expected "+ f"{constrained_columns!r} -> "+ f"{referred_table}.{referred_columns!r}. "+ "Recreate the database before running migrations."+ )+ if endpoints_match:+ actual_ondelete = (fk.get("options") or {}).get("ondelete")+ if (+ isinstance(actual_ondelete, str)+ and actual_ondelete.strip().upper() == ondelete.strip().upper()+ ):+ matching_signature = True+ continue+ raise RuntimeError(+ f"0010: existing {table_name} foreign key for "+ f"{constrained_columns!r} uses ON DELETE "+ f"{actual_ondelete or 'NO ACTION'}; expected {ondelete}. "+ "Recreate the database before running migrations."+ )+ return matching_signaturedef upgrade():bind = op.get_bind()inspector = inspect(bind)+ # Validate any pre-existing FK before creating chat tables or indexes.+ # SQLite DDL is not transactionally rolled back by Alembic, so discovering+ # an incompatible constraint later would otherwise leave a partially+ # upgraded schema even though the revision remains at 0009.+ research_history_exists = inspector.has_table("research_history")+ chat_session_fk_exists = False+ if research_history_exists:+ chat_session_fk_exists = _fk_exists(+ "research_history",+ "fk_research_history_chat_session_id",+ ["chat_session_id"],+ "chat_sessions",+ ["id"],+ "SET NULL",+ )+# --- chat_sessions table ---if not inspector.has_table("chat_sessions"):op.create_table(@@ -246,7 +385,7 @@ def upgrade():# pre-0001 point with a hand-crafted DB that doesn't include# research_history. Real fresh-install and upgrade paths both have# it, so the guard only no-ops on those synthetic fixtures.- if inspector.has_table("research_history"):+ if research_history_exists:if not _column_exists("research_history", "chat_session_id"):op.add_column("research_history",@@ -261,9 +400,7 @@ def upgrade():"research_history",["chat_session_id"],)- if not _fk_exists(- "research_history", "fk_research_history_chat_session_id"- ):+ if not chat_session_fk_exists:with op.batch_alter_table("research_history", schema=None) as batch_op:@@ -315,7 +452,7 @@ def upgrade():# SQLite supports partial indexes since 3.8.0 (2014); project# floor is Python >= 3.12 which bundles SQLite >= 3.39._idx_name = "ux_research_history_chat_session_in_progress"- if inspector.has_table("research_history") and not _index_exists(+ if research_history_exists and not _index_exists(_idx_name, "research_history"):op.create_index(diff --git a/src/local_deep_research/journal_quality/db.py b/src/local_deep_research/journal_quality/db.pyindex 0f45c7d172..1fad7ecd3c 100644--- a/src/local_deep_research/journal_quality/db.py+++ b/src/local_deep_research/journal_quality/db.py@@ -31,7 +31,7 @@ import sqlite3import sysimport threadingimport time-from contextlib import contextmanager+from contextlib import closing, contextmanagerfrom pathlib import Pathfrom typing import Iterable, Iterator, Optional@@ -1178,8 +1178,8 @@ def build_db(elapsed = time.time() - startsize_mb = output_path.stat().st_size / (1024 * 1024)- with sqlite3.connect(- f"file:{output_path}?mode=ro&immutable=1", uri=True+ with closing(+ sqlite3.connect(f"file:{output_path}?mode=ro&immutable=1", uri=True)) as _count_conn:source_count = _count_conn.execute("SELECT COUNT(*) FROM sources"diff --git a/src/local_deep_research/utilities/es_utils.py b/src/local_deep_research/utilities/es_utils.pyindex 60a1d14316..ed14063ea5 100644--- a/src/local_deep_research/utilities/es_utils.py+++ b/src/local_deep_research/utilities/es_utils.py@@ -284,16 +284,13 @@ class ElasticsearchManager:str: Document ID if successful, None otherwise"""try:- from langchain_community.document_loaders import (- UnstructuredFileLoader,- )-- # Extract file content and metadata- loader = UnstructuredFileLoader(file_path)- documents = loader.load()+ from unstructured.partition.auto import partition- # Combine all content from the documents- content = "\n\n".join([doc.page_content for doc in documents])+ # This is the same local partitioning + single-document join used+ # by the deprecated LangChain loader, without constructing unused+ # sync and async Unstructured API clients for every indexed file.+ elements = partition(filename=file_path)+ content = "\n\n".join(str(element) for element in elements)# Get the filename for the titlefilename = Path(file_path).name@@ -309,11 +306,11 @@ class ElasticsearchManager:document[title_field] = title# Add metadata if requested- if extract_metadata and documents:- # Include metadata from the first document- document["metadata"] = documents[0].metadata-- # Add file-specific metadata+ if extract_metadata:+ # Legacy UnstructuredFileLoader(mode="single") exposed only+ # file-level metadata. Preserve that behavior for empty files+ # and multi-element documents alike.+ document["metadata"] = {"source": file_path}document["source"] = file_pathdocument["file_extension"] = Path(filename).suffix.lstrip(".")document["filename"] = filename@@ -323,7 +320,8 @@ class ElasticsearchManager:except ImportError:logger.error(- "UnstructuredFileLoader not available. Please install the 'unstructured' package."+ "Unstructured partitioner not available. Please install the "+ "'unstructured' package.")return Noneexcept Exception:diff --git a/src/local_deep_research/web/auth/cleanup_middleware.py b/src/local_deep_research/web/auth/cleanup_middleware.pyindex 3d190ba6c6..2d202cbef7 100644--- a/src/local_deep_research/web/auth/cleanup_middleware.py+++ b/src/local_deep_research/web/auth/cleanup_middleware.py@@ -9,8 +9,8 @@ from flask import sessionfrom loguru import loggerfrom sqlalchemy.exc import OperationalError, PendingRollbackError, TimeoutError+from ...database import session_context as db_session_contextfrom ...database.models import UserActiveResearch-from ...database.session_context import get_g_db_sessionfrom .middleware_optimizer import should_skip_database_middleware@@ -51,7 +51,10 @@ def cleanup_completed_research():if not username:return- db_session = get_g_db_session()+ # Resolve this through the module at call time. Importing the function+ # directly can retain a temporary test patch if this middleware is first+ # imported while another module is exercising the session helper.+ db_session = db_session_context.get_g_db_session()if db_session:try:# Find completed researches that haven't been cleaned updiff --git a/tests/api_tests_with_login/package.json b/tests/api_tests_with_login/package.jsonindex 2c675781e9..b3663d02e8 100644--- a/tests/api_tests_with_login/package.json+++ b/tests/api_tests_with_login/package.json@@ -30,5 +30,8 @@"chai": "^6.2.2","mocha": "^11.7.6","puppeteer": "^25.3.0"+ },+ "allowScripts": {+ "puppeteer": false}}diff --git a/tests/auth_tests/test_auth_integration.py b/tests/auth_tests/test_auth_integration.pyindex 3bea48f26d..dc817ff6b7 100644--- a/tests/auth_tests/test_auth_integration.py+++ b/tests/auth_tests/test_auth_integration.py@@ -59,6 +59,10 @@ def app(temp_data_dir, monkeypatch):app.config["TESTING"] = Trueapp.config["WTF_CSRF_ENABLED"] = Falseapp.config["SESSION_COOKIE_SECURE"] = False+ monkeypatch.setattr(+ "local_deep_research.web.auth.routes._perform_post_login_tasks",+ lambda _username, _password: None,+ )yield appdiff --git a/tests/auth_tests/test_auth_rate_limiting.py b/tests/auth_tests/test_auth_rate_limiting.pyindex 61145eb9d1..5a47869308 100644--- a/tests/auth_tests/test_auth_rate_limiting.py+++ b/tests/auth_tests/test_auth_rate_limiting.py@@ -51,6 +51,10 @@ class TestAuthRateLimiting:# Reset limiter storage between tests to prevent cross-test pollutionlimiter.reset()+ monkeypatch.setattr(+ "local_deep_research.web.auth.routes._perform_post_login_tasks",+ lambda _username, _password: None,+ )yield appdiff --git a/tests/auth_tests/test_auth_routes.py b/tests/auth_tests/test_auth_routes.pyindex 57d5f82f90..2913330878 100644--- a/tests/auth_tests/test_auth_routes.py+++ b/tests/auth_tests/test_auth_routes.py@@ -53,6 +53,14 @@ def app(temp_data_dir, monkeypatch):app.config["WTF_CSRF_ENABLED"] = Falseapp.config["SESSION_COOKIE_SECURE"] = False # For testing without HTTPS+ # This module tests synchronous auth responses. The post-login worker has+ # dedicated coverage elsewhere and must not outlive this fixture's engine+ # teardown, which would leave its SQLite connections for delayed GC.+ monkeypatch.setattr(+ "local_deep_research.web.auth.routes._perform_post_login_tasks",+ lambda _username, _password: None,+ )+# Initialize auth databaseinit_auth_database()diff --git a/tests/auth_tests/test_encrypted_db.py b/tests/auth_tests/test_encrypted_db.pyindex e8a550d1c4..da780de0ff 100644--- a/tests/auth_tests/test_encrypted_db.py+++ b/tests/auth_tests/test_encrypted_db.py@@ -30,7 +30,8 @@ def db_manager(temp_data_dir, monkeypatch):manager = DatabaseManager()manager.data_dir = temp_data_dir / "encrypted_databases"manager.data_dir.mkdir(parents=True, exist_ok=True)- return manager+ yield manager+ manager.close_all_databases()@pytest.fixturediff --git a/tests/auth_tests/test_sqlcipher_compatibility.py b/tests/auth_tests/test_sqlcipher_compatibility.pyindex 35b6cff0e6..a95dda4920 100644--- a/tests/auth_tests/test_sqlcipher_compatibility.py+++ b/tests/auth_tests/test_sqlcipher_compatibility.py@@ -50,7 +50,8 @@ def db_manager(temp_data_dir, monkeypatch):manager = DatabaseManager()manager.data_dir = temp_data_dir / "encrypted_databases"manager.data_dir.mkdir(parents=True, exist_ok=True)- return manager+ yield manager+ manager.close_all_databases()@pytest.fixturediff --git a/tests/chat/test_chat_archive_blocked_in_progress.py b/tests/chat/test_chat_archive_blocked_in_progress.pyindex 06b225054e..1c31cbbf69 100644--- a/tests/chat/test_chat_archive_blocked_in_progress.py+++ b/tests/chat/test_chat_archive_blocked_in_progress.py@@ -17,6 +17,7 @@ silent side effects on running computation."""import uuid+from contextlib import contextmanagerfrom unittest.mock import patchimport pytest@@ -61,11 +62,16 @@ def _seed_session_and_research(db, status: str):def _run_archive(SessionLocal, service, session_id):"""Drive ``archive_session`` against the test SessionLocal."""++ @contextmanager+ def _managed_test_session():+ with SessionLocal() as db:+ yield db+with patch(- "src.local_deep_research.chat.service.get_user_db_session"- ) as ctx:- ctx.return_value.__enter__.return_value = SessionLocal()- ctx.return_value.__exit__.return_value = False+ "src.local_deep_research.chat.service.get_user_db_session",+ side_effect=lambda *_args, **_kwargs: _managed_test_session(),+ ):return service.archive_session(session_id)diff --git a/tests/chat/test_chat_attempt_delete_retry.py b/tests/chat/test_chat_attempt_delete_retry.pyindex 35848569b4..75b7f32154 100644--- a/tests/chat/test_chat_attempt_delete_retry.py+++ b/tests/chat/test_chat_attempt_delete_retry.py@@ -57,11 +57,16 @@ def _service_db(SessionLocal):DB from ``setup_database_for_all_tests`` is a plain SQLite file.Same pattern as ``tests/chat/test_chat_delete_terminates_research.py``."""++ @contextmanager+ def _managed_test_session():+ with SessionLocal() as db:+ yield db+with patch(- "src.local_deep_research.chat.service.get_user_db_session"- ) as ctx:- ctx.return_value.__enter__.return_value = SessionLocal()- ctx.return_value.__exit__.return_value = False+ "src.local_deep_research.chat.service.get_user_db_session",+ side_effect=lambda *_args, **_kwargs: _managed_test_session(),+ ):yielddiff --git a/tests/chat/test_chat_delete_terminates_research.py b/tests/chat/test_chat_delete_terminates_research.pyindex c5861b3f7b..d2d687b35f 100644--- a/tests/chat/test_chat_delete_terminates_research.py+++ b/tests/chat/test_chat_delete_terminates_research.py@@ -24,6 +24,7 @@ on call args without needing a real worker thread."""import uuid+from contextlib import contextmanagerfrom unittest.mock import patchfrom src.local_deep_research.chat.service import ChatService@@ -61,6 +62,22 @@ def _seed_session_and_research(db, username: str, status: str):return session_id, research_id+@contextmanager+def _patched_service_db(SessionLocal):+ """Route service DB access through a session that always closes."""++ @contextmanager+ def _managed_test_session():+ with SessionLocal() as db:+ yield db++ with patch(+ "src.local_deep_research.chat.service.get_user_db_session",+ side_effect=lambda *_args, **_kwargs: _managed_test_session(),+ ):+ yield++def test_delete_session_flags_in_progress_research_for_termination(setup_database_for_all_tests,):@@ -90,12 +107,8 @@ def test_delete_session_flags_in_progress_research_for_termination("src.local_deep_research.chat.service.set_termination_flag",side_effect=_capture,),- patch(- "src.local_deep_research.chat.service.get_user_db_session"- ) as ctx,+ _patched_service_db(SessionLocal),):- ctx.return_value.__enter__.return_value = SessionLocal()- ctx.return_value.__exit__.return_value = Falseassert service.delete_session(session_id) is Trueassert flagged == [research_id], (@@ -126,12 +139,8 @@ def test_delete_session_skips_completed_research(setup_database_for_all_tests):"src.local_deep_research.chat.service.set_termination_flag",side_effect=lambda rid: flagged.append(rid),),- patch(- "src.local_deep_research.chat.service.get_user_db_session"- ) as ctx,+ _patched_service_db(SessionLocal),):- ctx.return_value.__enter__.return_value = SessionLocal()- ctx.return_value.__exit__.return_value = Falseassert service.delete_session(session_id) is Trueassert flagged == [], (@@ -154,12 +163,8 @@ def test_delete_session_returns_false_for_missing_session("src.local_deep_research.chat.service.set_termination_flag",side_effect=lambda rid: flagged.append(rid),),- patch(- "src.local_deep_research.chat.service.get_user_db_session"- ) as ctx,+ _patched_service_db(SessionLocal),):- ctx.return_value.__enter__.return_value = SessionLocal()- ctx.return_value.__exit__.return_value = Falseresult = service.delete_session(str(uuid.uuid4()))assert result is Falsediff --git a/tests/conftest.py b/tests/conftest.pyindex 0c14550306..0d02358f24 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -278,6 +278,13 @@ def app(temp_data_dir, monkeypatch):# Tests that need HTTPS should explicitly set environ_base={"wsgi.url_scheme": "https"}app.config["PREFERRED_URL_SCHEME"] = "http"+ # Request tests exercise synchronous login behavior. Post-login background+ # work has dedicated tests and must not race this fixture's DB teardown.+ monkeypatch.setattr(+ "local_deep_research.web.auth.routes._perform_post_login_tasks",+ lambda _username, _password: None,+ )+# Initialize auth database in test directoryinit_auth_database()@@ -306,6 +313,10 @@ def app_with_csrf(temp_data_dir, monkeypatch):# Deliberately do NOT disable CSRF — this fixture exists to verify it.app.config["SESSION_COOKIE_SECURE"] = Falseapp.config["PREFERRED_URL_SCHEME"] = "http"+ monkeypatch.setattr(+ "local_deep_research.web.auth.routes._perform_post_login_tasks",+ lambda _username, _password: None,+ )init_auth_database()return appdiff --git a/tests/database/backup/test_backup_service.py b/tests/database/backup/test_backup_service.pyindex ca2eb172db..297351de98 100644--- a/tests/database/backup/test_backup_service.py+++ b/tests/database/backup/test_backup_service.py@@ -1,5 +1,6 @@"""Tests for backup service functionality."""+from contextlib import closingimport osimport threadingimport time@@ -3736,10 +3737,10 @@ class TestBackupEncryptionVerification:# Try to open with standard sqlite3 (not SQLCipher)with pytest.raises(sqlite3.DatabaseError) as exc_info:- std_conn = sqlite3.connect(str(backup_path))- std_cursor = std_conn.cursor()- std_cursor.execute("SELECT * FROM sqlite_master")- std_cursor.fetchall()+ with closing(sqlite3.connect(str(backup_path))) as std_conn:+ std_cursor = std_conn.cursor()+ std_cursor.execute("SELECT * FROM sqlite_master")+ std_cursor.fetchall()# Standard SQLite returns "file is not a database" for encrypted filesassert "not a database" in str(exc_info.value).lower(), (diff --git a/tests/database/test_migration_0010.py b/tests/database/test_migration_0010.pyindex 8c270443bc..86bdd92979 100644--- a/tests/database/test_migration_0010.py+++ b/tests/database/test_migration_0010.py@@ -20,12 +20,15 @@ Tests cover:- Downgrade is NotImplementedError."""+from importlib import import_module+import warnings+import pytestfrom alembic import commandfrom sqlalchemy import create_engine, event, inspectfrom sqlalchemy import text-from sqlalchemy.exc import IntegrityError+from sqlalchemy.exc import IntegrityError, SAWarningfrom local_deep_research.database.alembic_runner import (get_alembic_config,@@ -35,6 +38,9 @@ from local_deep_research.database.alembic_runner import (_PARTIAL_UNIQUE_INDEX_NAME = "ux_research_history_chat_session_in_progress"+_MIGRATION_MODULE = (+ "local_deep_research.database.migrations.versions.0010_add_chat_tables"+)def _run_downgrade_to(engine, revision):@@ -44,6 +50,37 @@ def _run_downgrade_to(engine, revision):command.downgrade(config, revision)+def _create_research_history_with_fk(+ engine,+ *,+ constraint_name="fk_research_history_chat_session_id",+ local_column="chat_session_id",+ referred_table="chat_sessions",+ ondelete="SET NULL",+):+ columns = [+ "id TEXT PRIMARY KEY",+ "query TEXT NOT NULL",+ "mode TEXT NOT NULL",+ "status TEXT NOT NULL",+ "created_at TEXT NOT NULL",+ "chat_session_id TEXT",+ ]+ if local_column != "chat_session_id":+ columns.append(f"{local_column} TEXT")+ constraint_prefix = (+ f"CONSTRAINT {constraint_name} " if constraint_name is not None else ""+ )+ columns.append(+ f"{constraint_prefix}FOREIGN KEY({local_column}) "+ f"REFERENCES {referred_table}(id) ON DELETE {ondelete}"+ )+ with engine.begin() as conn:+ conn.execute(+ text(f"CREATE TABLE research_history ({', '.join(columns)})")+ )++@pytest.fixturedef fresh_engine(tmp_path):db_path = tmp_path / "fresh_0010.db"@@ -105,6 +142,25 @@ class TestSchemaShape:assert "chat_session_id" in colsassert "step_count" in cols+ def test_research_history_has_exactly_one_chat_session_fk(+ self, fully_migrated_engine+ ):+ """The create_all FK and migration guard must not produce duplicates."""+ with fully_migrated_engine.connect() as conn:+ rows = conn.execute(+ text("PRAGMA foreign_key_list(research_history)")+ ).mappings()+ chat_fks = [+ row+ for row in rows+ if row["from"] == "chat_session_id"+ and row["table"] == "chat_sessions"+ and row["to"] == "id"+ ]++ assert len(chat_fks) == 1+ assert chat_fks[0]["on_delete"] == "SET NULL"+def test_chat_progress_steps_unique_per_research_seq(self, fully_migrated_engine):@@ -142,6 +198,61 @@ class TestSchemaShape:]+ ("actual_ondelete", "should_raise"),+ [+ ("SET NULL", False),+ ("set null", False),+ ("CASCADE", True),+ (None, True),+ ],+)+def test_fk_guard_requires_matching_delete_action(+ monkeypatch, actual_ondelete, should_raise+):+ """Matching FK endpoints are insufficient when delete behavior differs."""+ migration = import_module(_MIGRATION_MODULE)+ options = (+ {"ondelete": actual_ondelete} if actual_ondelete is not None else {}+ )++ class _Inspector:+ @staticmethod+ def has_table(_table_name):+ return True++ @staticmethod+ def get_foreign_keys(_table_name):+ return [+ {+ "name": None,+ "constrained_columns": ["chat_session_id"],+ "referred_table": "chat_sessions",+ "referred_columns": ["id"],+ "options": options,+ }+ ]++ monkeypatch.setattr(migration.op, "get_bind", lambda: object())+ monkeypatch.setattr(migration, "inspect", lambda _bind: _Inspector())++ def _check_fk():+ return migration._fk_exists(+ "research_history",+ "fk_research_history_chat_session_id",+ ["chat_session_id"],+ "chat_sessions",+ ["id"],+ "SET NULL",+ )++ if should_raise:+ with pytest.raises(RuntimeError, match="expected SET NULL"):+ _check_fk()+ else:+ assert _check_fk() is True++class TestIdempotency:"""Re-running migrations on a head DB is a no-op."""@@ -179,8 +290,8 @@ class TestExistingDataBackfill:the DB at 0009 so 0010 forward runs the actual ADD COLUMN path."""- def test_step_count_backfilled_for_existing_rows(self, tmp_path):- engine = create_engine(f"sqlite:///{tmp_path}/m.db")+ def test_step_count_backfilled_for_existing_rows(self, fresh_engine):+ engine = fresh_engine# Hand-build pre-0010 research_history (subset of NOT NULL cols).with engine.begin() as conn:@@ -225,6 +336,384 @@ class TestExistingDataBackfill:assert row.step_count == 0assert row.chat_session_id is None+ def test_wrong_existing_fk_action_fails_without_duplicate(self, tmp_path):+ """An unsupported FK variant must fail instead of adding a second FK."""+ engine = create_engine(f"sqlite:///{tmp_path}/wrong_fk_action.db")++ @event.listens_for(engine, "connect")+ def _enable_fk(dbapi_connection, _):+ dbapi_connection.execute("PRAGMA foreign_keys = ON")++ try:+ _create_research_history_with_fk(+ engine, constraint_name="wrong_action", ondelete="CASCADE"+ )++ stamp_database(engine, "0009")+ with pytest.raises(RuntimeError, match="expected SET NULL"):+ run_migrations(engine, target="0010")++ with engine.connect() as conn:+ rows = list(+ conn.execute(+ text("PRAGMA foreign_key_list(research_history)")+ ).mappings()+ )++ assert len(rows) == 1+ assert rows[0]["on_delete"] == "CASCADE"+ assert inspect(engine).has_table("chat_sessions") is False+ with engine.connect() as conn:+ assert (+ conn.exec_driver_sql("PRAGMA foreign_keys").scalar_one()+ == 1+ )+ finally:+ engine.dispose()++ def test_unnamed_fk_to_wrong_table_fails_before_chat_ddl(self, tmp_path):+ """An unnamed FK on the target column must still match endpoints."""+ engine = create_engine(f"sqlite:///{tmp_path}/wrong_unnamed_fk.db")+ try:+ _create_research_history_with_fk(+ engine,+ constraint_name=None,+ referred_table="other_sessions",+ )+ stamp_database(engine, "0009")++ with pytest.raises(RuntimeError, match="wrong endpoints"):+ run_migrations(engine, target="0010")++ assert inspect(engine).has_table("chat_sessions") is False+ finally:+ engine.dispose()++ def test_duplicate_equivalent_fks_fail_before_reflection_warning(+ self, tmp_path+ ):+ """A partial prior upgrade must not hide a duplicate FK."""+ engine = create_engine(f"sqlite:///{tmp_path}/duplicate_fks.db")+ try:+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TABLE research_history ("+ "id TEXT PRIMARY KEY, "+ "query TEXT NOT NULL, "+ "mode TEXT NOT NULL, "+ "status TEXT NOT NULL, "+ "created_at TEXT NOT NULL, "+ "chat_session_id TEXT, "+ "FOREIGN KEY(chat_session_id) "+ "REFERENCES chat_sessions(id) ON DELETE SET NULL, "+ "CONSTRAINT fk_research_history_chat_session_id "+ "FOREIGN KEY(chat_session_id) "+ "REFERENCES chat_sessions(id) ON DELETE SET NULL"+ ")"+ )+ )+ stamp_database(engine, "0009")++ with warnings.catch_warnings():+ warnings.simplefilter("error", SAWarning)+ with pytest.raises(RuntimeError, match="more than one"):+ run_migrations(engine, target="0010")++ assert inspect(engine).has_table("chat_sessions") is False+ finally:+ engine.dispose()++ def test_correct_named_fk_is_accepted(self, tmp_path):+ engine = create_engine(f"sqlite:///{tmp_path}/correct_named_fk.db")+ try:+ _create_research_history_with_fk(engine)+ stamp_database(engine, "0009")++ run_migrations(engine, target="0010")++ assert inspect(engine).has_table("chat_sessions")+ finally:+ engine.dispose()++ def test_fk_restore_failure_invalidates_connection_without_masking(+ self, tmp_path+ ):+ engine = create_engine(f"sqlite:///{tmp_path}/fk_restore_failure.db")++ @event.listens_for(engine, "connect")+ def _enable_fk(dbapi_connection, _):+ dbapi_connection.execute("PRAGMA foreign_keys = ON")++ try:+ _create_research_history_with_fk(+ engine, constraint_name="wrong_action", ondelete="CASCADE"+ )+ stamp_database(engine, "0009")+ restore_attempted = False++ @event.listens_for(engine, "before_cursor_execute")+ def _fail_fk_restore(+ _conn, _cursor, statement, _parameters, _context, _executemany+ ):+ nonlocal restore_attempted+ if statement.strip().upper() == "PRAGMA FOREIGN_KEYS = ON":+ restore_attempted = True+ raise RuntimeError("injected FK restore failure")++ with pytest.raises(RuntimeError, match="expected SET NULL"):+ run_migrations(engine, target="0010")++ assert restore_attempted is True+ with engine.connect() as conn:+ assert (+ conn.exec_driver_sql("PRAGMA foreign_keys").scalar_one()+ == 1+ )+ finally:+ engine.dispose()++ @pytest.mark.parametrize("restore_failure", ["raises", "ignored"])+ def test_successful_upgrade_restore_failure_invalidates_connection(+ self, tmp_path, restore_failure+ ):+ """A committed upgrade must not pool an FK-disabled connection."""+ engine = create_engine(+ f"sqlite:///{tmp_path}/successful_restore_{restore_failure}.db"+ )++ @event.listens_for(engine, "connect")+ def _enable_fk(dbapi_connection, _):+ dbapi_connection.execute("PRAGMA foreign_keys = ON")++ @event.listens_for(engine, "before_cursor_execute")+ def _break_final_fk_restore(+ _conn, cursor, statement, _parameters, _context, _executemany+ ):+ if statement.strip().upper() != "PRAGMA FOREIGN_KEYS = ON":+ return+ if restore_failure == "raises":+ raise RuntimeError("injected successful FK restore failure")+ # SQLite silently ignores the following PRAGMA while this+ # DBAPI-level transaction is active.+ cursor.execute("BEGIN")++ expected = (+ "injected successful FK restore failure"+ if restore_failure == "raises"+ else "foreign-key enforcement remained disabled"+ )+ try:+ with pytest.raises(RuntimeError, match=expected):+ run_migrations(engine)++ # The schema committed before restoration failed. A retry therefore+ # takes the already-at-head fast path and cannot repair a pooled+ # handle; correctness depends on invalidating it above.+ run_migrations(engine)+ with engine.connect() as conn:+ assert (+ conn.exec_driver_sql("PRAGMA foreign_keys").scalar_one()+ == 1+ )+ finally:+ engine.dispose()++ def test_keyboard_interrupt_restores_fk_before_pool_return(+ self, tmp_path, monkeypatch+ ):+ engine = create_engine(f"sqlite:///{tmp_path}/fk_interrupt.db")++ @event.listens_for(engine, "connect")+ def _enable_fk(dbapi_connection, _):+ dbapi_connection.execute("PRAGMA foreign_keys = ON")++ def _interrupt_upgrade(*_args, **_kwargs):+ raise KeyboardInterrupt++ monkeypatch.setattr(command, "upgrade", _interrupt_upgrade)+ try:+ with pytest.raises(KeyboardInterrupt):+ run_migrations(engine)++ with engine.connect() as conn:+ assert (+ conn.exec_driver_sql("PRAGMA foreign_keys").scalar_one()+ == 1+ )+ finally:+ engine.dispose()++ def test_cancellation_during_cleanup_is_not_masked(+ self, tmp_path, monkeypatch+ ):+ runner = import_module("local_deep_research.database.alembic_runner")+ engine = create_engine(f"sqlite:///{tmp_path}/cleanup_interrupt.db")++ @event.listens_for(engine, "connect")+ def _enable_fk(dbapi_connection, _):+ dbapi_connection.execute("PRAGMA foreign_keys = ON")++ def _fail_upgrade(*_args, **_kwargs):+ raise RuntimeError("injected migration failure")++ def _interrupt_cleanup(conn):+ conn.invalidate()+ raise KeyboardInterrupt++ monkeypatch.setattr(command, "upgrade", _fail_upgrade)+ monkeypatch.setattr(+ runner, "_restore_fk_after_migration", _interrupt_cleanup+ )+ try:+ with pytest.raises(KeyboardInterrupt):+ run_migrations(engine)++ with engine.connect() as conn:+ assert (+ conn.exec_driver_sql("PRAGMA foreign_keys").scalar_one()+ == 1+ )+ finally:+ engine.dispose()++ def test_real_cleanup_interrupt_invalidates_connection(+ self, tmp_path, monkeypatch+ ):+ """Cancellation inside the real restore helper cannot pool FK OFF."""+ engine = create_engine(+ f"sqlite:///{tmp_path}/real_cleanup_interrupt.db"+ )++ @event.listens_for(engine, "connect")+ def _enable_fk(dbapi_connection, _):+ dbapi_connection.execute("PRAGMA foreign_keys = ON")++ def _fail_upgrade(*_args, **_kwargs):+ raise RuntimeError("injected migration failure")++ restore_interrupted = False++ @event.listens_for(engine, "before_cursor_execute")+ def _interrupt_real_restore(+ _conn, _cursor, statement, _parameters, _context, _executemany+ ):+ nonlocal restore_interrupted+ if (+ not restore_interrupted+ and statement.strip().upper() == "PRAGMA FOREIGN_KEYS = ON"+ ):+ restore_interrupted = True+ raise KeyboardInterrupt++ monkeypatch.setattr(command, "upgrade", _fail_upgrade)+ try:+ with pytest.raises(KeyboardInterrupt):+ run_migrations(engine)++ assert restore_interrupted is True+ with engine.connect() as conn:+ assert (+ conn.exec_driver_sql("PRAGMA foreign_keys").scalar_one()+ == 1+ )+ finally:+ engine.dispose()++ def test_disable_fk_aborts_if_explicit_begin_ignores_toggle(+ self, tmp_path, monkeypatch+ ):+ """Never call Alembic when SQLite did not accept PRAGMA FK OFF."""+ engine = create_engine(f"sqlite:///{tmp_path}/explicit_begin.db")++ @event.listens_for(engine, "connect")+ def _configure_explicit_begin(dbapi_connection, _):+ dbapi_connection.isolation_level = None+ dbapi_connection.execute("PRAGMA foreign_keys = ON")++ @event.listens_for(engine, "begin")+ def _begin_explicitly(conn):+ conn.exec_driver_sql("BEGIN")++ upgrade_called = False++ def _record_upgrade(*_args, **_kwargs):+ nonlocal upgrade_called+ upgrade_called = True++ monkeypatch.setattr(command, "upgrade", _record_upgrade)+ try:+ with pytest.raises(RuntimeError, match="remained enabled"):+ run_migrations(engine)++ assert upgrade_called is False+ with engine.connect() as conn:+ assert (+ conn.exec_driver_sql("PRAGMA foreign_keys").scalar_one()+ == 1+ )+ finally:+ engine.dispose()++ def test_disable_failure_restores_fk_before_pool_return(+ self, tmp_path, monkeypatch+ ):+ runner = import_module("local_deep_research.database.alembic_runner")+ engine = create_engine(f"sqlite:///{tmp_path}/fk_disable_failure.db")++ @event.listens_for(engine, "connect")+ def _enable_fk(dbapi_connection, _):+ dbapi_connection.execute("PRAGMA foreign_keys = ON")++ original_disable = runner._disable_fk_for_migration++ def _disable_then_fail(conn):+ original_disable(conn)+ raise RuntimeError("injected post-disable failure")++ monkeypatch.setattr(+ runner, "_disable_fk_for_migration", _disable_then_fail+ )+ try:+ with pytest.raises(RuntimeError, match="post-disable failure"):+ run_migrations(engine)++ with engine.connect() as conn:+ assert (+ conn.exec_driver_sql("PRAGMA foreign_keys").scalar_one()+ == 1+ )+ finally:+ engine.dispose()++ @pytest.mark.parametrize(+ ("local_column", "ondelete", "message"),+ [+ ("chat_session_id", "CASCADE", "expected SET NULL"),+ ("other_id", "SET NULL", "wrong endpoints"),+ ],+ )+ def test_expected_fk_name_does_not_bypass_signature_validation(+ self, tmp_path, local_column, ondelete, message+ ):+ engine = create_engine(+ f"sqlite:///{tmp_path}/named_fk_mismatch_{local_column}.db"+ )+ try:+ _create_research_history_with_fk(+ engine,+ local_column=local_column,+ ondelete=ondelete,+ )+ stamp_database(engine, "0009")++ with pytest.raises(RuntimeError, match=message):+ run_migrations(engine, target="0010")++ assert inspect(engine).has_table("chat_sessions") is False+ finally:+ engine.dispose()+# ---------------------------------------------------------------------------# Partial unique index: at-most-one-in-progress per chat_session_iddiff --git a/tests/database/test_migration_0022_note_references.py b/tests/database/test_migration_0022_note_references.pyindex 5671fa72ef..221fda98d1 100644--- a/tests/database/test_migration_0022_note_references.py+++ b/tests/database/test_migration_0022_note_references.py@@ -34,7 +34,10 @@ def engine():dbapi_conn.execute("PRAGMA foreign_keys=ON")Base.metadata.create_all(eng)- return eng+ try:+ yield eng+ finally:+ eng.dispose()@pytest.fixturediff --git a/tests/database/test_multiuser_db.py b/tests/database/test_multiuser_db.pyindex f508b4d264..25b0309ad7 100644--- a/tests/database/test_multiuser_db.py+++ b/tests/database/test_multiuser_db.py@@ -35,7 +35,10 @@ class TestMultiUserDatabase:manager = DatabaseManager()manager.data_dir = Path(temp_dir) / "encrypted_databases"manager.data_dir.mkdir(parents=True, exist_ok=True)- yield manager+ try:+ yield manager+ finally:+ manager.close_all_databases()@pytest.fixturedef mock_auth_db(self, monkeypatch):diff --git a/tests/database/test_post_login_settings_atomicity.py b/tests/database/test_post_login_settings_atomicity.pyindex dee80c2d7a..f436c05897 100644--- a/tests/database/test_post_login_settings_atomicity.py+++ b/tests/database/test_post_login_settings_atomicity.py@@ -268,31 +268,41 @@ class TestCheckedOutConnectionSurvivesDispose:t = threading.Thread(target=writer, daemon=True)t.start()-- assert writer_ready.wait(timeout=5.0), (- f"writer did not start; result={writer_result}"- )- engine.dispose()- main_disposed.set()- t.join(timeout=10.0)- assert not t.is_alive(), "writer thread did not finish"-- assert writer_result.get("ok") is True, (- "engine.dispose() must NOT break a thread holding a "- "checked-out connection — if this fires, either SA 2.0 "- "semantics changed or SQLCipher introduced a hook that "- "violates them. Error: "- f"{writer_result.get('error')}"- )-- Session = sessionmaker(bind=engine)- with Session() as s:- row = s.query(Setting).filter(Setting.key == key).first()- assert row is not None, (- "writer's committed row must be readable from a fresh "- "session after dispose"+ retired_pool = None+ try:+ assert writer_ready.wait(timeout=5.0), (+ f"writer did not start; result={writer_result}"+ )+ retired_pool = engine.pool+ engine.dispose()+ main_disposed.set()+ t.join(timeout=10.0)+ assert not t.is_alive(), "writer thread did not finish"++ assert writer_result.get("ok") is True, (+ "engine.dispose() must NOT break a thread holding a "+ "checked-out connection — if this fires, either SA 2.0 "+ "semantics changed or SQLCipher introduced a hook that "+ "violates them. Error: "+ f"{writer_result.get('error')}")- assert row.value == f"value_{iteration}"++ Session = sessionmaker(bind=engine)+ with Session() as s:+ row = s.query(Setting).filter(Setting.key == key).first()+ assert row is not None, (+ "writer's committed row must be readable from a fresh "+ "session after dispose"+ )+ assert row.value == f"value_{iteration}"+ finally:+ main_disposed.set()+ t.join(timeout=10.0)+ if retired_pool is not None:+ # The checked-out connection returns to the pre-dispose pool,+ # which is no longer reachable from ``engine``. Dispose that+ # retired pool explicitly after the writer checks it back in.+ retired_pool.dispose()def test_dispose_without_checked_out_connections_is_noop_for_clients(self, user_enginediff --git a/tests/database/test_queue_service.py b/tests/database/test_queue_service.pyindex 06590c0ec7..afcb781e8b 100644--- a/tests/database/test_queue_service.py+++ b/tests/database/test_queue_service.py@@ -10,8 +10,9 @@ Tests cover:- Task cleanup"""-from unittest.mock import Mock+from contextlib import contextmanagerfrom datetime import datetime, UTC+from unittest.mock import Mockclass TestUserQueueServiceInit:@@ -365,6 +366,7 @@ class TestProcessingToQueuedRevert:"""@staticmethod+ @contextmanagerdef _service():from sqlalchemy import create_enginefrom sqlalchemy.orm import sessionmaker@@ -380,36 +382,40 @@ class TestProcessingToQueuedRevert:QueueStatus.__table__.create(engine)TaskMetadata.__table__.create(engine)session = sessionmaker(bind=engine)()- return UserQueueService(session)+ try:+ yield UserQueueService(session)+ finally:+ session.close()+ engine.dispose()def test_processing_then_queued_round_trips_counts(self):- svc = self._service()- svc.add_task_metadata("r1", "research") # queued 1 / active 0- assert svc.get_queue_status()["queued_tasks"] == 1- assert svc.get_queue_status()["active_tasks"] == 0-- svc.update_task_status("r1", "processing") # queued 0 / active 1- s = svc.get_queue_status()- assert s["queued_tasks"] == 0- assert s["active_tasks"] == 1-- svc.update_task_status("r1", "queued") # reverted: queued 1 / active 0- s = svc.get_queue_status()- assert s["queued_tasks"] == 1, (- "queued->processing claim must be reverted on re-queue"- )- assert s["active_tasks"] == 0, (- "active slot must not leak after a capacity re-queue"- )+ with self._service() as svc:+ svc.add_task_metadata("r1", "research") # queued 1 / active 0+ assert svc.get_queue_status()["queued_tasks"] == 1+ assert svc.get_queue_status()["active_tasks"] == 0++ svc.update_task_status("r1", "processing") # queued 0 / active 1+ s = svc.get_queue_status()+ assert s["queued_tasks"] == 0+ assert s["active_tasks"] == 1++ svc.update_task_status("r1", "queued") # queued 1 / active 0+ s = svc.get_queue_status()+ assert s["queued_tasks"] == 1, (+ "queued->processing claim must be reverted on re-queue"+ )+ assert s["active_tasks"] == 0, (+ "active slot must not leak after a capacity re-queue"+ )def test_repeated_capacity_rejects_do_not_drift(self):"""Three processing->queued cycles (simulating capacity retries)must leave the counter exactly where it started."""- svc = self._service()- svc.add_task_metadata("r1", "research")- for _ in range(3):- svc.update_task_status("r1", "processing")- svc.update_task_status("r1", "queued")- s = svc.get_queue_status()- assert s["queued_tasks"] == 1- assert s["active_tasks"] == 0+ with self._service() as svc:+ svc.add_task_metadata("r1", "research")+ for _ in range(3):+ svc.update_task_status("r1", "processing")+ svc.update_task_status("r1", "queued")+ s = svc.get_queue_status()+ assert s["queued_tasks"] == 1+ assert s["active_tasks"] == 0diff --git a/tests/domain_classifier/test_classifier_edge_cases.py b/tests/domain_classifier/test_classifier_edge_cases.pyindex 2121f4257f..64421e304b 100644--- a/tests/domain_classifier/test_classifier_edge_cases.py+++ b/tests/domain_classifier/test_classifier_edge_cases.py@@ -8,6 +8,7 @@ Covers gaps not addressed by existing tests:- classify_all_domains URL parsing and www stripping"""+from contextlib import contextmanagerfrom unittest.mock import MagicMock, patchfrom local_deep_research.domain_classifier.classifier import (@@ -179,6 +180,7 @@ class TestGetDomainSamplesEscaping:"""@staticmethod+ @contextmanagerdef _session_with(resources):from sqlalchemy import create_enginefrom sqlalchemy.orm import sessionmaker@@ -189,55 +191,59 @@ class TestGetDomainSamplesEscaping:engine = create_engine("sqlite:///:memory:")Base.metadata.create_all(engine)session = sessionmaker(bind=engine)()- # This bare engine has no foreign_keys PRAGMA (the app enables it- # per-engine in encrypted_db/auth_db, not globally), so the orphan- # research_id values below commit without a real research_history row.- session.add_all(- ResearchResource(- research_id=f"r{i}",- url=url,- title=f"resource {i}",- created_at="2026-01-01T00:00:00",+ try:+ # This bare engine has no foreign_keys PRAGMA (the app enables it+ # per-engine in encrypted_db/auth_db, not globally), so the orphan+ # research_id values below commit without a research_history row.+ session.add_all(+ ResearchResource(+ research_id=f"r{i}",+ url=url,+ title=f"resource {i}",+ created_at="2026-01-01T00:00:00",+ )+ for i, url in enumerate(resources))- for i, url in enumerate(resources)- )- session.commit()- return session+ session.commit()+ yield session+ finally:+ session.close()+ engine.dispose()def test_percent_treated_as_literal(self):"""Sampling domain '100%.com' must not pull '100pages.com' rows."""- session = self._session_with(+ with self._session_with(["https://100%.com/paper", "https://100pages.com/article"]- )- classifier = DomainClassifier(username="test")+ ) as session:+ classifier = DomainClassifier(username="test")- urls = [- s["url"]- for s in classifier._get_domain_samples("100%.com", session)- ]+ urls = [+ s["url"]+ for s in classifier._get_domain_samples("100%.com", session)+ ]- assert "https://100%.com/paper" in urls- assert "https://100pages.com/article" not in urls+ assert "https://100%.com/paper" in urls+ assert "https://100pages.com/article" not in urlsdef test_underscore_treated_as_literal(self):"""Sampling domain 's3_bucket.example.com' must not pull 's3Xbucket…'."""- session = self._session_with(+ with self._session_with(["https://s3_bucket.example.com/a","https://s3Xbucket.example.com/b",]- )- classifier = DomainClassifier(username="test")-- urls = [- s["url"]- for s in classifier._get_domain_samples(- "s3_bucket.example.com", session- )- ]+ ) as session:+ classifier = DomainClassifier(username="test")++ urls = [+ s["url"]+ for s in classifier._get_domain_samples(+ "s3_bucket.example.com", session+ )+ ]- assert "https://s3_bucket.example.com/a" in urls- assert "https://s3Xbucket.example.com/b" not in urls+ assert "https://s3_bucket.example.com/a" in urls+ assert "https://s3Xbucket.example.com/b" not in urlsclass TestBuildClassificationPromptEdgeCases:diff --git a/tests/infrastructure_tests/package.json b/tests/infrastructure_tests/package.jsonindex 4147ab8b82..d602fd78cb 100644--- a/tests/infrastructure_tests/package.json+++ b/tests/infrastructure_tests/package.json@@ -16,6 +16,10 @@"@types/jest": "^30.0.0","jest": "^30.4.2"},+ "allowScripts": {+ "fsevents": false,+ "[email protected]": true+ },"jest": {"testEnvironment": "node","testMatch": [diff --git a/tests/journal_quality/conftest.py b/tests/journal_quality/conftest.pyindex 54ac1e791e..086f8c4f3c 100644--- a/tests/journal_quality/conftest.py+++ b/tests/journal_quality/conftest.py@@ -19,4 +19,7 @@ def ref_db():pytest.skip("journal_quality.db not built — run journal data download first")- return db+ try:+ yield db+ finally:+ db.reset()diff --git a/tests/journal_quality/test_search_like_escaping.py b/tests/journal_quality/test_search_like_escaping.pyindex bf0376107e..789189158b 100644--- a/tests/journal_quality/test_search_like_escaping.py+++ b/tests/journal_quality/test_search_like_escaping.py@@ -14,6 +14,7 @@ use metacharacter-free terms (``"nature"``), so this is the only fail-on-revertcoverage for these two escape sites."""+import pytestfrom sqlalchemy import create_enginefrom sqlalchemy.orm import sessionmaker@@ -47,6 +48,22 @@ def _db_with(sources=(), institutions=()):return db+def journal_db_factory():+ """Create test databases and reset their engines after each test."""+ databases = []++ def _make(*, sources=(), institutions=()):+ db = _db_with(sources=sources, institutions=institutions)+ databases.append(db)+ return db++ yield _make++ for db in reversed(databases):+ db.reset()++def _source(name, name_lower):return Source(name=name,@@ -57,9 +74,9 @@ def _source(name, name_lower):)-def test_journal_search_percent_treated_as_literal():+def test_journal_search_percent_treated_as_literal(journal_db_factory):"""Searching journals for '100%' must not match '100pages'."""- db = _db_with(+ db = journal_db_factory(sources=[_source("Journal 100%", "journal 100%"),_source("Journal 100pages", "journal 100pages"),@@ -72,9 +89,9 @@ def test_journal_search_percent_treated_as_literal():assert "Journal 100pages" not in names-def test_journal_search_underscore_treated_as_literal():+def test_journal_search_underscore_treated_as_literal(journal_db_factory):"""Searching journals for 'a_b' must not match 'aXb'."""- db = _db_with(+ db = journal_db_factory(sources=[_source("Journal a_b", "journal a_b"),_source("Journal aXb", "journal axb"),@@ -87,9 +104,9 @@ def test_journal_search_underscore_treated_as_literal():assert "Journal aXb" not in names-def test_institution_search_underscore_treated_as_literal():+def test_institution_search_underscore_treated_as_literal(journal_db_factory):"""Searching institutions for 'a_b' must not match 'aXb'."""- db = _db_with(+ db = journal_db_factory(institutions=[Institution(openalex_id="I1", name="Univ a_b", name_lower="univ a_b"diff --git a/tests/js/setup.js b/tests/js/setup.jsindex a54cbea8a5..ddb543f92c 100644--- a/tests/js/setup.js+++ b/tests/js/setup.js@@ -14,6 +14,20 @@ globalThis.SafeLogger = {debug: () => {},};+// Match production's standards-mode document so KaTeX does not warn about+// happy-dom's default doctype-less (quirks-mode) test document.+if (!document.doctype) {+ const doctype = document.implementation.createDocumentType('html', '', '');+ document.insertBefore(doctype, document.documentElement);+}+// happy-dom does not currently derive compatMode from an inserted doctype.+if (document.compatMode !== 'CSS1Compat') {+ Object.defineProperty(document, 'compatMode', {+ value: 'CSS1Compat',+ configurable: true,+ });+}+// Load the shared formatting service (window.formatting) — in production// base.html always loads services/formatting.js before any page/component// script, and several of them now delegate to it (e.g.diff --git a/tests/metrics/test_token_counter_coverage.py b/tests/metrics/test_token_counter_coverage.pyindex e872902fb4..43b5c72a79 100644--- a/tests/metrics/test_token_counter_coverage.py+++ b/tests/metrics/test_token_counter_coverage.py@@ -4,6 +4,7 @@ import jsonimport threadingfrom unittest.mock import MagicMock, Mock, patch+import pytestfrom sqlalchemy import create_enginefrom sqlalchemy.orm import sessionmaker@@ -14,6 +15,23 @@ from local_deep_research.metrics.token_counter import ()+def sqlite_session_factory():+ """Create SQLite session factories and dispose their engines per test."""+ engines = []++ def _make():+ engine = create_engine("sqlite:///:memory:")+ engines.append(engine)+ Base.metadata.create_all(engine)+ return sessionmaker(bind=engine)++ yield _make++ for engine in reversed(engines):+ engine.dispose()++def _make_callback(**overrides):"""Create a TokenCountingCallback with sensible defaults."""ctx = overrides.pop(@@ -648,10 +666,10 @@ class TestGetResearchTimelineMetricsCallStackDeserialization:):return counter.get_research_timeline_metrics(research_id)- def test_json_null_call_stack_returned_as_none(self):- engine = create_engine("sqlite:///:memory:")- Base.metadata.create_all(engine)- Session = sessionmaker(bind=engine)+ def test_json_null_call_stack_returned_as_none(+ self, sqlite_session_factory+ ):+ Session = sqlite_session_factory()with Session() as session:self._seed(session, "res-json-null", None)@@ -659,17 +677,17 @@ class TestGetResearchTimelineMetricsCallStackDeserialization:assert len(result["timeline"]) == 1assert result["timeline"][0]["call_stack"] is None- def test_real_call_stack_string_unquoted(self):- engine = create_engine("sqlite:///:memory:")- Base.metadata.create_all(engine)- Session = sessionmaker(bind=engine)+ def test_real_call_stack_string_unquoted(self, sqlite_session_factory):+ Session = sqlite_session_factory()with Session() as session:self._seed(session, "res-real-stack", "a.py:f:1 -> b.py:g:2")result = self._run("res-real-stack", Session)assert result["timeline"][0]["call_stack"] == "a.py:f:1 -> b.py:g:2"- def test_non_string_json_shapes_serialized_back_to_string(self):+ def test_non_string_json_shapes_serialized_back_to_string(+ self, sqlite_session_factory+ ):"""Legacy or out-of-band writes can land numbers, bools, listsor objects in the JSON column. The API contract is `string |null`, so the endpoint must serialize those shapes back to a@@ -681,9 +699,7 @@ class TestGetResearchTimelineMetricsCallStackDeserialization:([1, 2], "[1, 2]"),({"a": 1}, '{"a": 1}'),]:- engine = create_engine("sqlite:///:memory:")- Base.metadata.create_all(engine)- Session = sessionmaker(bind=engine)+ Session = sqlite_session_factory()rid = f"res-{type(stored).__name__}"with Session() as session:self._seed(session, rid, stored)diff --git a/tests/news/test_library_sweep.py b/tests/news/test_library_sweep.pyindex 3a169cc75c..716816b2ad 100644--- a/tests/news/test_library_sweep.py+++ b/tests/news/test_library_sweep.py@@ -18,6 +18,8 @@ from contextlib import contextmanagerfrom datetime import datetime, UTCfrom unittest.mock import MagicMock, patch+import pytest+from local_deep_research.scheduler.background import (_LIBRARY_SWEEP_BATCH,BackgroundJobScheduler,@@ -760,10 +762,11 @@ def _seed_document(return doc-def _real_db_session():+def real_db_session():"""Build an in-memory SQLite session with the library schema created and aSourceType + two collections (a default library + a normal collection)- seeded. Returns (session, source_type_id, default_lib_id, coll_id).+ seeded."""import uuid@@ -798,17 +801,23 @@ def _real_db_session():)session.add_all([st, default_lib, other])session.commit()- return session, st.id, "default-lib", "coll-A"+ try:+ yield session, st.id, "default-lib", "coll-A"+ finally:+ session.close()+ engine.dispose()-def test_case_a_predicate_selects_only_unindexed_with_text_real_db():+def test_case_a_predicate_selects_only_unindexed_with_text_real_db(+ real_db_session,+):"""Finding 2 (a): with a REAL DB, the case-(a) query selects an unindexedin-collection doc with text, and excludes an already-indexed doc and anull-text doc. A wrong predicate (e.g. indexed.is_(True)) fails here."""from local_deep_research.database.models.library import DocumentCollection- session, st_id, default_lib_id, coll_id = _real_db_session()+ session, st_id, default_lib_id, coll_id = real_db_session# Doc 1: unindexed, has text, in coll-A -> SHOULD be selected._seed_document(session, st_id, doc_id="doc-unindexed", text_content="hi")@@ -875,7 +884,7 @@ def test_case_a_predicate_selects_only_unindexed_with_text_real_db():assert "doc-notext" not in indexed_ids-def test_case_b_predicate_selects_research_orphans_real_db():+def test_case_b_predicate_selects_research_orphans_real_db(real_db_session):"""Finding 2 (b): with a REAL DB, the case-(b) outerjoin/predicate selects aresearch orphan (research_id set, text not null, NO default-library link)and excludes a research doc already linked in the default library. Inverting@@ -883,7 +892,7 @@ def test_case_b_predicate_selects_research_orphans_real_db():"""from local_deep_research.database.models.library import DocumentCollection- session, st_id, default_lib_id, coll_id = _real_db_session()+ session, st_id, default_lib_id, coll_id = real_db_session# Orphan: research_id set, text, NO link in default library -> selected._seed_document(@@ -1076,7 +1085,9 @@ def test_orphan_path_error_does_not_leak_password(loguru_caplog_full):# ----------------------------------------------------------------------------def test_case_a_selection_is_randomized_not_deterministic_real_db():+def test_case_a_selection_is_randomized_not_deterministic_real_db(+ real_db_session,+):"""Finding 1: the case-(a) query uses ``order_by(func.random())`` (not astable id order) so a block of permanently-failing low-id rows can't pin theLIMIT slots every tick and starve indexable higher-id rows forever.@@ -1095,7 +1106,7 @@ def test_case_a_selection_is_randomized_not_deterministic_real_db():"""from local_deep_research.database.models.library import DocumentCollection- session, st_id, default_lib_id, coll_id = _real_db_session()+ session, st_id, default_lib_id, coll_id = real_db_session# Seed a pool LARGER than the batch so the LIMIT(BATCH) must subsample it.pool_size = _LIBRARY_SWEEP_BATCH + 25@@ -1165,7 +1176,9 @@ def test_case_a_selection_is_randomized_not_deterministic_real_db():)-def test_case_b_orphan_selection_is_randomized_not_deterministic_real_db():+def test_case_b_orphan_selection_is_randomized_not_deterministic_real_db(+ real_db_session,+):"""Finding 4: case-(b) (research orphans) ALSO uses order_by(func.random())so a block of permanently-failing low-id orphans can't pin the LIMIT slotsevery tick and starve the rest. The case-(a) randomization test above seeds@@ -1176,7 +1189,7 @@ def test_case_b_orphan_selection_is_randomized_not_deterministic_real_db():order_by(Document.id) and this test fails (every draw identical) while thecase-(a) test still passes."""- session, st_id, default_lib_id, coll_id = _real_db_session()+ session, st_id, default_lib_id, coll_id = real_db_session# Seed a pool of research ORPHANS (research_id set, text, and NO# default-library DocumentCollection link) larger than the batch. With nodiff --git a/tests/news/test_subscription_runner.py b/tests/news/test_subscription_runner.pyindex 7439ccb1eb..596c186aaf 100644--- a/tests/news/test_subscription_runner.py+++ b/tests/news/test_subscription_runner.py@@ -35,8 +35,11 @@ def db_session():engine = create_engine("sqlite:///:memory:")NewsSubscription.__table__.create(engine)session = sessionmaker(bind=engine)()- yield session- session.close()+ try:+ yield session+ finally:+ session.close()+ engine.dispose()def _make_sub(session, sub_id, **overrides):diff --git a/tests/notes/test_cross_user_isolation.py b/tests/notes/test_cross_user_isolation.pyindex b6cbdcb034..78af401308 100644--- a/tests/notes/test_cross_user_isolation.py+++ b/tests/notes/test_cross_user_isolation.py@@ -35,7 +35,7 @@ from tests.notes.helpers import _generate_hash@pytest.fixture-def two_user_dbs(monkeypatch):+def two_user_dbs(monkeypatch, request):"""Build two independent in-memory SQLite engines and route``get_user_db_session`` to the right one based on username.@@ -48,48 +48,55 @@ def two_user_dbs(monkeypatch):def _build_engine():engine = create_engine("sqlite:///:memory:")-- @event.listens_for(engine, "connect")- def _set_sqlite_pragma(dbapi_conn, _connection_record):- cursor = dbapi_conn.cursor()- cursor.execute("PRAGMA foreign_keys=ON")- cursor.close()-- Base.metadata.create_all(engine)- return engine+ try:++ @event.listens_for(engine, "connect")+ def _set_sqlite_pragma(dbapi_conn, _connection_record):+ cursor = dbapi_conn.cursor()+ cursor.execute("PRAGMA foreign_keys=ON")+ cursor.close()++ Base.metadata.create_all(engine)+ return engine+ except BaseException:+ # The engine has not yet been returned to the fixture, so no+ # outer cleanup callback can own it on this failure path.+ engine.dispose()+ raiseengine_a = _build_engine()+ request.addfinalizer(engine_a.dispose)engine_b = _build_engine()+ request.addfinalizer(engine_b.dispose)Session = sessionmaker()# Seed both DBs with their own source_type rows so service queries- # that resolve note_source_type_id work.+ # that resolve note_source_type_id work. Context managers also close+ # the sessions when add/commit raises during fixture construction.type_id_a = str(uuid.uuid4())type_id_b = str(uuid.uuid4())- sess_a = Session(bind=engine_a)- sess_a.add(- SourceType(- id=type_id_a,- name="note",- display_name="Note",- description="x",- icon="sticky-note",+ with Session(bind=engine_a) as sess_a:+ sess_a.add(+ SourceType(+ id=type_id_a,+ name="note",+ display_name="Note",+ description="x",+ icon="sticky-note",+ ))- )- sess_a.commit()- sess_a.close()- sess_b = Session(bind=engine_b)- sess_b.add(- SourceType(- id=type_id_b,- name="note",- display_name="Note",- description="x",- icon="sticky-note",+ sess_a.commit()+ with Session(bind=engine_b) as sess_b:+ sess_b.add(+ SourceType(+ id=type_id_b,+ name="note",+ display_name="Note",+ description="x",+ icon="sticky-note",+ ))- )- sess_b.commit()- sess_b.close()+ sess_b.commit()@contextmanagerdef fake_session(username=None, password=None):@@ -109,7 +116,7 @@ def two_user_dbs(monkeypatch):fake_session,)- return {+ yield {"engine_a": engine_a,"engine_b": engine_b,"Session": Session,diff --git a/tests/notes/test_note_models.py b/tests/notes/test_note_models.pyindex ddd065b870..d82cb1ea0b 100644--- a/tests/notes/test_note_models.py+++ b/tests/notes/test_note_models.py@@ -3,6 +3,7 @@import uuidimport pytest+from sqlalchemy.exc import IntegrityErrorfrom local_deep_research.database.models import (Collection,@@ -556,7 +557,11 @@ class TestNoteModels:db_session.add(v1)db_session.commit()- # Try to add duplicate id+ # The duplicate row must reach the database so its PRIMARY KEY+ # constraint is what rejects it. Remove the original object from the+ # identity map first; otherwise SQLAlchemy warns about the deliberate+ # in-session identity conflict before issuing the INSERT.+ db_session.expunge(v1)v1_dup = NoteVersion(id=version_id,document_id=note.id,@@ -567,7 +572,7 @@ class TestNoteModels:)db_session.add(v1_dup)- with pytest.raises(Exception): # IntegrityError+ with pytest.raises(IntegrityError):db_session.commit()def test_note_version_relationship(self, db_session, note_source_type):diff --git a/tests/notes/test_note_service.py b/tests/notes/test_note_service.pyindex 538c33ad31..f5acea9520 100644--- a/tests/notes/test_note_service.py+++ b/tests/notes/test_note_service.py@@ -856,7 +856,7 @@ class TestNoteResearchServiceMethods:query=f"query {i}",mode="quick",status="completed",- created_at=now,+ created_at=now.isoformat(),)patched_session.add(rh)patched_session.commit()@@ -1929,7 +1929,7 @@ class TestPostReviewRegressions:query=f"q{i}",mode="quick",status="completed",- created_at=now,+ created_at=now.isoformat(),))patched_session.commit()@@ -1963,7 +1963,7 @@ class TestPostReviewRegressions:query="q-new",mode="quick",status="completed",- created_at=now,+ created_at=now.isoformat(),))patched_session.commit()@@ -2029,7 +2029,7 @@ class TestPostReviewRegressions:query="q",mode="quick",status="completed",- created_at=datetime.now(timezone.utc),+ created_at=datetime.now(timezone.utc).isoformat(),))patched_session.commit()@@ -2085,7 +2085,7 @@ class TestPostReviewRegressions:query="q",mode="quick",status="completed",- created_at=datetime.now(timezone.utc),+ created_at=datetime.now(timezone.utc).isoformat(),))patched_session.commit()@@ -2145,7 +2145,7 @@ class TestPostReviewRegressions:query="q",mode="quick",status="completed",- created_at=now,+ created_at=now.isoformat(),))patched_session.commit()@@ -2513,7 +2513,7 @@ class TestPostReviewRegressions:query="q",mode="quick",status="completed",- created_at=datetime.now(timezone.utc),+ created_at=datetime.now(timezone.utc).isoformat(),))patched_session.commit()@@ -4640,7 +4640,7 @@ class TestReviewRound2ServiceFixes:query=f"q{i}",mode="quick",status="completed",- created_at=now,+ created_at=now.isoformat(),))patched_session.commit()@@ -5388,7 +5388,7 @@ class TestReviewRound2ServiceFixes:query="q",mode="quick",status="completed",- created_at=datetime.now(timezone.utc),+ created_at=datetime.now(timezone.utc).isoformat(),))patched_session.commit()diff --git a/tests/notes/test_note_stress.py b/tests/notes/test_note_stress.pyindex 37d680f3e3..697b5f5ead 100644--- a/tests/notes/test_note_stress.py+++ b/tests/notes/test_note_stress.py@@ -774,7 +774,7 @@ class TestLinkResearchConcurrency:query=f"q{i}",mode="quick",status="completed",- created_at=now,+ created_at=now.isoformat(),))setup_session.commit()diff --git a/tests/notes/test_notes_routes_review_fixes.py b/tests/notes/test_notes_routes_review_fixes.pyindex 572ba358c2..f60c9b4e2f 100644--- a/tests/notes/test_notes_routes_review_fixes.py+++ b/tests/notes/test_notes_routes_review_fixes.py@@ -44,7 +44,10 @@ def real_engine():cur.close()Base.metadata.create_all(engine)- return engine, sessionmaker(bind=engine)+ try:+ yield engine, sessionmaker(bind=engine)+ finally:+ engine.dispose()class TestNotesRateLimitsAreKeyedPerUser:@@ -2236,24 +2239,12 @@ class TestNoteSubResourceRoutes404OnUnknownId:get_note already does. Mirrors the codebase's own _is_note contract."""- def _setup(self, monkeypatch):+ def _setup(self, monkeypatch, real_engine):from contextlib import contextmanagerfrom flask import Flask- from sqlalchemy import create_engine, event as sa_event- from sqlalchemy.orm import sessionmaker- from local_deep_research.database.models.base import Basefrom local_deep_research.web.routes import notes_routes- engine = create_engine("sqlite:///:memory:")-- @sa_event.listens_for(engine, "connect")- def enable_fks(dbapi_conn, connection_record):- cur = dbapi_conn.cursor()- cur.execute("PRAGMA foreign_keys=ON")- cur.close()-- Base.metadata.create_all(engine)- Session = sessionmaker(bind=engine)+ _engine, Session = real_enginewith Session() as session:session.add(@@ -2282,8 +2273,10 @@ class TestNoteSubResourceRoutes404OnUnknownId:app.register_blueprint(notes_routes.notes_bp)return app, notes_routes- def test_get_note_collections_404s_on_unknown_id(self, monkeypatch):- app, notes_routes = self._setup(monkeypatch)+ def test_get_note_collections_404s_on_unknown_id(+ self, monkeypatch, real_engine+ ):+ app, notes_routes = self._setup(monkeypatch, real_engine)bogus_id = str(uuid.uuid4())with app.test_request_context(f"/api/notes/{bogus_id}/collections"):@@ -2297,8 +2290,10 @@ class TestNoteSubResourceRoutes404OnUnknownId:assert status == 404assert "not found" in body.get_json()["error"].lower()- def test_get_note_research_404s_on_unknown_id(self, monkeypatch):- app, notes_routes = self._setup(monkeypatch)+ def test_get_note_research_404s_on_unknown_id(+ self, monkeypatch, real_engine+ ):+ app, notes_routes = self._setup(monkeypatch, real_engine)bogus_id = str(uuid.uuid4())with app.test_request_context(f"/api/notes/{bogus_id}/research"):@@ -2318,24 +2313,12 @@ class TestListNotesExposesTotal:guessing from ``len(notes) == limit``."""- def test_list_notes_response_includes_total(self, monkeypatch):+ def test_list_notes_response_includes_total(self, monkeypatch, real_engine):from contextlib import contextmanagerfrom flask import Flask- from sqlalchemy import create_engine, event as sa_event- from sqlalchemy.orm import sessionmaker- from local_deep_research.database.models.base import Basefrom local_deep_research.web.routes import notes_routes- engine = create_engine("sqlite:///:memory:")-- @sa_event.listens_for(engine, "connect")- def enable_fks(dbapi_conn, connection_record):- cur = dbapi_conn.cursor()- cur.execute("PRAGMA foreign_keys=ON")- cur.close()-- Base.metadata.create_all(engine)- Session = sessionmaker(bind=engine)+ _engine, Session = real_enginewith Session() as session:note_st = SourceType(diff --git a/tests/notes/test_post_review_bugfixes.py b/tests/notes/test_post_review_bugfixes.pyindex 8d5b1363c4..c0060b5b51 100644--- a/tests/notes/test_post_review_bugfixes.py+++ b/tests/notes/test_post_review_bugfixes.py@@ -1578,6 +1578,11 @@ class TestWikiLinkRenameSafety:# existing_link_targets entry now points at the deleted target1_id,# so _valid_note_target returns None (Priority-2 miss).service.delete_note(target1_id)+ # SQLite performed the NoteLink delete through ON DELETE CASCADE, so+ # the ORM still considers the previously loaded ``link`` persistent.+ # Expunge that stale identity before SQLite reuses its integer primary+ # key for the replacement link below.+ patched.expunge(link)patched.expire_all()# Re-save the source to trigger reparse. Resolution must falldiff --git a/tests/research_library/deletion/services/test_document_deletion_coverage.py b/tests/research_library/deletion/services/test_document_deletion_coverage.pyindex 5d0d9924f6..30895fa028 100644--- a/tests/research_library/deletion/services/test_document_deletion_coverage.py+++ b/tests/research_library/deletion/services/test_document_deletion_coverage.py@@ -8,6 +8,7 @@ import uuidfrom contextlib import contextmanagerfrom unittest.mock import MagicMock, Mock, patch+import pytestfrom sqlalchemy import create_enginefrom sqlalchemy.orm import sessionmaker@@ -874,11 +875,17 @@ def _make_real_chunk(document_id, collection_name, index=0):)-def _make_real_session():+def real_session():"""A fresh in-memory-sqlite session over the real Base metadata."""engine = create_engine("sqlite:///:memory:")Base.metadata.create_all(engine)- return sessionmaker(bind=engine)()+ session = sessionmaker(bind=engine)()+ try:+ yield session+ finally:+ session.close()+ engine.dispose()@contextmanager@@ -901,8 +908,9 @@ class TestRemoveFromCollectionOrphanRealSession:def test_remove_from_collection_orphan_purges_all_stranded_collections_not_just_removed_one(self,+ real_session,):- session = _make_real_session()+ session = real_sessiondocument_id = "doc-orphan-union-1"collection_id = "col-1"@@ -964,8 +972,9 @@ class TestPurgeDocumentRagBackstop:def test_purge_document_rag_backstop_removes_chunks_even_when_every_collection_purge_raises(self,+ real_session,):- session = _make_real_session()+ session = real_sessiondocument_id = "doc-backstop-1"session.add(_make_real_chunk(document_id, "collection_col-1"))session.add(_make_real_chunk(document_id, "collection_col-2"))@@ -1018,8 +1027,9 @@ class TestPurgeDocumentRagPartialUnlink:def test_purge_document_rag_partial_unlink_leaves_other_collections_chunks_intact(self,+ real_session,):- session = _make_real_session()+ session = real_sessiondocument_id = "doc-partial-1"self._seed_two_collections(session, document_id)@@ -1047,8 +1057,10 @@ class TestPurgeDocumentRagPartialUnlink:remaining_collections = {row.collection_name for row in remaining}assert remaining_collections == {"collection_col-B"}- def test_purge_document_rag_full_delete_sweeps_every_collection(self):- session = _make_real_session()+ def test_purge_document_rag_full_delete_sweeps_every_collection(+ self, real_session+ ):+ session = real_sessiondocument_id = "doc-partial-2"self._seed_two_collections(session, document_id)diff --git a/tests/research_library/routes/test_download_bulk_concurrent_claim_4691.py b/tests/research_library/routes/test_download_bulk_concurrent_claim_4691.pyindex 34a46e66a3..db131a24f0 100644--- a/tests/research_library/routes/test_download_bulk_concurrent_claim_4691.py+++ b/tests/research_library/routes/test_download_bulk_concurrent_claim_4691.py@@ -58,16 +58,22 @@ from local_deep_research.research_library.routes import (RESEARCH_ID = "r1"-def _engine_with_pending_row(tmp_path, name):+def _engine_with_pending_row(tmp_path, name, request):"""Build a real SQLite DB seeded with one PENDING download-queue row.Returns (Session factory, queue_item_id, resource_id)."""engine = create_engine(f"sqlite:///{tmp_path}/{name}.db")+ request.addfinalizer(engine.dispose)Base.metadata.create_all(engine)- Session = sessionmaker(bind=engine)+ session_factory = sessionmaker(bind=engine)- s = Session()+ def tracked_session_factory(*args, **kwargs):+ session = session_factory(*args, **kwargs)+ request.addfinalizer(session.close)+ return session++ s = tracked_session_factory()s.add(ResearchHistory(id=RESEARCH_ID,@@ -96,7 +102,7 @@ def _engine_with_pending_row(tmp_path, name):queue_item_id = row.idresource_id = resource.ids.close()- return Session, queue_item_id, resource_id+ return tracked_session_factory, queue_item_id, resource_iddef _set_status(Session, queue_item_id, status):@@ -123,14 +129,14 @@ def _auth_db_manager():)-def test_download_bulk_claims_pending_row_before_downloading(tmp_path):+def test_download_bulk_claims_pending_row_before_downloading(tmp_path, request):"""The row must be claimed (PENDING -> PROCESSING) BEFORE``download_resource`` runs, so a concurrent stream querying ``PENDING``won't also grab it. On unfixed main the row is still ``PENDING`` when thedownload starts, which is exactly the #4691 double-processing window."""Session, queue_item_id, resource_id = _engine_with_pending_row(- tmp_path, "claim_before"+ tmp_path, "claim_before", request)observed = {}@@ -191,7 +197,7 @@ def test_download_bulk_claims_pending_row_before_downloading(tmp_path):)-def test_pending_row_can_be_claimed_only_once(tmp_path):+def test_pending_row_can_be_claimed_only_once(tmp_path, request):"""The atomic claim is the single point of mutual exclusion: the firstclaim of a PENDING row wins (True) and flips it to PROCESSING; a secondclaim (the losing concurrent stream) sees 0 updated rows and returns False.@@ -200,7 +206,9 @@ def test_pending_row_can_be_claimed_only_once(tmp_path):_claim_download_queue_item,)- Session, queue_item_id, _ = _engine_with_pending_row(tmp_path, "claim_once")+ Session, queue_item_id, _ = _engine_with_pending_row(+ tmp_path, "claim_once", request+ )s = Session()first = _claim_download_queue_item(s, queue_item_id)@@ -214,19 +222,19 @@ def test_pending_row_can_be_claimed_only_once(tmp_path):s.close()-def test_missing_row_is_not_claimed(tmp_path):+def test_missing_row_is_not_claimed(tmp_path, request):"""Claiming a non-existent row returns False rather than raising."""from local_deep_research.research_library.routes.library_routes import (_claim_download_queue_item,)- Session, _, _ = _engine_with_pending_row(tmp_path, "claim_missing")+ Session, _, _ = _engine_with_pending_row(tmp_path, "claim_missing", request)s = Session()assert _claim_download_queue_item(s, 999999) is Falses.close()-def test_claim_is_released_back_to_pending_on_error(tmp_path):+def test_claim_is_released_back_to_pending_on_error(tmp_path, request):"""A claimed row returned via _release_download_queue_item is PENDING againand can be re-claimed, so a download that raised stays retryable."""@@ -236,7 +244,7 @@ def test_claim_is_released_back_to_pending_on_error(tmp_path):)Session, queue_item_id, _ = _engine_with_pending_row(- tmp_path, "claim_release"+ tmp_path, "claim_release", request)s = Session()@@ -258,7 +266,7 @@ def test_claim_is_released_back_to_pending_on_error(tmp_path):s.close()-def test_queue_research_downloads_leaves_in_flight_row_alone(tmp_path):+def test_queue_research_downloads_leaves_in_flight_row_alone(tmp_path, request):"""The pre-pass must not un-claim a row another stream is downloading.``download_bulk`` calls ``queue_research_downloads`` unconditionally on@@ -275,7 +283,9 @@ def test_queue_research_downloads_leaves_in_flight_row_alone(tmp_path):download_service as ds_mod,)- Session, queue_item_id, _ = _engine_with_pending_row(tmp_path, "prepass")+ Session, queue_item_id, _ = _engine_with_pending_row(+ tmp_path, "prepass", request+ )# Stream 1 has claimed the row and is downloading it right now._set_status(Session, queue_item_id, DocumentStatus.PROCESSING)@@ -316,7 +326,7 @@ def test_queue_research_downloads_leaves_in_flight_row_alone(tmp_path):)-def test_queue_research_downloads_still_resets_failed_row(tmp_path):+def test_queue_research_downloads_still_resets_failed_row(tmp_path, request):"""The guard must be narrow: a FAILED row is not in flight, so thedocumented retry-on-every-bulk-run behaviour (#4685) still resets it."""@@ -325,7 +335,7 @@ def test_queue_research_downloads_still_resets_failed_row(tmp_path):)Session, queue_item_id, _ = _engine_with_pending_row(- tmp_path, "prepass_failed"+ tmp_path, "prepass_failed", request)_set_status(Session, queue_item_id, DocumentStatus.FAILED)@@ -359,7 +369,7 @@ def test_queue_research_downloads_still_resets_failed_row(tmp_path):assert queued == 1-def test_text_only_bulk_finalizes_claim(tmp_path):+def test_text_only_bulk_finalizes_claim(tmp_path, request):"""A successful text extraction must leave the row COMPLETED, not stranded.``download_as_text`` and its call tree never write ``LibraryDownloadQueue``@@ -369,7 +379,9 @@ def test_text_only_bulk_finalizes_claim(tmp_path):Pre-fix these rows stayed PENDING, so stranding them is a regression innormal successful operation."""- Session, queue_item_id, _ = _engine_with_pending_row(tmp_path, "text_only")+ Session, queue_item_id, _ = _engine_with_pending_row(+ tmp_path, "text_only", request+ )@contextmanagerdef fake_db_session(*a, **kw):@@ -418,11 +430,13 @@ def test_text_only_bulk_finalizes_claim(tmp_path):)-def test_text_only_bulk_failure_returns_row_to_pending(tmp_path):+def test_text_only_bulk_failure_returns_row_to_pending(tmp_path, request):"""A failed text extraction returns the row to PENDING, matching thepre-fix behaviour where the row stayed retryable."""- Session, queue_item_id, _ = _engine_with_pending_row(tmp_path, "text_fail")+ Session, queue_item_id, _ = _engine_with_pending_row(+ tmp_path, "text_fail", request+ )@contextmanagerdef fake_db_session(*a, **kw):@@ -465,12 +479,14 @@ def test_text_only_bulk_failure_returns_row_to_pending(tmp_path):assert _status_of(Session, queue_item_id) == DocumentStatus.PENDING-def test_pdf_mode_terminal_status_is_not_overwritten(tmp_path):+def test_pdf_mode_terminal_status_is_not_overwritten(tmp_path, request):"""pdf-mode behaviour is unchanged: ``download_resource`` records its ownterminal status, so the finalize must be a no-op there. A row it markedFAILED must not be rewritten to COMPLETED by a truthy return."""- Session, queue_item_id, _ = _engine_with_pending_row(tmp_path, "pdf_noop")+ Session, queue_item_id, _ = _engine_with_pending_row(+ tmp_path, "pdf_noop", request+ )def fake_download_resource(rid):# Model download_resource's own terminal write.@@ -521,8 +537,10 @@ def test_pdf_mode_terminal_status_is_not_overwritten(tmp_path):# Guard against a schema change silently making the claim a no-op: a fresh# PENDING row must actually be flippable to PROCESSING at the DB level.-def test_status_column_round_trips_processing(tmp_path):- Session, queue_item_id, _ = _engine_with_pending_row(tmp_path, "roundtrip")+def test_status_column_round_trips_processing(tmp_path, request):+ Session, queue_item_id, _ = _engine_with_pending_row(+ tmp_path, "roundtrip", request+ )s = Session()row = s.get(LibraryDownloadQueue, queue_item_id)assert row.status == DocumentStatus.PENDING@@ -569,7 +587,9 @@ def _app():return app-def test_queue_all_undownloaded_does_not_reset_an_in_flight_claim(tmp_path):+def test_queue_all_undownloaded_does_not_reset_an_in_flight_claim(+ tmp_path, request+):"""``queue_all_undownloaded`` resets any row that is not PENDING back toPENDING. PROCESSING satisfies ``!= PENDING``, so it un-claims a row a``download_bulk`` stream is downloading right now, and the freed row is@@ -581,7 +601,7 @@ def test_queue_all_undownloaded_does_not_reset_an_in_flight_claim(tmp_path):completed Document yet."""Session, queue_item_id, resource_id = _engine_with_pending_row(- tmp_path, "qau_inflight"+ tmp_path, "qau_inflight", request)# A concurrent download_bulk stream holds the claim._set_status(Session, queue_item_id, DocumentStatus.PROCESSING)@@ -621,7 +641,7 @@ def test_queue_all_undownloaded_does_not_reset_an_in_flight_claim(tmp_path):)-def test_download_source_does_not_reset_an_in_flight_claim(tmp_path):+def test_download_source_does_not_reset_an_in_flight_claim(tmp_path, request):"""``download_source`` resets the row to PENDING unconditionally and thendownloads immediately in the request thread, without claiming it. Its onlyearly return is ``existing and existing.status == "completed"``, which is@@ -631,7 +651,7 @@ def test_download_source_does_not_reset_an_in_flight_claim(tmp_path):So the row must stay PROCESSING and no second download may start."""Session, queue_item_id, resource_id = _engine_with_pending_row(- tmp_path, "dsrc_inflight"+ tmp_path, "dsrc_inflight", request)_set_status(Session, queue_item_id, DocumentStatus.PROCESSING)@@ -724,7 +744,9 @@ def _run_download_bulk(Session, extra_patches=()):return ds_mock-def test_download_bulk_does_not_strand_a_claim_when_title_is_null(tmp_path):+def test_download_bulk_does_not_strand_a_claim_when_title_is_null(+ tmp_path, request+):"""``ResearchResource.title`` is a nullable Text column, so``resource.title[:50]`` raises TypeError for a resource whose title wasnever populated. That lookup ran after the claim was committed but before@@ -733,7 +755,7 @@ def test_download_bulk_does_not_strand_a_claim_when_title_is_null(tmp_path):them."""Session, queue_item_id, resource_id = _engine_with_pending_row(- tmp_path, "strand_null_title"+ tmp_path, "strand_null_title", request)s = Session()s.query(ResearchResource).filter_by(id=resource_id).update({"title": None})@@ -752,6 +774,7 @@ def test_download_bulk_does_not_strand_a_claim_when_title_is_null(tmp_path):def test_download_bulk_releases_the_claim_when_post_claim_work_raises(tmp_path,+ request,):"""The null title above is one instance of a structural window, not thewhole of it, so the fix is guaranteed cleanup rather than a null-check on@@ -762,7 +785,7 @@ def test_download_bulk_releases_the_claim_when_post_claim_work_raises(in that window."""Session, queue_item_id, _ = _engine_with_pending_row(- tmp_path, "release_post_claim"+ tmp_path, "release_post_claim", request)class _NotAnEntity:diff --git a/tests/research_library/routes/test_rag_routes.py b/tests/research_library/routes/test_rag_routes.pyindex d97b45b5c6..518d92cd33 100644--- a/tests/research_library/routes/test_rag_routes.py+++ b/tests/research_library/routes/test_rag_routes.py@@ -2763,7 +2763,7 @@ class TestGetCollectionsIndexedCounts:"""@staticmethod- def _seed_session():+ def _seed_session(request):"""Return an in-memory session seeded with TWO collections.Collection A: 3 docs, 2 indexed (1 pending).@@ -2789,8 +2789,10 @@ class TestGetCollectionsIndexedCounts:)engine = create_engine("sqlite:///:memory:")+ request.addfinalizer(engine.dispose)Base.metadata.create_all(engine)session = sessionmaker(bind=engine)()+ request.addfinalizer(session.close)source_type = SourceType(id=str(uuid.uuid4()),@@ -2890,9 +2892,9 @@ class TestGetCollectionsIndexedCounts:sess["session_id"] = "test-session-id"return client.get("/library/api/collections")- def test_payload_reports_total_and_indexed_counts(self):+ def test_payload_reports_total_and_indexed_counts(self, request):"""Payload includes both counts with the seeded values (A: 3 total, 2 indexed)."""- session, collection_a_id, _collection_b_id = self._seed_session()+ session, collection_a_id, _collection_b_id = self._seed_session(request)try:response = self._call_route(session)finally:@@ -2911,7 +2913,7 @@ class TestGetCollectionsIndexedCounts:# Pending = total - indexed; the UI derives the "pending" badge from this.assert coll["document_count"] - coll["indexed_document_count"] == 1- def test_each_collection_counts_are_independent(self):+ def test_each_collection_counts_are_independent(self, request):"""Two collections with different splits must each report their OWN counts.Guards the per-collection ``GROUP BY``: collection A is 2-of-3 indexed@@ -2919,7 +2921,7 @@ class TestGetCollectionsIndexedCounts:``group_by(collection_id)``, both would collapse to the same globalcount (3 indexed) and these per-collection assertions would fail."""- session, collection_a_id, collection_b_id = self._seed_session()+ session, collection_a_id, collection_b_id = self._seed_session(request)try:response = self._call_route(session)finally:@@ -2942,14 +2944,14 @@ class TestGetCollectionsIndexedCounts:)assert coll_a["document_count"] != coll_b["document_count"]- def test_indexed_count_zero_when_nothing_indexed(self):+ def test_indexed_count_zero_when_nothing_indexed(self, request):"""A collection with only unindexed links reports indexed_document_count == 0."""import uuidfrom local_deep_research.database.models.library import (DocumentCollection,)- session, collection_a_id, _collection_b_id = self._seed_session()+ session, collection_a_id, _collection_b_id = self._seed_session(request)# Flip every link in collection A to unindexed.session.query(DocumentCollection).filter(DocumentCollection.collection_id == collection_a_id@@ -2984,7 +2986,7 @@ class TestGetIndexStatusScoping:"""@staticmethod- def _seed_session():+ def _seed_session(request):"""In-memory session with indexing tasks for two collections.Collection A has TWO tasks: an older ``failed`` one and a newer@@ -3002,8 +3004,10 @@ class TestGetIndexStatusScoping:from local_deep_research.database.models.queue import TaskMetadataengine = create_engine("sqlite:///:memory:")+ request.addfinalizer(engine.dispose)Base.metadata.create_all(engine)session = sessionmaker(bind=engine)()+ request.addfinalizer(session.close)coll_a_id = "collection-a"coll_b_id = "collection-b"@@ -3097,9 +3101,9 @@ class TestGetIndexStatusScoping:f"/library/api/collections/{collection_id}/index/status")- def test_returns_this_collections_task_not_global_newest(self):+ def test_returns_this_collections_task_not_global_newest(self, request):"""A's status is its OWN processing task, even though B's is newer."""- session, coll_a_id, coll_b_id = self._seed_session()+ session, coll_a_id, coll_b_id = self._seed_session(request)try:resp = self._call_status(session, coll_a_id)finally:@@ -3111,12 +3115,12 @@ class TestGetIndexStatusScoping:assert data["task_id"] == "task-a"assert data["collection_id"] == coll_a_id- def test_returns_newest_task_for_the_collection(self):+ def test_returns_newest_task_for_the_collection(self, request):"""Among A's OWN tasks, the NEWEST (processing) wins over the older(failed) one — locking in the newest-first ordering. Flipping``.desc()`` to ``.asc()`` would return ``task-a-old`` and fail here."""- session, coll_a_id, _coll_b_id = self._seed_session()+ session, coll_a_id, _coll_b_id = self._seed_session(request)try:resp = self._call_status(session, coll_a_id)finally:@@ -3129,9 +3133,9 @@ class TestGetIndexStatusScoping:# The older failed run must NOT be what we returned.assert data["task_id"] != "task-a-old"- def test_returns_idle_only_when_no_task_for_collection(self):+ def test_returns_idle_only_when_no_task_for_collection(self, request):"""A collection with no indexing task at all reports idle (scoped)."""- session, _coll_a_id, _coll_b_id = self._seed_session()+ session, _coll_a_id, _coll_b_id = self._seed_session(request)try:resp = self._call_status(session, "collection-with-no-task")finally:diff --git a/tests/security/test_bulk_secret_name_coverage.py b/tests/security/test_bulk_secret_name_coverage.pyindex 99bc1cd39f..2eff731142 100644--- a/tests/security/test_bulk_secret_name_coverage.py+++ b/tests/security/test_bulk_secret_name_coverage.py@@ -18,40 +18,57 @@ from local_deep_research.security.data_sanitizer import DataSanitizerfrom local_deep_research.settings.manager import SettingsManager+def manager_factory():+ """Create managers and release their sessions and engines after a test."""+ resources = []++ def _make(settings):+ engine = create_engine("sqlite:///:memory:")+ Base.metadata.create_all(engine)+ session = sessionmaker(bind=engine)()+ session.add_all(settings)+ session.commit()+ manager = SettingsManager(db_session=session)+ resources.append((manager, session, engine))+ return manager++ yield _make++ for manager, session, engine in reversed(resources):+ manager.close()+ session.close()+ engine.dispose()++@pytest.mark.parametrize("leaf",["client_secret", "secret_key", "bearer_token", "api_secret", "app_secret"],)-def test_bulk_get_redacts_named_secret(leaf):+def test_bulk_get_redacts_named_secret(leaf, manager_factory):key = f"integrations.oauth.{leaf}"- engine = create_engine("sqlite:///:memory:")- Base.metadata.create_all(engine)- session = sessionmaker(bind=engine)()- session.add(- Setting(- key=key,- value="topsecret-value",- type="app",- name=key,- ui_element="password",- )+ manager = manager_factory(+ [+ Setting(+ key=key,+ value="topsecret-value",+ type="app",+ name=key,+ ui_element="password",+ )+ ])- session.commit()- manager = SettingsManager(db_session=session)# mirror GET /settings/api/bulk: get_setting(key) then redact_value(key, None, value)shipped = DataSanitizer.redact_value(key, None, manager.get_setting(key))assert shipped == DataSanitizer.REDACTION_TEXT-def test_bulk_get_redacts_named_secret_in_subtree():+def test_bulk_get_redacts_named_secret_in_subtree(manager_factory):"""A subtree request (keys[]=integrations.oauth) must redact a nestednon-classic secret while keeping non-secret siblings — pins the addednames composing with redact_value's subtree recursion (#5028)."""- engine = create_engine("sqlite:///:memory:")- Base.metadata.create_all(engine)- session = sessionmaker(bind=engine)()- session.add_all(+ manager = manager_factory([Setting(key="integrations.oauth.client_secret",@@ -69,8 +86,6 @@ def test_bulk_get_redacts_named_secret_in_subtree():),])- session.commit()- manager = SettingsManager(db_session=session)shipped = DataSanitizer.redact_value("integrations.oauth", None, manager.get_setting("integrations.oauth")diff --git a/tests/test_ci_coverage_summary.py b/tests/test_ci_coverage_summary.pynew file mode 100644index 0000000000..8c068c0ccc--- /dev/null+++ b/tests/test_ci_coverage_summary.py@@ -0,0 +1,350 @@+"""Regression tests for the coverage data shown on pull requests."""++# allow: no-sut-import — this guardian test exercises scripts/ci production code++import json+from pathlib import Path++import pytest++from scripts.ci import coverage_summary+from scripts.ci.coverage_summary import build_summary+++def _valid_coverage_xml(+ *,+ line_rate: str = "0.9",+ branch_rate: str = "0.8",+ lines_covered: str = "9",+ lines_valid: str = "10",+ branches_covered: str = "8",+ branches_valid: str = "10",+ contents: str = "",+) -> str:+ return (+ f'<coverage line-rate="{line_rate}" branch-rate="{branch_rate}" '+ f'lines-covered="{lines_covered}" lines-valid="{lines_valid}" '+ f'branches-covered="{branches_covered}" '+ f'branches-valid="{branches_valid}">'+ f"{contents}</coverage>"+ )+++def test_valid_coverage_xml_is_summarized(tmp_path: Path) -> None:+ coverage_path = tmp_path / "coverage.xml"+ coverage_path.write_text(+ """<?xml version="1.0" ?>+<coverage line-rate="0.9" branch-rate="0.8"+ lines-covered="9" lines-valid="10"+ branches-covered="8" branches-valid="10">+ <packages><package><classes>+ <class filename="src/local_deep_research/low.py" line-rate="0.4" />+ <class filename="src/local_deep_research/high.py" line-rate="0.75" />+ </classes></package></packages>+</coverage>+""",+ encoding="utf-8",+ )++ summary = build_summary(coverage_path)++ assert summary == {+ "generated": True,+ "valid": True,+ "lineRate": 0.9,+ "branchRate": 0.8,+ "linesCovered": 9,+ "linesTotal": 10,+ "filesAnalyzed": 2,+ "lowestCoverageFiles": [{"filename": "low.py", "rate": 40.0}],+ }+++ "xml",+ [+ '<coverage line-rate="0.9" branch-rate="0.8" '+ 'lines-covered="9" lines-valid="10" '+ 'branches-covered="8" branches-valid="10">',+ '<coverage line-rate="NaN" branch-rate="0.8" '+ 'lines-covered="9" lines-valid="10" '+ 'branches-covered="8" branches-valid="10" />',+ '<coverage line-rate="1.1" branch-rate="0.8" '+ 'lines-covered="9" lines-valid="10" '+ 'branches-covered="8" branches-valid="10" />',+ '<coverage line-rate="0.9" branch-rate="0.8" '+ 'lines-covered="11" lines-valid="10" '+ 'branches-covered="8" branches-valid="10" />',+ '<coverage line-rate="0.9" branch-rate="0.8" '+ 'lines-covered="9.5" lines-valid="10" '+ 'branches-covered="8" branches-valid="10" />',+ '<coverage line-rate="0.9" branch-rate="0.8" '+ 'lines-covered="9" lines-valid="10" '+ 'branches-covered="11" branches-valid="10" />',+ '<coverage line-rate="0.9" branch-rate="0.8" '+ 'lines-covered="9" lines-valid="10" />',+ ],+)+def test_malformed_or_impossible_coverage_is_rejected(+ tmp_path: Path, xml: str+) -> None:+ coverage_path = tmp_path / "coverage.xml"+ coverage_path.write_text(xml, encoding="utf-8")++ summary = build_summary(coverage_path)++ assert summary["generated"] is True+ assert summary["valid"] is False+ assert isinstance(summary["error"], str)+++def test_missing_coverage_is_distinct_from_malformed(tmp_path: Path) -> None:+ summary = build_summary(tmp_path / "missing.xml")++ assert summary == {"generated": False, "valid": False}+++def test_coverage_filename_is_safe_for_bot_markdown(tmp_path: Path) -> None:+ coverage_path = tmp_path / "coverage.xml"+ coverage_path.write_text(+ '<coverage line-rate="0.4" branch-rate="0.3" '+ 'lines-covered="4" lines-valid="10" '+ 'branches-covered="3" branches-valid="10">'+ '<class filename="src/x` @org/team</code>.py" '+ 'line-rate="0.4" />'+ "</coverage>",+ encoding="utf-8",+ )++ summary = build_summary(coverage_path)++ filename = summary["lowestCoverageFiles"][0]["filename"]+ assert "\n" not in filename+ assert "`" not in filename+ assert "@" not in filename+ assert "`" in filename+ assert "@org/team" in filename+ assert "</code>" in filename+++def test_coverage_py_rounded_rates_agree_with_counts(tmp_path: Path) -> None:+ coverage_path = tmp_path / "coverage.xml"+ coverage_path.write_text(+ _valid_coverage_xml(+ line_rate="0.9257",+ branch_rate="0.8805",+ lines_covered="50221",+ lines_valid="54249",+ branches_covered="14271",+ branches_valid="16208",+ ),+ encoding="utf-8",+ )++ summary = build_summary(coverage_path)++ assert summary["valid"] is True+++ ("line_rate", "branch_rate"),+ [("0", "1"), ("1", "0"), ("1", "1"), ("0", "0")],+)+def test_empty_coverage_accepts_common_zero_denominator_rates(+ tmp_path: Path, line_rate: str, branch_rate: str+) -> None:+ coverage_path = tmp_path / "coverage.xml"+ coverage_path.write_text(+ _valid_coverage_xml(+ line_rate=line_rate,+ branch_rate=branch_rate,+ lines_covered="0",+ lines_valid="0",+ branches_covered="0",+ branches_valid="0",+ ),+ encoding="utf-8",+ )++ assert build_summary(coverage_path)["valid"] is True+++ ("line_rate", "branch_rate"),+ [("0.99", "0.88"), ("0.01", "0.99")],+)+def test_declared_rates_must_agree_with_counts(+ tmp_path: Path, line_rate: str, branch_rate: str+) -> None:+ coverage_path = tmp_path / "coverage.xml"+ coverage_path.write_text(+ _valid_coverage_xml(+ line_rate=line_rate,+ branch_rate=branch_rate,+ lines_covered="1",+ lines_valid="100",+ branches_covered="88",+ branches_valid="100",+ ),+ encoding="utf-8",+ )++ summary = build_summary(coverage_path)++ assert summary["valid"] is False+ assert "disagrees with its counts" in summary["error"]+++def test_counts_must_fit_in_a_javascript_safe_integer(tmp_path: Path) -> None:+ coverage_path = tmp_path / "coverage.xml"+ coverage_path.write_text(+ _valid_coverage_xml(+ line_rate="1",+ lines_covered=str(2**53),+ lines_valid=str(2**53),+ ),+ encoding="utf-8",+ )++ summary = build_summary(coverage_path)++ assert summary["valid"] is False+ assert "JavaScript safe integer" in summary["error"]+++def test_javascript_safe_integer_boundary_is_accepted(tmp_path: Path) -> None:+ coverage_path = tmp_path / "coverage.xml"+ coverage_path.write_text(+ _valid_coverage_xml(+ line_rate="1",+ lines_covered=str(2**53 - 1),+ lines_valid=str(2**53 - 1),+ ),+ encoding="utf-8",+ )++ assert build_summary(coverage_path)["valid"] is True+++def test_unknown_declared_encoding_is_returned_as_json(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ coverage_path = tmp_path / "coverage.xml"+ coverage_path.write_bytes(+ b'<?xml version="1.0" encoding="not-a-real-codec"?>'+ b'<coverage line-rate="1" branch-rate="1" '+ b'lines-covered="1" lines-valid="1" '+ b'branches-covered="0" branches-valid="0" />'+ )+ output_path = tmp_path / "summary.json"+ monkeypatch.setattr(+ coverage_summary.sys,+ "argv",+ ["coverage_summary.py", str(coverage_path), str(output_path)],+ )++ assert coverage_summary.main() == 1+ summary = json.loads(output_path.read_text(encoding="utf-8"))+ assert summary["generated"] is True+ assert summary["valid"] is False+ assert summary["error"].startswith("LookupError:")+++def test_doctype_entities_are_rejected(tmp_path: Path) -> None:+ coverage_path = tmp_path / "coverage.xml"+ coverage_path.write_text(+ """<?xml version="1.0"?>+<!DOCTYPE coverage [<!ENTITY forged "1">]>+<coverage line-rate="&forged;" branch-rate="1"+ lines-covered="1" lines-valid="1"+ branches-covered="0" branches-valid="0" />+""",+ encoding="utf-8",+ )++ summary = build_summary(coverage_path)++ assert summary["generated"] is True+ assert summary["valid"] is False+ assert "Forbidden" in summary["error"]+++def test_error_diagnostic_is_bounded_and_single_line(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ capsys: pytest.CaptureFixture[str],+) -> None:+ coverage_path = tmp_path / "coverage.xml"+ coverage_path.write_text("<coverage />", encoding="utf-8")+ output_path = tmp_path / "summary.json"++ def reject_report(_coverage_path: Path) -> None:+ raise ValueError(f"first line\nsecond\tline {'x' * 2_000}")++ monkeypatch.setattr(coverage_summary.ElementTree, "parse", reject_report)+ monkeypatch.setattr(+ coverage_summary.sys,+ "argv",+ ["coverage_summary.py", str(coverage_path), str(output_path)],+ )++ assert coverage_summary.main() == 1+ summary = json.loads(output_path.read_text(encoding="utf-8"))+ error = summary["error"]+ stderr = capsys.readouterr().err.removesuffix("\n")++ assert isinstance(error, str)+ assert len(error) <= 1024+ assert "\n" not in error+ assert "\r" not in error+ assert "\t" not in error+ assert error.endswith("…")+ assert len(stderr) <= 1024+ assert "\n" not in stderr+++def test_cli_returns_zero_and_emits_json_for_valid_report(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ coverage_path = tmp_path / "coverage.xml"+ coverage_path.write_text(_valid_coverage_xml(), encoding="utf-8")+ output_path = tmp_path / "summary.json"+ monkeypatch.setattr(+ coverage_summary.sys,+ "argv",+ ["coverage_summary.py", str(coverage_path), str(output_path)],+ )++ assert coverage_summary.main() == 0+ assert json.loads(output_path.read_text(encoding="utf-8"))["valid"] is True++[email protected]("malformed", [False, True])+def test_cli_returns_one_and_emits_json_for_unusable_report(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ malformed: bool,+) -> None:+ coverage_path = tmp_path / "coverage.xml"+ if malformed:+ coverage_path.write_text("<coverage", encoding="utf-8")+ output_path = tmp_path / "summary.json"+ monkeypatch.setattr(+ coverage_summary.sys,+ "argv",+ ["coverage_summary.py", str(coverage_path), str(output_path)],+ )++ assert coverage_summary.main() == 1+ summary = json.loads(output_path.read_text(encoding="utf-8"))+ assert summary["generated"] is malformed+ assert summary["valid"] is False+++def test_cli_usage_error_returns_two(+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]+) -> None:+ monkeypatch.setattr(coverage_summary.sys, "argv", ["coverage_summary.py"])++ assert coverage_summary.main() == 2+ assert capsys.readouterr().err.startswith("usage:")diff --git a/tests/test_link_analytics.py b/tests/test_link_analytics.pyindex 25921bcd9d..d7683ebe86 100644--- a/tests/test_link_analytics.py+++ b/tests/test_link_analytics.py@@ -113,7 +113,7 @@ class TestLinkAnalytics:assert analytics["avg_links_per_research"] == 0assert len(analytics["top_domains"]) == 0- def test_get_link_analytics_real_db_projection(self):+ def test_get_link_analytics_real_db_projection(self, request):"""Real-DB guard (#4560): run get_link_analytics on real ``Row``objects (which expose ONLY the projected columns), notattribute-permissive mocks.@@ -135,6 +135,7 @@ class TestLinkAnalytics:from local_deep_research.database.models import Base, ResearchResourceengine = create_engine("sqlite://")+ request.addfinalizer(engine.dispose)Base.metadata.create_all(engine)with SASession(engine) as setup:setup.add_all(diff --git a/tests/ui_tests/package.json b/tests/ui_tests/package.jsonindex 8660b725fc..2efb3e5579 100644--- a/tests/ui_tests/package.json+++ b/tests/ui_tests/package.json@@ -34,6 +34,9 @@"dependencies": {"puppeteer": "25.3.0"},+ "allowScripts": {+ "puppeteer": false+ },"overrides": {"yauzl": "^3.2.1"},diff --git a/tests/utilities/test_es_utils.py b/tests/utilities/test_es_utils.pyindex 424bbbced3..b559304f0e 100644--- a/tests/utilities/test_es_utils.py+++ b/tests/utilities/test_es_utils.py@@ -493,18 +493,87 @@ class TestElasticsearchManagerIndexFile:return ElasticsearchManager()- def test_returns_none_if_loader_not_available(self, manager):- """Should return None if UnstructuredFileLoader not available."""+ def test_returns_none_if_loader_not_available(self, manager, tmp_path):+ """Should return None if the Unstructured partitioner is unavailable."""+ file_path = tmp_path / "import-check.txt"+ file_path.write_text("Loader import path check", encoding="utf-8")+ manager.client.index.return_value = {"_id": "unexpected"}# The import is lazy inside the function, so we patch at the sourcewith patch.dict("sys.modules",- {"langchain_community.document_loaders": None},+ {"unstructured.partition.auto": None},):- result = manager.index_file("test-index", "/path/to/file.txt")+ result = manager.index_file("test-index", str(file_path))# Will raise ImportError, caught and returns Noneassert result is None+ def test_indexes_real_text_with_unstructured_partition(+ self, manager, tmp_path+ ):+ """Direct local partitioning preserves text and file metadata."""+ file_path = tmp_path / "notes.txt"+ file_path.write_text(+ "First paragraph for the Elasticsearch document.\n\n"+ "Second paragraph from the same source file.",+ encoding="utf-8",+ )+ manager.client.index.return_value = {"_id": "doc-1"}++ result = manager.index_file("test-index", str(file_path))++ assert result == "doc-1"+ indexed = manager.client.index.call_args.kwargs["document"]+ assert "First paragraph" in indexed["content"]+ assert "Second paragraph" in indexed["content"]+ assert indexed["source"] == str(file_path)+ assert indexed["filename"] == "notes.txt"+ assert indexed["file_extension"] == "txt"+ assert indexed["metadata"]["source"] == str(file_path)++ def test_aggregate_metadata_excludes_first_element_details(+ self, manager, tmp_path+ ):+ """Combined content must not inherit one element's local metadata."""+ file_path = tmp_path / "multi-page.txt"++ class _Element:+ def __init__(self, text):+ self.text = text++ def __str__(self):+ return self.text++ mock_partition = Mock(+ return_value=[_Element("page one"), _Element("page two")]+ )+ manager.client.index.return_value = {"_id": "multi-doc"}++ with patch("unstructured.partition.auto.partition", mock_partition):+ result = manager.index_file("test-index", str(file_path))++ assert result == "multi-doc"+ indexed = manager.client.index.call_args.kwargs["document"]+ assert indexed["content"] == "page one\n\npage two"+ assert indexed["metadata"] == {"source": str(file_path)}+ mock_partition.assert_called_once_with(filename=str(file_path))++ def test_empty_file_keeps_identity_metadata(self, manager, tmp_path):+ """Zero loader elements must not produce an untraceable document."""+ file_path = tmp_path / "empty.txt"+ file_path.write_text("", encoding="utf-8")+ manager.client.index.return_value = {"_id": "empty-doc"}++ result = manager.index_file("test-index", str(file_path))++ assert result == "empty-doc"+ indexed = manager.client.index.call_args.kwargs["document"]+ assert indexed["content"] == ""+ assert indexed["source"] == str(file_path)+ assert indexed["filename"] == "empty.txt"+ assert indexed["file_extension"] == "txt"+ assert indexed["metadata"]["source"] == str(file_path)+def test_returns_none_on_error(self, manager):"""Should return None on error."""# Force an error by using a non-existent file path without mocking loaderdiff --git a/tests/utilities/test_es_utils_coverage.py b/tests/utilities/test_es_utils_coverage.pyindex 250b3764b8..4b96d29b58 100644--- a/tests/utilities/test_es_utils_coverage.py+++ b/tests/utilities/test_es_utils_coverage.py@@ -194,13 +194,11 @@ class TestIndexFileTitleFieldNone:def test_title_field_none_excludes_title_from_doc(self, tmp_path):mgr = _make_manager()- mock_doc = Mock()- mock_doc.page_content = "file content"- mock_doc.metadata = {"source": "test"}+ class _Element:+ def __str__(self):+ return "file content"- mock_loader = Mock()- mock_loader.load.return_value = [mock_doc]- mock_loader_class = Mock(return_value=mock_loader)+ mock_partition = Mock(return_value=[_Element()])indexed_doc = {}@@ -210,15 +208,19 @@ class TestIndexFileTitleFieldNone:mgr.index_document = _capture_index+ file_path = str(tmp_path / "report.txt")with patch(- "langchain_community.document_loaders.UnstructuredFileLoader",- mock_loader_class,+ "unstructured.partition.auto.partition",+ mock_partition,):- mgr.index_file(+ result = mgr.index_file("idx",- str(tmp_path / "report.txt"),+ file_path,title_field=None,)# title should not be in the document when title_field is None+ assert result == "doc-id"+ assert indexed_doc["content"] == "file content"assert "title" not in indexed_doc+ mock_partition.assert_called_once_with(filename=file_path)diff --git a/tests/utilities/test_thread_context_session_lifecycle.py b/tests/utilities/test_thread_context_session_lifecycle.pyindex cb3d6ff91a..4512421b75 100644--- a/tests/utilities/test_thread_context_session_lifecycle.py+++ b/tests/utilities/test_thread_context_session_lifecycle.py@@ -57,23 +57,37 @@ def real_app():return app-def _parent_session_with_pending_work():- """A real session holding one flushed-but-uncommitted row."""- engine = create_engine("sqlite:///:memory:")- Base.metadata.create_all(engine)- session = sessionmaker(bind=engine)()- session.add(_Widget(name="uncommitted-parent-work"))- session.flush() # emit INSERT; still inside the open (uncommitted) transaction- assert session.query(_Widget).count() == 1- return session+def parent_session_factory():+ """Build parent sessions and release their engines after each test."""+ resources = []++ def _make_parent_session():+ engine = create_engine("sqlite:///:memory:")+ Base.metadata.create_all(engine)+ session = sessionmaker(bind=engine)()+ resources.append((session, engine))+ session.add(_Widget(name="uncommitted-parent-work"))+ session.flush()+ assert session.query(_Widget).count() == 1+ return session++ yield _make_parent_session++ for session, engine in reversed(resources):+ try:+ session.close()+ finally:+ engine.dispose()def test_creating_context_does_not_commit_rollback_or_close_parent_session(real_app,+ parent_session_factory,):"""Guarantee 1: creating ``thread_context()`` does not commit, roll back,close, or otherwise alter the parent thread's active database session."""- parent = _parent_session_with_pending_work()+ parent = parent_session_factory()parent.commit = MagicMock(wraps=parent.commit)parent.rollback = MagicMock(wraps=parent.rollback)parent.close = MagicMock(wraps=parent.close)@@ -93,10 +107,11 @@ def test_creating_context_does_not_commit_rollback_or_close_parent_session(def test_parent_pending_work_survives_context_creation_and_worker_exit(real_app,+ parent_session_factory,):"""Guarantee 2: pending uncommitted work in the parent session remainspresent after context creation and after the worker context exits."""- parent = _parent_session_with_pending_work()+ parent = parent_session_factory()with real_app.app_context():g.current_user = "alice"@@ -140,10 +155,12 @@ def test_safe_values_available_inside_worker_context(real_app):assert seen["settings_snapshot"] == {"llm": "gpt"}-def test_teardown_owned_db_session_not_copied_into_worker(real_app):+def test_teardown_owned_db_session_not_copied_into_worker(+ real_app, parent_session_factory+):"""Guarantee 4: teardown-owned resources such as ``db_session`` are notcopied into the worker context."""- parent = _parent_session_with_pending_work()+ parent = parent_session_factory()seen = {}@thread_with_app_context@@ -161,12 +178,14 @@ def test_teardown_owned_db_session_not_copied_into_worker(real_app):assert seen["has_db_session"] is False-def test_worker_needing_db_gets_its_own_session_not_the_parents(real_app):+def test_worker_needing_db_gets_its_own_session_not_the_parents(+ real_app, parent_session_factory+):"""Guarantee 5: a worker that needs database access obtains its owncontext-local session rather than reusing the parent session."""from local_deep_research.database import session_context- parent = _parent_session_with_pending_work()+ parent = parent_session_factory()worker_session = MagicMock(name="worker-session")obtained = {}@@ -198,10 +217,12 @@ def test_worker_needing_db_gets_its_own_session_not_the_parents(real_app):assert obtained["session"] is not parent-def test_worker_teardown_closes_only_worker_owned_resources(real_app):+def test_worker_teardown_closes_only_worker_owned_resources(+ real_app, parent_session_factory+):"""Guarantee 6: worker teardown closes only worker-owned resources andleaves the parent session usable."""- parent = _parent_session_with_pending_work()+ parent = parent_session_factory()parent.rollback = MagicMock(wraps=parent.rollback)parent.close = MagicMock(wraps=parent.close)worker_owned = MagicMock(name="worker-owned-session")@@ -224,10 +245,12 @@ def test_worker_teardown_closes_only_worker_owned_resources(real_app):assert parent.query(_Widget).count() == 1-def test_exception_inside_worker_preserves_ownership_guarantees(real_app):+def test_exception_inside_worker_preserves_ownership_guarantees(+ real_app, parent_session_factory+):"""Guarantee 7: exception paths inside the worker context preserve the sameownership and cleanup guarantees."""- parent = _parent_session_with_pending_work()+ parent = parent_session_factory()parent.rollback = MagicMock(wraps=parent.rollback)parent.close = MagicMock(wraps=parent.close)worker_owned = MagicMock(name="worker-owned-session")diff --git a/tests/vector_stores/test_cross_tenant_isolation.py b/tests/vector_stores/test_cross_tenant_isolation.pyindex 78ce8cdec7..460e7dccef 100644--- a/tests/vector_stores/test_cross_tenant_isolation.py+++ b/tests/vector_stores/test_cross_tenant_isolation.py@@ -89,31 +89,48 @@ class _Tenant:def __init__(self, tmp_path, username: str, collection_name: str):self.username = usernameself.db_password = f"pw-{username}" # gitleaks:allow- engine = create_engine("sqlite:///:memory:")- Base.metadata.create_all(engine)- self.session = sessionmaker(bind=engine)()- self.index_dir = tmp_path / username- self.index_dir.mkdir()- self.vi = VectorIndex(- username=username,- db_password=self.db_password,- embeddings=_FakeEmbeddings(dim=8),- embedding_model="fake-model",- embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,- collection_name=collection_name,- dimension=8,- path=self.index_dir / f"{collection_name}.faiss",- lock=threading.Lock(),- integrity_record=_noop,- integrity_verify=_ok,- index_type="flat",- metric="cosine",- normalize=True,- )+ self.engine = None+ self.session = None+ try:+ self.engine = create_engine("sqlite:///:memory:")+ Base.metadata.create_all(self.engine)+ self.session = sessionmaker(bind=self.engine)()+ self.index_dir = tmp_path / username+ self.index_dir.mkdir()+ self.vi = VectorIndex(+ username=username,+ db_password=self.db_password,+ embeddings=_FakeEmbeddings(dim=8),+ embedding_model="fake-model",+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,+ collection_name=collection_name,+ dimension=8,+ path=self.index_dir / f"{collection_name}.faiss",+ lock=threading.Lock(),+ integrity_record=_noop,+ integrity_verify=_ok,+ index_type="flat",+ metric="cosine",+ normalize=True,+ )+ except BaseException:+ # Construction happens before the fixture can register its+ # finalizer, so partial instances must release their own resources.+ self.close()+ raise++ def close(self):+ """Release the tenant's session and its pooled SQLite connection."""+ try:+ if self.session is not None:+ self.session.close()+ finally:+ if self.engine is not None:+ self.engine.dispose()@pytest.fixture-def tenants(tmp_path, mocker):+def tenants(tmp_path, mocker, request):"""Two tenants, SAME logical collection_name (so ids collide), each withits own DB session and its own on-disk directory. ``get_user_db_session``is patched at the facade's import site to route by username to the@@ -121,7 +138,9 @@ def tenants(tmp_path, mocker):the caller's own encrypted per-user DB."""a = _Tenant(tmp_path, "userA", collection_name="c")+ request.addfinalizer(a.close)b = _Tenant(tmp_path, "userB", collection_name="c")+ request.addfinalizer(b.close)by_username = {"userA": a.session, "userB": b.session}@contextmanager@@ -135,9 +154,6 @@ def tenants(tmp_path, mocker):yield a, b- a.session.close()- b.session.close()-def test_colliding_ids_do_not_cross_tenant_boundary(tenants):"""Sanity precondition: both tenants really do get DocumentChunk.id == 1diff --git a/tests/vector_stores/test_integrity_tamper_lifecycle.py b/tests/vector_stores/test_integrity_tamper_lifecycle.pyindex b3a25bb52e..63a2f95048 100644--- a/tests/vector_stores/test_integrity_tamper_lifecycle.py+++ b/tests/vector_stores/test_integrity_tamper_lifecycle.py@@ -146,7 +146,7 @@ class _Rig:@pytest.fixture-def rig(tmp_path, monkeypatch, mocker):+def rig(tmp_path, monkeypatch, mocker, request):"""Real service, real FileIntegrityManager, real on-disk faiss index, ashared in-memory sqlite session standing in for the (encrypted, inproduction) per-user DB, and a real Document+Collection seeded with a@@ -154,8 +154,10 @@ def rig(tmp_path, monkeypatch, mocker):monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))engine = create_engine("sqlite:///:memory:")+ request.addfinalizer(engine.dispose)Base.metadata.create_all(engine)session = sessionmaker(bind=engine)()+ request.addfinalizer(session.close)def _shared(*_a, **_k):return _session_ctx(session)@@ -213,6 +215,7 @@ def rig(tmp_path, monkeypatch, mocker):embedding_provider="sentence_transformers",embedding_manager=emb_mgr,)+ request.addfinalizer(svc.close)# Real FileIntegrityManager, not a mock/stub.from local_deep_research.security.file_integrity import FileIntegrityManager@@ -241,7 +244,6 @@ def rig(tmp_path, monkeypatch, mocker):)yield r- svc.close()def _quarantine_files(index_path):diff --git a/tests/web/auth/test_auth_routes.py b/tests/web/auth/test_auth_routes.pyindex 24ae85fc2f..9b248f026b 100644--- a/tests/web/auth/test_auth_routes.py+++ b/tests/web/auth/test_auth_routes.py@@ -13,11 +13,21 @@ Tests cover:from pathlib import Pathfrom unittest.mock import MagicMock, patch+import pytestfrom flask import Flaskfrom local_deep_research.security.password_validator import PasswordValidator+def disable_post_login_worker(monkeypatch):+ """Keep synchronous route tests from starting real DB worker threads."""+ monkeypatch.setattr(+ "local_deep_research.web.auth.routes._perform_post_login_tasks",+ lambda _username, _password: None,+ )++class TestGetCsrfToken:"""Tests for /csrf-token endpoint."""@@ -896,6 +906,7 @@ class TestIntegrityCheck:assert response.json["integrity"] == "valid"[email protected]("disable_post_login_worker")class TestOpenRedirectPrevention:"""Tests for open redirect prevention in login."""@@ -1185,6 +1196,7 @@ class TestOpenRedirectPrevention:assert "admin" not in response.location[email protected]("disable_post_login_worker")class TestRedirectPathExtraction:"""Tests for defense-in-depth path extraction from redirect URLs.@@ -1362,6 +1374,82 @@ class TestRedirectPathExtraction:assert response.location.endswith("/")+class TestPostLoginWorkerDispatch:+ """Tests for successful-login background worker dispatch."""++ def test_successful_login_starts_post_login_worker(self):+ """The route must pass credentials to one daemon worker thread."""+ app = Flask(__name__)+ app.secret_key = "test"+ app.config["WTF_CSRF_ENABLED"] = False++ @app.route("/")+ def index():+ return "Index"++ app_ctx = object()+ wrapped_worker = MagicMock(name="wrapped_post_login_worker")+ thread = MagicMock(name="post_login_thread")++ with (+ patch(+ "local_deep_research.web.auth.routes.load_server_config",+ return_value={"allow_registrations": True},+ ),+ patch(+ "local_deep_research.web.auth.routes.db_manager"+ ) as mock_db_manager,+ patch(+ "local_deep_research.web.auth.routes.get_account_lockout_manager"+ ) as mock_get_lockout_manager,+ patch(+ "local_deep_research.web.auth.routes._create_user_session"+ ) as mock_create_user_session,+ patch(+ "local_deep_research.web.auth.routes.thread_context",+ return_value=app_ctx,+ ) as mock_thread_context,+ patch(+ "local_deep_research.web.auth.routes.thread_with_app_context",+ return_value=wrapped_worker,+ ) as mock_wrap_worker,+ patch(+ "local_deep_research.web.auth.routes.threading.Thread",+ return_value=thread,+ ) as mock_thread_cls,+ ):+ mock_db_manager.open_user_database.return_value = MagicMock()+ lockout_manager = mock_get_lockout_manager.return_value+ lockout_manager.is_locked.return_value = False++ from local_deep_research.web.auth.routes import (+ _perform_post_login_tasks,+ auth_bp,+ )++ app.register_blueprint(auth_bp)++ with app.test_client() as client:+ response = client.post(+ "/auth/login",+ data={+ "username": "testuser",+ "password": "password123",+ },+ )++ assert response.status_code == 302+ mock_create_user_session.assert_called_once()+ mock_thread_context.assert_called_once_with()+ mock_wrap_worker.assert_called_once_with(_perform_post_login_tasks)+ mock_thread_cls.assert_called_once_with(+ target=wrapped_worker,+ args=(app_ctx, "testuser", "password123"),+ daemon=True,+ )+ thread.start.assert_called_once_with()++class TestPostLoginTasksPasswordForwarding:"""Tests for _perform_post_login_tasks password forwarding."""diff --git a/tests/web/auth/test_cleanup_middleware.py b/tests/web/auth/test_cleanup_middleware.pyindex b2723b3819..c4a01db4e0 100644--- a/tests/web/auth/test_cleanup_middleware.py+++ b/tests/web/auth/test_cleanup_middleware.py@@ -91,6 +91,39 @@ class TestCleanupCompletedResearch:result = cleanup_completed_research()assert result is None+ def test_resolves_db_session_helper_at_call_time(self):+ """A temporary import-time patch must not become a stale dependency."""+ app = Flask(__name__)+ app.secret_key = "test"++ mock_db_session = MagicMock()+ mock_db_session.query.return_value.filter_by.return_value.limit.return_value.all.return_value = []++ from local_deep_research.web.auth import cleanup_middleware+ from flask import session++ with (+ patch.object(+ cleanup_middleware,+ "should_skip_database_middleware",+ return_value=False,+ ),+ patch.object(+ cleanup_middleware.db_session_context,+ "get_g_db_session",+ return_value=mock_db_session,+ ) as mock_get_db_session,+ ):+ with app.test_request_context("/dashboard"):+ session["username"] = "testuser"++ cleanup_middleware.cleanup_completed_research()++ mock_get_db_session.assert_called_once_with()+ mock_db_session.query.assert_called_once_with(+ cleanup_middleware.UserActiveResearch+ )+def test_cleans_up_completed_research_records(self):"""Should delete records for research not in active_research."""app = Flask(__name__)@@ -374,3 +407,19 @@ class TestCleanupCompletedResearch:assert result is Nonemock_db_session.query.assert_not_called()+++ ("sample", "expected"),+ [(1, True), (2, False)],+)+def test_should_run_cleanup_sampling(sample: int, expected: bool) -> None:+ """Sampling stays at one selected value without patching global random."""+ from local_deep_research.web.auth import cleanup_middleware++ with patch.object(cleanup_middleware, "random") as mock_random:+ mock_random.randint.return_value = sample++ assert cleanup_middleware._should_run_cleanup_sample() is expected++ mock_random.randint.assert_called_once_with(1, 100)