You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Pre-Proposal: Wasm GC Support in the Canonical ABI #525
Reacted by Sebastien Guillemot, Justin Fagnani, Francesco Iapicca, Pablo Henrique Batista, Simon Binder, mdh, Milan Raj and Ondra Pelech
Reacted by Florian and Jim M. R. Teichgräber
Reacted by Luke Wagner, Louis Pilfold, Kevin Moore, Sebastien Guillemot, Eli, Rikito Taniguchi, Justin Fagnani, Francesco Iapicca, YAMAMOTO Yuji, Milan Raj and 3 more
This is really exciting and I appreciate the clear writeup! Also, I love the approach of maximally-deriving the ABI from the core function type; that's an elegant solution to an otherwise gross problem. Overall, 👍 from me.
A few small questions/suggestions:
I'm probably misunderstanding the proposal, wasm-gc or both, but: for variant et al, your examples all put the supertype in a separate rec group than the case subtypes but I would think that this doesn't expose the semantic link between "the variant type" and "the case types" that you need to let the core function type tell the whole story. E.g., iiuc, there's no "edge" in the type graph from $animal' to the rec group containing $dog'. (The edge exists in the other direction, ofc, but that's many-to-1, so you couldn't talk about "the rec group that contains subtypes of this supertype".) Instead, I would think that, since we're sortof hijacking rec groups in this scheme anyways, we'd say that variants have to refer to a struct type that is the first of its rec group and all the subsequent rec group members must be its cases; then the typeidx used in the core function type points to a rec group that points to the cases.
While you're right about the reason that option can't represent none with ref.null in general, could we say that, when option<T> has a non-null-allowing T, ref.null represents none? This is ad hoc and irregular, but we are licensed to do that in the CABI when it's a significant win and option is very common and I expect this optimization would to 95% of options in practice.
result<T> (no E) and result (no T) are also super common and I think perhaps worth optimizing. Could the former use null for error and the latter return a (boolean) i32 (making it no less efficient than enum, so that no one has the perverse incentive to use an enum for a result for perf reasons)?
For the latin1+utf16 string-encoding, there's the question of how to communicate the dynamic "is it Latin-1 or UTF-16?" boolean (which is packed with the length into an i32 when using linear memory). One idea is that you could take a page from how variants work and have the static type be (ref null? array) and dynamically accept/produce either (ref (array i8)) or (ref (array i16)).
Regarding own, borrow, future and stream (as well as waitable sets and async subtasks): one issue I just realized is that various drop built-ins trap under various conditions (own and borrow trap if there are any extant async import calls to which they were lent; the writable end of a future traps if dropped without having written a value; etc). As a general rule, we try to avoid ever allowing user code of a safe language to hit a raw wasm trap, so somehow we need to figure out how the language runtime (running as wasm using the CABI) is able to avoid hitting these traps. One option would be to extend the "drop if unreachable" semantics to be "drop if unreachable and the trapping conditions are met", but I'm thinking this will get tricky and subtle. Another option is to force the wasm guest to root externrefs during times when they would trap if they became unreachable, but this might end requiring the wasm guest to maintain a lot of parallel bookkeeping already maintained by the C-M, maybe adding non-trivial overhead. So I wonder if a nice third option is to leave these types the same as with linear memory (i32s that need to be dropped), but introduce new canon built-ins that provide postmortem-notification analogous-to and polyfilled-via FinalizationRegistry and then allow the language runtime to use this primitive to Do The Right Thing itself. Such a built-in could also be used for other guest-internal purposes (such as associating a linear-memory buffer that needs to be freed with a wasm-GC object).
The even bigger reason that there are no canonical choices of type definitions to lower to are subtyping declarations, which the comment layer cannot guess.
For the various small scalar types, a common target representation will be i31-ref (e.g., in any language with a uniform representation), so I think (i31 null? ref) should also be allowed as an alternative, for both value and/or storage type.
For larger numeric types, various languages will probably need boxed representations to be able to process them, so perhaps it should be possible to map to those as well.
I like @lukewagner's suggestion regarding variants.
It is rather unfortunate that the CM calls arrays "lists"...
While you're right about the reason that option can't represent none with ref.null in general, could we say that, when option<T> has a non-null-allowing T, ref.null represents none? This is ad hoc and irregular, but we are licensed to do that in the CABI when it's a significant win and option is very common and I expect this optimization would to 95% of options in practice.
FWIW, I don't think it is gonna be even close to 95%. Languages with parametric polymorphism typically don't or can't do such a specialisation, because it would require costly runtime type passing and dispatch. That probably includes languages like Java with its Optional type.
While you're right about the reason that option can't represent none with ref.null in general, could we say that, when option has a non-null-allowing T, ref.null represents none? This is ad hoc and irregular, but we are licensed to do that in the CABI when it's a significant win and option is very common and I expect this optimization would to 95% of options in practice.
FWIW, I don't think it is gonna be even close to 95%. Languages with parametric polymorphism typically don't or can't do such a specialisation, because it would require costly runtime type passing and dispatch. That probably includes languages like Java with its Optional type.
Ah, interesting point. When I said "95%", I was talking about the percent of options appearing in WIT interfaces, but also thinking about how options are represented "at rest" in various languages is a good for regularity.
Question: if a lowered function type lowers an option into a non-eq reference with an empty struct representing none, can the engine implement none with a single-per-type allocation (since the identity isn't observable via eq or mutation)? If so, then the null optimization wouldn't even be that big of a win.
I would represent None as an i31 ref with value zero (or any random value). It is just an instance of a variant type, where runtimes typically represent nullary constructors as different tagged ints. Which, now that I mention it, is something the variant encoding should also support.
Edit: Though null would equally work for option. What these languages generally can't do is unboxing Some.
This is awesome! As an outsider, the wording on variant types is confusing:
Component variant types are matched against a reference to a struct type with no fields.
However the example defines a (struct (field i32)) which looks like a tagged union, but this is not explicitly stated. Is this the correct interpretation? And if so, can the lowering choose to use a smaller (packed) int instead, like the linear memory ABI does?
This is awesome! As an outsider, the wording on variant types is confusing:
Component variant types are matched against a reference to a struct type with no fields.
However the example defines a (struct (field i32)) which looks like a tagged union, but this is not explicitly stated. Is this the correct interpretation? And if so, can the lowering choose to use a smaller (packed) int instead, like the linear memory ABI does?
Ah I just forgot to update the example. There shouldn't be any (field i32) there. Will update the OP shortly.
1. I'm probably misunderstanding the proposal, wasm-gc or both, but: for variant et al, your examples all put the supertype in a separate rec group than the case subtypes but I would think that this doesn't expose the semantic link between "the variant type" and "the case types" that you need to let the core function type tell the whole story. E.g., iiuc, there's no "edge" in the type graph from $animal' to the rec group containing $dog'. (The edge exists in the other direction, ofc, but that's many-to-1, so you couldn't talk about "the rec group that contains subtypes of this supertype".) Instead, I would think that, since we're sortof hijacking rec groups in this scheme anyways, we'd say that variants have to refer to a struct type that is the first of its rec group and all the subsequent rec group members must be its cases; then the typeidx used in the core function type points to a rec group that points to the cases.
Because the shape of the cases' rec group is fully defined, there doesn't need to be an explicit link: the engine/fused adapter compiler can simply (re)define the cases' rec group and then rely on type canonicalization.
This approach is slightly more flexible than keeping the base type in the same rec group as the cases, since it allows the base type to be defined in any rec group of the producer's choosing.
2. While you're right about the reason that option can't represent none with ref.null in general, could we say that, when option<T> has a non-null-allowing T, ref.null represents none? This is ad hoc and irregular, but we are licensed to do that in the CABI when it's a significant win and option is very common and I expect this optimization would to 95% of options in practice.
3. result<T> (no E) and result (no T) are also super common and I think perhaps worth optimizing. Could the former use null for error and the latter return a (boolean) i32 (making it no less efficient than enum, so that no one has the perverse incentive to use an enum for a result for perf reasons)?
I'm fine with ultimately doing this kind of thing, but I am not going to do it for now, in my current prototyping, and therefore I am not going to update the OP with it either (which I will try to keep in sync with my prototyping).
As this extension settles and gets upstreamed into the spec, it should of course describe what we ultimately come to consensus on standardizing, and not what I just happen to have prototyped, but we can cross that bridge when we get to it.
For the latin1+utf16 string-encoding, there's the question of how to communicate the dynamic "is it Latin-1 or UTF-16?" boolean (which is packed with the length into an i32 when using linear memory). One idea is that you could take a page from how variants work and have the static type be (ref null? array) and dynamically accept/produce either (ref (array i8)) or (ref (array i16)).
Yeah, this makes sense and the OP reflects a misunderstanding on my part. Will update as soon as I fix my prototype.
Regarding own, borrow, future and stream (as well as waitable sets and async subtasks): one issue I just realized is that various drop built-ins trap under various conditions (own and borrow trap if there are any extant async import calls to which they were lent; the writable end of a future traps if dropped without having written a value; etc). As a general rule, we try to avoid ever allowing user code of a safe language to hit a raw wasm trap, so somehow we need to figure out how the language runtime (running as wasm using the CABI) is able to avoid hitting these traps. One option would be to extend the "drop if unreachable" semantics to be "drop if unreachable and the trapping conditions are met", but I'm thinking this will get tricky and subtle. Another option is to force the wasm guest to root externrefs during times when they would trap if they became unreachable, but this might end requiring the wasm guest to maintain a lot of parallel bookkeeping already maintained by the C-M, maybe adding non-trivial overhead. So I wonder if a nice third option is to leave these types the same as with linear memory (i32s that need to be dropped), but introduce new canon built-ins that provide postmortem-notification analogous-to and polyfilled-via FinalizationRegistry and then allow the language runtime to use this primitive to Do The Right Thing itself. Such a built-in could also be used for other guest-internal purposes (such as associating a linear-memory buffer that needs to be freed with a wasm-GC object).
Alternatively, we could continue to require explicit drop calls (as we do now for linear memory) rather than say that these things are implicitly dropped on finalization. If the externref becomes unreachable without the future/stream having been explicitly dropped, then the future/stream is never dropped. Language-specific bindings generators can wrap this stuff up similar to what they would have to do now when translating to the linear memory variant of the ABI (e.g. Python would use its with construct).
Then, as a next step, we can introduce those canonical builtins for finalizers that allows them to Do The Right Thing.
This approach is smaller and more incremental and crucially doesn't require finalizer support in implementations initially at all.
For the various small scalar types, a common target representation will be i31-ref (e.g., in any language with a uniform representation), so I think (i31 null? ref) should also be allowed as an alternative, for both value and/or storage type.
For larger numeric types, various languages will probably need boxed representations to be able to process them, so perhaps it should be possible to map to those as well.
This gets at the philosophical question of how much duck typing we want to do. The proposal is doing some amount already with its matching of component types against many core types by their shape, but right now they always match against one shape modulo nullability, subtyping, and rec group. Allowing i31ref in various places is widening things such that we would match against multiple shapes. It seems to me like this could potentially be a slippery slope: How many shapes is enough? How do we decide whether a shape is worthy of matching against?
I'm not saying I'm against adding support for i31ref, but I do think we should consider what design principles we want to follow in this CM+GC extension.
It is also possible my concerns are overblown, and this is the only additional shape we will actually want to match against.
That seems like a pretty good idea for an incremental first addition to me!
So just to check my understanding: you're suggesting no changes to lifting/lowering (yet), but rather a few new ABI built-ins (that can use Core WebAssembly reference types b/c they're ABI built-ins) that Jco could polyfill with FinalizationRegistery/WeakRef? If so, before a full PR, maybe a good first step would be to build a prototype implementation of these new ABI built-ins in Jco that you could validate with your Dart implementation? (cc @vados-cosmonic for thoughts.) Since this issue is already a bit long and is mostly focused on the lifting/lowering ABI questions, it's probably also a good idea to create a new issue dedicated to this idea to sketch out the shape of these new ABI built-ins before or during the prototyping.
Shouldn't weakrefs and finalization registries be in Wasm GC proper, not the component API? This would be one more thing that a toolchain has to compile differently for core modules on JS vs components.
Shouldn't weakrefs and finalization registries be in Wasm GC proper, not the component API? This would be one more thing that a toolchain has to compile differently for core modules on JS vs components.
I had a similar concern, if finalization registries and or weakrefs are added to the component model, it may duplicate effort or cause duplicate apis if similar wasm proposals are made as extensions to wasm gc.
Finalizers require callbacks, which requires a decision on when these callbacks run. The component model has a perfect primitive for this in the form of waitables, it doesn't seem like this can be added to core WebAssembly.
I have opened #752 to discuss that specifically, I'd love to hear your thoughts there!
I had a conversation with @alexcrichton yesterday about variants and CM+GC and the conclusion we came to is that this pre-proposal doesn't work for variants that have tuple and record payloads (and probably not any other compound type either).
The current "duck typing" allows producers and consumers to choose which GC struct to use for a record or tuple (in particular, which rec group it is defined in, whether it is final or not, and whether its fields are mut or not). And the way that variant is spec'd here, we can pass variants back and forth, but if you then want to downcast them to a particular arm of the variant, then what type do you test for in your downcast? It is obvious for scalars and the rules work in that case, but for compound types you don't know what rec group and mut fields the lowering chose, and there is currently no way to specify this from the canon lower, which is only based on the core-type function signature.
To show the problem concretely, let me modify the variant example from the OP:
;; Component model types and function signature.
(type$cat (record (field"lives" u8))
(type$animal
(variant
(case $cat"cat"$cat)
(case $dog"dog" u16))
(type$sig (func (param"animal"$animal)))
;; A valid core lowering of that component type and function signature.;; The supertype for all arms of the `variant`.
(core type$animal' (sub (struct)))
;; The variant arm types.
(core rec
(type$cat' (sub $animal' (struct (field ???))))
(type$dog' (sub $animal' (struct (field (muti16))))))
;; The function signature.
(core type$sig' (param (ref$animal')))
;; The lowered function.
(core func$l (canon lower (func ...) gc (core-type$sig')))
What should be in ??? here?
If we were passing a $cat directly as a parameter, we could use any of the following:
That is, we have the explicit chain canon lower -> core-type -> sig' -> $cat''' in this case. Lowering can always statically know that $cat''' is what is wanted here, and doesn't have to do any dynamic lookups or tests or anything like that.
But for a variant's payload, how does lowering know which version to allocate in order to pass it to the receiver? Because, unlike for when when the $cat record is passed directly, the lowered version of $cat does not appear in the (core-type ...):
We have canon lower -> core-type -> $sig' -> $animal', but no connection from $animal' to a unique, unambiguous choice between $cat'/$cat''/$cat'''/$cat''''. We could go searching through all the module's defined types for something whose shape is right, but there might be many such types and we can't know which is actually right. Also, that search is happening at runtime when it is the host that is doing this lowering.
I see two options to resolve this issue:
Stop doing the "duck typing" and just spec unique, canonical GC representations of CM types. This is straightforward, but does imply copies if the component needs to convert the types to its own representations (e.g. needs the data to be defined by a type in a particular rec group, or needs a mut field when the canonical representation specifies a non-mut field or vice versa, or the data must be defined by a type with a particular supertype because everything must have that supertype in this guest language, etc...)
Add a (variant-arm $animal $cat $cat') canonical option that must be specified for every variant arm whose payload is a compound type that appears in the lowering's function signature. This allows the components to specify everything they want so they can avoid copies, but is very verbose. And it feels kind of gross to me.
I guess I am leaning towards (1) because it is the simplest thing to do, unlocking CM+GC functionality, and then, as a next incremental step, I believe that lazy value lowering should hopefully allow lowerings into component-chosen core GC types. But I am interested in hearing if folks have ideas I missed, and what other people's opinions are.
If dropping "duck typing", that in theory matches linear memory languages a bit more closely too. The canonical ABI representation of types, structs, etc, rarely matches the idiomatic representation in source languages. In my mind the main things to get right are things like string and list<u8> since those are so common you really want to try to get those to match most languages, which is somewhat the case for linear memory languages (but not all).
If going the route of canonical types though it might make sense to do something canonical-ABI-ish where flattening comes into play more regularly. For example record point { x: u32, y: u32 } as an argument would be passed as i32 i32 in wasm instead of a (ref $struct). That would allow, in the "fast" case, languages to choose their source of representation more freely and not pay the cost of translation. Like with linear memory languages list<point> would probably still incur a heavy translation cost as that would need to be represented as (array (ref $struct)). Basically though it might make sense to be more linear-memory-like in the ABI if there's one canonical type to reclaim some of the flexibility of representation while maintaining performance. The main difference is that where the canonical ABI today specifies an in-memory layout the GC ABI would specify some sort of struct definition.
Reacted by Justin Fagnani, Simon Binder and Zalim Bashorov
After working on the Wasmtime prototype some more, talking with @alexcrichton about the prototype/design, and talking with @bashor and @jmrtsh from the Kotlin-Wasm team about the design and what would work for their toolchain in practice, I've concluded that the original pre-proposal was flawed. It took on a bunch of complexity to be compatible with different rec group shapes, whether or not a field was mut or not, whether a type is final or not, etc..., however that complexity didn't even pay off in practice because it wasn't flexible enough to allow for every object to have a hash code and vtable field, which every Kotlin object must have (as well as be a subtype of Kotlin's any struct that defines those fields). I know that Grain's branch with Wasm GC support has the same impedance mismatch, and probably many other Wasm GC toolchains as well. So we were paying for flexibility that wasn't good enough. Also, the original pre-proposal just didn't work for variants.
Therefore, I've updated the OP to define a canonical GC lowering for each component model type (one lowering for flat values in params/results, and another for lowering into storage types on the GC heap).
This brings the GC ABI more inline with the linear memory ABI now: e.g. passing a tuple as a parameter also flattens its fields into core Wasm parameters up to a max-parameters limit.
This is also much simpler: when a component model type lowers into a GC struct or array object, there is exactly one such type of struct/array that it lowers into.
This also guarantees zero copying at the ABI boundary: because there can't be a mismatch where one component wants a struct that is in thisrec group while the other wants one that is in thatrec group, and because we can specify that the canonical lowered types are not mut, we can just pass objects across the ABI boundary without any copying.
I've also made it so that variants can be exhaustively matched on in $O(1)$ time, rather than an $O(n)$ chain of br_on_casts/ref.tests, by adding a discriminator tag that lifting asserts is i only when this is the ith case of the variant, and which can therefore be br_tabled upon.
The Kotlin-Wasm folks were confident that they can target this new style of GC ABI with the same approach that they were thinking about for the original version of the GC ABI. Their ideas involved lazily allocating wrapper/reflector objects when upcasting a CM object into a Kotlin object. I won't speak for them and their project, but I did want to note here that there was positive feedback on the new design from the toolchain side of things, not just from the engine side of things.
Roughly, my plan moving forward is to:
Update the wasm-tools parsing/validation support for CM+GC
Continue implementing a prototype in Wasmtime
Make a proper PR to this repo that can have multiple commits and git history and such, rather than just be a big issue comment thread, and can fit into the actual canonical ABI definition
Reacted by Simon Binder, Zalim Bashorov, Rikito Taniguchi and Jim M. R. Teichgräber
This change generally looks good from my point of view as well (Scala toolchain).
One thing is problematic: immutable ref arrays are currently impossible to construct in core Wasm, if they don't have a compile-time known fixed size. I mean you can create one but only with default values. There is no way to create a variable length array at run-time with dynamic content, not even by copying from an existing mutable array.
So either we must add that capability to core Wasm very soon, or we must use mutable arrays in the ABI.
Edit: oh, I see now that you also added some external polyfill to do just that. OK, I guess that works too.
Another issue (not blocking but not great) is that it will require 2 full copies in the general case: one loop to fill a new mutable array with lowering(element) from the language array. Then another full copy into an immutable array.
A related but distinct issue is that it's not possible to create a variable-size array of T where T is non defaultable. Even a mutable one. So you're still stuck trying to create your (array (mut (ref $elem))) even before having to turn it into an immutable copy.
I mean, you could perform the following dance, but it's atrocious:
Test if the language array is empty. If yes, return a new empty immutable array.
Convert the first element if the language array into its ABI lowering $first.
Now that you have one (ref $elem): Allocate a new mutable array filled with $first, using array.new
Loop to convert all the other elements of the language array into lowered elements, and store them in that mutable array.
Finally copy the whole thing into an immutable array.
Could we potentially introduce a "Defaultable GC Heap Storage Type" for types and use that for arrays? Then we could use arrays with nullable element references initially. It requires components and runtimes to insert null checks, but wouldn't need polyfills (we could make them non-nullable in a future CM version after core WebAssembly has better support for creating arrays).
Awesome! The ABI change looks good to me as well (Scala toolchain) One thing, I also have a question about how async would work with the GC ABI.
In the current linear memory based ABI, async function results are written into linear memory on out_ptr provided by the caller. And,similarly, things like stream.read take a pointer to a linear memory buffer.
How should this work with the GC ABI?
A few possible approaches would be:
Storing to caller-provided mutable GC objects
The caller allocates a mutable GC object (a result box) and passes it to the callee, as suggested here
For stream.read, perhaps this could be a mutable GC array?
However, the runtime would need to keep the object alive while the operation is pending, which might complicate things? (what if caller write something to the result box while pending?)(when the runtime should release the strong ref to the box?)
Retrieve results after completion
Or, maybe the runtime could hold result until the caller explicitly retrieves it through something like subtask.get-result(handle) or something (?)
I think this is the right direction. Two comments:
There seems to be a typo in the storage type column for s/u16, which probably was meant to say i16.
The variant encoding is problematic, because it creates a fundamental discontinuity: by just adding or removing a case, the encoding can change unexpectedly and completely, for all other cases. That's not robust. The more canonical way to encode a variant while still preserving flattening typically is to use eqref, and all (small enough) nullary constructors become i31ref, while all others become (ref $variant). No special case needed then.
Activity
fitzgen commentedon Jun 3, 2025
+cc @lukewagner @alexcrichton
fitzgen commentedon Jun 3, 2025
Realization: we could actually remove the discriminants from sum types if we prescribe that the cases are all defined in the same
recgroup.I'll prototype this and update the OP once it is working in
wasm-tools.Remove discriminants from sum types
wasmparser(CM+GC): Add support for lowering variants, options, and re…
wasmparser(CM+GC): Add support for lowering variants, options, and re…
fitzgen commentedon Jun 3, 2025
Done and done
lukewagner commentedon Jun 4, 2025
This is really exciting and I appreciate the clear writeup! Also, I love the approach of maximally-deriving the ABI from the core function type; that's an elegant solution to an otherwise gross problem. Overall, 👍 from me.
A few small questions/suggestions:
I'm probably misunderstanding the proposal, wasm-gc or both, but: for
variantet al, your examples all put the supertype in a separate rec group than the case subtypes but I would think that this doesn't expose the semantic link between "the variant type" and "the case types" that you need to let the core function type tell the whole story. E.g., iiuc, there's no "edge" in the type graph from$animal'to the rec group containing$dog'. (The edge exists in the other direction, ofc, but that's many-to-1, so you couldn't talk about "the rec group that contains subtypes of this supertype".) Instead, I would think that, since we're sortof hijacking rec groups in this scheme anyways, we'd say that variants have to refer to astructtype that is the first of its rec group and all the subsequent rec group members must be its cases; then thetypeidxused in the core function type points to a rec group that points to the cases.While you're right about the reason that
optioncan't representnonewithref.nullin general, could we say that, whenoption<T>has a non-null-allowingT,ref.nullrepresentsnone? This is ad hoc and irregular, but we are licensed to do that in the CABI when it's a significant win andoptionis very common and I expect this optimization would to 95% ofoptions in practice.result<T>(noE) andresult(noT) are also super common and I think perhaps worth optimizing. Could the former usenullforerrorand the latter return a (boolean)i32(making it no less efficient thanenum, so that no one has the perverse incentive to use anenumfor aresultfor perf reasons)?lukewagner commentedon Jun 5, 2025
Two more follow-up thoughts:
latin1+utf16string-encoding, there's the question of how to communicate the dynamic "is it Latin-1 or UTF-16?" boolean (which is packed with the length into ani32when using linear memory). One idea is that you could take a page from how variants work and have the static type be(ref null? array)and dynamically accept/produce either(ref (array i8))or(ref (array i16)).own,borrow,futureandstream(as well as waitable sets and async subtasks): one issue I just realized is that variousdropbuilt-ins trap under various conditions (ownandborrowtrap if there are any extant async import calls to which they were lent; the writable end of afuturetraps if dropped without having written a value; etc). As a general rule, we try to avoid ever allowing user code of a safe language to hit a raw wasm trap, so somehow we need to figure out how the language runtime (running as wasm using the CABI) is able to avoid hitting these traps. One option would be to extend the "drop if unreachable" semantics to be "drop if unreachable and the trapping conditions are met", but I'm thinking this will get tricky and subtle. Another option is to force the wasm guest to rootexternrefs during times when they would trap if they became unreachable, but this might end requiring the wasm guest to maintain a lot of parallel bookkeeping already maintained by the C-M, maybe adding non-trivial overhead. So I wonder if a nice third option is to leave these types the same as with linear memory (i32s that need to be dropped), but introduce new canon built-ins that provide postmortem-notification analogous-to and polyfilled-viaFinalizationRegistryand then allow the language runtime to use this primitive to Do The Right Thing itself. Such a built-in could also be used for other guest-internal purposes (such as associating a linear-memory buffer that needs to be freed with a wasm-GC object).rossberg commentedon Jun 6, 2025
A few drive-by comments:
@lukewagner:
FWIW, I don't think it is gonna be even close to 95%. Languages with parametric polymorphism typically don't or can't do such a specialisation, because it would require costly runtime type passing and dispatch. That probably includes languages like Java with its Optional type.
lukewagner commentedon Jun 6, 2025
@rossberg
Ah, interesting point. When I said "95%", I was talking about the percent of
options appearing in WIT interfaces, but also thinking about howoptions are represented "at rest" in various languages is a good for regularity.Question: if a lowered function type lowers an
optioninto a non-eqreference with an emptystructrepresentingnone, can the engine implementnonewith a single-per-type allocation (since the identity isn't observable viaeqor mutation)? If so, then thenulloptimization wouldn't even be that big of a win.rossberg commentedon Jun 6, 2025
I would represent None as an i31 ref with value zero (or any random value). It is just an instance of a variant type, where runtimes typically represent nullary constructors as different tagged ints. Which, now that I mention it, is something the variant encoding should also support.
Edit: Though null would equally work for option. What these languages generally can't do is unboxing Some.
gertvv commentedon Jun 9, 2025
This is awesome! As an outsider, the wording on variant types is confusing:
However the example defines a
(struct (field i32))which looks like a tagged union, but this is not explicitly stated. Is this the correct interpretation? And if so, can the lowering choose to use a smaller (packed) int instead, like the linear memory ABI does?fitzgen commentedon Jun 13, 2025
Ah I just forgot to update the example. There shouldn't be any
(field i32)there. Will update the OP shortly.fitzgen commentedon Jun 13, 2025
@lukewagner
Because the shape of the cases' rec group is fully defined, there doesn't need to be an explicit link: the engine/fused adapter compiler can simply (re)define the cases' rec group and then rely on type canonicalization.
This approach is slightly more flexible than keeping the base type in the same rec group as the cases, since it allows the base type to be defined in any rec group of the producer's choosing.
I'm fine with ultimately doing this kind of thing, but I am not going to do it for now, in my current prototyping, and therefore I am not going to update the OP with it either (which I will try to keep in sync with my prototyping).
As this extension settles and gets upstreamed into the spec, it should of course describe what we ultimately come to consensus on standardizing, and not what I just happen to have prototyped, but we can cross that bridge when we get to it.
Yeah, this makes sense and the OP reflects a misunderstanding on my part. Will update as soon as I fix my prototype.
Alternatively, we could continue to require explicit drop calls (as we do now for linear memory) rather than say that these things are implicitly dropped on finalization. If the
externrefbecomes unreachable without the future/stream having been explicitly dropped, then the future/stream is never dropped. Language-specific bindings generators can wrap this stuff up similar to what they would have to do now when translating to the linear memory variant of the ABI (e.g. Python would use itswithconstruct).Then, as a next step, we can introduce those canonical builtins for finalizers that allows them to Do The Right Thing.
This approach is smaller and more incremental and crucially doesn't require finalizer support in implementations initially at all.
fitzgen commentedon Jun 13, 2025
@rossberg
This gets at the philosophical question of how much duck typing we want to do. The proposal is doing some amount already with its matching of component types against many core types by their shape, but right now they always match against one shape modulo nullability, subtyping, and rec group. Allowing
i31refin various places is widening things such that we would match against multiple shapes. It seems to me like this could potentially be a slippery slope: How many shapes is enough? How do we decide whether a shape is worthy of matching against?I'm not saying I'm against adding support for
i31ref, but I do think we should consider what design principles we want to follow in this CM+GC extension.It is also possible my concerns are overblown, and this is the only additional shape we will actually want to match against.
19 remaining items
lukewagner commentedon Oct 21, 2026
That seems like a pretty good idea for an incremental first addition to me!
So just to check my understanding: you're suggesting no changes to lifting/lowering (yet), but rather a few new ABI built-ins (that can use Core WebAssembly reference types b/c they're ABI built-ins) that Jco could polyfill with
FinalizationRegistery/WeakRef? If so, before a full PR, maybe a good first step would be to build a prototype implementation of these new ABI built-ins in Jco that you could validate with your Dart implementation? (cc @vados-cosmonic for thoughts.) Since this issue is already a bit long and is mostly focused on the lifting/lowering ABI questions, it's probably also a good idea to create a new issue dedicated to this idea to sketch out the shape of these new ABI built-ins before or during the prototyping.justinfagnani commentedon Oct 22, 2026
Shouldn't weakrefs and finalization registries be in Wasm GC proper, not the component API? This would be one more thing that a toolchain has to compile differently for core modules on JS vs components.
spotandjake commentedon Oct 22, 2026
I had a similar concern, if finalization registries and or weakrefs are added to the component model, it may duplicate effort or cause duplicate apis if similar wasm proposals are made as extensions to wasm gc.
simolus3 commentedon Oct 22, 2026
Finalizers require callbacks, which requires a decision on when these callbacks run. The component model has a perfect primitive for this in the form of waitables, it doesn't seem like this can be added to core WebAssembly.
I have opened #752 to discuss that specifically, I'd love to hear your thoughts there!
fitzgen commentedon Nov 4, 2026
I had a conversation with @alexcrichton yesterday about
variants and CM+GC and the conclusion we came to is that this pre-proposal doesn't work for variants that havetupleandrecordpayloads (and probably not any other compound type either).The current "duck typing" allows producers and consumers to choose which GC struct to use for a
recordortuple(in particular, whichrecgroup it is defined in, whether it isfinalor not, and whether its fields aremutor not). And the way thatvariantis spec'd here, we can passvariants back and forth, but if you then want to downcast them to a particular arm of thevariant, then what type do you test for in your downcast? It is obvious for scalars and the rules work in that case, but for compound types you don't know whatrecgroup andmutfields the lowering chose, and there is currently no way to specify this from thecanon lower, which is only based on the core-type function signature.To show the problem concretely, let me modify the
variantexample from the OP:What should be in
???here?If we were passing a
$catdirectly as a parameter, we could use any of the following:But which one is actually chosen is fixed by the core signature given as
(core-type ...)in the(canon lower ...), for example:That is, we have the explicit chain
canon lower->core-type->sig'->$cat'''in this case. Lowering can always statically know that$cat'''is what is wanted here, and doesn't have to do any dynamic lookups or tests or anything like that.But for a
variant's payload, how does lowering know which version to allocate in order to pass it to the receiver? Because, unlike for when when the$catrecord is passed directly, the lowered version of$catdoes not appear in the(core-type ...):We have
canon lower->core-type->$sig'->$animal', but no connection from$animal'to a unique, unambiguous choice between$cat'/$cat''/$cat'''/$cat''''. We could go searching through all the module's defined types for something whose shape is right, but there might be many such types and we can't know which is actually right. Also, that search is happening at runtime when it is the host that is doing this lowering.I see two options to resolve this issue:
Stop doing the "duck typing" and just spec unique, canonical GC representations of CM types. This is straightforward, but does imply copies if the component needs to convert the types to its own representations (e.g. needs the data to be defined by a type in a particular
recgroup, or needs amutfield when the canonical representation specifies a non-mutfield or vice versa, or the data must be defined by a type with a particular supertype because everything must have that supertype in this guest language, etc...)Add a
(variant-arm $animal $cat $cat')canonical option that must be specified for everyvariantarm whose payload is a compound type that appears in the lowering's function signature. This allows the components to specify everything they want so they can avoid copies, but is very verbose. And it feels kind of gross to me.I guess I am leaning towards (1) because it is the simplest thing to do, unlocking CM+GC functionality, and then, as a next incremental step, I believe that lazy value lowering should hopefully allow lowerings into component-chosen core GC types. But I am interested in hearing if folks have ideas I missed, and what other people's opinions are.
alexcrichton commentedon Nov 4, 2026
If dropping "duck typing", that in theory matches linear memory languages a bit more closely too. The canonical ABI representation of types, structs, etc, rarely matches the idiomatic representation in source languages. In my mind the main things to get right are things like
stringandlist<u8>since those are so common you really want to try to get those to match most languages, which is somewhat the case for linear memory languages (but not all).If going the route of canonical types though it might make sense to do something canonical-ABI-ish where flattening comes into play more regularly. For example
record point { x: u32, y: u32 }as an argument would be passed asi32 i32in wasm instead of a(ref $struct). That would allow, in the "fast" case, languages to choose their source of representation more freely and not pay the cost of translation. Like with linear memory languageslist<point>would probably still incur a heavy translation cost as that would need to be represented as(array (ref $struct)). Basically though it might make sense to be more linear-memory-like in the ABI if there's one canonical type to reclaim some of the flexibility of representation while maintaining performance. The main difference is that where the canonical ABI today specifies an in-memory layout the GC ABI would specify some sort ofstructdefinition.fitzgen commentedon Nov 18, 2026
After working on the Wasmtime prototype some more, talking with @alexcrichton about the prototype/design, and talking with @bashor and @jmrtsh from the Kotlin-Wasm team about the design and what would work for their toolchain in practice, I've concluded that the original pre-proposal was flawed. It took on a bunch of complexity to be compatible with different
recgroup shapes, whether or not a field wasmutor not, whether a type isfinalor not, etc..., however that complexity didn't even pay off in practice because it wasn't flexible enough to allow for every object to have a hash code and vtable field, which every Kotlin object must have (as well as be a subtype of Kotlin's any struct that defines those fields). I know that Grain's branch with Wasm GC support has the same impedance mismatch, and probably many other Wasm GC toolchains as well. So we were paying for flexibility that wasn't good enough. Also, the original pre-proposal just didn't work forvariants.Therefore, I've updated the OP to define a canonical GC lowering for each component model type (one lowering for flat values in params/results, and another for lowering into storage types on the GC heap).
This brings the GC ABI more inline with the linear memory ABI now: e.g. passing a
tupleas a parameter also flattens its fields into core Wasm parameters up to a max-parameters limit.This is also much simpler: when a component model type lowers into a GC
structorarrayobject, there is exactly one such type ofstruct/arraythat it lowers into.This also guarantees zero copying at the ABI boundary: because there can't be a mismatch where one component wants a
structthat is in thisrecgroup while the other wants one that is in thatrecgroup, and because we can specify that the canonical lowered types are notmut, we can just pass objects across the ABI boundary without any copying.I've also made it so that$O(1)$ time, rather than an $O(n)$ chain of
variants can be exhaustively matched on inbr_on_casts/ref.tests, by adding a discriminator tag that lifting asserts isionly when this is theithcaseof thevariant, and which can therefore bebr_tabled upon.The Kotlin-Wasm folks were confident that they can target this new style of GC ABI with the same approach that they were thinking about for the original version of the GC ABI. Their ideas involved lazily allocating wrapper/reflector objects when upcasting a CM object into a Kotlin object. I won't speak for them and their project, but I did want to note here that there was positive feedback on the new design from the toolchain side of things, not just from the engine side of things.
Roughly, my plan moving forward is to:
wasm-toolsparsing/validation support for CM+GCkevmoo commentedon Nov 18, 2026
This is great to hear, @fitzgen
There are a few of us in the Dart world that would love to collaborate here (CC @simolus3)
Would love to chat with @bashor etc at https://bytecodealliance.zulipchat.com/#narrow/channel/394175-SIG-Guest-Languages/topic/WasmGC.20guest.20language.20collaboration/with/633089671 (or somewhere else) on how we can align and validate
sjrd commentedon Nov 19, 2026
This change generally looks good from my point of view as well (Scala toolchain).
One thing is problematic: immutable ref arrays are currently impossible to construct in core Wasm, if they don't have a compile-time known fixed size. I mean you can create one but only with default values. There is no way to create a variable length array at run-time with dynamic content, not even by copying from an existing mutable array.
So either we must add that capability to core Wasm very soon, or we must use mutable arrays in the ABI.
Edit: oh, I see now that you also added some external polyfill to do just that. OK, I guess that works too.
Another issue (not blocking but not great) is that it will require 2 full copies in the general case: one loop to fill a new mutable array with
lowering(element)from the language array. Then another full copy into an immutable array.sjrd commentedon Nov 19, 2026
A related but distinct issue is that it's not possible to create a variable-size array of
TwhereTis non defaultable. Even a mutable one. So you're still stuck trying to create your(array (mut (ref $elem)))even before having to turn it into an immutable copy.I mean, you could perform the following dance, but it's atrocious:
$first.(ref $elem): Allocate a new mutable array filled with$first, usingarray.newWe would need something like WebAssembly/more-array-constructors#1 to deal with that.
fitzgen commentedon Nov 19, 2026
@sjrd I think we could avoid ~all of that pain via an
array.unfoldinstruction (which we could polyfill via new canon definitions in the meantime): WebAssembly/more-array-constructors#1 (comment)simolus3 commentedon Nov 19, 2026
Could we potentially introduce a "Defaultable GC Heap Storage Type" for types and use that for arrays? Then we could use arrays with nullable element references initially. It requires components and runtimes to insert null checks, but wouldn't need polyfills (we could make them non-nullable in a future CM version after core WebAssembly has better support for creating arrays).
tanishiking commentedon Nov 20, 2026
Awesome! The ABI change looks good to me as well (Scala toolchain) One thing, I also have a question about how
asyncwould work with the GC ABI.In the current linear memory based ABI, async function results are written into linear memory on
out_ptrprovided by the caller. And,similarly, things likestream.readtake a pointer to a linear memory buffer.How should this work with the GC ABI?
A few possible approaches would be:
stream.read, perhaps this could be a mutable GC array?subtask.get-result(handle)or something (?)rossberg commentedon Nov 23, 2026
I think this is the right direction. Two comments:
fitzgen commentedon Nov 24, 2026
I've now made a PR to update the actual spec instead of just having a sketch in this issue's OP: #773
I suggest that details be discussed there as PR reviews.