Fix spurious "Failed to detach context" error on Execution API disconnects#68039
Open
dheerajturaga wants to merge 1 commit into
Open
Fix spurious "Failed to detach context" error on Execution API disconnects#68039dheerajturaga wants to merge 1 commit into
dheerajturaga wants to merge 1 commit into
Conversation
kaxil
reviewed
Jun 4, 2026
3501422 to
3da728d
Compare
…nects
The Execution API trace-propagation dependency attaches an OpenTelemetry
context before yielding and detaches it afterwards. When a client disconnects
or the request is cancelled, the dependency generator is force-closed from a
different asyncio task, so the detach ran against a contextvars.Token created
in a different Context. OpenTelemetry caught and logged that ValueError at
ERROR ("Failed to detach context") before our suppression could see it,
producing alarming but harmless log noise on the Dag processor and other
clients.
Skip the detach only on the GeneratorExit force-close path, where the
originating Context is being discarded anyway. On all same-task unwind paths
-- normal completion and a route handler raising (which FastAPI throws into
the generator at the yield) -- detach as before so the upstream trace context
does not leak into the exception handler, the error response, or error-path
spans. The route-error detach is suppressed so it can never mask the original
exception.
3da728d to
00a8b23
Compare
kaxil
reviewed
Jun 6, 2026
Comment on lines
254
to
+274
| try: | ||
| yield | ||
| finally: | ||
| except GeneratorExit: | ||
| # Cross-task force-close (client disconnect / request cancellation): the | ||
| # finalizer runs in a different asyncio Task — and thus a different | ||
| # contextvars.Context — than attach did, so detaching the token would raise | ||
| # "Token was created in a different Context" (which OTel logs at ERROR before | ||
| # any suppression here could see it). The attached Context is being discarded | ||
| # with the dying task, so detaching is unnecessary; skip it and re-raise. | ||
| raise | ||
| except BaseException: | ||
| # A route handler raised: FastAPI throws the exception into this generator at | ||
| # the yield, in the SAME task that attach ran in. Detach so the upstream trace | ||
| # context does not stay attached for the exception handler, the error response, | ||
| # and any spans/logs emitted while unwinding. Suppress any detach error so it | ||
| # cannot mask the original exception being propagated. | ||
| with contextlib.suppress(Exception): | ||
| otel_context.detach(token) | ||
| raise | ||
| else: | ||
| otel_context.detach(token) |
Member
There was a problem hiding this comment.
Could you share before/after logs from an actual disconnect? The tests assert detach isn't called, but the spurious line is logged inside OTel's own detach() (except Exception: logger.exception(...)), so I'd like to see it's actually gone from the output.
Minor and optional: rather than splitting on GeneratorExit vs BaseException, you could capture the task at attach and detach only when unwinding in it:
attached_in = asyncio.current_task()
try:
yield
finally:
if asyncio.current_task() is attached_in:
otel_context.detach(token)Same result, one branch. Not a blocker.
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.
The Execution API trace-propagation dependency attaches an OpenTelemetry context before yielding and detaches it afterwards. When a client disconnects or the request is cancelled, the dependency generator is force-closed from a different asyncio task, so the detach ran against a contextvars.Token created in a different Context. OpenTelemetry caught and logged that ValueError at ERROR ("Failed to detach context") before our suppression could see it, producing alarming but harmless log noise on the Dag processor and other clients.
Skip the detach on the GeneratorExit unwind path, where the originating Context is being discarded anyway, and detach only on normal completion.
Was generative AI tooling used to co-author this PR?
ClaudeCode Opus 4.8