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)

Most upvoted comments

I don’t follow. From the linked lack of a Send bound for https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen_futures/fn.future_to_promise.html , I don’t see a reason why we need to disambiguate, and not just always provide a Send bound.

AIUI, the issue is that the future returned by future_to_promise is not Send, and therefore cannot be run by the normal tokio runtime (which requires all futures to be Send, which is where all the Send + Sync reqs come from). Fundamentally, we can’t require the futures to be Send on 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).

Thinking about how it’ll work in our context: the on_event() is actually implemented in TransactionExecutor and there we don’t know what the downstream implementations of TransactionAuthenticator could be. So, we probably can’t assume it would run in WASM (and so can’t rely on wasm_bindgen_futures) - or am I missing something?

In the context of the above, we want to figure out if the Send bounds on the future returned by on_event is an issue or not. So maybe @igamigo or @dagarcia7, is the plan to be able to do something like the following, or would this be handled differently (and not require wrapping JavaScript promises)?

fn on_event(
    &mut self,
    process: &mut ProcessState<'_>,
    _event_id: u32,
    _err_ctx: &impl ErrorContext,
) -> impl Future<Output = Result<(), ExecutionError>> + Send {
    let pub_key_hash = process.get_stack_word(0);
    async move {
        // Imagine this would call a "WasmAuthenticator" which calls into JavaScript and returns a Promise.
        let promise: js_sys::Promise = self.wasm_authenticator.generate_signature();
        let _signature = wasm_bindgen_futures::JsFuture::from(promise).await?;

        Ok(())
    }
}

If we do want to do something like this, then JsFuture wouldn’t be Send and so this wouldn’t compile. But if we don’t need that, then we can keep Send bounds on the future.

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 Send since it would include the JsFuture as you mentioned. I’m not very familiar with ProcessState and less so with ErrorContext so 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 Send requirement 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 AsyncHost would have to be re-exported (as generic parameters) through the execute_transaction interface, next to generics for TransactionAuthenticator and DataStore as well as generics their futures, so that all of them can be configured to be Send or not. If so, this adds a lot of complexity. Just doing this for the authenticator (ignoring DataStore) we would get something like:

fn execute_transaction<A, H, X, Y, Z>(&self, host: &TestHost, authenticator: A)
  where
      H: AsyncHost<X, Y>,
      X: Future<Output = Option<Arc<MastForest>>>,
      Y: Future<Output = Result<(), ExecutionError>>,
      Z: Future<Output = Result<Vec<Felt>, AuthenticationError>>,
      A: TransactionAuthenticator<Z>,
  {
  }

But maybe I’m missing how this would be used.


We basically know that we need !Send futures for target_family = wasm32 and Send futures for not(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 TransactionAuthenticator trait that looks like this:

pub trait TransactionAuthenticator {
    /// The method is currently not async - but that's what we are trying to change.
    async fn get_signature(
        &self,
        pub_key: Word,
        message: Word,
        account_delta: &AccountDelta,
    ) -> Result<Vec<Felt>, AuthenticationError>;
}

Then, we have a TransactionHost that can be instantiated with a transaction authenticator - so, the authenticator is a generic parameter. Here is a simplified sketch of the transaction host:

pub struct TransactionHost<'auth> {
    authenticator: &'auth dyn TransactionAuthenticator,
}

We are using a trait object right now, but should be able to switch to a regular generic object:

pub struct TransactionHost<'auth, A: TransactionAuthenticator> {
    authenticator: &'auth A,
}

Then, what we want to do is use this authenticator in the host’s on_event() method:

impl<'a, A: TransactionAuthenticator> TransactionHost<'a, A> {
    async fn on_event(
        &mut self,
        process: &ProcessState<'_>,
        event_id: u32,
    ) -> Result<Vec<AdviceMutation>, ExecutionError>{
        
        if event_id == GET_AUTH_SIG_EVENT {
            // TODO: read `pub_key`, `message`, `delta` from `process`
            let sig = self.authenticator.get_signature(pub_key, message, delta).await?;
            return Ok(vec![AdviceMutation::stack(sig)]);
        } else {
            ...
        }
    
    }
}

So, what we really want to do is just call TransactionAuthenticator::get_signature() from TransactionHost::on_event(), with get_signature() being an async mehtod.

The node would then need to manage 2 separate tokio runtimes: the multi-threaded one as used today (to handle RPC requests, etc), as well as a single-threaded one (such as tokio’s LocalRuntime, but whichever really) that would be used to run FastProcessor::execute(). Would be great to get input from the node team on this (cc @Mirko-von-Leipzig).

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 N local 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.

In https://github.com/0xMiden/miden-vm/issues/1558#issuecomment-2572407377 it looks like the “fast executor” itself is single-threaded, is that correct?

That’s correct.

Though note that since #1934 the FastProcessor’s execution is async, and so since it is Send + 'static, it could technically be moved between threads by tokio’s multi-threaded executor (which is how I assumed it would be executed downstream e.g. by the node).

If so, does it make sense to require Send bounds on the AsyncHost methods? If the executor runs single-threaded anyway, then the entire executor future will be run on a single thread anyway, so Send shouldn’t be required.

How I understand the problem, whether AsyncHost methods require a Send bound (and 'static) or not determines the async execution environment that we support. So in practice if the AsyncHost methods don’t have a Send bound, then we force everyone using the FastProcessor to use a single-threaded runtime (e.g. LocalRuntime as you mentioned), instead of tokio::runtime::Runtime that I assume we would want to use downstream.

So AFAIU, all our returned Futures need to be + Send (and + 'static probably?), otherwise they can’t be used with tokio::runtime::Runtime.

Overall, this may be good to clarify so we don’t have to change things again once these changes make their way to the client,

Agreed - it would be good to know for sure the requirements on the Futures. My current understanding is we need + Send + 'static on all Futures (if only to support tokio’s Runtime that I assume is used in the node), but would be good to confirm.

This may be naive thinking, but wouldn’t most of these issues go away after https://github.com/0xMiden/miden-vm/issues/1942?

This might help the ErrorContext case (which hopefully we can even get rid of with #1978), but I don’t think it would help ProcessState. Basically the main problem I now see is that if a 'static bound is needed on the returned Futures of AsyncHost methods, and that the futures need to capture the ProcessState (which they do), then ProcessState needs to own all its fields (i.e. we can’t use 'a anymore).

This might require us to rethink how AsyncHost methods query state from the processor. I don’t think ProcessState wrapping the entire FastProcessor/Process is viable (which as discussed previously, we’d now need to wrap in an Arc). The solution is probably to change ProcessState as

// There would be one variant per method of today's `ProcessState`
enum Request {
  Clk,
  // ...
}

enum Response {
    RowIndex(RowIndex),
    // ... all other possible responses
}

struct Message {
    request: Request,
    response: oneshot::Sender<Response>
}

struct ProcessState {
  sender: mspc::UnboundedSender<Message>
}

impl ProcessState {
    // Note: all methods become async
    pub async fn clk(&self) -> RowIndex {
        let (tx, rx) = oneshot::channel();
        self.sender.send(Message {
            request: Request::Clk,
            response: tx,
        }).await.unwrap();
    

        let resp = rx.await.unwrap();
        // downcast the response to a `RowIndex`
        downcast!(resp, Response::RowIndex)
    }
}

In other words, the FastProcessor is converted to a “server” for requests coming from AsyncHost methods.

Some general observations.

  • References should be short lived. If you have an long lived object that holds a reference then that forces the caller to always use a Arc<Mutex<T>> regardless of context. This is bad.
  • Similarly holding dyn T does not work well with letting the user dictate what their implementation should look like. Send + Sync + 'static will forever clash with async and futures.
  • Holding Arc<T> likewise forces the implementation to be exactly that shape and should be avoided around user owned mutable data.
  • Using proper generics lets the user decide whether they want Send, Sync etc 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.

  • Is the data borrowed? Pass it into the methods instead of owning it long term.
  • If holding it long term, then it shouldn’t be a reference. The user can always implement Arc<&T> themselves if they want to do that pattern.

The idea was that all work involving ProcessState (and sync work in general) would be done before the async move block

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 ProcessState Send.

#[cfg(test)]
mod async_tests {
    use super::*;

    struct TransactionAuthenticator {}

    struct AsyncTransactionHost {
        authenticator: TransactionAuthenticator,
    }

    impl TransactionAuthenticator {
        pub fn generate_signature(&self, _pub_key_hash: Word) -> impl Future<Output = Vec<Felt>> + Send {
            async { vec![] }
        }
    }

    impl AsyncTransactionHost {
        pub fn on_signature_requested(
            &mut self,
            process: &mut ProcessState<'_>,
        ) -> impl Future<Output = Result<(), ExecutionError>> + Send {
            let pub_key_hash = process.get_stack_word(0);

            async {
                let signature = self.authenticator.generate_signature(pub_key_hash).await;

                process.advice_provider_mut().stack.extend(signature);

                Ok(())
            }
        }
    }

    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 {
            self.on_signature_requested(process)
        }
    }
}

For reference:

error: future cannot be sent between threads safely
   --> processor/src/lib.rs:945:14
    |
945 |         ) -> 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:951:17
    |
951 |                 process.advice_provider_mut().stack.extend(signature);
    |                 ^^^^^^^ 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:945:14
    |
945 |         ) -> 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:951:17
    |
951 |                 process.advice_provider_mut().stack.extend(signature);
    |                 ^^^^^^^ has type `&mut ProcessState<'_>` which is not `Send`, because `ProcessState<'_>` is not `Send`

Yes, the ErrorContext I 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 the async move block, such as what’s done here. So in your above example you could rewrite it as

fn on_event(
  &mut self,
  process: &mut ProcessState<'_>,
  event_id: u32,
  _err_ctx: &impl ErrorContext,
) -> impl Future<Output = Result<(), ExecutionError>> + Send {
  process.get_mem_state(ContextId::root());

  async move {
      Ok(())
  }
}

Basically keeping ProcessState as not Send is more performant so ideally we don’t have to make it Send, 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 of ErrorContext with #1978 (probably next release), so hopefully the current workarounds should be enough.