Skip to content

What context.{get,set} slots are used when an async task returns a string? #678

Closed

Description

@alexcrichton

I've been thinking about bytecodealliance/wasmtime#13890 and how best to fix it recently. I've come across behavior though where I'm not entirely sure what to do, hence the question here. The basic problem of this Wasmtime issue is that when a thread exits there remains lingering references to the thread's ID and data structure which causes problems when they're later accessed. My original goal was to continue to "promptly deallocate" thread structures when a thread exits (as opposed to keeping them alive until subtasks have returned or something like that), but this led to a bit of a deeper question.

Specifically there's currently the scenario where a host async function returns in a "delayed" fashion. For example it's invoked, not ready yet, and then a subtask is created within the guest. Eventually when this host subtask actually generates its result it lowers the result into guest memory and then signals an event saying that the subtask is ready. The process of lowering, however, can invoke guest functions like realloc and need context.{get,set} intrinsics to work correctly. At this time I don't actually know what the right values are to use here and I think Wasmtime is relatively buggy.

A rough example of what I'm thinking of is this test:

Details
(component
  (core module $libc
    (import "" "context.set" (func $context.get (result i32)))
    (memory (export "m") 1)
    (func (export "realloc") (param i32 i32 i32 i32) (result i32)
      (i32.store
        (i32.const 100)
        (call $context.get))
      i32.const 0
    )
  )
  (component $A
    (core func $context.get (canon context.get i32 0))
    (core instance $libc (instantiate $libc
      (with "" (instance
        (export "context.set" (func $context.get))
      ))
    ))

    (core module $m
      (import "libc" "m" (memory 1))
      (import "" "task.return" (func $task.return (param i32 i32)))

      (global $go (mut i32) (i32.const 0))

      (func (export "run") (result i32)
        i32.const 1 ;; CALLBACK_CODE_YIELD
      )

      (func (export "run-cb") (param i32 i32 i32) (result i32)
        (if (result i32) (global.get $go)
          (then
            (call $task.return (i32.const 0) (i32.const 0))
            i32.const 0 ;; CALLBACK_CODE_EXIT
          )
          (else (i32.const 1)) ;; CALLBACK_CODE_YIELD
        )
      )

      (func (export "go") (global.set $go (i32.const 1)))
    )

    (core func $task.return (canon task.return (result string) (memory $libc "m")))
    (core instance $m (instantiate $m
      (with "libc" (instance $libc))
      (with "" (instance
        (export "task.return" (func $task.return))
      ))
    ))

    (func (export "run") async (result string)
      (canon lift (core func $m "run") async (memory $libc "m")
          (callback (func $m "run-cb")))
    )
    (func (export "go") (canon lift (core func $m "go") ))
  )

  (component $B
    (import "a" (instance $a
      (export "run" (func async (result string)))
      (export "go" (func))
    ))

    (core func $context.get (canon context.get i32 0))
    (core instance $libc (instantiate $libc
      (with "" (instance
        (export "context.set" (func $context.get))
      ))
    ))

    (core module $m
      (import "" "run" (func $run (param i32) (result i32)))
      (import "" "go" (func $go))
      (import "" "thread.yield" (func $thread.yield (result i32)))
      (import "" "context.set" (func $context.set (param i32)))
      (import "libc" "m" (memory 1))

      (global $subtask (mut i32) (i32.const 0))

      (func (export "start")
        (local $r i32)

        (call $context.set (i32.const 1))


        (local.set $r (call $run (i32.const 0)))
        (if (i32.ne
              (i32.and (local.get $r) (i32.const 0xf))
              (i32.const 1)) ;; STARTED
          (then (unreachable)))
        (global.set $subtask (i32.shr_u (local.get $r) (i32.const 4)))
      )

      (func (export "finish") (result i32)
        (call $context.set (i32.const 2))

        call $go
        (drop (call $thread.yield))
        (i32.load (i32.const 100))
      )
    )

    (core func $run
      (canon lower
        (func $a "run")
        async
        (memory $libc "m")
        (realloc (func $libc "realloc"))
      )
    )
    (core func $go (canon lower (func $a "go")))
    (core func $thread.yield (canon thread.yield))
    (core func $context.set (canon context.set i32 0))

    (core instance $i (instantiate $m
      (with "libc" (instance $libc))
      (with "" (instance
        (export "run" (func $run))
        (export "go" (func $go))
        (export "thread.yield" (func $thread.yield))
        (export "context.set" (func $context.set))
      ))
    ))

    (func (export "start") (canon lift (core func $i "start")))
    (func (export "finish") async (result u32) (canon lift (core func $i "finish")))
  )

  (instance $a (instantiate $A))
  (instance $b (instantiate $B (with "a" (instance $a))))
  (export "start" (func $b "start"))
  (export "finish" (func $b "finish"))
)

(assert_return (invoke "start"))
(assert_return (invoke "finish") (u32.const 0))

which runs as:

$ wasmtime wast foo.wast
Error: failed to run script file 'foo.wast'

Caused by:
    0: failed directive on foo.wast:136
    1: result 0 didn't match
    2: expected                  0 / 0x0000000000000000
actual                    2 / 0x0000000000000002

The basic premise of this script is that component $B has an export "start" which starts a subtask in $A. This subtask returns a string and isn't immediately ready yet. Next a new task in $B, the "finish" function, flags $A as "please complete now" which then leads to the completion of $A's original task. This invokes realloc where the definition here stores context.get in a known location in memory. The $B "finish" subtask then completes with what was returned by realloc at that location in memory. Currently Wasmtime runs realloc in the context of the "finish" task in $B, but I'm not sure if this is correct or the desired outcome here.

To me the "start" subtask seems wrong since it's exited. The "finish" subtask also seems wrong because it hasn't even said anything about $A's subtask yet. Should this be something where a fresh, temporary, task is created when $A returns to $B? This fresh, temporary, task is basically scoped to realloc invocations and is disposed of quickly afterwards.

This is where I got lost enough myself in the "right" answer here, hence the issue here.

Activity

  1. lukewagner commented on Jul 19, 2026

    @lukewagner
    Member

    Great catch! Indeed, calls to realloc are underspecified in the CABI Python definitions at the moment because they don't end up resume()ing a continuation, which is what establishes current_thread() and thus current_thread().storage[i].

    Allowing prompt internal storage deallocation seems like a good goal. The simplest way for the engine to do this would be to say that context.{get,set} and thread.index trap if called during realloc. This would make the thread identity unobservable and we could specify that technically calls to realloc start a new Thread (as if they were recursive export calls, b/c they essentially are), but since thread identity is unobservable, the impl can use whatever preexisting thread is convenient (as long as it's in the right component instance).

    The main challenge with this approach I can imagine is if realloc code unconditionally calls context.{get,set} b/c it's in all LLVM-compiled code by default when coop threads are enabled. But maybe there's some compiler hack we could find to avoid this just for the realloc path? If there isn't a good hack, then as a second-best option, we could keep context.{get,set} non-trapping in realloc, but still say that realloc calls create a new Thread (and thus the entry value of context.get when calling realloc would always be 0). Due to all the other may_leave traps (including a new trap added to thread.index), hopefully this call could still be cheap.

    WDYT?

  2. alexcrichton commented on Jul 20, 2026

    @alexcrichton
    CollaboratorAuthor

    I suspect it's going to be very hard to remove calls to context.{get,set} due to their usage for the stack pointer and thread-local data structures, although disallowing thread.index may be easier. Another problem with context.{get,set} is that we ideally want them to compile to just-a-load and just-a-store for efficiency, but otherwise we'd have to have a dynamic check on invocations for all functions that are reachable from realloc. Given all that I think the only realistic option here is to get context.* intrinsics working as part of realloc and at that point may as well get thread.index working too.

    Starting a fresh thread might be somewhat difficult though because it would mean guest-toolchain-wise there'd have to be something that calls context.{get,set} around the invocation of cabi_realloc. Right now this is managed during componentization with wasi-libc for exports in general, e.g. wasi-libc exports __wasm_init_task as a symbol which is recognized by wit-component as "synthesize a new export which calls __wasm_init_task which then calls the original export function". We'd have to do the same for cabi_realloc for example.

    This actually raises more questions for me... This cabi_realloc wrapper would have to pick a stack to use, of which I'm not sure there's a great options. Imports can't use the "main stack" because that might already be in use. Exports want to ideally use the stack already allocated for a task, but that doesn't exist yet because the task (in-guest) hasn't started yet. Exports could probably use the main stack though because by virtue of being able to enter a component it means that nothing is using the main stack. If anything it seems like cabi_realloc may need its own private stack to use separate from all the other stacks to avoid the combinatorial complexity here...

  3. lukewagner commented on Jul 20, 2026

    @lukewagner
    Member

    Thanks; agreed that making context.{get,set} trap is not the right design. Having thought about it a bit more in the meantime, having a conceptually new thread/task with fresh zeroed context.{get,set} storage cells does seem like the best option even though it does seem to require an extra entry thunk to initialize these. In particular, "reusing" some existing thread to make a fresh call would introduce a new kind of behavior: currently once a thread is created (for a new function call), it only suspends/resumes that original callstack, so I worry this might lead to other surprising interactions b/c now the thread has a stack of wasm call stacks.

  4. alexcrichton commented on Jul 20, 2026

    @alexcrichton
    CollaboratorAuthor

    I agree yeah I think the most reasonable thing here is a fresh thread. The only final thing is which stack it's going to use in the guest. I ideally want to use the main "original" stack, but that won't work in the case that a synchronous task (using the main stack) calls an import which returns a list/string/etc. Given that I think the only realistic option is to have a small section of memory for "this is cabi_realloc's stack" and mostly just pray it doesn't overflow. I suppose this is a rough analogy to sigaltstack of sorts. TLS-wise I'd want the cabi_realloc call to share TLS with the "main thread" to avoid the overhead of initializing it on all realloc calls.

  5. added 6 commits that reference this issue on Jul 22, 2026
    30d58f4
    d7081fc
    b96f62e
    585716a
    2ccbea5
    fa87174
  6. added a commit that references this issue on Aug 4, 2026
    7972c14
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