GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — gh-104144: Optimize gather to finish eagerly when all futures complete eagerly by itamaro · Pull Request #104138 · python/cpython

Conversation

@itamaro

@itamaro itamaro commented May 3, 2023 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

gh-97696 introduced eager tasks factory, which speeds up some async-heavy workloads by up to 50% when opted in.

installing the eager tasks factory applies out-of-the-box when gathering futures (asyncio.gather(...)), e.g.:

asyncio.get_event_loop().set_task_factory(asyncio.eager_task_factory)
await asyncio.gather(coro1, coro2, coro3)

coro{1,2,3} will eagerly execute the first step, and potentially complete without scheduling to the event loop if the coros don't block.

the implementation of eager uses callbacks internally that end up getting scheduled to the event loop even if all the futures were able to finish synchronously, and blocking the coroutine in which gather() was awaited, preventing the task from completing eagerly even if otherwise it could.

applications that use multiple levels of nested gathers can benefit significantly from eagerly completing multiple levels without blocking, as implemented in this PR by skipping scheduling done callbacks for futures that are already done (e.g. finished eagerly).

Benchmarks

this makes the async pyperformance benchmarks up to 3x faster (!!), using a patch to pyperformance that adds "eager" flavors

3.12-base.20230503.async.4.json
===============================

Performance version: 1.0.7
Python version: 3.12.0a7+ (64-bit) revision da1980afcb
Report on Linux-5.15.0-1033-aws-x86_64-with-glibc2.31
Number of logical CPUs: 72
Start date: 2023-05-03 23:27:23.329046
End date: 2023-05-03 23:46:37.706326

3.12-nogf.20230503.async.2.json
===============================

Performance version: 1.0.7
Python version: 3.12.0a7+ (64-bit) revision 5397cd9f62
Report on Linux-5.15.0-1033-aws-x86_64-with-glibc2.31
Number of logical CPUs: 72
Start date: 2023-05-03 23:05:45.011427
End date: 2023-05-03 23:22:44.908094

+-------------------------------+---------------------------------+---------------------------------+--------------+------------------------+
| Benchmark                     | 3.12-base.20230503.async.4.json | 3.12-nogf.20230503.async.2.json | Change       | Significance           |
+===============================+=================================+=================================+==============+========================+
| async_tree_cpu_io_mixed       | 868 ms                          | 859 ms                          | 1.01x faster | Not significant        |
+-------------------------------+---------------------------------+---------------------------------+--------------+------------------------+
| async_tree_eager              | 391 ms                          | 129 ms                          | 3.03x faster | Significant (t=209.74) |
+-------------------------------+---------------------------------+---------------------------------+--------------+------------------------+
| async_tree_eager_cpu_io_mixed | 756 ms                          | 490 ms                          | 1.54x faster | Significant (t=167.41) |
+-------------------------------+---------------------------------+---------------------------------+--------------+------------------------+
| async_tree_eager_io           | 1.51 sec                        | 1.50 sec                        | 1.00x faster | Not significant        |
+-------------------------------+---------------------------------+---------------------------------+--------------+------------------------+
| async_tree_eager_memoization  | 595 ms                          | 314 ms                          | 1.89x faster | Significant (t=70.25)  |
+-------------------------------+---------------------------------+---------------------------------+--------------+------------------------+
| async_tree_io                 | 1.39 sec                        | 1.40 sec                        | 1.00x slower | Not significant        |
+-------------------------------+---------------------------------+---------------------------------+--------------+------------------------+
| async_tree_memoization        | 677 ms                          | 683 ms                          | 1.01x slower | Not significant        |
+-------------------------------+---------------------------------+---------------------------------+--------------+------------------------+
| async_tree_none               | 575 ms                          | 574 ms                          | 1.00x faster | Not significant        |
+-------------------------------+---------------------------------+---------------------------------+--------------+------------------------+
  • Issue: Leverage eager tasks to optimize asyncio gather & TaskGroups further #104144

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@AlexWaygood AlexWaygood added the topic-asyncio label May 3, 2023
@itamaro
gh-NNNN: Skip creating GatheringFuture if all futures finished eagerly
b3e479a
@itamaro
itamaro force-pushed the asyncio-skip-gathering-future branch from 4a5d42c to b3e479a Compare May 3, 2023 20:57
@itamaro itamaro changed the title gh-NNNN: Skip creating GatheringFuture if all futures finished eagerly gh-104144: Skip creating GatheringFuture if all futures finished eagerly May 3, 2023
@bedevere-bot bedevere-bot mentioned this pull request May 3, 2023
Leverage eager tasks to optimize asyncio gather & TaskGroups further #104144
Closed
@itamaro
Add NEWS entry
8eeebaf
@itamaro
itamaro marked this pull request as ready for review May 3, 2023 23:52
@itamaro
itamaro requested review from 1st1, asvetlov, gvanrossum, kumaraditya303 and willingc as code owners May 3, 2023 23:52
carljm
carljm reviewed May 4, 2023
View reviewed changes

@carljm carljm left a comment

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks pretty straightforward and reasonable to me, but would prefer for asyncio experts to take a look.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

itamaro reacted with thumbs up emoji
All reactions
  • 👍 1 reaction
Comment thread Misc/NEWS.d/next/Library/2023-05-03-16-50-24.gh-issue-104144.yNkjL8.rst Resolved

Uh oh!

There was an error while loading. Please reload this page.

@itamaro @carljm
Apply review suggestion to NEWS entry
9289c9e
Co-authored-by: Carl Meyer <[email protected]>
jbower-fb
jbower-fb suggested changes May 4, 2023
View reviewed changes

@jbower-fb jbower-fb left a comment •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you look at gather._done_callback() you'll see it has a bunch of logic which gets executed at the moment all the futures have finished (starting from if nfinished == nfuts: on line 781). If all args can complete eagerly then this will be executed eagerly too.

This might have a few issues:

  • At this point outer will be None and this will cause trouble on line 803. (Maybe I missed something because I'm surprised this hasn't come up yet).
  • Handling for futures that were cancelled during eager execution is processed but the results discarded.
  • We inefficiently create a result list which we discard and then repeat when creating the eagerly completed future result.

Fortunately, I think an easy fix is to move creation of the eager result future to before the argument processing loop. See my in-line comments for specifics.

I'm not 100% sure how this will affect the issue described in bpo-46672, but it has a test so we'll see.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

itamaro reacted with thumbs up emoji
All reactions
  • 👍 1 reaction
Comment thread Lib/asyncio/tasks.py Resolved

Uh oh!

There was an error while loading. Please reload this page.

Comment thread Lib/asyncio/tasks.py Resolved

Uh oh!

There was an error while loading. Please reload this page.

Comment thread Lib/asyncio/tasks.py Resolved

Uh oh!

There was an error while loading. Please reload this page.

Comment thread Lib/asyncio/tasks.py Resolved

Uh oh!

There was an error while loading. Please reload this page.

Comment thread Lib/asyncio/tasks.py Resolved

Uh oh!

There was an error while loading. Please reload this page.

Comment thread Lib/asyncio/tasks.py Outdated
outer = futures.Future(loop=loop)
outer.set_result([c.result for c in children])
else:
outer = _GatheringFuture(children, loop=loop)

@jbower-fb jbower-fb May 4, 2023

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
outer = _GatheringFuture(children, loop=loop)
outer.__self_log_traceback = False
outer = _GatheringFuture(children, loop=loop)

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@bedevere-bot bedevere-bot added the awaiting core review label May 4, 2023
itamaro added 2 commits May 5, 2023 11:50
@itamaro
Merge branch 'main' into asyncio-skip-gathering-future
edbb04c
@itamaro
Modify implementation to eagerly call done callbacks at the end of th…
9be6e51
…e loop, after the GatheringFuture (outer) is created
@carljm

carljm commented May 5, 2023

Copy link
Copy Markdown
Member

The title no longer accurately describes the updated PR, since the _GatheringFuture is always created.

itamaro reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@itamaro

itamaro commented May 5, 2023

Copy link
Copy Markdown
Contributor Author

thanks for the review @jbower-fb !

I pushed a new version of the PR based on your suggestions, but not identical.
summary of my changes:

  • instead of immediately calling the done callbacks for eagerly completed futures in the loop, I add them to a list and call their callbacks only at the end, after creating the outer future
  • this helps because now outer is defined the same way, and the children list is fully populated, which is also important because the done callback uses the children list
  • I always create a GatheringFuture so I get the same cancellation treatment, but it will still finish eagerly if all futures completed eagerly thanks to the last done callback right before returning
  • there shouldn't be any issues with bpo-46672 since outer looks the same as before
jbower-fb reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@itamaro itamaro changed the title gh-104144: Skip creating GatheringFuture if all futures finished eagerly gh-104144: Optimize gather to finish eagerly when all futures complete eagerly May 5, 2023
@bedevere-bot bedevere-bot added awaiting review and removed awaiting core review labels May 5, 2023
@itamaro

itamaro commented May 5, 2023

Copy link
Copy Markdown
Contributor Author

The title no longer accurately describes the updated PR, since the _GatheringFuture is always created.

thanks, I updated the title!

carljm reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

itamaro added 2 commits May 5, 2023 14:14
@itamaro
update inline comment and NEWS entry
250b73c
@itamaro
Merge branch 'main' into asyncio-skip-gathering-future
7df90eb
gvanrossum
gvanrossum approved these changes May 6, 2023
View reviewed changes

@gvanrossum gvanrossum left a comment

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, will fix the typo. Maybe @carljm can merge when you all are agreed on this. Nice fix!

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread Misc/NEWS.d/next/Library/2023-05-03-16-50-24.gh-issue-104144.yNkjL8.rst Resolved

Uh oh!

There was an error while loading. Please reload this page.

@bedevere-bot bedevere-bot added awaiting merge and removed awaiting review labels May 6, 2023
@gvanrossum
Fix NEWS typo
ce52714
@AlexWaygood AlexWaygood added the performance Performance or resource usage label May 6, 2023
@gvanrossum

gvanrossum commented May 6, 2023

Copy link
Copy Markdown
Member

PS. In general there's no need to click the "Update branch" button (or otherwise merge main back into the PR) unless there are fixes/changes that might affect the PR (e.g. if touching the same file).

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

kumaraditya303
kumaraditya303 approved these changes May 6, 2023
View reviewed changes
@kumaraditya303
kumaraditya303 enabled auto-merge (squash) May 6, 2023 14:55
@kumaraditya303
kumaraditya303 merged commit 263abd3 into python:main May 6, 2023
@bedevere-bot bedevere-bot removed the awaiting merge label May 6, 2023
@itamaro
itamaro deleted the asyncio-skip-gathering-future branch May 7, 2023 22:16
jbower-fb pushed a commit to jbower-fb/cpython that referenced this pull request May 8, 2023
@itamaro @jbower-fb
pythongh-104144: Optimize gather to finish eagerly when all futures c…
cb70222
…omplete eagerly (python#104138)
@voorhs voorhs mentioned this pull request Aug 26, 2026
Scheduler.wait_and_close() livelocks at 100% CPU when a shielded future is already done (Python 3.12+) aio-libs/aiojobs#623
Open
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@carljm carljm carljm left review comments
@gvanrossum gvanrossum gvanrossum approved these changes
@kumaraditya303 kumaraditya303 kumaraditya303 approved these changes
@1st1 1st1 Awaiting requested review from 1st1 1st1 is a code owner
@asvetlov asvetlov Awaiting requested review from asvetlov asvetlov is a code owner
@willingc willingc Awaiting requested review from willingc willingc is a code owner
+1 more reviewer
@jbower-fb jbower-fb jbower-fb requested changes
Reviewers whose approvals may not affect merge requirements

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

performance Performance or resource usage topic-asyncio

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Uh oh!

There was an error while loading. Please reload this page.

7 participants

@itamaro @carljm @gvanrossum @jbower-fb @kumaraditya303 @bedevere-bot @AlexWaygood
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.