fix(fastapi): preserve OTel context from sync route handlers to BackgroundTasks (#3586)#4724
Open
rajdhruvsingh wants to merge 1 commit into
Open
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Fixes the context propagation asymmetry described in #3586: when a synchronous
FastAPI route handler attaches a value to the OpenTelemetry context (e.g. via
context.attach(set_value(...))) and then schedules aBackgroundTaskstask,that value was silently lost by the time the background task ran. The same
code in an async route handler worked correctly.
Root cause
Sync route handlers run inside a worker thread via
anyio.to_thread.run_sync(used internally by Starlette/FastAPI). This copies the current context into
the thread, but does not propagate any mutations made inside that thread back
out once it returns. By the time
BackgroundTasks.__call__executes, thecontext is already back to its pre-handler state — the mutation is gone before
this instrumentation's existing
BackgroundTask.__call__hook (added for#4251, background-task span parenting) ever runs, so there's no way to recover
it after the fact.
Fix
BackgroundTasks.add_taskis patched to snapshot the current OpenTelemetrycontext at the moment a task is scheduled (this happens inside the same
thread as the route handler, so it sees the mutated context). When the task
actually executes, that captured context is merged into the then-current
ambient context — keys already present in the ambient context (notably the
BackgroundTask span this instrumentation starts around each task, from
#4251) take precedence, so existing span-parenting behavior is unaffected.
Only context set during the route handler that would otherwise be lost is
backfilled.
This works identically for sync and async background task functions.
Fixes #3586
Type of change
How Has This Been Tested?
Added
test_background_task_inherits_sync_route_context: reproduces theexact repro from FastAPI: Context change in sync route does not appear in background tasks #3586 (sync and async routes, each attaching a context
value before scheduling a background task) and asserts both now see the
value, where previously only the async case did.
Added
test_background_task_context_does_not_clobber_span_parenting: async-route variant of the existing [fastapi] BackgroundTasks produce child spans that outlive their closed parent span #4251 regression test, confirming the
preserved context does not override the dedicated
BackgroundTaskspan orits parent/child span relationships.
Verified against the original issue's exact reproduction script
(TestClient, sync and async endpoints) with the fix applied (both pass)
and with the fix reverted via
git stash(sync fails exactly as reportedin the issue, async still passes) — confirming the fix addresses the real
reported behavior rather than an artifact of the new tests.
Full existing test suite for
opentelemetry-instrumentation-fastapirunlocally: 101 passed, 6 skipped, 0 failures (2 unrelated pre-existing
tests deselected —
test_entry_point_existsandtest_instruments_with_fastapi_installed, which fail in any local dev.venvwith multiple instrumentation packages installed, due toentry_points(group="opentelemetry_instrumentor")returning everyregistered instrumentor rather than just this one; this is a known
environment-isolation issue unrelated to this change and not present
under the project's isolated
toxCI environments).pytest instrumentation/opentelemetry-instrumentation-fastapi/tests/Does This PR Require a Core Repo Change?
Checklist:
See contributing.md for styleguide, changelog guidelines, and more.