Skip to content

Breaking: stop the OpenAI Agents streaming model activity when a parallel input guardrail trips - #228

Merged
campoy merged 14 commits into
mainfrom
fix/openai-agents-python-stream-continues-after-tripwire
Nov 13, 2026
Merged

campoy merged 14 commits into
mainfrom
fix/openai-agents-python-stream-continues-after-tripwire

Conversation

@campoy

@campoy campoy commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

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_response cancels the activity. The run still raises InputGuardrailTripwireTriggered, 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_streaming publishes an error event (ResponseErrorEvent, code cancelled) to the topic and stops.

    • It does this even when the cancel arrives after the model finished: while the activity is still publishing its events, stopping the stream's background flusher, or stopping its heartbeats. Then the error event comes after the buffered events.
    • Any cancel the workflow requests publishes it, including RunResultStreaming.cancel() and a ModelSettings.timeout. So it ends one model call, not the run.
    • Its param is the ID from the call's response.created event, 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.
    • Cancels that Temporal makes on its own (Worker shutdown, heartbeat timeout) publish no error event, because the activity's retry can still answer.
    • Publishing it is best effort. If the publish fails, the activity still reports the cancel.
  • To cover the heartbeat cleanup, the streaming activity no longer uses auto_heartbeater. It uses heartbeating() inside its cancellation handling instead: a context manager I took out of the decorator. auto_heartbeater uses 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_task and _triggered_input_guardrail_result with getattr. If a later openai-agents renames 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_advice marks the trip as an abort, and a ModelSettings.retry policy is never asked about it, as in a native run.

  • This change needs temporalio 1.35.0 or later. main already requires 1.36.0, so this PR doesn't change the floor or the lock. Why does it need 1.35.0? Two reasons:

    • With 1.34.0, a workflow that cancels an activity in WAIT_CANCELLATION_COMPLETED mode 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.
    • Only 1.35.0 lets a subscriber read the stream of a closed run. A subscriber needs that to get the error event after the workflow returns.
  • The README's streaming section says what subscribers now get, and that the cancel needs heartbeat_timeout. It also says:

    • when subscribers still get the whole answer: no heartbeat_timeout, ABANDON, or an activity that already returned;
    • what a trip during retry backoff leaves on the topic;
    • that the error event ends one model call, not the run, what its param holds, and that it comes after response.completed when the model had already finished;
    • that with the default TRY_CANCEL, a workflow that completes right after the trip can close before the error event is published, or stream more events before it. With WAIT_CANCELLATION_COMPLETED, the run raises only after the event is published, which keeps it ahead of the next model call's events.

    The heartbeat_timeout and cancellation_type docstrings 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-agents already 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:

  • If the guardrail tripped before the model call, it fails with [TMPRL1100].
  • If it tripped while the model streamed, it fails with [TMPRL1100] or with the SDK core's Fatal 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 main and 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.completed included.

Checklist

  1. Closes [Bug] openai_agents: stream topic subscribers get the rest of the answer after a parallel input guardrail trips #227

  2. 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 the cancelled error, with the response ID from the model's response.created in param, and there's no response.completed. The model's stream was cancelled. The test first checks that RunResultStreaming still 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's ModelSettings.retry policy, 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]: with WAIT_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 the error event. Each case moves the cancel to a different moment:

      • streaming: the model holds after its first delta, so the stream has that delta and the error event.
      • 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.completed and the error event.

    • 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 no error event.

    Do the tests catch the bugs? Here's what they do without each part of this change:

    • The first version of this fix, on temporalio 1.34.0, fails the sibling-cleaning-up cases, the Worker shutdown test, and the uncached waits_for_the_error_event case (Eviction processed, but 2 tasks remain, pytest timeout). The other new cases pass.
    • With this change but temporalio 1.34.0, all eight waits_for_the_error_event cases 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.
    • Before the activity handled a cancel during its final flush, both publishing cases fail: the stream has no error event. The streaming cases pass.
    • Before it handled a cancel while stopping the flusher, both stopping-the-flusher cases fail: the stream's last event is response.completed. The streaming and publishing cases pass.
    • Before it handled a cancel while stopping the heartbeats, both stopping-the-heartbeats cases fail: the stream's last event is response.completed.
    • Without get_retry_advice, both known-trip cases fail: refused after asking to retry 3 times. Without the response ID, both trip cases fail: param is None.

    I also ran some throwaway probes on this branch that aren't in the tests:

    • With no heartbeat_timeout, or with ABANDON, a tripped run's topic gets delta, delta, response.completed.
    • When the workflow catches the trip and streams a reply on the same topic, the error event (with the first response's ID) comes after the reply's response.completed with TRY_CANCEL, and before the reply with WAIT_CANCELLATION_COMPLETED.
    • With a publish that fails after the cancel, History ends in ActivityTaskCanceled. Before the publish was best effort, it ended in ActivityTaskFailed.

    And a few more checks:

    • A throwaway run with TRY_CANCEL and 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 lint and make test pass (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:

      subscriber got: ['part 0 ', 'part 1 ', 'part 2 ', 'part 3 ', 'error']
      
  3. Any docs updates needed?

    The README is updated here. Release notes should mention the cancel, the error event on the topic, and which runs stop replaying (see "Breaking change").

Not covered:

  • Without heartbeat_timeout, or with ABANDON, 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 no error event. The README says so.
  • A cancel that reaches the Worker after the activity has returned leaves the stream ending at response.completed. We can't avoid this race, and the README says so too.
  • Of the cancels that publish no error event, I only tested Worker shutdown, not pause or reset.
  • temporalio 1.34.x still bundles the old code as temporalio.contrib.openai_agents. A backport is a separate decision.
  • The TypeScript plugin has the same defect. [Bug] openai-agents (TypeScript): stream topic subscribers get the rest of the answer after a parallel input guardrail trips #428 tracks it.

@campoy

campoy commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor Author

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 main with the new workflow. The plugin code didn't change.

Locally, the test now passes 5 runs out of 5 on Python 3.13 and on 3.14, and it still fails on main with assert 'response.completed' not in [...]. Without its gate, the fix now fails the replay test with [TMPRL1100] Nondeterminism error. CI passes in every cell.

@campoy campoy changed the title openai_agents: stop the streaming model activity when a parallel input guardrail trips Breaking: stop the OpenAI Agents streaming model activity when a parallel input guardrail trips Oct 29, 2026
…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.
@campoy
campoy force-pushed the fix/openai-agents-python-stream-continues-after-tripwire branch from f400ce4 to b8a943e Compare October 31, 2026 18:30
@campoy
campoy marked this pull request as ready for review October 31, 2026 19:27
@campoy
campoy requested a review from a team as a code owner October 31, 2026 19:27

@DABH DABH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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():

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2: 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.

@campoy campoy Nov 5, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You're right, and the README even treated it as the end of the stream. I made two changes:

  • param now holds the ID from the call's response.created, so a subscriber can tell which response the event ends. It's empty if the cancel comes before response.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(), a ModelSettings.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.timeout answered by a retry: created(resp_1), delta, error(resp_1), created(resp_2), delta, delta, response.completed, and the run returns Hello world!.

sequence_number=len(events),
)
)
await stream.flush()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P3: 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).

@campoy campoy Nov 5, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment thread python/openai_agents/README.md Outdated
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P3: 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.

@campoy campoy Nov 5, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P3: the 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.

@campoy campoy Nov 5, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P3: 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.

@campoy campoy Nov 5, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.
@campoy

campoy commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor Author

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.

@JasonSteving99

Copy link
Copy Markdown
Contributor

One decision before 2.0: heartbeat_timeout defaults to None, so with default settings the plugin records the new cancel command (the replay break) but the activity never hears it, and a mid-stream trip still leaks the full answer, which is #227 itself. Since 2.0 is our window to change defaults, maybe we can default heartbeat_timeout when streaming_topic is set? Either that or I do think we should bring the one-time warning into this PR.

@campoy

campoy commented Nov 12, 2026

Copy link
Copy Markdown
Contributor Author

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 streaming_topic is set and heartbeat_timeout isn't, the streaming model activity will get a 10-second heartbeat timeout. That doesn't change replay (core only compares the activity's ID and type), so it doesn't need to ride on this breaking change, and we won't need the warning.

Does that work for you?

@campoy
campoy merged commit 570ac47 into main Nov 13, 2026
15 checks passed
@campoy
campoy deleted the fix/openai-agents-python-stream-continues-after-tripwire branch November 13, 2026 00:13
campoy added a commit that referenced this pull request Nov 13, 2026
…#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.
campoy added a commit that referenced this pull request Nov 17, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] openai_agents: stream topic subscribers get the rest of the answer after a parallel input guardrail trips

3 participants