Let a retired `aws_lambda` agent loop finish its own cleanup at the grace deadline

Merged
DS
1mo ago
+132-22

This pull request was posted by Claude Code using claude-opus-5-5 on behalf of David.

No linked issue: found while tracking down the test leak fixed in #12137.

When an aws_lambda durable run is abandoned and its cleanup is still running at the end of the retired loop's grace period, that cleanup now receives one CancelledError on the loop thread and can finish there. Before, the loop stopped under it: the cleanup was cut off mid-await, and its remaining finally code ran later under GeneratorExit, during GC, on whatever thread collected it.

[!NOTE]
Design point for review: the deadline cancel above is new behavior that cleanup code can observe. It is the expiry path the retirement already implements (and its waiter test exercised by patching loop.stop); this PR stops the loop from ending before that path runs. The loop still stops a few event-loop iterations after that cancel, so a cleanup that suppresses it, or awaits something else after it, is still cut off.

Why we make these changes

When run_durable abandons a run whose cleanup outlives cancel_timeout, it retires the background loop and gives the cleanup a grace period. If the cleanup was still running at the grace deadline, a timer stopped the loop at that same deadline, before the retirement's own clean_up could wake from its timed-out waits. Neither clean_up nor the abandoned run ever finished. Both were left pending on a closed loop, and asyncio logged Task was destroyed but it is pending! whenever GC collected them, which in a warm Lambda can be during a later invocation.

At the deadline, the loop now stops once clean_up has finished, so its expiry path runs: it cancels what outlived the budget, drains async generators and the default executor, then stops. If something already cancelled clean_up, the loop stops at the deadline as before. The change adds no time value: every wait clean_up makes after the deadline has a zero timeout.

New public surface

None.

User-visible behavior

Abandoned cleanup at the grace deadlineBeforeAfter
Finishes once cancelledleft pending; Task was destroyed but it is pending! for it and clean_up()finishes on the loop thread; nothing pending
Suppresses every cancellationleft pending, with clean_up()left pending alone

The retired loop's thread exits a few event-loop iterations after the grace deadline, where main stopped it at the deadline itself. On Python 3.11 it first waits for jobs already submitted to the loop's default executor, because cancelling shutdown_default_executor() joins its thread there.

Verification

What changes for existing users

Nothing for runs that finish within the grace period; a cleanup still running at its end is now cancelled on the loop instead of being finalized during GC.

PR decisions

2026-11-01 · retired-loop shutdown shape · iter -

  • Decision: At the grace deadline the loop stops once clean_up has ended (immediately if it is already gone); clean_up stops the loop via call_soon. The manager chose the recommended shape on David's behalf.
  • Why: David chose to have this PR; the shape needs no time value. Rejected: fixed margin (needs a value, leaves shutdown tasks pending), timed backstop (needs a value, can lose grace), no timer (loses grace when user code cancels clean_up).
  • Source: https://github.com/pydantic/pydantic-ai/tree/let-retired-loop-cleanup-finish
  • Session: 19b3fbdf-028b-4683-a28d-ff5c4f321fcd

2026-11-01 · no post-deadline settle time, no timed backstop · iter -

  • Decision: No extra post-deadline time and no timed hard-stop backstop. The manager chose on David's behalf: David stated no time value, and the evidence shows a backstop adds no protection once every post-deadline wait is bounded.
  • Why: Every await in clean_up after the deadline is a zero-timeout asyncio.wait or anyio.sleep(0); only a synchronously blocked loop thread prevents exit, which a timer cannot fix either.
  • Source: https://github.com/pydantic/pydantic-ai/tree/let-retired-loop-cleanup-finish
  • Session: 19b3fbdf-028b-4683-a28d-ff5c4f321fcd

2026-11-01 · create_task-raising task factory not covered · iter -

  • Decision: The create_task-raising factory case is not covered. The manager chose on David's behalf, following the schedule_run precedent in _bridge.py: task creation failing is treated as not reproducible.
  • Why: Covering it would mean arming the deadline callback before creating clean_up, for a path only a user task factory that raises can reach.
  • Source: https://github.com/pydantic/pydantic-ai/tree/let-retired-loop-cleanup-finish
  • Session: 19b3fbdf-028b-4683-a28d-ff5c4f321fcd

2026-11-01 · pre-push review 1 of 3 at 123684ee59e6bbb8033687bb0f81fa9bffb63419 · iter -

2026-11-01 · pre-push review 1 of 3 at 123684ee59e6bbb8033687bb0f81fa9bffb63419 · iter -

  • Decision: 2 findings: (1) docs/docstrings said only a suppressing cleanup is cut off -> remediated in 39533b4d4 (loop stops a few iterations after the deadline cancel; a cleanup still awaiting then is also cut off); (2) deadline timer redundant -> dismissed: user code cancelling every task also cancels clean_up, and without the timer the loop never stops; pinned by new test_retirement_stops_the_loop_at_the_grace_deadline_when_its_cleanup_is_cancelled
  • Why: tree f76f16f2f73558b4e1589036be58d964f7e1d2fd; full branch 6676611a8..123684ee5; a first launch failed before reviewing (CLI argument error) and is not counted
  • Source: https://github.com/pydantic/pydantic-ai/tree/123684ee59e6bbb8033687bb0f81fa9bffb63419
  • Session: 19b3fbdf-028b-4683-a28d-ff5c4f321fcd

2026-11-01 · pre-push review 2 of 3 at 39533b4d43f69e958c0e538775caafe6217617d3 · iter -

2026-11-01 · pre-push review 2 of 3 at 39533b4d43f69e958c0e538775caafe6217617d3 · iter -

2026-11-01 · pre-push review 3 of 3 at 1d4a4e4daac6efb6ff2dae588067928e5ad4599d · iter -

2026-11-01 · pre-push review 3 of 3 at 1d4a4e4daac6efb6ff2dae588067928e5ad4599d · iter -

2026-11-01 · douwebot comment 4434074801 at 302a6463988644dd5672028505b3663bbbd138f7 · iter -

  • Decision: Reworded, not dropped: the user-cancelled-cleanup sentence in docs/harness/aws-lambda.md and the README now says the cleanup is not cancelled again and the loop stops at the deadline, without naming the retirement's internal cleanup; remediated in f66402d65abe35fe39d866435c2e963b93794d8e
  • Why: Dropping it would leave 'cancelled again' wrong for a cleanup that cancels every task (pre-push review 3 finding); the internal-jargon half of the comment was valid. Docs page delta, not exempt; pre-push budget exhausted, so pushed after README/docs parity check; hosted review re-reviews; chains from reviewed 1d4a4e4da
  • Source: https://github.com/pydantic/pydantic-ai/pull/12140#discussion_r4434074801
  • Session: 19b3fbdf-028b-4683-a28d-ff5c4f321fcd

2026-11-01 · douwebot comment 4434084548 at f66402d65abe35fe39d866435c2e963b93794d8e · iter -

  • Decision: Moved, not dropped: the grace-end sentences now form their own paragraph after the module-global advice, restoring main's paragraph unchanged; the Python 3.11 executor note and the cancel-every-task case stay in the user docs
  • Why: Placement complaint valid and cheap to fix; dropping the details would make 'at most the grace period'/'stops shortly' false on 3.11 with executor jobs and 'cancelled again' false for a cleanup that cancels every task (pre-push reviews 2 and 3). Docs page delta, budget exhausted, pushed after docs/README parity check; chains from reviewed 1d4a4e4da
  • Source: https://github.com/pydantic/pydantic-ai/pull/12140#discussion_r4434084548
  • Session: 19b3fbdf-028b-4683-a28d-ff5c4f321fcd

2026-11-01 · optional douwebot comments are triaged on net value, not pushed away · iter -

  • Decision: The manager ruled on David's behalf: a comment-free douwebot pass is not needed on this PR. Triage an optional douwebot comment on net value: 'Apply it only when the change is clearly better for a reader.' 'Decline it with a reply and a resolve, and push nothing, when it is taste or a near-even trade.' 'Do not push only to earn a comment-free review.'
  • Why: Verified: the 'Gate: clean douwebot approval' status was success on 302a646 at 00:44:44Z, before any douwebot review existed (first at 02:02:09Z), and is success on f66402d and 07a6ec6. Two optional docs rounds already landed (f66402d, 07a6ec6). This departs from the pushing skill's merge-bar text: 'Clean means douwebot APPROVE on the current head, with no douwebot comments on that head.'
  • Source: https://github.com/pydantic/pydantic-ai/pull/12140
  • Session: 19b3fbdf-028b-4683-a28d-ff5c4f321fcd

2026-11-01 · size-S merge bar stands: no douwebot comments on the head · iter -

  • Decision: The manager retracted the previous entry on David's behalf. The S bar applies: 'douwebot APPROVE on the current head with no douwebot comments on that head.' 'Every douwebot comment, including a non-blocking one, gets addressed; then get a clean approval on the resulting head.' Triage on the evidence: valid -> fix; invalid -> evidence reply, thumbs-down, resolve. 'Do not decline a valid comment as "taste" to stop the loop.' 'If a third optional docs round lands after this one, stop and report it before you push.' No fix to the pushing skill.
  • Why: The pushing skill's Merge bar says PR Review Gates enforces M/L/XL only and 'Size S remains a manual judgment', so the gate status success on this size-S PR proves nothing.
  • Source: https://github.com/pydantic/pydantic-ai/pull/12140
  • Session: 19b3fbdf-028b-4683-a28d-ff5c4f321fcd
  • Supersedes: optional douwebot comments are triaged on net value, not pushed away

2026-11-01 · douwebot comment 4434095609 at 07a6ec693b15fa0fcaaafd2bc3ea53f525c12e53 · iter -

  • Decision: David chose option A from the manager's menu: cut the _RETIRED_LOOP_GRACE_SECONDS docstring to its summary line plus 'See _AgentLoop.retire for what happens at the deadline.'; retire's docstring and the call_at comment unchanged; remediated in a0590616f048be2f2948233303e1cd63f2e989ad
  • Why: Valid: the constant and retire docstrings duplicated the deadline mechanics and had already been edited in lockstep twice. The proposed single line was 134 chars (limit 120), so the same words are split into summary + pointer lines. Exempt delta (docstring only, no docs/** page) from reviewed 1d4a4e4da; ruff and pyright clean; CI on 07a6ec6 green before push
  • Source: https://github.com/pydantic/pydantic-ai/pull/12140#discussion_r4434095609
  • Session: 19b3fbdf-028b-4683-a28d-ff5c4f321fcd

2026-11-01 · correction: a0590616f is not an exempt delta from the reviewed SHA · iter -

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.