~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
ci(notes): gate releases on responsiveness and cleanup assertions (#6420)
LearningCircuitb709ab555cce
diff --git a/.github/workflows/notes-concurrency.yml b/.github/workflows/notes-concurrency.ymlnew file mode 100644index 0000000000..95e82ead34--- /dev/null+++ b/.github/workflows/notes-concurrency.yml@@ -0,0 +1,92 @@+name: Notes Concurrency++# Controlled blocking probes run only before releases or by manual request.+# No provider credentials, external model server, or Redis service are needed.+on:+ workflow_call:+ workflow_dispatch:++permissions: {}++jobs:+ notes-concurrency:+ runs-on: ubuntu-latest+ timeout-minutes: 20+ permissions:+ contents: read+ env:+ LDR_TESTING_WITH_MOCKS: 'false'+ LDR_DISABLE_RATE_LIMITING: 'false'++ steps:+ - name: Harden the runner+ uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1+ with:+ egress-policy: audit++ - name: Checkout repository+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false++ - name: Set up PDM+ uses: pdm-project/setup-pdm@544d7237314ee09c256785bd360f6b30add38b37 # v4.6+ with:+ python-version: '3.12'+ version: 2.26.2+ cache: true+ cache-restore-exact-match: true++ - name: Install SQLCipher system dependency+ run: |+ sudo apt-get update+ sudo apt-get install -y libsqlcipher-dev++ - name: Install project dependencies+ run: pdm sync -d --clean++ - name: Run notes concurrency regressions+ id: tests+ shell: bash+ run: |+ mkdir -p test-results+ pdm run pytest tests/integration/test_notes_release_concurrency.py \+ tests/notes/test_note_ai_service.py::TestNoteAIServiceAsyncTeardownAndOffload::test_cancellation_during_cleanup_waits_for_worker \+ -n 0 -p no:cov -v --tb=short --timeout=60 \+ --junitxml=test-results/notes-concurrency.xml \+ -o junit_logging=all \+ 2>&1 | tee test-results/notes-concurrency.log++ - name: Require executed and passing tests+ id: validate-results+ if: always()+ shell: bash+ run: |+ python - <<'PYTHON'+ from pathlib import Path+ from xml.etree import ElementTree++ report = Path("test-results/notes-concurrency.xml")+ if not report.is_file():+ raise SystemExit("Missing notes concurrency test report")+ root = ElementTree.parse(report).getroot()+ cases = list(root.iter("testcase"))+ if not cases:+ raise SystemExit("No notes concurrency tests executed")+ unsuccessful = [+ case.get("name", "unknown")+ for case in cases+ if any(child.tag in {"skipped", "failure", "error"} for child in case)+ ]+ if unsuccessful:+ raise SystemExit(f"Unsuccessful notes concurrency tests: {unsuccessful}")+ print(f"All {len(cases)} notes concurrency tests executed and passed")+ PYTHON++ - name: Upload concurrency diagnostics+ if: always()+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: notes-concurrency-results+ path: test-results/notes-concurrency.*+ retention-days: 14diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 18669309da..f2ad1ce567 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -176,6 +176,15 @@ jobs:permissions:contents: read+ # Required release-only probes: slow model cleanup and rate-limit storage+ # must allow unrelated requests to finish while preserving their behavior.+ notes-concurrency-gate:+ needs: [version-check]+ if: needs.version-check.outputs.should_release == 'true'+ uses: $/.github/workflows/notes-concurrency.yml+ permissions:+ contents: read+# ============================================================================# RESPONSIVE TEST GATE (Advisory) - Responsive UI tests across viewports# ============================================================================@@ -234,10 +243,10 @@ jobs:contents: readbuild:- needs: [version-check, release-gate, ci-gate, test-gate, e2e-test-gate, notes-test-gate, responsive-test-gate, compat-test-gate, compose-integration-gate, vulture-gate]+ needs: [version-check, release-gate, ci-gate, test-gate, e2e-test-gate, notes-test-gate, notes-concurrency-gate, responsive-test-gate, compat-test-gate, compose-integration-gate, vulture-gate]# test-gate (Playwright WebKit), responsive-test-gate, and vulture-gate are advisory- # release-gate, ci-gate, e2e-test-gate, notes-test-gate, compat-test-gate, and compose-integration-gate are required- if: ${{ !cancelled() && needs.release-gate.result == 'success' && needs.ci-gate.result == 'success' && needs.e2e-test-gate.result == 'success' && needs.notes-test-gate.result == 'success' && needs.compat-test-gate.result == 'success' && needs.compose-integration-gate.result == 'success' }}+ # release-gate, ci-gate, e2e-test-gate, notes-test-gate, notes-concurrency-gate, compat-test-gate, and compose-integration-gate are required+ if: ${{ !cancelled() && needs.release-gate.result == 'success' && needs.ci-gate.result == 'success' && needs.e2e-test-gate.result == 'success' && needs.notes-test-gate.result == 'success' && needs.notes-concurrency-gate.result == 'success' && needs.compat-test-gate.result == 'success' && needs.compose-integration-gate.result == 'success' }}runs-on: ubuntu-latestoutputs:version: ${{ steps.version.outputs.version }}diff --git a/docs/ci/workflow-status.md b/docs/ci/workflow-status.mdindex 6f040f7c6f..c9d4871a68 100644--- a/docs/ci/workflow-status.md+++ b/docs/ci/workflow-status.md@@ -29,7 +29,7 @@<!-- BEGIN GENERATED -->-**68 workflows:** 1 disabled · 3 stale · 1 manual-only · 63 active+**71 workflows:** 1 disabled · 3 stale · 1 manual-only · 66 active## ⚠ Disabled workflows@@ -73,7 +73,7 @@| `security-headers-validation.yml` | last 30 days | workflow_call, schedule(0 3 * * *), manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/security-headers-validation.yml) || `security-tests.yml` | last 30 days | workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/security-tests.yml) || `semgrep.yml` | last 30 days | workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/semgrep.yml) |-| `zizmor-security.yml` | last 30 days | manual, workflow_call, schedule(0 9 * * 1) | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/zizmor-security.yml) |+| `zizmor-security.yml` | last 30 days | PR, manual, workflow_call, schedule(0 9 * * 1) | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/zizmor-security.yml) |## Release gates — release-time only@@ -86,6 +86,7 @@| `docker-tests.yml` | last 30 days | PR, push:main, workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/docker-tests.yml) || `file-whitelist-check.yml` | last 30 days | PR, workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/file-whitelist-check.yml) || `mypy-type-check.yml` | last 30 days | PR, workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/mypy-type-check.yml) |+| `notes-concurrency.yml` | never | workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/notes-concurrency.yml) || `playwright-notes-tests.yml` | last 30 days | PR, workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/playwright-notes-tests.yml) || `playwright-webkit-tests.yml` | last 30 days | workflow_call, manual, schedule(0 2 * * *) | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/playwright-webkit-tests.yml) || `pre-commit.yml` | last 30 days | PR, workflow_call, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/pre-commit.yml) |@@ -106,6 +107,7 @@| `osv-scanner-scheduled.yml` | last 30 days | push:main, schedule(41 21 * * 1), manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/osv-scanner-scheduled.yml?query=event%3Aschedule) || `osv-scanner.yml` | last 30 days | PR, merge_group, schedule(39 12 * * 1), manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/osv-scanner.yml?query=event%3Aschedule) || `sbom.yml` | last 30 days | manual, schedule(0 10 * * 3), release | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/sbom.yml?query=event%3Aschedule) |+| `security-mxss-browser-tests.yml` | last 30 days | PR, manual, schedule(30 2 * * *) | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/security-mxss-browser-tests.yml?query=event%3Aschedule) || `update-dependencies.yml` | last 30 days | workflow_call, manual, schedule(0 8 * * 3) | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/update-dependencies.yml?query=event%3Aschedule) || `update-npm-dependencies.yml` | last 30 days | workflow_call, manual, schedule(0 8 * * 4) | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/update-npm-dependencies.yml?query=event%3Aschedule) || `update-oldest-auto-merge-pr.yml` | last 30 days | schedule(17,47 * * * *), manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/update-oldest-auto-merge-pr.yml?query=event%3Aschedule) |@@ -125,6 +127,7 @@| `gitleaks-rule-tests.yml` | last 30 days | PR, push:main,refactor/fastapi-migration-phase1, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/gitleaks-rule-tests.yml) || `labels-sync.yml` | last 30 days | push:main, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/labels-sync.yml) || `mcp-tests.yml` | last 30 days | push:main, PR, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/mcp-tests.yml) |+| `milvus-tests.yml` | last 30 days | push:main, PR, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/milvus-tests.yml) || `pr-triage.yml` | last 30 days | PR, pull_request_review | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/pr-triage.yml) || `release.yml` | last 30 days | push:main, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/release.yml) || `ui-full-shards.yml` | last 30 days | PR, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/ui-full-shards.yml) |diff --git a/docs/developing/notes-release-concurrency.md b/docs/developing/notes-release-concurrency.mdnew file mode 100644index 0000000000..0646605520--- /dev/null+++ b/docs/developing/notes-release-concurrency.md@@ -0,0 +1,49 @@+# Notes concurrency release check++`notes-concurrency.yml` runs before release publication and can also be started+manually from GitHub Actions. It does not run on ordinary pull requests. A failure,+cancellation, or skipped probe blocks the release build.++The probes hold synchronous model cleanup or rate-limit storage open and require+an unrelated request to complete before that work is released. An independent+watchdog records a failure before unblocking stalled work, so event-loop recovery+cannot turn a stall into a pass. The assertions cover:++- Owned models receive exactly one cleanup attempt after success, failure, or+ cancellation, and the request waits for cleanup to finish.+- A registered shared model stays usable across requests and remains owned by+ its registering caller.+- An unrelated request completes while cleanup or rate-limit storage is held.+- The notes AI quota allows ten requests, rejects the next with HTTP 429, and+ gives another user a separate quota.+- Deliberately blocking or removing cleanup, or disabling rate limiting, is+ rejected by the assertions themselves.++The probes use controlled local dependencies and require no model credentials+or Redis server. Elapsed times are diagnostics, not tight performance thresholds.+They exercise application cleanup ownership; native provider shutdown remains+provider-specific.+The release selection also includes a direct service cancellation test that+requires pending cleanup to finish before cancellation propagates.++After installing the development dependencies, run the release suite locally:++```sh+LDR_TESTING_WITH_MOCKS=false LDR_DISABLE_RATE_LIMITING=false \+ pdm run pytest tests/integration/test_notes_release_concurrency.py \+ tests/notes/test_note_ai_service.py::TestNoteAIServiceAsyncTeardownAndOffload::test_cancellation_during_cleanup_waits_for_worker \+ -n 0 -p no:cov -v --tb=short --timeout=60+```++Run it serially without coverage, as in the release workflow. The integration+marker keeps these deliberate blocking probes out of the ordinary mocked suite;+`LDR_TESTING_WITH_MOCKS=false` ensures they execute. The workflow independently+rejects missing, empty, skipped, or unsuccessful JUnit results, and preserves the+JUnit report and pytest output in the `notes-concurrency-results` artifact for+14 days, including failed runs.++The fast workflow contract tests run with the ordinary suite:++```sh+pdm run pytest tests/ci/test_notes_concurrency_release_gate.py -n 0 -p no:cov+```diff --git a/tests/ci/test_notes_concurrency_release_gate.py b/tests/ci/test_notes_concurrency_release_gate.pynew file mode 100644index 0000000000..fd369d035b--- /dev/null+++ b/tests/ci/test_notes_concurrency_release_gate.py@@ -0,0 +1,197 @@+"""The notes concurrency probes must execute and block a broken release."""++from __future__ import annotations++import os+from pathlib import Path+import shlex+import subprocess+import sys++import pytest+import yaml++REPO_ROOT = Path(__file__).resolve().parents[2]+WORKFLOWS = REPO_ROOT / ".github" / "workflows"+++def _workflow(name):+ parsed = yaml.safe_load((WORKFLOWS / name).read_text(encoding="utf-8"))+ # PyYAML uses YAML 1.1, which interprets the GitHub Actions `on` key as True.+ if True in parsed and "on" not in parsed:+ parsed["on"] = parsed.pop(True)+ return parsed++[email protected](scope="module")+def concurrency_workflow():+ return _workflow("notes-concurrency.yml")+++def test_release_requires_successful_concurrency_gate():+ jobs = _workflow("release.yml")["jobs"]+ gate = jobs["notes-concurrency-gate"]+ assert gate["uses"] == "$/.github/workflows/notes-concurrency.yml"+ assert gate["needs"] == ["version-check"]+ assert gate["if"] == (+ "needs.version-check.outputs.should_release == 'true'"+ )+ assert not gate.get("continue-on-error", False)++ # Existing required gates must stay required alongside the new one. An+ # advisory job in build.needs alone would not prevent publication because+ # build has an explicit status expression that permits advisory failures.+ required = {+ "release-gate",+ "ci-gate",+ "e2e-test-gate",+ "notes-test-gate",+ "notes-concurrency-gate",+ "compat-test-gate",+ "compose-integration-gate",+ }+ build = jobs["build"]+ assert required <= set(build["needs"])+ condition = build["if"].removeprefix("${{").removesuffix("}}")+ assert "||" not in condition, (+ "A successful advisory job must not bypass a gate"+ )+ operands = {operand.strip() for operand in condition.split("&&")}+ assert "!cancelled()" in operands+ for name in required:+ assert f"needs.{name}.result == 'success'" in operands+++def test_probes_run_serially_only_for_releases_or_manual_requests(+ concurrency_workflow,+):+ assert set(concurrency_workflow["on"]) == {+ "workflow_call",+ "workflow_dispatch",+ }+ job = concurrency_workflow["jobs"]["notes-concurrency"]+ assert "if" not in job, "A release call must not silently skip the probes"+ assert not job.get("continue-on-error", False)+ assert job["env"]["LDR_TESTING_WITH_MOCKS"] == "false"+ assert job["env"]["LDR_DISABLE_RATE_LIMITING"] == "false"+ steps = {step.get("id"): step for step in job["steps"] if "id" in step}+ run = steps["tests"]+ assert not run.get("continue-on-error", False)+ assert "if" not in run+ assert run["shell"] == "bash" # Actions runs bash with -e -o pipefail.+ command = shlex.split(run["run"])+ command = command[command.index("pytest") + 1 :]+ assert "tests/integration/test_notes_release_concurrency.py" in command+ assert (+ "tests/notes/test_note_ai_service.py::"+ "TestNoteAIServiceAsyncTeardownAndOffload::"+ "test_cancellation_during_cleanup_waits_for_worker"+ ) in command+ assert command[command.index("-n") + 1] == "0"+ assert command[command.index("-p") + 1] == "no:cov"+ assert "--junitxml=test-results/notes-concurrency.xml" in command+ assert steps["validate-results"]["if"] == "always()"+ assert not steps["validate-results"].get("continue-on-error", False)++ uploads = [+ step+ for step in job["steps"]+ if step.get("uses", "").startswith("actions/upload-artifact@")+ ]+ assert uploads, (+ "Keep diagnostics available when the watchdog detects a stall"+ )+ assert all(step["if"] == "always()" for step in uploads)+++ ("report", "passes"),+ [+ (+ '<testsuites><testsuite><testcase name="probe"/></testsuite></testsuites>',+ True,+ ),+ (None, False),+ ("<testsuites><testsuite tests='0'/></testsuites>", False),+ ("<testsuites>", False),+ *[+ (+ "<testsuites><testsuite>"+ '<testcase name="passed"/>'+ f'<testcase name="probe"><{outcome}/></testcase>'+ "</testsuite></testsuites>",+ False,+ )+ for outcome in ("skipped", "failure", "error")+ ],+ ],+ ids=[+ "pass",+ "missing",+ "empty",+ "malformed",+ "skipped",+ "failure",+ "error",+ ],+)+def test_report_validation_rejects_missing_or_unsuccessful_probes(+ concurrency_workflow, tmp_path, report, passes+):+ """Execute the workflow's real check, including a mixed pass/skip report."""+ if report is not None:+ reports = tmp_path / "test-results"+ reports.mkdir()+ (reports / "notes-concurrency.xml").write_text(report, encoding="utf-8")+ steps = concurrency_workflow["jobs"]["notes-concurrency"]["steps"]+ validator = next(+ step for step in steps if step.get("id") == "validate-results"+ )+ result = subprocess.run(+ ["bash", "-e", "-o", "pipefail", "-c", validator["run"]],+ cwd=tmp_path,+ env={+ **os.environ,+ "PATH": f"{Path(sys.executable).parent}{os.pathsep}{os.environ.get('PATH', '')}",+ },+ capture_output=True,+ text=True,+ timeout=10,+ check=False,+ )+ assert (result.returncode == 0) is passes, result.stdout + result.stderr+++ "pytest_status", [0, 1, 5], ids=["pass", "failure", "no-tests"]+)+def test_pytest_exit_status_survives_diagnostic_tee(+ concurrency_workflow, tmp_path, pytest_status+):+ """The artifact-producing pipeline must preserve pytest failure/no-tests."""+ binary_dir = tmp_path / "bin"+ binary_dir.mkdir()+ pdm = binary_dir / "pdm"+ pdm.write_text(+ f"#!/bin/sh\nprintf 'probe output\\n'\nexit {pytest_status}\n",+ encoding="utf-8",+ )+ pdm.chmod(0o755)+ steps = concurrency_workflow["jobs"]["notes-concurrency"]["steps"]+ test_step = next(step for step in steps if step.get("id") == "tests")+ result = subprocess.run(+ ["bash", "-e", "-o", "pipefail", "-c", test_step["run"]],+ cwd=tmp_path,+ env={+ **os.environ,+ "PATH": f"{binary_dir}{os.pathsep}{os.environ.get('PATH', '')}",+ },+ capture_output=True,+ text=True,+ timeout=10,+ check=False,+ )+ assert result.returncode == pytest_status, result.stdout + result.stderr+ assert (+ tmp_path / "test-results" / "notes-concurrency.log"+ ).read_text() == ("probe output\n")diff --git a/tests/integration/test_notes_release_concurrency.py b/tests/integration/test_notes_release_concurrency.pynew file mode 100644index 0000000000..615b13b494--- /dev/null+++ b/tests/integration/test_notes_release_concurrency.py@@ -0,0 +1,390 @@+"""Release assertions for note AI concurrency, without external model calls.++Run serially with LDR_TESTING_WITH_MOCKS=false. The real notes router,+SlowAPI middleware, registry and model wrappers are exercised. Only DB reads+and the model/network boundary are controlled. Deadlines are escape hatches;+success requires an independent request to finish BEFORE a held operation+is released, not a machine-dependent latency target.+"""++import asyncio+import threading+from concurrent.futures import TimeoutError as FutureTimeout+from contextlib import asynccontextmanager+from types import SimpleNamespace++import httpx+import pytest+from fastapi import FastAPI, Request+from langchain_core.language_models import BaseChatModel+from langchain_core.messages import AIMessage+from langchain_core.outputs import ChatGeneration, ChatResult+from limits.storage import MemoryStorage+from limits.strategies import MovingWindowRateLimiter+from pydantic import PrivateAttr+from slowapi import _rate_limit_exceeded_handler+from slowapi.errors import RateLimitExceeded+from slowapi.middleware import SlowAPIMiddleware+from starlette.middleware.sessions import SessionMiddleware++from local_deep_research.llm import register_llm, unregister_llm+from local_deep_research.research_library.notes.services.note_ai_service import (+ NoteAIService,+)+from local_deep_research.web.dependencies.auth import require_auth+from local_deep_research.web.routers import notes++pytestmark = [pytest.mark.integration, pytest.mark.asyncio]++DEADLINE = 10.0+PROVIDER = "release-concurrency-probe"+SUMMARY_URL = "/notes/api/notes/release-note/summarize"+++class _HeldOperation:+ """An external watchdog releases even a synchronously blocked loop.++ The watchdog stores its result before releasing the held operation.+ A health response arriving after a timeout cannot turn failure into+ success. Assertions live outside provider cleanup, which swallows errors.+ """++ def __init__(self, progress_timeout=DEADLINE):+ self.progress_timeout = progress_timeout+ self.entered = threading.Event()+ self.release = threading.Event()+ self.finished = threading.Event()+ self.progress = False+ self.expired = False+ self.error = None+ self.calls = 0+ # Set as soon as the operation returns, even when a later assertion+ # in this method raises -- lets a caller inspect what the operation+ # actually produced (e.g. its status code) instead of only the+ # AssertionError text.+ self.result = None++ def hold(self):+ self.calls += 1+ self.entered.set()+ try:+ if not self.release.wait(DEADLINE + self.progress_timeout * 2):+ self.expired = True+ finally:+ self.finished.set()++ async def run(self, client, operation):+ loop = asyncio.get_running_loop()++ def watch():+ pending = None+ try:+ if not self.entered.wait(DEADLINE):+ self.error = "held operation never started"+ return+ pending = asyncio.run_coroutine_threadsafe(+ client.get("/release-probe"), loop+ )+ response = pending.result(timeout=self.progress_timeout)+ self.progress = (+ response.status_code == 200+ and response.json() == {"ok": True}+ and not self.finished.is_set()+ )+ except FutureTimeout:+ self.error = "event loop did not serve the independent request"+ except Exception as exc:+ self.error = f"independent request failed: {type(exc).__name__}"+ finally:+ if pending is not None and not pending.done():+ pending.cancel()+ self.release.set()++ watchdog = threading.Thread(target=watch, daemon=True)+ watchdog.start()+ try:+ result = await operation()+ self.result = result+ # Record this before joining the watchdog: joining can otherwise+ # let detached cleanup finish after the request already returned.+ finished_before_return = self.finished.is_set()+ await asyncio.to_thread(watchdog.join, DEADLINE * 2)+ assert not watchdog.is_alive(), "watchdog did not finish"+ assert self.entered.is_set(), "held operation never started"+ assert self.progress, (+ self.error or "independent request ran too late"+ )+ assert finished_before_return, (+ "request completed before held operation finished"+ )+ assert not self.expired, "held operation escaped on its own timeout"+ return result+ finally:+ self.release.set()+ await asyncio.to_thread(watchdog.join, DEADLINE * 2)+++class _LocalModel(BaseChatModel):+ _gate = PrivateAttr(default=None)+ _mode = PrivateAttr(default="success")+ _started = PrivateAttr(default=None)+ _closed = PrivateAttr(default=False)+ _close_calls = PrivateAttr(default=0)+ _invoke_calls = PrivateAttr(default=0)++ @property+ def _llm_type(self):+ return "release-local-model"++ def _generate(self, messages, stop=None, run_manager=None, **kwargs):+ raise AssertionError("notes unexpectedly used synchronous inference")++ async def _agenerate(self, messages, stop=None, run_manager=None, **kwargs):+ assert not self._closed, "a closed model was reused"+ self._invoke_calls += 1+ self._started.set()+ if self._mode == "cancel":+ await asyncio.Event().wait()+ if self._mode == "error":+ raise RuntimeError("release-probe model failure")+ return ChatResult(+ generations=[ChatGeneration(message=AIMessage(content="summary"))]+ )++ def close(self):+ self._close_calls += 1+ if self._gate is not None:+ self._gate.hold()+ self._closed = True+++def harness(monkeypatch):+ # Use a fresh real storage backend while retaining the production+ # registrations and key functions. Simulated latency is added at the+ # same acquire_entry boundary that network-backed storage implements.+ storage = MemoryStorage()+ limiter = notes.limiter+ assert limiter.enabled, "release checks require rate limiting enabled"+ monkeypatch.setattr(limiter, "_storage", storage)+ monkeypatch.setattr(limiter, "_limiter", MovingWindowRateLimiter(storage))+ monkeypatch.setattr(limiter, "_exempt_routes", set(limiter._exempt_routes))+ app = FastAPI()+ app.include_router(notes.router)+ app.state.limiter = limiter+ app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)+ app.add_middleware(SessionMiddleware, secret_key="release-suite-session")+ app.add_middleware(SlowAPIMiddleware)++ async def authenticated_user(request: Request):+ return request.session["username"]++ app.dependency_overrides[require_auth] = authenticated_user++ @app.get("/release-probe")+ @limiter.exempt+ async def health():+ return {"ok": True}++ @app.post("/release-session/{username}")+ @limiter.exempt+ async def session(request: Request, username: str):+ request.session["username"] = username+ return {"ok": True}++ monkeypatch.setattr(+ NoteAIService, "_get_note_content", lambda self, note_id: "note text"+ )+ monkeypatch.setattr(+ NoteAIService,+ "_build_settings_snapshot",+ lambda self: {+ "llm.provider": PROVIDER,+ "llm.model": "local-test",+ "search.tool": "searxng",+ "_username": self.username,+ },+ )++ def install_model(gate=None, mode="success", shared=False):+ state = SimpleNamespace(models=[], started=asyncio.Event())++ def factory(**kwargs):+ model = _LocalModel()+ model._gate = gate+ model._mode = mode+ model._started = state.started+ state.models.append(model)+ return model++ register_llm(PROVIDER, factory() if shared else factory)+ return state++ @asynccontextmanager+ async def connect(username="alice"):+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app),+ base_url="http://testserver",+ ) as client:+ response = await client.post(f"/release-session/{username}")+ assert response.status_code == 200+ yield client++ yield SimpleNamespace(+ app=app,+ connect=connect,+ install_model=install_model,+ limiter=limiter,+ storage=storage,+ )+ unregister_llm(PROVIDER)+ storage.reset()++[email protected]("outcome", ["success", "error", "cancel"])+async def test_owned_cleanup_preserves_responsiveness(harness, outcome):+ gate = _HeldOperation()+ state = harness.install_model(gate=gate, mode=outcome)+ async with harness.connect() as client:++ async def request():+ if outcome != "cancel":+ return await client.post(SUMMARY_URL, json={})+ task = asyncio.create_task(client.post(SUMMARY_URL, json={}))+ try:+ await asyncio.wait_for(state.started.wait(), DEADLINE)+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ finally:+ if not task.done():+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)++ response = await gate.run(client, request)++ if outcome == "success":+ assert response.status_code == 200+ assert response.json() == {"success": True, "summary": "summary"}+ elif outcome == "error":+ assert response.status_code == 500+ assert response.json()["success"] is False+ assert len(state.models) == 1, "model factory was bypassed"+ model = state.models[0]+ assert model._invoke_calls == 1+ assert model._close_calls == 1, "owned cleanup was removed or duplicated"+ assert model._closed, "request completed before cleanup finished"+++async def test_shared_model_remains_usable_after_consumer_cleanup(harness):+ state = harness.install_model(shared=True)+ async with harness.connect() as client:+ for _ in range(2):+ response = await client.post(SUMMARY_URL, json={})+ assert response.status_code == 200+ assert response.json()["summary"] == "summary"+ model = state.models[0]+ assert model._invoke_calls == 2+ assert model._close_calls == 0, "consumer closed a caller-owned model"+ assert not model._closed+++def _assert_per_minute_window(harness):+ """The count-based checks in ``_assert_quota`` (9 pass, the 10th 429s)+ pass identically whether the route is "10 per minute" or "10 per hour"+ -- they pin the count and the per-user key but never the window. Read+ the actual RateLimitItem slowapi registered for the route (not a+ re-declared literal) so a widened window fails this even though the+ count-only checks above still pass.+ """+ name = f"{notes.summarize_note.__module__}.{notes.summarize_note.__name__}"+ route_limits = harness.limiter._route_limits.get(name, [])+ assert route_limits, (+ "no registered rate limit found for the summarize route"+ )+ windows = {limit.limit.GRANULARITY.seconds for limit in route_limits}+ assert windows and max(windows) <= 60, (+ f"quota window is not per-minute (or tighter): {windows} seconds"+ )+++async def _assert_quota(harness, alice, first_response):+ assert first_response.status_code == 200+ for _ in range(9):+ response = await alice.post(SUMMARY_URL, json={})+ assert response.status_code == 200, "quota was consumed more than once"+ response = await alice.post(SUMMARY_URL, json={})+ assert response.status_code == 429, "rate limiting was disabled or bypassed"+ _assert_per_minute_window(harness)+ async with harness.connect("bob") as bob:+ response = await bob.post(SUMMARY_URL, json={})+ assert response.status_code == 200, "users shared a rate-limit quota"+++async def test_storage_preserves_responsiveness_and_user_quotas(+ harness, monkeypatch+):+ state = harness.install_model()+ gate = _HeldOperation()+ acquire = harness.storage.acquire_entry++ def held_storage(*args, **kwargs):+ if not gate.entered.is_set():+ gate.hold()+ return acquire(*args, **kwargs)++ monkeypatch.setattr(harness.storage, "acquire_entry", held_storage)+ async with harness.connect() as alice:+ first = await gate.run(alice, lambda: alice.post(SUMMARY_URL, json={}))+ await _assert_quota(harness, alice, first)+ assert gate.calls == 1, "storage latency injection was bypassed"+ assert sum(model._invoke_calls for model in state.models) == 11++[email protected]("regression", ["blocking", "removed"])+async def test_cleanup_assertion_rejects_known_regressions(+ harness, monkeypatch, regression+):+ # Only the deliberately blocked progress phase gets a short timeout.+ # Startup remains generous so runner load cannot mask the intended fault.+ gate = _HeldOperation(progress_timeout=0.2)+ harness.install_model(gate=gate)++ async def broken_invoke(self, llm, prompt):+ try:+ return await llm.ainvoke(prompt)+ finally:+ if regression == "blocking":+ self._close_llm(llm)++ monkeypatch.setattr(NoteAIService, "_ainvoke_and_close", broken_invoke)+ expected = (+ "event loop did not serve"+ if regression == "blocking"+ else "never started"+ )+ async with harness.connect() as client:+ with pytest.raises(AssertionError, match=expected):+ await gate.run(client, lambda: client.post(SUMMARY_URL, json={}))+ if regression == "removed":+ # "never started" alone is also produced by any failure before+ # cleanup is reached (a bypassed model factory, an early 4xx) --+ # that is not this regression. Pin it to what only a skipped+ # cleanup produces: the request itself succeeded.+ assert gate.result is not None, "no request result was recorded"+ assert gate.result.status_code == 200, (+ "the removed-cleanup regression must be a successful "+ "request with cleanup skipped, not an earlier failure"+ )+ assert not gate.entered.is_set(), (+ "cleanup must never have started for this regression"+ )+++async def test_quota_assertion_rejects_disabled_limiting(harness, monkeypatch):+ harness.install_model()+ monkeypatch.setattr(harness.limiter, "enabled", False)+ async with harness.connect() as client:+ first = await client.post(SUMMARY_URL, json={})+ with pytest.raises(AssertionError, match="disabled or bypassed"):+ await _assert_quota(harness, client, first)