From 288897879e84107ea14f0dcb10174c749a885c39 Mon Sep 17 00:00:00 2001 From: DerThorsten Date: Wed, 18 Nov 2026 08:59:19 +0100 Subject: [PATCH 1/5] pyjs 5: new initialization (libarchive extraction, pinned installs, caches, progress) - core: Module.startPython() (synchronous) on a file system filled by the embedder; the classic bootstrap (load_pkg.js, untar / inflate / install_conda_file, dynload, init_phase_*) is removed - runtime: Module._extract_archive (libarchive: tar / zip, gzip / bzip2 / zstd, .conda / .tar.bz2, safe paths, archive mtimes kept) and Module._tar_files - npm: own init pipeline (runtime, solve, downloads in parallel), pinned urls, archives, files, sha256 only on request, progress events, compileRuntime / wasmModule, shared libs loaded after the start, npx lock - caches: installed packages as their final layout (pyjs-packages-v2) and python's bytecode per package (pyjs-packages-v2-bytecode); initTimings / installTimings - tests focus on the npm package (vanilla page removed); docs and playground updated (progress bar, timings) Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 101 ++- CMakeLists.txt | 22 +- build_local.sh | 80 ++- docs/_extra/playground/index.html | 115 +++- docs/cdn.md | 8 +- docs/cpp.md | 72 ++- docs/development.md | 23 +- docs/npm.md | 138 +++- environment-host.yml | 4 + include/pyjs/inflate.hpp | 10 - include/pyjs/install_conda_file.hpp | 12 - include/pyjs/pre_js/dynload/LICENCE | 0 include/pyjs/pre_js/dynload/README.md | 2 - include/pyjs/pre_js/dynload/dynload.js | 108 ---- include/pyjs/pre_js/fetch.js | 125 ---- include/pyjs/pre_js/init.js | 96 ++- include/pyjs/pre_js/load_pkg.js | 305 --------- include/pyjs/pre_js/wait_for_dependencies.js | 12 - include/pyjs/untar.hpp | 10 - npm/README.md | 35 +- npm/bin/pyjs.mjs | 104 ++- npm/build.mjs | 41 +- npm/package-lock.json | 1 - npm/package.json | 1 - npm/src/bytecode.ts | 115 ++++ npm/src/fetch.ts | 157 +++++ npm/src/install.ts | 169 +++++ npm/src/lock.ts | 45 ++ npm/src/runtime.ts | 633 +++++++++++-------- npm/src/sharedlibs.ts | 43 ++ npm/src/solve.ts | 112 ++++ npm/src/types.ts | 202 ++++-- npm/src/wasm32.ts | 14 +- npm/src/wasm64.ts | 14 +- npm/tsconfig.json | 4 +- pyjs_test_driver/__init__.py | 2 +- pyjs_test_driver/__main__.py | 7 +- pyjs_test_driver/pages.py | 13 +- pyjs_test_driver/test_channel.py | 73 ++- pyjs_test_driver/web/bundler_main.js | 5 +- pyjs_test_driver/web/harness.js | 2 +- pyjs_test_driver/web/npm_page.js | 13 +- pyjs_test_driver/web/vanilla_page.js | 29 - src/export_js_module.cpp | 13 +- src/extract.cpp | 633 +++++++++++++++++++ src/inflate.cpp | 31 - src/install_conda_file.cpp | 175 ----- src/untar.cpp | 322 ---------- tests/npm/test_channel.py | 3 +- tests/npm/test_install.py | 193 ++++++ tests/sync/test_extract.py | 286 +++++++++ 51 files changed, 3016 insertions(+), 1717 deletions(-) delete mode 100644 include/pyjs/inflate.hpp delete mode 100644 include/pyjs/install_conda_file.hpp delete mode 100644 include/pyjs/pre_js/dynload/LICENCE delete mode 100644 include/pyjs/pre_js/dynload/README.md delete mode 100644 include/pyjs/pre_js/dynload/dynload.js delete mode 100644 include/pyjs/pre_js/fetch.js delete mode 100644 include/pyjs/pre_js/load_pkg.js delete mode 100644 include/pyjs/pre_js/wait_for_dependencies.js delete mode 100644 include/pyjs/untar.hpp create mode 100644 npm/src/bytecode.ts create mode 100644 npm/src/fetch.ts create mode 100644 npm/src/install.ts create mode 100644 npm/src/lock.ts create mode 100644 npm/src/sharedlibs.ts create mode 100644 npm/src/solve.ts delete mode 100644 pyjs_test_driver/web/vanilla_page.js create mode 100644 src/extract.cpp delete mode 100644 src/inflate.cpp delete mode 100644 src/install_conda_file.cpp delete mode 100644 src/untar.cpp create mode 100644 tests/npm/test_install.py create mode 100644 tests/sync/test_extract.py diff --git a/CLAUDE.md b/CLAUDE.md index e35f55e..27f7bf7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -39,8 +39,7 @@ Everything lives in `build_root/` (gitignored, never commit): | dir | env file | | |---|---|---| | `dev_prefix` | `environment-dev.yml` | native, **one for wasm32 + wasm64**: `emscripten-core`, cmake, empack, node, playwright (+ playwright-python), sphinx | -| `host_prefix_` | `environment-host.yml` | emscripten env pyjs is built against + installed into | -| `test_env__` | none: `PYTHON_PACKAGES` + `TEST_PACKAGES` in build_local.sh | env of the vanilla test page (`` = `TEST_ENV`: `default` / `no_numpy`) | +| `host_prefix_` | `environment-host.yml` | emscripten env pyjs is built against + installed into (incl. `libarchive-static` for `src/extract.cpp`) | | `npm_env_` | none: `PYTHON_PACKAGES` | `npm`: the env shipped in the package (python only) | | `build_` | | cmake build dir | | `pages/` | | test pages (`pyjs_test_driver build-page`), `pages/bundler_projects/` the bundler apps | @@ -82,9 +81,13 @@ passes a pointer above that to JS (on wasm32 one object must be < 2 GiB: ### Gotchas in build_local.sh - Structure (top to bottom): command line, settings, helpers, dev env (activated once), one architecture (`use_arch`, `build_pyjs`, - `pack_runtime`, `build_vanilla_page`, `run_tests`), npm - (`build_npm_package`, `test_npm_package`), the `cmd_*` commands. `npm` / - `docs` loop over `ARCHS` in one process. Must stay readable by humans. + `pack_runtime`, `run_tests`), npm (`build_npm_package`, `build_npm_page`, + `test_npm_package`), the `cmd_*` commands. `npm` / `docs` loop over `ARCHS` + in one process; `test` / `bench` set `ARCHS=`. Must stay readable by + humans. +- The host env is only created when missing: after a change of + `environment-host.yml` delete `build_root/host_prefix_` (micromamba + `install` into it fails: it runs the emscripten python for pip interop). - One dev env for both architectures: it has `emscripten-core`, not `emscripten_emscripten-wasm32` / `-wasm64` (those only depend on emscripten-core and, for wasm64, add `-m64` in their activation). @@ -135,10 +138,11 @@ passes a pointer above that to JS (on wasm32 one object must be < 2 GiB: sets `globalThis.pyjs`, awaits `main(options)`), sets `window.__pyjs_result`; worker mode: `worker.js`, console + result relayed via postMessage. -- Page kinds: `vanilla` (raw `pyjs_runtime_browser.js` via indirect eval + - `bootstrap_from_empack_packed_environment` with the empack-packed - test env: the classic API xeus-python uses), `npm` (the package, - `TEST_PACKAGES` via `extraPackages` / mambajs, network), `vite` / `webpack` +- Only npm-based pages (pyjs 5: the vanilla page is gone; `test ` + builds the npm package of that arch). Page kinds: `npm` (the package, + `TEST_PACKAGES` via `packages` (solved), a test-channel package via `urls` + (pinned), `archives`, `files`, `onProgress` recorded in + `globalThis.__pyjs_progress`; network), `vite` / `webpack` / `rollup` / `esbuild` / `parcel` (bundled app around `web/bundler_main.js`, runtime files via `copy-assets` + `cdnUrl`, main thread only, built with `CI=true`). @@ -266,45 +270,74 @@ like synchronous JS errors; pyodide compatible: `.name` / `.message`, e.g. the solver from replacing the running python) -> `build_root/npm/stage//`; then `build_root/npm/package/` + `npm pack` -> `build_root/npm/*.tgz`. `ARCHS=wasm32` (local only), `NPM_TEST_BUNDLERS=0`. -- Init (`runtime.ts`) = the jupyterlite-xeus path via mambajs-core: - `createModule` (`assets//pyjs_runtime_browser.mjs` = the classic - MODULARIZE js + `export default createModule`, located via - `import.meta.url`) -> `bootstrapEmpackPackedEnvironment` (untarjs into - `Module.FS` *before* python starts) -> extra packages (mambajs `install`, - lock platform `emscripten-`) -> `bootstrapPython` (= - `init_phase_1/2`) -> `loadSharedLibs` (main thread only). untarjs is - created by us with its wasm at `dist/untarjs.wasm` (mambajs-core's own - copy would look for `./unpack-*.wasm` relative to the page). The packages - `python` / `pyjs` are never replaced by `installPackages`. -- Returns the existing Module (`exec`, `eval`, `exec_eval`, - `async_exec_eval`, `to_js`, ...) + `installPackages(specs)`; the - `bootstrap_from_empack_packed_environment` / `init_phase_*` API stays as is. +- pyjs 5 init: the core (libpyjs + pre/post js) never fills the file system + or preloads shared libs; whoever fills it calls `Module.startPython()` (synchronous) + (`pre_js/init.js`: python version from C++ `_python_version`, error without + `/lib/pythonX.Y`, idempotent). The classic API (`bootstrap_from_empack_*`, + `init_phase_*`, `_untar`, `_install_conda_file`, untar/inflate C++, + `load_pkg.js`, `dynload.js`, `fetch.js`) is gone. The runtime target + (not libpyjs) has `src/extract.cpp`: `Module._extract_archive(bytes, dest, + {conda, meta, rename})` on libarchive (tar / zip, gzip / bzip2 / zstd, no + xz; .conda = zip of pkg-/info-*.tar.zst), own write loop (no `..` / + absolute paths / writes through the archive's symlinks; hard links -> + copies), returns `{files, sharedLibs, meta}`. Tests: `tests/sync/test_extract.py`. +- npm init (`runtime.ts`), all in parallel: `createModule` (or `wasmModule` + via `instantiateWasm`), solve (`solve.ts`: mambajs, lazy chunk, also + `empackLockToMambajsLock` / `formatChannels` / `computePackageUrl` from it: + the main bundle has no mambajs / untarjs), downloads (`fetch.ts`: byte + progress, sha256 only with `verifySha256`, max 6 parallel); package cache + (Cache Storage `pyjs-packages-v2`, by package URL): the installed layout + as uncompressed tar (`_extract_archive` option `tar`) + relocation + placeholders in a header, a warm install only untars (bypassed with + `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 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/` -> + `lib/pythonX.Y/site-packages/`, `info/paths.json` text placeholders -> "", + per-package file lists, old files removed before a replacement) -> + `archives` -> `files` -> `startPython` -> `sharedlibs.ts` (dlopen promise, + libs RTLD_GLOBAL first, `.cpython-*.so` / lib-dynload RTLD_LOCAL; main + thread only; *after* python started: extension modules' static + initializers use the C API, e.g. matplotlib's ft2font crashes otherwise). + `Module.initTimings`: phase times (ms) of the init, `Module.installTimings` + of the last `installPackages` (`state.timings` points to the running one). Options: `packages` (specs), `urls` (pinned + `{url, sha256?}`), `archives`, `files`, `cache`, `verifySha256`, + `onProgress`, `wasmModule`, `env`. `python` / `pyjs` are never replaced. +- Returns the Module + `installPackages(specs | pinned)`, `unpackArchive`, + `addFiles` (serialized in a queue). Entries also export `compileRuntime()`. + CLI: `npx lock ` (`src/lock.ts`, bundled for node into + `bin/lock.mjs`) -> `{wasm32: [{url, sha256}], ...}`; the docs build pins the + playground's numpy with it (`pyjs-lock.json`). - Tests: the full test suite on npm pages (both archs x main / worker) and on the 5 bundler pages (see Tests). npm-only tests: `tests/npm/test_*.py` (async), run by `tests/main.py` only with option `npm_package` (the harness - sets it when the Module has `installPackages`; the recipe never runs them). + sets it when the Module has `installPackages`); `test_install.py`: pinned at + init / runtime, `.conda`, relocation, replacing, sha256, cache, bytecode + cache, progress, `compileRuntime`. `tests/npm/test_channel.py` installs from a self-hosted channel (static files, like GitHub Pages next to docs) that the driver generates at `/test-channel/` (`pyjs_test_driver/test_channel.py`: noarch python package - + arch package, rattler-build output layout). The rattler gateway first + + arch package, rattler-build output layout; unindexed for pinned tests: a + `.conda` package, arch package v2.0.0). The rattler gateway first probes `repodata_shards.msgpack.zst` / `repodata.json.zst` / `.bz2` (404s are fine), then reads `repodata.json`. - Channel order = priority. mambajs' `install` appends new channels *after* the lock's (the shipped env: emscripten-forge, conda-forge), so `solve` in - `runtime.ts` puts the requested channels first (`formatChannels` from + `solve.ts` puts the requested channels first (`formatChannels` from mambajs-core): a self-hosted CI build must win over a published package (`test_self_hosted_channel_has_priority`: a fake `tabulate` 0.0.1 beats conda-forge's 0.9.x). -- Archives: option `archives: [{url, path}]` (unpacked with untarjs before - python starts) / `Module.unpackArchive({url, path})` (later, then - `importlib.invalidate_caches()`); files written with absolute paths - (cwd-independent), directory entries skipped, paths outside `path` rejected. +- Archives: option `archives: [{url, path}]` (unpacked by `_extract_archive` + before python starts) / `Module.unpackArchive({url, path})` (later, then + `importlib.invalidate_caches()`); paths resolved against `path` (never the + cwd), directory entries not listed, paths outside `path` rejected. Tests: `tests/npm/test_archives.py` with archives the driver generates (`pyjs_test_driver/test_archives.py`); the npm / bundler pages pass one in `archives`. -- mambajs-core creates the dirs of relative package paths relative to the - *cwd* but writes the files below the prefix `/`: `applyLock` in - `runtime.ts` runs with cwd `/` (Python may have changed it). - CI: `.github/workflows/npm.yml` builds + tests (all browsers), publishes on release tags (`4.1.0`, must equal the package version) / manual dispatch; npm trusted publishing (OIDC, configured on npmjs.com for this repo + @@ -312,7 +345,7 @@ like synchronous JS errors; pyodide compatible: `.name` / `.message`, e.g. `cd build_root/npm/package && npm publish --access public`. - On jsDelivr import `dist/index.js` directly, not `/+esm` (re-bundling breaks the `import.meta.url` asset paths). -- Assets (`assets/untarjs.wasm`, `assets//`: runtime + packed env) are +- Assets (`assets//`: runtime + packed env) are fetched at runtime, bundlers do not copy them. Lookup (`resolveAssets` in `runtime.ts`): `assetsUrl` -> `assets/` next to the module (probe of `/empack_env_meta.json`, must parse as env meta: dev servers answer @@ -324,7 +357,7 @@ like synchronous JS errors; pyodide compatible: `.name` / `.message`, e.g. lives in the unminified `dist/load-runtime.js` (esbuild's minifier drops the `webpackIgnore` / `@vite-ignore` comments), `__filename` / `__dirname` defined as `undefined` (webpack rewrites `typeof __filename` - in the untarjs glue). + in the untarjs glue bundled by mambajs-core, lazy solver chunk). - `build_utils/npm_bundler_test.py` (part of `npm --test`, `NPM_TEST_BUNDLERS=0` skips it): vite, webpack, rollup, esbuild, parcel, each self-hosted (`copy-assets`) and with the CDN fallback (`cdnUrl` -> diff --git a/CMakeLists.txt b/CMakeLists.txt index 9c76179..8f0bdfa 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 4.0) -project(pyjs VERSION 4.4.1 DESCRIPTION "pyjs") +project(pyjs VERSION 5.0.0 DESCRIPTION "pyjs") # cmake module directory @@ -53,13 +53,9 @@ set(PREJS_FILES ${CMAKE_CURRENT_SOURCE_DIR}/include/pyjs/pre_js/shortcuts.js ${CMAKE_CURRENT_SOURCE_DIR}/include/pyjs/pre_js/operators.js ${CMAKE_CURRENT_SOURCE_DIR}/include/pyjs/pre_js/platform.js - ${CMAKE_CURRENT_SOURCE_DIR}/include/pyjs/pre_js/wait_for_dependencies.js ${CMAKE_CURRENT_SOURCE_DIR}/include/pyjs/pre_js/init.js ${CMAKE_CURRENT_SOURCE_DIR}/include/pyjs/pre_js/cleanup.js ${CMAKE_CURRENT_SOURCE_DIR}/include/pyjs/pre_js/make_proxy.js - ${CMAKE_CURRENT_SOURCE_DIR}/include/pyjs/pre_js/dynload/dynload.js - ${CMAKE_CURRENT_SOURCE_DIR}/include/pyjs/pre_js/fetch.js - ${CMAKE_CURRENT_SOURCE_DIR}/include/pyjs/pre_js/load_pkg.js ${CMAKE_CURRENT_SOURCE_DIR}/include/pyjs/pre_js/literal_map.js ${CMAKE_CURRENT_SOURCE_DIR}/include/pyjs/pre_js/canvas.js ) @@ -97,9 +93,6 @@ set(PYJS_HEADERS include/pyjs/export_js_proxy.hpp include/pyjs/export_py_object.hpp include/pyjs/export_pyjs_module.hpp - include/pyjs/untar.hpp - include/pyjs/install_conda_file.hpp - include/pyjs/inflate.hpp ${CMAKE_CURRENT_BINARY_DIR}/pyjs_pre.js ${CMAKE_CURRENT_BINARY_DIR}/pyjs_post.js ) @@ -114,9 +107,6 @@ add_library(pyjs STATIC src/export_py_object.cpp src/convert.cpp src/export_pyjs_module.cpp - src/inflate.cpp - src/untar.cpp - src/install_conda_file.cpp ) if(WASM64) target_compile_options(pyjs PUBLIC -m64) @@ -189,7 +179,9 @@ find_package(pybind11 CONFIG) -add_executable(pyjs_runtime_browser src/runtime.cpp ) +# the runtime; src/extract.cpp (libarchive) only here, not in libpyjs: +# embedders like xeus-python fill the file system themselves +add_executable(pyjs_runtime_browser src/runtime.cpp src/extract.cpp) SET(ENVIRONMENT "web,worker") target_compile_definitions(pyjs_runtime_browser PUBLIC -DPYTEST_DRIVER_WEB) @@ -212,7 +204,11 @@ target_compile_options(pyjs_runtime_browser PRIVATE -fPIC) # include the dir where pybind11 is installed, so that we can find the pybind11Config.cmake file include_directories(${pybind11_INCLUDE_DIRS}) -target_link_libraries(pyjs_runtime_browser PRIVATE ${PYTHON_LIBRARIES} pyjs) +# libarchive first: it needs bz2 / z / zstd from PYTHON_LIBRARIES +target_link_libraries(pyjs_runtime_browser PRIVATE + ${CMAKE_INSTALL_PREFIX}/lib/libarchive.a + ${PYTHON_LIBRARIES} + pyjs) diff --git a/build_local.sh b/build_local.sh index 13f4ed1..6fa23e3 100755 --- a/build_local.sh +++ b/build_local.sh @@ -4,9 +4,9 @@ # all tools come from conda environments, created on the first run. # # ./build_local.sh build wasm32|wasm64 build pyjs -# ./build_local.sh test wasm32|wasm64 build pyjs, run the tests in the browser -# ./build_local.sh bench wasm32|wasm64 build pyjs, run the benchmarks in the browser -# ./build_local.sh npm [--test] build the npm package (+ run the tests on it) +# ./build_local.sh test wasm32|wasm64 build the npm package (this arch), run the tests on it +# ./build_local.sh bench wasm32|wasm64 build the npm package (this arch), run the benchmarks +# ./build_local.sh npm [--test] build the npm package (+ tests: all ARCHS + bundlers) # ./build_local.sh docs build the npm package + the docs # # --fresh delete the environments and build directories first @@ -31,7 +31,6 @@ # dev_prefix/ native tools: emscripten, cmake, node, playwright, ... # host_prefix_/ what pyjs is built against (python, pybind11, ...) # build_/ cmake build directory of pyjs -# test_env__/ python + test packages for the tests in the browser # npm_env_/ python + stdlib, shipped in the npm package # pages/ web pages the tests run on (pyjs_test_driver) # npm/ the npm package (npm/package/, npm/*.tgz) @@ -80,8 +79,7 @@ NUM_JOBS="$(sysctl -n hw.ncpu 2>/dev/null || nproc)" CHANNELS=(https://repo.prefix.dev/emscripten-forge/6x conda-forge) # the packages the tests need (tests/sync/test_http.py: the http stack of -# e.g. scipy.datasets). Test pages with the raw runtime get them packed into -# the test env, npm pages install them at runtime (mambajs). +# e.g. scipy.datasets), solved and installed at runtime by the npm pages case "$TEST_ENV" in default) TEST_PACKAGES=(numpy pytest urllib3 requests pyodide-http pooch) ;; no-numpy) TEST_PACKAGES=(pytest) ;; # pyjs must work without (optional) numpy @@ -183,8 +181,6 @@ use_arch() { PLATFORM="emscripten-$ARCH" export PREFIX="$BUILD_ROOT/host_prefix_$ARCH" BUILD_DIR="$BUILD_ROOT/build_$ARCH" - TEST_ENV_PREFIX="$BUILD_ROOT/test_env_${TEST_ENV//-/_}_$ARCH" - VANILLA_PAGE="$BUILD_ROOT/pages/vanilla_$ARCH" if [ "$ARCH" = "wasm64" ]; then export EMCC_CFLAGS="$EMCC_CFLAGS_WASM32 -m64" else @@ -251,14 +247,6 @@ pack_runtime() { empack pack append --env-meta "$out/empack_env_meta.json" --tarfile "$out/pyjs_module.tar.gz" } -# build_vanilla_page: the test page with the raw runtime of this build and the -# test packages packed by empack (VANILLA_PAGE) -build_vanilla_page() { - create_env_from_packages "$TEST_ENV_PREFIX" "$PLATFORM" "${PYTHON_PACKAGES[@]}" "${TEST_PACKAGES[@]}" - pack_runtime "$TEST_ENV_PREFIX" "$BUILD_ROOT/pages/vanilla_assets_$ARCH" - test_driver build-page vanilla --assets "$BUILD_ROOT/pages/vanilla_assets_$ARCH" --out "$VANILLA_PAGE" -} - # run_tests