End the open message part when a restarted part's start arrives

Closed
RA
4d ago
+380-13

Changes

A retried durable activity republishes the model events it already published — durable_exec/temporal/_event_stream.py documents this — so a subscriber of stream_agent_events reads the first attempt's PartStartEvent and deltas followed by the retry's PartStartEvent for the same index, with no PartEndEvent between them. transform_stream opened a second part over the first one (_open_part is simply overwritten), so the first part was never ended and the stream finished with a message part still streaming: AG-UI's verifyEvents fails the run with Cannot send 'RUN_FINISHED' while text messages are still active, and Vercel AI leaves the part in state: 'streaming'. #11734 has the full trace, including a runnable repro.

The fix ends the part tracked as open when a new PartStartEvent arrives, before the new part's start is emitted:

  • The error path's part-closing block (apply the recorded deltas so the synthetic end carries what the client last saw, emit handle_part_end for _open_part_index, clear the tracking state) is extracted into _end_open_part(), unchanged in behaviour.
  • The PartStartEvent branch of transform_stream calls it before _turn_to('response'), so a republished start ends the previous attempt's part first — exactly the cleanup the error path already does for a stream that fails mid-part.
  • The error path now calls the same helper (order preserved: the part is still closed before the pending-tool-call cleanup and on_error).

A well-formed stream is unaffected: there, each part's end arrives before the next part's start, so _open_part is already None and the helper returns immediately.

Fixes #11734

What the client sees

When an activity retry republishes its events, the client receives the first attempt's partial
part as its own, now-ended part, followed by the retry's full part. For a text part under the
AG-UI encoder that is: TEXT_MESSAGE_START (Hel) -> TEXT_MESSAGE_CONTENT (lo) ->
TEXT_MESSAGE_END, then a fresh TEXT_MESSAGE_START / TEXT_MESSAGE_CONTENT (Hello, world) /
TEXT_MESSAGE_END. The partial content is not merged into the retry's part, and deduplicating a
retried attempt's events is a separate change.