diff --git a/CLAUDE.md b/CLAUDE.md
index e243d73..803ff1d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -305,8 +305,10 @@ like synchronous JS errors; pyodide compatible: `.name` / `.message`, e.g.
`verifySha256` + sha256); bytecode cache (`bytecode.ts`,
`pyjs-packages-v2-bytecode`, by package / env tarball URL): the `.pyc`
files of each package's `.py` files (`Module._tar_files`), restored with
- the package, saved when `__pycache__` entry counts grow (3 s interval,
- page hidden, `Module.saveBytecode()`). Valid because the extraction keeps
+ the package, saved (units whose `__pycache__` entry counts grew) only on
+ `Module.saveBytecode()` and, best effort, on `visibilitychange` -> hidden
+ (main thread): no interval since 5.2 (periodic readdirs of every
+ `__pycache__` = unpredictable cost). Valid because the extraction keeps
the archive mtimes (`set_mtime`) and `relocate` restores them (python
checks a `.pyc` against source mtime + size); then extraction in order
env tarballs -> packages (`install.ts`: conda layout, `site-packages/` ->
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 78423cb..799dc8d 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 4.0)
-project(pyjs VERSION 5.1.0 DESCRIPTION "pyjs")
+project(pyjs VERSION 5.2.0 DESCRIPTION "pyjs")
# cmake module directory
diff --git a/docs/_extra/playground/index.html b/docs/_extra/playground/index.html
index 6210776..98cbd19 100644
--- a/docs/_extra/playground/index.html
+++ b/docs/_extra/playground/index.html
@@ -439,8 +439,8 @@
pyjs canvas playground
await pyjs.async_exec_eval(editorApi.get());
// (imports included: fast when their bytecode came from the cache)
if (myRun === runId) status(`done in ${((performance.now() - t0) / 1000).toFixed(2)} s`);
- // keep the bytecode of this run's imports for the next visit (also automatic)
- pyjs.saveBytecode();
+ // keep the bytecode of this run's imports for the next visit
+ await pyjs.saveBytecode();
} catch (e) {
write(pyErrorText(e), true);
status("error");
diff --git a/docs/npm.md b/docs/npm.md
index e797b44..1d27be6 100644
--- a/docs/npm.md
+++ b/docs/npm.md
@@ -97,11 +97,27 @@ accepts both, specs and pinned packages.
of the python environment are kept too (`-bytecode`, by package
URL) and come back with the package, so imports do not compile the sources
again (the imports above: 2.2 s -> 0.5 s, python's start 0.36 s -> 0.09 s).
- They are saved when there are new ones (checked every few seconds and when
- the page is hidden) or right away with `await pyjs.saveBytecode()`.
+ **Saving is up to the app:** call `await pyjs.saveBytecode()` once the
+ imports are done (it stores only what python wrote since the last save;
+ await it before a reload). Nothing saves periodically; the only automatic
+ save is a best-effort one when the page becomes hidden (main thread only: a
+ closing page may be gone before the write completes; workers must call
+ `saveBytecode()` themselves).
+
+ ```js
+ pyjs.exec("import numpy, scipy.linalg");
+ await pyjs.saveBytecode();
+ ```
+
+ Restoring is automatic (with the package).
Python checks each `.pyc` against the modification time + size of its
source (kept from the archive), a stale one is compiled again.
- `bytecodeCache: false` turns it off.
+ `bytecodeCache: false` turns it off. So does python itself when it writes
+ no bytecode: `sys.dont_write_bytecode = True` / `PYTHONDONTWRITEBYTECODE`
+ (also `PYTHONPYCACHEPREFIX` moves the files out of reach). Code edited at
+ runtime needs neither: delete the edited files' `.pyc` before re-importing
+ (`importlib.util.cache_from_source(path)`), python also recompiles when the
+ source's mtime or size changed.
* **Archives** are not cached by default (an archive URL may change its
content). `{url, path, cache: true}` caches one like a package: its
unpacked files and the bytecode of its `.py` files, by URL + `path`. Only
@@ -179,7 +195,7 @@ JavaScript modules, so bundlers do not copy them; two ways to deploy them:
| `files` | `[]` | files (`{path, data}` or `{path, url}`) written before Python starts |
| `channels` | emscripten-forge 6x, conda-forge | channels the specs are solved against (also self-hosted ones, see below) |
| `cache` | `true` | package cache in Cache Storage (`false`, or a cache name) |
-| `bytecodeCache` | `true` (with `cache`) | keep python's `.pyc` files of the packages for the next visit |
+| `bytecodeCache` | `true` (with `cache`) | keep python's `.pyc` files of the packages for the next visit (saved by `saveBytecode()`) |
| `verifySha256` | `false` | check the sha256 of packages / archives that have one |
| `onProgress` | | progress events (see above) |
| `wasmModule` | | the runtime wasm compiled already (`compileRuntime()`) |
@@ -244,6 +260,13 @@ more than 4 GB of memory (pyjs is linked with up to 16 GB) but needs a
browser with memory64 support. Extra packages are taken from the matching
channel subdir (`emscripten-wasm32` / `emscripten-wasm64`).
+## Changes in 5.2
+
+* The bytecode cache no longer saves every few seconds (that listed every
+ `__pycache__` directory periodically, an unpredictable cost): it saves on
+ `await pyjs.saveBytecode()` (call it once the imports are done) and, best
+ effort, when the page becomes hidden.
+
## Changes in 5.1
* Archives can be cached like packages: `{url, path, cache: true}` (unpacked
diff --git a/npm/README.md b/npm/README.md
index 3ff74c5..c6aebee 100644
--- a/npm/README.md
+++ b/npm/README.md
@@ -69,7 +69,7 @@ The returned object is the pyjs runtime (the emscripten `Module`): `exec`,
| `files` | `[]` | files (`{path, data}` / `{path, url}`) written before python starts |
| `channels` | emscripten-forge 6x, conda-forge | channels the specs are solved against |
| `cache` | `true` | package cache in Cache Storage (`false`, or a cache name) |
-| `bytecodeCache` | `true` (with `cache`) | keep python's `.pyc` files of the packages for the next visit |
+| `bytecodeCache` | `true` (with `cache`) | keep python's `.pyc` files of the packages for the next visit (saved by `await pyjs.saveBytecode()`) |
| `verifySha256` | `false` | check sha256 values where given |
| `onProgress` | | `{item, phase, done, total}`: solve / download / cached / extract / link / start |
| `wasmModule` | | the runtime compiled already (`compileRuntime()`) |
diff --git a/npm/src/bytecode.ts b/npm/src/bytecode.ts
index b6991bb..d192615 100644
--- a/npm/src/bytecode.ts
+++ b/npm/src/bytecode.ts
@@ -4,16 +4,16 @@
* URL and restored with the package on the next visit, so imports load
* bytecode instead of compiling the sources again.
*
- * Python writes the files at import time; they are saved when there are new
- * ones (checked every few seconds, and when the page is hidden) or on
- * `Module.saveBytecode()`. Python validates every cache file against the
- * modification time + size of its source, which the extraction keeps from the
- * archive: a stale or foreign file is recompiled, never used.
+ * Python writes the files at import time; they are saved on
+ * `Module.saveBytecode()` (the app calls it, e.g. once after its imports) and,
+ * best effort, when the page becomes hidden (main thread only: a closing page
+ * may be gone before the async write completes). Nothing runs periodically.
+ * Python validates every cache file against the modification time + size of
+ * its source, which the extraction keeps from the archive: a stale or foreign
+ * file is recompiled, never used.
*/
import { bytecodeFiles } from "./install";
-const CHECK_INTERVAL_MS = 3000;
-
/** a unit of the bytecode cache: one package (or env tarball) */
interface IUnit {
url: string;
@@ -96,10 +96,12 @@ export class BytecodeCache {
return this.saving;
}
- /** save automatically: every few seconds when there is something new, and when the page is hidden */
+ /**
+ * save when the page becomes hidden (tab switch, minimize, navigation,
+ * close; best effort). Event driven, no periodic work; workers have no
+ * such event (there only `saveBytecode()` saves)
+ */
watch(): void {
- const timer: any = setInterval(() => this.save(), CHECK_INTERVAL_MS);
- timer?.unref?.(); // (node: does not keep the process alive)
const doc = (globalThis as any).document;
doc?.addEventListener?.("visibilitychange", () => {
if (doc.visibilityState === "hidden") {
diff --git a/npm/src/types.ts b/npm/src/types.ts
index df46429..0dfaaef 100644
--- a/npm/src/types.ts
+++ b/npm/src/types.ts
@@ -137,9 +137,11 @@ export interface PyjsModule {
addFiles(files: IFile[]): Promise;
/**
- * save new bytecode of the packages to the bytecode cache now (also done
- * automatically every few seconds and when the page is hidden); a no-op
- * without the cache
+ * save the bytecode python wrote since the last save (packages, the python
+ * environment, archives with `cache: true`) to the bytecode cache. Call it
+ * once the imports are done (await it before a reload). Besides, it is only
+ * tried when the page becomes hidden (best effort, main thread only):
+ * nothing saves periodically. A no-op without the cache
*/
saveBytecode(): Promise;
@@ -225,7 +227,7 @@ export interface IInitializeOptions extends IAssetsOptions {
* keep python's bytecode (`__pycache__/*.pyc`) of the packages and the
* python environment in Cache Storage ("-bytecode"), so imports
* on the next visit do not compile the sources again (default: true when
- * `cache` is on); saved automatically, see `PyjsModule.saveBytecode`
+ * `cache` is on); restored automatically, saved by `PyjsModule.saveBytecode`
*/
bytecodeCache?: boolean;
/** check the sha256 of packages / archives that have one (default: false) */