Skip to content

Breaking: refuse OpenAI Agents traces with their own tracing key at Temporal boundaries - #186

Merged
campoy merged 5 commits into
mainfrom
fix/openai-agents-python-tracing-key-dropped-in-activities
Oct 29, 2026
Merged

campoy merged 5 commits into
mainfrom
fix/openai-agents-python-tracing-key-dropped-in-activities

Conversation

@campoy

@campoy campoy commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

What was changed

The OpenAI Agents plugin now refuses a trace that has its own tracing key when it would pass that trace across a Temporal boundary, instead of silently dropping the key. Workflow code is refused where it sets the key.

  • In Workflow code, Runner.run and Runner.run_streamed (in TemporalOpenAIRunner._prepare_workflow_run) and trace() (in TemporalTraceProvider.create_trace) raise the refusal when given their own tracing key, before any hook or other Workflow logic runs. Agent runs inside Activities and code outside Temporal keep their keys.
  • As a backstop, OpenAIAgentsContextPropagationInterceptor.set_header_from_context, which every outbound path uses, raises ValueError when the current trace has its own tracing key (RunConfig(tracing={"api_key": ...}) or trace(..., tracing={"api_key": ...})). The message says to set the key on every process with set_tracing_export_api_key or OPENAI_API_KEY. This covers the client's start, signal, query and update, and the Workflow's Activity, local Activity, child Workflow and external signal calls. Traces without a key, including the ones the plugin rebuilds from headers, pass as before. The OpenTelemetry mode uses the same header path.
  • The README's "Tracing" section documents the rule.

Other places that can set the key go through these checks: nested runs, such as Agent.as_tool, call Runner.run with their own or the parent's run_config; a run_config dict is turned into a RunConfig first; direct create_trace calls hit the provider check; a resumed RunState takes the key only from RunConfig. Runner.run_sync is already refused in Workflows. On the client, start, signal, query and update are where a keyed trace first meets Temporal, so the header check is the earliest point there.

The header is stored in Event History, so it must not carry the key. Refusing is the only safe option that keeps spans from going out under another key.

Breaking change: a Workflow that runs with RunConfig(tracing={"api_key": ...}), or opens such a trace, completes today with some spans exported under the Worker's key; with this change its Workflow Task fails with the refusal at that Runner.run, Runner.run_streamed or trace() call. A client that starts, signals, queries or updates a Workflow under a keyed trace now gets ValueError. Such applications must move the key to process-wide settings. A different key per run is no longer possible through the plugin; a key reference resolved on the Worker would be a separate, additive feature.

The refusal has no version gate. A run that used a key in Workflow code before this version gets the refusal when it replays. If the Workflow does not catch it, its Workflow Task fails on every attempt. If it catches it, the run fails with [TMPRL1100] when its error path sends other commands. A run that has not used a key yet is refused at its first keyed call after the upgrade. Runs that never use a key in Workflow code are not affected. Client code is not replayed.

Upgrade: let runs that use RunConfig(tracing={"api_key": ...}) or a keyed trace() in Workflow code finish on the earlier version before you upgrade, or keep them there with Worker Versioning.

The branch has four commits and a merge of main: the second changes only the README, the third (cc8e0bc) adds the earlier refusals from review, and the fourth (01935c3) removes the version gate. Review the combined diff against main.

Why?

See #185. The plugin passes the current trace to Workflows and Activities in a header that holds only the trace name, trace ID and span ID. The receiving side rebuilds the trace without its key, so spans made there, including the model call's generation span with the prompt, are exported with that process's OPENAI_API_KEY. Against OpenAI's trace ingest the key selects the account, so those spans land in another account, and nothing reports it.

Checklist

  1. Closes [Bug] openai_agents: a run's or trace's own tracing key does not reach spans made in Activities #185

  2. How was this tested:

    • New test_trace_tracing_key_refused in tests/test_openai_tracing.py: a run's key in a Workflow must fail its Workflow Task with the refusal, and a keyed client trace must make start_workflow raise it. On main it fails with AssertionError: The run's tracing key was not refused; it passes with the change. It also checks that Runner.run, Runner.run_streamed and trace() in a Workflow raise the refusal at the call, before the agent's on_agent_start hook. With the earlier head (c05ffcc) these fail with run: refused after the agent started, run_streamed: not refused and trace: not refused.
    • Locally, on 01935c3, the full suite passes (391 tests), and ruff check --select I, ruff format --check, pyright, mypy, basedpyright and pydocstyle pass. These ran with uv 0.13.1, outside the plugin's required-version, so not through make. CI covers make lint and make test.
    • [Bug] openai_agents: a run's or trace's own tracing key does not reach spans made in Activities #185's reproduction exits 1 on 1.1.0 and main. With the change, the run-key Workflow's Task fails with the refusal and the keyed client trace's start_workflow raises it, before any span goes out with another key.
    • Replay on 01935c3 of 22 histories recorded on main, finished and still waiting: runs with no key, a run's own key, a keyed trace opened in Workflow code, and two-turn cases, including the first keyed call in the Workflow constructor or in a class with __slots__ = (). The 6 runs that had not used a key replay. The 16 that had fail with [TMPRL1100], because the test Workflow catches the refusal and its error path sends other commands. A control that renames an Activity fails all 22 with [TMPRL1100] (run on cc8e0bc; the rename does not touch the gate).
  3. Any docs updates needed?
    The README's "Tracing" section is updated here, with an upgrade note.

Not covered:

  • Without the gate, the replay check was not rerun with live Workers: no run waiting on main was carried onto this change, and histories recorded with this change were not replayed on main.
  • temporalio 1.34.x still bundles the old code as temporalio.contrib.openai_agents. No backport here.
  • Child Workflows and external signals go through the same header code but were not run.
  • The OpenAI Agents TypeScript plugin has the same mechanism; it needs its own change.

Open questions:

  • Scope: client queries, signals and updates under a keyed trace are refused too, since their spans would also go out with another key. Refusing only RunConfig(tracing={"api_key": ...}) would leave the client-trace case open.
  • Refusal type: ValueError, so the Workflow Task fails and is retried until the code changes, like the plugin's other refusals, rather than failing the Workflow.
  • Should temporalio 1.34.x get a backport?

Draft while the breaking change and these questions are open.

The plugin passes the current trace to Workflows, Activities and child
Workflows in a header that holds the trace name and IDs, not the trace's own
tracing key. A key set with `RunConfig(tracing={"api_key": ...})` or
`trace(..., tracing={"api_key": ...})` was dropped there, so spans made on the
other side, such as the model call's generation span with the prompt, were
exported with that process's default `OPENAI_API_KEY`. The header is stored in
Event History, so it cannot carry the key.

Starting a Workflow, signaling, querying or updating it, or scheduling an
Activity or child Workflow under a trace with its own tracing key now raises
`ValueError` with a clear message.

Breaking change: Workflows that run with `RunConfig(tracing={"api_key": ...})`
or open such a trace now fail their Workflow Task, and clients that start or
signal Workflows under such a trace get `ValueError`. Set the tracing key on
every client and Worker process instead, with `set_tracing_export_api_key` or
`OPENAI_API_KEY`. In Workflow code the check is behind the
`openai_agents.refuse-trace-tracing-key` patch: runs that started on an
earlier version keep working without it and still replay. A run that records
the patch marker cannot be replayed by an earlier version.
The patch is checked at a run's first keyed outbound call, so a run that started
on an earlier version keeps passing keyed traces only if it already did so before
the upgrade; a run that does it first after the upgrade gets the error.
@campoy
campoy force-pushed the fix/openai-agents-python-tracing-key-dropped-in-activities branch from 53f54f5 to e341c44 Compare October 28, 2026 23:15
@campoy
campoy marked this pull request as ready for review October 28, 2026 23:24
@campoy
campoy requested a review from a team as a code owner October 28, 2026 23:25

@brianstrauch brianstrauch left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please add earlier validation of unsupported tracing keys at the public entry points where they are supplied, including Runner.run, Runner.run_streamed, and trace(...) in workflow code, and audit other entry points that can introduce the same configuration.

With validation only in set_header_from_context, the configuration is accepted and agent hooks or other workflow logic can run before an Activity/child-workflow handoff finally raises the error. Reporting the unsupported key at the originating call would make the cause much easier to find.

Keep the boundary check as a backstop. Scope the earlier rejection to workflow execution so keyed agent runs inside Activities or outside Temporal remain supported, preserve replay compatibility for existing histories, and add tests for the earlier failures. I would like this addressed before merging.

Runner.run, Runner.run_streamed and trace() now raise the refusal in
Workflow code when given their own tracing key, before any hook or other
Workflow logic runs. The header check stays as a backstop. Activities and
code outside Temporal keep their keys. The check uses the same patch
marker, so earlier runs still replay.
Fixes add no version gates for now, so remove the
`openai_agents.refuse-trace-tracing-key` patch and the replay test
History that only checked it. Workflow code now refuses its own tracing
key in every run.

Breaking change: a run that used such a key in Workflow code before this
version gets the refusal when it replays. If the Workflow does not catch
it, its Workflow Task fails on every attempt; if it catches it, the run
fails with a non-determinism error. Let those runs finish before you
upgrade, or use Worker Versioning.
@campoy

campoy commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @brianstrauch, addressed in cc8e0bc and 01935c3.

  • In Workflow code, Runner.run and Runner.run_streamed now refuse a keyed RunConfig.tracing before the run starts, so no hook or agent logic runs first. trace(..., tracing={"api_key": ...}) is refused by the plugin's trace provider.
  • Other entry points: nested runs like Agent.as_tool go through Runner.run; a run_config dict is converted first; direct create_trace calls hit the same check; a resumed RunState takes the key only from RunConfig; run_sync was already refused. On the client, start/signal/query/update are the first Temporal calls, so the header check is already the earliest point there.
  • The header check stays as a backstop. Only Workflow code is affected: keyed runs in Activities and outside Temporal still work.
  • The new checks have no version gate, per our no-gates rule for the 1.0 releases. The PR description lists which runs break and how to upgrade.
  • test_trace_tracing_key_refused now covers all three calls and checks that the refusal comes before on_agent_start.

@campoy
campoy requested a review from brianstrauch October 29, 2026 01:29

@brianstrauch brianstrauch left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Found one regression involving explicitly disabled tracing. All 25 existing tracing tests pass; both focused Workflow reproductions below pass on the base commit and fail on this head.

@campoy
campoy merged commit 3488fbe into main Oct 29, 2026
27 checks passed
@campoy
campoy deleted the fix/openai-agents-python-tracing-key-dropped-in-activities branch October 29, 2026 18:41

@DABH DABH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This PR merged while the review was running, so treat these as follow-ups. Lint passes on the head; findings were verified in-process against openai-agents 0.22 and the SDK sources cited, and the dev-server behaviors below were reproduced.

Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.

Headline: the README's 'Agent runs inside Activities can still use their own key' is false in the common case, and the refusal is both un-gated (unlike the sibling model_provider refusal in the same function) and broader than the harm it describes (it fires when tracing is disabled, when a trace is already current, and inside nested agent-as-tool runs, where the SDK would simply have ignored the key).

Activities in headers, which are stored in Event History, so it cannot pass the key, and their spans
would be exported with another key. In Workflow code, `Runner.run`, `Runner.run_streamed` and
`trace()` raise `ValueError` when given such a key. Starting a Workflow, or scheduling an Activity or
child Workflow, under such a trace raises it too. Agent runs inside Activities can still use their

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1: this sentence is false whenever the Activity runs under a propagated trace, which is the normal case. The activity inbound interceptor's context_from_header rebuilds the caller's trace with tracing_api_key=None and makes it current (_trace_interceptor.py:209-219). Inside the Activity, Runner.run(agent, x, run_config=RunConfig(tracing={'api_key': K})) goes straight to AgentRunner.run, whose create_trace_for_run (agents/tracing/context.py:59-61) returns None because a current trace exists, so run_config.tracing is never read and every span exports with the Worker's default key (verified in-process: create_trace_for_run(...) -> None, span.tracing_api_key -> None). That is exactly the #185 symptom, now undocumented and unrefused on the Activity side; the sentence holds only for an Activity whose header carries no traceId. A second narrowing in the same sentence: an Activity agent run under its own keyed trace() whose tool starts, signals, queries or updates a workflow through a plugin-configured client now raises ValueError from inside the tool (set_header_from_context is not exempt for non-workflow code the way create_trace is). Qualify the sentence, and consider at least a warning on the Activity side when a keyed RunConfig is ignored.

)

# Model calls run in an Activity, which cannot get the run's own tracing key.
if run_config.tracing is not None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2: un-gated, and broader than the harm. The sibling model_provider refusal ten lines above is wrapped in if workflow.patched(_REFUSE_RUN_MODEL_PROVIDER_PATCH): so in-flight histories keep replaying; this check, the create_trace override and the header backstop run unconditionally, and the first commit's gate plus its replay fixture (tests/histories/run-tracing-key-workflow-history.json) were deleted. A run started on the previous version with RunConfig(tracing={'api_key': K}), sleeping on a timer, replays _prepare_workflow_run after the upgrade and raises before any command; ValueError is not an AgentsWorkflowError, so the task fails and is retried indefinitely (the PR's own test has to terminate() the run), and README line 940's 'gets the error when it replays' understates a silent task-failure loop. Separately, the refusal fires in three cases where the SDK itself would have ignored the key and nothing is exported under a wrong key: when a trace is already current in the workflow (propagated from a client with trace(...) or an outer trace(); create_trace_for_run returns None), in nested runs (agent.as_tool(run_config=RunConfig(tracing=...)) or Runner.run inside a function tool), where the ValueError is absorbed by the SDK's function-tool failure handler into model-visible tool output ('An error occurred while running the tool ... cannot pass a trace's own tracing key') and the workflow completes with the model having read the refusal, and with tracing_disabled=True (see the create_trace comment). The message 'would be exported with another key' does not describe those cases; either narrow the check to get_trace_provider().get_current_trace() is None and not run_config.tracing_disabled, or say the key is refused even where the SDK would ignore it.

tracing: TracingConfig | None = None,
) -> Trace:
"""Create a new trace, refusing its own tracing key in workflow code."""
if workflow.in_workflow() and tracing is not None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2: refuses before the SDK's own disabled checks, and disagrees with the header backstop. DefaultTraceProvider.create_trace returns NoOpTrace() for disabled=True or a disabled provider before it ever reads tracing (provider.py:384-392), so a worker started with OPENAI_AGENTS_DISABLE_TRACING=1 or set_tracing_disabled(True), or workflow code using trace('x', disabled=True, tracing={'api_key': K}), now fails the workflow task with 'their spans would be exported with another key' although no span is exported at all (verified: NoOpTrace, key None). set_header_from_context meanwhile lets a NoOpTrace through because its tracing_api_key is None, so the three checks disagree on the disabled case. Checking the explicit disabled argument and run_config.tracing_disabled first keeps determinism (do not consult the process-global flag, which would make replay depend on process state).

spans made on the other side are exported with that process's default key instead.
Workflow code is refused where it sets the key; every header write checks again.
"""
if tracing_api_key is None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P3: an empty-string key is refused although the SDK treats it as no key. The exporter does api_key = item_key or self.api_key (processors.py:131) and Trace.to_json uses truthiness, so RunConfig(tracing={'api_key': os.environ.get('TRACING_KEY', '')}) exports with the default key on both sides and nothing diverges, yet the plugin raises. if not tracing_api_key: return matches the exporter's semantics.


def set_header_from_context(self, input: _InputWithHeaders) -> None:
"""Inserts the OpenAI Agents trace/span data in the input header."""
current_trace = get_trace_provider().get_current_trace()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P3: the refusal runs after maybe_span has already started the Temporal span, so a refused operation still exports a temporal:startWorkflow:* (and signal/query/update) custom span under the user's key with no error attached. On the client, start_workflow enters maybe_span (span started, exported under sk-x), then this raises, and SpanImpl.__exit__ just finish()es; in _span_for_start the ExitStack callback exits the span with (None, None, None). Moving the _refuse_tracing_key check ahead of maybe_span in the four client methods and in _span_for_start avoids the phantom span.

`trace(..., tracing={"api_key": ...})`, is not supported. The plugin passes traces to Workflows and
Activities in headers, which are stored in Event History, so it cannot pass the key, and their spans
would be exported with another key. In Workflow code, `Runner.run`, `Runner.run_streamed` and
`trace()` raise `ValueError` when given such a key. Starting a Workflow, or scheduling an Activity or

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P3 (docs): the README names only 'Starting a Workflow, or scheduling an Activity or child Workflow', but the backstop also refuses queries, signals, updates, external and child signals and local activities (query_workflow, signal_workflow, start_workflow_update, signal_child_workflow, signal_external_workflow, start_local_activity all call set_header_from_context); query headers are not stored in Event History, so the stated rationale does not even apply to that path. Conversely start_update_with_start_workflow (and start_nexus_operation on both sides) are not overridden by the client interceptor, so update-with-start under a keyed trace neither raises nor propagates: the workflow starts, its spans export under the worker's key in a separate trace, and the caller believes they are in the keyed one. Both update-with-start inputs carry headers, so the interceptor could write the header on start_workflow_input and update_workflow_input. One more scope note: a client still on temporalio.contrib.openai_agents (the SDK wheel ships a full copy with the same __openai_span header and no refusal) or an older plugin writes keyed-trace headers that this worker cannot detect, so the 'exported with another key' outcome persists silently in mixed-version deployments until the client side is upgraded too.

return "not refused"


async def test_trace_tracing_key_refused(client: Client):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P3 (tests): every public workflow path is refused by _prepare_workflow_run/create_trace before any header write, so the workflow-side backstop (set_header_from_context raising inside context.run(...) in _span_for_start, and the ExitStack unwind) runs in no test; only the client start_workflow branch is covered. The RunTracingKeyWorkflow block says the key 'could not reach the model Activity's spans' but check() only looks for the failure-message substring and never asserts that no ACTIVITY_TASK_SCHEDULED event exists before terminate(), so it would still pass if the refusal moved after the activity was scheduled; the entry-point loop is what actually guards ordering. Add a history assertion or drop the redundant workflow.

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] openai_agents: a run's or trace's own tracing key does not reach spans made in Activities

3 participants