Skip to content

gh-160760: asyncio: run newly scheduled callbacks eagerly before polling for I/O - #145149

Open
asvetlov wants to merge 3 commits into
python:mainfrom
asvetlov:eager-loop
Open

asvetlov wants to merge 3 commits into
python:mainfrom
asvetlov:eager-loop

Conversation

@asvetlov

@asvetlov asvetlov commented Feb 23, 2026 •

Copy link
Copy Markdown
Contributor

Run callbacks that are scheduled during an event loop iteration eagerly, within a small budget, instead of always waiting for the next I/O poll. This removes one select()/epoll_wait() call per hop in code that resolves futures or wakes tasks in chains.

  • New asyncio.EventLoopSettings(eager_max_time, eager_max_callbacks) and loop.get_settings() / loop.set_settings(). The defaults are 100 µs and 100 callbacks; eager_max_time=0 turns eager processing off.
  • Eager processing ends early on asyncio.sleep(0), which still guarantees an I/O poll, and on loop.stop(), which keeps its documented "current batch only" behaviour.
  • Callbacks still run in first-in, first-out order. Only the number of I/O polls changes.

Benchmarks (release build, script): a call_soon() chain is 38% faster, Queue ping-pong 25% faster, and a task awaiting a child task 33% faster. Servers with many connections are unchanged. While a long run of callbacks keeps going, timers and I/O can be delayed by up to about 100–200 µs.

A few tests that assumed "one task hop = one I/O poll" were adjusted.

@github-actions

This comment was marked as outdated.

@github-actions github-actions Bot added the stale Stale PR or inactive for long period of time. label May 7, 2026
@asvetlov asvetlov changed the title Implement eager loop runner #160760: Implement eager loop runner Oct 27, 2026
@asvetlov asvetlov added topic-asyncio and removed stale Stale PR or inactive for long period of time. labels Oct 27, 2026
@asvetlov asvetlov changed the title #160760: Implement eager loop runner gh-160760: asyncio: run newly scheduled callbacks eagerly before polling for I/O Oct 27, 2026
@bedevere-app bedevere-app Bot added the type-feature A feature request or enhancement label Oct 27, 2026
@read-the-docs-community

read-the-docs-community Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 cpython-previews | 🛠️ Build #36181429 | 📁 Comparing eb7066e against main (085d366)

  🔍 Preview build  

192 files changed · + 1 added · ± 191 modified

+ Added

± Modified

@asvetlov
asvetlov force-pushed the eager-loop branch 6 times, most recently from 2950322 to 917f47b Compare October 28, 2026 15:33
@asvetlov
asvetlov marked this pull request as ready for review October 29, 2026 10:42
@asvetlov
asvetlov requested a review from 1st1 as a code owner October 29, 2026 10:42
Comment thread Lib/asyncio/base_events.py Resolved
Comment thread Lib/asyncio/base_events.py Resolved
Comment thread Lib/asyncio/events.py Resolved
Comment thread Lib/asyncio/events.py Resolved
Comment thread Lib/asyncio/constants.py Resolved
@YvesDup

YvesDup commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Sorry, but I don't see in any tests, assertion on the _eager_state attribute used as a counter even it is a private attribute ? Maybe I missed something.

@asvetlov

asvetlov commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Right, no test asserts the value of _eager_state directly. That's on purpose: it's a private detail, so the tests check what it controls: which callbacks run in which iteration, what is left in _ready, and how many times the selector is polled. To make sure this covers the counter, I tried storing no count, a count one too high and a count one too low; each change makes test_run_until_complete_after_eager_limit fail, and most of them also make some of the test_run_forever_stop_* tests fail.

@YvesDup

YvesDup commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

That sounds good to me.

…e polling for I/O

Run callbacks that are scheduled during an event loop iteration eagerly,
within the limits of the new asyncio.EventLoopSettings, instead of always
waiting for the next I/O poll.  asyncio.sleep(0) and loop.stop() end
eager processing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@asvetlov

Copy link
Copy Markdown
Contributor Author

@kumaraditya303 have you a chance to review this PR? Thanks.

@kumaraditya303

Copy link
Copy Markdown
Contributor

I'll try to take a look soon

# Conflicts:
#	Modules/clinic/_asynciomodule.c.h
# Conflicts:
#	Modules/clinic/_asynciomodule.c.h
@kumaraditya303

Copy link
Copy Markdown
Contributor

A few issues found by Claude:

1. Callbacks can be lost in the final iteration after stop(), hanging asyncio.run()

In the nleft >= 0 and self._stopping branch of _run_once(), the later handles are popped, the new I/O/timer handles run, and later is pushed back without try/finally. If one of those handles raises SystemExit/KeyboardInterrupt, the popped handles are dropped:

import asyncio, sys

async def worker(fut):
    await fut

async def main():
    loop = asyncio.get_running_loop()
    fut = loop.create_future()
    asyncio.create_task(worker(fut))
    hop = loop.create_future()
    loop.call_soon(hop.set_result, None)
    await hop                             # get into the eager phase
    loop.call_soon(fut.set_result, None)  # same batch as the stop() callback
    loop.call_later(0, sys.exit, 3)       # due at the final iteration's poll

asyncio.run(main())

On main this exits with status 3. With this PR it hangs forever in _cancel_all_tasks(), because the worker's wakeup was lost. Wrapping the second _run_handles() call in try/finally should fix it.

2. A server can miss a short-lived client, and test_streams.test_unhandled_exception becomes flaky

A client's connect / write / close / wait_closed() can now complete without any I/O poll, so server.close() runs before the listening socket is ever accepted:

async def once():
    seen = []
    async def handler(r, w):
        seen.append(1); w.close()
    server = await asyncio.start_server(handler, '127.0.0.1', 0)
    rd, wr = await asyncio.open_connection(*server.sockets[0].getsockname())
    wr.write(b'test msg'); await wr.drain()
    wr.close(); await wr.wait_closed()
    server.close(); await server.wait_closed()
    return bool(seen)

On an idle machine (macOS, debug build) the handler ran in 2000/2000 rounds on main and 1961/2000 with this PR. test_unhandled_exception has the same shape: run in a loop in six parallel processes, it failed 182/2400 times with this PR, 0/2400 on main, and 0/2400 with this PR and eager processing disabled.

@kumaraditya303

kumaraditya303 commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Benchmarks (release build, script): a call_soon() chain is 38% faster, Queue ping-pong 25% faster, and a task awaiting a child task 33% faster. Servers with many connections are unchanged. While a long run of callbacks keeps going, timers and I/O can be delayed by up to about 100–200 µs.

I'd like to see if this improves performance of any real world workload. In my experience, such improvements on microbenchmarks don't improve performance of asyncio workloads generally. The microbenchmarks use trivial callbacks but application code callback are much slower so the cost of I/O isn't bottleneck.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

asyncio: run newly scheduled callbacks eagerly before polling for I/O

3 participants