Keep a Temporal stream's partial response in the conversation when the run is cancelled

Merged
DO
2d ago
+779-42

Closes #13731

Why

A Temporal workflow that cancels a streaming run (a CancellationToken fired from a signal, or a workflow cancel) recorded ModelResponse(state='interrupted', parts=[]), although the model activity had already streamed text to the client. Outside durable execution, and per the RunCancelled docs, the partial is kept. Keeping it means waiting for the activity, so per Douwe it's opt-in; reconsidering the default for V3 is #14487.

New public surface

None.

User-visible behavior

TemporalDurability(
    model_activity_config=ActivityConfig(cancellation_type=ActivityCancellationType.WAIT_CANCELLATION_COMPLETED),
)
...
except RunCancelled as exc:
    exc.all_messages()[-1]
    # before: ModelResponse(parts=[], state='interrupted')
    # after:  ModelResponse(parts=[TextPart('The partial reply')], state='interrupted')
  • Default (TRY_CANCEL): unchanged. The cancel is instant, the partial is lost, and the activity fails on the cancellation as before.
  • Opted in (WAIT_CANCELLATION_COMPLETED on the model activity): the workflow schedules the streamed model activity with a pydantic-ai-keep-partial-on-cancel header (added by PydanticAIPlugin), and on a cancel request (not a worker shutdown, pause, reset or heartbeat timeout) that activity returns what it streamed. When a CancellationToken, a workflow cancel or asyncio.wait_for cancels the run, the workflow attaches the result to the original CancelledError and still raises it, and the run records the partial through the existing interrupted-response path. The wait costs up to 0.8 x heartbeat_timeout (~24 s by default).
  • The opted-in cancellation type applies to every cancel, deadlines included: a request_timeout (and so ModelFallback) and a run's timeout= wait for the activity as they do on main.
  • The opted-in changes sit behind workflow.patched('pydantic_ai:stream_cancel_partial'), which is only checked for an opted-in stream: default-config runs issue exactly today's commands, and histories recorded by opted-in runs before this change replay as recorded.

Verification

  • Reproduction: CI run 45518226664 on the test-only commit 0ad1da664b fails with [] == [TextPart('The partial reply')].
  • tests/durable_exec/temporal/test_agent.py:
    • test_temporal_run_cancelled_by_signal_loses_streamed_partial_by_default: parts=[], the run raises within 5 s of workflow time, no patch marker, and the model activity is scheduled with main's input (2 payloads) and no header.
    • test_temporal_run_cancelled_by_signal_keeps_streamed_partial_response and test_temporal_workflow_cancel_keeps_streamed_partial_response: opted in, the partial is kept, usage billed once, history replays; the activity carries the header.
    • test_temporal_stream_cancellation_replays_history_recorded_without_the_partial: an opted-in history without the marker replays.
  • tests/durable_exec/temporal/test_durability.py: test_durability_opted_in_run_timeout_waits_for_the_model_activity asserts an opted-in run timeout= still waits (the activity's cancellation is recorded before the workflow completes); test_durability_request_timeout_cancels_the_model_activity is unchanged from main.
  • tests/durable_exec/test_temporal_activity_execution.py covers the result hand-over and the deadline wait; test_cancelled_model_stream_unit_fails_unless_the_engine_returns_its_output pins non-Temporal engines.

What changes for existing users

Nothing, unless they opt in. A user who already set cancellation_type=WAIT_CANCELLATION_COMPLETED on the model activity now keeps the streamed partial on a cancel; everything else, deadlines included, behaves as on main.

PR decisions

2026-11-25 · Partial reaches history through the continuation stream · iter -

  • Decision: _ContinuationStreamedResponse folds the partial attached to a cancellation that ended an unopened segment into get(), so the graph's existing interrupted-response commit (primed and lazy sites, and the wrap task's billing) records it unchanged
  • Why: ProcessEventStream pulls the stream in a child task whose anyio scope swallows the marked CancelledError, so reading the mark at the graph's commit sites (design note) would miss it; the continuation stream catches the same exception object directly
  • Source: https://github.com/pydantic/pydantic-ai/pull/14460

2026-11-25 · Patch id pydantic_ai:stream_cancel_partial · iter -

  • Decision: workflow.patched('pydantic_ai:stream_cancel_partial') gates both the WAIT_CANCELLATION_COMPLETED default and the workflow-side result read; the activity-side return is ungated
  • Why: matches existing pydantic_ai: ids; an old TRY_CANCEL workflow ignores a late activity result
  • Source: https://github.com/pydantic/pydantic-ai/pull/14460

2026-11-25 · Marker helper moved into core · iter -

  • Decision: mark_streamed_before_failing/streamed_before_failing live in pydantic_ai/models/_streamed_before_failing.py, re-exported from durable_exec/_utils
  • Why: core's continuation stream reads the mark and must not import durable_exec
  • Source: https://github.com/pydantic/pydantic-ai/pull/14460

2026-11-25 · pre-push review 1 of 3 at ff592a2286 · iter -

2026-11-25 · pre-push review 1 of 3 at ff592a2286 · iter -

  • Decision: remediated: docs latency 80% of heartbeat_timeout (verified temporalio worker/_worker.py), base elif-false branch test, usage-billed-once asserts; continuation-segment merge test not added (helper's merge path is a one-line ternary, same code as _snapshot); request_timeout latency escalated to Douwe
  • Why: tree 872c1eeccb reviewed; remediation commit 295eb9c810
  • Source: https://github.com/pydantic/pydantic-ai/pull/14460

2026-11-25 · Request deadlines don't wait for the cancelled stream activity (option B) · iter -

  • Decision: WAIT only when the run cancels (token, workflow cancel, wait_for, run timeout=); when a request deadline (request_timeout/first_event under the workflow) cancels the streamed model activity, _await_with_single_cancel raises at once and retrieves the handle's later error in a done callback, keeping TRY_CANCEL-like speed; same pydantic_ai:stream_cancel_partial gate
  • Why: AGENTS.md: leave behaviour unchanged for users not hitting the problem; request_timeout/ModelFallback users would otherwise wait up to ~24 s and keep nothing (the deadline turns the cancel into ModelRequestTimeout). Decided by webinar-aws-lambda
  • Source: https://github.com/pydantic/pydantic-ai/pull/14460

2026-11-25 · pre-push review 2 of 3 at 23d9ef7377 · iter -

2026-11-25 · pre-push review 2 of 3 at 23d9ef7377 · iter -

  • Decision: remediated: request-deadline skip only when WAIT came from the default (explicit cancellation_type keeps its wait), docs narrowed, unit test for the default wait; JournalDurability test now asserts the failed unit records parts=[]
  • Why: tree de824d0161 reviewed; remediation commit a2d0ea53c4
  • Source: https://github.com/pydantic/pydantic-ai/pull/14460

2026-11-25 · pre-push review 3 of 3 at a2d0ea53c4 · iter -

2026-11-25 · pre-push review 3 of 3 at a2d0ea53c4 · iter -

2026-11-25 · Run timeout= doesn't wait for the cancelled stream activity either · iter -

  • Decision: When the run's timeout= (RunCancellation.timed_out) or a request deadline cancels the streamed model activity under the defaulted WAIT_CANCELLATION_COMPLETED, _await_with_single_cancel raises at once (skips_wait_on_cancel predicate from the operation backend); only a CancellationToken, workflow cancel or asyncio.wait_for waits and keeps the partial; an explicit cancellation_type keeps its wait
  • Why: fallback+errors BLOCKER at a2d0ea53c4: RunTimedOut landed up to 0.8 x heartbeat_timeout (~24 s) late; same unchanged-behaviour rule as option B
  • Source: https://github.com/pydantic/pydantic-ai/pull/14460

2026-11-25 · Direct fix of reviewer blocker after review budget 3/3 · iter -

  • Decision: pushed b04bcd5a2a without a fourth pre-push review (budget exhausted); ruff/format/complexity via pre-commit
  • Why: pushing-commits skill: after the third review, remediate findings, run local checks, push; finding came from fallback+errors via aoe
  • Source: https://github.com/pydantic/pydantic-ai/pull/14460

2026-11-25 · Remaining cancel latency trade goes to Douwe · iter -

  • Decision: Open for Douwe via fallback+errors: a signal (token) or workflow cancel of a streaming run now takes up to about one heartbeat throttle (0.8 x heartbeat_timeout, ~24 s by default) instead of being immediate, in exchange for keeping the streamed partial; TRY_CANCEL in model_activity_config is the opt-out
  • Why: a behavioural default for Temporal streaming users, settled in the design but worth Douwe's explicit sign-off
  • Source: https://github.com/pydantic/pydantic-ai/pull/14460

2026-11-25 · Douwe: keeping the streamed partial is opt-in; TRY_CANCEL stays the default · iter -

  • Decision: Default stays TRY_CANCEL (instant cancel, partial lost, exactly today's commands: patched() is only checked when the streamed model activity is configured with WAIT_CANCELLATION_COMPLETED). Opt-in = cancellation_type=WAIT_CANCELLATION_COMPLETED in model_activity_config: a token, workflow cancel or wait_for then keeps the partial. Deadlines (request_timeout, run timeout=, and so ModelFallback) never wait, even when opted in. Reconsidering the default for V3 is tracked in https://github.com/pydantic/pydantic-ai/issues/14487
  • Why: Douwe's decision via agent-switchboard; supersedes the WAIT default and the explicit-setting-wins rule
  • Source: https://github.com/pydantic/pydantic-ai/issues/14487
  • Supersedes: Run timeout= doesn't wait for the cancelled stream activity either

2026-11-25 · Douwe 20:2x: unit-side interrupted end approved (option a) · iter -

  • Decision: Document that a response start can lack its end; #14460 adds the unit-side ModelResponseEndEvent(status='interrupted', response=partial) on the opted-in waiting path only; no end made up in workflow code. NOT built yet: ModelResponseStartEvent/ModelResponseEndEvent and the unit-side emitter (_response_boundary_events) exist only on #14478 (open, head 5d88aaca71), so #14460 adds the end once #14478 merges (merge main, then add)
  • Why: switchboard decisions.log line 153; fallback+errors relay of option (a)
  • Source: https://github.com/pydantic/pydantic-ai/pull/14478

2026-11-25 · docs/agent.md missing-end sentence left to the PR that adds the end · iter -

  • Decision: #14460 doesn't touch docs/agent.md; the opt-in sentence goes into #14478's missing-end paragraph with whichever PR adds the unit-side end; 'What a cancelled stream keeps' only says the history keeps the interrupted response
  • Why: the sentence is only true once the unit emits the interrupted end
  • Source: https://github.com/pydantic/pydantic-ai/pull/14478

2026-11-25 · Maintainer-decision rework, budget exhausted · iter -

  • Decision: pushed 8dd8fc6332 (opt-in rework + merge of origin/main + regenerated durable_exec_contract.json) without a fourth pre-push review; targeted checks only: ruff/format/complexity via pre-commit, durable_exec_contract.py --write; no public symbol changed, so no API-compat check
  • Why: review budget 3/3 used
  • Source: https://github.com/pydantic/pydantic-ai/pull/14460

2026-11-25 · Unit-side interrupted end ships with whichever of #14460/#14478 merges second · iter -

  • Decision: #14460 ships without the unit-side ModelResponseEndEvent(status='interrupted'); whichever of #14460 / #14478 merges second adds it on the opted-in waiting path, with its test and the docs/agent.md missing-end sentence; if #14478 merges first, webinar-aws-lambda adds it in a follow-up
  • Why: keeps #14460 unblocked by #14478, whose event types and emitter it needs (webinar-aws-lambda call, relayed to fallback+errors)
  • Source: https://github.com/pydantic/pydantic-ai/pull/14478
  • Supersedes: Douwe 20:2x: unit-side interrupted end approved (option a)

2026-11-25 · Opt-in flag can't be omitted from the activity input when default · iter -

  • Decision: stopped before building: the model-request activity input (RequestParams, a stdlib dataclass) is serialized by temporalio's pydantic converter with pydantic_core.to_json inference, which writes every dataclass field and ignores field metadata (checked: a field(metadata={'exclude_if': ...}) still serializes as false; a pydantic Field default fails); no transport field is omitted when default today (telemetry* None fields serialize as null)
  • Why: webinar-aws-lambda asked for a default-config input byte-identical to main's, or a stop if that can't be done cleanly
  • Source: https://github.com/pydantic/pydantic-ai/pull/14460

2026-11-25 · Opt-in reaches the activity through a header, not an extra argument (option A) · iter -

  • Decision: Under TRY_CANCEL the activity re-raises the cancel as on main; only an activity the workflow schedules for an opted-in stream carries the pydantic-ai-keep-partial-on-cancel header (KeepPartialInterceptor, registered by PydanticAIPlugin), and only then returns its partial. Default-config activities keep main's input (2 payloads: params, deps) and no header. Option E (an optional extra activity argument) was rejected: temporalio 1.31.0 worker/_activity.py:567 drops all arg type hints when the payload count differs from the parameter count, so default runs would decode params and deps untyped
  • Why: webinar-aws-lambda call under AGENTS.md's unchanged-behaviour rule: users who don't opt in must see exactly today's activity behaviour
  • Source: https://github.com/pydantic/pydantic-ai/pull/14460
  • Supersedes: Opt-in flag can't be omitted from the activity input when default

2026-11-25 · Header fix pushed, review budget exhausted · iter -

2026-11-25 · Merged origin/main at 0d2438c026 · iter -

  • Decision: merge commit; one conflict (temporalio.workflow import line in test_durability.py) resolved as the union of both sides' names; durable_exec_contract.json regenerated with --write; no new lines of our own, review budget exhausted (3/3), so no review
  • Why: PR conflicted with main; #14478's ModelResponseStartEvent/ModelResponseEndEvent/_response_boundary_events are not on main yet, so the unit-side end is not due in #14460
  • Source: https://github.com/pydantic/pydantic-ai/pull/14460

2026-11-25 · PR Review Checks finding: type _scheduled_model_activity · iter -

2026-11-26 · CI fix after durable review at a7b268ef6a · iter -

  • Decision: moved the reportPrivateUsage ignore back to the _Definition import (test_agent.py:127); the 2-min hang on durable-exec 3.15 and both FastMCP jobs is likely test_cancelled_model_stream_unit_fails_unless_the_engine_returns_its_output (test_durable_operation.py, the one new test those three jobs share; Temporal tests skip on 3.14+; main's 3.15 job passes): it passed the handler at run level, so the Journal unit likely never streamed and the test waited forever on its event; it now gives JournalDurability the handler and stops waiting if the run ends first. Test-only, budget exhausted, targeted checks only
  • Why: independent durable review (2)
  • Source: https://github.com/pydantic/pydantic-ai/pull/14460#issuecomment-7204157683

2026-11-26 · Deadline override of an explicit WAIT goes to Douwe · iter -

  • Decision: not changed: the durable reviewer's blocking finding (1) — deadlines skip the wait even for a user who set WAIT_CANCELLATION_COMPLETED explicitly, a change for users not hitting the bug; recommends dropping skips_wait_on_cancel, _enforcing_scopes/request_deadline_passed and _cancelled_by_a_deadline — is with Douwe, since it reverses his earlier deadlines-never-wait instruction given when WAIT was to be the default
  • Why: webinar-aws-lambda: design calls go to Douwe
  • Source: https://github.com/pydantic/pydantic-ai/pull/14460#issuecomment-7204157683

2026-11-26 · Decision A pushed, review budget exhausted · iter -

  • Decision: targeted checks only: ruff/format/complexity via pre-commit, durable_exec_contract.py --write; no public symbol changed (only private helpers removed), so no API-compat check
  • Why: budget 3/3 used
  • Source: https://github.com/pydantic/pydantic-ai/pull/14460

2026-11-26 · Douwe decision A: drop the deadline exemption · iter -

  • Decision: Removed skips_wait_on_cancel, the core deadline hook (_enforcing_scopes / request_deadline_passed in models/_request_timeout.py, now identical to main) and _cancelled_by_a_deadline: an opted-in (explicit) WAIT_CANCELLATION_COMPLETED is honoured on every cancel, request_timeout and run timeout= included, exactly as on main; default TRY_CANCEL unaffected. Kept: opt-in via cancellation_type, header-based keep-partial, the pydantic_ai:stream_cancel_partial gate. Tests: request_timeout test back to main's; the opted-in run timeout= test asserts the activity's cancellation is recorded before the workflow completes (1 s heartbeat, no sleeps); deadline-skip unit tests removed
  • Why: Douwe's decision on the switchboard, 11/26 22:10 CDMX, after the independent durable review found the exemption changed behaviour for users who set WAIT explicitly
  • Source: https://github.com/pydantic/pydantic-ai/pull/14460#issuecomment-7204157683
  • Supersedes: Douwe: keeping the streamed partial is opt-in; TRY_CANCEL stays the default

Checklist

  • No breaking changes in accordance with the version policy.
  • Any permitted compatibility impact has a label, warning, migration and release note, and an exact API-check waiver if the gate reports it.
  • PR title is fit for the release changelog.