From d95294f4058e6f248236e5844d5a616995c227cd Mon Sep 17 00:00:00 2001 From: TejasLamba2006 Date: Wed, 18 Nov 2026 10:08:47 +0530 Subject: [PATCH] fix(asgi): Isolate pipelined requests from the previous request's scope uvicorn starts the next pipelined request's task from inside the final send() of the previous one, so the new task inherited a context in which the previous request was still marked as active. The middleware then took the nested fast path and skipped creating an isolation scope and a transaction, and anything it did run in the previous request's scopes. Track a per-request state in the context variable that is flagged once the final response body has been sent. A middleware that finds a completed request's state starts a fresh request from the scopes the previous request started from. Nested middleware inside an in-flight request still takes the fast path. Fixes #8271 --- sentry_sdk/integrations/asgi.py | 46 ++++++++-- tests/integrations/asgi/test_asgi.py | 123 +++++++++++++++++++++++++++ 2 files changed, 163 insertions(+), 6 deletions(-) diff --git a/sentry_sdk/integrations/asgi.py b/sentry_sdk/integrations/asgi.py index 5b07b43087..5c4993ff2a 100644 --- a/sentry_sdk/integrations/asgi.py +++ b/sentry_sdk/integrations/asgi.py @@ -26,7 +26,7 @@ from sentry_sdk.integrations._wsgi_common import ( DEFAULT_HTTP_METHODS_TO_CAPTURE, ) -from sentry_sdk.scope import Scope +from sentry_sdk.scope import Scope, use_isolation_scope, use_scope from sentry_sdk.sessions import track_session from sentry_sdk.traces import ( SegmentNameSource, @@ -47,7 +47,16 @@ from sentry_sdk._types import Attributes, Event, Hint -_asgi_middleware_applied: "ContextVar[bool]" = ContextVar( +class _RequestState: + __slots__ = ("parent_scope", "parent_isolation_scope", "response_complete") + + def __init__(self, parent_scope: "Scope", parent_isolation_scope: "Scope") -> None: + self.parent_scope = parent_scope + self.parent_isolation_scope = parent_isolation_scope + self.response_complete = False + + +_asgi_middleware_applied: "ContextVar[_RequestState]" = ContextVar( "sentry_asgi_middleware_applied" ) @@ -162,7 +171,13 @@ async def _run_asgi3(self, scope: "Any", receive: "Any", send: "Any") -> "Any": async def _run_app( self, scope: "Any", receive: "Any", send: "Any", asgi_version: int ) -> "Any": - is_recursive_asgi_middleware = _asgi_middleware_applied.get(False) + request_state = _asgi_middleware_applied.get(None) + # A server can start the next pipelined request's task from inside the + # final `send()` of the previous one, so that task inherits a context + # in which the previous request is still marked as active. + is_recursive_asgi_middleware = ( + request_state is not None and not request_state.response_complete + ) is_lifespan = scope["type"] == "lifespan" if is_recursive_asgi_middleware or is_lifespan: try: @@ -177,9 +192,21 @@ async def _run_app( self._capture_lifespan_exception(exc) reraise(*exc_info) - _asgi_middleware_applied.set(True) + if request_state is not None: + # Pipelined sibling request: start from the scopes the previous + # request itself started from, not from the previous request's. + parent_scope = request_state.parent_scope + parent_isolation_scope = request_state.parent_isolation_scope + else: + parent_scope = Scope.get_current_scope() + parent_isolation_scope = Scope.get_isolation_scope() + + request_state = _RequestState(parent_scope, parent_isolation_scope) + token = _asgi_middleware_applied.set(request_state) try: - with sentry_sdk.isolation_scope() as sentry_scope: + with use_scope(parent_scope), use_isolation_scope( + parent_isolation_scope + ), sentry_sdk.isolation_scope() as sentry_scope: with track_session(sentry_scope, session_mode="request"): sentry_scope.clear_breadcrumbs() sentry_scope._name = "asgi" @@ -280,6 +307,13 @@ async def _sentry_wrapped_send( event["status"], ) + if event.get( + "type" + ) == "http.response.body" and not event.get( + "more_body" + ): + request_state.response_complete = True + return await send(event) if asgi_version == 2: @@ -321,7 +355,7 @@ async def _sentry_wrapped_send( "sentry.segment.name.source", source ) finally: - _asgi_middleware_applied.set(False) + _asgi_middleware_applied.reset(token) def event_processor( self, event: "Event", hint: "Hint", asgi_scope: "Any" diff --git a/tests/integrations/asgi/test_asgi.py b/tests/integrations/asgi/test_asgi.py index c00a1db15e..1c0e5343fa 100644 --- a/tests/integrations/asgi/test_asgi.py +++ b/tests/integrations/asgi/test_asgi.py @@ -1,3 +1,4 @@ +import asyncio from collections import Counter import pytest @@ -1136,3 +1137,125 @@ async def test_user_agent_original_attribute( assert server_span["attributes"]["user_agent.original"] == "TestBrowser/1.0" assert child_span["attributes"]["user_agent.original"] == "TestBrowser/1.0" + + +def _request_scope(path): + return { + "type": "http", + "method": "GET", + "path": path, + "headers": [], + "query_string": b"", + "server": ("localhost", 80), + "client": ("127.0.0.1", 1234), + } + + +async def _noop_receive(): + return {"type": "http.request", "body": b"", "more_body": False} + + +@pytest.mark.asyncio +async def test_pipelined_request_does_not_inherit_previous_request_scope( + sentry_init, capture_items +): + """ + uvicorn starts the next pipelined request's task from inside the final + `send()` of the previous one, so the new task copies a context in which the + previous request is still active. + """ + sentry_init(traces_sample_rate=1.0) + items = capture_items("event", "span") + sentry_sdk.set_tag("boot", "1") + + seen_on_entry = {} + tasks = [] + + async def app(scope, receive, send): + path = scope["path"] + isolation_scope = sentry_sdk.get_isolation_scope() + seen_on_entry[path] = { + "tags": dict(isolation_scope._tags), + "user": isolation_scope._user, + "trace_id": isolation_scope.get_traceparent(), + } + sentry_sdk.set_tag("path", path) + sentry_sdk.set_user({"id": path}) + capture_message(path) + await send({"type": "http.response.start", "status": 200, "headers": []}) + await send({"type": "http.response.body", "body": b"ok"}) + + middleware = SentryAsgiMiddleware(app) + + async def send(event): + if event["type"] == "http.response.body" and not tasks: + # what uvicorn's on_response_complete() does for a pipelined request + tasks.append( + asyncio.create_task( + middleware(_request_scope("/second"), _noop_receive, _discard_send) + ) + ) + + async def _discard_send(event): + pass + + await middleware(_request_scope("/first"), _noop_receive, send) + await asyncio.gather(*tasks) + sentry_sdk.flush() + + assert seen_on_entry["/second"]["tags"] == {"boot": "1"} + assert seen_on_entry["/second"]["user"] is None + assert ( + seen_on_entry["/second"]["trace_id"].split("-")[0] + != seen_on_entry["/first"]["trace_id"].split("-")[0] + ) + + spans = { + item.payload["name"]: item.payload for item in items if item.type == "span" + } + assert set(spans) == {"http://localhost/first", "http://localhost/second"} + assert ( + spans["http://localhost/first"]["trace_id"] + != spans["http://localhost/second"]["trace_id"] + ) + + events = { + item.payload["message"]: item.payload for item in items if item.type == "event" + } + assert set(events) == {"/first", "/second"} + assert events["/first"]["tags"]["path"] == "/first" + assert events["/second"]["tags"]["path"] == "/second" + assert events["/second"]["user"] == {"id": "/second"} + assert ( + events["/first"]["contexts"]["trace"]["trace_id"] + != events["/second"]["contexts"]["trace"]["trace_id"] + ) + assert sentry_sdk.get_isolation_scope()._tags == {"boot": "1"} + + +@pytest.mark.asyncio +async def test_nested_middleware_in_same_request_creates_one_segment( + sentry_init, capture_items +): + sentry_init(traces_sample_rate=1.0) + items = capture_items("event", "span") + + async def app(scope, receive, send): + sentry_sdk.set_tag("inner", "1") + capture_message("nested") + await send({"type": "http.response.start", "status": 200, "headers": []}) + await send({"type": "http.response.body", "body": b"ok"}) + + async def discard(event): + pass + + inner = SentryAsgiMiddleware(app) + outer = SentryAsgiMiddleware(inner) + + await outer(_request_scope("/nested"), _noop_receive, discard) + sentry_sdk.flush() + + (span,) = [item.payload for item in items if item.type == "span"] + assert span["name"] == "http://localhost/nested" + (event,) = [item.payload for item in items if item.type == "event"] + assert event["tags"]["inner"] == "1"