miden-vm: `ErrorContext` and `ProcessState` are not `Send`
Version: 0.16.2
ErrorContext is not Send
The following test does not compile:
#[cfg(test)]
mod async_tests {
use alloc::{boxed::Box, string::String};
use super::*;
struct AsyncTransactionHost;
#[derive(Debug, thiserror::Error)]
enum ParseError {
#[error("stub")]
FailedToParse,
}
fn parse_event(_event_id: u32) -> Result<String, ParseError> {
Err(ParseError::FailedToParse)
}
impl BaseHost for AsyncTransactionHost {}
impl AsyncHost for AsyncTransactionHost{
fn get_mast_forest(
&self,
_node_digest: &Word,
) -> impl Future<Output = Option<Arc<MastForest>>> + Send {
async { None }
}
fn on_event(
&mut self,
process: &mut ProcessState<'_>,
event_id: u32,
err_ctx: &impl ErrorContext,
) -> impl Future<Output = Result<(), ExecutionError>> + Send {
async move {
let transaction_event = parse_event(event_id)
.map_err(|err| ExecutionError::event_error(Box::new(err), err_ctx))?;
Ok(())
}
}
}
}
results in:
error: future cannot be sent between threads safely
--> processor/src/lib.rs:957:14
|
957 | ) -> impl Future<Output = Result<(), ExecutionError>> + Send {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ future created by async block is not `Send`
|
note: captured value is not `Send` because `&` references cannot be sent unless their referent is `Sync`
--> processor/src/lib.rs:960:79
|
960 | .map_err(|err| ExecutionError::event_error(Box::new(err), err_ctx))?;
| ^^^^^^^ has type `&impl ErrorContext` which is not `Send`, because `impl ErrorContext` is not `Sync`
help: consider restricting opaque type `impl ErrorContext` with trait `Sync`
|
956 | err_ctx: &impl ErrorContext + core::marker::Sync,
| ++++++++++++++++++++
ProcessState is not Send
Similarly, replacing the above on_event impl with:
fn on_event(
&mut self,
process: &mut ProcessState<'_>,
event_id: u32,
_err_ctx: &impl ErrorContext,
) -> impl Future<Output = Result<(), ExecutionError>> + Send {
async move {
process.get_mem_state(ContextId::root());
Ok(())
}
}
results in:
error: future cannot be sent between threads safely
--> processor/src/lib.rs:957:14
|
957 | ) -> impl Future<Output = Result<(), ExecutionError>> + Send {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ future created by async block is not `Send`
|
= help: the trait `Sync` is not implemented for `(dyn miden_debug_types::SourceManager + 'static)`
note: captured value is not `Send` because `&mut` references cannot be sent unless their referent is `Send`
--> processor/src/lib.rs:959:17
|
959 | process.get_mem_state(ContextId::root());
| ^^^^^^^ has type `&mut ProcessState<'_>` which is not `Send`, because `ProcessState<'_>` is not `Send`
error: future cannot be sent between threads safely
--> processor/src/lib.rs:957:14
|
957 | ) -> impl Future<Output = Result<(), ExecutionError>> + Send {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ future created by async block is not `Send`
|
= help: the trait `Send` is not implemented for `(dyn miden_debug_types::SourceManager + 'static)`
note: captured value is not `Send` because `&mut` references cannot be sent unless their referent is `Send`
--> processor/src/lib.rs:959:17
|
959 | process.get_mem_state(ContextId::root());
| ^^^^^^^ has type `&mut ProcessState<'_>` which is not `Send`, because `ProcessState<'_>` is not `Send`
Both of these prevent implementing an actual host implementation that uses the process or error context.
This seems related to https://github.com/0xMiden/miden-vm/issues/1978 and https://github.com/0xMiden/miden-vm/issues/1942, which may provide a way to resolve these issues.
About this issue
- Original URL
- State: open
- Created a year ago
- Comments: 27 (17 by maintainers)
AIUI, the issue is that the future returned by
future_to_promiseis notSend, and therefore cannot be run by the normal tokio runtime (which requires all futures to beSend, which is where all theSend + Syncreqs come from). Fundamentally, we can’t require the futures to beSendon Wasm because of this, which is why @PhilippGackstatter was talking about making the requirement here conditional on the target.There are single-threaded tokio runtimes, but IIRC they come with some caveats (i.e. stuff that is unsupported, which isn’t surprising, and may be fine for our use case on Wasm).
Sorry I’m late to the conversation. I believe the way it is currently set up, we’d end up doing something like the above. Specifically (@dagarcia7 can correct me if I’m wrong), I think the current implementation would like to call Indexed DB from within the authenticator. It doesn’t right now because the signature is sync, so it caches the keys beforehand and uses those (this has its own set of drawbacks as has been discussed in the past). So the future generated by the authenticator would not be
Sendsince it would include theJsFutureas you mentioned. I’m not very familiar withProcessStateand less so withErrorContextso I’m also sorry I can’t comment too much on the other ideas before reading some more about them.I believe that’s the main thing, yes - aside from that, imposing the
Sendrequirement is mostly a non-issue (it sucks for other reasons, but that’s the nature of building everything around a multi-threaded async runtime, and pretty much unavoidable for us). I’ll defer to others on that question though, as they are closer to it than I.I think the associated types for the futures on
AsyncHostwould have to be re-exported (as generic parameters) through theexecute_transactioninterface, next to generics forTransactionAuthenticatorandDataStoreas well as generics their futures, so that all of them can be configured to beSendor not. If so, this adds a lot of complexity. Just doing this for the authenticator (ignoringDataStore) we would get something like:But maybe I’m missing how this would be used.
We basically know that we need
!Sendfutures fortarget_family = wasm32andSendfutures fornot(target_family = wasm32), so I would prefer trying the “hard-coding” first, using#[cfg(target)], to avoid introducing that level of complexity.If the target hard coding doesn’t end up working, then we could fall back to this or some other solution.
Currently, the client is not exposed to the
on_event()handler directly. The setup is like this:We have a
TransactionAuthenticatortrait that looks like this:Then, we have a
TransactionHostthat can be instantiated with a transaction authenticator - so, the authenticator is a generic parameter. Here is a simplified sketch of the transaction host:We are using a trait object right now, but should be able to switch to a regular generic object:
Then, what we want to do is use this authenticator in the host’s
on_event()method:So, what we really want to do is just call
TransactionAuthenticator::get_signature()fromTransactionHost::on_event(), withget_signature()being an async mehtod.That would kinda suck tbh 😅 We’re wanting to have an actor per account executing transactions… So that would mean either only ever doing one tx at a time, or creating
Nlocal runtimes iiuc. Neither of these are appealing.I think this is where we’re meant to use
#[trait_variant::make](blog post). So that we can decide.That’s correct.
Though note that since #1934 the
FastProcessor’s execution is async, and so since it isSend + 'static, it could technically be moved between threads bytokio’s multi-threaded executor (which is how I assumed it would be executed downstream e.g. by the node).How I understand the problem, whether
AsyncHostmethods require aSendbound (and'static) or not determines theasyncexecution environment that we support. So in practice if theAsyncHostmethods don’t have aSendbound, then we force everyone using theFastProcessorto use a single-threaded runtime (e.g.LocalRuntimeas you mentioned), instead oftokio::runtime::Runtimethat I assume we would want to use downstream.So AFAIU, all our returned
Futures need to be+ Send(and+ 'staticprobably?), otherwise they can’t be used withtokio::runtime::Runtime.Agreed - it would be good to know for sure the requirements on the
Futures. My current understanding is we need+ Send + 'staticon allFutures (if only to support tokio’sRuntimethat I assume is used in the node), but would be good to confirm.This might help the
ErrorContextcase (which hopefully we can even get rid of with #1978), but I don’t think it would helpProcessState. Basically the main problem I now see is that if a'staticbound is needed on the returnedFutures ofAsyncHostmethods, and that the futures need to capture theProcessState(which they do), thenProcessStateneeds to own all its fields (i.e. we can’t use'aanymore).This might require us to rethink how
AsyncHostmethods query state from the processor. I don’t thinkProcessStatewrapping the entireFastProcessor/Processis viable (which as discussed previously, we’d now need to wrap in anArc). The solution is probably to changeProcessStateasIn other words, the
FastProcessoris converted to a “server” for requests coming fromAsyncHostmethods.Some general observations.
Arc<Mutex<T>>regardless of context. This is bad.dyn Tdoes not work well with letting the user dictate what their implementation should look like.Send + Sync + 'staticwill forever clash with async and futures.Arc<T>likewise forces the implementation to be exactly that shape and should be avoided around user owned mutable data.Send,Syncetc and methods will or won’t be available based on user choice.All of these are somewhat okay for short-lived objects but are bad for long lived ones. Even short ones will be bad in an async context. It sort of sounds like we need to think through who is meant to own what data. My issues with this in the tx execution have been that I want to own the data but that the traits and APIs force me to share it with the execution contexts for forever.
Arc<&T>themselves if they want to do that pattern.Yes, that makes sense for sync work that can be done ahead of time, like fetching stack state. I should’ve provided a more real-worldy example, which requires doing some async work (getting a signature) and then pushing that to the advice stack. So it requires accessing the process’ advice provider after awaiting the signature generation, which means we’ll run into the same problem, unfortunately.
So this is a basic example that mirrors the real flow that we would use for async signature generation, which I’m not sure we can solve without making the
ProcessStateSend.For reference:
Yes, the
ErrorContextI can ignore for a while, so if there’s a mid-term solution I think that’s totally fine 😃ProcessState
The idea was that all work involving
ProcessState(and sync work in general) would be done before theasync moveblock, such as what’s done here. So in your above example you could rewrite it asBasically keeping
ProcessStateas notSendis more performant so ideally we don’t have to make itSend, but let us know if still you’re getting more issues.ErrorContext
In your example you could also run the synchronous function outside the
async move {}block. But this might cause issues indeed if you’re trying to run it in a “truly” async context. But as you mentioned we’re probably getting rid ofErrorContextwith #1978 (probably next release), so hopefully the current workarounds should be enough.