Fix flaky `test_run_sync_token_cancel_from_another_thread` by closing the event loop `run_sync` leaves on its worker thread

Merged
DS
20d ago
+11-3

Why we make these changes

test_run_sync_token_cancel_from_another_thread errored at teardown with ValueError: Invalid file descriptor: -1 from BaseEventLoop.__del__ (failing run).

Root cause. The test runs Agent.run_sync() on an asyncio.to_thread worker. There, run_sync() creates a new event loop, sets it as the thread's loop, and nothing closes it. The teardown collection in tests/gc_isolation.py finalizes the test's garbage. When it reaches the loop's self-pipe socket before the loop, BaseEventLoop.__del__ closes the loop over an already-closed socket and raises.

Fix. The worker closes that loop in a finally once the run ends, since the run raises RunCancelled. This is the fix #12724 made for #12708. The library's run_sync() is unchanged.

#12933 and #12857 made the same change to this test. This PR lands it on its own, with a forced reproduction, so the flake stops failing CI while #12933's other fixes are reviewed.

New public surface

None.

User-visible behavior

None.

Verification

A scratch pytest plugin (not committed) records each loop set as current on a non-main thread. After the test body, it closes the self-pipe socket of each recorded loop that is neither running nor closed: the order the CI failure hit. Local runs on Python 3.15.

mainthis PR
forced orderERROR at teardown: ValueError: Invalid file descriptor: -1, on the loop set on thread asyncio_125 of 25 runs pass
-W "error:unclosed event loop:ResourceWarning"ERROR at teardown: BaseEventLoop.__del__25 of 25 runs pass
Reproduction plugin
"""Forces the teardown collection to finalize a leaked event loop's self-pipe socket before the loop itself.

Load with `-p force_self_pipe_first` and this directory on `PYTHONPATH`.

Every loop set as current on a non-main thread is recorded. After the test body, each recorded loop that is neither
running nor closed gets its self-pipe socket closed: what the collector's socket finalizer does when it reaches the
socket before the loop.
"""

from __future__ import annotations

import asyncio
import sys
import threading
import weakref
from collections.abc import Generator

import pytest

_set_event_loop = asyncio.set_event_loop
_thread_loops: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, str] = weakref.WeakKeyDictionary()


def _recording_set_event_loop(loop: asyncio.AbstractEventLoop | None) -> None:
    thread = threading.current_thread()
    if loop is not None and thread is not threading.main_thread():
        _thread_loops[loop] = thread.name
    _set_event_loop(loop)


setattr(asyncio, 'set_event_loop', _recording_set_event_loop)


@pytest.hookimpl(wrapper=True)
def pytest_runtest_call(item: pytest.Item) -> Generator[None, object, object]:
    try:
        return (yield)
    finally:
        forced: list[str] = []
        for loop, thread_name in list(_thread_loops.items()):
            if isinstance(loop, asyncio.BaseEventLoop) and not loop.is_running() and not loop.is_closed():
                loop._ssock.close()  # pyright: ignore[reportAttributeAccessIssue]
                forced.append(f'{loop!r} set on thread {thread_name!r}')
        _thread_loops.clear()
        print(f'\n[force_self_pipe_first] {item.nodeid}: closed the self-pipe of {forced}', file=sys.stderr)

Run with PYTHONPATH=<dir> uv run pytest -p force_self_pipe_first "tests/test_run_cancellation.py::test_run_sync_token_cancel_from_another_thread" -p no:randomly.

What changes for existing users

Nothing.

PR decisions

2026-11-14 · fix #12712 in its own PR despite #12933's claim · iter -

2026-11-14 · reuse #12933's test-side close, not a run_sync change · iter -

  • Decision: The test wraps run_sync in a function that closes the worker thread's loop in a finally; run_sync and _utils.get_event_loop stay unchanged
  • Why: Same fix #12724 made for #12708; closing loops in run_sync is a behavior change for every caller on a worker thread
  • Source: https://github.com/pydantic/pydantic-ai/pull/12933
  • Session: 4584a8ff-db6d-4089-a377-50c9e5e4e257

2026-11-14 · pre-push review 1 of 3 at cc17e65f8b7468d6835428c664d5edd0de816b3a · iter -

2026-11-14 · pre-push review 1 of 3 at cc17e65f8b7468d6835428c664d5edd0de816b3a · iter -

2026-11-16 · supersede #12857 · iter -

  • Decision: Open this PR as planned, credit #12857 and #12933 in the body, and close #12857 with thanks as superseded
  • Why: David chose this PR over adopting the contributor's equivalent fix; this PR carries the forced reproduction the flake-fix rules require
  • Source: https://github.com/pydantic/pydantic-ai/pull/12857
  • Session: 4584a8ff-db6d-4089-a377-50c9e5e4e257

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.

Summary by cubic

Fixes the flaky test_run_sync_token_cancel_from_another_thread teardown failure by closing the event loop that run_sync creates on the asyncio.to_thread worker thread. Leaving the loop open made the garbage collector raise ValueError: Invalid file descriptor: -1 from BaseEventLoop.__del__ when it finalized the loop's self-pipe socket first. run_sync is unchanged; the test now closes the loop in a finally.

Verification

  • With a reproduction plugin forcing the self-pipe-first finalization order, 25 of 25 local runs pass on Python 3.15, also with -W "error:unclosed event loop:ResourceWarning".