Skip to content

ASGI: a pipelined HTTP/1.1 request under uvicorn runs in the previous request's isolation scope #8271

Open

Description

@ddelange

How do you use Sentry?

Sentry Saas (sentry.io)

Version

2.75.0 (also 2.0.0)

Steps to Reproduce

Two HTTP/1.1 requests pipelined on one connection to an app wrapped in SentryAsgiMiddleware, served by uvicorn.
Request /a sets a user and a tag, both requests capture a message.
The script below exits 1 when the leak happens.

#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = ["sentry-sdk", "uvicorn[standard]"]
# ///
"""A pipelined HTTP/1.1 request runs in the previous request's Sentry isolation scope under uvicorn.

    ./repro.py [httptools|h11] [--reset-contextvars]

Exits 1 when request 2's event carries request 1's user or tag, or request 2 gets no transaction.
"""
import socket
import sys
import threading
import time

import sentry_sdk
import uvicorn
from sentry_sdk.integrations.asgi import SentryAsgiMiddleware

events, transactions = [], []
sentry_sdk.init(
    dsn="http://public@127.0.0.1:9/1",  # never reached: both hooks drop what they collect
    traces_sample_rate=1.0,
    before_send=lambda event, hint: events.append(event),
    before_send_transaction=lambda event, hint: transactions.append(event),
)


async def app(scope, receive, send):
    if scope["path"] == "/a":
        sentry_sdk.set_user({"id": "user-a"})
        sentry_sdk.set_tag("request", "a")
    sentry_sdk.capture_message(f"hello from {scope['path']}")
    await send({"type": "http.response.start", "status": 200, "headers": [(b"content-length", b"2")]})
    await send({"type": "http.response.body", "body": b"ok"})


parser = next((a for a in sys.argv[1:] if not a.startswith("-")), "httptools")
options = {"reset_contextvars": True} if "--reset-contextvars" in sys.argv else {}
server = uvicorn.Server(uvicorn.Config(SentryAsgiMiddleware(app), http=parser, lifespan="off", log_level="warning", **options))
sock = socket.socket()
sock.bind(("127.0.0.1", 0))
thread = threading.Thread(target=server.run, kwargs={"sockets": [sock]}, daemon=True)
thread.start()
while not server.started:
    assert thread.is_alive(), "uvicorn exited before it started"
    time.sleep(0.01)

with socket.create_connection(sock.getsockname(), timeout=10) as client:
    # Both requests in one write: uvicorn queues /b and starts it when /a's response completes.
    client.sendall(b"GET /a HTTP/1.1\r\nHost: x\r\n\r\nGET /b HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n")
    while client.recv(65536):
        pass
server.should_exit = True
thread.join(timeout=10)

print(f"sentry-sdk {sentry_sdk.VERSION}, uvicorn {uvicorn.__version__}, {parser}, {options or 'default context'}")
for event in events:
    trace = event.get("contexts", {}).get("trace", {})
    print(f"  {event['message']}: user={event.get('user')} tags={event.get('tags')} url={event.get('request', {}).get('url')} transaction={event.get('transaction')} trace_id={trace.get('trace_id')}")
print(f"  transactions: {[t.get('transaction') for t in transactions]}")
b = next(e for e in events if e["message"] == "hello from /b")
leaked = "user" in b or "request" in b.get("tags", {}) or len(transactions) != 2
print("  LEAK: /b ran in /a's isolation scope" if leaked else "  CLEAN")
sys.exit(int(leaked))

./repro.py httptools (uvicorn's default parser when uvicorn[standard] is installed), Python 3.14.6:

sentry-sdk uvicorn parser result
2.75.0 0.54.0 httptools leaks
2.75.0 0.54.0 h11 leaks
2.75.0 0.42.0 httptools leaks
2.75.0 0.42.0 h11 clean
2.0.0 0.54.0 httptools leaks
2.75.0 0.54.0 --reset-contextvars both clean

Expected Result

The event from /b has no user, no request tag, the request url /b, and its own transaction and trace id.
Two transactions are sent.

Actual Result

sentry-sdk 2.75.0, uvicorn 0.54.0, httptools, default context
  hello from /a: user={'id': 'user-a'} tags={'request': 'a'} url=http://x/a transaction=http://127.0.0.1:56310/a trace_id=5bc07f4b...
  hello from /b: user={'id': 'user-a'} tags={'request': 'a'} url=http://x/a transaction=http://127.0.0.1:56310/a trace_id=5bc07f4b...
  transactions: ['http://127.0.0.1:56310/a']

The event from /b carries /a's user, tags, request data, transaction and trace id, and /b gets no transaction.
In production this attributes one user's errors and breadcrumbs to another user's request.

Mechanism

uvicorn starts a queued pipelined request from on_response_complete(), which the finished request's final send() calls inside that request's task (uvicorn/protocols/http/httptools_impl.py:561 and :341, h11_impl.py on_response_complete via handle_events()), so loop.create_task() copies request 1's context into request 2's task.
That context still holds _asgi_middleware_applied = True (sentry_sdk/integrations/asgi.py:227), because the finally at asgi.py:438 runs only after that send() returns.
Request 2 therefore takes the recursive path at asgi.py:200 to :207: no isolation_scope(), no event processor for its own ASGI scope, no transaction, and everything it captures goes to request 1's isolation scope.

uvicorn's side is tracked in Kludex/uvicorn#3170 (open) and Kludex/uvicorn#3158.
Even with uvicorn fixed, the SDK turns any inherited context into a silently uninstrumented request.
A guard keyed on the request, for example the ASGI scope dict the outer middleware saw, or a request id stored in the contextvar and compared against scope, would start a new isolation scope and transaction for request 2.
Note that sentry_sdk.isolation_scope() forks the current isolation scope (sentry_sdk/scope.py:2185), so request 2 would still inherit request 1's user and tags from the leaked context; the outermost ASGI middleware may need to fork from a clean isolation scope instead.

Workaround: run uvicorn 0.45.0 or later with --reset-contextvars (Config(reset_contextvars=True)), which starts each request task from an empty context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions