Skip to content

Added TrioEventLoop - #372

Merged
tonycpsu merged 4 commits into
urwid:masterfrom
collmot:feature/trio-event-loop
Nov 5, 2019
Merged

tonycpsu merged 4 commits into
urwid:masterfrom
collmot:feature/trio-event-loop

Conversation

@ntamas

@ntamas ntamas commented Oct 24, 2019

Copy link
Copy Markdown
Contributor
Checklist
  • I've ensured that similar functionality has not already been implemented
  • I've ensured that similar functionality has not earlier been proposed and declined
  • I've branched off the master or python-dual-support branch
  • I've merged fresh upstream into my branch recently
  • I've ran tox successfully in local environment
  • I've included docstrings and/or documentation and/or examples for my code (if this is a new feature)
Description:

This PR adds support for Trio-based event loops. Trio is an asyncio alternative for Python 3.5.

The PR implements the same functionality as #298 but with more modern Trio constructs (detached cancel scopes) that were proposed in the comments of #298 by @njsmith

@coveralls

coveralls commented Oct 24, 2019 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.3%) to 77.333% when pulling 94cebe5 on collmot:feature/trio-event-loop into 96a1be0 on urwid:master.

@ntamas ntamas mentioned this pull request Oct 24, 2019
4 of 6 tasks
Comment thread urwid/_async_kw_event_loop.py Outdated
This is needed because `CancelScope.cancelled_caught` stays `False` until
someone actually _handles_ the cancellation, and
`CancelScope.cancel_called` can only be called from an async context
(which we cannot guarantee).

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Huh, does urwid use threads? "async context" just means "inside the same thread where trio.run is running".

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I had to use this solution because the unit tests failed if I simply relied on CancelScope.cancelled_caught. There is one unit test where the code calls loop.remove_watch(some_handle) twice and checks whether the first one returns True (since the handle was removed) and the second one returns False. Since there is no checkpoint between the two calls anywhere, cancelled_caught is still False for the second invocation. Having realized this, I tried using cancel_called instead, and that's where I received an exception about not calling cancel_called within an async context.

It could be the case that the unit test is doing something fishy (e.g., not actually running the loop but just adding and removing a handle outside the loop), but since this part of the unit test is common for all event loop tests within urwid, it seemed easier not to argue about changing the unit test itself.

As for threads - urwid does not use threads as far as I know and is not thread-safe either, although I can imagine that certain urwid apps indeed use threads and call urwid functions from different threads. (I have tried this myself a few years ago, not having realized that urwid is thread-safe, and it sort-of-kind-of worked).

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

It could be the case that the unit test is doing something fishy (e.g., not actually running the loop but just adding and removing a handle outside the loop), but since this part of the unit test is common for all event loop tests within urwid, it seemed easier not to argue about changing the unit test itself.

I see, yeah, that must be what's going on. If the loop was running then cancel_called would work.

It sounds like there's an argument for fixing the test, rather than adding contortions to the main loop to work around these issues, but I can see why you might not want to argue about it too...

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It sounds like there's an argument for fixing the test, rather than adding contortions to the main loop to work around these issues

@tonycpsu @ulidtko Not sure who calls the shots in issues like this; would you be open to changing the unit tests such that the tests for the remove_alarm() and remove_watch_file() calls (in test_remove_alarm() and test_remove_watch_file(), respectively) are also executed while the event loop is running? The reason is that right now in the implementation of the Trio event loop we need to jump through extra hoops to make these methods work even outside the event loop. (For me it's okay to keep it this way - after all, it works - I just need a second opinion).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@ntamas : I agree with @njsmith that fixing the test code is preferable to complicating the run loop code. As long as the test code changes don't cause any test failures when testing with the other run loops, I don't have a problem with it. If it does, then those would need to be addressed, and at that point maybe we just accept what you have that's working now and live to fight another day.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the feedback - I'll give it a go to refactor the tests and simplify the run loop and I'll push the changes here if it works smoothly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

PR updated - I have changed the tests a bit and it now works without additional hackery in the TrioEventLoop code.

Note that I needed to changed the tests for the TwistedEventLoop as well because its reactor cannot be restarted.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nice, looks good. Thanks much for the contribution!

Comment thread urwid/_async_kw_event_loop.py Outdated
while True:
await self._sleep(self._idle_emulation_delay)
for idle_callback in self._idle_callbacks.values():
idle_callback()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

It's a bit unfortunate that this needs to wake up constantly, even if there isn't actually any work to do; it hurts battery life b/c it stops CPUs from going to sleep. I think it's fine for a first version, but I do wonder if there's any way to avoid that.

At first I thought well, maybe we can only run the loop while there's an idle function actually registered. But I checked and it looks like urwid always has an idle function registered, so that wouldn't actually help anything.

The reason urwid always has an idle function registered is that it uses it to redraw the screen. Which struck me as a weird thing to do from an idle callback, since normally you'd only want to redraw the screen after something changed, not when the program is sitting there idle!

After looking a bit more I think what's going on here is:

urwid's own home-grown loop calls the idle callbacks exactly once before each time it sleeps for an extended period. So the idea is that you go back and forth between executing code, and sleeping; and we assume that the screen might change while executing code, but not while sleeping, so we want to update the screen on those transitions. It's a little bit hacky compared to a more fine-grained system that actually tracks whether the screen needs redraw (e.g. it might do extra redraws, or if the program is busy for a while then it might not redraw for a while), but it's a lot simpler to implement than fine-grained damage tracking, and probably works about 99% as well in practice, so it makes sense.

However, other main loops don't actually provide this operation. E.g. Glib has something called an "idle callback", but it runs constantly whenever the loop could otherwise be sleeping, which is very different. But, since they're both named "idle callback", maybe no-one noticed?

So like... maybe the real solution here is for urwid to implement a fine-grained damage tracking system, which might be non-trivial, but I think it's the only way to really properly support external event loops.

In the mean time...... there is a way to get the original run-once-before-sleeping semantics in Trio. It doesn't fix the issue for other loops like glib, and it's pretty gross, but maybe it's a reasonable medium-term hack.

What you could do is use Trio's instrumentation API. Normally this is intended for debugging and profiling, but it does let you find out when Trio is about to go to sleep and run some code.

Because they're a low-level debugging interface, instrumentation hooks run in a weird context: you have to be very careful not to let any exceptions escape, and you're not inside any task so you can't await or use the cancellation machinery normally. (Though you should still be able to do operations that rely on run-global state, like call trio.current_time().)

Anyway, like I said, I don't think you necessarily need to do anything about this now. But it's interesting to think about the options...

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It's a bit unfortunate that this needs to wake up constantly, even if there isn't actually any work to do

Yes, I felt bad about this for a while until I realized that urwid registers an idle callback for redrawing the screen anyway so there's always at least one idle callback. Other async event loops like the one for Twisted or asyncio also handle things in a similar way and I did not know that Trio's event loop actually has a concept similarly to the idle callback of urwid's default select-based loop.

I'll investigate whether I could use the instrumentation API for the event loop. In the previous PR, you suggested using wait_all_tasks_blocked() instead - wouldn't that be a better option? (At least in the sense that we don't need to register a custom instrument).

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

In the previous PR, you suggested using wait_all_tasks_blocked() instead - wouldn't that be a better option? (At least in the sense that we don't need to register a custom instrument).

Not really, unfortunately – if you wrote a loop like:

while True:
    await wait_all_tasks_blocked()
    ...

...then the loop would indeed wait until the program was otherwise idle before starting to run, but once the rest of the program became idle then it would keep running constantly, similarly to the loop you have now.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Okay, I have tried to use the instrumentation API (haven't committed it yet), and it seems to work - at least the unit tests pass correctly. Would before_io_wait() also get called if there are no IO tasks to wait for at all and there are only pending sleep() calls that might wake up the Trio loop?

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Would before_io_wait() also get called if there are no IO tasks to wait for at all and there are only pending sleep() calls that might wake up the Trio loop?

Yeah... the name is maybe a bit confusing, actually. Operating systems provide a single combined check-for-I/O-and-maybe-wait-for-timeouts-to-expire operation, so Trio always uses that. Sometimes Trio just wants to check for I/O without waiting (because there are other tasks already ready to run), sometimes it just wants to wait for timeouts, sometimes it wants to do both at once – in all cases it uses the same underlying operation. And in all cases it calls before_io_wait.

You can tell whether it's going to sleep, actually. If the timeout passed in to before_io_wait is zero, then it means there are already tasks ready to run, and Trio is just doing a quick check to see if any I/O has appeared – it isn't actually going to wait, despite the name. If the timeout argument is > zero, then it means Trio is ready to sleep for a bit.

I guess to really match the traditional urwid semantics, you could make your idle callbacks only run when timeout > 0. I'm not sure if this is actually better or not – the tradeoff is that we do fewer screen refreshes, which is more efficient (Trio often does a quick check for I/O even though the program is otherwise busy), but if the program is busy for a while then it could cause the screen refreshes to get out of date.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Okay, I have updated my PR with your suggestions - thanks a lot!

Also adjusted tests to ensure that `remove_alarm()` and 
`remove_watch_file()` are called only when the loop is running.
@tonycpsu
tonycpsu merged commit 14813f4 into urwid:master Nov 5, 2019
@ntamas
ntamas deleted the feature/trio-event-loop branch November 5, 2019 19:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants