ContextVars pollution when uvicorn installed without [standard] extensions #2044
Replies: 3 comments 3 replies
-
Can you try only with unicorn and uvloop? Can you try other python versions? I don't know why this is happening, I'll check tomorrow. |
Beta Was this translation helpful? Give feedback.
-
Hey! I've stumbled upon this issue as well. We're also using uvicorn with builtin asyncio (not uvloop) on python 3.10, and this have caused issues with opentelemetry tracing. def fix_contextvars_leak(app: ASGI3Application) -> ASGI3Application:
async def wrapped_app(
scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable
) -> None:
coro = app(scope, receive, send)
return await Context().run(asyncio.create_task, coro) # type: ignore
return wrapped_app Unfortunately I believe that it might be a good idea to start with a fresh context when uvicorn is creating tasks in uvicorn/uvicorn/protocols/http/h11_impl.py Line 255 in e2a3979 I'm not quite sure how the leakage happens but I suspect that sharing a single connection (and thus a single parent task handling the connection) is involved somehow and contextvar state from the child per-request task is propagated to the parent task when interacting (send/receive). Is there any way I could assist in resolving this? |
Beta Was this translation helpful? Give feedback.
-
Created #2167. |
Beta Was this translation helpful? Give feedback.
-
Hi team, we have discovered a weird ContextVars behaviour when uvicorn being installed without [standard] extensions.
Can you please take a look - should this be considered as a bug or maybe you can help to explain why it happens?
Summary
Workarounds
uvicorn[standard]
instead of plainuvicorn
(seems to be a good option)scope
to store request-bound data (not always possible: for example opentelemetry cloud tracing middleware stores current trace span inside context var and this logic cannot be changed)Steps to reproduce
Hardware/OS/tools
Prepare environment
Prepare test scripts - create following files:
client.py
server.py
Executing test
Expected behaviour
Actual behaviour
Notes
uvicorn[standard]
- maybe it's happening because standard edition utilisesuvloop
?Beta Was this translation helpful? Give feedback.
All reactions