pyodide
pyodide copied to clipboard
Allow capping WASM heap growth per `loadPyodide()` instance
🚀 Feature
A loadPyodide option, for example maxMemoryBytes (name open to discussion), that caps growth of the WebAssembly memory for that instance.
Motivation
We run user-authored Python in Pyodide on Node, one interpreter per execution, and need a hard per-interpreter memory ceiling so a runaway script gets a MemoryError instead of growing the host process.
Pyodide 314.0.7 links with ALLOW_MEMORY_GROWTH=1 and MAXIMUM_MEMORY=4GB (Makefile.envs), and loadPyodide() has no option to choose a lower ceiling at load time. Related: #1513 (abort(out of memory)).
Pitch
- Unset by default, and then nothing changes.
- A value above the build-time maximum is clamped or rejected.
- Exceeding the cap fails like any other out-of-memory, as a
MemoryErrorwhere Python can surface it. The instance stays usable afterwards.
Alternatives
- Rebuild Pyodide with a lower
MAXIMUM_MEMORY. The limit is then fixed per build, not per instance. - Patch the generated glue. This is what we do today. We replace
getHeapMax=()=>4294901760withgetHeapMax=()=>Math.min(globalThis.__CA_WASM_HEAP_MAX__||4294901760,4294901760)and check the patched file's digest. With a 128 MiB cap,bytearray(512 * 1024 * 1024)raises a normal PythonMemoryErrorand the same interpreter keeps working. It works, but it's a string rewrite of generated code that has to be re-verified on every release.
Additional context
We'd drop our patch if this existed, and can send a PR if the approach is acceptable. Pyodide 314.0.7, Node, Linux amd64/arm64.