Repository navigation
Breaking: stop the OpenAI Agents streaming model activity when a parallel input guardrail trips - #228
Conversation
|
I pushed a fix for a flaky run of the new test. CI failed it on Ubuntu with Python 3.14. What went wrong? The test raced the fix. The fake model streamed five deltas 300 ms apart, so the cancel had about 0.5 s to arrive with the next heartbeat. On a slow runner, the model sometimes finished first. Now the fake model sends its first delta and then waits up to 10 s. And instead of sleeping, the workflow stays open until the test has read the topic's last event. I recorded the replay test's History again on Locally, the test now passes 5 runs out of 5 on Python 3.13 and on 3.14, and it still fails on |
…t guardrail trips
On the streaming route, the model activity publishes each event to the
stream topic as the model sends it, but the framework checks parallel
input guardrails only against the events the workflow yields after the
activity returns. So when such a guardrail tripped mid-stream, topic
subscribers still got the rest of the answer and response.completed.
Now the workflow-side model cancels the streaming activity when the
guardrail trips, and does not start it when the guardrail has already
tripped. The run raises InputGuardrailTripwireTriggered as before. On
cancel, the activity publishes an `error` event with the code
`cancelled` to the topic and stops. Both are behind
workflow.patched("openai_agents.stream-tripwire-cancel"), because runs
recorded before this change have no cancel command at that point.
…timing The test relied on the cancel reaching the streaming activity before the fake model finished its 1.5 s stream. The cancel arrives with the next heartbeat, so on a slow runner the model sometimes finished first and the topic got response.completed. The fake model now sends its first delta and then waits up to 10 s, so the guardrail always trips mid-stream and the cancel has time to arrive. The workflow stays open until the test has read the topic's last event, instead of sleeping. The replay test's History is recorded again on main with the new workflow.
…sion gate Fixes add no version gates for now, so remove the `openai_agents.stream-tripwire-cancel` patch and the replay test and History that only checked it. When a parallel input guardrail trips, the Workflow now cancels the streaming model Activity, or does not start it, in every run. Breaking change: a streamed run in which a parallel input guardrail tripped before this version recorded no cancel. On replay it now cancels the model Activity, or does not schedule it, so the replay fails, with a non-determinism error or with a `Fatal error in workflow machines` error from the SDK core. Let those runs finish before you upgrade, or use Worker Versioning.
f400ce4 to
b8a943e
Compare
DABH
left a comment
There was a problem hiding this comment.
Review at head 9d4dd6a, first round. On a worktree at the head, make lint is clean and make test passes 458 of 458. I recorded six streamed runs on origin/main and replayed them at the head, and the reverse (results under Replay). I ran the PR's new tests against main's plugin source: on temporalio 1.35.0 all twelve guardrail cases fail there for the right reason (response.completed on the topic, or the activity scheduled), the Worker-shutdown case passes on both sides as a guard, and all thirteen passed four repeated runs at the head, one of them with -n 8 under load. Every finding below was reproduced with a temporary test at the head. Checked and not a problem: openai-agents 0.22.3, the newest the pin allows, keeps both private fields and still records the trip before gathering the sibling guardrails; the watcher is deterministic with the cache off; by code reading, turn-2+ calls, handoffs and nested streamed runs watch the right run; heartbeat coverage is unchanged, since everything before the new try is synchronous; auto_heartbeater behaves as before for the MCP activities; the mid-stream tripwire is not retried by a ModelSettings.retry policy. Not verified: the README's TRY_CANCEL closing race from the subscriber's side. In my History of a run that returns right after the trip, the cancel request and the completion share one Workflow Task, which is consistent with it.
Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.
Replay. The break is disclosed and behaves as the body says. Histories recorded on origin/main, replayed at the head: a parallel guardrail tripping mid-stream fails with Fatal error in workflow machines: ActivityMachine in state ScheduledActivityCancelCommandCreated says the transition is invalid during event ... ActivityTaskStarted; a trip known before the model call fails with [TMPRL1100] Nondeterminism error: Complete workflow machine does not handle this event: HistoryEvent(id: 15, ActivityTaskScheduled). A guardrail passing mid-stream, one passing after the model, a trip after the activity returned, and no guardrails all replay cleanly, and every head-recorded history replays at the head. No gate is needed if this ships in 2.0.0, as the GA-wave policy intends; a 1.x release would need one. Three corrections for the body. The policy sentence says 'the plugins' 1.0 releases', but this plugin is already GA at 1.x, so the break ships in 2.0.0. The 'replay check was not rerun' line under Not covered is out of date. And rollback breaks too: head-recorded tripped runs fail on main with [TMPRL1100] Nondeterminism error: No command scheduled for event HistoryEvent(id: 15, ActivityTaskCancelRequested), so the Upgrade note should say that rolling back fails open runs that tripped on the new version.
Where the problems cluster: with heartbeat_timeout set and TRY_CANCEL or WAIT_CANCELLATION_COMPLETED, the cancel path is right and well tested, including the four cancel windows. What is left is the contract of the new error event on the topic. It does not reliably mark the end of the call it cancels: under TRY_CANCEL it can land among the next call's events, and any cancel the workflow requests publishes it, including a framework timeout that a framework retry then answers. In three other configurations it is not published, and subscribers still get the whole answer or part of it: the default heartbeat settings, ABANDON, and a trip during retry backoff. The README states neither side, and the parameter docstrings say nothing.
COMMENT: there is no P1 and the code is correct where the README says it works, but the topic contract this PR introduces should be fixed or documented before merge (the P2 and the README comment below), and the body still lists its open questions as open.
Cross-language parity. The TypeScript plugin keeps the #227 behaviour. On main, getStreamedResponse awaits invokeModelStreamActivity before yielding anything (activity-backed-model.ts:152-169); the activity publishes each event as it arrives (activities.ts:182); nothing cancels it on a trip; and @openai/agents-core 0.14.3 runs input guardrails in parallel with the streamed call by default (runInParallel defaults to true, runner/turnPreparation.js:90), which the plugin does not override. This is from reading the code; I did not run it. After this PR the two languages differ, and no TypeScript issue tracks it, so one is worth filing.
PR body. It still ends with 'Draft while ...', although the PR is ready for review. The 1.35.0 floor has a second reason the body does not give: draining a closed run's stream is new in 1.35.0 (see its contrib/workflow_streams README), and the waits_for_the_error_event cases and any late subscriber rely on it. With the head's source on 1.34.0, all eight of those cases fail, not only the uncached ones: four hang on the eviction bug and four read nothing. The before-and-after runs cite 68c494b and ecff357, which are no longer on the branch.
| # managers flushes the events, so publish after both, behind the events | ||
| # still buffered. Other cancels, such as a Worker shutdown or a heartbeat | ||
| # timeout, can be retried, so publish nothing and let the retry answer. | ||
| if _cancel_requested(): |
There was a problem hiding this comment.
P2: the error/cancelled event does not reliably mark the end of the call it cancels: under the default TRY_CANCEL it can land among the next model call's events, and it is published for every cancel the workflow requests, including a ModelSettings.timeout that a ModelSettings.retry then answers. The event carries only code, message and sequence_number=len(events). A Temporal cancel request has no reason, so _cancel_requested() (lines 407-410) cannot tell a trip from any other workflow-side cancel, and a subscriber cannot tell which call the event ends. Two probes at the head, each run twice. (a) A workflow catches the tripwire and streams a reply from a guardrail-free agent on the same topic (TRY_CANCEL, heartbeat_timeout=3s). The stub raises as soon as it requests the cancel, and the old activity hears of it at its next heartbeat, by which time the reply is streaming. The topic read delta 'Hello ' (old), delta 'Hello ' (reply), error, delta 'world!' (reply), response.completed (reply), and the stale event's sequence_number (1) equals the reply's second delta. (b) No guardrails, ModelSettings(timeout=2.0, retry=ModelRetrySettings(max_retries=2, policy=retry_policies.network_error())), and a model that holds 8 s on its first call. The framework's timeout cancels the attempt, the activity publishes the event, and the retry's new activity publishes a whole answer. The topic read delta, error/cancelled, delta, delta, response.completed, and the run returned Hello world!, which contradicts the rationale at README lines 840-842. In both, a subscriber that stops at error cuts off or fails a real answer. README lines 837-838 treat it as the end of the stream ('see the stream end without the event'), and the PR's own collect_until_the_end stops there (test line 681). RunResultStreaming.cancel() also publishes it (probe: delta, error/cancelled); workflow cancellation requests the same cancel but usually closes the run before the activity hears of it. That is reasonable, since the call does end, but neither the README nor the release-notes guidance in the body mentions it. Fix: make the event attributable, for example the response ID from response.created when one was seen, or the activity ID in param. Then say in the README and in this activity's docstring that the event follows any cancel the workflow requests while the run is open (guardrail trip, RunResultStreaming.cancel(), ModelSettings.timeout), that it ends one model call rather than the run, that a framework retry or a later call can publish after it, and that WAIT_CANCELLATION_COMPLETED keeps it ahead of the next call. Reword the retry rationale at 840-842 to match.
There was a problem hiding this comment.
You're right, and the README even treated it as the end of the stream. I made two changes:
paramnow holds the ID from the call'sresponse.created, so a subscriber can tell which response the event ends. It's empty if the cancel comes beforeresponse.created, and Chat Completions and LiteLLM models send__fake_id__for every call. The README says both.- The README and the activity's docstring now document the rest: the event ends one model call, not the run; any cancel the workflow requests publishes it (a trip,
RunResultStreaming.cancel(), aModelSettings.timeout); a retry or a later call can publish after it; and WAIT_CANCELLATION_COMPLETED keeps it ahead of the next call. The retry rationale now covers only the cancels Temporal makes on its own.
Then I reran your two probes as throwaway tests, with a model that sends response.created:
- (a) A trip, then a reply on the same topic. With TRY_CANCEL:
created(resp_1), delta, created(resp_2), delta, delta, response.completed, error(resp_1). With WAIT_CANCELLATION_COMPLETED:created(resp_1), delta, error(resp_1), created(resp_2), delta, delta, response.completed. - (b) A
ModelSettings.timeoutanswered by a retry:created(resp_1), delta, error(resp_1), created(resp_2), delta, delta, response.completed, and the run returnsHello world!.
| sequence_number=len(events), | ||
| ) | ||
| ) | ||
| await stream.flush() |
There was a problem hiding this comment.
P3: if publishing the event fails, that error replaces the CancelledError, so the attempt is recorded and logged as a failure instead of a cancellation. WorkflowStreamClient.flush() re-raises the first signal failure, and here it runs unprotected inside except asyncio.CancelledError:, so the bare raise at 554 is skipped. Probes at the head: (a) TRY_CANCEL, the workflow returns 4 s after the trip, and the cancelled activity's publish is held back. The signal raised RPCError('workflow execution already completed') with cancel_requested=True, and the Worker logged WARNING Completing activity as failed ... RPCError(...). (b) WAIT_CANCELLATION_COMPLETED with an injected UNAVAILABLE on that signal. History ended in ActivityTaskFailed (retry_state=7, 'injected unavailable') where ActivityTaskCanceled was expected; the workflow still returned refused through cancelled_for. Both need a narrow window (the hold-back in (a) was artificial), so this is noise rather than a wrong result. Fix: make the publish best effort and keep the bare raise after it, e.g. wrap the async with heartbeating(): block in try: ... except Exception: activity.logger.debug("Could not publish the cancelled event", exc_info=True).
There was a problem hiding this comment.
Good catch. I made the publish best effort, as you suggested: the publish and flush now sit in a try/except Exception that logs at debug level, and the bare raise stays after it.
To check it, I wrote a throwaway test close to your (b): WAIT_CANCELLATION_COMPLETED, a trip, and a publish signal that fails once the cancel is requested. With the activity you reviewed, History ends in ActivityTaskFailed. With the fix, it ends in ActivityTaskCanceled. The run returns refused both times.
| trips while the model is streaming, the plugin cancels the streaming | ||
| activity, and the run raises `InputGuardrailTripwireTriggered` as | ||
| `stream_events()` does. The cancel reaches the activity through its | ||
| heartbeat, so set `heartbeat_timeout`: the activity then stops and |
There was a problem hiding this comment.
P3: three configurations get none of the fix, and only the first is hinted at here. (a) Default parameters. heartbeat_timeout defaults to None, so heartbeating() starts no task and the cancel never reaches the activity. Probe at the head with the PR's StreamingInputGuardrailWorkflow and HoldingStreamingModel(hold=4), and no heartbeat_timeout: the run returned refused, and the topic got delta, delta, response.completed. That is the #227 symptom, which the issue says occurs 'with or without heartbeat_timeout'. This line says to set it, but the heartbeat_timeout, cancellation_type and streaming_topic docstrings in _model_parameters.py (lines 51-61 and 75-88), where the option is set, do not. (b) cancellation_type=ABANDON. handle.cancel() sends no cancel request, so with heartbeat_timeout=3s the topic still got delta, delta, response.completed and History had no ActivityTaskCancelRequested, while line 822 says the plugin cancels the activity. (c) A trip while the activity is in retry backoff. Attempt 1 published a delta and failed, the guardrail tripped during the 6 s backoff, and the server cancelled the activity without starting attempt 2. Under both TRY_CANCEL and WAIT_CANCELLATION_COMPLETED, the topic ended at that one delta with no terminal event; main streamed a whole answer on attempt 2. Fix: list the three cases next to 'If the activity has already returned' (830-831). Put the heartbeat_timeout requirement in that field's docstring, and the TRY_CANCEL/WAIT_CANCELLATION_COMPLETED trade-off in cancellation_type's. Consider a one-time workflow.logger warning when a streamed run with parallel input guardrails has no heartbeat_timeout. On the first open question: heartbeating without a timeout would deliver the cancel only at the 30 s default throttle, later than many responses take to stream, so documenting and warning looks like the better trade.
There was a problem hiding this comment.
The README now lists all three next to the "already returned" case: no heartbeat_timeout, ABANDON, and a trip during retry backoff. The heartbeat_timeout docstring says streaming needs it for the cancel, and cancellation_type's explains the trade-off between TRY_CANCEL, WAIT_CANCELLATION_COMPLETED and ABANDON.
I reran (a) and (b) as throwaway tests and got the same as you: refused, with delta, delta, response.completed on the topic. I didn't rerun (c); that one comes from your probe.
What about the warning? I left it out to keep this PR small, but I'm happy to add it in a follow-up if you think it's worth it. And I agree on the first open question: no heartbeats without a timeout. I took it out of the body.
| """Return the streamed run in progress and its parallel input guardrails task, if any.""" | ||
| streamed_run = _current_streamed_run.get() | ||
| result = streamed_run.result if streamed_run is not None else None | ||
| task = result._input_guardrails_task if result is not None else None |
There was a problem hiding this comment.
P3: the private fields are read with plain attribute access on every streamed model call, so a rename in a later 0.22.x would fail the Workflow Task of every streamed run, not only runs with guardrails. 0.22.3, the newest release openai-agents>=0.22,<0.23 allows, still has _input_guardrails_task and _triggered_input_guardrail_result (agents/result.py:647-648), and its run_input_guardrails_with_queue is byte-identical to 0.22.0, so this is fine today. But deployments resolve the newest 0.22.x without the plugin's lock, and an AttributeError raised here is not a Temporal failure, so the task retries until the dependency is pinned back. On the second open question: reading them is reasonable under the pin if a rename degrades to the pre-PR behaviour, for example getattr(result, "_input_guardrails_task", None) here and getattr(..., "_triggered_input_guardrail_result", None) at 357 and 384-388. Add one test asserting both attributes exist, so the nightly latest-dependencies run names the rename directly.
There was a problem hiding this comment.
Agreed. The stub now reads both fields with getattr(..., None), so a rename turns the cancel off (the behavior before this PR) instead of failing every streamed run.
Instead of a new test, the trip test now starts by checking that RunResultStreaming still has both fields. So a rename fails it by name, in the nightly run too. That answers the second open question, so I took it out of the body.
| if guardrails is not None: | ||
| triggered = guardrails[0]._triggered_input_guardrail_result | ||
| if triggered is not None: | ||
| raise InputGuardrailTripwireTriggered(triggered) |
There was a problem hiding this comment.
P3: this raise runs inside the framework's model retry wrapper, so a user's ModelSettings.retry policy is consulted for a guardrail trip, which never happens natively. stream_response_with_retry calls the stub through get_stream and hands any Exception to the policy. Natively, the trip is raised by before_side_effects, outside that wrapper. Probe at the head: an agent with ModelSettings(retry=ModelRetrySettings(max_retries=3, policy=lambda ctx: True)), plus the PR's refuse_after_a_second and DelayModelCall. No activity was scheduled, but the stub was re-invoked three times with backoff timers before the tripwire surfaced: refused 5.1 s after the run started, with five timers in History instead of two. The mid-stream raise at 398 is not retried, because its __context__ (the ActivityError caused by the cancel) makes the framework treat it as an abort. Putting a cancel in this raise's chain too would apply the same veto; otherwise a README note is enough.
There was a problem hiding this comment.
I went with the code fix, since in a native run the policy never sees a trip. But instead of a fake cancel in the chain, the model stub now overrides get_retry_advice. For InputGuardrailTripwireTriggered, it returns ModelRetryAdvice(normalized=ModelRetryNormalizedError(is_abort=True)). The framework treats an abort as a hard veto before it asks the policy, so this also covers the mid-stream raise without relying on its __context__.
The known-trip test now gives the agent a policy that retries every error. Without the change, it fails with refused after asking to retry 3 times.
… be published If publishing the error event failed, that error replaced the CancelledError, so the attempt was recorded as failed, not cancelled. Publish it best effort and log the failure at debug level.
…re renamed The model stub read RunResultStreaming._input_guardrails_task and _triggered_input_guardrail_result with plain attribute access on every streamed model call, so a rename in a later openai-agents 0.22.x would fail the Workflow Task of every streamed run. Read them with getattr, so a rename only turns off the guardrail cancel, and assert in the trip test that both fields exist, so a rename fails that test by name.
…uardrail trip When a parallel input guardrail had already tripped, the model stub raised InputGuardrailTripwireTriggered inside the framework's model retry loop, so a ModelSettings.retry policy was asked about it and could call the stub again with backoff timers. Natively the trip is raised outside that loop. The stub's get_retry_advice now marks the trip as an abort, which the framework never retries. The known-trip test gives the agent a policy that retries every error and checks it is never asked.
… apply The README now lists the cases where subscribers still get the whole answer (no heartbeat_timeout, ABANDON, an activity that already returned) and a trip during retry backoff. It says the error event ends one model call, not the run: any cancel the workflow requests publishes it, including RunResultStreaming.cancel() and a ModelSettings.timeout that a ModelSettings.retry answers. The heartbeat_timeout and cancellation_type docstrings and the streaming activity's docstring say the same.
The cancelled error event carried only a code, a message and a sequence number, so a subscriber could not tell which model call it ended: with TRY_CANCEL it can land among a later call's events, and a ModelSettings.retry can answer after it. Put the ID from the call's response.created event in its param. The README says when param is empty, that Chat Completions and LiteLLM models send the same placeholder ID for every call, and that WAIT_CANCELLATION_COMPLETED keeps the event ahead of the next model call's events.
|
Thanks for the thorough review, DABH! I answered each thread in place. Here's the rest:
I pushed five new commits on top of the head you reviewed, with no force-push. |
|
One decision before 2.0: |
|
Good catch, Jason. You're right: with the default settings, this PR records the cancel, but the activity never hears about it, so subscribers still get the whole answer. I'd like to keep this PR as it is and fix it in a follow-up that lands before the 2.0 release. When Does that work for you? |
…#496) ## What was changed `ModelActivityParameters.heartbeat_timeout` now defaults to 10 seconds instead of `None`, so both model activities (`invoke_model_activity` and `invoke_model_activity_streaming`) heartbeat by default. - The model activities already heartbeat on a timer at half the timeout, so they don't change. - A timeout you set wins, and `heartbeat_timeout=None` turns heartbeats off, as before. - The README's guardrail section from #228 said `heartbeat_timeout` isn't set by default, so the cancel needs you to set it. It now says the default is 10 seconds, and that `None` turns the cancel off. - The `heartbeat_timeout` docstring said it detects "a stuck model call". It doesn't: the timer keeps beating while a model call hangs. It now says what the heartbeats do. A comment in `_TemporalModelStub.stream_response` made the same claim, so I fixed it too. Local activities (`use_local_activity=True`) don't take a heartbeat timeout, and still don't get one. ## Why? Without a heartbeat timeout, the model activities never heartbeat. So a cancel never reaches a running model call, and the model keeps generating until it's done. A lost worker also goes unnoticed until the 60-second start-to-close timeout. Jason pointed out on #228 that this makes the guardrail fix there do nothing with the defaults: the Workflow records the cancel, but the activity never hears it. Why 10 seconds? #491 has the measurements. Does this break anything? Not replay: when core replays a scheduled Activity, it only compares its ID and type (#491 has the check), and the replay tests pass. But a model call that didn't set `heartbeat_timeout` now heartbeats, which in Temporal Cloud is at most one Action every 8 seconds of a running call. And a Worker whose event loop blocks for about 10 seconds now fails the call with a heartbeat timeout, and retries it. ## Checklist 1. Closes #495 2. How was this tested: - `test_heartbeat` now runs three cases and reads the model activity's heartbeat timeout from History: `set` (0.5 seconds, which passes only if the activity heartbeats, since the model takes a second), `default` (10 seconds) and `off` (`None`, no heartbeat timeout). Without the change, `default` fails with `assert [None] == [datetime.timedelta(seconds=10)]`. - Locally, `make test` (626 passed, 2 skipped), `make lint` and the conventions check pass, on Python 3.12 with uv 0.12.24. 3. Any docs updates needed? The docstring and the README are updated here. Release notes should mention the new default, and how to turn it off.
…beat timeout (#514) ## What was changed The model Activities (`invokeModelActivity` and `invokeModelStreamActivity`) now get a 10-second `heartbeatTimeout` by default. It sits in `DEFAULT_MODEL_ACTIVITY_OPTIONS`, next to the 60-second `startToCloseTimeout`. - The Activities already heartbeat on a timer (`startAdaptiveHeartbeat`) at half the timeout. - That timer now sends its first heartbeat half the timeout into the call, instead of right away, like the Vercel AI SDK, Google ADK and Strands plugins. So a call that ends sooner sends none. - A `heartbeatTimeout` you set wins, in the plugin's `modelParams` or in the runner's `defaultModelParams`. `heartbeatTimeout: 0` turns heartbeats off. - `ModelActivityOptions` now documents `heartbeatTimeout`: what the default does, how to turn it off, and how much time the Worker's startup and heartbeat encoding get. The README says the same, next to the `modelParams` example. Local Activities (`useLocalActivity: true`) don't take a heartbeat timeout, and still don't get one. The stateful MCP session uses the same timer. It sends its own heartbeat when it starts, so it still heartbeats right away. Only the timer's first beat, a repeat with the same details, moves later. Its tests pass, including the slow connect and heartbeat timeout ones. ## Why? Without a heartbeat timeout, the model Activities never heartbeat. So a cancel never reaches a running model call, and a lost Worker goes unnoticed until the 60-second start-to-close timeout. #491 has the details, and the measurements behind 10 seconds. #496 makes the same change in Python. Why wait before the first heartbeat? The heartbeat timeout already counts from the start of the attempt, so a heartbeat right away adds nothing. Waiting means a call shorter than 5 seconds sends no heartbeat, and doesn't pay for one. What's the catch? The first heartbeat has to reach the server within the timeout. It goes out half the timeout after the Activity starts, and the Worker encodes it with your payload codecs first. So the Worker's startup work for the attempt (interceptors and payload decoding) plus that encoding must fit in the other half: under 5 seconds with the default. A slower setup, like a codec that calls a remote key service, needs a `heartbeatTimeout` of more than twice that time, or `0`. The docs say so. So does a cancel stop the model call now? Not yet. The cancel reaches the Activity, but the Activity doesn't pass it to the model, so the call still runs to the end. That's #503. A fix for #428 (the TypeScript side of #227, which #228 fixes in Python) needs both. Does this break anything? Not replay: when core replays a scheduled Activity, it only compares its ID and type. I recorded a model call on `main`, with no heartbeat timeout, and it replays fine with this change. But a model call that didn't set `heartbeatTimeout` now heartbeats once it runs past 5 seconds. In Temporal Cloud, that's at most one Action every 8 seconds from then on. A Worker whose event loop is blocked for about 10 seconds now fails the call with a heartbeat timeout, and retries it. If interceptors, payload decoding or a payload codec take a large part of the timeout, raise `heartbeatTimeout`. ## Checklist 1. Closes #513 2. How was this tested: - Two tests now read the model Activities' heartbeat timeout from History, and expect 10 seconds: `agent.asTool() runs take the run model, model settings and runner defaults` (four `invokeModelActivity` calls, with a runner `defaultModelParams` that doesn't set one) and `Streaming: external subscriber and in-workflow result see the same events` (`invokeModelStreamActivity`, with a client `modelParams` that doesn't set one). Without the default, they fail with `- 0 + 10`. - The `layerModelParams` tests check the 10-second default, and that a `0` from the runner or the client wins over it. - The credentials test that checked the timer already runs while the callback waits is now `the Activity heartbeats while the callback is asked for credentials, and a quick call sends none`. With a 200 ms timeout, a quick call sends no heartbeat, and a call whose callback takes 350 ms sends at least two. With the old timer, the quick call fails with `- 1 + 0`. - The new `A model call slower than its heartbeat timeout completes on its first attempt` runs a 2.5-second call with a 1-second heartbeat timeout, and it finishes on its first attempt. - I also ran a 6-second model call with `heartbeatTimeout` unset, `0`, `'0s'` and `'3s'`, and read History, `activityInfo().heartbeatTimeoutMs` and, 5.5 seconds in, the pending Activity's last heartbeat: ``` PROBE modelParams=null history.heartbeatTimeout=10s+0ns activityInfo.heartbeatTimeoutMs=10000 pending.lastHeartbeatTime=set PROBE modelParams={"heartbeatTimeout":0} history.heartbeatTimeout=0s+0ns activityInfo.heartbeatTimeoutMs=0 pending.lastHeartbeatTime=none PROBE modelParams={"heartbeatTimeout":"0s"} history.heartbeatTimeout=0s+0ns activityInfo.heartbeatTimeoutMs=0 pending.lastHeartbeatTime=none PROBE modelParams={"heartbeatTimeout":"3s"} history.heartbeatTimeout=3s+0ns activityInfo.heartbeatTimeoutMs=3000 pending.lastHeartbeatTime=set ``` - With the scheduled-time math gone, in a Docker image with Node 24: `pnpm run lint` (0 errors; the 8 warnings are existing ones), and the credentials and model test files (22 passed). CI runs the full suite. 3. Any docs updates needed? The `heartbeatTimeout` JSDoc and the README's `modelParams` section are updated here, including the time budget for startup and heartbeat encoding. Release notes should mention the new default, how to turn it off, and that slow codecs need a larger timeout.
What was changed
When a parallel input guardrail trips on the streaming route, the plugin now cancels the streaming model activity. So stream topic subscribers stop getting the answer.
If the guardrail trips while the streaming model activity runs,
_TemporalModelStub.stream_responsecancels the activity. The run still raisesInputGuardrailTripwireTriggered, as before.If the guardrail has already tripped when the model is called, the activity never starts.
The stub acts on the trip as soon as the framework records it. It doesn't wait for the other parallel guardrails to finish their cleanup.
When the workflow cancels it,
invoke_model_activity_streamingpublishes anerrorevent (ResponseErrorEvent, codecancelled) to the topic and stops.errorevent comes after the buffered events.RunResultStreaming.cancel()and aModelSettings.timeout. So it ends one model call, not the run.paramis the ID from the call'sresponse.createdevent, when the model sent one, so subscribers can tell which response it ends. Chat Completions and LiteLLM models send the same placeholder ID (__fake_id__) for every call.errorevent, because the activity's retry can still answer.To cover the heartbeat cleanup, the streaming activity no longer uses
auto_heartbeater. It usesheartbeating()inside its cancellation handling instead: a context manager I took out of the decorator.auto_heartbeateruses the same context manager, so other activities don't change.To watch the run's guardrails, the runner hands the streamed run to the model stub through a context variable. The stub reads
RunResultStreaming._input_guardrails_taskand_triggered_input_guardrail_resultwithgetattr. If a lateropenai-agentsrenames them, the cancel turns off instead of every streamed run failing.The stub raises a trip it already knows about inside the framework's model retry loop. So its
get_retry_advicemarks the trip as an abort, and aModelSettings.retrypolicy is never asked about it, as in a native run.This change needs
temporalio1.35.0 or later.mainalready requires 1.36.0, so this PR doesn't change the floor or the lock. Why does it need 1.35.0? Two reasons:WAIT_CANCELLATION_COMPLETEDmode and is then evicted never finishes the eviction (Eviction processed, but 2 tasks remain), and Worker shutdown hangs. 1.35.0 fixes this SDK bug, and this change makes that cancel automatic.errorevent after the workflow returns.The README's streaming section says what subscribers now get, and that the cancel needs
heartbeat_timeout. It also says:heartbeat_timeout,ABANDON, or an activity that already returned;errorevent ends one model call, not the run, what itsparamholds, and that it comes afterresponse.completedwhen the model had already finished;TRY_CANCEL, a workflow that completes right after the trip can close before theerrorevent is published, or stream more events before it. WithWAIT_CANCELLATION_COMPLETED, the run raises only after the event is published, which keeps it ahead of the next model call's events.The
heartbeat_timeoutandcancellation_typedocstrings say the same.No public names or options change.
Breaking change: the cancel request is a new command, and not starting the activity drops one. There's no version gate: we're not adding version gates to these fixes.
temporalio-openai-agentsalready shipped 1.0.0 and 1.1.0, so this break needs its next major release, 2.0.0.Which runs break? A streamed run in which a parallel input guardrail tripped before this version recorded no cancel, so its replay now fails:
[TMPRL1100].[TMPRL1100]or with the SDK core'sFatal error in workflow machines: ActivityMachine in state ScheduledActivityCancelCommandCreated says the transition is invalid during event ... ActivityTaskStarted, depending on the History.Streamed runs whose guardrails didn't trip, and runs that don't stream, are fine.
Rolling back breaks too. A streamed run in which a guardrail tripped on this version recorded a cancel, so an earlier version fails its replay with
[TMPRL1100] Nondeterminism error: No command scheduled for event HistoryEvent(id: 15, ActivityTaskCancelRequested).In the first review round, DABH recorded streamed runs on
mainand replayed them on this branch, and the reverse, with these results.Upgrade: let open streamed runs in which a parallel input guardrail tripped finish on the earlier version before you upgrade, or keep them there with Worker Versioning. Don't roll a Worker back to 1.x while streamed runs in which a guardrail tripped on 2.0 are open: they'd fail replay there.
There are many commits here, so please review the combined diff against
main.Why?
See #227. The streaming activity publishes each event to the topic as the model sends it. But the workflow only yields the events after the activity returns, so the framework's per-event guardrail check never gated the topic. A subscriber got the whole answer to a rejected request,
response.completedincluded.Checklist
Closes [Bug] openai_agents: stream topic subscribers get the rest of the answer after a parallel input guardrail trips #227
How was this tested:
New tests in
tests/test_openai_streaming.py:test_streaming_input_guardrail_trip_stops_the_topic[alone|sibling-cleaning-up]: a parallel guardrail trips after one second while the fake model holds after its first delta. In the second case, another guardrail takes 12 s to clean up. The subscriber's last event is thecancellederror, with the response ID from the model'sresponse.createdinparam, and there's noresponse.completed. The model's stream was cancelled. The test first checks thatRunResultStreamingstill has the two private fields the stub reads.test_streaming_input_guardrail_known_trip_skips_the_model[alone|sibling-cleaning-up]: a guardrail trips while an agent hook delays the model call. No streaming activity is scheduled, and the agent'sModelSettings.retrypolicy, which retries every error, is never asked.test_streaming_input_guardrail_trip_waits_for_the_error_event[streaming|publishing|stopping-the-flusher|stopping-the-heartbeats]-[cached|uncached]: withWAIT_CANCELLATION_COMPLETED, a workflow returns right after the trip and the Worker shuts down, with or without a Workflow cache. The stream's last event is theerrorevent. Each case moves the cancel to a different moment:streaming: the model holds after its first delta, so the stream has that delta and theerrorevent.publishing: the model finishes at once, but the stream's publish signals are held for 8 s, so the cancel arrives during the activity's final flush.stopping-the-flusher: the background flusher's first publish hangs until it's cancelled and then takes 8 s to clean up, so the cancel arrives while the stream stops the flusher.stopping-the-heartbeats: the heartbeat task takes 8 s to stop and keeps heartbeating meanwhile, so the cancel arrives while the activity stops its heartbeats.In the last three, the stream has two deltas,
response.completedand theerrorevent.test_streaming_worker_shutdown_publishes_no_error_event: the Worker shuts down while the model streams, and the retry on a new Worker answers. The topic gets noerrorevent.Do the tests catch the bugs? Here's what they do without each part of this change:
sibling-cleaning-upcases, the Worker shutdown test, and the uncachedwaits_for_the_error_eventcase (Eviction processed, but 2 tasks remain, pytest timeout). The other new cases pass.waits_for_the_error_eventcases fail. DABH found this in the first review round. The four uncached ones hang on the eviction bug, and the four cached ones read nothing, because 1.34.0 can't read a closed run's stream. On 1.35.0 they pass.publishingcases fail: the stream has noerrorevent. Thestreamingcases pass.stopping-the-flushercases fail: the stream's last event isresponse.completed. Thestreamingandpublishingcases pass.stopping-the-heartbeatscases fail: the stream's last event isresponse.completed.get_retry_advice, both known-trip cases fail:refused after asking to retry 3 times. Without the response ID, both trip cases fail:paramisNone.I also ran some throwaway probes on this branch that aren't in the tests:
heartbeat_timeout, or withABANDON, a tripped run's topic getsdelta, delta, response.completed.errorevent (with the first response's ID) comes after the reply'sresponse.completedwithTRY_CANCEL, and before the reply withWAIT_CANCELLATION_COMPLETED.ActivityTaskCanceled. Before the publish was best effort, it ended inActivityTaskFailed.And a few more checks:
A throwaway run with
TRY_CANCELand a workflow that returns right after the trip had only the delta in its stream, with and without a Workflow cache. That's the caveat the README describes.Locally,
make lintandmake testpass (458 tests). I ran them in Docker with Python 3.13 and uv 0.12.24.On
main, an earlier version of the trip test failed:assert 'response.completed' not in [...].A History of the trip test recorded on
main(the guardrail tripped mid-stream, the activity ran to completion, no cancel) fails replay with the first version of this fix:[TMPRL1100] Nondeterminism error: Activity machine does not handle this event: HistoryEvent(id: 28, WorkflowExecutionUpdateCompleted). That's the breaking change above, so it's not in the tests.[Bug] openai_agents: stream topic subscribers get the rest of the answer after a parallel input guardrail trips #227's reproduction exits 1 on 1.1.0 and on
main. With the first version of this fix, it exits 0 with the same four deltas a native consumer got:Any docs updates needed?
The README is updated here. Release notes should mention the cancel, the
errorevent on the topic, and which runs stop replaying (see "Breaking change").Not covered:
heartbeat_timeout, or withABANDON, the activity never hears about the cancel and keeps publishing until the model finishes. A trip during retry backoff leaves the failed attempt's events on the topic, with noerrorevent. The README says so.response.completed. We can't avoid this race, and the README says so too.errorevent, I only tested Worker shutdown, not pause or reset.temporalio1.34.x still bundles the old code astemporalio.contrib.openai_agents. A backport is a separate decision.