Skip to content

Implement Wasm GC in Wasmtime - #31

Merged
fitzgen merged 13 commits into
bytecodealliance:mainfrom
fitzgen:wasm-gc
Jun 5, 2023
Merged

fitzgen merged 13 commits into
bytecodealliance:mainfrom
fitzgen:wasm-gc

Conversation

@fitzgen

@fitzgen fitzgen commented Apr 14, 2023

Copy link
Copy Markdown
Member

Implement support for the WebAssembly garbage collection proposal in Wasmtime. Allow plugging different collectors into Wasmtime to support the requirements of different Wasmtime embeddings running different Wasm workloads.

Rendered

@c-cube

c-cube commented Apr 16, 2023

Copy link
Copy Markdown

Hi, just a drive-by suggestion: has Immix been considered as an alternative to Boehm? It's a precise GC afaik, whereas Boehm is conservative.

@programmerjake

programmerjake commented Apr 16, 2023 •

Copy link
Copy Markdown
Contributor

imho wasm gc will eventually need to support a multi-threaded wasm program with gc, so do try to account for this and don't rely on wasmtime api types being !Send unless you can think of a reasonable way to access them from a different thread (e.g. separate Send + Sync and !Send types, where the latter is kinda like a mutex guard or maybe a Rc<Arc<T>>)

@waywardmonkeys

Copy link
Copy Markdown

@fitzgen Have you seen or looked at https://github.com/Ravenbrook/mps ?

@rptb1 may have more to add, but MPS is a great GC and has been used in production scenarios over the years. There's not a Rust binding at the moment, but that seems like it could be resolved.

Comment thread accepted/wasm-gc.md Resolved
@fitzgen

fitzgen commented Apr 17, 2023

Copy link
Copy Markdown
Member Author

@programmerjake

imho wasm gc will eventually need to support a multi-threaded wasm program with gc, so do try to account for this and don't rely on wasmtime api types being !Send unless you can think of a reasonable way to access them from a different thread (e.g. separate Send + Sync and !Send types, where the latter is kinda like a mutex guard or maybe a Rc<Arc<T>>)

Minor correction: the relevant wasmtime API types are !Sync + Send, not !Send.

Regarding the larger idea of combining Wasm threads and Wasm GC: every sketch I've seen about extending the Wasm threading model to new bits of state requires marking that state as shared the same way that memories are either shared or not. So GC types would need to be marked shared to allow multi-threaded access to their instances. Assuming that is the case, then when we are compiling Wasm code, we'll be able to only emit atomic and synchronized operations when necessary and omit them when we the type information tells us it is statically unnecessary. In the public wasmtime API we may want to have separate Rust types for reflecting shared vs not Wasm GC types, the way we have wasmtime::SharedMemory and wasmtime::Memory, or allow dynamic downcasting to unsynchronized types based on checking whether the underlying GC object's type is shared or not. But all this is a bit speculative and far future as there hasn't been any proposal about how to combine these two different features yet, as far as I'm aware.

@alexcrichton alexcrichton left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This all sounds great to me!

I read the term "GC pause" in relation to the pooling instance allocator and something it reminded me of is the interaction with epochs/fuel. Embedders limiting the execution time of a wasm instance will often use fuel for determinism, epochs for a timeout, or epochs plus async for "allow me to cancel at any epoch time slice". If GC is expected to take a negligible amount of time (e.g. short-lived instances) this may not be much of a problem but as the cost of a GC grows this may become noticeable.

I'm not really sure what to do with this myself, but we may end up needing to integrate epochs and fuel into the stop-the-world part of the GC. That would necesitate some level of "save the work for later and then resume" style GC's though which doesn't seem like it would be trivial. Alternatively though, especially for a time-sliced HTTP server, pausing for a "big GC" also seems like it could end quite badly too.

Basically another way to put this is that I'm not sure if there's sufficient knobs for an embedder to protect themselves against a pathological scenario where GCs are frequent and very long. Do you have thoughts though on how this could be addressed?

Comment thread accepted/wasm-gc.md Resolved
Comment thread accepted/wasm-gc.md Resolved
Comment thread accepted/wasm-gc.md Resolved
Comment thread accepted/wasm-gc.md Resolved
Comment thread accepted/wasm-gc.md Resolved
Comment thread accepted/wasm-gc.md Outdated
1. The null GC, which allocates until it runs out of heap space, at which
point it triggers a trap in the guest.

2. A general-purpose collector, built on top of an off-the-shelf GC library.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Out of curiosity, is the "GC" part of the off-the-shelf library necessary? It seems like we're doing all the hard work of rooting and maintaining layouts, so building an implementation on top of malloc wouldn't really be all that much worse than any other GC library at that point (like boehm or something like that I'd presume).

This definitely makes sense to have, but it seems to be like it could be basically something backed by SystemAlloc in Rust.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The hard part is not rooting and object layouts, but implementing a nursery, compaction, background sweeping, parallel tracing, incremental GC, and everything else that a general-purpose GC is going to eventually want.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(still have some thoughts so un-resolving this temporarily)

For a first-pass implementation do we need that though? Of the benefits you listed:

  • Nursery / compaction - these seem like things that malloc is a "proxy" for, although I realize that malloc is not perfect for these of course.
  • Background sweeping - we're not going to want this any time in the near future I think? That'd be reliant on something like the shared attribute in core wasm?
  • Parallel tracing - does a GC library do this for us? Wouldn't we do all the tracing ourselves since we're the ones understanding the heap layout of all GC objects? I haven't worked with any off-the-shelf GC libraries so I'm likely missing something here.

I can understand how perhaps, one day, we want a super-fancy all-the-bells-and-whistles GC. That to me feels on the order of numbers-of-years out though so it seems like "just call malloc" with a simple mark/sweep could be sufficient for quite some time.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nursery / compaction - these seem like things that malloc is a "proxy" for, although I realize that malloc is not perfect for these of course.

Do you mean proxy in that the malloc implementation should handle these things for us? I don't think it can or will. I'm not totally following you here.

Background sweeping - we're not going to want this any time in the near future I think? That'd be reliant on something like the shared attribute in core wasm?

Because wasm-gc doesn't have finalizers, it isn't semantically visible to the wasm program where/when sweeping happens. Therefore, it doesn't rely on anything like a shared attribute, and is purely a runtime optimization. And it is a very nice optimization, since sweeping is O(heap size) not O(live objects), at least in simple mark-sweep.

Parallel tracing - does a GC library do this for us? Wouldn't we do all the tracing ourselves since we're the ones understanding the heap layout of all GC objects? I haven't worked with any off-the-shelf GC libraries so I'm likely missing something here.

It depends on the details of the library, I suppose. I haven't used any of these libraries in anger myself either.

But before digging in too much further: we are not the ones who understand object layout. It is the collector that knows object layout, and us who have to indirectly access fields. And object layout has to be the collector's responsibility since different collectors have different requirements for things like header words or reference counts or any other kind of metadata it requires.

I can understand how perhaps, one day, we want a super-fancy all-the-bells-and-whistles GC. That to me feels on the order of numbers-of-years out though so it seems like "just call malloc" with a simple mark/sweep could be sufficient for quite some time.

Yeah, perhaps if we don't hear from any of the non-FaaS Wasmtime embedders (who are all going to want to use the semi-space copying collector) we can ignore the general-purpose GC usecase for now and only have the null collector and the semi-space copying collector.

But if we still want to have a general-purpose GC, then I'm not sure what you are proposing. Just doing malloc/free and simple mark-sweep ourselves is going to be a very suboptimal collector, probably worse than the semi-space copying collector for long-running Wasm programs. So I'm not sure it would actually gain us anything.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm before I answer some other things one thing you said confuses me:

And object layout has to be the collector's responsibility since different collectors have different requirements for things like header words or reference counts or any other kind of metadata it requires.

I don't understand this because doesn't compiled code need to access the object's layout? Doesn't this mean that, no matter what, the in-memory layout of an object is intimately know by the runtime to something other than a collector as a black box? For example the GcCompiler trait would have a very close relationship to the collector, so if we picked an off-the-shelf library doing fancy things here we'd reverse-engineer it and codify it in a corresponding GcCompiler implementation.

I think overall what I'm feeling is that we should start with something backed by mark-and-sweep plus malloc knowing that it's not going to be that performant. We can have a specialization for the pooling allocator and FaaS-style runtimes of course, but I'm hesitant to bring in a large GC library dependency. GC is notoriously hard to get right and I'm not sure that any of us are so familiar with any particular GC library that we'd be willing to stake our security on the correctness of it and our understanding of its internals.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand this because doesn't compiled code need to access the object's layout? Doesn't this mean that, no matter what, the in-memory layout of an object is intimately know by the runtime to something other than a collector as a black box? For example the GcCompiler trait would have a very close relationship to the collector, so if we picked an off-the-shelf library doing fancy things here we'd reverse-engineer it and codify it in a corresponding GcCompiler implementation.

Yes, object layout would be completely encapsulated within GcCompiler implementations. The GcCompiler implementation wouldn't really "reverse engineer" the object layout, but would be considered "part of" the collector and would have insider knowledge/collaboration that the rest of the compiler/runtime wouldn't have (or would only get indirectly via GcObjectLayout) and which would potentially differ across different collector implementations.

I think overall what I'm feeling is that we should start with something backed by mark-and-sweep plus malloc knowing that it's not going to be that performant. We can have a specialization for the pooling allocator and FaaS-style runtimes of course, but I'm hesitant to bring in a large GC library dependency. GC is notoriously hard to get right and I'm not sure that any of us are so familiar with any particular GC library that we'd be willing to stake our security on the correctness of it and our understanding of its internals.

I agree with you about the difficulty of building a correct and performant GC.

What I'm saying though is that if we don't want to pull in an external library for the general-purpose GC use case, then we shouldn't attempt to build our own. Instead we should just use the semi-space copying collector that we need for pooling allocator integration for the general-purpose GC use case. It won't be as good as what someone could build with MMTK, but it will be better than naive mark-and-sweep backed by malloc/free. And this approach allows us to build just two GCs (null, semi-space copying) instead of three (null, semi-space copying, mark-and-sweep).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've updated the RFC to remove MMTK and the general-purpose collector. Now there is just the null GC and the semi-space copying collector.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok yeah that all sounds reasonable to me 👍

Comment thread accepted/wasm-gc.md Resolved

@jakobkummerow jakobkummerow left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caveat: I'm not familiar with wasmtime or Rust, just commented on a few things I noticed as a fellow WasmGC implementer.

I hope that at least some of these comments are useful.

I'm very excited to see this project getting started!

Comment thread accepted/wasm-gc.md Resolved
Comment thread accepted/wasm-gc.md Resolved
Comment thread accepted/wasm-gc.md Resolved
Comment thread accepted/wasm-gc.md Resolved
Comment thread accepted/wasm-gc.md Resolved
Comment thread accepted/wasm-gc.md Resolved
Comment thread accepted/wasm-gc.md Resolved
@fitzgen

fitzgen commented Apr 28, 2023

Copy link
Copy Markdown
Member Author

@alexcrichton

I'm not really sure what to do with this myself, but we may end up needing to integrate epochs and fuel into the stop-the-world part of the GC. That would necesitate some level of "save the work for later and then resume" style GC's though which doesn't seem like it would be trivial. Alternatively though, especially for a time-sliced HTTP server, pausing for a "big GC" also seems like it could end quite badly too.

Basically another way to put this is that I'm not sure if there's sufficient knobs for an embedder to protect themselves against a pathological scenario where GCs are frequent and very long. Do you have thoughts though on how this could be addressed?

I don't think this actually requires that the GC is incremental the way that the GC literature defines it, because these scenarios don't require resuming the mutator when we async yield.

But that is a good point that we want the equivalent of

trait GcRuntime {
    // ...

    unsafe async fn async_gc(
        &self,
        heap: GcHeap,
        roots: RootSet,
        yield_every: std::time::Duration,
    );
}

but of course it would be a bit uglier than that because we can't have async methods in traits yet.

I think this should be sufficient to address your concerns, yeah?

@alexcrichton

Copy link
Copy Markdown
Member

I'm not sure myself really, I don't feel like I've got a good enough handle on the problems that GC might bring pause-wise. There's a balancing act between what the GC algorithms can support and what embedders want to happen. For example can all GC algorithms easily implement what you listed above where, in the middle of a GC, it realizes "time's up" and records info to resume later? I'm not sure additionally how it would work to thread through the deadline into embedders. For example they could configure "take no longer than 2ms" but if WebAssembly already nearly consumed its entire time slice with executing code and then the GC takes an additional 2ms is that bad?

I'm not sure that we're really positioned to answer these questions at this time. I feel like we'll basically have to wait and see and figure it out as we go along and have more constraints available to us to design a solution within.

@fitzgen

fitzgen commented May 3, 2023

Copy link
Copy Markdown
Member Author

I'm not sure myself really, I don't feel like I've got a good enough handle on the problems that GC might bring pause-wise. There's a balancing act between what the GC algorithms can support and what embedders want to happen. For example can all GC algorithms easily implement what you listed above where, in the middle of a GC, it realizes "time's up" and records info to resume later? I'm not sure additionally how it would work to thread through the deadline into embedders. For example they could configure "take no longer than 2ms" but if WebAssembly already nearly consumed its entire time slice with executing code and then the GC takes an additional 2ms is that bad?

I'm not sure that we're really positioned to answer these questions at this time. I feel like we'll basically have to wait and see and figure it out as we go along and have more constraints available to us to design a solution within.

I don't think we need to require that all collectors to implement async_gc, just the ones we intend to use with async, ie the collector that integrates with the pooling allocator. But in general, production GCs are very used to trying to minimize stop-the-world pauses and doing work incrementally. Our problem is easier than usual because we aren't even resuming the mutator in between slices. But you're right that this might not align with existing off-the-shelf libraries and their APIs. I think that is fine: the same way that some collectors just won't integrate with the pooling allocator, some won't support async collection. And if we move to having just the null GC and the semi-space copying collector (as discussed up thread) then we can make them both support async pretty easily.

As far as the API for setting quanta and all that: I'm all ears. Rather than a single Future that completes when GC is finished, we could have many futures, each completing when their time slice is completed and then returning either "I'm done GCing, here is your instance back" or "I have more GC work to do, give me a quantum and I'll return a new future for this next time slice". This would let us have different lengths of GC slices and notably make that first one shorter because of the amount of time that Wasm has already executed for the whole store's current time slice. Or we could explicitly pass in some kind of "check whether you should yield" handle to the collector that checks the epoch in VMRuntimeLimits directly. I kind of like this latter approach...

fitzgen added 2 commits May 3, 2023 13:15
Also add public API methods for `{in,ex}ternalize`
Just have the null GC and the semi-space copying collector for now.

Can evaluate and consider options (MMTK vs home-rolled, etc) later on if/when
stakeholders are actually clamoring for a general-purpose collector.
@fitzgen

fitzgen commented May 15, 2023

Copy link
Copy Markdown
Member Author

Motion to Finalize

Disposition: Merge

It seems like we have mostly come to consensus here and the bits that we haven't hammered out 100% are things we can do during the implementation phase. As such, I am moving that we merge this RFC.


Note: I don't want to trawl through commit logs and try and figure out which committer is part of which BA organization, so I'm not making a stakeholder check list. Just approve the PR or comment to sign off, or alternatively leave a comment detailing your objections if you have them. I'll manually keep track of whether we have multi-org sign off and all that as the comments come in.

As always, details on the RFC process can be found here: https://github.com/bytecodealliance/rfcs/blob/main/accepted/rfc-process.md#making-a-decision-merge-or-close

@pchickey pchickey left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great work, Nick!

@tschneidereit tschneidereit left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is really great! <3

@fitzgen

fitzgen commented May 24, 2023

Copy link
Copy Markdown
Member Author

As there have been signoffs from at least two people representing different stakeholder organizations, this RFC is entering its 10 day

Final Comment Period

and the last day to raise objections before this can merge is 2023-06-03.

@fitzgen

fitzgen commented Jun 5, 2023

Copy link
Copy Markdown
Member Author

Seeing as no objections have been raised during the final comment period, I'm going to go ahead and merge this. Thanks everyone!

@fitzgen
fitzgen merged commit 19e1dc4 into bytecodealliance:main Jun 5, 2023
@fitzgen
fitzgen deleted the wasm-gc branch June 5, 2023 16:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.