Pyodide memory snapshots (Python kernel)
⚠️ Major point of attention. This mechanism relies on Pyodide's private internals (undocumented, likely to change with each version). At each Pyodide upgrade, it must be checked again entirely (see the procedure). For safety, it disables itself for any Pyodide version other than
SNAPSHOT_CHECKED_PYODIDE_VERSION(packages/kernel-python3/src/worker.ts).⚠️ Snapshots are stored in IndexedDB from one visit to the next: a snapshot must never be reused with another build of Pyodide (see the key). Increment
SNAPSHOT_FORMATas soon as what is done before the snapshot, after its restoration or the way it is stored changes. Never replace the files of a published Pyodide version at the same path (cdn.basthon.fr, local copies).
Goal
Speed up the Python kernel's start: the restarts (the console's reset button, the notebook's kernel restart), which each create a new worker and initialize Pyodide again, and the first start of the next visits. With a snapshot of Pyodide's memory taken right after it is loaded, Python's initialization is skipped.
Measures in production conditions (isolated kernel, without cross-origin isolation, Pyodide 0.26.4, lightly loaded machine): loadPyodide goes from ~2.3 s to ~0.3 to 0.4 s. The rest of the start (loadPackage("basthon"), import basthon) is done again each time:
- restart: ~0.9 s instead of ~2.4 s;
- next visit (snapshot read from IndexedDB): kernel ready ~0.95 s after the start of the navigation, instead of ~2.3 to 2.4 s;
- the very first visit is not sped up.
Choice: a snapshot of Pyodide alone, before Basthon
The snapshot is taken right after loadPyodide, before anything else (lockfile, import basthon, patches, kernel start). Basthon is therefore imported again at each start (with loadPackage, a few hundred milliseconds), but this guarantees that:
- nothing of Basthon is frozen in the snapshot: files written at import (the filesystem is not in the snapshot), values read at import (
syncCommSupport, version...), state of the random generators imported by Basthon; - the snapshot only depends on Pyodide's build (useful to store it, see below);
- Python doesn't reference any JS object yet besides those Pyodide expects: Pyodide's
_makeSnapshotmode is not needed (it wraps all the JS globals in Proxies for the whole session, which breaks the objects given to native APIs such aspostMessage).
A first version took the snapshot after import basthon. It was more fragile (JS references wrapped for the time of the snapshot, site-packages files lost at restoration) for ~0.5 s more.
How it works
A Pyodide snapshot holds a copy of the WebAssembly memory (~20 MB with Pyodide 0.26.4) and the list of the JS objects referenced from Python. It doesn't hold the virtual filesystem, Pyodide's JS state (loadedPackages, lockfile) nor the dynamically loaded C libraries.
First start (Python3KernelWorker._init)
- Pyodide is loaded normally (without the
_makeSnapshotoption). makePyodideSnapshot()sets the private flag_api.config._makeSnapshotfor the time of themakeMemorySnapshot()call (finally). If anything fails: no snapshot (a warning in the worker's console), the kernel works normally.- Usual sequel: lockfile,
loadPackage("basthon"), kernel start. - The main thread (
Python3Kernel._start) gets the snapshot at the end of the initialization, before any evaluation, and keeps it in memory.
Restart
Python3Kernel.workerOptions()adds the snapshot to the new worker's options (copied, the main thread keeps its own).- The worker restores Pyodide (
loadPyodide({ _loadSnapshot })), seedsrandomagain if Pyodide imported it (for safety), then follows the usual path (lockfile,loadPackage("basthon")...). - If the restoration fails, normal loading (and a new snapshot).
The legacy mode (kernel in the main thread) doesn't use snapshots: its restart is already lazy.
Storage from one visit to the next (snapshot-store.ts)
- The snapshot is stored raw (~20 MB) in IndexedDB, on the main thread's side, in the page's origin (database
basthon-python3, storepyodide-snapshot, a single recordsnapshot={ key, data }). A new snapshot replaces the old one. The worker has no access to it (opaque origin). - No compression: gzip (
CompressionStream) reduces it to ~5 MB but takes ~1 s to compress and ~250 ms to decompress, while reading the raw record takes ~40 ms (writing ~90 ms). Zero pages are only ~37 % of the snapshot. Python3Kernelreads the record as soon as it is created (while the page loads) and gives it to the worker at the first start.- After the start, it writes in the background the new snapshot made by the worker (first visit, different key or failed restoration), or deletes the record if it was rejected without being replaced. If the page is left before the end of the writing, the snapshot is simply made again at the next visit.
- Any error (IndexedDB unavailable, quota...) is ignored with a warning: normal start.
- Kernel option
pyodideSnapshotCache: false: no storage (restarts are still sped up). - To empty the cache by hand: the browser's developer tools, IndexedDB storage, database
basthon-python3.
The key of a snapshot
Pyodide 0.26.4 checks nothing at restoration (its snapshot "BUILD_ID" is a constant). The worker computes the key (snapshotKey) and only restores if it is identical:
SNAPSHOT_FORMAT: version of the mechanism, to increment at each change of what is done before the snapshot, after its restoration or of the way it is stored;- Pyodide's version;
- Basthon's version: a safety net if
SNAPSHOT_FORMATis not incremented (the snapshot is made again once per release). In development, it is always0.0.0: incrementSNAPSHOT_FORMATor empty the cache then; - the URL of the
pyodide.jsactually used (local copy, cdn.basthon.fr, jsDelivr or URLs given as an option): it holds Pyodide's version and tells apart builds that could differ.
The content is not checked: corrupted data is detected if its header is invalid ("invalid magic number", then normal loading and a new snapshot), not beyond.
Trust
A snapshot is only written if it comes from a new worker, before any evaluation (Python3Kernel._start). The students' code runs in the sandboxed worker and has no access to IndexedDB: a malicious notebook can't install a trapped snapshot. A script of the page's origin could change the record, but it could already do much worse.
Pyodide's private internals used
| Internal | Use |
|---|---|
_api.config._makeSnapshot | flag set for the time of the snapshot |
makeMemorySnapshot(), _loadSnapshot option | making and restoring |
| JS references "expected" by the snapshot | no other one must exist right after loadPyodide |
loadedPackages checked by the snapshot | no package must be loaded before the snapshot |
On each Pyodide upgrade
- Read again in
pyodide.asm.js:makeSnapshot(check of the JS references and ofloadedPackages),restoreSnapshot, the resynchronization of the JS references at restoration, the handling of_makeSnapshotinfinalizeBootstrap. - Check that the snapshot freezes nothing that must change from one session to the next (modules imported by Pyodide at start, random seeds...).
- Run the automatic tests
tests/python3_70_snapshots.test.ts(restarts,random, user modules, IndexedDB, outdated key, legacy mode), then test by hand withtests/test.html(browser bundle) in production conditions: isolated kernel, without COOP/COEP headers:- the snapshot is made (
kernel._pyodideSnapshot, no "Can't make Pyodide's snapshot" warning in the worker's console); - several quick restarts, a different
random.random()each time; input(), numpy, pandas, matplotlib, turtle andjs.basthonafter restoration;- after reloading the page: start from IndexedDB, and a snapshot with a different key ignored then replaced.
- the snapshot is made (
- Only then, update
SNAPSHOT_CHECKED_PYODIDE_VERSION(the key changes with Pyodide's version: snapshots stored with the old version are ignored then replaced).