posborne opened PR #15101 from posborne:resource-table-host-heap-limiter to bytecodealliance:main:
Motivation
Embedders currently lack an aggregate host-side memory boundary for component model resources in
ResourceTable. While #12652 added mitigations around handle counts and hostcall fuel, cumulative host heap allocations owned by resources inResourceTablewere previously untracked by any umbrella mechanism.Over the past several releases, Wasmtime has had to address a recurring class of guest-driven host memory exhaustion advisories with mitigations including [GHSA-852m-cvvp-9p4w] and [GHSA-243v-98vx-264h] (#12652), [GHSA-c9gc-w9vx-w86p], [GHSA-gqmc-89g8-p25r], and [GHSA-6fr9-xmw9-5352]. While per-resource and per-call limits help, they do not bound the aggregate host heap memory accumulated across entries in a
ResourceTable.Solution
This PR adds host heap usage accounting and optional per-table byte limits to
wasmtime::component::ResourceTable. This provides a level of umbrella coverage to protect against host paths that may not have protections currently and to provide a higher level limit that is easier to reason about for embedders.The way that this is achieved involves the introduction of a
HostHeapUsagetrait which is required for all resources. This is accompanied by aFixedHostHeapUsagetrait as a marker for types which do not contain children with heap storage not accounted for in their own size directly. Methods on the table that push, delete or mutate (update) resources use the traits to account for the heap usage changes associated with the operation. If a limit is set and an operation causes the heap usage to grow beyond the set limit, the operations return an error which will typically result in a guest-side trap.These new requirements necessitate updates across the wasmtime tree and will be a breaking change for embedders that are pushing their own resources into
ResourceTables.Design Decisions
The code here has gone through a few iterations and updates based on discussion in #12984. What is present here tries to incorporate that feedback and is closer to some of the implementation from servo/firefox/stylo
MallocSizeOftrait.In instrumenting the code to implement the traits, I decided that to ease the burden on embedders and to provide some additional static guarantees, it would be beneficial to introduce proc-macros in order to aid in deriving the traits on compatible structs and enums.
For mutation I went with a closure-based
updaterather than a guard, because the limit check has to be fallible and a guard could only account inDrop. This makes former get_mut call sites a bit noisier. Since update can only measure after the mutation runs, growth past the limit is reported rather than prevented, and the mutation isn't rolled back because the error is expected to trap. The overshoot is roughly limited to what a single host call can allocate.Across the code in tree (mostly wasi p2/p3), I tried to provide pragmatic implementations of the trait where reasonable and erred on the side of overcounting bytes in most cases. There are some reference counted cases which are not tracked with complete accuracy but, even in those cases, abuse should be challenging as the fixed size of the resource will be counted even if the amortized cost of the shared data is left unaccounted.
Future Work
The changes here are sprawling, so I wanted to avoid increasing the scope beyond what was required for purpose and reasonable ergonomics (adding derive). Potential future work that I opted to not try to incorporate here include:
- Allow for the limit to be set at a higher level outside of individual tables, probably on the
ResourceLimiter.- Hooks to intervene when limits are exceeded or at watermarks prior to the limit.
- Fast path or conditional compilation to opt out of tracking; even if no limit is set the accounting is done and count is available.
Closes #12984
[GHSA-852m-cvvp-9p4w]: https://github.com/bytecodealliance/wasmtime/security/advisories/GHSA-852m-cvvp-9p4w
[GHSA-243v-98vx-264h]: https://github.com/bytecodealliance/wasmtime/security/advisories/GHSA-243v-98vx-264h
[GHSA-c9gc-w9vx-w86p]: https://github.com/bytecodealliance/wasmtime/security/advisories/GHSA-c9gc-w9vx-w86p
[GHSA-gqmc-89g8-p25r]: https://github.com/bytecodealliance/wasmtime/security/advisories/GHSA-gqmc-89g8-p25r
[GHSA-6fr9-xmw9-5352]: https://github.com/bytecodealliance/wasmtime/security/advisories/GHSA-6fr9-xmw9-5352
posborne removed the review request for wasmtime-wasi-reviewers from PR #15101.
posborne requested rvolosatovs for a review on PR #15101.
posborne requested wasmtime-wasi-reviewers for a review on PR #15101.
posborne removed the review request for wasmtime-core-reviewers from PR #15101.
posborne requested alexcrichton for a review on PR #15101.
posborne requested wasmtime-core-reviewers for a review on PR #15101.
github-actions[bot] added the label wasi on PR #15101.
github-actions[bot] added the label wasmtime:c-api on PR #15101.
:memo: alexcrichton submitted PR review:
Thanks for this! I personally think this is a pretty reasonable change to make and it's only going to be even more accurate than things are today if embedders conservatively always use
FixedHostHeapUsage. By providing the knobs though I think this is going to be quite useful.
:speech_balloon: alexcrichton created PR review comment:
I think this'd make sense to have it just be a
usizesince it can always be unlimited withusize::MAX
:speech_balloon: alexcrichton created PR review comment:
Would it make sense to call
self.reservehere to track the capacity of the table itself?
:speech_balloon: alexcrichton created PR review comment:
I'm a bit surprised, but we didn't end up needing an impl for
Box<T>?
:speech_balloon: alexcrichton created PR review comment:
I haven't gotten to looking more closely at the WASI bits yet, but this might make more sense as an RAII guard rather than a closure-based update. That'd help with rightward drift and it would have the same rough semantics for the borrows. I think it would require a small bit of
unsafecode and/or a raw pointer to simultaneously hold the table and the entry pointer, but that seems like it's likely going to be worthwhile given the ergonomic wins.
:speech_balloon: alexcrichton created PR review comment:
Could this be moved close to the definition of
Descriptor, and would it perhaps make sense to account for this with a simple constant return value of the size of an OS file/dir?
:speech_balloon: alexcrichton created PR review comment:
Similar to filesystems, could this move up closer to the definition?
(same for many other files too, I'll stop commenting here)
:speech_balloon: alexcrichton created PR review comment:
Similar to the write stream elsewhere, I think it might make sense to just assume that this is always maximally buffering (or similar-ish to that) because otherwise this can't adequately track what's happening in the background task
:speech_balloon: alexcrichton created PR review comment:
Could this comment as to why it's a
saturating_sub? Is that for mutations that don't go throughupdate?
:speech_balloon: alexcrichton created PR review comment:
Should this perhaps get deleted with byte-based tracking? The purpose of this change was to effectively be a small proxy for byte-based tracking but bytes is a much more accurate limit than total slots
:speech_balloon: alexcrichton created PR review comment:
FWIW I think we're definitely going to want to revisit this in the future, this table definitely wants to keep track of memory.
:speech_balloon: alexcrichton created PR review comment:
How come the reexport here?
:speech_balloon: alexcrichton created PR review comment:
Ah, also with RAII, this shouldn't be necessary
:speech_balloon: alexcrichton created PR review comment:
s/len/capacity/ ?
:speech_balloon: alexcrichton created PR review comment:
Could this use
#[derive]? (along with the one above too)
:speech_balloon: alexcrichton created PR review comment:
Ideally in my mind we'd account for as much as possible in this budget -- could this perhaps assume that it's always got something buffered and count for a fixed-and-large size?
:speech_balloon: alexcrichton created PR review comment:
Similar to
Response, but for other fields -- shouldn't this account for a number of other fields? For example the method/scheme/authority/path I think can all have arbitrary strings, and the strategy developed in this PR I think could subsume https://github.com/bytecodealliance/wasmtime/pull/14598 for example otherwise
:speech_balloon: alexcrichton created PR review comment:
This is a bit of a lie because concurrent mutations are allowed, but not tracked, right? In that sense would it make sense to assume that this is always at its maximal value?
:speech_balloon: alexcrichton created PR review comment:
I commented far down below about this, but by moving
updateto an RAII-style pattern it'd avoid the need for the??here which is a bit awkward
:speech_balloon: alexcrichton created PR review comment:
Similar to below in p3, I think it'd make sense to exhaustively destructor the structs here to ensure that all fields are accounted for
:speech_balloon: alexcrichton created PR review comment:
How come
bodyisn't accounted for here?
:speech_balloon: alexcrichton created PR review comment:
Similar to other locations, I think it might make sense for stdio things to assume maximal internal buffering perhaps?
:speech_balloon: alexcrichton created PR review comment:
Ah for these I think it might make sense to have this in Wasmtime itself as:
impl<T> HostHeapUsage for Box<T> where T: HostHeapUsage + ?Sized { // ... }(assuming that actually works)
:speech_balloon: alexcrichton created PR review comment:
Could this exhaustively match to avoid
_?
:speech_balloon: alexcrichton created PR review comment:
This one is preexisting, but could this, and the new trait impl below, be moved above the tests? It's a bit unidiomatic to have tests located above actual code
:speech_balloon: alexcrichton created PR review comment:
Could this grow some small documentation as to what it's doing, in particular to the
bound_all_fieldsparameter and whattype_mentions_identis doing?
:speech_balloon: alexcrichton created PR review comment:
(also, it'd probably make sense to have crate-scoped helpers which handle types from the
httpcrate to avoid duplicating it across p2/p3)
:speech_balloon: alexcrichton created PR review comment:
Or, alternatively, what's the downside to using
#[derive]for these?
:speech_balloon: alexcrichton created PR review comment:
If it makes sense to add these, and implementation trick that I think might make sense here is:
let Request { method, scheme, authority } = *self; // exhaustive match of all fields // ... add up for each field matched ...so that way we get compiler warnings on missed fields and compiler errors if a field is ever added
:speech_balloon: alexcrichton created PR review comment:
Would it make sense to charge something nonzero for this, say maybe 4KiB, as a placeholder?
:speech_balloon: alexcrichton created PR review comment:
Could this use the
#[derive]?
:memo: posborne submitted PR review.
:speech_balloon: posborne created PR review comment:
Yeah, that sounds reasonable.
:memo: posborne submitted PR review.
:speech_balloon: posborne created PR review comment:
Possibly; my only hesitation was related to conflicting with mechanisms that may have already been tuned by embedders; that being said, I do think simplifying would be better and the byte tracking is easier to reason about and probably the right control. Embedders will, most likely, already be bumping into breakages from the new trait requirements (unless not adding any of their own hostcalls/resources) so this isn't really a huge lift on top of that.
:memo: posborne submitted PR review.
:speech_balloon: posborne created PR review comment:
I can add a comment; the reasoning is basically that, it isn't possibly to guarantee that in all cases the tracking could never get off in some way with out of band mutations. Saturating rather than underflow seemed like the more pragmatic and safe option here; bubbling up an error that will guest-trap could be another option but that feels heavy-handed.
:memo: posborne submitted PR review.
:speech_balloon: posborne created PR review comment:
This is the approach I originally wanted to go; the problem with that is that when limits are exceeded the behavior we want is to raise an error that will result in a guest trap rather than a host trap. So
Dropisn't a great option there unless there's a trick I haven't thought through.Having a
finish()consuming self explicitly can make that explicit but doesn't statically avoid theDropand when I had used it in a few places, it generally didn't make things easier to write, so I ended up consolidating on the closure-based approach instead for this case.
:memo: posborne submitted PR review.
:speech_balloon: posborne created PR review comment:
I agree; I wasn't too happy to leave these and should have had a comment as to why they were omitted. The reason isn't the best, but it's basically that I had trouble thinking through exactly how we'd track these in all cases. There are some other specific protections here, but having it not included in the umbrella isn't ideal.
There is tracking taking place, even for FixedHostHeapUsage, but it is just the size of the struct itself without following the boxed types, so it is better than nothing and would catch the most naive runaway usage attempts.
The other bad thing here is that since this table is internal, I don't think embedders will often be aware that this extra table even exists and is performing host allocations. It might not even be possible to get a reference to the table to set a limit on it as an embedder (though I would need to double check that). That's probably best solved by wiring up the limits to coalesce at a higher level.
:memo: posborne submitted PR review.
:speech_balloon: posborne created PR review comment:
I would have liked to have an impl for
Box<T>and attempted it. ABox<T> where T: HostHeapUsage + ?Sizedimpl conflicts withimpl<T: FixedHostHeapUsage> HostHeapUsage for T { ... }because
Boxis#[fundamental], so a downstream crate could implementFixedHostHeapUsage for Box<MyType>and overlap with it (E0119).The way to get a generic Box<T> is to drop that blanket impl, so fixed types would need an explicit
HostHeapUsageimpl alongsideFixedHostHeapUsage.#[derive(FixedHostHeapUsage)]can emit both, so derived types are unaffected. The hand-writtenimpl FixedHostHeapUsage for X {}sites would need a second impl, which a small helper macro could cover (e.g.impl_fixed_host_heap_usage!(MyType)).Honestly, I wasn't quite sure which direction to go with this one, so happy to hear any suggestion you might have.
:speech_balloon: posborne created PR review comment:
Yeah, we can make it work by giving it the extra attribute required for bits that are within the wasmtime crate itself.
#[derive(FixedHostHeapUsage)] #[component(wasmtime_crate = crate)] struct TaskGroup { ref_count: usize, }Some of these sites were ones that I had written prior to adding the proc-macro; I can probably just do a conversion of to use the proc-macro for all sites where it can be applied. That gives us a bit more confidence that those impls are safe which makes auditing easier.
:memo: posborne submitted PR review.
:memo: posborne submitted PR review.
:speech_balloon: posborne created PR review comment:
This one should be possible but isn't as the type is generated by wit-bindgen. Having bindgen types impl the trait might be possible, but I didn't want to touch it in this change and I'm not sure how often it will be encountered in practice.
:memo: posborne submitted PR review.
:speech_balloon: posborne created PR review comment:
Yeah, that suggestion makes sense to me; I'll make that update.
:memo: posborne submitted PR review.
:speech_balloon: posborne created PR review comment:
Yeah, I think that makes sense here (and for other buffered streams).
:speech_balloon: posborne created PR review comment:
Agreed.
:memo: posborne submitted PR review.
:memo: alexcrichton submitted PR review.
:speech_balloon: alexcrichton created PR review comment:
Yeah that's my thinking as well, it's breaking to remove this but I'd like to ideally keep knobs relatively simple. We've got a ton of performance tuning knobs but ideally the knobs for "don't DoS yourself" are pretty simple to set.
:memo: alexcrichton submitted PR review.
:speech_balloon: alexcrichton created PR review comment:
Oh right sorry yes I remember now that was in the OP and forgot about that when re-reading this. That's a good point too!
Subjectively I place a high value on preventing rightward-drift and using RAII wherever possible, so I'm tempted nevertheless to push on this. What would you think about something like:
- An explicit
finishwhich returnsResult- Changing
Dropto flag a table as "over capacity" to yield an error on next-accessThat way embedders can get eager traps if they want, but otherwise natural access of the table would still handle this error case at least eventually. My thinking is that
updateis already sort of catching a sin that's already been committed as opposed to preventing it from happening in the first place, so delaying that error a bit longer probably isn't the worst in the world.
:memo: alexcrichton submitted PR review.
:speech_balloon: alexcrichton created PR review comment:
Oh wow TIL.
One possibly crazy idea -- entirely remove
FixedHostHeapUsage. I think the primary motivation for that isResourceTable::get_mutwhich doesn't return an RAII thing, but if you agree with what I'm thinking above we could switch it to RAII which might remove the motivation for the fixed trait entirely.
:memo: alexcrichton submitted PR review.
:speech_balloon: alexcrichton created PR review comment:
Table-wise we definitely need to improve where the table is located yeah, and ideally reuse this table for probably everything (e.g. WASI resources and such). We do have an accessor though for the sole reason of being able to set the maximum capacity
:memo: alexcrichton submitted PR review.
:speech_balloon: alexcrichton created PR review comment:
Oh right yes I saw the definition wasn't in bindgen and naively assumed the derive could be used but the first field is indeed bindgen-generated. I think it's fine to leave this as-is in that case and can always handle the
bindgen!bits later.
:speech_balloon: posborne created PR review comment:
Yeah, that's probably the safer option here which we should take. We might just want to bolster our wording around what the heap number represents, but I think that's the right approach given that the important here is to guard against DoS.
:memo: posborne submitted PR review.
:memo: posborne submitted PR review.
:speech_balloon: posborne created PR review comment:
Yeah, I think that makes sense. 4KiB is generous but not problematically so for realistic usages.
:memo: posborne submitted PR review.
:speech_balloon: posborne created PR review comment:
Yeah, this shouldn't be here. I had some back and forth with some of the wasi-io traits having or not having trait dependencies on these core traits which must have left this stray; definitely doesn't make sense to be here.
:memo: posborne submitted PR review.
:speech_balloon: posborne created PR review comment:
The comments here on
Request,Responsemake sense. I'll have to play around with things and think a bit more on the approach but will push a commit with changes to try to handle this following the general convervative-upper-bound approach being added elsewhere.Will try to share between p2/p3 for how we handle tracking for the http types. That will probably come in after the base changes around the core trait(s).
xia-chao commented on PR #15101:
While investigating wasi-http fields memory I found that with current defaults, 25k fields × 120 KiB in a 3 GiB cgroup gets OOM-killed (rc=137). This PR adds the API; do you plan a CLI default too?
:memo: posborne submitted PR review.
:speech_balloon: posborne created PR review comment:
I'm trialing a version of the change that goes this direction (single trait and RAII access patterns). I _think_ it will work and we can trap at the right places, though I need to play with a few options there: at the head of future subsequent mutating access blocks is the obvious instrumentation point (which we already have in some places), but I think there may also be a way to do the check at the point we're about to re-enter guests; that would mean that we trap without having to make another subsequent hostcall, which seems like what you would want. We'll lose a little visibility into which table change pushed things over the limit, but I generally expect that this will either be unimportant or obvious from context (and solvable if we decide it matters).
This should allow for most of the table accesses to go back to the upstream form which should make review a bit easier.
alexcrichton commented on PR #15101:
Yeah this'll definitely be reflected in the CLI, either here or in a follow-up.
:memo: posborne submitted PR review.
:speech_balloon: posborne created PR review comment:
I'll go through and resolve comments once I have changed vetted and on the branch, but I am moving toward making it so that we can apply the proc-macro (over the single
HostHeapUsagetrait) in almost all cases.The macro will have attributes for the common cases we seem to encounter, currently thinking something like these:
fn dynamic_size(field: &MyType) -> usize { // ... 42 } struct MyStruct { #[heap_usage(shared)] shared: Arc<SomeType>, // where SomeType: HostHeapUsage. Will include the size of SomeType for this field. #[heap_usage(constant = 42)] fixed_opaque: OpaqueFixed, // some type that we can account for with a fixed value (expr) #[heap_usage(skip = "reason skipping is reasonable")] zero_size: Opaque, #[heap_usage(with = dynamic_size)] dynamic: MyType, // MyType doesn't/can't impl HostHeapUsage }
:speech_balloon: posborne edited PR review comment.
:memo: alexcrichton submitted PR review.
:speech_balloon: alexcrichton created PR review comment:
Nice! That looks great to me!
Last updated: Nov 19 2026 at 20:05 UTC