Allowed time slot for eager callbacks execution timed out (100us by default).
Allowed amount of eager callbacks are processed (100 by default).
Explicit await asyncio.sleep(0) is called as a request for task suspension and I/O polling.
Loop is stopped (obsolete but still supported loop.run_until_complete() semantics is preserved).
A chained call_soon() are 38% faster, ping-pong over asyncio.Queue is 25% faster.
Awaiting a scheduled task that doesn’t suspends on I/O is 33% faster; it partially eliminates the need for controversial eager tasks (the implementation has a benchmark script attached).
In case of massive concurrent I/O (server under load), the PR shows the same speed as ‘main’; saturated server doesn’t show any difference.
The new mode is backward compatible with virtually any existing asyncio code; the only visible change is possible reordering of call_soon() and I/O callbacks.
I believe it is not an issue with any production code but it could affect specific unit tests that strictly rely on the execution order.
The eager mode could be disabled per loop instance; two of 3000+ asyncio tests require this change. I could rewrite them to relax the strict ordering requirement, sure, but the eagerness disabling is a minimalistic fix.
A slow CPU-bound callback could suspend a loop for an additional 100-200 us in the worst case in comparison to the ‘main’.
Keep in mind that CPU-bound code is an anti-pattern for the asyncio world and should be avoided anyway; it is bad with the ‘main’ as well.
Max eager callbacks execution timeout and their count could be tuned by loop.set_settings().
I’ve chosen 100ms and 100 callbacks as default after measuring alternative numbers.
Zero timeout or amount means returning to old behavior.
The implementation is pretty short; it contains setting the flag in asyncio.sleep(0) and reimplementing BaseEventLoop._run_once(); all other asyncio code keeps working as-is.
I very much appreciate the code review and discussion, either here or in PR.
Overall this looks like a nice improvement. I was able to build and test against a large asyncio project last week, but hadn’t taken the time to type up my thoughts until today.
This is the one bit I’m not sold on. Even though sleep(0) is implemented as a special case, the behavior follows from the general case: “yield back to the event loop, allowed to resume after at least this much time”, and is therefore easy to explain to others without hesitation about there being a special case involved, and in a way that people can follow from an intuitive understanding.
I don’t feel great about documenting something like that as part of a special case of sleep, so even if you think this is the best behavior to implement here, I think leaving the precise timing of callback scheduling to the event loop as an optimization going forward is better than saying it is part of sleep’s behavior. If you still think it’s worth noting in documentation, I think it’s worth relaxing the language so that it’s not something that can be read as a guarantee of behavior.
Conceptually, everything looks good and as far as I can tell. I’m reasonably certain that this doesn’t have any of the same conceptual issues that people have found with eager task factories.
Performance notes below, these are all positive and within what I expected
Testing was done by replaying captured events representing real traffic to a full test network[1], 10 batches of 15 minutes of traffic, at increasing event rates (and therefore also corresponding to load)
Applying the change reduced p95 response time[2] by between 8 and 15% over the first 9 batches of recorded events in 15 minute segments. The fluctuation appears to not correlate with load other than full saturation, which matched my expectations.
The 10th batch did not experience a measurable change, but that batch corresponds to a load that fully saturated the test network. We have tests for backpressure related concerns, and those observed no measurable difference in propagation of backpressure.
No process had become worse in any statistic we test or simulate for.
Due to the amount of time these take to run and that the same machines are used for other testing, I usually only get to do a couple of these per python version in development, but asyncio performance improvements are something I try to ensure gets the time and testing to evaluate at work given our reliance on asyncio. ↩︎
measured by observing the network, not from within the process measured itself. ↩︎
I’m pretty sure that asyncio.sleep(0) is called more often than any other sleep value (at least in terms of source lines), and that the intention in most cases is “give the event loop a chance to do something else so we don’t hog the CPU here”.
I don’t want to speculate in how many cases it’s intended as a way to cause the event loop to go back to its check whether I/O is ready, but I somehow betcha that’s a significant fraction. In any case my worry is that we might end up breaking expectations of some zero-sleep callers, thus breaking their applications and presenting them with what could be an incredibly hard to debug issue, possibly even a heisenbug.
Continuing the special case feels much safer; and I doubt that this occurs often enough to affect the average speed-up due to Andew’s proposal.
I consider await sleep(0) as a regular sleep, not a special case.
Now on the ‘main’ it is implemented differently than sleeping for a positive delay, but I read it as an implementation detail made for speeding up the event loop.
In turn, await sleep(1) always polls I/O.
I’ve analyzed 11 libraries from PyPI top 100.
aiohttp, httpx, Starlette, FastAPI, aiohappyeyeballs, AnyIO, SQLAlchemy, grpc.aio have tests suites that are passed with both eager loop and non-breaking asyncio.sleep(0) (as was suggested by @mikeshardmind).
But uvicorn and websockets both are green with eager tasks but have some failed tests with non-breaking sleep(0); they use the call exactly for running pending I/O.
I think the numbers confirm the design choice.
The interesting observation: 34% of callbacks in test suites are executed eagerly; the PR makes sense.
However, unlike time.sleep, we document asyncio.sleep as follows:
sleep() always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
The reason why time.sleep(0) was special is that it depends on the platform. On Windows, it effectively does what people wanted to do, but on Unix, it’s different (and it depends on the distribution as well). A more robust way to emulate Windows’ sleep behavior on Unix is to use the scheduler. Now, with asyncio.sleep, the documentation doesn’t seem to distinguish the underlying platform, and documents asyncio.sleep(0) as a special case. I believe we should keep it as is or offer an alternative that doesn’t make asyncio.sleep(0) special anymore (like a scheduler, but we just removed the asycnio’s policies…).
@picnixzasyncio.sleep() has zero relation to time.sleep(). It is implemented differently and doesn’t call time.sleep() at all.
The proposal keeps existing asyncio.sleep(0) behavior as is because a change proposed by @mikeshardmind breaks some tests for PyPI top 100 libraries (and, sure, many other libraries not listed in the top 100 as well).
I know that it’s not calling time.sleep and my point wasn’t about the implementation but the semantics and why I believe asycnio.sleep(0) shouldn’t change (independently of downstream breakage). We document asyncio.sleep(0) as a special case already so we can’t change it. For time.sleep(0), the special case was only for Windows. I wanted to highlight the documented implementation details and anything changing that should offer an alternative (but since your proposal doesn’t change anything it’s fine).
I suspect that may miss Guido’s point: the top 100 libraries are well-tested (possibly incl. alternative event loops; across many Python versions; should be free from side-effects). Meanwhile, the long tail, the average Jane/Joe code may (Guido suggests, I think) use await asyncio.sleep(0) to work around concurrency bleh (something developer didn’t figure out, yet sleep(0) solves it), and these are the cases that may get subtly broken.
TBH, I don’t know how much of an issue this is. Over the years of coding all kinds of stuff, I recall sprinkling await asyncio.sleep(0) only once in application code where it mattered (code lost now), and one case in a library where it may or may not matter (for i in range(...): do.stuff(); await asyncio.sleep(i)). I’d say it’s relatively rare in decent code.
variable sleep, that may happen to be zero: hard to grasp
Going through the earlier, it seems more of a case of multiple libraries glued together, where correct synchronisation is not done (not possible, because no API; or author couldn’t be bothered), exemplified by:
async def start(gtk_app):
# give chence to the splash screen to appear
await asyncio.sleep(0)
gtk_app.register()
gtk_app.activate()
In this case, .register/.activate being synchronous calls, if they register callbacks, then there could be a case (imagine slightly different ordering) that proposal changes the observed behaviour, though I’d be more worried about the heisenbug of callbacks sometimes exceeding the deadline and other times not.
P.S. overall I think it’s a great, controlled change!
@dimaqq I agree.
My intuition whispers to me that asyncio.sleep(0) is a very important special case, it behavior should be preserved.
The same is for stopping the loop by run_until_complete() , some code could rely on it.
Both cases make the code for _run_once() a little more complex but it is the price for “don’t break anything” in that sensitive domain.