Close the event loop `run_sync` leaves on a worker thread, so its `__del__` cannot fail an unrelated test
Closes #12856
What was wrong
run_sync runs the agent on the calling thread's event loop, creating one via _utils.get_event_loop() when the thread has none. Nothing closes that loop. For a short-lived worker thread (asyncio.to_thread, a ThreadPoolExecutor worker) the loop becomes unreachable while still open, so CPython's BaseEventLoop.__del__ closes it during a later garbage collection — after its self-pipe is already gone:
ValueError: Invalid file descriptor: -1
The error surfaces in whichever test is running at the collection, not in the test that leaked the loop. tests/test_run_cancellation.py::test_run_sync_token_cancel_from_another_thread runs run_sync through asyncio.to_thread, and #12712 reports the teardown error landing on a later test.
The change
Test-only, following the fix #12724 made for the DBOS executor thread: the worker thread closes the loop run_sync set on it before returning, so the loop is closed by its owner rather than by the GC.
The test also asserts the loop came back closed (closed_loops == [True]), so removing the close fails here instead of resurfacing as an unrelated test's teardown error.
Verification
- Without the
loop.close(),tests/test_run_cancellation.py::test_run_sync_token_cancel_from_another_threadfails withassert [] == [True]; with it, the test passes. pytest tests/test_run_cancellation.py -p no:randomly -q→ 104 passed.ruff check/ruff format --check tests/test_run_cancellation.py→ clean.
Notes
Product code is untouched: closing the loop inside run_sync would break callers that keep using the loop afterwards (the sync stream wrappers hold it), which is why #12724 fixed it at the test too.
Related: #12712
Needs a pkg: label from a maintainer — an external contributor can't add labels.
Summary by cubic
Fixes a flaky test failure where run_sync left an event loop open on a worker thread, and garbage collection later closed it during an unrelated test's teardown, raising ValueError: Invalid file descriptor: -1. The worker thread now closes the loop before returning, and the test asserts it is closed so the fix stays enforced.