Fix flaky `test_recovery_reaches_the_same_decision` by closing the event loop `run_sync` leaves on the DBOS executor thread

Merged
DS
1mo ago
+3-0

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

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

Root cause. DBOS.resume_workflow() runs the recovered workflow on a DBOS executor thread. There, Agent.run_sync() creates a new event loop, sets it as the thread's loop, and nothing closes it. Once DBOS shuts its executor down, the loop is garbage, and the teardown collection in tests/gc_isolation.py finalizes it. When the collector reaches the loop's self-pipe socket before the loop, BaseEventLoop.__del__ closes the loop over an already-closed socket and raises.

Fix. The workflow closes that loop at the end of the recovered attempt, so the test leaves no unclosed loop to finalize. The library's run_sync() is unchanged.

Reproduction. A scratch pytest plugin (not committed) joins executor workers on shutdown and, after the test body, closes the self-pipe socket of each idle loop set on a non-main thread — the order the flaky runs hit.

without the fixwith the fix
forced orderERROR at teardown: ValueError: Invalid file descriptor: -1; one leaked loop, set on dbos-executor-_0no leaked loop; passes
-W "error:unclosed event loop:ResourceWarning"ERROR at teardown: ResourceWarning: unclosed event loopno warning; passes
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`.

1. Executor shutdowns wait for their workers, so a loop set on a worker thread is garbage by the time
   `tests/gc_isolation.py` collects in teardown (DBOS shuts its executor down with `wait=False`).
2. 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 concurrent.futures
import sys
import threading
import weakref
from collections.abc import Generator

import pytest

_shutdown = concurrent.futures.ThreadPoolExecutor.shutdown


def _shutdown_and_join(
    self: concurrent.futures.ThreadPoolExecutor, wait: bool = True, *, cancel_futures: bool = False
) -> None:
    _shutdown(self, wait=True, cancel_futures=cancel_futures)


setattr(concurrent.futures.ThreadPoolExecutor, 'shutdown', _shutdown_and_join)

_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/harness/detect_loops/test_dbos.py::test_recovery_reaches_the_same_decision" -s.

PR decisions

2026-11-06 · pre-push review 1 of 3 at fb0d0000ceebabc3696a77a135fb4dfd6c8ddb0b · iter -

2026-11-06 · close the leaked loop in the test, not in run_sync · iter -

  • Decision: The recovered workflow closes the loop run_sync set on the DBOS executor thread; pydantic_ai._utils.get_event_loop and run_sync stay unchanged
  • Why: A flake fix changes only the failing test's module; making run_sync close loops it creates on worker threads is a behavior change for every caller
  • Source: https://github.com/pydantic/pydantic-ai/issues/12708
  • Session: ff800d20-f26f-40ed-ad21-c62f447080b4

2026-11-06 · pre-push review 1 of 3 at fb0d0000ceebabc3696a77a135fb4dfd6c8ddb0b · iter -

2026-11-06 · leave #12712 to its claimant · iter -

  • Decision: test_run_sync_token_cancel_from_another_thread reproduces with the same mechanism (loop run_sync sets on an asyncio.to_thread worker) but stays out of this PR; no comment on #12712
  • Why: Its flake issue carries a claim naming another branch; the maintainer driving this PR decided to leave it there
  • Source: https://github.com/pydantic/pydantic-ai/issues/12712
  • Session: ff800d20-f26f-40ed-ad21-c62f447080b4

2026-11-06 · library-level run_sync loop leak out of scope · iter -

  • Decision: run_sync leaving its worker-thread loop unclosed is not changed or filed in this PR; the code-mode DBOS test leaks the same way but only reports it on stderr at session end
  • Why: A flake fix changes only the failing test's module; changing run_sync is a behavior change for every caller
  • Source: https://github.com/pydantic/pydantic-ai/issues/12708
  • Session: ff800d20-f26f-40ed-ad21-c62f447080b4

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.