Skip to content

WASM support #3311

Open
Open

Description

@A5rocks

To be concrete: support for the emscripten build of CPython and pyodide.

It would be really cool :3

I mean, it would also indicate that our basic IO manager protocol is good enough to stabilize if we can implement such a strange architecture.

I'm not sure how testing would work nor whether anyone would use it. Also I'm not sure concretely what we can support:

  • obviously we can manage sleeping and rescheduling
  • sockets isn't possible AFAIK? I guess there's those WASI things.
  • does pyodide provide a virtual file system or something? Maybe WASI does?

Unless... Trio already works due to some compatibility things done by CPython? I am 95% it doesn't work though. At least I should figure out how tests would work.

Activity

  1. CoolCat467 commented on Aug 4, 2025

    @CoolCat467
    Member

    On https://pyodide.org/en/stable/console.html (had to hack the script to use v0.28.0 instead of 0.28.1)

    >>> import micropip
    >>> await micropip.install("trio")
    >>> import trio
    Traceback (most recent call last):
      File "<console>", line 1, in <module>
      File "/lib/python3.13/site-packages/trio/__init__.py", line 22, in <module>
        from ._core import TASK_STATUS_IGNORED as TASK_STATUS_IGNORED  # isort: split
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/lib/python3.13/site-packages/trio/_core/__init__.py", line 21, in <module>
        from ._local import RunVar, RunVarToken
      File "/lib/python3.13/site-packages/trio/_core/_local.py", line 9, in <module>
        from . import _run
      File "/lib/python3.13/site-packages/trio/_core/_run.py", line 3004, in <module>
        raise NotImplementedError("unsupported platform")
    NotImplementedError: unsupported platform

    So kind of success so far, can install at least, but needs work of course

  2. davidbrochart commented on Aug 4, 2025

    @davidbrochart

    Maybe you just want to run a trio event loop on its own as a first step, but it's worth mentioning that pyodide integrates asyncio into the JavaScript event loop here. That allows e.g. JavaScript to await a Python task.

  3. A5rocks commented on Aug 7, 2025

    @A5rocks
    ContributorAuthor

    I would expect we don't need any special support in pyodide because of trio.lowlevel.wait_task_rescheduled (for Python awaiting JS) and the other way around is probably simple to do with plain JS promises.


    So kind of success so far, can install at least, but needs work of course

    Yeah, I think that means we don't have an IO manager for it.

  4. A5rocks commented on May 23, 2026

    @A5rocks
    ContributorAuthor

    I made a prototype version. See https://github.com/A5rocks/trio/tree/wasm-trio, you can run it via uv run -m build && uv run -m http.server, then open http://localhost:8000 and try something like this in the console:

    pyodide.runPython(`
    import trio
    
    async def main():
      await trio.sleep(1)
      return 5
    
    print(trio.run(main))`)

    Unfortunately, there doesn't seem to be a way to suspend execution. This makes this entirely impractical, since it means you won't be able to reschedule from e.g. promises. It's possible to work around this, but that would mean no return value from trio.run (note: it's synchronous!).

    The best alternate implementation probably involves spitting a signal at the program like in https://pyodide.org/en/stable/usage/keyboard-interrupts.html but that's pyodide specific. This is all just supposed to be whimsical so I don't really think it's worth tying ourselves to a particular implementation for practical results.

  5. arthur-tacca commented on Nov 15, 2026

    @arthur-tacca
    Member

    I had a look into this recently. Here are my findings, sorry they're a bit of a stream of consciousness.

    PEP 818

    As background: I got interested in this because I found out about PEP 818 – Adding the Core of the Pyodide Foreign Function Interface to Python

    The discussion thread for the PEP included discussion about whether it should include hooks for converting between Python and JS awaitables (see below).

    Any work we do for Pyodide would translate pretty directly to the equivalent in the Python standard library, if this PEP gets accepted.

    Proof of concept implementation

    To test things out I asked an LLM to make an implementation. I guided it on how to fit it into Trio but left the rest up to the LLM, so it may not be good code (I'm certainly not proposing it for direct inclusion in Trio) but it does prove that it is actually possible.

    It has (see later sections for details): the core implementation, wrappers for calling async functions to/from Python <-> JS, wrappers for mapping between Trio cancel scopes and JS abort signals, wrappers for calling JS Fetch API and WebSockets, httpx2 bridges for HTTP and WebSockets

    Core implementation

    It seems clear that the best way to implement this in Trio is with guest mode. The problem that A5rocks encountered is that the regular loop in Trio blocks until it's complete, so it doesn't let any JS events run. Instead, we need to allow the JS loop to be in charge, and for it to run Trio events when they occur. That's almost exactly what guest mode is.

    Guest mode was designed for a slightly different problem: it's intended for a host loop to run Trio events (which we want) but for Trio to still do its own IO including synchronously waiting for readiness (which we don't want) in a separate thread (which we can't have in JavaScript). But it's a small change to guest mode to allow disabling the synchronous wait in the thread.

    Details
    • Update guest mode so that it doesn't start the worker thread (that synchronously waits for I/O manager's get_events() method) on Pyodide. For example, this could be a conditional check on platform in the runner, or it could be factored out of the runner into the I/O manager (with all the others sharing a common function to run the thread).
    • Give a default for run_sync_soon_threadsafe when the platform is Pyodide so the caller doesn't have to figure that out (probably best put on the I/O manager since it's platform specific). It doesn't need to be thread safe (there are no threads) so can just directly schedule the next iteration. There are a few options for triggering this in JavaScript; setTimeout(fn, 0) is traditional but the timeout is rounded up (4ms in some browsers, 1ms in Node); MessageChannel with postMessage is more suitable. queueMicrotask wouldn't be right because it doesn't let other types of events run (it's analogous to adding directly to Trio's runq which Trio deliberately doesn't do).
    • Most obviously, a new I/O manager is needed for Pyodide:
      • Waiting for socket readiness (wait_readable / wait_writable) can go unimplemented - see below discussion of socket I/O
      • Scheduling the next tick of the event loop when the deadline expires (in place of the synchronous wait in the thread) using setTimeout(fn, timeout).
      • force_wakeup() needs to cancel the timeout and trigger the next iteration of guest mode loop (via run_sync_soon_threadsafe)
      • Synchronously waiting for I/O events get_events() - in Pyodide there is no synchronous wait and no worker thread, but this is still called with timeout of 0 in the guest mode tick so needs to be callable. It needs to return something truthy if force_wakeup was called (otherwise wait_all_tasks_blocked or MockClock with autojump_threshold can believe that a timeout genuinely expired and wake too soon) but it can be anything and just be ignored by process_events().
    • WakeupSocketpair needs to be updated to work with Pyodide. This has two uses: (1) some I/O managers use it for force_wakeup, but the Pyodide one can just choose not to; (2) in EntryQueue for TrioToken.run_sync_soon. The second one seems irrelevant for Pyodide but it is used in a few places aside from thread API: finalising generators, during shutdown, and for signal handling. It's tempting to just call reschedule (which goes on to wake the loop via I/O manager's force_wakeup) since we're in the same thread. But Pyodide emulated signals and generator finalisers called during GC can happen at arbitrary points, in which case Trio's internal state might be inconsistent; instead, it should just set a flag and post a callback to the JS event loop, and reschedule the entry queue task from that callback.
    • Not strictly essential, but ideally a wrapper around start_guest_run that sets up a JS promise that resolves with the done_callback.

    Calling to/from Python

    Synchronous calls between JS and Python don't depend on the async runtime, but converting between awaitable functions needs to go through a helper:

    # Call JS async function from Python 
    result = await trio.pyodide.call(js.jsFn, x)
    # Allow Python async function to be called from JS
    js.pyFn = trio.pyodide.callable_from_js(py_fn)

    Pyodide includes some extra logic to make this transparent for asyncio. As discussed in the PEP 818 discussion thread, there could be hooks in Pyodide to allow Trio to add these too - I added a request in pyodide/pyodide#6513. Then the above calls would simply be

    # Call JS async function from Python
    result = await js.jsFn(x)
    # Allow Python async function to be called from JS
    js.pyFn = py_fn

    Cancellation

    Asyncio cancels async JS functions by simply abandoning them and raising asyncio.CancelledError. I suggest that Trio should instead continue waiting for them, and leave it up to the application to attempt to interrupt it. We could supply a helper that turns a Trio cancellation into cancellation of a JS abort signal, and vice-versa:

    # Call JS function from Python 
    with trio.pyodide.abort_signal() as signal:
        result = await js.someAsyncFunction(arg, signal)
    # Python function intended to be called from JS
    async def fn(x, signal=None):
        with trio.pyodide.cancel_on_abort(signal):
            ... # becomes cancelled when signal is aborted

    Network I/O

    There's not much point using Trio unless it can do network I/O, and I think it has to match native API to be useful (so that you can share code between platforms). There are a few options:

    • Use regular Python sockets: You can't use real sockets directly from a web browser, so Emscripten emulates sockets using WebSockets. This already limits its usefulness, and in addition there are all sorts of niggles that make it a poor fit for Trio: e.g. writes always go through immediately and are queued internally (you could wait for something like "write readiness" waiting for the queue length to go down, but you need to poll for it and the Trio socket write would need restructuring to not attempt synchronously first); there's also no real notion of address lookup and Trio's implementation uses a thread which can't work in a browser. Overall I don't think this is worth it.
    • Adapt native APIs to the web API: It's easy enough to write a Python/Trio wrapper around the JS Fetch API for HTTP, then you could provide a separate implementation of the same API using native HTTP libraries for use on other platforms.
    • Adapt web API to native API: This is the more sensible option: provide a JS implementation that matches an existing API (or subset of it) of a native library e.g. my proof of concept includes a WebSockets wrapper that attempts to follow the API of the websockets library
    • Use httpx2 pluggable transport: This is really a variant of the previous option - it's adapting the web API to an existing native API. But httpx2 offers a really interesting way to do this: you can supply it with a custom transport. It was made for exactly this sort of thing and it's already used HTTP Pyodide support for asyncio. If we get this far, I think there's a case for the Trio (or AnyIO) version to be included in httpx2 itself.

    The last one could be used like this:

    async with httpx2.AsyncClient(transport=trio_httpx2.BrowserTransport()) as client:
        response = await client.get(url)
        async with client.websocket(ws_url) as ws:
            await ws.send_text("hello")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions