Repository navigation
Description
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
lukewagner commentedon Jul 19, 2026
Great catch! Indeed, calls to
reallocare underspecified in the CABI Python definitions at the moment because they don't end upresume()ing a continuation, which is what establishescurrent_thread()and thuscurrent_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}andthread.indextrap if called duringrealloc. This would make the thread identity unobservable and we could specify that technically calls toreallocstart a newThread(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
realloccode unconditionally callscontext.{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 thereallocpath? If there isn't a good hack, then as a second-best option, we could keepcontext.{get,set}non-trapping inrealloc, but still say thatrealloccalls create a newThread(and thus the entry value ofcontext.getwhen callingreallocwould always be0). Due to all the othermay_leavetraps (including a new trap added tothread.index), hopefully this call could still be cheap.WDYT?
alexcrichton commentedon Jul 20, 2026
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 disallowingthread.indexmay be easier. Another problem withcontext.{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 fromrealloc. Given all that I think the only realistic option here is to getcontext.*intrinsics working as part ofreallocand at that point may as well getthread.indexworking 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 ofcabi_realloc. Right now this is managed during componentization with wasi-libc for exports in general, e.g. wasi-libc exports__wasm_init_taskas a symbol which is recognized bywit-componentas "synthesize a new export which calls__wasm_init_taskwhich then calls the original export function". We'd have to do the same forcabi_reallocfor example.This actually raises more questions for me... This
cabi_reallocwrapper 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 likecabi_reallocmay need its own private stack to use separate from all the other stacks to avoid the combinatorial complexity here...lukewagner commentedon Jul 20, 2026
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 zeroedcontext.{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.alexcrichton commentedon Jul 20, 2026
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 tosigaltstackof sorts. TLS-wise I'd want thecabi_realloccall to share TLS with the "main thread" to avoid the overhead of initializing it on all realloc calls.Avoid dangling references to exited threads (bytecodealliance#13926)
Define 'realloc' calls to execute on fresh thread
Define 'realloc' calls to execute on fresh thread
Define 'realloc' calls to execute on fresh thread
Define 'realloc' calls to execute on fresh thread
Define 'realloc' calls to execute on fresh thread
Define 'realloc' calls to execute on fresh thread
Avoid dangling references to exited threads (#13926)
Define 'realloc' calls to execute on fresh thread (WebAssembly#680)