Keep a run paused when content is queued at a `DeferredToolRequests` or `PendingModelResponse` pause, and have `BackgroundTools` wait for its tasks there

Merged
AD
17d ago
+1379-216

Closes #7537

Stacked on #13051, which this PR targets; merge that first.

[!WARNING]
Compatibility impact:

  • Content queued with enqueue when a run pauses for deferred tools is added to the message history after the paused step, marked as part of the pause, also when every call in the step was deferred. It used to redirect the run into another model request in that case. At a PendingModelResponse pause, or when queued content holds a ModelResponse or an interrupted request, it stays on AgentRun.pending_messages instead of continuing the run.
  • A new user prompt on a history that paused after other tools in the step ran now raises UserError, as it already did when no other tool ran. It used to continue and leave the pending calls unanswerable.
  • BackgroundTools waits for its live tasks at a deferred-tool pause instead of cancelling them. A run that ends with a PendingModelResponse still ends once its request is submitted: live tasks are cancelled, as after run_stream().

Why this can ship in a minor release: Continuing skipped the approval the run paused for, or abandoned the provider job (#7537), and a new prompt made the approval permanently unanswerable (#12156). The error is the one docs/message-history.md already promised.

Migration: Answer the pause with deferred_tool_results, then send the prompt; or call pydantic_ai.messages.repair_messages() on the history to abandon the pending calls. Bound a slow background tool with its own timeout, or the whole wait with the run's timeout=.

Durable execution: Both changes alter which model calls a given history produces, and with the legacy TemporalAgent and an event_stream_handler, a deferred pause that records content now runs one more event-handler activity. So a Temporal workflow that is in flight across the upgrade may fail with a nondeterminism error on replay. Let in-flight workflows finish before upgrading.

Why we make these changes

A run that pauses hands control back to the caller, who saves the history and answers later, possibly after a restart. Queued content turned the pause into another model request (Adam's report in #7537), or abandoned the provider's suspended job. BackgroundTools cancelled live tasks at a deferred pause and dropped finished results.

Per Douwe on this PR, the message history is the only thing that survives every boundary a pause can span: durable engines, run() and run_stream(), UI adapters and ConversationStore. So core writes request-only queued content into the history at a deferred pause, carrying #13051's pause mark, so a plain resume pauses again. BackgroundTools only queues: at a pause it waits for its live tasks and queues their results in dispatch order, so a replay rebuilds the same request.

A new prompt on a mixed pause raises before anything is recorded, so the pause stays answerable. Supporting a prompt while an approval is pending is #13439.

New public surface

none

User-visible behavior

  pydantic_ai/run.py :: AgentRun.next()
  └─ capabilities/_pending_messages.py :: drain_pending_messages_at_end()
     ├─ DeferredToolRequests, some calls ran → End; queued requests appended to history (marked)
-    ├─ DeferredToolRequests, all calls deferred → ModelRequestNode(queued request)   # approval skipped
+    ├─ DeferredToolRequests, all calls deferred → End; queued requests appended to history (marked)
-    ├─ DeferredToolRequests, queued ModelResponse → ModelRequestNode(...)            # approval skipped
-    └─ PendingModelResponse → ModelRequestNode(queued request)                       # provider job abandoned
+    └─ queued ModelResponse/interrupted request, or PendingModelResponse → End; left on pending_messages
  pydantic_ai/run.py :: AgentRun._deliver_leftover_events()   (new)
+    └─ EnqueuedMessagesEvent emitted after the last stream closed → every on_event listener, then event_stream_handler
  pydantic_ai/_agent_graph.py :: UserPromptNode._history_to_run()
-    └─ new prompt on a mixed pause → model request; pending calls unanswerable
+    └─ new prompt on a mixed pause → UserError, nothing recorded
  pydantic_ai_harness/background_tools/_capability.py :: BackgroundTools.after_node_run()
-    └─ pause → live tasks cancelled in wrap_run, results dropped
+    └─ deferred-tool pause → waits for every live task (an error ends the run at once); takes back its
+               still-queued results and queues all in dispatch order
+    └─ PendingModelResponse end → no wait; live tasks cancelled in wrap_run, arrived results stay queued

Verification

  • tests/test_capability_pending_messages.py: test_enqueue_at_deferred_tool_pause_keeps_the_pause (all-deferred and queued ModelResponse; both priorities; the mixed pause is #13051's test_enqueue_at_deferred_tool_pause_is_recorded_without_another_model_request), test_content_recorded_at_a_deferred_pause_keeps_the_pause_on_a_plain_resume, test_interrupted_request_queued_at_a_deferred_pause_stays_queued, test_enqueue_at_pending_model_response_pause_keeps_the_pause, test_asap_content_queued_before_resuming_a_suspended_response_waits_for_the_next_request.
  • Event delivery: test_content_recorded_at_a_deferred_pause_is_reported_once_to_listeners_and_streams (run, run with a handler, run_stream_events, run_stream), test_content_recorded_when_run_stream_finds_a_deferred_result_reaches_the_handler, and test_content_recorded_at_a_deferred_pause_reaches_listeners_when_the_handler_stops_early, which fails when listeners only see what the handler consumes.
  • tests/test_transcript_repair.py::test_deferred_run_history_not_silently_repaired (#6319) now expects the UserError, and that the pause can still be approved afterwards.
  • tests/harness/background_tools/test_background_tools.py: test_results_recorded_at_a_deferred_pause_follow_dispatch_order (fails when results are queued in arrival order), test_result_queued_before_a_deferred_pause_reaches_a_fresh_agent_after_approval (a fresh agent, as after a restart, sends the result to the model once), test_deferred_tool_pause_waits_for_a_live_background_task, test_pending_model_response_end_cancels_a_live_background_task, test_fully_deferred_pause_records_a_finished_result_after_its_calls, test_error_finishing_after_a_deferred_pause_is_reached_ends_the_run, test_retry_exhausted_before_a_deferred_pause_ends_the_run; test_temporal.py::test_deferred_pause_waits_for_a_background_result_under_temporal.
  • Targeted deferred, pause, approval, enqueue and background tests in test_agent.py, test_tools.py, test_streaming.py, test_ui.py, test_vercel_ai.py, test_ag_ui.py and tests/harness/subagents pass.

What changes for existing users

A pause stays a pause: queued content and background results are in the paused history, so they survive until the approval comes, also across a restart, and reach the model once. A new prompt on a paused history raises instead of making the approval unanswerable.

Notes for review

  • Douwe: implements your answer on this PR. Your #6319 test now expects the error.
  • Results recorded at a pause follow dispatch order. A background result that arrived before the paused step went into an earlier request no matter what, and whether it did depends on timing, so a replay can still differ there.
  • If you drive node.stream() yourself with iter(), no stream remains for the events emitted after the last one closed; listeners still get them, and the content is in the history. Documented in docs/message-history.md.
  • With run_stream(), when the stream itself finds the deferred calls, the streamed result's messages were copied before the run ended; content recorded at the pause is now added to them too (test_content_recorded_when_run_stream_finds_a_deferred_result_reaches_the_handler checks the history).
  • BackgroundTools' wait at the pause moves onto the in-flight registry in #13217, which lands after this PR.
  • Adam's second ask, a public way to check or await that no background tools are running, is left for that registry.
PR decisions

2026-11-10 · Record queued requests at every deferred pause instead of redirecting · iter -

  • Decision: No redirect at any pause; request-only queued content is appended after a deferred pause, a queued ModelResponse and all content at a PendingModelResponse pause stay queued
  • Why: Appending after a fully deferred response is safe once #13051 raises on a resume without deferred_tool_results; Douwe on #7537 asked that content that can't be recorded stay readable on AgentRun.pending_messages
  • Source: https://github.com/pydantic/pydantic-ai/issues/7537
  • Session: 6d7fbd3d-5c31-4680-8a58-6ff4f94cd7c1

2026-11-10 · BackgroundTools waits for live tasks at a pause · iter -

  • Decision: Wait for every live task at a DeferredToolRequests or PendingModelResponse End; errors end the run; run timeout bounds the wait
  • Why: User decision in session: a pause always stands and results are not dropped; waiting is preferred over cancelling tasks
  • Source: https://github.com/pydantic/pydantic-ai/issues/7537
  • Session: 6d7fbd3d-5c31-4680-8a58-6ff4f94cd7c1

2026-11-10 · pre-push review 1 of 3 at 02b574d7d · iter -

2026-11-10 · pre-push review 1 of 3 at 02b574d7d · iter -

  • Decision: remediated in c17aa30cc: queue closed at both pause paths with enqueue-raises tests (#1); BackgroundTools PendingModelResponse test with two tasks, fails on old code (#2); docs say undelivered content is never resent and SubAgents requeues its reports, pending_messages docstring no longer 'Internal' (#6, Douwe on #7537); rewrap and wording (#9, #10); compatibility impact goes in the PR body (#4). Dismissed #3: batch.md is core and does not mention BackgroundTools, harness page states the wait. Kept #7 (never is the guarantee) and #8 (fixed code passes regardless of timing). #5 docs-parity gate run next.
  • Why: reviewed tree eb9cd955834376385a607c899ea1f4211016f198
  • Source: https://github.com/pydantic/pydantic-ai/tree/fix/issue-7537-pause-holds-queued-content
  • Session: 6d7fbd3d-5c31-4680-8a58-6ff4f94cd7c1

2026-11-10 · pre-push review 2 of 3 at c17aa30cc · iter -

2026-11-10 · pre-push review 2 of 3 at c17aa30cc · iter -

  • Decision: remediated in 352b63222: pending_messages docstring and message-history say paused content can be read but not changed (#1); whole-queue ModelResponse rule and resend wording (#3, #4); PendingModelResponse test gated on an Event set at suspension, still fails on old code (#5); docs-parity nit: diagram alt text in docs and README. Dismissed #2: on main a run ending at PendingModelResponse never left the queue open (empty queue closed by drain_at_end, non-empty redirected), so closing at the pause keeps main's end state.
  • Why: reviewed tree 57ad8fa976fa331892d531d56f957bf79c785f85
  • Source: https://github.com/pydantic/pydantic-ai/tree/fix/issue-7537-pause-holds-queued-content
  • Session: 6d7fbd3d-5c31-4680-8a58-6ff4f94cd7c1

2026-11-10 · pre-push review 3 of 3 at 352b63222 · iter -

2026-11-10 · pre-push review 3 of 3 at 352b63222 · iter -

  • Decision: remediated in 82029d2b3: the SVG's own description still held the old sentence, so it now matches the alt text (the visible SVG labels already said a paused run waits) (#1); 'Pydantic AI itself' wording (#5); removed unneeded sleep in the test (#6). Accepted #7 (only a user-queued ModelResponse keeps background results queued; documented in message-history). #8 is pre-existing: the run_stream limitation note vs wrap_run's comment, left for a separate fix. Dismissal of the compatibility claim confirmed. Budget spent; no fourth dispatch.
  • Why: reviewed tree dc69d11736ac5cb4e871d3eabb85e808e54803cf
  • Source: https://github.com/pydantic/pydantic-ai/tree/fix/issue-7537-pause-holds-queued-content
  • Session: 6d7fbd3d-5c31-4680-8a58-6ff4f94cd7c1

2026-11-10 · CI on 82029d2b3: coverage and tests-and-dependencies findings · iter -

  • Decision: remediated in c2645280c: harness pause tests await an Event set by a capability whose after_node_run runs before BackgroundTools' (reverse dispatch order, combined.py:664) instead of asyncio.sleep(0.05); PendingModelResponse test's second task gated on the pause so it still fails on the old code; removed the core test's unreachable second-model-call branch; wrap_run's after-handler error check collects errors in one pass (no partial branch). The error-after-pause test also passes on the old code, since old wrap_run re-raised late errors; kept as a behavior guard. Pre-push review budget spent; local coverage 100% on the changed files.
  • Why: PR Review Checks findings on tests/harness/background_tools/test_background_tools.py and coverage report on head 82029d2b3
  • Source: https://github.com/pydantic/pydantic-ai/pull/13054#pullrequestreview-5845006671
  • Session: 6d7fbd3d-5c31-4680-8a58-6ff4f94cd7c1

2026-11-12 · Settle background outcomes at a pause; plain resume after recorded content pauses again · iter -

  • Decision: In 836b692c9 the pause branch calls _settle after delivering every outcome, so an exhausted retry raises as it does mid-run. Recorded pause content is recognized by its run_id in #13051, so a plain resume of an all-deferred pause with recorded results pauses again (supersedes the "raise" premise of the 2026-11-10 entry).
  • Why: gpt-6.1-sol review: the pause branch returned before any node settled retries, and an appended request without results made a plain resume skip the approval
  • Source: https://github.com/pydantic/pydantic-ai/pull/13054
  • Session: 6d7fbd3d-5c31-4680-8a58-6ff4f94cd7c1

2026-11-12 · Mark recorded pause content instead of stamping a run_id; deliver end-of-run events · iter -

  • Decision: Recorded content gets #13051's deferred_pause mark (supersedes the run_id premise of the previous entry). In 1122e60d4 events buffered when a run ends are streamed through the capability chain and to the run's event stream handler.
  • Why: gpt-6.1-sol third pass: run_id is not proof of a pause; the EnqueuedMessagesEvent for recorded content was emitted after the final step's stream closed, so listeners and handlers never saw it (reproduced for all four run modes)
  • Source: https://github.com/pydantic/pydantic-ai/pull/13054
  • Session: 6d7fbd3d-5c31-4680-8a58-6ff4f94cd7c1

2026-11-12 · run_stream() passes its handler through the final step · iter -

  • Decision: In a930c89c1 run_stream()'s on_complete runs SetFinalResult through _run_node_with_hooks with event_stream_handler, so end-of-run events reach the handler. Handler cancellation mid-delivery and manual node.stream() drivers are documented limits, not fixed.
  • Why: gpt-6.1-sol fourth pass: agent_run.next(SetFinalResult(...)) dropped the handler (reproduced: the handler saw no EnqueuedMessagesEvent). The other two findings match existing node-stream semantics; fixing them needs new public API.
  • Source: https://github.com/pydantic/pydantic-ai/pull/13054
  • Session: 6d7fbd3d-5c31-4680-8a58-6ff4f94cd7c1

2026-11-12 · Core leaves content queued at a pause; BackgroundTools writes its own results · iter -

  • Decision: In f9f661631 the drain closes the queue at either pause and records nothing (supersedes "Record queued requests at every deferred pause" and the end-of-run event delivery and run_stream handler entries). BackgroundTools, at a deferred pause, dequeues its undelivered results and appends them with the newly finished ones as one marked request; at a PendingModelResponse pause they stay queued.
  • Why: Recording in core went against Douwe's #7537 comment and its premise (a plain resume raises) was reversed; it caused four review rounds of event-delivery gaps. BackgroundTools keeps nothing between runs, so an in-memory requeue would lose Adam's results on a restart before the approval; the history he saves already carries them. Chosen with a Fable advisor review.
  • Source: https://github.com/pydantic/pydantic-ai/issues/7537
  • Session: 6d7fbd3d-5c31-4680-8a58-6ff4f94cd7c1

2026-11-17 · Core records queued content at every deferred pause; new prompt on a mixed pause raises · iter -

  • Decision: Supersedes 2026-11-12. Core records request-only queued content at both deferred pause shapes, marked, and reports it via end-of-run event delivery (listeners before the handler); BackgroundTools only queues, in dispatch order at a pause; a new prompt on a mixed pause raises UserError and #6319's test expects it
  • Why: Douwe's answer on this PR: the history is the only thing that survives every pause boundary; SubAgents acknowledges on the event; replay needs dispatch order; continuing makes the approval unanswerable
  • Source: https://github.com/pydantic/pydantic-ai/pull/13054#issuecomment-6867311572
  • Session: 6d7fbd3d-5c31-4680-8a58-6ff4f94cd7c1

2026-11-17 · gpt-6.1-sol review rounds on the new design · iter -

  • Decision: Round 1: run_stream() history lacked content recorded at the pause (fixed in 9d9099e023: the final node's additions are carried into the streamed messages); a fatal background error at a pause waited for unrelated live tasks (fixed: raised as it arrives). Round 2: an exhausted hook retry had the same wait, same root cause (fixed in c31735a9fb: every outcome at a pause goes through one check as it arrives). Round 3: nothing worth fixing
  • Why: Pre-push adversarial review
  • Source: https://github.com/pydantic/pydantic-ai/pull/13054
  • Session: 6d7fbd3d-5c31-4680-8a58-6ff4f94cd7c1

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.