Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(web): release FastAPI worker DB sessions (#6095)

LearningCircuit39b7b33d9172
diff --git a/changelog.d/6095.bugfix.md b/changelog.d/6095.bugfix.md
new file mode 100644
index 0000000000..88b13683b6
--- /dev/null
+++ b/changelog.d/6095.bugfix.md
@@ -0,0 +1,4 @@
+Fixed FastAPI worker threads retaining per-user database connections after
+synchronous 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.
diff --git a/docs/architecture.md b/docs/architecture.md
index 779ba77e8b..982ae5c3dc 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -492,8 +492,10 @@ Cleanup is defense-in-depth with multiple layers:
| Layer | Trigger | What it cleans |
|-------|---------|----------------|
| `@thread_cleanup` decorator | Thread function exit (normal or exception) | DB session (returned to per-user pool), settings context, search context |
+| `WorkerCleanupAPIRoute` (`web/dependencies/threadpool.py`) | Synchronous FastAPI endpoint exit (normal or exception) | Sessions and ambient thread-local state on the AnyIO worker that served the endpoint |
+| `WorkerCleanupStreamingResponse` (`web/dependencies/threadpool.py`) | Each synchronous streamed-response iterator step (chunk, completion, or exception) | Sessions and ambient thread-local state on whichever AnyIO worker advanced that step |
| `finally` blocks | Per-research in `run_research_process()` | Search engine HTTP sessions, strategy thread pool executors |
-| `DatabaseMiddleware` `finally` block (`web/fastapi_app.py`) | After each HTTP request | Calls `cleanup_dead_threads()` + `cleanup_current_thread()`. Note: as `async def` middleware it runs on the event-loop thread, so a *sync* route's thread-local session on an AnyIO worker is not the one reclaimed here — see `warn_if_threadpool_exceeds_db_pool()` |
+| `DatabaseMiddleware` `finally` block (`web/fastapi_app.py`) | After each HTTP request | Sweeps dead workers and cleans event-loop-owned state; synchronous endpoint and stream-iterator state are reclaimed on their owning workers by the two wrappers above |
| Periodic pool dispose | Every 30 min | Calls `engine.dispose()` on per-user QueuePool engines to release SQLCipher+WAL file handles that accumulate from out-of-order connection closes |
| Logout cascade | User logout | Scheduler unregister (removes password) → DB close (`engine.dispose()`) → session destroy |
| Stale session cleanup | `clear_session_if_unrecoverable()`, called from `require_auth()` when the DB connection is missing (`web/dependencies/auth.py`) | Clears the signed session cookie for users whose DB connection is gone and who have no recovery credential. Not sampled/throttled — unlike the old `before_request` hook it only runs on an already-failed auth check |
diff --git a/docs/decisions/0004-nullpool-for-sqlcipher.md b/docs/decisions/0004-nullpool-for-sqlcipher.md
index df82ab2fbd..eb304b0241 100644
--- a/docs/decisions/0004-nullpool-for-sqlcipher.md
+++ b/docs/decisions/0004-nullpool-for-sqlcipher.md
@@ -8,7 +8,7 @@
Each user has their own SQLCipher-encrypted SQLite database, opened at
login and closed at logout. Background threads (research workers,
metric writers, news scheduler jobs) need database sessions for the
-same user concurrently with Flask request handlers.
+same user concurrently with web request handlers.
### Why QueuePool
diff --git a/src/local_deep_research/database/thread_local_session.py b/src/local_deep_research/database/thread_local_session.py
index 6d735670d6..f2da9ba525 100644
--- a/src/local_deep_research/database/thread_local_session.py
+++ b/src/local_deep_research/database/thread_local_session.py
@@ -1,6 +1,6 @@
"""
Thread-local database session management.
-Each thread gets its own database session that persists for the thread's lifetime.
+Each thread gets its own database session, reused until its owned cleanup boundary.
"""
import functools
@@ -18,7 +18,7 @@ from .encrypted_db import db_manager
class ThreadLocalSessionManager:
"""
Manages database sessions per thread.
- Each thread gets its own session that is reused throughout the thread's lifetime.
+ Each thread gets its own session, reused until the request or task finishes.
"""
def __init__(self):
@@ -271,16 +271,11 @@ class ThreadLocalSessionManager:
Entries here hold the user's plaintext SQLCipher password so a
pooled worker can rebuild its session without a round-trip to the
- password store. Under Flask such an entry lived for exactly one
- request: ``teardown_appcontext`` called ``cleanup_current_thread()``
- ON the request-serving thread (``web/app_factory.py``). FastAPI runs
- sync route handlers on a shared AnyIO worker pool while the
- equivalent middleware hook is ``async`` and therefore runs on the
- event-loop thread, so it pops the loop thread's entry and never a
- worker's. ``cleanup_dead_threads()`` only reaps threads that have
- exited, and AnyIO keeps a worker alive for 10s of idle — under
- sustained load, indefinitely. So without this the password outlived
- the session that authorised it, including across logout.
+ password store. Synchronous routes normally drop their owner-thread
+ entry through ``WorkerCleanupAPIRoute``. This username-wide cleanup
+ is still required on logout because another worker may be executing
+ background work for the same user, and one thread cannot clear a
+ different thread's ``threading.local`` state.
Only the tracking dict is cleared. The owning thread's
``threading.local`` session is deliberately left alone: one thread
@@ -322,7 +317,8 @@ thread_session_manager = ThreadLocalSessionManager()
def get_metrics_session(username: str, password: str) -> Optional[Session]:
"""
Get a database session for metrics operations in the current thread.
- The session is created once and reused for the thread's lifetime.
+ The session is created once and reused until the thread's owned cleanup
+ boundary (request, task, or worker exit).
Note: This specifically uses create_thread_safe_session_for_metrics internally
and should only be used for metrics-related database operations.
@@ -336,12 +332,33 @@ def get_current_thread_session() -> Optional[Session]:
def cleanup_current_thread():
- """Clean up the current thread's database session and cached credentials.
+ """Clean up every database session owned by the current thread.
Also clears any passwords cached by ``metrics_writer`` on this thread —
pooled worker threads must not retain plaintext credentials across tasks.
"""
- thread_session_manager.cleanup_thread()
+ try:
+ thread_session_manager.cleanup_thread()
+ except Exception:
+ logger.debug(
+ "cleanup_current_thread: error closing thread-local DB session",
+ exc_info=True,
+ )
+ try:
+ # Lazy import avoids the encrypted_db -> thread_local_session import
+ # cycle during module bootstrap. This is the second session path:
+ # ambient SettingsManager callers use db_utils' per-thread LRU rather
+ # than ThreadLocalSessionManager.
+ from ..utilities.db_utils import (
+ cleanup_cached_user_sessions_current_thread,
+ )
+
+ cleanup_cached_user_sessions_current_thread()
+ except Exception:
+ logger.debug(
+ "cleanup_current_thread: error closing cached DB sessions",
+ exc_info=True,
+ )
try:
from .thread_metrics import metrics_writer
diff --git a/src/local_deep_research/utilities/db_utils.py b/src/local_deep_research/utilities/db_utils.py
index f8fafd5adc..db2be7a59d 100644
--- a/src/local_deep_research/utilities/db_utils.py
+++ b/src/local_deep_research/utilities/db_utils.py
@@ -8,7 +8,7 @@ from sqlalchemy.orm import Session
from ..config.paths import get_data_directory
from ..exceptions import NoUserDatabaseError
from ..database.encrypted_db import db_manager
-from .threading_utils import thread_specific_cache
+from .threading_utils import g_thread_local_store, thread_specific_cache
from .request_context import get_current_username
# Database paths using new centralized configuration
@@ -64,7 +64,20 @@ def get_db_session(
)
return None
- return _get_cached_user_session(username, _namespace)
+ session = _get_cached_user_session(username, _namespace)
+
+ # Keep an owner-thread registry in addition to the bounded shared cache.
+ # The cache can evict this thread's entry while the session is still in
+ # use, so scanning the cache alone at request teardown is insufficient:
+ # an evicted SQLAlchemy Session retains its QueuePool connection until a
+ # cyclic-GC pass happens to reclaim it. The registry lets the worker that
+ # acquired the session close it deterministically at its cleanup boundary.
+ tracked = getattr(g_thread_local_store, "db_sessions", None)
+ if tracked is None:
+ tracked = {}
+ g_thread_local_store.db_sessions = tracked
+ tracked[id(session)] = session
+ return session
@thread_specific_cache(cache=LRUCache(maxsize=10))
@@ -82,6 +95,49 @@ def _get_cached_user_session(username: str, _namespace: str = "") -> Session:
raise NoUserDatabaseError(f"No database found for user {username}")
+def cleanup_cached_user_sessions_current_thread() -> int:
+ """Close sessions cached or acquired by the current worker thread.
+
+ ``_get_cached_user_session`` uses a process-wide LRU with the worker's
+ UUID in each key. FastAPI reuses those workers across requests, so the
+ entries must be removed and closed on the worker itself when a request or
+ owned background task finishes. Sessions evicted from the LRU are also
+ closed via the owner-thread registry populated by ``get_db_session``.
+
+ Returns the number of distinct sessions closed.
+ """
+ thread_key = getattr(g_thread_local_store, "thread_id", None)
+ tracked = getattr(g_thread_local_store, "db_sessions", {})
+ sessions = dict(tracked)
+
+ cache = _get_cached_user_session.cache
+ lock = _get_cached_user_session.cache_lock
+ if thread_key is not None:
+ # Detach under cachetools' own lock, but close outside it. Session
+ # close can perform driver work and must not serialize unrelated
+ # workers' cache access.
+ with lock:
+ current_keys = [
+ key for key in list(cache) if key and key[0] == thread_key
+ ]
+ for key in current_keys:
+ session = cache.pop(key)
+ sessions[id(session)] = session
+
+ if hasattr(g_thread_local_store, "db_sessions"):
+ del g_thread_local_store.db_sessions
+
+ for session in sessions.values():
+ try:
+ session.close()
+ except Exception:
+ logger.warning(
+ "Failed to close a cached DB session on worker cleanup"
+ )
+
+ return len(sessions)
+
+
def get_settings_manager(
db_session: Session | None = None, username: str | None = None
):
diff --git a/src/local_deep_research/web/database/README.md b/src/local_deep_research/web/database/README.md
index a5f2980a1a..24a6feb15b 100644
--- a/src/local_deep_research/web/database/README.md
+++ b/src/local_deep_research/web/database/README.md
@@ -46,9 +46,13 @@ The unified database contains:
The application uses per-user encrypted SQLite databases (via [SQLCipher](https://www.zetetic.net/sqlcipher/)) with a single shared [SQLAlchemy QueuePool](https://docs.sqlalchemy.org/en/20/core/pooling.html) per user:
-- **QueuePool** (shared per-user engine in `DatabaseManager.connections`): Serves both Flask request handlers AND background threads (research workers, scheduler jobs, metric writers). `pool_size=20`, `max_overflow=40`, `pool_timeout=10`. Engines are created with `check_same_thread=False` so they're safe to share across threads. FD usage is bounded by `pool_size + max_overflow` per user, not by the number of active background threads.
+- **QueuePool** (shared per-user engine in `DatabaseManager.connections`): Serves both FastAPI request handlers and background threads (research workers, scheduler jobs, metric writers). `pool_size=20`, `max_overflow=40`, `pool_timeout=10`. Engines are created with `check_same_thread=False` so they're safe to share across threads. FD usage is bounded by `pool_size + max_overflow` per user, not by the number of active background threads.
-Cleanup is handled by the `@thread_cleanup` decorator (closes sessions at thread exit, returning connections to the pool) and by a periodic `engine.dispose()` sweep every 30 minutes that mitigates a SQLCipher+WAL handle leak triggered by out-of-order connection closes.
+Cleanup is handled by `WorkerCleanupAPIRoute` for synchronous HTTP endpoints,
+`WorkerCleanupStreamingResponse` for each synchronous streamed-response
+iterator step, the `@thread_cleanup` decorator for owned background tasks, and
+a periodic `engine.dispose()` sweep every 30 minutes that mitigates a
+SQLCipher+WAL handle leak triggered by out-of-order connection closes.
Note: The core database module is at `src/local_deep_research/database/`, separate from this `web/database/` directory. See [Architecture - Thread & Resource Lifecycle](../../../../docs/architecture.md#thread--resource-lifecycle) for the full cleanup architecture.
diff --git a/src/local_deep_research/web/dependencies/threadpool.py b/src/local_deep_research/web/dependencies/threadpool.py
index 473a8eafde..6b005643d5 100644
--- a/src/local_deep_research/web/dependencies/threadpool.py
+++ b/src/local_deep_research/web/dependencies/threadpool.py
@@ -10,20 +10,175 @@ attached to that worker — the next task that lands on it would inherit
the previous user's session (memory bloat at best, cross-user state
mixing at worst).
-``run_db_sync`` wraps the sync helper in a ``try/finally`` that calls
-``cleanup_current_thread()`` on the worker, guaranteeing each task
-starts fresh.
+``WorkerCleanupAPIRoute`` supplies that owner-thread boundary for plain
+``def`` endpoints. ``WorkerCleanupStreamingResponse`` supplies it for each
+worker that advances a synchronous response body, and ``run_db_sync`` does
+the same for explicit ``asyncio.to_thread`` DB work inside asynchronous
+endpoints.
"""
from __future__ import annotations
import asyncio
+import functools
+import inspect
+from collections.abc import AsyncIterable, Iterable, Iterator
from typing import Any, Callable, TypeVar
+from fastapi.encoders import jsonable_encoder
+from fastapi.routing import APIRoute, APIRouter
from loguru import logger
+from starlette.responses import Response, StreamingResponse
T = TypeVar("T")
+_WORKER_CLEANUP_MARKER = "__ldr_worker_thread_cleanup__"
+
+
+def wrap_sync_route_with_cleanup(fn: Callable[..., T]) -> Callable[..., T]:
+ """Wrap a synchronous FastAPI endpoint in an owner-thread cleanup.
+
+ FastAPI executes plain ``def`` endpoints on an AnyIO worker, while ASGI
+ middleware teardown runs on the event-loop thread. Database sessions are
+ thread-local, so middleware cannot release the endpoint worker's sessions.
+ This wrapper's ``finally`` runs on that worker and restores Flask's former
+ request-teardown ownership model.
+
+ Deliberately NOT a ``yield``-dependency and NOT a ``BackgroundTask``.
+ Both would move cleanup to a *second*, separate
+ ``anyio.to_thread.run_sync`` dispatch, and anyio gives no thread
+ affinity between separate dispatches — the documented hazard in
+ ``get_db_session_dep`` (``web/dependencies/auth.py``) for exactly that
+ split. Cleanup has to happen inside the SAME worker dispatch that ran
+ the endpoint, which is why this wraps ``dependant.call`` itself rather
+ than framing the boundary with FastAPI's own request-lifecycle hooks.
+
+ That constraint also decides *where inside this one dispatch* cleanup
+ must sit. FastAPI does not serialize a plain (non-``Response``) return
+ value inside ``dependant.call``: ``routing.py``'s route handler calls
+ ``serialize_response``/``jsonable_encoder`` on the raw return value
+ *after* ``dependant.call`` has already returned, back on the event-loop
+ thread. Releasing the session before returning — the natural place for
+ a ``finally``/``with`` cleanup — would therefore free this worker's DB
+ session (and SQLCipher passphrase) before that encoding step runs. Any
+ lazily loaded ORM attribute touched only during encoding would then hit
+ a closed session (``DetachedInstanceError``) or silently serialize as
+ incomplete 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.
+ """
+ # 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.
+ if (
+ inspect.iscoroutinefunction(fn)
+ or inspect.isgeneratorfunction(fn)
+ or inspect.isasyncgenfunction(fn)
+ or getattr(fn, _WORKER_CLEANUP_MARKER, False)
+ ):
+ return fn
+
+ @functools.wraps(fn)
+ def _wrapped(*args: Any, **kwargs: Any) -> T:
+ from ...database.thread_local_session import thread_cleanup
+
+ with thread_cleanup():
+ result = fn(*args, **kwargs)
+ if isinstance(result, Response):
+ return result
+ # Force JSON encoding now, on the worker thread that still owns
+ # the DB session this endpoint used, instead of leaving it for
+ # FastAPI to do afterward on the event-loop thread with the
+ # session already released.
+ return jsonable_encoder(result)
+
+ setattr(_wrapped, _WORKER_CLEANUP_MARKER, True)
+ return _wrapped
+
+
+def iterate_sync_with_cleanup(iterable: Iterable[T]) -> Iterator[T]:
+ """Iterate a synchronous response body with owner-worker cleanup.
+
+ Starlette advances a synchronous ``StreamingResponse`` body through one
+ ``anyio.to_thread.run_sync(next, ...)`` call per chunk. Those calls happen
+ *after* the endpoint has returned, and they are not guaranteed to use the
+ endpoint's worker (or even the same worker for consecutive chunks).
+ Therefore the endpoint wrapper cannot release sessions opened while the
+ body is being produced.
+
+ Wrapping each individual ``next()`` call gives every worker that advances
+ the 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.
+ """
+ iterator: Iterator[T] | None = None
+ 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
+
+
+class WorkerCleanupStreamingResponse(StreamingResponse):
+ """Streaming response that cleans workers advancing synchronous bodies.
+
+ Async iterables already run on the event-loop task and are covered by the
+ request middleware. Only synchronous iterables are handed to AnyIO
+ workers, so only those need the per-iteration wrapper.
+ """
+
+ def __init__(self, content: Any, *args: Any, **kwargs: Any) -> None:
+ if not isinstance(content, AsyncIterable):
+ content = iterate_sync_with_cleanup(content)
+ super().__init__(content, *args, **kwargs)
+
+
+class WorkerCleanupAPIRoute(APIRoute):
+ """APIRoute that cleans thread-local state after synchronous endpoints."""
+
+ def __init__(self, path: str, endpoint: Callable[..., Any], **kwargs: Any):
+ # Keep ``route.endpoint`` as the exact registered handler. SlowAPI,
+ # route-contract checks, and other FastAPI integrations use that
+ # public attribute for metadata and identity. Request dispatch goes
+ # 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
+ raise RuntimeError("FastAPI route has no dispatch callable")
+ self.dependant.call = wrap_sync_route_with_cleanup(call)
+
+
+def prepare_router_for_worker_cleanup(router: APIRouter) -> None:
+ """Wrap sync dispatch targets on an already-populated router.
+
+ ``FastAPI.include_router`` copies each source route and rebuilds its
+ dependency graph, so this must run on the destination application's
+ router *after* inclusion. Mutating ``dependant.call`` is intentional:
+ FastAPI dispatches through it while ``route.endpoint`` remains the exact
+ handler registered by the module.
+ """
+ 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)
+
async def run_db_sync(fn: Callable[..., T], /, *args: Any, **kwargs: Any) -> T:
"""Run a sync DB-touching function on the asyncio default
@@ -100,4 +255,11 @@ async def run_db_sync(fn: Callable[..., T], /, *args: Any, **kwargs: Any) -> T:
return await asyncio.to_thread(_wrapped)
-__all__ = ["run_db_sync"]
+__all__ = [
+ "WorkerCleanupAPIRoute",
+ "WorkerCleanupStreamingResponse",
+ "iterate_sync_with_cleanup",
+ "prepare_router_for_worker_cleanup",
+ "run_db_sync",
+ "wrap_sync_route_with_cleanup",
+]
diff --git a/src/local_deep_research/web/fastapi_app.py b/src/local_deep_research/web/fastapi_app.py
index bc7be55616..b592a746d2 100644
--- a/src/local_deep_research/web/fastapi_app.py
+++ b/src/local_deep_research/web/fastapi_app.py
@@ -117,15 +117,11 @@ def warn_if_threadpool_exceeds_db_pool(worker_threads: int) -> bool:
"""Warn when the AnyIO worker pool is larger than a user's DB pool.
Raising ``web.threadpool_max_threads`` above the per-user pool capacity is
- not merely a tuning choice, because a sync route's DB session is never
- returned to the pool: ``DatabaseMiddleware`` is ``async def``, so its
- ``finally`` runs on the event-loop thread and calls
- ``cleanup_current_thread()`` there, while the session lives in a
- ``threading.local()`` on the AnyIO worker that actually served the
- request. Measured on this branch: checked-out connections track the
- number of distinct worker threads (32 concurrent requests -> 14 checked
- out, 86 sequential -> 1) and never return to zero, so the ceiling is the
- worker count rather than request volume.
+ not merely a tuning choice. ``WorkerCleanupAPIRoute`` returns each sync
+ route's connections when that request finishes, but every concurrently
+ active DB-touching worker can still hold one pool slot. More workers than
+ slots therefore permit a burst from one user to exhaust the pool before
+ any request reaches its cleanup boundary.
Below the pool capacity that is harmless, which is why this warns instead
of failing. Above it, one user's concurrent requests can exhaust their own
@@ -141,8 +137,8 @@ def warn_if_threadpool_exceeds_db_pool(worker_threads: int) -> bool:
return False
logger.warning(
"web.threadpool_max_threads ({}) exceeds the per-user database pool "
- "capacity ({} = pool_size {} + max_overflow {}). Synchronous routes "
- "retain one connection per worker thread, so a single user's "
+ "capacity ({} = pool_size {} + max_overflow {}). Concurrent "
+ "synchronous routes can each hold one connection, so a single user's "
"concurrent requests can exhaust their pool and then block for "
"pool_timeout. Keep this at or below {}.",
worker_threads,
@@ -1589,15 +1585,12 @@ class DatabaseMiddleware:
# Cleanup after request.
#
- # Two INDEPENDENT try blocks, matching main's
- # `cleanup_db_session` teardown hook (web/app_factory.py). They
- # must not share one: `cleanup_dead_threads()` walks a shared
- # registry and is by some margin the likelier of the pair to
- # throw, and `cleanup_current_thread()` is the call that reclaims
- # *this* request thread's DB session and the SQLCipher passphrase
- # that opened it. Collapsing them let one throw from the sweep
- # skip that reclamation for the rest of the process's life.
- # Pinned by tests/web/test_teardown_cleanup_asgi.py.
+ # Keep the two sweeps independent so one failure cannot skip the
+ # other. This async middleware can clean event-loop-owned state;
+ # WorkerCleanupAPIRoute already reclaimed a synchronous
+ # endpoint's AnyIO-worker state before control returned here.
+ # Pinned by tests/web/test_teardown_cleanup_asgi.py and
+ # tests/web/test_db_session_lifecycle_asgi.py.
try:
from ..database.thread_local_session import (
cleanup_dead_threads,
@@ -2151,6 +2144,15 @@ app = FastAPI(
lifespan=lifespan,
)
+# FastAPI runs plain ``def`` endpoints on AnyIO workers, whereas ASGI
+# middleware teardown runs on the event-loop thread. Install an endpoint
+# wrapper so thread-local DB sessions are released on the worker that owns
+# them. Populated module routers receive the same dispatch wrapper in
+# ``_mount_all`` without replacing their registered endpoint objects.
+from .dependencies.threadpool import WorkerCleanupAPIRoute # noqa: E402
+
+app.router.route_class = WorkerCleanupAPIRoute
+
# ASGI middleware stack.
# Starlette add_middleware is LIFO: last added = outermost.
# Desired order (outer→inner): SecureCookie → SecurityHeaders → Session → CSRF → Database → app
@@ -2332,6 +2334,7 @@ def _mount_all(app: FastAPI) -> None:
from ..database.session_context import get_user_db_session
from ..settings.logger import log_settings
from ..utilities.db_utils import get_settings_manager
+ from .dependencies.threadpool import prepare_router_for_worker_cleanup
from .routers.api_v1 import router as api_v1_router
from .services.socketio_asgi import socket_app
@@ -2383,6 +2386,13 @@ def _mount_all(app: FastAPI) -> None:
for name, r in _routers.items():
app.include_router(r)
+ # include_router() preserves the source APIRoute class rather than using
+ # app.router.route_class for already-populated module routers. Apply the
+ # cleanup to the copied dispatch targets after every router is mounted;
+ # route.endpoint remains the original handler for introspection, SlowAPI,
+ # and route-identity security checks.
+ prepare_router_for_worker_cleanup(app.router)
+
@app.get("/", include_in_schema=False)
def index(request: Request):
"""Root route - redirect to login if not authenticated."""
diff --git a/src/local_deep_research/web/routers/auth.py b/src/local_deep_research/web/routers/auth.py
index ffe7d0a71e..1a7eb1aa83 100644
--- a/src/local_deep_research/web/routers/auth.py
+++ b/src/local_deep_research/web/routers/auth.py
@@ -861,15 +861,11 @@ def logout(request: Request):
session_password_store.clear_all_for_user(username)
- # Same reasoning, second store. Pooled AnyIO worker threads
- # cache the plaintext SQLCipher password so they can rebuild a
- # session cheaply. Flask dropped that entry at the end of every
- # request — teardown_appcontext ran cleanup_current_thread() ON
- # the request-serving thread — but the FastAPI equivalent is
- # async and runs on the event-loop thread, so it can never pop a
- # worker's entry, and the dead-thread sweep only reaps threads
- # that have already exited. Without this the password outlives
- # the session that authorised it.
+ # Same reasoning, second store. Ordinary synchronous requests
+ # clear their worker-local credential through
+ # WorkerCleanupAPIRoute, but logout must also remove entries held
+ # by other workers currently acting for this user. One thread
+ # cannot clear another thread's ``threading.local`` directly.
from ...database.thread_local_session import (
clear_user_credentials,
)
diff --git a/src/local_deep_research/web/routers/library.py b/src/local_deep_research/web/routers/library.py
index 1744f2dd79..8e09482ad2 100644
--- a/src/local_deep_research/web/routers/library.py
+++ b/src/local_deep_research/web/routers/library.py
@@ -12,10 +12,12 @@ from fastapi.responses import (
HTMLResponse,
JSONResponse,
Response,
- StreamingResponse,
)
from ..dependencies.auth import require_auth
-from ..dependencies.threadpool import run_db_sync
+from ..dependencies.threadpool import (
+ WorkerCleanupStreamingResponse,
+ run_db_sync,
+)
from ..template_config import templates
import os
@@ -879,7 +881,7 @@ def download_all_text(
# `except Exception as e:` block in generate() above, which only ever
# surfaces `type(e).__name__` or an already-scrubbed string from
# download_service.
- return StreamingResponse(
+ return WorkerCleanupStreamingResponse(
generate(),
media_type="text/event-stream",
headers={
@@ -1304,7 +1306,7 @@ async def download_bulk(
# download_as_text and their helpers in download_service.py) or, on the
# `except Exception as e:` path above, is built from `type(e).__name__`
# only — never the raw `error_msg = str(e)`.
- return StreamingResponse(
+ return WorkerCleanupStreamingResponse(
generate(),
media_type="text/event-stream",
headers={
diff --git a/src/local_deep_research/web/routers/rag.py b/src/local_deep_research/web/routers/rag.py
index 40d2109d22..8860de883c 100644
--- a/src/local_deep_research/web/routers/rag.py
+++ b/src/local_deep_research/web/routers/rag.py
@@ -11,14 +11,17 @@ Provides endpoints for managing RAG indexing of library documents:
import asyncio
from fastapi import APIRouter, Depends, HTTPException, Request
-from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse
+from fastapi.responses import HTMLResponse, JSONResponse
from ..dependencies.auth import require_auth
from ..dependencies.rate_limit import (
limiter,
upload_rate_limit_ip,
upload_rate_limit_user,
)
-from ..dependencies.threadpool import run_db_sync
+from ..dependencies.threadpool import (
+ WorkerCleanupStreamingResponse,
+ run_db_sync,
+)
from ..template_config import templates
import os
@@ -1355,7 +1358,7 @@ def index_all(
_sse_cancel.set()
safe_close(rag_service, "rag_service (index-all SSE)")
- return StreamingResponse(
+ return WorkerCleanupStreamingResponse(
generate(),
media_type="text/event-stream",
headers={
@@ -3502,7 +3505,9 @@ def index_collection(
else:
safe_close(rag_service, "rag_service (index-collection SSE)")
- response = StreamingResponse(generate(), media_type="text/event-stream")
+ response = WorkerCleanupStreamingResponse(
+ generate(), media_type="text/event-stream"
+ )
# Prevent buffering for proper SSE streaming
response.headers["Cache-Control"] = "no-cache, no-transform"
response.headers["Connection"] = "keep-alive"
diff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.py
index 73070815f8..7879446485 100644
--- a/src/local_deep_research/web/routers/research.py
+++ b/src/local_deep_research/web/routers/research.py
@@ -2,7 +2,6 @@ from fastapi import APIRouter, Depends, Request
from fastapi.responses import (
JSONResponse,
RedirectResponse,
- StreamingResponse,
)
from ..dependencies.auth import require_auth
from ..dependencies.rate_limit import (
@@ -13,7 +12,10 @@ from ..dependencies.rate_limit import (
upload_rate_limit_ip,
upload_rate_limit_user,
)
-from ..dependencies.threadpool import run_db_sync
+from ..dependencies.threadpool import (
+ WorkerCleanupStreamingResponse,
+ run_db_sync,
+)
from ..template_config import templates
import asyncio
@@ -2321,7 +2323,7 @@ def export_research_logs(
safe_id = re.sub(r"[^a-zA-Z0-9_-]", "", research_id)
filename = f"research_logs_{safe_id or 'export'}.jsonl"
- return StreamingResponse(
+ return WorkerCleanupStreamingResponse(
generate(),
media_type="application/x-ndjson",
headers={
diff --git a/tests/research_library/routes/test_rag_routes_cancel_and_worker_wiring.py b/tests/research_library/routes/test_rag_routes_cancel_and_worker_wiring.py
index 6ce7f90544..e7ccac097d 100644
--- a/tests/research_library/routes/test_rag_routes_cancel_and_worker_wiring.py
+++ b/tests/research_library/routes/test_rag_routes_cancel_and_worker_wiring.py
@@ -359,7 +359,7 @@ class TestIndexCollectionSSERegistrationLifecycle:
patch(f"{MODULE}.safe_close"),
patch(f"{_DB_CTX}.get_user_db_session") as mock_get_session,
patch(
- f"{MODULE}.StreamingResponse",
+ f"{MODULE}.WorkerCleanupStreamingResponse",
side_effect=_capture_streaming_response,
),
):
@@ -510,7 +510,7 @@ class TestIndexCollectionDisconnectWorkerDrain:
patch(f"{MODULE}.safe_close") as mock_safe_close,
patch(f"{_DB_CTX}.get_user_db_session") as mock_get_session,
patch(
- f"{MODULE}.StreamingResponse",
+ f"{MODULE}.WorkerCleanupStreamingResponse",
side_effect=_capture_streaming_response,
),
patch("threading.Thread", thread_cls),
@@ -864,7 +864,7 @@ class TestMaxWorkersPlumbedFromSettings:
patch(f"{MODULE}.safe_close"),
patch(f"{_DB_CTX}.get_user_db_session") as mock_get_session,
patch(
- f"{MODULE}.StreamingResponse",
+ f"{MODULE}.WorkerCleanupStreamingResponse",
side_effect=_capture_streaming_response,
),
):
diff --git a/tests/research_library/routes/test_rag_routes_gaps_main_port.py b/tests/research_library/routes/test_rag_routes_gaps_main_port.py
index 9d246a3f64..8945d93ccc 100644
--- a/tests/research_library/routes/test_rag_routes_gaps_main_port.py
+++ b/tests/research_library/routes/test_rag_routes_gaps_main_port.py
@@ -229,7 +229,9 @@ def _captured_stream():
captured["media_type"] = kwargs.get("media_type")
return SimpleNamespace(content=content, headers=captured["headers"])
- with patch(f"{MODULE}.StreamingResponse", side_effect=_capture):
+ with patch(
+ f"{MODULE}.WorkerCleanupStreamingResponse", side_effect=_capture
+ ):
yield captured
diff --git a/tests/security/test_realtime_channel_isolation.py b/tests/security/test_realtime_channel_isolation.py
index 931bc2ab2b..7bd16185f7 100644
--- a/tests/security/test_realtime_channel_isolation.py
+++ b/tests/security/test_realtime_channel_isolation.py
@@ -749,7 +749,10 @@ def test_the_stream_route_inventory_still_matches_the_source(app):
if not isinstance(node, ast.Call):
continue
fn = node.func
- if getattr(fn, "id", None) != "StreamingResponse":
+ if getattr(fn, "id", None) not in {
+ "StreamingResponse",
+ "WorkerCleanupStreamingResponse",
+ }:
continue
media = next(
(
diff --git a/tests/security/test_secret_leakage_sweep.py b/tests/security/test_secret_leakage_sweep.py
index 9d7c606908..c9e40ec894 100644
--- a/tests/security/test_secret_leakage_sweep.py
+++ b/tests/security/test_secret_leakage_sweep.py
@@ -103,6 +103,7 @@ RESPONSE_CTORS = frozenset(
"PlainTextResponse",
"Response",
"StreamingResponse",
+ "WorkerCleanupStreamingResponse",
"HTTPException",
}
)
diff --git a/tests/web/dependencies/test_threadpool.py b/tests/web/dependencies/test_threadpool.py
index 81bdc02c5d..5a77576ae5 100644
--- a/tests/web/dependencies/test_threadpool.py
+++ b/tests/web/dependencies/test_threadpool.py
@@ -10,11 +10,17 @@ the same worker doesn't inherit the previous user's session.
from __future__ import annotations
import asyncio
+import ast
+import inspect
import threading
from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
from unittest.mock import patch
import pytest
+from fastapi import APIRouter, FastAPI
+from fastapi.routing import APIRoute
+from fastapi.testclient import TestClient
def test_run_db_sync_calls_cleanup_on_success():
@@ -236,3 +242,332 @@ def test_run_db_sync_passes_kwargs_through():
"local_deep_research.database.thread_local_session.cleanup_current_thread"
):
assert asyncio.run(run_db_sync(_work, 10, b=32)) == 42
+
+
+def test_worker_cleanup_route_runs_cleanup_on_success_and_error():
+ """A synchronous endpoint always cleans on the serving worker."""
+ from local_deep_research.web.dependencies.threadpool import (
+ WorkerCleanupAPIRoute,
+ wrap_sync_route_with_cleanup,
+ )
+
+ worker_threads: list[int] = []
+ cleanup_threads: list[int] = []
+
+ def ok():
+ worker_threads.append(threading.get_ident())
+ return {"ok": True}
+
+ def boom():
+ worker_threads.append(threading.get_ident())
+ raise RuntimeError("route failed")
+
+ ok_route = WorkerCleanupAPIRoute("/ok", ok, methods=["GET"])
+ assert ok_route.endpoint is ok
+ assert getattr(
+ ok_route.dependant.call, "__ldr_worker_thread_cleanup__", False
+ )
+ assert ok_route.dependant.call.__wrapped__ is ok
+
+ with patch(
+ "local_deep_research.database.thread_local_session.cleanup_current_thread",
+ side_effect=lambda: cleanup_threads.append(threading.get_ident()),
+ ):
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ assert executor.submit(ok_route.dependant.call).result() == {
+ "ok": True
+ }
+ with pytest.raises(RuntimeError, match="route failed"):
+ executor.submit(wrap_sync_route_with_cleanup(boom)).result()
+
+ assert cleanup_threads == worker_threads
+
+
+def test_worker_cleanup_encodes_plain_return_value_before_releasing_session():
+ """A non-``Response`` return value must be serialized before cleanup.
+
+ Regression test for the release-before-serialize ordering bug:
+ FastAPI's own routing.py only calls ``serialize_response``/
+ ``jsonable_encoder`` on a plain (non-``Response``) return value AFTER
+ ``dependant.call`` has already returned. An ordinary
+ ``with thread_cleanup(): return fn(...)`` releases the session the
+ instant ``fn`` returns -- before that encoding step -- so a lazily
+ materialized value would be read back with the session already gone.
+ ``wrap_sync_route_with_cleanup`` must therefore encode the value
+ itself, inside the cleanup block, before cleanup runs.
+ """
+ from local_deep_research.web.dependencies.threadpool import (
+ WorkerCleanupAPIRoute,
+ )
+
+ events: list[str] = []
+
+ class LazyValue:
+ """Stands in for data whose materialization needs a live session.
+
+ ``jsonable_encoder`` falls back to ``dict(obj)`` for an object
+ that isn't a primitive, Pydantic model, dataclass, dict, or
+ list -- which calls ``__iter__``. Recording that call lets the
+ test observe whether it happened before or after cleanup.
+ """
+
+ def __iter__(self):
+ events.append("encoded")
+ return iter({"id": 1}.items())
+
+ def endpoint():
+ return {"value": LazyValue()}
+
+ route = WorkerCleanupAPIRoute("/lazy", endpoint, methods=["GET"])
+
+ with patch(
+ "local_deep_research.database.thread_local_session.cleanup_current_thread",
+ side_effect=lambda: events.append("cleaned"),
+ ):
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ result = executor.submit(route.dependant.call).result()
+
+ assert events == ["encoded", "cleaned"], (
+ f"value must be serialized before the session is released, got {events}"
+ )
+ assert result == {"value": {"id": 1}}
+
+
+def test_worker_cleanup_leaves_async_and_generator_endpoints_unchanged():
+ """Deferred endpoint bodies need a different lifetime model."""
+ from local_deep_research.web.dependencies.threadpool import (
+ wrap_sync_route_with_cleanup,
+ )
+
+ async def async_endpoint():
+ return {"kind": "async"}
+
+ def sync_generator_endpoint():
+ yield {"kind": "sync-generator"}
+
+ 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
+ )
+ assert (
+ wrap_sync_route_with_cleanup(async_generator_endpoint)
+ is async_generator_endpoint
+ )
+
+
+def test_sync_iterator_cleanup_runs_on_chunk_completion_and_error():
+ """Every ``next()`` outcome cleans on the worker that produced it."""
+ from local_deep_research.web.dependencies.threadpool import (
+ iterate_sync_with_cleanup,
+ )
+
+ cleanup_threads: list[int] = []
+ iteration_threads: list[int] = []
+
+ def complete_body():
+ iteration_threads.append(threading.get_ident())
+ yield b"complete"
+
+ def failing_body():
+ iteration_threads.append(threading.get_ident())
+ yield b"first"
+ iteration_threads.append(threading.get_ident())
+ raise ValueError("stream failed")
+
+ with patch(
+ "local_deep_research.database.thread_local_session.cleanup_current_thread",
+ side_effect=lambda: cleanup_threads.append(threading.get_ident()),
+ ):
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ complete = iterate_sync_with_cleanup(complete_body())
+ assert executor.submit(next, complete).result() == b"complete"
+ with pytest.raises(StopIteration):
+ executor.submit(next, complete).result()
+
+ failing = iterate_sync_with_cleanup(failing_body())
+ assert executor.submit(next, failing).result() == b"first"
+ with pytest.raises(ValueError, match="stream failed"):
+ executor.submit(next, failing).result()
+
+ assert len(cleanup_threads) == 4
+ assert set(cleanup_threads) == set(iteration_threads)
+
+
+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 (
+ WorkerCleanupStreamingResponse,
+ )
+
+ async def body():
+ yield b"async"
+
+ content = body()
+ response = WorkerCleanupStreamingResponse(content)
+ assert response.body_iterator is content
+
+
+def test_production_routers_do_not_use_bare_streaming_response():
+ """New synchronous streams cannot silently bypass worker cleanup."""
+ router_root = (
+ Path(__file__).resolve().parents[3]
+ / "src"
+ / "local_deep_research"
+ / "web"
+ / "routers"
+ )
+ bare_imports: list[str] = []
+ bare_calls: list[str] = []
+ protected_calls: list[str] = []
+
+ for path in sorted(router_root.glob("*.py")):
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
+ for node in ast.walk(tree):
+ if isinstance(node, ast.ImportFrom):
+ for name in node.names:
+ if name.name == "StreamingResponse":
+ bare_imports.append(f"{path.name}:{node.lineno}")
+ if not isinstance(node, ast.Call):
+ continue
+ if isinstance(node.func, ast.Name):
+ call_name = node.func.id
+ elif isinstance(node.func, ast.Attribute):
+ call_name = node.func.attr
+ else:
+ call_name = None
+ if call_name == "StreamingResponse":
+ bare_calls.append(f"{path.name}:{node.lineno}")
+ elif call_name == "WorkerCleanupStreamingResponse":
+ protected_calls.append(f"{path.name}:{node.lineno}")
+
+ assert bare_imports == [], (
+ "router modules imported bare StreamingResponse: "
+ f"{bare_imports}; use WorkerCleanupStreamingResponse"
+ )
+ assert bare_calls == [], (
+ "router modules constructed bare StreamingResponse objects: "
+ f"{bare_calls}; use WorkerCleanupStreamingResponse"
+ )
+ assert len(protected_calls) >= 5, (
+ f"the production stream census unexpectedly shrank: {protected_calls}"
+ )
+
+
+def test_prepare_router_wraps_sync_routes_only_and_is_idempotent():
+ """Mounted routes wrap dispatch without replacing endpoint identity."""
+ from local_deep_research.web.dependencies.threadpool import (
+ prepare_router_for_worker_cleanup,
+ )
+
+ router = APIRouter()
+
+ @router.get("/sync")
+ def sync_endpoint():
+ return {"kind": "sync"}
+
+ @router.get("/async")
+ async def async_endpoint():
+ return {"kind": "async"}
+
+ app = FastAPI()
+ app.include_router(router)
+ original = {
+ route.path: (route.endpoint, route.dependant.call)
+ for route in app.routes
+ if isinstance(route, APIRoute)
+ }
+ prepare_router_for_worker_cleanup(app.router)
+ once = {
+ route.path: (route.endpoint, route.dependant.call)
+ for route in app.routes
+ if isinstance(route, APIRoute)
+ }
+ prepare_router_for_worker_cleanup(app.router)
+ twice = {
+ route.path: (route.endpoint, route.dependant.call)
+ for route in app.routes
+ if isinstance(route, APIRoute)
+ }
+
+ assert once["/sync"][0] is original["/sync"][0]
+ assert once["/sync"][1] is not original["/sync"][1]
+ assert once["/sync"][1].__wrapped__ is once["/sync"][0]
+ assert once["/async"] == original["/async"]
+ assert twice == once
+
+
+def test_prepared_router_dispatches_through_cleanup_on_the_worker():
+ """Post-mount dispatch mutation is observed by FastAPI's route handler."""
+ from local_deep_research.web.dependencies.threadpool import (
+ prepare_router_for_worker_cleanup,
+ )
+
+ endpoint_threads: list[int] = []
+ cleanup_threads: list[int] = []
+ router = APIRouter()
+
+ @router.get("/sync")
+ def sync_endpoint():
+ endpoint_threads.append(threading.get_ident())
+ return {"ok": True}
+
+ app = FastAPI()
+ app.include_router(router)
+ prepare_router_for_worker_cleanup(app.router)
+
+ mounted = next(
+ route
+ for route in app.routes
+ if isinstance(route, APIRoute) and route.path == "/sync"
+ )
+ assert mounted.endpoint is sync_endpoint
+
+ with patch(
+ "local_deep_research.database.thread_local_session.cleanup_current_thread",
+ side_effect=lambda: cleanup_threads.append(threading.get_ident()),
+ ):
+ with TestClient(app) as client:
+ response = client.get("/sync")
+
+ assert response.status_code == 200
+ assert response.json() == {"ok": True}
+ assert endpoint_threads
+ assert cleanup_threads == endpoint_threads
+
+
+def test_production_app_wraps_every_sync_api_route():
+ """No module router or app-local endpoint can bypass worker cleanup."""
+ from local_deep_research.web.fastapi_app import app
+
+ sync_routes = [
+ route
+ for route in app.routes
+ if isinstance(route, APIRoute)
+ and not inspect.iscoroutinefunction(route.endpoint)
+ ]
+ missing = [
+ route.path
+ for route in sync_routes
+ if not getattr(
+ route.dependant.call, "__ldr_worker_thread_cleanup__", False
+ )
+ ]
+ identity_mismatches = [
+ route.path
+ for route in sync_routes
+ if getattr(route.dependant.call, "__wrapped__", None)
+ is not route.endpoint
+ ]
+
+ assert sync_routes, "production app unexpectedly has no synchronous routes"
+ assert missing == [], (
+ f"synchronous routes without owner-worker cleanup: {sorted(missing)}"
+ )
+ assert identity_mismatches == [], (
+ "cleanup dispatch wrappers no longer point at the registered endpoint: "
+ f"{sorted(identity_mismatches)}"
+ )
diff --git a/tests/web/routers/test_migration_antipattern_guards.py b/tests/web/routers/test_migration_antipattern_guards.py
index c69c16c06d..045938814c 100644
--- a/tests/web/routers/test_migration_antipattern_guards.py
+++ b/tests/web/routers/test_migration_antipattern_guards.py
@@ -137,9 +137,15 @@ def _is_streamingresponse_call(node: ast.AST) -> bool:
return False
func = node.func
if isinstance(func, ast.Name):
- return func.id == "StreamingResponse"
+ return func.id in {
+ "StreamingResponse",
+ "WorkerCleanupStreamingResponse",
+ }
if isinstance(func, ast.Attribute):
- return func.attr == "StreamingResponse"
+ return func.attr in {
+ "StreamingResponse",
+ "WorkerCleanupStreamingResponse",
+ }
return False
@@ -266,7 +272,7 @@ class TestStreamingBytesIOScannerSelfTest:
def test_flags_inline_bytesio(self):
tree = ast.parse(
"def route():\n"
- " return StreamingResponse(BytesIO(data), media_type='application/pdf')\n"
+ " return WorkerCleanupStreamingResponse(BytesIO(data), media_type='application/pdf')\n"
)
violations = find_streamingresponse_bytesio(tree)
assert len(violations) == 1
diff --git a/tests/web/routers/test_sse_response_headers.py b/tests/web/routers/test_sse_response_headers.py
index a2be60dfbd..e5a252dca5 100644
--- a/tests/web/routers/test_sse_response_headers.py
+++ b/tests/web/routers/test_sse_response_headers.py
@@ -43,6 +43,9 @@ from fastapi.testclient import TestClient
from starlette.middleware.sessions import SessionMiddleware
TEST_USER = "sse-header-tester"
+STREAMING_RESPONSE_NAMES = frozenset(
+ {"StreamingResponse", "WorkerCleanupStreamingResponse"}
+)
def _make_client(router):
@@ -228,7 +231,7 @@ def _sse_calls_missing_headers(path: Path):
continue
func = node.func
name = getattr(func, "id", None) or getattr(func, "attr", None)
- if name != "StreamingResponse":
+ if name not in STREAMING_RESPONSE_NAMES:
continue
is_sse = any(
kw.arg == "media_type"
diff --git a/tests/web/routers/test_streaming_contracts.py b/tests/web/routers/test_streaming_contracts.py
index 1d4d3ceaec..7dc576a860 100644
--- a/tests/web/routers/test_streaming_contracts.py
+++ b/tests/web/routers/test_streaming_contracts.py
@@ -317,6 +317,9 @@ class TestSessionAcrossYieldScannerSelfTest:
SSE_MEDIA_TYPE = "text/event-stream"
NDJSON_MEDIA_TYPE = "application/x-ndjson"
ALLOWED_STREAMING_MEDIA_TYPES = {SSE_MEDIA_TYPE, NDJSON_MEDIA_TYPE}
+STREAMING_RESPONSE_NAMES = frozenset(
+ {"StreamingResponse", "WorkerCleanupStreamingResponse"}
+)
def find_streamingresponse_media_types(tree: ast.AST):
@@ -326,7 +329,7 @@ def find_streamingresponse_media_types(tree: ast.AST):
not a string constant (e.g. computed)."""
results = []
for node in ast.walk(tree):
- if _call_target_name(node) != "StreamingResponse":
+ if _call_target_name(node) not in STREAMING_RESPONSE_NAMES:
continue
media_type_node = None
if len(node.args) >= 2:
@@ -402,7 +405,7 @@ class TestMediaTypeScannerSelfTest:
def test_recognises_sse_and_ndjson(self):
tree = ast.parse(
"def a():\n"
- " return StreamingResponse(g(), media_type='text/event-stream')\n"
+ " return WorkerCleanupStreamingResponse(g(), media_type='text/event-stream')\n"
"def b():\n"
" return StreamingResponse(g(), media_type='application/x-ndjson')\n"
)
diff --git a/tests/web/test_db_session_lifecycle_asgi.py b/tests/web/test_db_session_lifecycle_asgi.py
index 7f5d1a9030..fa8d7eb1a1 100644
--- a/tests/web/test_db_session_lifecycle_asgi.py
+++ b/tests/web/test_db_session_lifecycle_asgi.py
@@ -20,31 +20,33 @@ What each section establishes, and what breaks if it regresses:
nothing to scope one per thread. Losing it hands one ``Session`` to
two concurrent AnyIO workers: concurrent identity-map mutation.
-2. **Where the middleware's cleanup can actually reach.** Pinned by
- execution, not by reading the source: the cleanup demonstrably runs
- on the loop thread, demonstrably does not touch the worker's session,
- and the *same* cleanup call demonstrably does close it when it runs on
- the worker. That last step is the control — without it, "the session
- was not closed" would be equally consistent with cleanup being broken
- everywhere.
-
-3. **``run_db_sync`` is the only mechanism that does reach a worker.**
- Its ``finally`` runs *on* the worker, so it can close what the
- middleware cannot. Verified with real sessions and real pool
- accounting, against a bare ``asyncio.to_thread`` positive control on
- the same pinned worker thread.
-
-4. **Connections must come back to the pool.** A per-user engine is a
+2. **Where request cleanup runs.** ASGI middleware still tears down on the
+ loop thread, but every synchronous endpoint is wrapped by
+ ``WorkerCleanupAPIRoute``. Its ``finally`` runs on the handler worker and
+ closes that worker's thread-local sessions before the response returns.
+
+3. **Synchronous response bodies need a per-iteration boundary.** Starlette
+ consumes them on AnyIO workers only after the endpoint returns. The
+ production response wrapper cleans the worker after each iterator step;
+ the regression test first demonstrates the leak with Starlette's bare
+ response against the same real one-connection pool.
+
+4. **Explicit async offloads need the same boundary.** ``run_db_sync``'s
+ ``finally`` runs *on* the executor worker, so DB work launched from an
+ async endpoint receives the same guarantee as a sync route. Verified with
+ real sessions and pool accounting against a bare ``asyncio.to_thread``
+ positive control on the same pinned worker thread.
+
+5. **Connections must come back to the pool.** A per-user engine is a
``QueuePool(POOL_SIZE=20, MAX_OVERFLOW=40, pool_timeout=10)``. A
session that is never closed pins its connection for as long as
- something references the session — and under uvicorn the referencing
- thread lives for the process's lifetime.
+ something references the session. The request wrapper is what prevents
+ uvicorn's long-lived workers from retaining those references.
-5. **A measured defect in the cache itself.** See
- ``test_evicting_a_cached_session_closes_it`` (xfail, strict) and its
- companion pin: eviction from the ``LRUCache(maxsize=10)`` never closes
- the evicted ``Session``, so its pooled connection is released only by
- a generational GC pass.
+6. **LRU eviction while a session is live.** Eviction cannot close a session
+ because its caller may still be using it. ``get_db_session`` therefore
+ keeps an owner-thread registry outside the LRU, and worker cleanup closes
+ every acquired session even when its cache entry has already been evicted.
Everything here binds real production objects — the real
``thread_specific_cache``-decorated ``_get_cached_user_session``, the
@@ -75,11 +77,16 @@ from sqlalchemy import create_engine, text
from sqlalchemy.exc import TimeoutError as SATimeoutError
from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy.pool import QueuePool
+from starlette.responses import StreamingResponse
from local_deep_research.database import thread_local_session as tls
from local_deep_research.utilities import db_utils
from local_deep_research.utilities.request_context import request_user
-from local_deep_research.web.dependencies.threadpool import run_db_sync
+from local_deep_research.web.dependencies.threadpool import (
+ WorkerCleanupAPIRoute,
+ WorkerCleanupStreamingResponse,
+ run_db_sync,
+)
from local_deep_research.web.fastapi_app import DatabaseMiddleware
# Give-up deadline for every blocking rendezvous below. Never measured,
@@ -191,7 +198,7 @@ def _isolate_session_state():
def _reset():
db_utils._get_cached_user_session.cache_clear()
- tls.thread_session_manager.cleanup_thread()
+ tls.cleanup_current_thread()
with tls.thread_session_manager._lock:
tls.thread_session_manager._thread_credentials.clear()
gc.collect()
@@ -277,6 +284,7 @@ def server_sessions():
def _stack(handler, server_sessions, path="/probe"):
app = FastAPI()
+ app.router.route_class = WorkerCleanupAPIRoute
app.get(path)(handler)
return _SessionInjector(DatabaseMiddleware(app), server_sessions)
@@ -436,21 +444,16 @@ def test_one_worker_serving_two_users_never_reuses_the_first_session(
@pytest.mark.asyncio
-async def test_middleware_cleanup_runs_on_the_loop_not_the_handler_worker(
+async def test_sync_route_cleanup_runs_on_the_handler_worker(
server_sessions, monkeypatch
):
- """The structural consequence of the port, pinned by execution.
-
- Flask's ``teardown_appcontext`` ran on the request thread. This
- middleware's ``finally`` is ``async``, so it runs on the event-loop
- thread — and the sync handler ran on an AnyIO worker. One thread
- cannot reach another's ``threading.local()``, so the session the
- handler left behind survives the response.
-
- The control is the last step: the SAME ``cleanup_current_thread``
- call, dispatched onto the worker instead, does close it. Without
- that step "not closed" would be equally consistent with cleanup
- being broken outright, which would make this test worthless.
+ """The route wrapper restores same-thread request cleanup.
+
+ ``DatabaseMiddleware`` still cleans the event-loop thread, which cannot
+ reach a sync handler's ``threading.local``. ``WorkerCleanupAPIRoute`` adds
+ the missing cleanup on the handler worker. Both calls are observed so a
+ future refactor cannot accidentally move the only effective cleanup back
+ to the loop thread.
"""
leftover = MagicMock(name="session_opened_by_the_handler")
handler_thread = {}
@@ -485,50 +488,28 @@ async def test_middleware_cleanup_runs_on_the_loop_not_the_handler_worker(
assert handler_thread, "the handler never ran"
loop_thread = threading.get_ident()
- assert cleanup_threads == [loop_thread], (
- "DatabaseMiddleware's post-request cleanup must have run "
- f"exactly once, on the event-loop thread; saw "
- f"{cleanup_threads} (loop is {loop_thread})"
- )
assert handler_thread["ident"] != loop_thread, (
"premise: a sync `def` handler must be offloaded to an "
"AnyIO worker. If Starlette ever stopped offloading, this "
"whole hazard would disappear and this test must be "
"rewritten rather than deleted."
)
- assert leftover.close.call_count == 0, (
- "the middleware's cleanup reached the worker thread's "
- "session. That would be an improvement over the pinned "
- "behaviour, but ThreadLocalSessionManager's cross-user "
- "guard and run_db_sync's worker-side cleanup are both "
- "sized for this NOT happening — revisit them together."
+ assert cleanup_threads == [handler_thread["ident"], loop_thread], (
+ "expected owner-worker cleanup followed by middleware's "
+ f"loop-thread cleanup; saw {cleanup_threads}"
)
- assert leftover.rollback.call_count == 0, (
- "same claim from the other half of _cleanup_thread_session"
+ assert leftover.close.call_count == 1, (
+ "the synchronous endpoint returned without closing its "
+ "worker-owned session"
)
-
- # CONTROL: same call, dispatched onto the worker.
- await anyio.to_thread.run_sync(_spy)
-
- assert cleanup_threads[-1] == handler_thread["ident"], (
- "premise for the control: with the limiter pinned to one token "
- "the follow-up must land on the same worker that served the "
- f"request; it ran on {cleanup_threads[-1]}, handler was on "
- f"{handler_thread['ident']}"
- )
- assert leftover.close.call_count == 1, (
- "CONTROL FAILED: cleanup_current_thread does not close a session "
- "even when it runs ON the owning thread, so the assertion above "
- "was not evidence of unreachability."
- )
+ assert leftover.rollback.call_count == 1
@pytest.mark.asyncio
-async def test_the_next_request_on_that_worker_inherits_the_session(
- server_sessions, fake_db_manager
+async def test_the_next_request_on_that_worker_starts_without_a_session(
+ server_sessions, fake_db_manager, engines
):
- """What "not cleaned up" costs: the following request finds the
- previous request's session still attached to the worker.
+ """Consecutive requests on one worker do not retain a DB connection.
Two requests, one pinned worker, real ``ThreadLocalSessionManager``
and real sessions. Request 1 opens one; request 2 reports what it
@@ -565,8 +546,6 @@ async def test_the_next_request_on_that_worker_inherits_the_session(
with _pin_single_anyio_worker():
first = await _get(stack, "/probe", "alice")
second = await _get(stack, "/probe", "alice")
- # Leave no session on the shared AnyIO worker.
- await anyio.to_thread.run_sync(tls.cleanup_current_thread)
assert first.status_code == 200 and second.status_code == 200
assert len(observed) == 2
@@ -587,20 +566,110 @@ async def test_the_next_request_on_that_worker_inherits_the_session(
"premise: the worker must start this test with no session, "
"otherwise the second observation proves nothing"
)
- assert on_entry_two is not None, (
- "the second request found NO session on the worker, meaning "
- "something cleaned it up between requests. If that is now "
- "DatabaseMiddleware, the sibling test above must be updated "
- "too — and run_db_sync's worker-side cleanup revisited."
+ assert on_entry_two is None, (
+ "the second request inherited the first request's worker-local session"
)
- assert closes_on_entry_two == 0, (
- "the inherited session was still open — it is a live handle on "
- "the previous request's database connection, not a husk"
+ assert closes_on_entry_two is None
+ assert engines["alice"].pool.checkedout() == 0, (
+ "the request completed but its connection remained checked out"
)
# ---------------------------------------------------------------------------
-# 3. run_db_sync is the only thing that reaches a worker's session
+# 3. Synchronous stream bodies need an owner-worker cleanup per iterator step
+# ---------------------------------------------------------------------------
+
+
+async def test_stream_body_cleanup_runs_on_the_iteration_worker(
+ server_sessions, fake_db_manager, engines
+):
+ """A sync stream receives a cleanup boundary for every ``next()``.
+
+ A synchronous endpoint returns its ``StreamingResponse`` before Starlette
+ starts consuming the body. The endpoint cleanup therefore runs too early
+ to see a session opened by the body iterator. The raw response below is a
+ positive control reproducing that leak; the production response wrapper
+ must close the same real SQLAlchemy session and return its connection to
+ the real QueuePool before the completed response reaches the caller.
+ """
+ pool = engines["alice"].pool
+ manager = tls.thread_session_manager
+ body_threads: dict[str, int] = {}
+ opened: dict[str, _TrackingSession] = {}
+
+ def body(label):
+ body_threads[label] = threading.get_ident()
+ session = manager.get_session("alice", "pw")
+ assert isinstance(session, _TrackingSession)
+ opened[label] = session
+ session.execute(text("select 1"))
+ yield b"ok"
+
+ def raw_stream():
+ return StreamingResponse(body("raw"))
+
+ def protected_stream():
+ return WorkerCleanupStreamingResponse(body("protected"))
+
+ def peek():
+ return threading.get_ident(), manager.get_current_session()
+
+ with patch(
+ "local_deep_research.web.dependencies.auth.ensure_user_database",
+ lambda request: None,
+ ):
+ with _pin_single_anyio_worker():
+ raw_response = await _get(
+ _stack(raw_stream, server_sessions), "/probe", "alice"
+ )
+ raw_peek_thread, raw_seen = await anyio.to_thread.run_sync(peek)
+ raw_checked_out = pool.checkedout()
+
+ # Reset the positive control on its owning worker before running
+ # the protected half on that same deterministic worker.
+ await anyio.to_thread.run_sync(tls.cleanup_current_thread)
+
+ protected_response = await _get(
+ _stack(protected_stream, server_sessions),
+ "/probe",
+ "alice",
+ )
+ (
+ protected_peek_thread,
+ protected_seen,
+ ) = await anyio.to_thread.run_sync(peek)
+ protected_checked_out = pool.checkedout()
+
+ assert raw_response.status_code == 200
+ assert raw_response.content == b"ok"
+ assert raw_peek_thread == body_threads["raw"], (
+ "premise: the positive-control observation must reuse the worker "
+ "that advanced the raw stream"
+ )
+ assert raw_seen is opened["raw"]
+ assert raw_checked_out == 1, (
+ "positive control: a bare synchronous StreamingResponse body must "
+ "leave its connection checked out, or this test cannot detect the bug"
+ )
+
+ assert protected_response.status_code == 200
+ assert protected_response.content == b"ok"
+ assert protected_peek_thread == body_threads["protected"], (
+ "premise: the protected observation must reuse the worker that "
+ "advanced the stream"
+ )
+ assert protected_seen is None, (
+ "the next task inherited the completed stream's thread-local session"
+ )
+ assert opened["protected"].close_calls == 1
+ assert protected_checked_out == 0, (
+ "the stream completed but its connection remained checked out"
+ )
+
+
+# ---------------------------------------------------------------------------
+# 4. Explicit asyncio offloads use the same owner-worker cleanup
# ---------------------------------------------------------------------------
@@ -678,7 +747,7 @@ async def test_run_db_sync_closes_the_workers_session_and_frees_the_conn(
# ---------------------------------------------------------------------------
-# 4. Connections must come back to the pool
+# 5. Connections must come back to the pool
# ---------------------------------------------------------------------------
@@ -806,7 +875,7 @@ def test_cleanup_on_the_worker_returns_every_connection_to_the_pool(
# ---------------------------------------------------------------------------
-# 5. The session cache never closes what it evicts
+# 6. Owner tracking closes sessions that the LRU can no longer see
# ---------------------------------------------------------------------------
@@ -823,25 +892,13 @@ def _fill_cache(namespace_prefix, count):
return opened
- strict=True,
- reason=(
- "DEFECT: cachetools has no eviction callback and "
- "_get_cached_user_session does not add one, so the LRUCache "
- "drops a live Session without calling close(). The cache is the "
- "sole owner of that Session under ASGI — nothing else holds a "
- "reference — so eviction is the last moment its connection can "
- "be returned deliberately. Mechanism: "
- "utilities/db_utils.py::_get_cached_user_session's "
- "@thread_specific_cache(cache=LRUCache(maxsize=10)); "
- "cachetools.Cache.__setitem__ -> popitem() -> __delitem__."
- ),
-)
-def test_evicting_a_cached_session_closes_it(fake_db_manager):
- """An entry evicted from the session cache must be closed.
+def test_cache_eviction_does_not_close_a_potentially_active_session(
+ fake_db_manager,
+):
+ """Eviction detaches the cache entry but cannot end its caller's use.
- Asserted on ``close()`` rather than on pool counters so the result
- does not depend on garbage-collector timing.
+ The owner-thread registry tested below, rather than an unsafe cross-thread
+ eviction callback, closes it at the worker boundary.
"""
cache = db_utils._get_cached_user_session.cache
maxsize = cache.maxsize
@@ -851,11 +908,7 @@ def test_evicting_a_cached_session_closes_it(fake_db_manager):
evicted = opened[0]
assert evicted is not opened[-1], "premise: distinct sessions"
try:
- assert evicted.close_calls == 1, (
- "the session evicted from the cache was never closed; its "
- "pooled connection is released only if and when the garbage "
- "collector reclaims it"
- )
+ assert evicted.close_calls == 0
finally:
for session in opened:
session.close()
@@ -864,8 +917,7 @@ def test_evicting_a_cached_session_closes_it(fake_db_manager):
def test_cached_sessions_pin_connections_until_the_collector_runs(
fake_db_manager, engines
):
- """FINDING, pinned: the connections behind evicted cache entries come
- back only via a generational GC pass.
+ """Mechanism control: the bare private cache cannot reclaim evictions.
An evicted ``Session`` is unreachable but sits in a reference cycle,
so CPython's refcounting never frees it; the pooled connection stays
@@ -873,15 +925,10 @@ def test_cached_sessions_pin_connections_until_the_collector_runs(
disabled the count climbs past what the cache can even hold, and
``gc.collect()`` is what brings it down to ``maxsize``.
- This is the mechanism behind the reported exhaustion under a client
- that gives every request a fresh thread: each new thread is a new
- cache key, so every request opens a session, and nothing on the
- request path ever closes one. ``SettingsManager.close()`` would —
- but it is only reachable via ``owns_session=True`` and no caller in
- the web layer ever calls it.
-
- Asserts nothing about which behaviour is correct; it exists so the
- gap cannot be closed or widened silently.
+ Production calls use ``get_db_session`` rather than this private helper;
+ the paired test below proves its owner registry closes all of these at
+ the worker boundary. Keeping this control demonstrates why the registry
+ is necessary even though the LRU itself contains only ``maxsize`` entries.
"""
pool = engines["alice"].pool
cache = db_utils._get_cached_user_session.cache
@@ -901,12 +948,10 @@ def test_cached_sessions_pin_connections_until_the_collector_runs(
f"holding {len(cache)}"
)
assert held_without_gc == total, (
- "FINDING CHANGED: with the collector off, every session ever "
+ "with the collector off, every session ever "
"created should still hold its connection — including the "
f"{total - maxsize} the cache already evicted. Expected "
- f"{total} checked out, saw {held_without_gc}. If eviction "
- "now closes sessions, delete this test and flip the strict "
- "xfail above."
+ f"{total} checked out, saw {held_without_gc}"
)
gc.collect()
assert pool.checkedout() == maxsize, (
@@ -918,3 +963,46 @@ def test_cached_sessions_pin_connections_until_the_collector_runs(
if gc_was_enabled:
gc.enable()
gc.collect()
+
+
+def test_worker_cleanup_closes_even_sessions_evicted_from_the_cache(
+ fake_db_manager, engines
+):
+ """The public accessor tracks sessions beyond the LRU's reach.
+
+ More namespaces than the cache can hold forces eviction. At the worker
+ boundary every acquired session must still be closed without relying on
+ garbage collection, otherwise a burst can exhaust the production pool
+ before the collector runs.
+ """
+ pool = engines["alice"].pool
+ cache = db_utils._get_cached_user_session.cache
+ total = cache.maxsize + 5
+ prefix = uuid.uuid4().hex
+
+ gc_was_enabled = gc.isenabled()
+ gc.disable()
+ try:
+ sessions = [
+ db_utils.get_db_session(f"{prefix}{index}", username="alice")
+ for index in range(total)
+ ]
+ for session in sessions:
+ session.execute(text("select 1"))
+
+ assert pool.checkedout() == total, "premise: every session checked out"
+ closed = db_utils.cleanup_cached_user_sessions_current_thread()
+
+ assert closed == total
+ assert all(session.close_calls == 1 for session in sessions)
+ assert pool.checkedout() == 0
+ assert not [
+ key
+ for key in cache
+ if key[0]
+ == getattr(db_utils.g_thread_local_store, "thread_id", None)
+ ]
+ finally:
+ if gc_was_enabled:
+ gc.enable()
+ gc.collect()