Repository navigation
Breaking: refuse TypeScript OpenAI Agents traces with their own tracing key at Temporal boundaries - #324
Conversation
…the TypeScript OpenAI Agents plugin
The plugin passes traces across Temporal boundaries in a header that is
stored in Event History, so it cannot carry a tracing key. Spans made past
the boundary were exported with another key.
Workflow code is refused where it sets the key: TemporalOpenAIRunner.run
with tracing: { apiKey }, and a trace started with tracingApiKey. Every
header write refuses a trace with its own key too, which covers Client
calls. A key the Worker's tracingApiKey option put on a restored trace is
not refused.
715299f to
aff368e
Compare
DABH
left a comment
There was a problem hiding this comment.
Review at head aff368e (two commits over 4bcde9a, which is main for this plugin). On a worktree at the head with pnpm 10.27.0, make lint is clean apart from the 8 existing warnings and make test passes 252 of 252. Every item below was reproduced at the head against the installed @openai/agents-core 0.14.3, the Workflow ones with real Workers and a dev server; the test item rests on a mutation run (each mutant applied alone, then the unit file and the integration test). Replay, recorded with real Workers on main and on the head and replayed across with Worker.runReplayHistory, matches the body line for line. On the head, main's keyless runs replay (finished, open, and started inside a keyed Client trace); main's tracing: { apiKey } and keyed withTrace runs, finished or open, fail with the refusal as a Workflow Task failure; a main run that catches it fails with [TMPRL1100] Complete workflow machine does not handle this event: HistoryEvent(id: 5, ActivityTaskScheduled). On main, the head's refused runs whose only Workflow Task failed replay, and a head run that caught the refusal fails with [TMPRL1100] Activity machine does not handle this event: HistoryEvent(id: 5, WorkflowExecutionCompleted); each build replays its own histories. So the replay break is the disclosed one, and the README's upgrade note covers it. Checked and fine: all 13 header writes go through currentAgentsSpanHeader; the onTraceStart refusal runs before the replay check, so it is deterministic; the resolved-key exemption holds for streamed runs, asTool, handoffs and addTemporalSpans on either side in an Activity with the resolver; the key reaches no header and no History. Refuted: copies of a restored trace that bypass the clone patch (agents-core 0.14.3 copies the current trace only through cloneCurrentContext); state left behind by the withTrace rejection; two copies of headers.ts splitting the WeakMap (one CommonJS build serves import and require). Not raised: a run state serialized with includeTracingApiKey: true and resumed in a second Activity is refused at its next Client call although only the resolver set the key (opt-in key persistence, rare). Not verified by running: the Python half of the first README item, which is by code reading.
Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.
Parity with #186. Same refusal points (run options, a keyed trace in Workflow code, every header write), same Client scope (start, signal, query, update), same error type and effect (plain Error here, ValueError there: a Workflow Task failure in Workflow code, a retryable failure in an Activity), the same message plus the resolver hint, and the same upgrade note. The differences are justified: a keyed Workflow trace is refused when it starts rather than when it is created (this plugin uses the upstream global provider; disclosed under 'Not covered'), keys this plugin's own resolver set are exempt (Python has no resolver), and update-with-start, Nexus and continue-as-new are covered because only this plugin propagates through them. Both READMEs carry the inaccurate Activity sentence (first inline comment), and the Python README leaves out signal, query and update although its code refuses them.
Open questions in the body. Keep the plain Error: in Workflow code it fails the Workflow Task, which a code change recovers, as #186's ValueError does, while a non-retryable ApplicationFailure would close the run. The Client scope matches #186. One thing to weigh: outside Workflow code the same Error is retryable (an Activity converts it with ensureApplicationFailure, so nonRetryable is false; a Nexus handler turns it into a retryable HandlerError('INTERNAL')), so an Activity that calls the Client under its own keyed trace repeats its model calls on every attempt. A non-retryable ApplicationFailure when !inWorkflowContext() would stop that, as a deliberate divergence from Python or a change to both.
Where the problems cluster: the refusal and its exemption are sound and the replay break is disclosed; what is left is what the docs promise around them and the paths that miss the two entry checks. The new README sentence about Activity runs is false in the common case, the resolver advice leaves out Client-side spans, three uncommon ways of putting a keyed trace around run end in a permanent Workflow failure (and runConfig inside a Client trace is not refused at all), and the Workflow-side header check and the streamed entry point have no test. Commenting rather than approving because the README this PR adds tells users that an agent run inside an Activity keeps its own tracing key, which is false under the trace the plugin restores and leads back to #214's silent misrouting; with that sentence fixed I would approve, and the other items are non-blocking.
PR body: it still says 'Draft while the breaking change and these questions are open'; my answers to the two questions are above. 'If it catches it, the run fails with [TMPRL1100]' is what the Replayer reports; on a live Worker the Workflow Task fails with TMPRL1100 on every attempt and the run stays open unless workflowFailureErrorTypes lists NondeterminismError (likewise, an uncaught refusal fails the run instead of the task where the failure types list Error). The 'Not covered' runConfig note needs the correction in the runner.ts comment.
| ### Tracing keys per run | ||
|
|
||
| The exporter sends each span with its trace's key, or with its default key (`OPENAI_API_KEY` or `setTracingExportApiKey()`) when the trace has none. The plugin does not write tracing keys into Workflow history, so a trace that crosses a Temporal boundary arrives without its key. A key a run sets in Workflow code with `tracing: { apiKey }` applies to that run's Workflow spans only when the run starts its own trace. When the Workflow runs inside a trace a Client started, the run joins that trace and the Agents SDK ignores the run's key. Spans made in Activities (including stateful MCP operations) and Nexus handlers, and the Workflow spans of a trace that a Client started, with or without `tracingApiKey`, use the exporter's default key. | ||
| The exporter sends each span with its trace's key, or with its default key (`OPENAI_API_KEY` or `setTracingExportApiKey()`) when the trace has none. A trace's own tracing key, set with `tracing: { apiKey }` on a run or `tracingApiKey` on a trace, is not supported. The plugin passes traces to Workflows, Activities and Nexus handlers 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, `TemporalOpenAIRunner.run` with `tracing: { apiKey }` and `withTrace(name, fn, { tracingApiKey })` throw. Starting, signaling, querying or updating a Workflow, or scheduling an Activity, child Workflow or Nexus operation, under such a trace throws too. Agent runs inside Activities can still use their own key. Set the tracing key on every Client and Worker process instead. A run that used such a key in Workflow code before you deploy this version gets the error when it replays: let those runs finish first, or use Worker Versioning. |
There was a problem hiding this comment.
P2: 'Agent runs inside Activities can still use their own key' is false for every Activity scheduled while the Workflow had a trace, which covers every Activity a run calls as a tool and every Activity of a Workflow started inside a Client trace; there a run's tracing: { apiKey } is dropped silently, which is #214's symptom in the place this sentence sends users. The Activity interceptor makes the header's trace current, and upstream Runner.run joins a current trace (withTraceContext(invocationTraceContext, ...) in run.js), applying tracing.apiKey only to a trace it creates itself. Probe at the head, upstream Runner.run(agent, 'hello', { tracing: { apiKey: 'sk-activity-run' } }) inside OpenAIAgentsTraceActivityInboundInterceptor.execute: under a restored trace the task, agent and turn spans carry no key (the Worker's default), or sk-resolved with a resolver; only an Activity whose header has no trace gets sk-activity-run. A trace the Activity starts itself with withTrace(name, fn, { tracingApiKey }) keeps its key, under a new trace ID detached from the Workflow's trace. Nexus handlers restore the trace the same way. Suggested: 'An agent run in an Activity or Nexus handler can use its own key only in a trace it starts itself with withTrace(name, fn, { tracingApiKey }), which is separate from the Workflow's trace and whose Temporal calls are refused; a run that joins the restored trace ignores tracing: { apiKey }, so use the Worker's tracingApiKey option there.' The Python README has the same sentence (python/openai_agents/README.md#L960), and by code reading the same join applies there (create_trace_for_run returns None when a trace is current, and execute_activity makes the header's trace current), so the correction belongs in both.
There was a problem hiding this comment.
Thanks, you're right, and the same holds in Python. Upstream Runner.run joins a current trace and uses tracing.apiKey only for a trace it creates (run.js here, create_trace_for_run in Python). I checked the Python half with a run against openai-agents 0.22.3: with RunConfig(tracing={"api_key": "sk-run"}), a run that starts its own trace exports its spans with sk-run, and the same run inside with trace(...) exports them with no key.
Fixed in 3c0a962, in both READMEs. In TS: an agent run in an Activity or Nexus handler joins the trace the plugin restored there and ignores tracing: { apiKey }, so use the Worker's tracingApiKey option. Only a trace that the Activity or handler starts itself with withTrace(name, fn, { tracingApiKey }) keeps its key; that trace is separate from the Workflow's trace, and Temporal calls under it throw. Python says the same with its names. Python has no resolver, so it says the spans use the Worker's default key.
| The exporter sends each span with its trace's key, or with its default key (`OPENAI_API_KEY` or `setTracingExportApiKey()`) when the trace has none. A trace's own tracing key, set with `tracing: { apiKey }` on a run or `tracingApiKey` on a trace, is not supported. The plugin passes traces to Workflows, Activities and Nexus handlers 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, `TemporalOpenAIRunner.run` with `tracing: { apiKey }` and `withTrace(name, fn, { tracingApiKey })` throw. Starting, signaling, querying or updating a Workflow, or scheduling an Activity, child Workflow or Nexus operation, under such a trace throws too. Agent runs inside Activities can still use their own key. Set the tracing key on every Client and Worker process instead. A run that used such a key in Workflow code before you deploy this version gets the error when it replays: let those runs finish first, or use Worker Versioning. | ||
|
|
||
| To send those spans with another key, resolve it on the Worker with `tracingApiKey`. It gets the trace ID, and when known the trace name and the Workflow ID and type, and returns a key or `undefined` for the default: | ||
| To use a different key per run, resolve it on the Worker with `tracingApiKey`. The plugin calls it for Workflow spans and for spans made in Activities (including stateful MCP operations) and Nexus handlers. It gets the trace ID, and when known the trace name and the Workflow ID and type, and returns a key or `undefined` for the default: |
There was a problem hiding this comment.
P3: the resolver reaches only spans made on Workers, so for a trace a Client starts, the trace record and the Client's own spans keep the Client process's default key while the Workflow and Activity spans of the same trace get the resolved key; this paragraph, the TracingApiKeyResolver JSDoc and the error message all point keyed Client traces here without saying so. Probe at the head with this paragraph's example resolver: in withTrace('tenant-a-request', ...) around a start through the Client interceptor with addTemporalSpans, the trace record and temporal:startWorkflow:Agent export with the Client's default key, and model-call and temporal:executeActivity:invokeModelActivity in the same trace with sk-tenant-a. On main, a keyed Client trace plus a matching resolver kept all four under sk-tenant-a; the head refuses that start, which is right since a Client cannot see the Worker's resolver, but the body's own reason for refusing ('the trace would still be split across two keys') is what this migration produces whenever the resolver returns a key other than the Client's default. Suggested addition: 'The resolver applies to spans made on Workers. A trace a Client starts, and the spans the Client makes in it, use the Client's default key; to keep a run under one key, start the Workflow outside a Client trace so the run starts its own trace, or have the resolver return the Client's key for it.'
There was a problem hiding this comment.
Agreed. Fixed in 3c0a962: after the example, the README now says the resolver runs only on Workers. A trace that a Client starts, and the spans the Client makes in it, keep the Client's default key. To keep a run under one key, start the Workflow outside a Client trace so the run starts its own trace, or have the resolver return the Client's key for that trace. The TracingApiKeyResolver JSDoc now says the resolver runs only on Workers too. I left the error message alone: it's already long, and it doesn't promise that the resolver covers Client spans.
| options?: TemporalRunOptions<TContext> | ||
| ): Promise<RunResult<any, TAgent> | StreamedRunResult<TContext, TAgent>> { | ||
| // Model calls run in an Activity, which cannot get the run's own tracing key. | ||
| refuseTracingApiKey(options?.tracing?.apiKey); |
There was a problem hiding this comment.
P2 (non-blocking): this check covers options.tracing.apiKey only, so the other ways of putting a keyed trace around a run are refused later, inside the upstream runner, where normalizeAgentsRunError (line 322) wraps the plain Error into the non-retryable AgentsWorkflowError and the Workflow fails for good instead of retrying its Workflow Task; one of them is not refused at all. Reproduced with real Workers and a dev server at the head, each around runner.run(agent, 'Hello'): runConfig: { tracing: { apiKey } }, withTrace(new Trace({ tracingApiKey }), fn) and withTraceContext({ trace: getGlobalTraceProvider().createTrace({ tracingApiKey }) }, fn) all end in WorkflowExecutionFailed with 'Agent workflow failed: The OpenAI Agents plugin cannot pass...' and no Activity. A Trace built with new Trace(...) uses agents-core's defaultProcessor() instead of the global provider's processors, so the onTraceStart refusal never sees it. Contrary to the body's 'Not covered' note, the runConfig case needs no cast: a run config shared through a variable (const rc = { workflowName: 'support', tracing: { apiKey } }; runner.run(agent, 'Hello', { runConfig: rc })) passes tsc (only an inline literal hits the excess-property check), and line 300 spreads it into new Runner(...). Started inside a keyless Client trace, the same run is not refused: the upstream runner joins the restored trace, drops the key and completes with its Activity, so the note's 'its trace is refused when it starts' holds only without a Client trace. A main history that used runConfig.tracing fails replay on the head with [TMPRL1100] Fail workflow machine does not handle this event: HistoryEvent(id: 5, ActivityTaskScheduled), a case the body's replay paragraph does not list. Fix here: also refuseTracingApiKey((options?.runConfig as { tracing?: TracingConfig } | undefined)?.tracing?.apiKey) and refuseTracingApiKey(getCurrentTrace()?.tracingApiKey) (no trace in Workflow code legitimately has a key: restored traces carry none and keyed starts are refused), or give the refusal its own Error subclass that normalizeAgentsRunError and the RunState.fromString catch rethrow unwrapped.
There was a problem hiding this comment.
Thanks for the repro. Fixed in 3c0a962 with your first option. Before anything else, run now also refuses runConfig.tracing.apiKey and a current trace that has a key, so these fail the Workflow Task the same way tracing: { apiKey } does. That also covers runConfig.tracing inside a keyless Client trace, plus withTrace(new Trace(...)) and createTrace with withTraceContext around run. I kept the fix at the top of run and didn't add an Error subclass, because #270 is changing normalizeAgentsRunError and the RunState catch.
Tests: tracingKeyRefusedWorkflow has new runConfig (passed through a variable, no cast) and traceContext cases, and both check that no Activity is scheduled. In the body, I removed the runConfig "Not covered" note. I also replayed it against main. main's runConfig.tracing runs, and its runs with a keyed createTrace trace made current around run, now fail on this branch with the refusal itself as a Workflow Task failure, the same as its tracing: { apiKey } runs, instead of the [TMPRL1100] you saw. Runs without a key still replay both ways. The replay paragraph in the body says so.
| }); | ||
|
|
||
| // A trace's own key is refused in Workflow code before the model call. | ||
| for (const entryPoint of ['run', 'withTrace'] as const) { |
There was a problem hiding this comment.
P3 (tests): the Workflow-side header check, the streamed entry point and the Client calls other than start have no test, and two unit assertions are weaker than they look. Mutation run, each mutant alone against trace-interceptor.test.ts and this test: skipping the currentAgentsSpanHeader refusal inside the Workflow sandbox survives, although a probe Workflow holding a keyed trace that never went through onTraceStart (createTrace plus withTraceContext, or a key assigned after start) then records ActivityTaskScheduled, StartChildWorkflowExecutionInitiated and SignalExternalWorkflowExecutionInitiated and is not refused at continue-as-new, where the head refuses each one and records no command. Skipping the top-of-run refusal for stream: true also survives; the body's 'streamed or not' holds by probe, and #186 tests run_streamed. The other mutants (top-of-run check, onTraceStart check, header check, clone patch, exemption, mark call, identity-only exemption, refusal as ApplicationFailure) are caught. Client signal, query, startUpdate, signalWithStart and startUpdateWithStart refuse by probe, with and without addTemporalSpans, but only start is asserted. In trace-interceptor.test.ts, line 54's t.throws(() => currentAgentsSpanHeader()) has no message matcher, and the replaced-key check at 43-44 runs on a clone of a clone, so a patch that marks first-level clones without re-patching them still passes it (only the Activity test's case with spans on both sides catches that mutant). Suggested: add a stream case and a backstop case (a keyed trace through createTrace plus withTraceContext around an Activity call, asserting the refusal and no command) to tracingKeyRefusedWorkflow, loop the keyed Client trace over the other Client calls, add { message: /cannot pass a trace's own tracing key/ } at 54, and check the replaced key at depth 1 with a separate positive check at depth 2.
There was a problem hiding this comment.
Thanks, all added in 3c0a962:
tracingKeyRefusedWorkflowhas newstream,runConfig,traceContextandactivitycases. The last makes acreateTracetrace current withwithTraceContextaround an Activity call. Each case checks the refusal and that no Activity was scheduled.- The keyed Client trace now loops over start, signal, query, startUpdate, signalWithStart and startUpdateWithStart.
- The handler-trace check at line 54 has the message matcher.
- The replaced key is now checked at depth 1, with a separate positive check at depth 2.
I re-ran the mutation check, applying each mutant alone: removing the runConfig check or the current-trace check from run, skipping the tracing check for streamed runs, removing the header check in Workflow code, marking clones without re-patching them, making the exemption ignore the key, and removing the check from each of the five Client calls. Each one fails the tests at its own case; the clone mutant now fails at the depth-2 check.
| /** | ||
| * Throws if a trace has its own tracing key. Headers are stored in Event History, so they cannot | ||
| * carry the key, and spans past the boundary would be exported with another key. Workflow code | ||
| * is refused where it sets the key; every header write checks again. |
There was a problem hiding this comment.
P3 (comment and message): 'Workflow code is refused where it sets the key' is #186's wording (Python refuses in create_trace); here createTrace({ tracingApiKey }) and getCurrentTrace()!.tracingApiKey = ... do not throw, and the refusal comes when the trace starts or at the next header write. Suggested: 'Workflow code is refused when it starts a keyed trace or runs with tracing: { apiKey }; every header write checks again.' The message at line 71 also names only 'Temporal Workflows and Activities', while Nexus operations are refused too and the README says 'Workflows, Activities and Nexus handlers'.
There was a problem hiding this comment.
Fixed in 3c0a962. The JSDoc now says Workflow code is refused when it starts a keyed trace or calls run with a key, and that every header write checks again. The message names Nexus operations too. The body's first paragraph has the same correction.
… the docs TemporalOpenAIRunner.run now also refuses runConfig.tracing.apiKey and a current trace with its own key before anything else runs. Inside the upstream runner these were refused later and wrapped, so the Workflow failed instead of its Workflow Task, or, inside a keyless Client trace, the runConfig key was dropped without an error. Both READMEs said agent runs inside Activities keep their own key. They don't: a run joins the trace the plugin restored there and ignores its own key. The TypeScript README also says the resolver runs only on Workers, and the Python one lists signals, queries and updates among the refused Client calls. The refusal message names Nexus operations. Tests cover the streamed run, runConfig.tracing, a keyed current trace around run and around an Activity call, every Client call, and clones of clones of a restored trace.
|
Thanks for the review. The five threads have their own replies; here are the summary items:
|
DABH
left a comment
There was a problem hiding this comment.
Second round, at head 3c0a962 (one commit over aff368e; 4bcde9a is still main for the TypeScript plugin, and the Python README merges cleanly onto current main). On worktrees at the head, TypeScript make lint shows only the 8 existing warnings and make test passes 252 of 252 (pnpm 10.27.0); Python make lint is clean and make test passes 425. Each earlier item was rechecked at this head by rerunning its reproduction (the Workflow ones with real Workers and a dev server) or, for the test items, by a mutation run. The Python README's new sentences were checked with a real-Worker probe against the locked openai-agents 0.22.0: under the trace the plugin restores in an Activity, RunConfig(tracing={"api_key": ...}) is ignored and the run's spans carry no key (scheduled outside any trace, the run keeps it: first inline comment); a keyed trace() that the Activity starts keeps its key under a new trace ID, and activity.client().start_workflow under it raises; start, signal, query, start_update and signal-with-start under a keyed Client trace raise (update-with-start is neither refused nor propagated, because the Python plugin does not intercept it, so no trace crosses there). Replay, recorded with real Workers on 4bcde9a and on the head and replayed across with Worker.runReplayHistory, matches the body: keyless runs, plain or inside a keyless Client trace, finished or open, replay both ways; every main run that used a key in Workflow code (tracing: { apiKey } or runConfig.tracing, each with and without a Client trace, keyed withTrace, createTrace plus withTraceContext, withTrace(new Trace({ tracingApiKey })), finished or open) fails on the head with the refusal as a Workflow Task failure, and the variants that catch it fail with [TMPRL1100] Complete workflow machine does not handle this event: HistoryEvent(id: 5, ActivityTaskScheduled); main replays the head's refused runs and fails the head's caught runs with [TMPRL1100] Activity machine does not handle this event: HistoryEvent(id: 5, WorkflowExecutionCompleted). So the replay break is the disclosed one. The three new or changed tests fail on 4bcde9a's sources and pass on the head, and a mutation run (each mutant alone, against the unit file and the integration test) catches every mutant the body lists, plus removing the whole entry check, the header check or the mark call; the one survivor is the test item below. Checked and fine: no Workflow-side trace legitimately has a key (the Workflow interceptor restores traces without one and the resolver applies only in the Worker's sink), so the new current-trace check cannot refuse a legitimate run, and the three entry checks still run before any command. Not raised: a keyed nested run inside a Workflow tool() reaches the model as a tool error through upstream's default errorFunction instead of failing the Workflow Task (upstream tool semantics, and Python's function_tool does the same); runConfig.tracingDisabled with a key is still refused, as in Python.
Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.
Previous rounds. Addressed, each verified at this head: the Activity sentence is replaced in both READMEs by one that is right whenever the plugin restored a trace (TypeScript: an upstream run with tracing: { apiKey } under the restored trace exports task, agent and turn with no key, or sk-resolved with a resolver, and a withTrace(..., { tracingApiKey }) in the Activity keeps its key under a new trace ID; Python as above), though the replacement now overreaches (first inline comment); run refuses runConfig.tracing.apiKey and a current keyed trace before anything else, so runConfig, withTrace(new Trace({ tracingApiKey })) and createTrace plus withTraceContext fail the Workflow Task with the refusal and schedule nothing instead of failing the Workflow, and runConfig inside a keyless Client trace is refused; the README and the TracingApiKeyResolver JSDoc say that the resolver runs only on Workers and what a Client's own spans get (probe: with a keyless Client trace and the README's resolver, the trace record and temporal:startWorkflow:Agent export with the default key and the Worker's spans with sk-tenant-a); the stream, runConfig, traceContext and activity cases, the loop over six Client calls, the message matcher and the depth-1 and depth-2 checks are in; the JSDoc and the message name the right refusal points and Nexus operations; the body is out of draft, separates live-Worker and Replayer outcomes and drops the runConfig note. Accepted declines: the error message keeps its wording, and the refusal stays a plain Error outside Workflow code, as in #186. Still open from the last round: nothing.
Where the problems cluster: the code is right at this head; what is left is wording around it (the Activity sentence and where the commit lands in release notes) and one test that the new entry check made redundant. Commenting rather than approving because the replacement Activity sentence is now unconditional and tells users who run an agent in an Activity without a Client trace that their tracing: { apiKey } is ignored and to use the resolver, which never runs there, so following it loses the key; with the TypeScript sentence made conditional I would approve (the Python one should get the same condition, here or in a separate docs PR), and the two P3s are non-blocking.
Findings on lines outside the diff
scripts/release/release_tool.py:456: P3 (release notes, non-blocking): the squash commit touchespython/openai_agents/README.md, and this line selects commits by path, so the Python plugin's next generated notes will list 'Breaking: refuse TypeScript OpenAI Agents traces with their own tracing key at Temporal boundaries (#324)' as a Python change. Simulated by squashing this PR onto current main and runningrelease_tool.py release-notes --plugin-dir python/openai_agents --tag python/openai_agents/v2.0.0 --ref HEAD: it is the first entry, above #291, #275, #232 and #186. Either move the Python paragraph into its own docs PR with a non-breaking subject (which can also carry the Python half of the first inline comment), or drop the line when reviewing the Python release draft.
| ### Tracing keys per run | ||
|
|
||
| The exporter sends each span with its trace's key, or with its default key (`OPENAI_API_KEY` or `setTracingExportApiKey()`) when the trace has none. The plugin does not write tracing keys into Workflow history, so a trace that crosses a Temporal boundary arrives without its key. A key a run sets in Workflow code with `tracing: { apiKey }` applies to that run's Workflow spans only when the run starts its own trace. When the Workflow runs inside a trace a Client started, the run joins that trace and the Agents SDK ignores the run's key. Spans made in Activities (including stateful MCP operations) and Nexus handlers, and the Workflow spans of a trace that a Client started, with or without `tracingApiKey`, use the exporter's default key. | ||
| The exporter sends each span with its trace's key, or with its default key (`OPENAI_API_KEY` or `setTracingExportApiKey()`) when the trace has none. A trace's own tracing key, set with `tracing: { apiKey }` on a run or `tracingApiKey` on a trace, is not supported. The plugin passes traces to Workflows, Activities and Nexus handlers 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, `TemporalOpenAIRunner.run` with `tracing: { apiKey }` or inside such a trace, and `withTrace(name, fn, { tracingApiKey })`, throw. Starting, signaling, querying or updating a Workflow, or scheduling an Activity, child Workflow or Nexus operation, under such a trace throws too. Set the tracing key on every Client and Worker process instead. In an Activity or Nexus handler, an agent run joins the trace the plugin restored there and ignores `tracing: { apiKey }`; use the Worker's `tracingApiKey` option instead. Only a trace that the Activity or handler starts itself, with `withTrace(name, fn, { tracingApiKey })`, keeps its own key; it is separate from the Workflow's trace, and Temporal calls under it throw. A run that used such a key in Workflow code before you deploy this version gets the error when it replays: let those runs finish first, or use Worker Versioning. |
There was a problem hiding this comment.
P2: the corrected sentence is now unconditional, but the plugin restores a trace in an Activity or Nexus handler only when the caller had one; when it had none, the run starts its own trace and keeps tracing: { apiKey }, and the resolver is never called, so the advice to switch to tracingApiKey drops the key there. The caller has no trace when Workflow code calls the Activity outside a run and outside withTrace in a Workflow started without a Client trace (or by a Schedule, the UI, or a Client without the interceptor): the header carries traceId: null (headers.ts:84), and withRestoredAgentsTraceContext returns fn() with no trace and no resolver call (trace-context.ts:58, worker/trace-interceptor.ts:85-92, Nexus at 128-130). Probe at the head through the Activity interceptor, resolver returning sk-resolved, such a header: an upstream run with tracing: { apiKey: 'sk-run' } exports its trace record and its turn, agent and task spans with sk-run; the same run without the key, as this paragraph advises, exports them with no key, and the resolver is called 0 times; withTrace(..., { tracingApiKey: 'sk-own' }) keeps sk-own either way. A real Worker running that Workflow shape gives the same result, and with a keyless Client trace around the start the run's spans get sk-resolved, as the README says. That is the agent-in-an-Activity pattern without a Client trace: a user of it who reads this section while upgrading and follows it sends the run's spans with the Worker's default key, which is #214's symptom. My suggested wording last round had the same gap. Suggested: 'An Activity or Nexus handler called under a trace runs in the trace the plugin restored there: an agent run joins it and ignores tracing: { apiKey }, and the Worker's tracingApiKey option gives its spans a key. When the caller had no trace, the run starts its own trace and keeps tracing: { apiKey }; the resolver is not called for it. A trace that the Activity or handler starts itself with withTrace(name, fn, { tracingApiKey }) keeps its key in both cases; it is separate from the Workflow's trace, and Temporal calls under it throw.' Line 637's 'for spans made in Activities ... and Nexus handlers' needs the same qualifier ('under the trace the plugin restored there'). The Python README's new sentence (python/openai_agents/README.md#L939-L942) has the same gap: with a real Worker and the locked openai-agents 0.22.0, a run in an Activity scheduled outside any trace keeps RunConfig(tracing={"api_key": ...}) on its trace and every span, so 'ignores the key in its RunConfig, so its spans use the Worker's default key' needs the same condition; its fallback (a keyed trace() in the Activity) works in both cases, so there the text is only inaccurate. The body's 'the same wrong sentence' should say the old Python sentence was right when no trace was restored.
There was a problem hiding this comment.
Thanks, you're right. With no trace in the header, the Activity and Nexus interceptors restore nothing and never call the resolver, so the run starts its own trace and keeps its key. Fixed in 246845d with your wording. An Activity or Nexus handler called under a trace runs in the restored trace: the run ignores tracing: { apiKey }, and the resolver gives its spans a key. When the caller had no trace, the run keeps its key and the resolver isn't called. A trace that the handler starts itself keeps its key in both cases.
Line 637 and the TracingApiKeyResolver JSDoc now say the resolver covers Activity and Nexus spans under the restored trace. The Python sentence gets the same condition in this PR, and the body's Python bullet now says the old sentence was right when the Activity was called without a trace.
| break; | ||
| } | ||
| case 'withTrace': | ||
| await withTrace('workflow-trace', () => runner.run(agent, 'Hello'), { tracingApiKey: 'sk-workflow' }); |
There was a problem hiding this comment.
P3 (tests, non-blocking): the new current-trace check at the top of run now refuses this withTrace case first, so the trace processor's onTraceStart refusal (agent-sink-processor.ts:103) is no longer covered by any test. Mutation run at this head: replacing refuseTracingApiKey(trace.tracingApiKey) in onTraceStart with a no-op leaves both test files green, because this case still returns refused: The OpenAI Agents plugin ..., now from runner.ts:248. Without that refusal, a keyed withTrace whose body makes no run and no Temporal call is not refused at all, so the README's 'withTrace(name, fn, { tracingApiKey }) ... throw' would stop holding without a test noticing. The body's 'without the trace-start check, withTrace is refused only at the model Activity, wrapped the same way' describes the first round. Suggested: add an entry point whose body makes no run, case 'withTraceOnly': await withTrace('workflow-trace', async () => {}, { tracingApiKey: 'sk-workflow' }), to TracingKeyEntryPoint and to the loop in test-openai-agents.ts; I checked that it passes on the head and fails with withTraceOnly: not refused when the onTraceStart refusal is removed.
There was a problem hiding this comment.
Thanks. Added in 246845d: a withTraceOnly entry point, whose body makes no run and no Temporal call, in TracingKeyEntryPoint and in the loop. With the onTraceStart refusal replaced by a no-op, the integration test now fails at withTraceOnly: not refused. I also fixed the body's sentence about the trace-start check, which still described the first round.
The README said an agent run in an Activity or Nexus handler always joins the restored trace and ignores its own key. The plugin restores a trace only when the caller had one; without it, the run starts its own trace, keeps its key, and the resolver is not called. Both READMEs and the resolver's doc now say so. A test case runs a keyed withTrace with nothing inside, so the trace processor's refusal is covered again now that run refuses keyed traces first.
|
Thanks. Both threads have replies (246845d). On the release notes: we're keeping the Python README change in this PR, so the release tool will list it in the Python plugin's generated notes. I added a "Release notes" line to the body saying to drop it from the Python release draft. |
DABH
left a comment
There was a problem hiding this comment.
Third round, at head 246845d (one commit over 3c0a962; it changes the two READMEs, the TracingApiKeyResolver JSDoc and one test case, and no runtime code). On a worktree at the head, TypeScript make lint shows only the 8 existing warnings and make test passes 252 of 252 (pnpm 10.27.0); Python make lint is clean and make test passes 425. CI is green at this head; its run tested the merge with main at 1acb19f (#166), and the PR still merges cleanly onto current main, whose later commits touch neither plugin. The last round's README item was rechecked by rerunning its probes, and its test item by its mutation. The TypeScript sentence, through the Activity and Nexus interceptors with agents-core 0.14.3: under the caller's trace, an upstream run with its own tracing: { apiKey } exports turn, agent and task with no key, or sk-resolved with the resolver; with a header whose traceId is null, or no header, the trace record and every span carry the run's key and the resolver is called 0 times; a keyed withTrace(name, fn, { tracingApiKey }) started in the Activity keeps its key in both cases (under a new trace ID when a trace was restored), and a Client start under it throws the refusal while one under the restored trace goes through. The Python sentence, with a real Worker and the locked openai-agents 0.22.0: under the restored trace the run's spans carry no key; in an Activity scheduled outside any trace the run keeps RunConfig(tracing={"api_key": ...}) on every span; a keyed trace() in the Activity keeps its key under a new trace ID, and activity.client().start_workflow under it raises. Replay: last round's 29 histories, replayed with Worker.runReplayHistory on this head's build, give the same results as on 3c0a962. Main's keyless runs (plain, in a keyless Client trace, open) replay; every main run that used a key in Workflow code and reached the model Activity fails, with the refusal as a Workflow Task failure or, for the two that catch it, with [TMPRL1100] Complete workflow machine does not handle this event: HistoryEvent(id: 5, ActivityTaskScheduled); the histories recorded on 3c0a962 replay. With no runtime change since then, the reverse direction checked last round still holds, so the replay break is still the disclosed one.
Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.
Previous rounds. Round two, each verified at this head: the Activity and Nexus sentence is conditional in both READMEs and matches the probes above, and the resolver paragraph and the TracingApiKeyResolver JSDoc now say 'under the trace the plugin restored there'; the withTraceOnly case is in, and with the onTraceStart refusal replaced by a no-op the integration test fails with withTraceOnly: not refused (it passes at the head); the body now tells whoever drafts the Python release to drop this PR's line, one of the two options I offered. Round one's items, fixed in 3c0a962, are unchanged at this head. Accepted declines: the plain Error outside Workflow code and the message's wording, as in #186. Still open: nothing.
Approving: every item from the earlier rounds is fixed and verified at this head, CI is green, the breaking change and its replay break are disclosed in the body and the README, and the one inline comment is a non-blocking nit.
| * them to Workflow history. | ||
| * to leave the exporter's default key. The plugin calls it for spans made in | ||
| * Activities (including stateful MCP operations) and Nexus handlers under the | ||
| * trace the plugin restored there, and for Workflow traces and spans. Workflow code and Clients can't give a trace its |
There was a problem hiding this comment.
P3 (cleanup, non-blocking): this edit left the line at 119 characters in a comment block wrapped at about 78. Rewrap lines 29-36 to the block's width; the wording is fine.
There was a problem hiding this comment.
Thanks for the approval. Rewrapped in f90bc67 to the block's width; the wording is unchanged. make lint shows only the 8 existing warnings.
What was changed
The TypeScript 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, as #186 does for Python. Workflow code is refused when it starts a keyed trace or calls
runwith a key or inside a keyed trace; every header write checks again.TemporalOpenAIRunner.run(streamed or not) throws the refusal when giventracing: { apiKey }orrunConfig.tracing.apiKey, or when it is called inside a trace with its own key, before anything else runs. A trace that Workflow code starts with its own key, such aswithTrace(name, fn, { tracingApiKey }), is refused when it starts: the plugin's Workflow trace processor throws, sowithTracerejects before the run inside it starts.currentAgentsSpanHeader(), which every outbound header write uses, throws when the current trace has its own key. This covers the Client's start, signal, signal-with-start, query, update and update-with-start, and the Workflow's Activity, Local Activity, child Workflow, Nexus operation, external signal and continue-as-new calls. Traces without a key, including the ones the plugin rebuilds from headers, pass as before.Error, so in Workflow code it fails the Workflow Task, which is retried until the code changes, as Breaking: refuse OpenAI Agents traces with their own tracing key at Temporal boundaries #186'sValueErrordoes. The message says to set the key on every Client and Worker process withsetTracingExportApiKey()orOPENAI_API_KEY, or to resolve it on the Worker withtracingApiKey.TracingApiKeyResolverdoc say the same. They also say that the resolver runs only on Workers, so a trace that a Client starts keeps the Client's default key, and the README says that an agent run in an Activity or Nexus handler called under a trace joins the restored trace and ignores its owntracing: { apiKey }, while one called without a trace keeps it.With
tracingApiKey(#215): a key the Worker's resolver put on a trace the plugin rebuilt in an Activity or Nexus handler is not refused. It is Worker configuration, not the trace's own key, and the header still carries no key: the resolver gives the spans past the next boundary their key again. The plugin records the resolved key for the rebuilt trace and for the copies the Agents SDK makes of it in span helpers and runs, so an Activity or Nexus handler that starts a Workflow under its restored trace keeps working with the option set, with or withoutaddTemporalSpans. If application code replaces that key with another one, the trace has its own key and is refused. A key that application code sets is refused whether or not the Worker has a resolver:With the refusal, the resolver is the way to use a different key per run, and it now gives every Workflow span its key too, since no Workflow span has its own.
Breaking change: a Workflow that runs with
tracing: { apiKey }or inside a keyed trace, or starts a keyed trace, completes today with some spans exported under the Worker's key; with this change its Workflow Task fails with the refusal at thatrunorwithTracecall. A Client that starts, signals, queries or updates a Workflow under a keyed trace now gets the error. Such applications must move the key to process-wide settings, or totracingApiKeyon the Worker.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 and its error path sends other commands, its Workflow Task fails with
[TMPRL1100]on every attempt and the run stays open; the Replayer reports the same error. WhereworkflowFailureErrorTypeslistsNondeterminismError, orErrorfor an uncaught refusal, the run fails instead. 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 a tracing key in Workflow code (
tracing: { apiKey },runConfig.tracingor a keyed trace) finish on the earlier version before you upgrade, or keep them there with Worker Versioning.Why?
See #214. The plugin passes the current trace to Workflows, Activities and Nexus handlers in the
__openai_spanheader, which 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'sgenerationspan with the prompt, are exported with that process's default key. Against OpenAI's trace ingest the key selects the account, so those spans land in another account, and nothing reports it. The header is stored in Event History, so it must not carry the key.#215 added the opt-in
tracingApiKeyresolver. Applications that don't set it still lose the key: #214's reproduction still fails onmainatff14931without the option (output in the reopening comment).Checklist
Closes [Bug] openai-agents (TypeScript): a run's or client trace's tracing key does not reach spans made past a Temporal boundary #214
How was this tested:
src/__tests__/test-openai-agents.tsis extended. Its resolver cases now run without an application key: a run that starts its own trace, a Workflow started inside a Client trace, and a stateful MCP Workflow; each Activity, Workflow and MCP span gets the key the Worker resolves. The run with its own key and the keyed Client trace now check the refusal. In Workflow code,runwithtracing: { apiKey }, streamed or not, or withrunConfig.tracing(passed through a variable, which type-checks),runinside a keyedwithTraceor inside acreateTracetrace made current withwithTraceContext, a keyedwithTracewith nothing inside, and an Activity call inside such a trace each throw it before any Activity is scheduled. Uncaught, it fails the Workflow Task. Start, signal, query, startUpdate, signalWithStart and startUpdateWithStart inside a keyed Client trace each reject with it.src/__tests__/trace-interceptor.test.tsalso checks that a handler can write a header under its restored trace with the resolved key, directly, insidewithCustomSpan(which clones the trace) and inside a nested one (a clone of the clone), that a key application code puts on a clone in place of the resolved one is refused, and that a trace with its own key opened inside the handler is refused.addTemporalSpansoff and on for each interceptor: each start reaches the next interceptor with the trace ID and no key in the header, and with the resolved key replaced by an application key each start is refused before it.main's source files, with these tests, the integration test fails withrun: not refusedand the Nexus test fails because the handler's own keyed trace is not refused. With parts of the fix turned off, each test fails at the part it covers: without the check at the top ofrun, the run is refused only inside the Agents SDK runner, which wraps it (run: refused: Agent workflow failed: ...) and fails the Workflow instead of the Workflow Task; without the trace-start check, a keyedwithTracewhose body makes no run and no Temporal call is not refused (withTraceOnly: not refused); without the header check, the keyed Client trace'sstartresolves; without the exemption for resolved keys, the Nexus handler's header write under its restored trace throws. With an exemption tied to the rebuilt trace object, the restored trace is refused inside span helpers and with temporal spans on, and a replaced key is not refused. With the change all pass. After the first review, each newer part removed alone also fails them: therunConfigand current-trace checks inrun, the check for streamed runs, the header check in Workflow code, re-patching clones of clones, matching the key in the exemption, and the check on each Client call other thanstart.make sync,make lint(8 existing warnings, none in files this PR touches),make test(252 tests),make build,node ../_shared/smoke.mjsandscripts/ci/check_conventions.pypass. CI covers the other Node versions and platforms.mainatff14931without the option; withresolve(the option set) it exits 0 onmain. A fix check with the same Workflow and fake model exits 1 onmainand 0 on this branch: the run with its own key fails its Workflow Task with the refusal before any Activity or span, starting a Workflow inside a keyed Client trace throws it and starts nothing, and withtracingApiKeyset a keyless run and a keyless Client trace get the resolved key on every span.mainand on this branch: no key, a run with its own key, a keyedwithTracein the Workflow, and a run with its own key that catches the error; finished and open. Each version replays its own histories, and runs without a key replay in both directions.main's keyed runs fail on this branch: uncaught, with the refusal itself (ReplayError: Replay failed due workflow task failure ... The OpenAI Agents plugin cannot pass ...); caught, with[TMPRL1100] ... Complete workflow machine does not handle this event: HistoryEvent(id: 5, ActivityTaskScheduled). A run recorded on this branch that caught the refusal fails onmainwith[TMPRL1100] ... Activity machine does not handle this event: HistoryEvent(id: 5, WorkflowExecutionCompleted); refused runs whose only Workflow Task failed replay onmain. Open runs without a key complete across an upgrade, a rollback and a Worker replacement;main's open keyed run gets the refusal at its next Workflow Task on this branch. A control that renames the model Activity fails with[TMPRL1100]in both directions. After the first review, the same check againstmainwith runs that usedrunConfig.tracing, or a keyedcreateTracetrace made current aroundrun: on this branchmain's finished and open runs of both kinds fail with the refusal itself, as itstracing: { apiKey }runs do;mainreplays this branch's refused runs; runs without a key replay in both directions and complete across an upgrade and a rollback.Any docs updates needed?
The README's "Tracing keys per run" part is updated here, with an upgrade note, and so is the tracing key part of the Python README.
Release notes: because this PR also edits
python/openai_agents/README.md, the release tool lists it in the Python plugin's generated notes. Drop it from the Python release draft; it belongs only in the TypeScript notes.Not covered:
getGlobalTraceProvider().createTrace({ tracingApiKey })and never started is refused only byrunor when it reaches a boundary. Breaking: refuse OpenAI Agents traces with their own tracing key at Temporal boundaries #186 refuses it at creation, through its own trace provider; the TypeScript plugin uses the Agents SDK's global provider.Decided in review:
Error, as in Breaking: refuse OpenAI Agents traces with their own tracing key at Temporal boundaries #186. In Workflow code it fails the Workflow Task, which is retried until the code changes; the plugin's other Workflow refusals, such asUnsafeSessionError, throw a non-retryableApplicationFailure, which fails the Workflow instead. In an Activity or Nexus handler the refusal is a retryable failure, like any other bug there.