-
Notifications
You must be signed in to change notification settings - Fork 38
Should finalizers be able to hint how much memory may be freed when they run? #87
Description
WebAssembly is a key use case for finalizers. In a system with WebAssembly and JavaScript, the total memory consumption can be approximately said to be the JS heap plus the WebAssembly heap.
Some objects in the JS heap will have finalizers which will release memory in the WebAssembly heap. One goal for the combined system is to keep total memory consumption under control, which means periodically "running GC". Generally speaking, the more JS allocates, the more the JS garbage collector runs. If JS isn't allocating much it's not worth it to run GC, so engines will put it off for a while.
However, the issue is that the GC only sees the JS allocation rate when it's making decisions. It would be nice if a library author could give a hint to the GC that e.g. a small JS allocation rate goes along with a large off-heap allocation rate, and thus that a sooner GC might be useful.
Examples of APIs of this kind:
- https://searchfox.org/mozilla-central/source/js/src/gc/GCRuntime.h#351-370
- https://chromium.googlesource.com/v8/v8.git/+/refs/heads/master/src/api.cc#7926 (not quite the same as V8 uses malloc less than SM and embedder has to keep limit)
- https://www.gnu.org/software/guile/docs/master/guile.html/Memory-Blocks.html#index-scm_005fgc_005fregister_005fallocation
Example user problems when such an API is not present:
- Memory leak with sequences emcconville/wand#300 (users having problems with python not finalizing often enough, small GC objects protecting large off-GC data)
For me, the right API here is not something that attempts to precisely measure the WebAssembly heap size, but rather something that attempts to measure off-heap allocation rate. So, like another argument to FinalizationGroup.prototype.register or something that takes a number of bytes as a parameter, as in Guile's API. I would not have a corresponding registerFree thing as it's too complicated and error-prone. Anyway, this issue is to determine if such an API is desired in the weakrefs spec, and if it is desired by engine maintainers.
NB I am not an expert GC implementor, so corrections (e.g. "lol this is not needed") are very welcome :)