docs: clarify BaseHTTPMiddleware impact on contextvars for subsequent middleware - #2943
Merged
Merged
Conversation
Kludex
approved these changes
Sep 6, 2025
Kludex
enabled auto-merge (squash)
September 6, 2025 10:41
Owner
|
Thanks! |
exa160
added a commit
to exa160/yande.re-spider
that referenced
this pull request
Jun 10, 2026
…itting
## Root cause (two bugs, not one)
### Bug 1: BaseHTTPMiddleware cross-task ContextVar
BaseHTTPMiddleware.dispatch() uses anyio.create_task_group() to run
endpoints in a new asyncio task. ContextVars do NOT propagate across
asyncio task boundaries (Python language guarantee). Symptom:
endpoint's _request_session.get() returned None (cross-task default).
### Bug 2 (the real culprit): BaseDAO.session caches the first session
Even after fixing Bug 1, POSTs would commit only the FIRST request's
data and silently fail on subsequent requests. The cause: favorite_dao
is a module-level singleton. First call to .session property stored
the result in self._session permanently. Next request:
- dispatch creates new session B, sets ContextVar to B
- favorite_dao.session returns cached A (now closed)
- INSERT into closed A: silently lost
This is also why v1.1.1's 'with FavoriteDao() as dao:' pattern worked
for scheduler tasks (DAO created fresh each call) but NOT for HTTP
endpoints (singletons used directly).
## Fixes
1. middleware/session.py: Pure ASGI middleware (not BaseHTTPMiddleware)
- Direct await self.app(scope, receive, send): no task spawn
- ContextVar propagates correctly within same task
- get_session() in strict mode: RuntimeError instead of silent
fallback (catches future ContextVar regressions immediately)
- API-compatible: init_app / get_session / remove_session unchanged
- src/__init__.py and DAO callers untouched
2. dao/database.py: BaseDAO.session refetches ContextVar per call
- Single-instance path: always read fresh from ContextVar
- No more stale closed session across requests
- Explicit construction (with FavoriteDao(s) as dao:) preserved
## Verified
- 6 consecutive POSTs all land in DB (count 8 -> 14, fix3-1..6)
- 8 endpoints e2e (4x 200 OK, 4x pre-existing 404/405 unrelated)
- 0 zombie transactions after restart + 6 POSTs
- Lifespan starts cleanly (Loaded 0 scheduled folders from DB)
- get_session() strict mode: no false positive in lifespan (uses with)
## Series
- v1.1.1: zombie stale read (BaseDAO.owns_session + with scheduler)
- v1.1.2: JSON storage (native MariaDB JSON column)
- v1.1.3: zombie write (Pure ASGI + DAO refetch) -- root cause
Refs: https://starlette.dev/middleware/ (BaseHTTPMiddleware limitations)
Refs: Kludex/starlette#1678
Refs: Kludex/starlette#2943
Refs: Kludex/starlette#2160
6 tasks
exa160
added a commit
to exa160/yande.re-spider
that referenced
this pull request
Aug 24, 2026
…itting
## Root cause (two bugs, not one)
### Bug 1: BaseHTTPMiddleware cross-task ContextVar
BaseHTTPMiddleware.dispatch() uses anyio.create_task_group() to run
endpoints in a new asyncio task. ContextVars do NOT propagate across
asyncio task boundaries (Python language guarantee). Symptom:
endpoint's _request_session.get() returned None (cross-task default).
### Bug 2 (the real culprit): BaseDAO.session caches the first session
Even after fixing Bug 1, POSTs would commit only the FIRST request's
data and silently fail on subsequent requests. The cause: favorite_dao
is a module-level singleton. First call to .session property stored
the result in self._session permanently. Next request:
- dispatch creates new session B, sets ContextVar to B
- favorite_dao.session returns cached A (now closed)
- INSERT into closed A: silently lost
This is also why v1.1.1's 'with FavoriteDao() as dao:' pattern worked
for scheduler tasks (DAO created fresh each call) but NOT for HTTP
endpoints (singletons used directly).
## Fixes
1. middleware/session.py: Pure ASGI middleware (not BaseHTTPMiddleware)
- Direct await self.app(scope, receive, send): no task spawn
- ContextVar propagates correctly within same task
- get_session() in strict mode: RuntimeError instead of silent
fallback (catches future ContextVar regressions immediately)
- API-compatible: init_app / get_session / remove_session unchanged
- src/__init__.py and DAO callers untouched
2. dao/database.py: BaseDAO.session refetches ContextVar per call
- Single-instance path: always read fresh from ContextVar
- No more stale closed session across requests
- Explicit construction (with FavoriteDao(s) as dao:) preserved
## Verified
- 6 consecutive POSTs all land in DB (count 8 -> 14, fix3-1..6)
- 8 endpoints e2e (4x 200 OK, 4x pre-existing 404/405 unrelated)
- 0 zombie transactions after restart + 6 POSTs
- Lifespan starts cleanly (Loaded 0 scheduled folders from DB)
- get_session() strict mode: no false positive in lifespan (uses with)
## Series
- v1.1.1: zombie stale read (BaseDAO.owns_session + with scheduler)
- v1.1.2: JSON storage (native MariaDB JSON column)
- v1.1.3: zombie write (Pure ASGI + DAO refetch) -- root cause
Refs: https://starlette.dev/middleware/ (BaseHTTPMiddleware limitations)
Refs: Kludex/starlette#1678
Refs: Kludex/starlette#2943
Refs: Kludex/starlette#2160
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This PR updates the documentation for BaseHTTPMiddleware to clarify an important limitation regarding contextvars propagation.
The "Limitations" section previously noted that BaseHTTPMiddleware prevents contextvars changes from propagating upwards. This change adds a crucial detail: if a BaseHTTPMiddleware is positioned earlier in the middleware stack, it will also disrupt contextvars propagation for any subsequent Pure ASGI Middleware that relies on them.
This clarification helps users understand a potential pitfall when mixing BaseHTTPMiddleware and Pure ASGI Middleware, ensuring they design their middleware stack appropriately for contextvars to function as expected.
Example
If you run this app and curl localhost:8000, you can see that everything happens as described in the documentation:
But if you swap BadMiddleware and ShinyMiddleware, you will get unexpected (?) behavior:
Checklist