Skip to content

Fix Django span finalization for StreamingHttpResponse - #4919

Open
saisharan0103 wants to merge 1 commit into
open-telemetry:mainfrom
saisharan0103:mergepath/issue-4681-django-instrumentation-spans-close-prema
Open

Fix Django span finalization for StreamingHttpResponse#4919
saisharan0103 wants to merge 1 commit into
open-telemetry:mainfrom
saisharan0103:mergepath/issue-4681-django-instrumentation-spans-close-prema

Conversation

@saisharan0103

Copy link
Copy Markdown

Fixes #4681.

The Django middleware currently starts the server span in process_request with a use_span activation that ends on exit, then exits that activation in process_response. For StreamingHttpResponse, process_response runs before Django consumes the response iterator, and Django only calls response.close() after streaming finishes. That causes the span end time, request duration metrics, and active request decrement to be recorded before the actual response lifecycle is complete.

This changes the middleware so process_response detaches the span context without ending the span there. It wraps response.close so the original close always runs first, then OpenTelemetry finalization runs in a finally block after the response is closed. The existing duration metric recording, active request decrement, and span.end() call now live in a small once-only finalizer used by the close wrapper.

process_response still handles response attributes, propagator injection, hooks, and exception recording.

Regression coverage adds streaming response views and tests for WSGI and ASGI middleware paths. The tests assert that no server span is exported until the streaming response is consumed and closed, then assert the exported span has the expected HTTP attributes.

ruff check instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/middleware/otel_middleware.py instrumentation/opentelemetry-instrumentation-django/tests/test_middleware.py instrumentation/opentelemetry-instrumentation-django/tests/test_middleware_asgi.py instrumentation/opentelemetry-instrumentation-django/tests/views.py reports no new findings on the changed files.
Ran pytest -x locally with no new failures.

@linux-foundation-easycla

Copy link
Copy Markdown

CLA Missing ID

  • ❌ The email address for the commit (d241940) is not linked to the GitHub account, preventing the EasyCLA check. Consult this Help Article and GitHub Help to resolve. (To view the commit's email address, add .patch at the end of this PR page's URL.) For further assistance with EasyCLA, please visit our EasyCLA portal and chat with our support bot.

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

Labels

None yet

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

Django Instrumentation: Spans close prematurely for StreamingHttpResponse

1 participant