~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(web): follow-up to #6095 worker DB session cleanup (#6207)
LearningCircuitc3f8e8c87ba6
diff --git a/changelog.d/+6095-followup-worker-session-cleanup.bugfix.md b/changelog.d/+6095-followup-worker-session-cleanup.bugfix.mdnew file mode 100644index 0000000000..a2dd0bcd2b--- /dev/null+++ b/changelog.d/+6095-followup-worker-session-cleanup.bugfix.md@@ -0,0 +1,19 @@+Follow-up to the #6095 FastAPI worker DB session cleanup: bounded a+multi-user pool-exhaustion vector where two of the library API's per-item+loops (the library index route, `/library/api/documents`, `POST+/library/api/sync-library`) could each pin one extra pooled connection per+LRU eviction of another user's cached session on the same worker, and+added cleanup when a suspended stream iterator is closed or finalized.+This does not establish immediate iterator closure on client disconnect.++Behaviour note: this wrapper's `GeneratorExit` handler gives the wrapped+generator a cleanup boundary whenever the wrapper itself is closed or+finalized, closing the wrapped generator inside that boundary. If a+streamed body's own `finally` raises during that close, the exception+propagates out of `close()` instead of being silently swallowed. That+guarantee only covers the close path itself, though: starlette's+`iterate_in_threadpool` (which drives every production `StreamingResponse`+body) never explicitly calls `close()` on its source iterator, so on the+production path this wrapper -- and any such error -- is only closed at+garbage collection, where a raising `close()` is again reported as an+"Exception ignored" message rather than surfaced to a caller.diff --git a/changelog.d/6095.bugfix.md b/changelog.d/6095.bugfix.mdindex 88b13683b6..81f8ae83d7 100644--- a/changelog.d/6095.bugfix.md+++ b/changelog.d/6095.bugfix.md@@ -1,4 +1,8 @@Fixed FastAPI worker threads retaining per-user database connections aftersynchronous request handlers and streamed-response chunks, which could-exhaust the connection pool during research and cause a successful login to-redirect back to the login page.+exhaust the connection pool during research. A pool-exhaustion timeout on an+authenticated request surfaces as a 500, not a redirect to login; the+original wording of this note additionally claimed pool exhaustion could+make a successful login redirect back to the login page, but that specific+mechanism could not be traced (`is_user_connected()` is a lock-guarded dict+membership check, not affected by pool state) and is not asserted here.diff --git a/pyproject.toml b/pyproject.tomlindex da0e0de5e4..b961ae7f1d 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -125,6 +125,22 @@ dependencies = [# fastapi 0.136.3 + starlette 1.3.1 was verified in a clean venv to# include routers correctly and serve requests, which is what let the# starlette security floor below be raised without touching this pin.+ #+ # A future bump carries a second, unrelated cost: fastapi 0.141.1+ # REMOVED ``Dependant.is_coroutine_callable`` / ``is_gen_callable`` /+ # ``is_async_gen_callable``. Three places read those flags and must be+ # rewritten in the same change, or ``WorkerCleanupAPIRoute.__init__``+ # raises ``AttributeError`` reading them on the very first route it+ # wraps -- a hard crash at app import, not a silently unenforced+ # #6095 owner-worker cleanup guarantee. Update:+ # - src/local_deep_research/web/dependencies/threadpool.py —+ # ``wrap_sync_route_with_cleanup``'s skip branch+ # - tests/web/dependencies/test_threadpool.py —+ # ``test_production_app_wraps_every_sync_api_route`` (BOTH the+ # ``sync_routes`` census and the ``generator_routes`` assertion)+ # - tests/web/dependencies/test_threadpool.py —+ # ``test_worker_cleanup_gates_on_fastapi_callable_classification+ # _not_inspect``"fastapi~=0.136.3",# Pin starlette explicitly so the lock cannot float it.#diff --git a/src/local_deep_research/database/thread_local_session.py b/src/local_deep_research/database/thread_local_session.pyindex f2da9ba525..6c45058beb 100644--- a/src/local_deep_research/database/thread_local_session.py+++ b/src/local_deep_research/database/thread_local_session.py@@ -355,9 +355,35 @@ def cleanup_current_thread():cleanup_cached_user_sessions_current_thread()except Exception:- logger.debug(- "cleanup_current_thread: error closing cached DB sessions",- exc_info=True,+ # ERROR, not debug: this is the #6095 owner-thread registry+ # cleanup that turns a GC-reclaimable session leak into a+ # deterministic release. If it ever breaks (e.g. a cachetools+ # upgrade renames ``cache_lock``), the fix silently reverts to the+ # pre-#6095 behavior (an evicted session waits on the cyclic+ # collector to reclaim its pooled connection) with nothing above+ # debug level to notice.+ #+ # Uses logger.exception(), NOT logger.warning(..., exc_info=True):+ # this module imports raw loguru (see the module imports above),+ # which has no ``exc_info`` parameter. Passing it to warning()+ # makes it an ordinary str.format kwarg that is silently discarded,+ # so no traceback is emitted at all -- verified empirically.+ # ``logger.exception()`` logs at ERROR, louder than WARNING, which+ # suits a silent revert to pre-#6095 behaviour.+ #+ # It DOES attach the traceback: this is plain loguru, not+ # SecureLogger, so nothing gates that on diagnose mode. The+ # traceback still does not leave the process. The encrypted-DB sink+ # persists ``_exception_context(record) + record["message"]`` -- an+ # exception type/value prefix, never the frames -- and the frontend+ # sink forwards only ``record["message"]``; see ``database_sink``,+ # ``_exception_context`` and the frontend sink in+ # ``utilities/log_utils.py``. It reaches the stderr/file sinks,+ # which is exactly where it is wanted.+ logger.exception(+ "cleanup_current_thread: error closing cached DB sessions "+ "(owner-thread registry cleanup failed — falling back to "+ "GC-reclaimed cleanup for this thread's sessions)")try:from .thread_metrics import metrics_writerdiff --git a/src/local_deep_research/research_library/services/library_service.py b/src/local_deep_research/research_library/services/library_service.pyindex cc1d223c29..097dbc4726 100644--- a/src/local_deep_research/research_library/services/library_service.py+++ b/src/local_deep_research/research_library/services/library_service.py@@ -29,6 +29,8 @@ from ...database.models.metrics import ResearchRatingfrom ...database.models.research import ResearchHistory, ResearchResourcefrom ...database.session_context import get_user_db_sessionfrom ...config.paths import get_library_directory+from ...utilities.db_utils import get_settings_manager+from ...utilities.resource_utils import safe_closefrom ...utilities.sql_utils import escape_like as _escape_likefrom ..utils import (get_absolute_path_from_settings,@@ -409,105 +411,147 @@ class LibraryService:# Process results — deduplicate by doc.id since the ResourceByDoc# outer join can fan out when multiple ResearchResource rows# point to the same document via document_id.+ #+ # Resolve one settings manager for the whole page (lazily, on the+ # first document that actually needs a path resolved) instead of+ # letting get_absolute_path_from_settings() fall back to the+ # ambient get_settings_manager() per iteration (up to `limit`+ # times). Each ambient call opens a DB session via+ # get_db_session(), which is now tracked in a per-thread owner+ # registry (utilities/db_utils.py) until this request's cleanup+ # boundary — so on a busy multi-user instance, enough process-wide+ # LRU evictions between iterations can pin one pooled connection+ # per evicted-and-recreated session for the rest of the request+ # (see changelog/#6095 follow-up). Creating it once here bounds+ # that to at most one session for this call, mirroring the+ # pattern already used in DownloadService (self.settings,+ # threaded through get_absolute_path_from_settings calls).seen_doc_ids = set()- for doc, res_by_fk, res_by_doc, research, doc_collection in results:- if doc.id in seen_doc_ids:- continue- seen_doc_ids.add(doc.id)- # Prefer the resource matched via Document.resource_id FK;- # fall back to the one matched via ResearchResource.document_id.- resource = res_by_fk or res_by_doc- # Determine availability flags - use Document.file_path directly- file_absolute_path = None- if doc.file_path and doc.file_path not in FILE_PATH_SENTINELS:- abs_path = get_absolute_path_from_settings(- doc.file_path, self.username+ settings_manager = None+ try:+ for (+ doc,+ res_by_fk,+ res_by_doc,+ research,+ doc_collection,+ ) in results:+ if doc.id in seen_doc_ids:+ continue+ seen_doc_ids.add(doc.id)+ # Prefer the resource matched via Document.resource_id FK;+ # fall back to the one matched via ResearchResource.document_id.+ resource = res_by_fk or res_by_doc+ # Determine availability flags - use Document.file_path directly+ file_absolute_path = None+ if (+ doc.file_path+ and doc.file_path not in FILE_PATH_SENTINELS+ ):+ if settings_manager is None:+ settings_manager = get_settings_manager(+ username=self.username+ )+ abs_path = get_absolute_path_from_settings(+ doc.file_path,+ self.username,+ settings_manager=settings_manager,+ )+ if abs_path:+ file_absolute_path = str(abs_path)++ # Check if PDF is available (filesystem OR database)+ has_pdf = bool(file_absolute_path)+ if not has_pdf and doc.storage_mode == "database":+ has_pdf = doc.id in blob_ids+ has_text_db = bool(doc.text_content) # Text now in Document++ # Use DocumentCollection from query results+ has_rag_indexed = (+ doc_collection.indexed if doc_collection else False+ )+ rag_chunk_count = (+ doc_collection.chunk_count if doc_collection else 0)- if abs_path:- file_absolute_path = str(abs_path)-- # Check if PDF is available (filesystem OR database)- has_pdf = bool(file_absolute_path)- if not has_pdf and doc.storage_mode == "database":- has_pdf = doc.id in blob_ids- has_text_db = bool(doc.text_content) # Text now in Document- # Use DocumentCollection from query results- has_rag_indexed = (- doc_collection.indexed if doc_collection else False- )- rag_chunk_count = (- doc_collection.chunk_count if doc_collection else 0- )+ all_documents.append(+ {+ "id": doc.id,+ "resource_id": doc.resource_id,+ "research_id": doc.research_id,+ # Document info+ "document_title": doc.title+ or (resource.title if resource else doc.filename),+ "authors": doc.authors,+ "published_date": doc.published_date,+ "doi": doc.doi,+ "arxiv_id": doc.arxiv_id,+ "pmid": doc.pmid,+ # File info+ "file_path": doc.file_path,+ "file_absolute_path": file_absolute_path,+ "file_name": Path(doc.file_path).name+ if doc.file_path+ and doc.file_path not in FILE_PATH_SENTINELS+ else doc.filename,+ "file_size": doc.file_size,+ "file_type": doc.file_type,+ # URLs+ "original_url": doc.original_url,+ "domain": self._extract_domain(doc.original_url)+ if doc.original_url+ else "User Upload",+ # Status+ "download_status": doc.status or "completed",+ "downloaded_at": doc.processed_at.isoformat()+ if doc.processed_at+ else (+ doc.uploaded_at.isoformat()+ if hasattr(doc, "uploaded_at")+ and doc.uploaded_at+ else None+ ),+ "favorite": doc.favorite+ if hasattr(doc, "favorite")+ else False,+ "tags": doc.tags if hasattr(doc, "tags") else [],+ # Research info (None for user uploads)+ "research_title": research.title+ or research.query[:80]+ if research+ else "User Upload",+ "research_query": research.query+ if research+ else None,+ "research_mode": research.mode+ if research+ else None,+ "research_date": research.created_at+ if research+ else None,+ # Classification flags+ "is_arxiv": self._is_arxiv_url(doc.original_url)+ if doc.original_url+ else False,+ "is_pubmed": self._is_pubmed_url(doc.original_url)+ if doc.original_url+ else False,+ "is_pdf": doc.file_type == "pdf",+ # Availability flags+ "has_pdf": has_pdf,+ "has_text_db": has_text_db,+ "has_rag_indexed": has_rag_indexed,+ "rag_chunk_count": rag_chunk_count,+ }+ )- all_documents.append(- {- "id": doc.id,- "resource_id": doc.resource_id,- "research_id": doc.research_id,- # Document info- "document_title": doc.title- or (resource.title if resource else doc.filename),- "authors": doc.authors,- "published_date": doc.published_date,- "doi": doc.doi,- "arxiv_id": doc.arxiv_id,- "pmid": doc.pmid,- # File info- "file_path": doc.file_path,- "file_absolute_path": file_absolute_path,- "file_name": Path(doc.file_path).name- if doc.file_path- and doc.file_path not in FILE_PATH_SENTINELS- else doc.filename,- "file_size": doc.file_size,- "file_type": doc.file_type,- # URLs- "original_url": doc.original_url,- "domain": self._extract_domain(doc.original_url)- if doc.original_url- else "User Upload",- # Status- "download_status": doc.status or "completed",- "downloaded_at": doc.processed_at.isoformat()- if doc.processed_at- else (- doc.uploaded_at.isoformat()- if hasattr(doc, "uploaded_at") and doc.uploaded_at- else None- ),- "favorite": doc.favorite- if hasattr(doc, "favorite")- else False,- "tags": doc.tags if hasattr(doc, "tags") else [],- # Research info (None for user uploads)- "research_title": research.title or research.query[:80]- if research- else "User Upload",- "research_query": research.query if research else None,- "research_mode": research.mode if research else None,- "research_date": research.created_at- if research- else None,- # Classification flags- "is_arxiv": self._is_arxiv_url(doc.original_url)- if doc.original_url- else False,- "is_pubmed": self._is_pubmed_url(doc.original_url)- if doc.original_url- else False,- "is_pdf": doc.file_type == "pdf",- # Availability flags- "has_pdf": has_pdf,- "has_text_db": has_text_db,- "has_rag_indexed": has_rag_indexed,- "rag_chunk_count": rag_chunk_count,- }+ # Sorting and pagination are now handled at SQL level+ return all_documents+ finally:+ safe_close(+ settings_manager, "settings manager", allow_none=True)- # Sorting and pagination are now handled at SQL level- return all_documents-def get_all_collections(self) -> List[Dict]:"""Get all collections with document and indexed document counts."""with get_user_db_session(self.username) as session:@@ -1165,8 +1209,6 @@ class LibraryService:def _get_storage_path(self) -> str:"""Get library storage path from settings (respects LDR_DATA_DIR)."""- from ...utilities.db_utils import get_settings_manager-settings = get_settings_manager()return str(Path(@@ -1215,41 +1257,77 @@ class LibraryService:# purged AFTER this transaction commits (see the post-commit block).removed_doc_ids: List[str] = []- # Sync documents with filesystem- for doc in documents:- # Get download tracker- tracker = (- session.query(DownloadTracker)- .filter_by(url_hash=self._get_url_hash(doc.original_url))- .first()- )-- if tracker and tracker.file_path:- # Check if file exists (per-user, legacy-shared fallback)- file_path = get_absolute_path_from_settings(- tracker.file_path, self.username+ # Sync documents with filesystem.+ #+ # Resolve one settings manager for the whole sync (lazily, on the+ # first document that actually needs a path resolved) instead of+ # letting get_absolute_path_from_settings() fall back to the+ # ambient get_settings_manager() per document (this is a sync+ # `def`, so a large library means one iteration per completed+ # document, unbounded). Each ambient call opens a DB session that+ # is now tracked in a per-thread owner registry+ # (utilities/db_utils.py) until this request's cleanup boundary,+ # so enough process-wide LRU evictions between iterations can pin+ # one pooled connection per evicted-and-recreated session for the+ # rest of the request (see changelog/#6095 follow-up). Creating+ # it once here bounds that to at most one session, mirroring+ # DownloadService's self.settings pattern.+ settings_manager = None+ try:+ for doc in documents:+ # Get download tracker+ tracker = (+ session.query(DownloadTracker)+ .filter_by(+ url_hash=self._get_url_hash(doc.original_url)+ )+ .first())- if file_path and file_path.is_file():- stats["files_found"] += 1- else:- # File missing or path invalid - mark for re-download- stats["files_missing"] += 1- stats["missing_files"].append(- {- "id": doc.id,- "title": doc.title,- "path": str(file_path)- if file_path- else "invalid",- "url": doc.original_url,- }++ if tracker and tracker.file_path:+ # Check if file exists (per-user, legacy-shared fallback)+ if settings_manager is None:+ settings_manager = get_settings_manager(+ username=self.username+ )+ file_path = get_absolute_path_from_settings(+ tracker.file_path,+ self.username,+ settings_manager=settings_manager,)+ if file_path and file_path.is_file():+ stats["files_found"] += 1+ else:+ # File missing or path invalid - mark for re-download+ stats["files_missing"] += 1+ stats["missing_files"].append(+ {+ "id": doc.id,+ "title": doc.title,+ "path": str(file_path)+ if file_path+ else "invalid",+ "url": doc.original_url,+ }+ )- # Reset tracker- tracker.is_downloaded = False- tracker.file_path = None+ # Reset tracker+ tracker.is_downloaded = False+ tracker.file_path = None- # Delete the document entry so it can be re-queued+ # Delete the document entry so it can be re-queued+ from ..deletion.utils.cascade_helper import (+ CascadeHelper,+ )++ CascadeHelper.delete_document_completely(+ session, doc.id+ )+ removed_doc_ids.append(doc.id)+ stats["trackers_updated"] += 1+ else:+ # No tracker or path - delete the document entry+ stats["files_missing"] += 1from ..deletion.utils.cascade_helper import (CascadeHelper,)@@ -1258,14 +1336,10 @@ class LibraryService:session, doc.id)removed_doc_ids.append(doc.id)- stats["trackers_updated"] += 1- else:- # No tracker or path - delete the document entry- stats["files_missing"] += 1- from ..deletion.utils.cascade_helper import CascadeHelper-- CascadeHelper.delete_document_completely(session, doc.id)- removed_doc_ids.append(doc.id)+ finally:+ safe_close(+ settings_manager, "settings manager", allow_none=True+ )session.commit()logger.info(diff --git a/src/local_deep_research/utilities/db_utils.py b/src/local_deep_research/utilities/db_utils.pyindex db2be7a59d..f9ea78be07 100644--- a/src/local_deep_research/utilities/db_utils.py+++ b/src/local_deep_research/utilities/db_utils.py@@ -131,7 +131,29 @@ def cleanup_cached_user_sessions_current_thread() -> int:try:session.close()except Exception:- logger.warning(+ # This session has already been dropped from both the LRU+ # cache and the owner-thread registry above, so this is the+ # only place the actual close failure is ever observable — a+ # bare warning with no traceback makes a real driver-level+ # failure indistinguishable from routine noise.+ #+ # logger.exception(), not logger.warning(..., exc_info=True):+ # this module imports raw loguru (see the module imports+ # above), which has no ``exc_info`` parameter, so that kwarg is+ # silently swallowed as a format argument and yields no+ # traceback whatsoever.+ #+ # ``logger.exception()`` DOES attach the traceback — this is+ # plain loguru, not SecureLogger, so nothing gates it on+ # diagnose mode. The traceback does not leave the process: the+ # encrypted-DB sink persists ``_exception_context(record) ++ # record["message"]`` (exception type/value prefix only, never+ # the frames) and the frontend sink forwards only+ # ``record["message"]``; see ``database_sink``,+ # ``_exception_context`` and the frontend sink in+ # ``utilities/log_utils.py``. It reaches the stderr/file sinks,+ # which is the point.+ logger.exception("Failed to close a cached DB session on worker cleanup")diff --git a/src/local_deep_research/web/dependencies/threadpool.py b/src/local_deep_research/web/dependencies/threadpool.pyindex 6b005643d5..4230e32dbf 100644--- a/src/local_deep_research/web/dependencies/threadpool.py+++ b/src/local_deep_research/web/dependencies/threadpool.py@@ -21,23 +21,51 @@ from __future__ import annotationsimport asyncioimport functools-import inspectfrom collections.abc import AsyncIterable, Iterable, Iterator-from typing import Any, Callable, TypeVar+from typing import TYPE_CHECKING, Any, Callable, TypeVarfrom fastapi.encoders import jsonable_encoderfrom fastapi.routing import APIRoute, APIRouterfrom loguru import loggerfrom starlette.responses import Response, StreamingResponse+if TYPE_CHECKING:+ from fastapi.dependencies.models import Dependant+T = TypeVar("T")_WORKER_CLEANUP_MARKER = "__ldr_worker_thread_cleanup__"-def wrap_sync_route_with_cleanup(fn: Callable[..., T]) -> Callable[..., T]:+def wrap_sync_route_with_cleanup(dependant: "Dependant") -> None:"""Wrap a synchronous FastAPI endpoint in an owner-thread cleanup.+ Mutates ``dependant.call`` in place; does not return the wrapped+ callable. Takes the ``Dependant`` (rather than the bare callable) so the+ sync/async/generator classification below can use FastAPI's own+ ``is_coroutine_callable`` / ``is_gen_callable`` / ``is_async_gen_callable``+ (``fastapi/dependencies/models.py``) instead of ``inspect.iscoroutinefunction``+ et al. Those ``inspect`` functions do NOT follow a ``functools.wraps``+ ``__wrapped__`` chain; FastAPI's own predicates do (via+ ``inspect.unwrap``), and FastAPI dispatches based on its own predicates+ -- so a hypothetical ``functools.wraps``-decorated sync passthrough over+ an ``async def`` endpoint would be misclassified as sync by ``inspect.*``,+ wrapped here, and then get *awaited* by FastAPI's dispatcher (a 500).+ Unreachable today (no such endpoint exists in this app, and slowapi's+ rate-limit decorator preserves sync/async-ness), but free to close and+ it removes the divergence from FastAPI's own model.++ These three properties are ``cached_property``s on ``Dependant``,+ memoized from whatever ``dependant.call`` is at first access. FastAPI's+ own ``APIRoute.__init__`` (via ``get_route_handler`` ->+ ``get_request_handler``) already reads ``is_coroutine_callable`` while+ building the route, before this function ever runs -- so by the time+ this runs (either from ``WorkerCleanupAPIRoute.__init__`` for direct+ routes, or from the post-``include_router`` sweep in+ ``prepare_router_for_worker_cleanup``), the value is already pinned to+ the real, original endpoint and is unaffected by this function+ subsequently replacing ``dependant.call`` with the cleanup wrapper.+FastAPI executes plain ``def`` endpoints on an AnyIO worker, while ASGImiddleware teardown runs on the event-loop thread. Database sessions arethread-local, so middleware cannot release the endpoint worker's sessions.@@ -64,31 +92,83 @@ def wrap_sync_route_with_cleanup(fn: Callable[..., T]) -> Callable[..., T]:lazily loaded ORM attribute touched only during encoding would then hita closed session (``DetachedInstanceError``) or silently serialize asincomplete data instead of raising.- ``Response`` subclasses (``JSONResponse``, ``HTMLResponse``,- ``TemplateResponse``, ``RedirectResponse``, ...) are unaffected: they- render their body synchronously in ``__init__``, i.e. before the- endpoint returns them here, so the bytes are already materialized.- Everything else gets encoded here, on this worker, before cleanup runs- — mirroring what FastAPI's own ``serialize_response`` falls back to- when there is no ``response_model`` (there is none anywhere in this- app), so this only moves that work earlier rather than duplicating it.+ ``JSONResponse``, ``HTMLResponse``, ``TemplateResponse`` and+ ``RedirectResponse`` are unaffected: they render their body+ synchronously in ``__init__``, i.e. before the endpoint returns them+ here, so the bytes are already materialized. ``FileResponse`` is the+ exception, NOT covered by that claim: its ``__init__`` only sets+ headers (starlette ``responses.py``); the file is opened and streamed+ later, in its async ``__call__``. That distinction is moot for this+ wrapper specifically -- every route in this app that returns a+ ``FileResponse`` (``favicon``, ``serve_static`` in+ ``web/fastapi_app.py``) is ``async def``, so this sync-only wrapper+ never touches them -- but do not extend the "renders in ``__init__``"+ claim to ``FileResponse`` if a future sync route ever returns one.+ Everything else (a plain dict, list, Pydantic model, ...) gets encoded+ here, on this worker, before cleanup runs. This is NOT, contrary to an+ earlier version of this docstring, simply moving forward a+ ``jsonable_encoder``-only fallback that every route in this app takes.+ ``APIRoute.__init__`` derives ``response_model`` from a route's return+ *type annotation* whenever one isn't given explicitly+ (``fastapi/routing.py``, ~840-905), and a bare ``-> Any`` annotation+ (21 routes in ``news_flask_api.py``, 14 of them synchronous and so+ routed through this wrapper) is truthy, so those routes DO get a+ ``response_field`` -- "no route declares a ``response_model``" is+ false. With a ``response_field`` present, FastAPI's own+ ``serialize_response`` (``routing.py``) takes the+ ``field.validate()`` + ``field.serialize_json()`` branch instead of the+ bare ``jsonable_encoder`` branch -- but that still runs, on the+ event-loop thread, on WHATEVER this wrapper already handed back as this+ worker's return value. Because that value already went through+ ``jsonable_encoder`` here, ``field.validate``/``serialize_json`` sees+ already-plain JSON primitives, not the original rich Python objects, so+ it has nothing left to reformat -- ``jsonable_encoder`` running first+ effectively wins the two encoders' formatting differences rather than+ being replaced by the second one. Measured deltas from running+ ``jsonable_encoder`` first: an aware ``datetime`` serializes as+ ``...+00:00`` (``datetime.isoformat()``, used by ``jsonable_encoder``)+ instead of pydantic's compact ``...Z``; ``Decimal("1.50")`` becomes the+ float ``1.5`` instead of a decimal-preserving pydantic encoding;+ ``timedelta`` becomes a float of total seconds instead of pydantic's+ ISO-8601 duration string. No route in this app hits this today -- every+ datetime returned from one of these routes is already+ ``.isoformat()``'d before it reaches this wrapper -- but nothing pins+ that; see ``tests/web/dependencies/test_threadpool.py`` for a+ regression test on one such route's serialized shape."""+ fn = dependant.call+ if fn is None or getattr(fn, _WORKER_CLEANUP_MARKER, False):+ return+# FastAPI streams generator endpoints after the endpoint call returns.# An ordinary ``finally`` would therefore clean up before iteration even# starts (and sync generator iterations are not worker-affine). There are# no generator endpoints in the production app; leave any future one- # untouched so the all-routes census fails visibly instead of applying an- # incorrect lifetime model.+ # untouched here rather than apply an incorrect lifetime model.+ #+ # Skipping them silently is only safe because a dedicated assertion+ # watches for them: ``generator_routes == []`` in+ # ``tests/web/dependencies/test_threadpool.py``'s+ # ``test_production_app_wraps_every_sync_api_route``. That test's OTHER+ # census (``missing == []``) cannot cover this -- it classifies routes+ # by the very same ``is_gen_callable``/``is_async_gen_callable`` flags+ # read here, so anything this branch returns early on is excluded from+ # it by construction. Nor can+ # ``test_production_routers_do_not_use_bare_streaming_response``, which+ # AST-scans for a ``StreamingResponse`` construction a generator+ # endpoint never writes. If the ``generator_routes`` assertion is+ # dropped, a new ``def ...: yield`` route streams via a bare+ # ``StreamingResponse``/``iterate_in_threadpool`` with no per-chunk+ # cleanup -- the #6095 leak class -- and nothing says so.if (- inspect.iscoroutinefunction(fn)- or inspect.isgeneratorfunction(fn)- or inspect.isasyncgenfunction(fn)- or getattr(fn, _WORKER_CLEANUP_MARKER, False)+ dependant.is_coroutine_callable+ or dependant.is_gen_callable+ or dependant.is_async_gen_callable):- return fn+ return@functools.wraps(fn)- def _wrapped(*args: Any, **kwargs: Any) -> T:+ def _wrapped(*args: Any, **kwargs: Any) -> Any:from ...database.thread_local_session import thread_cleanupwith thread_cleanup():@@ -102,7 +182,7 @@ def wrap_sync_route_with_cleanup(fn: Callable[..., T]) -> Callable[..., T]:return jsonable_encoder(result)setattr(_wrapped, _WORKER_CLEANUP_MARKER, True)- return _wrapped+ dependant.call = _wrappeddef iterate_sync_with_cleanup(iterable: Iterable[T]) -> Iterator[T]:@@ -117,21 +197,68 @@ def iterate_sync_with_cleanup(iterable: Iterable[T]) -> Iterator[T]:Wrapping each individual ``next()`` call gives every worker that advancesthe iterator its own deterministic cleanup boundary. Cleanup happens- before the chunk is handed back to the event loop, and also when iteration- finishes or raises.+ before the chunk is handed back to the event loop, and when iteration+ finishes or raises INSIDE ``next()``.++ Once started (at least one ``next()`` has been pulled), closing or+ finalizing this wrapper throws ``GeneratorExit`` at ``yield item``,+ after the per-chunk cleanup block has exited. The handler below closes+ the wrapped iterator inside another cleanup boundary, covering its+ synchronously executed ``finally``. Work that this ``finally``+ schedules elsewhere is outside that boundary. Closing this wrapper+ before its first ``next()`` has no such boundary to throw into --+ Python marks an unstarted generator closed without ever running the+ handler below.++ That close handler is NOT worker-affine, despite running the same+ ``thread_cleanup()`` the per-chunk block does. This wrapper is a+ generator, and asyncio's async-generator/garbage-collection finalizer+ schedules the closing ``aclose()``/``close()`` on the EVENT LOOP+ thread, so ``thread_cleanup()`` there sweeps the loop thread rather+ than whichever worker last advanced the iterator. That is benign here:+ ``DatabaseMiddleware`` already sweeps the loop thread once per+ request, so the loop thread never accumulates sessions, and the+ per-chunk boundary above -- which does run on the advancing worker --+ is what actually covers the workers.++ This describes what happens WHEN the wrapper is closed, not when a+ client disconnect causes it to close. The pinned Starlette 1.3.1+ ``StreamingResponse`` does not explicitly ``aclose()`` its body+ iterator on a failed send; closure can depend on response/iterator+ finalization. The direct-close regression test therefore does not+ establish deterministic cleanup at disconnect. The synchronous route+ generators close their existing service objects in ``finally``;+ this wrapper protects that work once close/finalization occurs."""iterator: Iterator[T] | None = None- while True:- try:+ try:+ while True:+ try:+ from ...database.thread_local_session import thread_cleanup++ with thread_cleanup():+ if iterator is None:+ iterator = iter(iterable)+ item = next(iterator)+ except StopIteration:+ return+ yield item+ except GeneratorExit:+ # ``iterable`` is typed broadly (``Iterable[T]``); a plain list/tuple+ # iterator has no ``close()``. Only generators (the only thing the+ # five production callers ever pass) do, so guard the call rather+ # than assuming one exists. Those callers are ``library.py:909``+ # and ``:1342``, ``rag.py:1361`` and ``:3508``, and+ # ``research.py:2326``; ``test_threadpool.py``'s+ # ``test_production_routers_do_not_use_bare_streaming_response``+ # pins the count at ``>= 5``.+ close = getattr(iterator, "close", None)+ if close is not None:from ...database.thread_local_session import thread_cleanupwith thread_cleanup():- if iterator is None:- iterator = iter(iterable)- item = next(iterator)- except StopIteration:- return- yield item+ close()+ raiseclass WorkerCleanupStreamingResponse(StreamingResponse):@@ -158,10 +285,11 @@ class WorkerCleanupAPIRoute(APIRoute):# through ``route.dependant.call``, so wrapping that call target gives# us the worker-thread boundary without changing route identity.super().__init__(path, endpoint, **kwargs)- call = self.dependant.call- if call is None: # pragma: no cover - APIRoute rejects this first+ if (+ self.dependant.call is None+ ): # pragma: no cover - APIRoute rejects this firstraise RuntimeError("FastAPI route has no dispatch callable")- self.dependant.call = wrap_sync_route_with_cleanup(call)+ wrap_sync_route_with_cleanup(self.dependant)def prepare_router_for_worker_cleanup(router: APIRouter) -> None:@@ -175,9 +303,7 @@ def prepare_router_for_worker_cleanup(router: APIRouter) -> None:"""for route in router.routes:if isinstance(route, APIRoute):- call = route.dependant.call- if call is not None:- route.dependant.call = wrap_sync_route_with_cleanup(call)+ wrap_sync_route_with_cleanup(route.dependant)async def run_db_sync(fn: Callable[..., T], /, *args: Any, **kwargs: Any) -> T:@@ -205,6 +331,27 @@ async def run_db_sync(fn: Callable[..., T], /, *args: Any, **kwargs: Any) -> T:cleanup_current_thread()except Exception:+ # Never render a traceback here — this frame holds+ # credentials; see #6223. ``_wrapped`` closes over+ # ``args``, and one production caller passes a plaintext+ # DB password through it+ # (``socketio_asgi.py``: ``run_db_sync(+ # db_manager.open_user_database, username, password)``).+ # ``exc_info=True`` is inert under loguru's ``logger.debug``+ # and stays that way deliberately. Under+ # ``LDR_LOGURU_DIAGNOSE`` loguru renders the value of every+ # identifier on each traced frame's displayed source line,+ # and the stderr sink's default ``backtrace=True`` extends+ # the trace upward through the executor frames. Today no+ # displayed line names ``args`` (this frame's is the+ # ``cleanup_current_thread()`` call, and+ # ``asyncio.to_thread`` hands the executor a zero-argument+ # ``partial``, so ``_WorkItem.args`` is empty), but that is+ # an accident of which line raises, not a property anyone+ # maintains: any traceback formatted from inside a closure+ # holding a password is one refactor away from rendering+ # it, and the redaction-invariant test cannot catch this+ # call site. So: never ``logger.exception()`` here.logger.debug("run_db_sync: cleanup_current_thread failed",exc_info=True,@@ -226,6 +373,8 @@ async def run_db_sync(fn: Callable[..., T], /, *args: Any, **kwargs: Any) -> T:clear_settings_context()except Exception:+ # Never render a traceback here — this frame holds+ # credentials; see #6223 and the handler above.logger.debug("run_db_sync: clear_settings_context failed",exc_info=True,@@ -247,6 +396,8 @@ async def run_db_sync(fn: Callable[..., T], /, *args: Any, **kwargs: Any) -> T:clear_active_context()except Exception:+ # Never render a traceback here — this frame holds+ # credentials; see #6223 and the first handler above.logger.debug("run_db_sync: clear_active_context failed",exc_info=True,diff --git a/src/local_deep_research/web/fastapi_app.py b/src/local_deep_research/web/fastapi_app.pyindex 64870aeadc..986fa0700f 100644--- a/src/local_deep_research/web/fastapi_app.py+++ b/src/local_deep_research/web/fastapi_app.py@@ -6,7 +6,6 @@ It mounts Socket.IO as an ASGI sub-app, configures middleware, templates,static files, and background services."""-import asyncioimport ipaddressimport loggingimport os@@ -1544,6 +1543,7 @@ class DatabaseMiddleware:session_data = scope.get("session", {})if session_data:from .dependencies.auth import ensure_user_database+ from .dependencies.threadpool import run_db_sync# Create a minimal request-like object for ensure_user_databaseclass _MinimalRequest:@@ -1554,7 +1554,23 @@ class DatabaseMiddleware:# key derivation, file I/O) which would block the event loop# for hundreds of ms on first call after login. Offload to a# threadpool so concurrent requests don't serialize behind it.- await asyncio.to_thread(+ #+ # Use run_db_sync, not bare asyncio.to_thread: a cold+ # open_user_database() call runs the phase-2 rekey path+ # (_run_phase2_rekey -> rekey_user_indexes), which opens a+ # get_user_db_session() unconditionally, before its own+ # marker check (vector_stores/legacy_rekey.py). That leaves a+ # thread-local session on whichever asyncio default-executor+ # thread served this call, with no cleanup boundary --+ # asyncio.to_thread's executor is not drained by+ # DatabaseMiddleware (event-loop thread only) or by any+ # per-worker cleanup, only ever replaced when that pooled+ # thread later serves a different username. run_db_sync+ # exists for exactly this: it runs the sync call on the same+ # default executor, then cleans up the thread-local DB+ # session (and other ambient thread-local state) on that+ # worker before returning.+ await run_db_sync(ensure_user_database, _MinimalRequest(session_data))diff --git a/src/local_deep_research/web/routers/library.py b/src/local_deep_research/web/routers/library.pyindex 8e09482ad2..38dbad2314 100644--- a/src/local_deep_research/web/routers/library.py+++ b/src/local_deep_research/web/routers/library.py@@ -772,6 +772,31 @@ def download_all_text(yield f"data: {json.dumps({'progress': 0, 'current': 0, 'total': 0, 'error': 'Authentication required', 'complete': True})}\n\n"return+ # This DownloadService (and the SettingsManager session inside+ # download_service.settings) is built ONCE, before the loop, and+ # lives across every ``yield`` below. That crosses a cleanup+ # boundary the wrapper's per-chunk cleanup does NOT know about:+ # ``WorkerCleanupStreamingResponse`` wraps this generator in+ # ``iterate_sync_with_cleanup``, whose ``thread_cleanup()`` runs+ # after EVERY ``next()`` (i.e. after every chunk, not just at the+ # end) and closes every session cached or tracked on this thread+ # (``utilities/db_utils.py``). The first chunk that touches+ # ``download_service.settings`` therefore gets its underlying+ # SQLAlchemy session closed by that per-chunk cleanup the moment the+ # chunk's ``yield`` returns -- but the ``SettingsManager``/``Session``+ # OBJECTS themselves are untouched, only their pooled connection is+ # released, so the next chunk's use of ``download_service.settings``+ # transparently reopens a fresh connection (ordinary SQLAlchemy+ # session behavior after ``close()``). That connection then sits in+ # neither the LRU cache nor the owner-thread registry until stream+ # end, when ``safe_close(download_service, ...)`` below closes it+ # via ``SettingsManager.close()`` -- exactly where it was released+ # pre-#6095, so this is NOT a leak, just a "cleanup at every+ # boundary" invariant violated for the longest-lived object in this+ # stream. Documented rather than restructured: giving this loop its+ # own re-created-per-chunk settings manager would fix the invariant+ # but changes this route's session lifetime shape for no behavioral+ # gain, and isn't warranted without a demonstrated leak.download_service = DownloadService(username, user_password)try:# Fetch the resource rows in a SHORT-LIVED session, snapshotting@@ -1033,6 +1058,14 @@ async def download_bulk(yield f"data: {json.dumps({'progress': 0, 'current': 0, 'total': 0, 'error': 'Authentication required', 'complete': True})}\n\n"return+ # Same per-chunk-cleanup caveat as download_all_text() above:+ # download_service.settings' session gets closed (connection+ # released, object untouched) by iterate_sync_with_cleanup's+ # per-chunk thread_cleanup() after the first chunk that uses it, and+ # transparently reopens a fresh connection on later chunks. Not a+ # leak -- safe_close(download_service, ...) below releases it at+ # stream end exactly as pre-#6095 -- just documented here rather+ # than restructured; see the fuller note there.download_service = DownloadService(username, user_password)try:total = 0diff --git a/src/local_deep_research/web/services/socketio_asgi.py b/src/local_deep_research/web/services/socketio_asgi.pyindex da22fc973a..142c73c009 100644--- a/src/local_deep_research/web/services/socketio_asgi.py+++ b/src/local_deep_research/web/services/socketio_asgi.py@@ -364,9 +364,22 @@ async def connect(sid, environ, auth=None):return Falsetry:# SQLCipher open is sync I/O — keep it off the event loop.- await asyncio.to_thread(- db_manager.open_user_database, username, password- )+ #+ # Use run_db_sync, not bare asyncio.to_thread: a cold+ # open_user_database() call runs the phase-2 rekey path+ # (_run_phase2_rekey -> rekey_user_indexes), which opens a+ # get_user_db_session() unconditionally, before its own marker+ # check (vector_stores/legacy_rekey.py). That leaves a thread-local+ # session on whichever asyncio default-executor thread served+ # this call, with no cleanup boundary. run_db_sync runs the sync+ # call on that same default executor, then cleans up the+ # thread-local DB session (and other ambient thread-local+ # state) on that worker before returning -- same shape as the+ # equivalent fix at fastapi_app.py's DatabaseMiddleware+ # (ensure_user_database).+ from ..dependencies.threadpool import run_db_sync++ await run_db_sync(db_manager.open_user_database, username, password)except Exception as e:# Capture the type name only and log OUTSIDE the handler:# logger.exception's diagnose=True traceback would render thediff --git a/tests/research_library/services/test_library_service_crud_deep.py b/tests/research_library/services/test_library_service_crud_deep.pyindex b79440b9e6..27bb0079e3 100644--- a/tests/research_library/services/test_library_service_crud_deep.py+++ b/tests/research_library/services/test_library_service_crud_deep.py@@ -725,6 +725,159 @@ class TestSyncLibraryWithFilesystem:assert result["files_found"] == 2assert result["files_missing"] == 1+ def test_settings_manager_resolved_once_not_per_document(self, mocker):+ """Regression test for the #6095 follow-up (issue 1).++ Pre-fix, ``get_absolute_path_from_settings`` fell back to the+ ambient ``get_settings_manager()`` on EVERY call when no explicit+ manager was passed — one DB session opened per completed document in+ this sync loop, unbounded. ``sync_library_with_filesystem`` now+ resolves one settings manager lazily (on the first document that+ needs a path resolved) and threads it through every+ ``get_absolute_path_from_settings`` call in the loop, so this must+ stay at exactly one ``get_settings_manager()`` call — not zero (the+ loop does need it) and not N (one per document, the regression this+ guards against) — for N>1 documents with trackers. It must also be+ closed exactly once, at the end.+ """+ service = _make_service()+ mock_session = MagicMock()++ docs = []+ for i in range(3):+ d = Mock()+ d.id = f"doc-{i}"+ d.title = f"Doc {i}"+ d.original_url = f"https://example.com/doc{i}.pdf"+ docs.append(d)++ trackers = [Mock(file_path=f"pdfs/doc{i}.pdf") for i in range(3)]++ call_count = {"n": 0}++ def query_router(model):+ call_count["n"] += 1+ if call_count["n"] == 1:+ q = MagicMock()+ q.filter_by.return_value.filter.return_value.options.return_value.all.return_value = docs+ return q+ idx = call_count["n"] - 2+ tq = MagicMock()+ tq.filter_by.return_value.first.return_value = trackers[idx]+ return tq++ mock_session.query.side_effect = query_router+ _mock_session_cm(mocker, mock_session)++ mock_path = MagicMock()+ mock_path.is_file.return_value = True+ mock_path_resolver = mocker.patch(+ "local_deep_research.research_library.services.library_service.get_absolute_path_from_settings",+ return_value=mock_path,+ )++ mock_manager = MagicMock()+ mock_get_settings_manager = mocker.patch(+ "local_deep_research.research_library.services.library_service.get_settings_manager",+ return_value=mock_manager,+ )++ result = service.sync_library_with_filesystem()++ assert result["total_documents"] == 3+ assert result["files_found"] == 3++ mock_get_settings_manager.assert_called_once_with(username="test_user")+ mock_manager.close.assert_called_once()++ # Every resolved-path call must have received the SAME manager+ # instance, not a fresh one per document.+ assert mock_path_resolver.call_count == 3+ for call in mock_path_resolver.call_args_list:+ assert call.kwargs["settings_manager"] is mock_manager++ def test_settings_manager_not_resolved_when_no_documents(self, mocker):+ """Lazy creation: zero documents means zero settings-manager calls."""+ service = _make_service()+ mock_session = MagicMock()+ mock_session.query.return_value.filter_by.return_value.filter.return_value.options.return_value.all.return_value = []+ _mock_session_cm(mocker, mock_session)++ mock_get_settings_manager = mocker.patch(+ "local_deep_research.research_library.services.library_service.get_settings_manager"+ )++ result = service.sync_library_with_filesystem()++ assert result["total_documents"] == 0+ mock_get_settings_manager.assert_not_called()++ def test_get_documents_reuses_one_settings_manager_for_page(self, mocker):+ """Catch reverting get_documents to ambient path resolution per document."""+ service = _make_service()+ mock_session = MagicMock()++ rows = []+ for i in range(3):+ doc = Mock()+ doc.id = f"doc-{i}"+ doc.resource_id = None+ doc.research_id = None+ doc.title = f"Doc {i}"+ doc.authors = None+ doc.published_date = None+ doc.doi = None+ doc.arxiv_id = None+ doc.pmid = None+ doc.file_path = f"pdfs/doc{i}.pdf"+ doc.filename = f"doc{i}.pdf"+ doc.file_size = 1024+ doc.file_type = "pdf"+ doc.original_url = None+ doc.status = "completed"+ doc.processed_at = None+ doc.uploaded_at = None+ doc.favorite = False+ doc.tags = []+ doc.text_content = None+ doc.storage_mode = "filesystem"+ rows.append((doc, None, None, None, None))++ mock_query = MagicMock()+ mock_query.join.return_value = mock_query+ mock_query.outerjoin.return_value = mock_query+ mock_query.filter.return_value = mock_query+ mock_query.order_by.return_value = mock_query+ mock_query.offset.return_value = mock_query+ mock_query.limit.return_value = mock_query+ mock_query.subquery.return_value = MagicMock()+ mock_query.all.side_effect = [rows, []]+ mock_session.query.return_value = mock_query+ _mock_session_cm(mocker, mock_session)++ mocker.patch(+ "local_deep_research.database.library_init.get_default_library_id",+ return_value="default-id",+ )+ mock_path_resolver = mocker.patch(+ "local_deep_research.research_library.services.library_service.get_absolute_path_from_settings",+ return_value=MagicMock(),+ )+ mock_manager = MagicMock()+ mock_get_settings_manager = mocker.patch(+ "local_deep_research.research_library.services.library_service.get_settings_manager",+ return_value=mock_manager,+ )++ result = service.get_documents()++ assert len(result) == 3+ mock_get_settings_manager.assert_called_once_with(username="test_user")+ mock_manager.close.assert_called_once()+ assert mock_path_resolver.call_count == 3+ for call in mock_path_resolver.call_args_list:+ assert call.kwargs["settings_manager"] is mock_manager+# ============== mark_for_redownload ==============diff --git a/tests/web/dependencies/test_threadpool.py b/tests/web/dependencies/test_threadpool.pyindex 5a77576ae5..0073a61ef2 100644--- a/tests/web/dependencies/test_threadpool.py+++ b/tests/web/dependencies/test_threadpool.py@@ -246,6 +246,8 @@ def test_run_db_sync_passes_kwargs_through():def test_worker_cleanup_route_runs_cleanup_on_success_and_error():"""A synchronous endpoint always cleans on the serving worker."""+ from fastapi.dependencies.models import Dependant+from local_deep_research.web.dependencies.threadpool import (WorkerCleanupAPIRoute,wrap_sync_route_with_cleanup,@@ -269,6 +271,16 @@ def test_worker_cleanup_route_runs_cleanup_on_success_and_error():)assert ok_route.dependant.call.__wrapped__ is ok+ # wrap_sync_route_with_cleanup takes a Dependant and mutates ``.call`` in+ # place (rather than returning a wrapped callable) so it can gate on+ # FastAPI's own Dependant.is_coroutine_callable/is_gen_callable/+ # is_async_gen_callable instead of inspect.iscoroutinefunction et al.+ # (see the function's docstring / issue (5) of the #6095 follow-up).+ boom_dependant = Dependant(call=boom)+ wrap_sync_route_with_cleanup(boom_dependant)+ assert boom_dependant.call is not boom+ assert getattr(boom_dependant.call, "__ldr_worker_thread_cleanup__", False)+with patch("local_deep_research.database.thread_local_session.cleanup_current_thread",side_effect=lambda: cleanup_threads.append(threading.get_ident()),@@ -278,7 +290,7 @@ def test_worker_cleanup_route_runs_cleanup_on_success_and_error():"ok": True}with pytest.raises(RuntimeError, match="route failed"):- executor.submit(wrap_sync_route_with_cleanup(boom)).result()+ executor.submit(boom_dependant.call).result()assert cleanup_threads == worker_threads@@ -333,8 +345,69 @@ def test_worker_cleanup_encodes_plain_return_value_before_releasing_session():assert result == {"value": {"id": 1}}+def test_worker_cleanup_pins_serialization_shape_for_untyped_any_routes():+ """Regression test for issue (2): the docstring's premise was false.++ This wrapper's docstring used to claim no route in the app declares a+ ``response_model``, so every sync route takes FastAPI's bare+ ``jsonable_encoder`` fallback in ``serialize_response``. That premise is+ false: a route annotated ``-> Any`` (21 of them in+ ``news_flask_api.py``, 14 synchronous) gets a ``response_model``/+ ``response_field`` derived from that annotation by+ ``APIRoute.__init__`` (``fastapi/routing.py``), so+ ``serialize_response`` takes the ``field.validate`` ++ ``field.serialize_json`` branch instead -- just on a value this wrapper+ already ran through ``jsonable_encoder``.++ Because ``jsonable_encoder`` already reduces datetimes/Decimals/+ timedeltas to plain JSON primitives before pydantic's serializer ever+ sees them, pydantic's own JSON-mode formatting for those types never+ applies. This pins the resulting shape (Python's ``datetime.isoformat()``+ with a ``+00:00`` offset, ``Decimal`` narrowed to ``float``, ``timedelta``+ narrowed to a ``float`` of total seconds) so a future ``-> Any`` sync+ route returning a raw, non-``isoformat()``'d value is caught by a shape+ change here rather than silently shipping a different wire format.+ """+ from datetime import datetime, timedelta, timezone+ from decimal import Decimal+ from typing import Any++ from fastapi import FastAPI+ from fastapi.testclient import TestClient++ from local_deep_research.web.dependencies.threadpool import (+ WorkerCleanupAPIRoute,+ )++ def untyped_any_endpoint() -> Any:+ return {+ "created_at": datetime(2026, 1, 1, 12, 0, 0, tzinfo=timezone.utc),+ "amount": Decimal("1.50"),+ "duration": timedelta(seconds=90),+ }++ app = FastAPI()+ app.router.route_class = WorkerCleanupAPIRoute+ app.add_api_route("/thing", untyped_any_endpoint, methods=["GET"])++ with patch(+ "local_deep_research.database.thread_local_session.cleanup_current_thread"+ ):+ with TestClient(app) as client:+ response = client.get("/thing")++ assert response.status_code == 200+ assert response.json() == {+ "created_at": "2026-01-01T12:00:00+00:00",+ "amount": 1.5,+ "duration": 90.0,+ }++def test_worker_cleanup_leaves_async_and_generator_endpoints_unchanged():"""Deferred endpoint bodies need a different lifetime model."""+ from fastapi.dependencies.models import Dependant+from local_deep_research.web.dependencies.threadpool import (wrap_sync_route_with_cleanup,)@@ -348,14 +421,61 @@ def test_worker_cleanup_leaves_async_and_generator_endpoints_unchanged():async def async_generator_endpoint():yield {"kind": "async-generator"}- assert wrap_sync_route_with_cleanup(async_endpoint) is async_endpoint- assert (- wrap_sync_route_with_cleanup(sync_generator_endpoint)- is sync_generator_endpoint+ for endpoint in (+ async_endpoint,+ sync_generator_endpoint,+ async_generator_endpoint,+ ):+ dependant = Dependant(call=endpoint)+ wrap_sync_route_with_cleanup(dependant)+ assert dependant.call is endpoint, (+ f"{endpoint} should be left untouched by wrap_sync_route_with_cleanup"+ )+++def test_worker_cleanup_gates_on_fastapi_callable_classification_not_inspect():+ """Regression test for issue (5): gate on Dependant.is_*_callable.++ ``inspect.iscoroutinefunction``/``isgeneratorfunction``/+ ``isasyncgenfunction`` do NOT follow a ``functools.wraps`` __wrapped__+ chain, but FastAPI's own ``Dependant.is_coroutine_callable`` /+ ``is_gen_callable`` / ``is_async_gen_callable`` do (they call+ ``inspect.unwrap`` internally) -- and FastAPI dispatches based on its+ own predicates, not ``inspect.*``. A sync ``functools.wraps`` passthrough+ over an ``async def`` endpoint must therefore be left untouched here too,+ even though ``inspect.iscoroutinefunction`` on the passthrough itself+ would say False.+ """+ import functools++ from fastapi.dependencies.models import Dependant++ from local_deep_research.web.dependencies.threadpool import (+ wrap_sync_route_with_cleanup,+ )++ async def real_async_endpoint():+ return {"kind": "async"}++ @functools.wraps(real_async_endpoint)+ def sync_passthrough_over_async(*args, **kwargs):+ return real_async_endpoint(*args, **kwargs)++ assert inspect.iscoroutinefunction(sync_passthrough_over_async) is False, (+ "test setup: this must be the exact case inspect.* misclassifies"+ )++ dependant = Dependant(call=sync_passthrough_over_async)+ assert dependant.is_coroutine_callable is True, (+ "test setup: FastAPI's own predicate must classify this as a "+ "coroutine callable via __wrapped__")- assert (- wrap_sync_route_with_cleanup(async_generator_endpoint)- is async_generator_endpoint++ wrap_sync_route_with_cleanup(dependant)++ assert dependant.call is sync_passthrough_over_async, (+ "a callable FastAPI's own dispatch model treats as a coroutine "+ "must not be wrapped in the sync worker-cleanup boundary")@@ -397,6 +517,68 @@ def test_sync_iterator_cleanup_runs_on_chunk_completion_and_error():assert set(cleanup_threads) == set(iteration_threads)+def test_sync_iterator_cleanup_runs_on_explicit_close():+ """Closing a suspended wrapper runs the body's finally inside cleanup.++ This tests the explicit-close contract, not whether Starlette closes+ the response iterator immediately when a client disconnects.+ """+ from local_deep_research.web.dependencies.threadpool import (+ iterate_sync_with_cleanup,+ )++ events: list[str] = []++ def body():+ try:+ events.append("start")+ yield b"chunk1"+ yield b"chunk2"+ finally:+ events.append("inner-finally")++ cleanup_calls: list[None] = []+ with patch(+ "local_deep_research.database.thread_local_session.cleanup_current_thread",+ side_effect=lambda: cleanup_calls.append(None),+ ):+ wrapped = iterate_sync_with_cleanup(body())+ assert next(wrapped) == b"chunk1"+ assert events == ["start"]+ assert len(cleanup_calls) == 1++ # Close directly; a real response may instead rely on finalization.+ wrapped.close()++ # PRIMARY assertion. This is the only one that fails with the fix+ # reverted: without the GeneratorExit handler's explicit close, CPython+ # still runs the body's ``finally`` when the sole reference to it is+ # dropped (refcount finalization), so ``events`` below reaches its final+ # state either way. Only the SECOND cleanup boundary is genuinely new.+ assert len(cleanup_calls) == 2, (+ "close() must get its own thread_cleanup() boundary, not run bare"+ )+ # Ordering only -- deliberately NOT the regression signal, for the+ # refcount reason above.+ assert events == ["start", "inner-finally"], (+ "wrapped generator's finally must run during close(), in order"+ )+++def test_sync_iterator_close_is_a_noop_for_non_generator_iterables():+ """A plain iterable (no ``.close()``) must not break on close()."""+ from local_deep_research.web.dependencies.threadpool import (+ iterate_sync_with_cleanup,+ )++ with patch(+ "local_deep_research.database.thread_local_session.cleanup_current_thread"+ ):+ wrapped = iterate_sync_with_cleanup([b"a", b"b", b"c"])+ assert next(wrapped) == b"a"+ wrapped.close() # must not raise AttributeError++def test_streaming_response_leaves_async_body_on_the_event_loop():"""Async response bodies must not be handed to the sync worker wrapper."""from local_deep_research.web.dependencies.threadpool import (@@ -540,14 +722,49 @@ def test_prepared_router_dispatches_through_cleanup_on_the_worker():def test_production_app_wraps_every_sync_api_route():- """No module router or app-local endpoint can bypass worker cleanup."""+ """No module router or app-local endpoint can bypass worker cleanup.++ Classifies "synchronous" the same way ``wrap_sync_route_with_cleanup``+ itself does -- via ``route.dependant.is_coroutine_callable`` /+ ``is_gen_callable`` / ``is_async_gen_callable`` -- rather than+ ``inspect.iscoroutinefunction(route.endpoint)``. The latter does not+ follow a ``functools.wraps`` ``__wrapped__`` chain and shares the exact+ blind spot fixed in the production code (issue (5) of the #6095+ follow-up): a hypothetical sync passthrough wrapping an async endpoint+ would be miscounted as "needs cleanup" by ``inspect.*`` here even though+ FastAPI itself, and this module's own wrapper, correctly treat it as a+ coroutine callable and leave it alone.++ That swap alone would DISARM this census for generator endpoints, so it+ comes with ``generator_routes`` below. ``inspect.iscoroutinefunction``+ is ``False`` for BOTH ``def f(): yield`` and ``async def f(): yield``+ (verified against fastapi 0.136.3), so the old predicate swept generator+ endpoints into ``sync_routes``, where they failed ``missing == []``+ because ``wrap_sync_route_with_cleanup`` deliberately leaves them+ unmarked. The new predicate excludes them -- and neither+ ``test_production_routers_do_not_use_bare_streaming_response`` (it+ AST-scans for ``StreamingResponse`` construction, which a generator+ endpoint never performs) nor anything else would notice. FastAPI would+ stream such a route through ``_sync_stream_jsonl()`` -> a bare+ ``StreamingResponse`` -> ``iterate_in_threadpool`` with no per-chunk+ cleanup: the #6095 leak class, silently reintroduced. The separate+ ``generator_routes`` assertion is what keeps that visible.+ """from local_deep_research.web.fastapi_app import app+ api_routes = [route for route in app.routes if isinstance(route, APIRoute)]sync_routes = [route- for route in app.routes- if isinstance(route, APIRoute)- and not inspect.iscoroutinefunction(route.endpoint)+ for route in api_routes+ if not route.dependant.is_coroutine_callable+ and not route.dependant.is_gen_callable+ and not route.dependant.is_async_gen_callable+ ]+ generator_routes = [+ route.path+ for route in api_routes+ if route.dependant.is_gen_callable+ or route.dependant.is_async_gen_callable]missing = [route.path@@ -567,6 +784,20 @@ def test_production_app_wraps_every_sync_api_route():assert missing == [], (f"synchronous routes without owner-worker cleanup: {sorted(missing)}")+ assert generator_routes == [], (+ "the production app grew a generator endpoint: "+ f"{sorted(generator_routes)}. ``wrap_sync_route_with_cleanup`` "+ "deliberately leaves these untouched (see its skip branch and the "+ "comment above it, "+ "src/local_deep_research/web/dependencies/threadpool.py:143-162) "+ "because an endpoint-level ``finally`` would clean up before "+ "FastAPI even starts streaming the body. FastAPI streams such a "+ "route through a bare ``StreamingResponse`` and "+ "``iterate_in_threadpool``, with no per-chunk cleanup -- the #6095 "+ "leak class. Give the route an explicit "+ "``WorkerCleanupStreamingResponse(iterate_sync_with_cleanup(...))`` "+ "body instead of a generator endpoint, then drop it from here."+ )assert identity_mismatches == [], ("cleanup dispatch wrappers no longer point at the registered endpoint: "f"{sorted(identity_mismatches)}"diff --git a/tests/web/services/test_socketio_connect_gate.py b/tests/web/services/test_socketio_connect_gate.pyindex d7966b6fe4..09e5e8937a 100644--- a/tests/web/services/test_socketio_connect_gate.py+++ b/tests/web/services/test_socketio_connect_gate.py@@ -9,6 +9,7 @@ session-cookie decoding and DB seams patched."""import asyncio+import threadingfrom unittest.mock import Mock, patchimport pytest@@ -124,6 +125,37 @@ class TestConnectGate:store.get_session_password.assert_called_once_with("alice", "s1")assert sid_users == {"sid-1": "alice"}+ def test_lazy_db_open_sweeps_session_on_executor_worker(self, sid_users):+ """Regression test for reverting run_db_sync to bare asyncio.to_thread.++ A cold open can create a thread-local DB session during phase-two rekey.+ The connect path must sweep that session on the same pooled executor+ worker before returning, rather than leave it attached for a later user.+ """+ dbm = Mock()+ dbm.is_user_connected.return_value = False+ open_threads = []+ cleanup_threads = []++ def record_open_thread(username, password):+ open_threads.append(threading.get_ident())++ dbm.open_user_database.side_effect = record_open_thread++ with patch(+ "local_deep_research.database.thread_local_session.cleanup_current_thread",+ side_effect=lambda: cleanup_threads.append(threading.get_ident()),+ ):+ result, _ = _connect(+ session_data={"username": "alice", "session_id": "s1"},+ db_manager=dbm,+ password="pw",+ )++ assert result is True+ assert cleanup_threads == open_threads+ assert cleanup_threads[0] != threading.get_ident()+def test_lazy_db_open_failure_rejects_connection(self, sid_users):dbm = Mock()dbm.is_user_connected.return_value = Falsediff --git a/tests/web/test_db_session_lifecycle_asgi.py b/tests/web/test_db_session_lifecycle_asgi.pyindex fa8d7eb1a1..b0ba09900e 100644--- a/tests/web/test_db_session_lifecycle_asgi.py+++ b/tests/web/test_db_session_lifecycle_asgi.py@@ -451,9 +451,22 @@ async def test_sync_route_cleanup_runs_on_the_handler_worker(``DatabaseMiddleware`` still cleans the event-loop thread, which cannotreach a sync handler's ``threading.local``. ``WorkerCleanupAPIRoute`` adds- the missing cleanup on the handler worker. Both calls are observed so a+ the missing cleanup on the handler worker. All calls are observed so afuture refactor cannot accidentally move the only effective cleanup backto the loop thread.++ PREMISE UPDATE (PR #6207, follow-up to #6095): ``DatabaseMiddleware``+ now offloads ``ensure_user_database`` through ``run_db_sync`` (instead+ of a bare ``asyncio.to_thread`` that left the executor thread's+ thread-local session with no cleanup boundary at all — the leak+ #6207 closes). ``run_db_sync``'s own ``finally`` unconditionally calls+ ``cleanup_current_thread()`` on whichever asyncio default-executor+ thread it ran on, BEFORE the request is dispatched to the inner app.+ That executor pool is a structurally different pool from both AnyIO's+ worker pool (``_pin_single_anyio_worker`` only pins the latter) and the+ event-loop thread, so this now observes THREE distinct-thread cleanup+ calls instead of two: the run_db_sync offload thread, then the sync+ handler's owner-worker thread, then the middleware's loop thread."""leftover = MagicMock(name="session_opened_by_the_handler")handler_thread = {}@@ -494,10 +507,30 @@ async def test_sync_route_cleanup_runs_on_the_handler_worker("whole hazard would disappear and this test must be ""rewritten rather than deleted.")- assert cleanup_threads == [handler_thread["ident"], loop_thread], (+ assert len(cleanup_threads) == 3, (+ "expected the run_db_sync offload of ensure_user_database, "+ "then owner-worker cleanup, then middleware's loop-thread "+ f"cleanup; saw {cleanup_threads}"+ )+ offload_thread, owner_thread, seen_loop_thread = cleanup_threads+ assert (owner_thread, seen_loop_thread) == (+ handler_thread["ident"],+ loop_thread,+ ), ("expected owner-worker cleanup followed by middleware's "f"loop-thread cleanup; saw {cleanup_threads}")+ assert offload_thread not in (+ handler_thread["ident"],+ loop_thread,+ ), (+ "the leading entry is run_db_sync's cleanup of the "+ "ensure_user_database offload, which runs on asyncio's "+ "default ThreadPoolExecutor -- a different pool from both "+ "AnyIO's worker pool (the handler thread) and the event "+ f"loop thread, so it must be a third distinct thread; saw "+ f"{cleanup_threads}"+ )assert leftover.close.call_count == 1, ("the synchronous endpoint returned without closing its ""worker-owned session"diff --git a/tests/web/test_teardown_cleanup_asgi.py b/tests/web/test_teardown_cleanup_asgi.pyindex e7958bc420..d5dd684b82 100644--- a/tests/web/test_teardown_cleanup_asgi.py+++ b/tests/web/test_teardown_cleanup_asgi.py@@ -151,6 +151,23 @@ async def test_both_sweeps_run_after_a_successful_request(after every request. Both are credential sweepers: what they reclaimis a thread-local DB session and the password that opened it, so adropped sweep leaves a decrypted handle alive on a pooled worker.++ PREMISE UPDATE (PR #6207, follow-up to #6095): this stack's request is+ authenticated (``server_sessions`` + the default ``user="alice"`` in+ ``_get``), so ``DatabaseMiddleware`` now also runs+ ``ensure_user_database`` through ``run_db_sync`` instead of a bare+ ``asyncio.to_thread``. ``run_db_sync``'s own ``finally`` unconditionally+ calls ``cleanup_current_thread()`` on the executor thread it ran on,+ before the request is even dispatched to the inner app — that boundary+ is the whole point of the change (closing a leak where a cold rekey's+ ``get_user_db_session()`` pinned a session on a pooled default-executor+ thread with no cleanup at all). It runs regardless of whether+ ``ensure_user_database`` did anything, which is why it still fires here+ even though this file's ``_no_real_db`` fixture stubs it to a no-op —+ the cleanup is a cheap unconditional safety net by design, not+ conditioned on the wrapped call's effect. That is a genuine third sweep+ on a genuinely different thread, not a duplicate of the loop-thread+ pair below it."""def probe():@@ -159,9 +176,11 @@ async def test_both_sweeps_run_after_a_successful_request(response = await _get(_stack(probe, server_sessions))assert response.status_code == 200, response.text- assert sweeps == ["dead", "current"], (- f"post-request cleanup ran {sweeps}; main guaranteed both sweeps, "- "dead-thread first"+ assert sweeps == ["current", "dead", "current"], (+ f"post-request cleanup ran {sweeps}; expected the middleware's "+ "run_db_sync offload of ensure_user_database to sweep once up "+ "front, then main's guaranteed pair (dead-thread first) after "+ "the request")@@ -202,6 +221,12 @@ async def test_both_sweeps_run_when_the_handler_raises(server_sessions, sweeps):"""``teardown_appcontext`` ran on the error path too; a ``finally``must as well. If it did not, the one request shape most likely tohave left a half-open session behind is the one that skips cleanup.++ PREMISE UPDATE (PR #6207): same reasoning as+ ``test_both_sweeps_run_after_a_successful_request`` above — the+ authenticated request now also produces a leading ``run_db_sync``+ sweep of ``ensure_user_database`` before the (raising) handler ever+ runs, so the expected sequence gains that same third, earlier entry."""def boom():@@ -209,9 +234,10 @@ async def test_both_sweeps_run_when_the_handler_raises(server_sessions, sweeps):await _get(_stack(boom, server_sessions))- assert sweeps == ["dead", "current"], (- f"a failing handler left cleanup at {sweeps}; the finally block "- "must run on the error path"+ assert sweeps == ["current", "dead", "current"], (+ f"a failing handler left cleanup at {sweeps}; expected the "+ "run_db_sync offload sweep up front plus the finally block's "+ "guaranteed pair (dead-thread first) on the error path")@@ -298,13 +324,31 @@ class TestIndependenceOfTheTwoSweeps:self, server_sessions, sweeps):"""Without this, the failing test below would be satisfied by a- second sweep that never runs at all."""+ second sweep that never runs at all.++ PREMISE UPDATE (PR #6207): this invocation is byte-identical to+ ``test_both_sweeps_run_after_a_successful_request``, whose expected+ sequence this PR changed to ``["current", "dead", "current"]`` --+ the leading entry being ``run_db_sync``'s unconditional sweep of the+ executor thread that ran ``ensure_user_database``, fired BEFORE the+ request is dispatched. A bare ``"current" in sweeps`` is therefore+ now satisfied by that leading entry alone: it would still pass with+ the entire post-request pair gone, which is exactly the vacuity this+ control exists to rule out. Count instead -- two ``"current"``+ sweeps means run_db_sync's AND the post-request one both ran, so a+ healthy first sweep really did reach the second.+ """def probe():return {"ok": True}await _get(_stack(probe, server_sessions))- assert "current" in sweeps+ assert sweeps.count("current") == 2, (+ f"post-request cleanup ran {sweeps}; expected run_db_sync's "+ "up-front sweep plus the post-request current-thread sweep. One "+ "``current`` means the post-request pair never ran, which would "+ "make the sibling failure test below vacuous"+ )@pytest.mark.asyncioasync def test_current_thread_sweep_still_runs_when_dead_sweep_throws(@@ -319,6 +363,17 @@ class TestIndependenceOfTheTwoSweeps:a closed engine). Under this branch's single ``try`` that throw takesthe current-thread sweep with it, so the loop thread's own entry isnever reclaimed. main's two separate blocks made that impossible.++ PREMISE UPDATE (PR #6207): the leading ``"current"`` entry below is+ NOT part of the dead/current pair this test is about — it is+ ``run_db_sync``'s own unconditional cleanup of the executor thread+ that ran ``ensure_user_database`` (see+ ``test_both_sweeps_run_after_a_successful_request`` for the full+ explanation), and it happens before the handler runs, so it happens+ before ``cleanup_dead_threads`` even has a chance to throw. The+ property this test actually pins — that a throwing dead-thread+ sweep does not take the current-thread sweep down with it — is+ still exactly the last two entries, ``["dead", "current"]``."""calls: list[str] = []@@ -337,10 +392,13 @@ class TestIndependenceOfTheTwoSweeps:response = await _get(_stack(probe, server_sessions))assert response.status_code == 200, response.text- assert calls == ["dead", "current"], (+ assert calls == ["current", "dead", "current"], ("cleanup_dead_threads raised and took cleanup_current_thread "- f"down with it (calls={calls}). main ran each sweep in its own "- "try/except precisely so one failing sweeper could not disable "- "the other; DatabaseMiddleware.__call__'s finally in "- "web/fastapi_app.py shares a single try. Fix: split the block."+ f"down with it (calls={calls}). DatabaseMiddleware.__call__'s "+ "finally in web/fastapi_app.py runs cleanup_dead_threads and "+ "cleanup_current_thread in two independent try/except blocks "+ "precisely so one failing sweeper cannot disable the other; "+ "this assertion pins that isolation holding. (leading entry is "+ "run_db_sync's own pre-dispatch sweep of ensure_user_database, "+ "unrelated to the dead/current pair)")