kaxil commented on code in PR #68039:
URL: https://github.com/apache/airflow/pull/68039#discussion_r3366181145


##########
airflow-core/src/airflow/api_fastapi/execution_api/app.py:
##########
@@ -253,9 +253,25 @@ async def _extract_w3c_trace_context(
     token = otel_context.attach(ctx)
     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)

Review 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:
   
   ```python
   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 is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to