Skip to content

Conversation

VegetarianOrc
Copy link
Contributor

@VegetarianOrc VegetarianOrc commented Oct 11, 2025

What was changed

The OpenTelemetry and OpenAI Agents interceptors have been updated to avoid detaching context in such a way that does not cause a <Token> was created in a different Context error.

Why?

There are some situations where cleanup happens in a different asyncio.Task (when tasks get garbage collected for instance). When those situations happen the contextvars.Context used to create the contextvars.Token is no longer available. By confirming that the Otel context is the same as the one we attached, we can do a best effort detach and avoid the error.

Checklist

  1. Issues Closed

    1. Closes [Bug] GeneratorExit possibly causing issues on context detach in OTel finally #441
  2. How was this tested:

A new test was added to force a GeneratorExit error after a task is garbage collected by disabling safe eviction. The test captures OpenTelemetry logs and ensures that the Failed to detach context message is not printed.

  1. Any docs updates needed?

@VegetarianOrc VegetarianOrc marked this pull request as ready for review October 16, 2025 22:46
@VegetarianOrc VegetarianOrc requested a review from a team as a code owner October 16, 2025 22:46
# different contextvars.Context than the one the token was created
# on. As such we do a best effort detach to avoid using a mismatched
# token.
if context is opentelemetry.context.get_current():
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice

unpause_and_assert,
workflow_update_exists,
)
from tests.helpers.cache_evitction import (
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Misspelling in the filename

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] GeneratorExit possibly causing issues on context detach in OTel finally

3 participants