Stamp model-stream events with a `ModelResponseOrigin` so consumers can tell retried and replaced attempts apart

Merged
DO
8d ago
+824-24
  • Closes #13739
  • Part of #14378 (stream attempts: response boundaries, attempt identity and partials)

One request step can stream more than one response: ModelFallback, RetryOnModelErrors or another RetryModelRequest attempts the model again, a wrap_model_request hook stops the model's stream and streams its own response, or a durable engine retries a model unit that already streamed part of a response (Temporal publishes those events again at new offsets). Today nothing on the events tells a consumer which response they belong to, so retried output looks like additional output.

This adds ModelResponseOrigin and an origin field on PartStartEvent, PartDeltaEvent, PartEndEvent and FinalResultEvent:

@dataclass(frozen=True, kw_only=True)
class ModelResponseOrigin:
    run_id: str
    run_step: int
    attempt: int = 1            # attempt at the request step, counted by the agent graph (deterministic)
    execution_attempt: int = 1  # the durable engine's execution of that attempt

    @property
    def response_id(self) -> str: ...  # f'{run_id}:{run_step}:{attempt}', same across engine re-executions
    def supersedes(self, other: ModelResponseOrigin) -> bool: ...

A consumer keeps the latest origin per (run_id, run_step) and drops events from any origin a later one supersedes (documented in agent.md under "Replaced responses", and in the Temporal, DBOS and Prefect handler notes).

How it's stamped

  • Agent stream (every run): AgentStream stamps each model-stream event with the run, the step and ModelRequestContext.attempt, the counter the attempt loop already keeps for RetryModelRequest. A wrap_model_request that replaces the stream it stopped streams the replacement as the next attempt.
  • Durable units: ModelRequestParams gains attempt: int = 1, carried across the Temporal activity boundary and through the DBOS step arguments. The model unit's events() wrapper stamps the origin with execution_attempt from a new DurableOperationBackend.execution_attempt() hook (default 1):
    • Temporal: activity.info().attempt
    • DBOS: the step's current_attempt + 1, plus the attempts of earlier runs when a model error's retry_after split the step into durable waits, so it keeps growing
    • Prefect: the task run's run_count
  • The attempt reaches DurableModel.request_stream(), which doesn't take a request context, through a private context variable set while a segment is opened.
  • FallbackModel's candidates are not attempts: it switches models inside one model request, before the first event, so no consumer ever sees two of its candidates. ModelFallback moves on in the attempt loop, so its next model is attempt 2.

Compatibility

  • origin is excluded from serialization when None, so events that don't carry one serialize byte for byte as before. An older decoder ignores the unknown field.
  • origin is excluded from equality and repr() (field(compare=False, repr=False)). Otherwise every user test that compares agent events by equality would break on upgrade, and every event snapshot would need run_id=IsStr(); with it, no existing snapshot changes. Origins are asserted explicitly in the tests.
  • The API compatibility check against v2.73.0 passes.

Not in this PR

Response start and end events, UI adapter handling (dropping superseded events, Vercel reset-step), ModelResponseRejectedEvent.origin (#11939), history changes. The deprecated TemporalAgent / DBOSAgent / PrefectAgent model wrappers aren't stamped. The Harness engines (Lambda, Absurd, pgtask, Azure Durable Task, Render) use the default execution_attempt() of 1 for now, and Render's and Azure's transports don't carry ModelRequestParams.attempt yet.

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.

šŸ¤– Generated with Claude Code


Summary by cubic

Adds ModelResponseOrigin with an origin field on PartStartEvent, PartDeltaEvent, PartEndEvent, and FinalResultEvent, so consumers can tell apart responses that were retried, fallen back, or replaced by a later attempt at the same request step. Closes #13739.

How it works

  • ModelResponseOrigin carries run_id, run_step, attempt, and execution_attempt; response_id is stable across engine re-executions of one attempt, and supersedes() identifies which earlier origins' events to drop.
  • The agent stream stamps an attempt's origin once, on its first event; tests assert every event type, including each streamed delta, carries its attempt's origin.
  • A wrap_model_request replacement streams as the next attempt; ModelFallback moving on counts as attempt 2, while a FallbackModel's candidates share one attempt.
  • Durable engines stamp execution_attempt via the new DurableOperationBackend.execution_attempt() hook: Temporal's activity attempt, DBOS's step attempt, and Prefect's task run count.
  • attempt travels into durable units through ModelRequestParams, carried across the Temporal, DBOS, Azure Durable Task, and Render transports.
  • Documents the drop logic for consumers in agent.md, the durable execution docs, and the agents skill.

Compatibility

  • origin is excluded from equality, repr(), and serialization when None, so events compare and serialize as they did before.
  • Wire tests cover that serialization, and the API compatibility check against v2.73.0 passes.
  • DBOS keeps a step's attempt count in memory, so a recovered workflow's resumed step restarts at execution_attempt=1 and its events can't be told apart from the first run's.
  • The Lambda, Absurd, and pgtask harness engines still use the default execution_attempt() of 1.