Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/` ->
Expand Down
2 changes: 1 addition & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -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
Expand Down
4 changes: 2 additions & 2 deletions docs/_extra/playground/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -439,8 +439,8 @@ <h1>pyjs canvas playground</h1>
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");
Expand Down
31 changes: 27 additions & 4 deletions docs/npm.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,27 @@ accepts both, specs and pinned packages.
of the python environment are kept too (`<cache name>-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
Expand Down Expand Up @@ -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()`) |
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion npm/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()`) |
Expand Down
22 changes: 12 additions & 10 deletions npm/src/bytecode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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") {
Expand Down
10 changes: 6 additions & 4 deletions npm/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,11 @@ export interface PyjsModule {
addFiles(files: IFile[]): Promise<void>;

/**
* 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<void>;

Expand Down Expand Up @@ -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 ("<cache name>-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) */
Expand Down
Loading