Visitar URL original
gh-96471: Add asyncio queue shutdown by EpicWink · Pull Request #104228 · python/cpython · GitHub
The Wayback Machine - https://web.archive.org/web/20240405141056/https://github.com/python/cpython/pull/104228
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-96471: Add asyncio queue shutdown #104228

Open
wants to merge 28 commits into
base: main
Choose a base branch
from

Conversation

EpicWink
Copy link
Contributor

@EpicWink EpicWink commented May 6, 2023 •

asyncio-only changes from #102499 (which supercedes #96474), updated to match the API introduced by #104750


📚 Documentation preview 📚: https://cpython-previews--104228.org.readthedocs.build/

EpicWink and others added 2 commits May 6, 2023 14:50
* Queue state enum members are capitalised
* Termination state in str/repr
* Include raised exception in docstrings
* Factor out queue-state checks and updates to methods
* Logic fixes in get_nowait and shutdown
* Handle queue shutdown in task_done and join
* Updated tests
* Document feature added in 3.13
@EpicWink
Copy link
Contributor Author

EpicWink commented May 6, 2023

@willingc ready for review

@gvanrossum
Copy link
Member

asyncio-only changes from #102499 (on top of #96474)

I assume the "on top of ..." part is obsolete, since that PR was closed without merging. I'll add @willingc as a reviewer per your request.

@gvanrossum gvanrossum requested a review from willingc May 9, 2023 17:56
@gvanrossum
Copy link
Member

@EpicWink Could you merge main?

@EpicWink
Copy link
Contributor Author

Could you merge main?

Done, but like #104750, we may want to modify the implementation of immediate=True to simply consume the queue rather than having a separate state.

@gvanrossum
Copy link
Member

Eh, @EpicWink, did you see the hubbub about the hanging test in your previous PR? The test was disabled because it kept hanging in CI on various platforms. Could you look into what's wrong with it? (At least the feature wasn't reverted.)

@EpicWink
Copy link
Contributor Author

Eh, @EpicWink, did you see the hubbub about the hanging test in your previous PR? The test was disabled because it kept hanging in CI on various platforms. Could you look into what's wrong with it?

I did see the follow-on issue and pull-requests. Yves and I are working on fixing it (you can follow the changes here: main...EpicWink:cpython:fix-thread-queue-shutdown-test)

@gvanrossum
Copy link
Member

Awesome! (An acknowledgement that you were working on it would have lessened my stress. :-)

@gvanrossum
Copy link
Member

Looking at this with an eye towards review, I realized that the threaded-queue implementation doesn't appear to match its documentation: It appears that q.join() does not raise ShutDown when the queue is shutdown immediately. The tests don't seem to be testing for this either. (Come to think of it, the test never seems to take the except self.queue.ShutDown path -- if I put a breakpoint there it never gets hit during any of the tests. The test logic is pretty convoluted, which is my only excuse for not having caught this in the review of gh-104750.)

@EpicWink
Copy link
Contributor Author

EpicWink commented Feb 22, 2024 via email

@gvanrossum
Copy link
Member

Now that the immediate-consume implementation of the threading queue shutdown has been accepted, I'm going to do the same here and for multiprocessing. I'll personally rewrite the tests to be more readable and obvious.

And what about queue.Queue.join()? Should it raise after shutdown(immediate=True)? Either way some changes are needed -- either in the implementation or in the docs. And the tests there too (what you wrote above appears to apply to the asyncio and multiprocessing versions only.)

Copy link
Member

@gvanrossum gvanrossum left a comment

Choose a reason for hiding this comment

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

I'll wait reviewing until you've rewritten shutdown, but here's one doc markup nit.

Also, please mark PRs that aren't ready for review as Draft.

Doc/library/asyncio-queue.rst Outdated Show resolved Hide resolved
@EpicWink EpicWink marked this pull request as draft February 22, 2024 01:14
@EpicWink
Copy link
Contributor Author

And what about queue.Queue.join()? Should it raise after shutdown(immediate=True)? Either way some changes are needed -- either in the implementation or in the docs. And the tests there too (what you wrote above appears to apply to the asyncio and multiprocessing versions only.)

The behaviour should (and I intend to implement it to) be the same between the threading, multiprocessing and asyncio queues

@YvesDup
Copy link
Contributor

YvesDup commented Feb 22, 2024 •

By the way, should task_done() raise an exception after shutdown or not ?
update; see https://docs.python.org/3.13/library/queue.html#queue.Queue.task_done

@EpicWink
Copy link
Contributor Author

EpicWink commented Feb 25, 2024 •

By the way, should task_done() raise an exception after shutdown or not ?

@YvesDup No (except the usual ValueError); see #115838

@YvesDup
Copy link
Contributor

YvesDup commented Mar 27, 2024

With your actual organization (test_shutdown_empty, test_shutdown_nonempty), its seems to me harder to follow the test purposes. It'is up to you.

Each test is a different scenario, and I'm checking (hopefully) the full externally-visible state and functionality for each scenario. I think I will add more comments in these tests.

Thank for all the comments, this is really easier to understand.
IMO an important use case is missing: the context is when there are an empty queue and a pending get.

  • when shutdown is not immediate, the task still stay in the q._gettersand we have to cancel it.
  • when shutdown is immediate, this task is removed in the shutdownmethod.

It could be based on following code:

async def _test_shutdown_pending_get(immediate_=False):
    async def _get(q, res):
        try:
            r = await q.get()
            res.append(r)
        except asyncio.queues.QueueShutDown:
            res.append(True)
        except asyncio.CancelledError:
            res.append(False)

    res = []
    q = asyncio.Queue(1)
    loop = asyncio.get_running_loop()
    get_task = loop.create_task(_get(q, res))
    await _ensure_started(get_task)

    q.shutdown(immediate=immediate_)
    if not immediate_:
        get_task.cancel()

    await get_task
    assert(res[0] == immediate_)

@gvanrossum
Copy link
Member

Hey guys, great progress here. Can you at-mention me on this PR when you're ready for review? I recommend merging main just before you do that (don't rebase please).

@EpicWink
Copy link
Contributor Author

EpicWink commented Mar 28, 2024 •

IMO an important use case is missing: the context is when there are an empty queue and a pending get.

* when shutdown is not immediate, the task still stay in the `q._getters`and we have to cancel it.

* when shutdown is immediate, this task is removed in the `shutdown`method.

@YvesDup No, in both cases the task should raise ShutDown: when the queue is empty, there should be no distinction between immediate and non-immediate shutdown (ignoring unfinished-tasks). I'm fixing I have fixed this bug and updating the test.


The failing multi-processing WithProcessesTestBarrier tests in the Windows 64-bit free-threading builds seem unrelated

@EpicWink
Copy link
Contributor Author

@gvanrossum ready for review

@YvesDup
Copy link
Contributor

YvesDup commented Apr 3, 2024

in both cases the task should raise ShutDown: when the queue is empty, there should be no distinction between immediate and non-immediate shutdown (ignoring unfinished-tasks).

@EpicWink , there is the same bug on threading queue shutdown. I will open an issue.

Copy link
Member

@gvanrossum gvanrossum left a comment •

Choose a reason for hiding this comment

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

Hi there! I'm torn. This looks great apart from 1-2 teensy nits, but the tests are a lot of code that I haven't fully grokked yet. I want to trust that you two have done the right thing there, but at the same time I remember that the threaded queue tests had some issue that caused random CI flakiness. While I ponder this I'm going to start a buildbots run to hopefully smoke out any test flakes.

Meanwhile, can you address my nits and merge main (there's a simple conflict in what's new), but not push until the big test run completes? (Buildbot tests can take many hours, sorry.)

EDIT: I went ahead and merged the conflict, since tests won't run when there's a conflict.

Lib/asyncio/queues.py Outdated Show resolved Hide resolved
Lib/asyncio/queues.py Outdated Show resolved Hide resolved
Lib/asyncio/queues.py Outdated Show resolved Hide resolved
Lib/asyncio/queues.py Outdated Show resolved Hide resolved
@gvanrossum gvanrossum added the 🔨 test-with-buildbots Test PR w/ buildbots; report in status section label Apr 3, 2024
@bedevere-bot
Copy link

🤖 New build scheduled with the buildbot fleet by @gvanrossum for commit 2fa1bd9 🤖

If you want to schedule another build, you need to add the 🔨 test-with-buildbots label again.

@bedevere-bot bedevere-bot removed the 🔨 test-with-buildbots Test PR w/ buildbots; report in status section label Apr 3, 2024
@gvanrossum
Copy link
Member

gvanrossum commented Apr 3, 2024 •

ALso, why is the DO-NOT-MERGE label set? Is it because of this?

EIT: But that is fixed (I actually stumbled over this, wondering why you always wake up all getters -- and came to the conclusion that it is needed).

Copy link
Member

@gvanrossum gvanrossum left a comment

Choose a reason for hiding this comment

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

Hm... Now that I've actually looked, I think these tests work, but could be simplified a bunch. Here are my additional comments.

Lib/test/test_asyncio/test_queues.py Outdated Show resolved Hide resolved
Lib/test/test_asyncio/test_queues.py Outdated Show resolved Hide resolved
Lib/test/test_asyncio/test_queues.py Outdated Show resolved Hide resolved
Comment on lines +576 to +585
# Ensure put() and get() raise ShutDown
with self.assertRaisesShutdown():
await q.put("data")
with self.assertRaisesShutdown():
q.put_nowait("data")

with self.assertRaisesShutdown():
await q.get()
with self.assertRaisesShutdown():
q.get_nowait()
Copy link
Member

Choose a reason for hiding this comment

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

Since you have these I'm not sure why you also have a task exercising q.get()?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm testing await q.get() raises after shutting down here, but for the previous task the get() is started before the shut down

Lib/test/test_asyncio/test_queues.py Outdated Show resolved Hide resolved
q = self.q_class(maxsize=1)
loop = asyncio.get_running_loop()

q.put_nowait("data")
Copy link
Member

Choose a reason for hiding this comment

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

Why not just await q.put("data")?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

In this scenario the two are equivalent (the queue is not empty, there are no other tasks scheduled), so I thought put_nowait was more explicit

@EpicWink
Copy link
Contributor Author

EpicWink commented Apr 4, 2024

I want to trust that you two have done the right thing there

@gvanrossum please don't trust, have you seen xz-utils's backdoor?

but not push until the big test run completes? (Buildbot tests can take many hours, sorry.)

Oops, sorry. I forgot to hold off my most recent push

ALso, why is the DO-NOT-MERGE label set? Is it because of #104228?

No, I think it was because I hadn't updated the implementation to match the new agreed-upon behaviour (this PR was in draft at that time anyway, so I don't think the label was needed).

wondering why you always wake up all getters -- and came to the conclusion that it is needed

I should probably add a comment

@EpicWink
Copy link
Contributor Author

EpicWink commented Apr 4, 2024

there is the same bug on threading queue shutdown. I will open an issue.

@YvesDup I've created issue #117531, and fix in PR #117532

# Setup queue with 2 items (1 retrieved), and a join() task
q = self.q_class()
loop = asyncio.get_running_loop()
q.put_nowait("data")
Copy link
Contributor

Choose a reason for hiding this comment

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

I suggest:

q.put_nowait("data1")
q.put_nowait("data2")

q.put_nowait("data")
q.put_nowait("data")
join_task = loop.create_task(q.join())
self.assertEqual(await q.get(), "data")
Copy link
Contributor

Choose a reason for hiding this comment

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

and testing on "data1".

Copy link
Contributor Author

@EpicWink EpicWink Apr 4, 2024 •

Choose a reason for hiding this comment

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

Except when q is an instance of LifoQueue, when the value should be "data2". Is it necessary to test queue ordering in the shutdown tests?

Copy link
Contributor

Choose a reason for hiding this comment

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

I forgot the LifoQueue class. Is this worth commenting on?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I have implemented your suggestion, but I have not committed. I am considering it. I don't think it's necessary.

Copy link
Contributor

Choose a reason for hiding this comment

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

The test case (thus including LifoQueue) is implicit. A comment would be enough.

@YvesDup
Copy link
Contributor

YvesDup commented Apr 4, 2024

there is the same bug on threading queue shutdown. I will open an issue.

@YvesDup I've created issue #117531, and fix in PR #117532

I have seen and commented

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

Successfully merging this pull request may close these issues.

None yet

5 participants