Skip to content

openai_agents OTel bridge logs "Failed to detach context" errors for agent spans that outlive a workflow task #1853

Description

@DABH

Component: temporalio.contrib.openai_agents with OpenAIAgentsPlugin(use_otel_instrumentation=True) (SDK 1.32.0).

What happens

openinference-instrumentation-openai-agents attaches an OpenTelemetry context in on_span_start (self._tokens[span.span_id] = attach(...)) and detaches it in on_span_end. Temporal runs each workflow task in a copied contextvars context (_workflow_instance.py uses contextvars.copy_context()), so for every Agents SDK span that starts in one workflow task and ends in a later one (agent spans, temporal:startActivity, turn), the detach runs in a different context and OpenTelemetry logs:

ERROR opentelemetry.context: Failed to detach context
ValueError: <Token var=<ContextVar name='current_context' ...> was created in a different Context

with a full traceback, once per such span. A small agent run produces eight of these. Tracing itself is unaffected (spans are correct and exported once), but worker logs are flooded at ERROR level, which will alarm users.

Repro

Any workflow that runs Runner.run(agent) with the plugin above and an in-memory exporter; watch the worker's log output.

Possible fixes

Wrap the processor so the token bookkeeping is skipped inside workflows (the SDK already monkeypatches on_trace_start), or catch/suppress the ValueError in a thin processor wrapper. Until then, the Arize tracing sample (samples-python, AI-411) installs a logging filter on the opentelemetry.context logger that drops "Failed to detach context" records.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions