Skip to content

Add block_on_detached and maintain separate task queues per executor - #1794

Closed
tschneidereit wants to merge 2 commits into
bytecodealliance:mainfrom
tschneidereit:block-on-detached
Closed

tschneidereit wants to merge 2 commits into
bytecodealliance:mainfrom
tschneidereit:block-on-detached

Conversation

@tschneidereit

Copy link
Copy Markdown
Member

The first commit here fixes issues with task queue management, by maintaining separate queues per executor. Building on that, the second one introduces a new function, block_on_detached, which blocks on a single task, but doesn't use the inner executor's queue for tasks spawned while processing that task.

`rust_spawn` now pushes the task onto a queue in the `SharedTaskState` its
`ptr` argument points to, and each executor drains only its own queue.
Previously all executors of one `wit-bindgen` copy shared a static queue, so
a `block_on` call ran tasks that the enclosing task had spawned earlier in
the same poll.
`block_on_detached` is the same as `block_on`, except that tasks spawned with
`spawn_local` during the call are spawned onto the task that encloses the
call, through that task's `rust_spawn` hook. That task's executor runs them
after the call returns, where `block_on` would drain them inline.
@tschneidereit

Copy link
Copy Markdown
Member Author

For context, I need something like this for debugging support in StarlingMonkey, where tasks spawned from under the debugger shouldn't go on the debugger's executor's queue.

Also, I'm happy to split this into separate PRs if that seems better. The first one didn't seem very strongly motivated without the second one.

@alexcrichton alexcrichton left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Trying to think through this, would it perhaps make sense to delete block_on_detached and have that just be the default behavior of block_on? I sort of wish we could get rid of spawn_local given how fundamentally broken it is in relation to block_on... Another alternative would to to move to something more Tokio-like where executors are more explicitly created and managed, and in such a scenario block_on would be forbidden within an async task because you would be disallowed from reentrantly entering an executor.

@tschneidereit

Copy link
Copy Markdown
Member Author

If you think that making this the default behavior will not cause meaningful breakage, then yes, that'd make sense to me! I'll look into it and update the PR if that seems to work out. (Whereas I don't think I have the expertise needed to make bigger changes along the lines of what you described.)

@alexcrichton

Copy link
Copy Markdown
Member

Yeah if anything I'd expect it to help more than it hurts because that way block_on can actually return and the task lives "even more in the background". And yeah I don't see any other great solution right now to the other issues, sorry I'm just sort of waxing a bit...

@tschneidereit

Copy link
Copy Markdown
Member Author

This isn't entirely straightforward a change, unfortunately. Might still make sense, but has some downsides:

  1. It only works if we support running spawned tasks under the block_on if there isn't an outer task. Here's an example of code that would break otherwise.
  2. With the first commit in this PR, a nested block_on that awaits its own spawn works. With this change, it'd silently deadlock instead. That probably doesn't matter, since it currently also doesn't work, but ideally we'd at least detect the deadlock and abort instead.
  3. It's as you know fairly common to accidentally have multiple versions of wit-bindgen in an app. With forwarding as the default, we'd panic if the outer task was spawned by an older version. We could detect that and run the task under the block_on instead in that situation, but then behavior would change when the old version is removed.

On the general idea of forbidding block_on within async tasks: we'd then at least have to introduce something equivalent to block_on_detached again to allow it in situations where it's really needed—same as Tokio did with block_in_place. StarlingMonkey certainly does need this ability to make the debugger work, for example.

Looking back at this, it all seems reasonable to me, though the third issue seems kinda gnarly. WDYT?

@alexcrichton

Copy link
Copy Markdown
Member

Hm... could you detail a bit more about the rationale for this? Why is it required to get recursive invocations working? For example it sounds like block_on_detached, as proposed, also would break if you were to await on spawned tasks b/c they'd only be polled by the outer executor. Overall it seems like we really should be forbidding nested executors because everything gets too confusing.

@tschneidereit

Copy link
Copy Markdown
Member Author

No, I want spawned tasks to be polled by the outer executor—hence the need for block_on_detached's semantics in the first place. My point was about your suggestion that ideally we'd forbid block_on under async tasks entirely: that would break debugging for JS. When execution hits a breakpoint during execution, I need to be able to communicate with the debugger client while the stack stays where it currently is. You're right that .awaiting any tasks spawned from under block_on_detached would deadlock, and StarlingMonkey doesn't do that and has documentation warning against it. (Detecting the deadlock and panicking would obviously be great to have for this, though.)

Conversely, if we panic instead of forwarding, doing things like evaluating JS that calls fetch from under the debugger wouldn't work anymore, where it currently does. The returned promise just doesn't resolve until execution resumes.

@alexcrichton

Copy link
Copy Markdown
Member

To clarify, my understanding is that this PR as-is behaves as:

  • block_on - allowed anywhere and spawned tasks just prevent block_on from returning. Spawned tasks get polled as usual on normal async/await interactions. Outer spawned tasks, however, never get polled because the outer executor is never consulted.
  • block_on_detached - required to be in the context of an outer event loop, and spawned tasks never get polled until block_on_detached returns. Outer spawned tasks also aren't polled.

Additionally, in my mind, block_on, in both forms, is fundamentally broken w.r.t. spawn. (nested executors which never really plays well)

You say you want spawned tasks to be polled by the outer executor, can you clarify if you need that during the block_on_detached future or only after? As-is I would expect that during block_on_detached they're never polled. And yeah I don't want to break things, but can you explain a bit more why debugging in JS fundamentally relies on this ability? I don't know much about how spidermonkey debugging works myself.

@tschneidereit

Copy link
Copy Markdown
Member Author

To clarify, my understanding is that this PR as-is behaves as

That's pretty much it, yeah. One slight correction on block_on_detached: it can be called anywhere. Only spawn_local panics if there's no enclosing task.

You say you want spawned tasks to be polled by the outer executor, can you clarify if you need that during the block_on_detached future or only after?

Only after, so things like fetch called from under the debugger (which supports evaluating code) works. In theory I could hold all tasks back manually in StarlingMonkey and only turn them into actual async tasks upon resumption I guess, but that'd be very messy and error-prone I think, in addition to being a lot of effort.

And yeah, fundamentally I do need a nested executor / event loop here. I know those suck, but they're needed here. The same is true in browser devtools as well, and leads to a bunch of complexity in engines. (Here's as an example V8's version of this).

This requirement follows from the fact that the debugger itself is implemented in the same engine as the debuggee, and needs an event loop of its own, all the while the outer event loop is paused and the stack can't be unwound until the debugger continues.

If you're interested in more details for SpiderMonkey specifically:

The way debugging works in SpiderMonkey is that there's a Debugger object which you have available in separate globals, and which you can use to register debuggee globals. Once you do, you can register hooks for things like entering and exiting a frame, set breakpoints, etc. These hooks run synchronously, and stop the outer event loop.

The code implementing the debugger's server side is implemented in JS itself, and can use async features. And has to, because it communicates via a socket, so must be able to do IO.

@alexcrichton

Copy link
Copy Markdown
Member

Hm ok, well somehow I still feel that something needs to change here but I'm still not entirely sure how. Already today spawn_local makes no sense w.r.t. block_on. This is adding a second block_on_detached which deepens the confusion further because now spawn_local can panic if block_on_detached wasn't enclosed by something. Further confusion can arise because spawn_local is sibling-polled in block_on, but not block_on_detached, so after this PR spawn_local could (a) work and be polled next to the main work, (b) panic because block_on_detached was called, (c) work but not actually get polled next to the main work inside of block_on_detached, or (d) work but erroneously keep block_on from returning. All of that is something I would consider a bug and we'd also have no fundamental path to solving. Basically I don't want to further the confusion and problems of spawn_local and block_on, so I'm tempted to seek alternatives.

Originally I was thinking we could just fold block_on_detached's semantics into block_on except maybe avoiding the panic in case there was nothing ambient. I think that would solve your use case as the spawned tasks don't need to be polled until the main block_on runs. I now however don't think this is a good idea because it still deepens the confusion and bugs of block_on and spawn_local (e.g. (b) is solved, but (c) is still present).

In the V8 header you linked, that mentions reference to what I was wondering about as well -- could threads be used here? Instead of trying to use spawn_local or do synchronous I/O or such, could a thread be spawned and the result of that waited on? That wouldn't need to interact with async tasks at all and might compose much better too.

Otherwise, another question, why does debugger/debuggee work need to spawn a task which is disconnected from block_on?

@tschneidereit

Copy link
Copy Markdown
Member Author

Yeah, I do see your point on how confusing this is all getting. And I think threads would probably work for this. I guess I can depend on a fork of wit-bindgen until coop threads are enabled by default. I first thought I'd also be blocked on a Rust release with threads support, but I think I can make it work with just WASI-SDK.

Otherwise, another question, why does debugger/debuggee work need to spawn a task which is disconnected from block_on?

The debugger doesn't ever spawn tasks, but the debuggee might: since JS debuggers support calling code, or more general eval, arbitrary JS can run, including code that triggers I/O, and hence spawns tasks.

However, I'm very glad you're pushing on this, because I finally realized that what I'd get with block_on_detached isn't actually what I ultimately want: I do want tasks spawned under block_on to be polled, I just don't want them to become blocking. I had talked myself into thinking that I'd actively not want I/O to complete while under the debugger, but I realized that no, that's just a limitation of my current approach, and e.g. browser devtools are perfectly happy with running code like this to completion under the debugger: await fetch("/"), instead of the promise returned by fetch only resolving after content JS has resumed execution.

I can do all this with threads, but also now wonder if there is a reasonable semantics for block_on to be had here that'd be better than what we have now:

Tasks spawned under block_on are polled alongside the blocked-on future. When that future completes, any of them still pending are handed to the enclosing task. Without an enclosing task, the call keeps running them until they finish, as block_on does today.

I think that'd resolve your bad scenarios b-d: for (b), there's no more panic; for (c), tasks are always polled by something; for (d) block_on would never block on these additional tasks.

If you think that might be reasonable, I'm happy to work through it in more detail. But otherwise, feel free to close this for now, and I'll focus on the threads-based approach in the long run, and use a fork short-term.

@alexcrichton

Copy link
Copy Markdown
Member

Chalk up another use case for threads...

But yeah I was also trying to figure out if there's something to do with block_on and improve it, and I was considering exactly what you're thinking as well. If we were to implement that, though, there's still enough gotchas that I don't think it really moves the needle on things:

  • block_on still can spuriously block on spawned tasks, it just depends on if there's an enclosing task or not. For example my (d) may or may not still be applicable.
  • In theory block_on only work on its own spawned tasks is also a bug. If there's an enclosing task with spawned tasks, why aren't those polled as well? There's nothing necessarily preventing them from being polled (unlike the "main task" which called block_on)

Overall this is where I still would like to (eventually) push on forbidding nested executors. If you're able to use threads that'd already decouple them to fit within that requirement I think, and the concerns here are kind of all downstream of allowing nested executors at all. Disallowing nested executors wouldn't fix all my concerns (e.g. block_on still makes no sense with spawn_local), but it at least scopes it to just that one concern remaining AFAIK.

@tschneidereit

Copy link
Copy Markdown
Member Author

Okay, that all makes sense, and I think we can start to wrap this up here, I think :)

One question on this PR: do you think landing the first commit still makes sense? It seems to me that it does, and improves the situation, albeit not by that much.

On the long-term goal of forbidding nested executors, I think once coop threads are stable, that does become viable. I had a clanker do an audit of existing uses of block_on that spawn tasks, and it seems like StarlingMonkey might be the least easy one to move to coop threads.

Cases it found include some in Golem projects [1,2,3,4], and one in Lann's polymorph-iroh. All of these should port pretty easily to a threads-based approach, I think.

@alexcrichton

Copy link
Copy Markdown
Member

Oh, right, yes! I'm always a fan of deleting static muts!

And ok sounds like we "just" need to wait a bit on the disallowance...

@tschneidereit

Copy link
Copy Markdown
Member Author

Okay, I opened #1795 for that and will close this PR.

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.

2 participants