From ac5de729c94fbeaab550e116d7b4c4b313887504 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 | 49 +++++++++++-- tests/integrations/asgi/test_asgi.py | 106 +++++++++++++++++++++++++++ 2 files changed, 150 insertions(+), 5 deletions(-) diff --git a/sentry_sdk/integrations/asgi.py b/sentry_sdk/integrations/asgi.py index b1ef63ff84..4b8b0d7b27 100644 --- a/sentry_sdk/integrations/asgi.py +++ b/sentry_sdk/integrations/asgi.py @@ -25,7 +25,12 @@ from sentry_sdk.integrations._wsgi_common import ( DEFAULT_HTTP_METHODS_TO_CAPTURE, ) -from sentry_sdk.scope import Scope, should_send_default_pii +from sentry_sdk.scope import ( + Scope, + should_send_default_pii, + use_isolation_scope, + use_scope, +) from sentry_sdk.sessions import track_session from sentry_sdk.traces import ( SOURCE_FOR_STYLE as SEGMENT_SOURCE_FOR_STYLE, @@ -63,6 +68,15 @@ from sentry_sdk.tracing import Span +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("sentry_asgi_middleware_applied") _DEFAULT_TRANSACTION_NAME = "generic ASGI request" @@ -197,7 +211,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: @@ -224,9 +244,21 @@ async def _run_app( client = sentry_sdk.get_client() span_streaming = has_span_streaming_enabled(client.options) - _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" @@ -383,6 +415,13 @@ async def _sentry_wrapped_send( else: span.set_http_status(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: @@ -435,7 +474,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 f15a7ec36a..5eda428d06 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 @@ -1576,3 +1577,108 @@ 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_events +): + """ + 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) + events = capture_events() + 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}) + 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) + + 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] + ) + + transactions = {e["transaction"]: e for e in events if e["type"] == "transaction"} + assert set(transactions) == {"http://localhost/first", "http://localhost/second"} + assert transactions["http://localhost/first"]["tags"]["path"] == "/first" + assert transactions["http://localhost/second"]["tags"]["path"] == "/second" + assert transactions["http://localhost/second"]["user"] == {"id": "/second"} + assert ( + transactions["http://localhost/first"]["contexts"]["trace"]["trace_id"] + != transactions["http://localhost/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_transaction( + sentry_init, capture_events +): + sentry_init(traces_sample_rate=1.0) + events = capture_events() + + async def app(scope, receive, send): + sentry_sdk.set_tag("inner", "1") + 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) + + (transaction,) = [e for e in events if e["type"] == "transaction"] + assert transaction["tags"]["inner"] == "1"