From 59026f89d9ad249fa8e12afb9a36c9d2245afd64 Mon Sep 17 00:00:00 2001 From: BREW <81044362+b-re-w@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:15:43 +0900 Subject: [PATCH 1/3] Feature: wasmJs embeds free-threaded CPython 3.15t built with pthreads (#175) build-cpython.sh builds CPython 3.15.0 with --disable-gil --enable-wasm-pthreads on Emscripten 5.0.3 with the pyemscripten_2026_0 ABI (leader, Decision 10 a1 and b1), taking in the ft-wasm script's flags, trampoline patch, _pm_upcall module and Makefile patches, and adding smoke and probe steps. _pm_upcall.c, smoke.py and embed-probe.mjs move beside it. embedsFreeThreadedPython is true on wasmJs, so every published variant that carries a CPython states freeThreaded=true and autoDrainInterval defaults to on there. Defects found on the way: - select.poll() raised ENOSYS: 3.15 prefers ppoll(), which Emscripten links as a stub. Configured with ac_cv_func_ppoll=no; smoke.py asserts poll() works. - cpython.mjs readCString decoded a view of the shared memory, which a browser's TextDecoder rejects; it copies first. Tests: WasmGilBuildTest becomes WasmFreeThreadedBuildTest; WasmCycleCollectionTest reads the free-threaded wasm32 refcount layout; WasmBrowserRuntimeTest uses the t landmark; WasmCompiledWheelTest waits for a pypackpack cp315t wheel (Decision 10 c1, #82). Karma serves COOP/COEP (SPEC T-8). wasm.yml's test job builds the runtime itself, cached on the hashes of build-cpython.sh and _pm_upcall.c (leader, Decision 11 a); the WASM_RUNTIME_URL gate is gone. Local: wasmJsNodeTest 599 tests, 0 failed; wasmJsBrowserTest 10 tests, 0 failed. --- .github/scripts/ft-wasm/build-wasm.sh | 7 +- .github/workflows/build-ft-wasm.yml | 2 +- .github/workflows/wasm.yml | 98 +++-- README.md | 2 +- docs/SPEC.md | 16 +- docs/design/threading-and-abi.md | 2 +- docs/platforms/free-threaded-wasm.md | 27 +- docs/platforms/python-version-acquisition.md | 2 +- docs/platforms/wasm-design.md | 18 +- docs/roadmap/ROADMAP.md | 19 +- .../gradle/EmbeddedPythonVersion.kt | 2 +- python-multiplatform/build.gradle.kts | 33 +- .../karma.config.d/cpython.js | 11 +- .../scripts/wasm}/_pm_upcall.c | 0 .../scripts/wasm/build-cpython.sh | 379 +++++++++++++----- .../scripts/wasm}/embed-probe.mjs | 0 .../scripts/wasm}/smoke.py | 5 + .../multiplatform/EmbeddedPythonBuild.kt | 11 +- .../kotlin/python/multiplatform/Versions.kt | 2 +- .../python/multiplatform/ffi/Python3.kt | 5 +- .../python/multiplatform/VersionsTest.kt | 4 +- .../DesktopFreeThreadedBuildTest.kt | 2 +- python-multiplatform/src/wasmJsMain/README.md | 7 +- .../EmbeddedPythonBuild.wasmJs.kt | 7 +- .../src/wasmJsMain/resources/cpython.mjs | 17 +- .../WasmFreeThreadedBuildTest.kt | 37 ++ .../python/multiplatform/WasmGilBuildTest.kt | 22 - .../browser/WasmBrowserRuntimeTest.kt | 3 +- .../ref/WasmCycleCollectionTest.kt | 23 +- .../ffi/emscripten/WasmCompiledWheelTest.kt | 12 +- 30 files changed, 529 insertions(+), 246 deletions(-) rename {.github/scripts/ft-wasm => python-multiplatform/scripts/wasm}/_pm_upcall.c (100%) rename {.github/scripts/ft-wasm => python-multiplatform/scripts/wasm}/embed-probe.mjs (100%) rename {.github/scripts/ft-wasm => python-multiplatform/scripts/wasm}/smoke.py (96%) create mode 100644 python-multiplatform/src/wasmJsTest/kotlin/python/multiplatform/WasmFreeThreadedBuildTest.kt delete mode 100644 python-multiplatform/src/wasmJsTest/kotlin/python/multiplatform/WasmGilBuildTest.kt diff --git a/.github/scripts/ft-wasm/build-wasm.sh b/.github/scripts/ft-wasm/build-wasm.sh index 046778ef6..bdf563a4f 100755 --- a/.github/scripts/ft-wasm/build-wasm.sh +++ b/.github/scripts/ft-wasm/build-wasm.sh @@ -20,6 +20,9 @@ # Emscripten 5.0.3. The flags below are the #175 investigation's proposal, not a decision. set -euo pipefail here="$(cd "$(dirname "$0")" && pwd)" +# _pm_upcall.c, smoke.py and embed-probe.mjs live beside build-cpython.sh, which builds the same +# runtime for the library (Decision 10 a1); this script is deleted once wasm.yml is green on it. +wasm_scripts="$(cd "$here/../../../python-multiplatform/scripts/wasm" && pwd)" export FT_WORK="${FT_WORK:-$PWD/.tmp/ft-wasm}" export FT_OUT="${FT_OUT:-$PWD/.tmp/ft-wasm-out}" @@ -213,7 +216,7 @@ patch_makefile_exports # Built in statically through the build tree's Modules/Setup.local (configure leaves an empty # one there; makesetup reads it and finds the source under $(srcdir)/Modules). Its exported # functions (EMSCRIPTEN_KEEPALIVE) are checked below; smoke.py tests the routing. -cp "$here/_pm_upcall.c" Modules/_pm_upcall.c +cp "$wasm_scripts/_pm_upcall.c" Modules/_pm_upcall.c printf '*static*\n_pm_upcall _pm_upcall.c\n' >> "$hostdir/Modules/Setup.local" log "Setup.local: $(tr '\n' ' ' < "$hostdir/Modules/Setup.local")" @@ -276,7 +279,7 @@ run_smoke() { local label="$1"; shift local out="$FT_WORK/smoke-$label.log" rc set +e - timeout 600 "$@" "$here/smoke.py" > "$out" 2>&1 + timeout 600 "$@" "$wasm_scripts/smoke.py" > "$out" 2>&1 rc=$? set -e cat "$out" diff --git a/.github/workflows/build-ft-wasm.yml b/.github/workflows/build-ft-wasm.yml index 16dddcd56..33aca24aa 100644 --- a/.github/workflows/build-ft-wasm.yml +++ b/.github/workflows/build-ft-wasm.yml @@ -82,7 +82,7 @@ jobs: [ -d "$root" ] || { echo "no unpacked archive under $FT_WORK/wasm-check"; exit 1; } log="$FT_WORK/embed-probe.log" set +e - timeout 600 node .github/scripts/ft-wasm/embed-probe.mjs "$root" > "$log" 2>&1 + timeout 600 node python-multiplatform/scripts/wasm/embed-probe.mjs "$root" > "$log" 2>&1 rc=$? set -e cat "$log" diff --git a/.github/workflows/wasm.yml b/.github/workflows/wasm.yml index bb0149b7b..94d78555b 100644 --- a/.github/workflows/wasm.yml +++ b/.github/workflows/wasm.yml @@ -10,7 +10,10 @@ name: WasmJS CI # python-multiplatform/build.gradle.kts. # # `compile` is what a runner can always do honestly, and it is named for exactly that. -# `test` runs the real suite, and runs only when there is a runtime to run it against. +# `test` builds the runtime itself and runs the real suite against it. Leader, Decision 11 (a), +# 2026-11-26 (team report pmp-binder.md): "wasm.yml's test job runs build-cpython.sh itself, output in +# actions/cache keyed on the script and _pm_upcall.c hashes. No release asset." Until then the job +# was gated on a `WASM_RUNTIME_URL` repository variable that was never set, so it never ran. on: # Runs only as part of ci.yml, which is started by hand (owner, 2026-11-14: "개발 테스트 ci는 @@ -51,33 +54,14 @@ jobs: - name: Compile wasmJs main and test sources run: ./gradlew :python-multiplatform:compileKotlinWasmJs :python-multiplatform:wasmJsTestClasses --console=plain - # Says out loud what the green tick above does and does not cover, so that a reader of this - # workflow's result does not have to infer it. Drops away the moment the runtime URL exists. - - name: Say what did not run - if: vars.WASM_RUNTIME_URL == '' - run: | - { - echo "### wasmJs tests did not run" - echo - echo "This job compiled \`wasmJsMain\` and \`wasmJsTest\`. **No wasm test was executed.**" - echo - echo "Running them needs a CPython Emscripten build, which this repository publishes as" - echo "\`org.thisisthepy:python-multiplatform-wasm-runtime\` (a 7 MB zip built by" - echo "\`:python-multiplatform:wasmBrowserRuntimeZip\`) but has never pushed to a remote" - echo "repository -- it exists only in the maintainer's \`mavenLocal\`." - echo - echo "Set the repository variable \`WASM_RUNTIME_URL\` to a URL that serves that zip" - echo "(a GitHub release asset is enough) and the \`test\` job below will run the real" - echo "suite: 344 Node tests and 10 browser tests." - } >> "$GITHUB_STEP_SUMMARY" - echo "::warning title=wasmJs tests did not run::No CPython Emscripten runtime is available to this runner; set the WASM_RUNTIME_URL repository variable. This job compiled only." - test: - name: WasmJS Node + browser tests - runs-on: ubuntu-latest - # The whole point of the guard: this job exists only when it can do its job. A job that does not - # run shows up grey in the checks list, which is a different claim from a green one. - if: vars.WASM_RUNTIME_URL != '' + name: WasmJS Node + browser tests (CPython 3.15t built here) + runs-on: ubuntu-24.04 + # A cold cache is a full CPython build (a free-threaded build Python, then the wasm32 cross build). + timeout-minutes: 150 + env: + # build-cpython.sh's default staging directory, and the one -PwasmPythonDir points at below. + WASM_RUNTIME_DIR: ${{ github.workspace }}/.caches/wasm-runtime steps: - name: Checkout uses: actions/checkout@v4 @@ -89,10 +73,12 @@ jobs: distribution: 'zulu' cache: 'gradle' + # CPython 3.15.0 pins node 24 (Platforms/emscripten/config.toml, node-version); the runtime is + # built with -fwasm-exceptions and pthreads, and the test tasks run it under this node. - name: Setup Node uses: actions/setup-node@v4 with: - node-version: '20' + node-version: '24' - name: Cache Konan uses: actions/cache@v4 @@ -102,26 +88,52 @@ jobs: restore-keys: | ${{ runner.os }}-konan- - # The five files this unpacks are the whole interpreter as far as the test tasks are - # concerned -- python.wasm, python.mjs, the stdlib zip and the two glue modules. That is a - # property of `cpython.mjs`'s boot rather than an accident: the Node route used to reach the - # standard library through NODEFS against a CPython *source checkout*, which no artefact - # carries, and now installs the staged zip into MEMFS exactly as the browser route does. - - name: Fetch the CPython Emscripten runtime + # The staged runtime (python.wasm, python.mjs, the stdlib zip) is a pure function of the build + # script and the C module it compiles in, so those two hashes are the key (Decision 11 (a)). + # Restore and save are separate steps so that a red test run still keeps a runtime that built + # and passed its own checks; no restore-keys, a runtime from another script is never reused. + - name: Restore the CPython 3.15t runtime + id: runtime + uses: actions/cache/restore@v4 + with: + path: .caches/wasm-runtime + key: wasm-cpython315t-${{ runner.os }}-${{ hashFiles('python-multiplatform/scripts/wasm/build-cpython.sh', 'python-multiplatform/scripts/wasm/_pm_upcall.c') }} + + - name: Install build Python prerequisites + if: steps.runtime.outputs.cache-hit != 'true' + run: > + sudo apt-get update && sudo apt-get install -y + build-essential pkg-config libssl-dev zlib1g-dev libffi-dev + libbz2-dev liblzma-dev libsqlite3-dev libzstd-dev + + # The script's default `all`: build, zip, verify (ABI tags, shared memory, Py_GIL_DISABLED, + # the _pm_upcall exports), smoke.py under python.sh, stage, and the embedding probe against the + # staged runtime. Any of them failing stops here, before a runtime is cached. + - name: Build CPython 3.15t for wasm32-emscripten + if: steps.runtime.outputs.cache-hit != 'true' + run: bash python-multiplatform/scripts/wasm/build-cpython.sh + + - name: Save the CPython 3.15t runtime + if: steps.runtime.outputs.cache-hit != 'true' + uses: actions/cache/save@v4 + with: + path: .caches/wasm-runtime + key: ${{ steps.runtime.outputs.cache-primary-key }} + + - name: Check the runtime run: | set -euo pipefail - curl -fsSL "${{ vars.WASM_RUNTIME_URL }}" -o "$RUNNER_TEMP/wasm-runtime.zip" - mkdir -p "$RUNNER_TEMP/wasm-runtime" - unzip -q "$RUNNER_TEMP/wasm-runtime.zip" -d "$RUNNER_TEMP/wasm-runtime" - for f in python.wasm python.mjs; do - test -f "$RUNNER_TEMP/wasm-runtime/$f" \ - || { echo "::error::$f is not in the runtime zip served by WASM_RUNTIME_URL"; exit 1; } + for f in python.wasm python.mjs python3.15t.zip; do + test -f "$WASM_RUNTIME_DIR/$f" \ + || { echo "::error::$f is not in $WASM_RUNTIME_DIR"; exit 1; } done - ls -l "$RUNNER_TEMP/wasm-runtime" + ls -l "$WASM_RUNTIME_DIR" # `WasmCompiledWheelTest` imports a real compiled pyemscripten_2026_0 wheel. Under # `-PrequireWasmRuntime` a missing wheel is a failure, not a skip, so fetch them first: by URL, - # each accepted only against the sha256 the script pins. + # each accepted only against the sha256 the script pins. The script pins none today: the + # wheel has to be a pypackpack-built cp315t one (leader, Decision 10 (c) c1, 2026-11-26), and + # until pypackpack #82 produces it this job fails on that one test, by name, by design. - name: Fetch the pinned wasm wheels run: bash python-multiplatform/scripts/wasm/build-cpython.sh wheels @@ -134,7 +146,7 @@ jobs: ./gradlew \ :python-multiplatform:wasmJsNodeTest \ :python-multiplatform:wasmJsBrowserTest \ - -PwasmPythonDir="$RUNNER_TEMP/wasm-runtime" \ + -PwasmPythonDir="$WASM_RUNTIME_DIR" \ -PrequireWasmRuntime=true \ --console=plain diff --git a/README.md b/README.md index 9e121c936..e3fd40c57 100644 --- a/README.md +++ b/README.md @@ -202,7 +202,7 @@ Honest summary, see the [roadmap](docs/roadmap/ROADMAP.md) for what is left to d | Binding prebuilt jars, Compose from Python | ✅ desktop · ⏳ Android / iOS / wasm | | Binding Kotlin/Native klibs | 🟡 scanner only | | `.pyi` stub generation | 🟡 partial | -| Free-threaded CPython 3.15t (the only build on desktop since #158 and on Android / iOS since #328; wasm GIL until #175) | 🟡 desktop · 🟡 Android / iOS (compiled, not yet run on emulator or simulator) · ⏳ wasm | +| Free-threaded CPython 3.15t (the only build on desktop since #158, on Android / iOS since #328 and on wasm since #175) | 🟡 desktop · 🟡 Android / iOS (compiled, not yet run on emulator or simulator) · ⏳ wasm | ## 🧱 The ecosystem diff --git a/docs/SPEC.md b/docs/SPEC.md index 4aa9eed05..721713abf 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -1294,24 +1294,28 @@ All in `PM/commonTest`, so they run wherever the interpreter loads. desktop JVM, `macosArm64` and `linuxX64` embed the free-threaded CPython 3.15t, with no GIL option (`-PpythonFreeThreaded` is removed and the build fails if it is passed); Android (ART on arm64-v8a and x86_64, and androidNative) and iOS embed the project's own free-threaded CPython 3.15t (T-2), with - no GIL option either; wasm embeds a GIL CPython until #175. The fact is per platform - (`embedsFreeThreadedPython`, an `expect`/`actual`, kept while wasm is the exception), and + no GIL option either; wasm (wasmJs) embeds the project's own free-threaded CPython 3.15t built with + pthreads by `python-multiplatform/scripts/wasm/build-cpython.sh` (#175; owner, 2026-10-04: "The wasm + interpreter is also 3.15t, built by us ... with pthreads"; leader, Decision 10 (a) a1, 2026-11-26), and + in a browser needs a cross-origin isolated page (T-8). The fact is per platform + (`embedsFreeThreadedPython`, an `expect`/`actual`), and `Versions.abiFlags` (`t` or empty) and every name derived from it (`libpython3.15t`, `lib/python3.15t/`, - `libmultiplatform_python3.15t.so`) follow it. On the GIL platform Kotlin threads attach a thread state - and serialise on the GIL. + `libmultiplatform_python3.15t.so`) follow it. `Status: implemented` on desktop, Android and iOS (CI run 44889681538, 2026-11-21: the Android x86_64 emulator, API 34, ran the instrumented suite on 3.15t, 539 tests, 0 failed, `AndroidFreeThreadedBuildTest` among them; the iOS simulator ran the library suite on 3.15t, 513 tests, 0 failed, `IosFreeThreadedBuildTest` among them, and the plugin-staged `ios-consumer` app printed `IOS_CONSUMER_PROBE stdlib=ok ext=ok payload=ok ft=ok`; jobs `android-native.yml` `emulator` and `ios.yml` `ios-consumer`, owner-approved 2026-11-21, #328); `partial` on androidNative (compiled against 3.15t, its `artTest` not run on a device or emulator) and - wasm (GIL build until #175), + wasm (3.15t `wasmJsNodeTest` run locally only; `wasm.yml`'s test job, which builds the runtime itself, + has not run in CI yet, ROADMAP 10.1), `PM/desktopTest/.../DesktopFreeThreadedBuildTest.kt` (ABI flags, `Py_GIL_DISABLED` of the loaded interpreter, checkpoint default), `PM/desktopNativeTest/.../DesktopNativeFreeThreadedBuildTest.kt`, `PM/androidInstrumentedTest/.../AndroidFreeThreadedBuildTest.kt` (ABI flags, stdlib path, the AAR's `python.properties`, `Py_GIL_DISABLED` of the loaded interpreter, checkpoint default), `PM/artTest/.../AndroidNativeFreeThreadedBuildTest.kt`, `PM/iosSimulatorArm64Test/.../IosFreeThreadedBuildTest.kt`, - `PM/wasmJsTest/.../WasmGilBuildTest.kt`, + `PM/wasmJsTest/.../WasmFreeThreadedBuildTest.kt` (ABI flags, `Py_GIL_DISABLED` of the loaded + interpreter, `sys._is_gil_enabled()`), `PM/commonTest/.../VersionsTest.kt`; the release after initialisation is tested by `GilReleaseTest` / `GilReleaseNativeTest` (see C-4). - **T-1a** On desktop, Python may be entered from a JVM virtual thread (#161 option B, user decision): diff --git a/docs/design/threading-and-abi.md b/docs/design/threading-and-abi.md index b29e7056a..05e60a90e 100644 --- a/docs/design/threading-and-abi.md +++ b/docs/design/threading-and-abi.md @@ -14,7 +14,7 @@ the build differs by platform (SPEC T-1): |---|---|---| | Desktop JVM, `macosArm64`, `linuxX64` | `python3.15t` (free-threaded), the only desktop build | Each Kotlin thread talks to its own free-running Python thread | | Android (ART, androidNative; arm64-v8a and x86_64), iOS | `python3.15t` (free-threaded), the project's own build, the only mobile build since #328 | Each Kotlin thread talks to its own free-running Python thread (not yet run on an emulator or simulator) | -| wasmJs | GIL until #175 | single-threaded | +| wasmJs | `python3.15t` (free-threaded) with pthreads, the project's own build (`scripts/wasm/build-cpython.sh`, #175) | Kotlin runs on the main runtime thread only; Python threads are pthreads (Web Workers), and their upcalls and proxy slots are routed to the main thread by the `_pm_upcall` module. A browser page must be cross-origin isolated (SPEC T-8) | The per-platform fact is `embedsFreeThreadedPython` (commonMain `EmbeddedPythonBuild.kt`, an `expect`/`actual`); `-PpythonFreeThreaded` is removed. The interpreter version is pinned by diff --git a/docs/platforms/free-threaded-wasm.md b/docs/platforms/free-threaded-wasm.md index af63b541f..697060e70 100644 --- a/docs/platforms/free-threaded-wasm.md +++ b/docs/platforms/free-threaded-wasm.md @@ -1,17 +1,20 @@ # Free-threaded CPython for wasm32-emscripten -Status: build recipe written from the CPython 3.15.0 source; **not yet run in CI.** Nothing -here has been compiled, linked or run. Tracking issue: #175 (this is its first step, the -build experiment). The owner approved the CI job on 2026-11-13 ("#175 may add the new wasm -3.15t CI build job"). +Status: the experiment this file records is done. `.github/workflows/build-ft-wasm.yml` built the +3.15t pthreads interpreter in CI and passed its smoke test and embedding probe (run 45704188042 on +Emscripten 5.0.3), and its flags and patches moved into +`python-multiplatform/scripts/wasm/build-cpython.sh`, which now builds the runtime the wasmJs suite +uses (leader, Decision 10 (a) a1, 2026-11-26) and which `wasm.yml`'s test job runs itself (leader, +Decision 11 (a), 2026-11-26). The CI-only `.github/scripts/ft-wasm/` script and `build-ft-wasm.yml` +are deleted once `wasm.yml` is green on `build-cpython.sh`. Tracking issue: #175. The owner approved +the CI job on 2026-11-13 ("#175 may add the new wasm 3.15t CI build job"). python-multiplatform gets its parallelism from free-threaded CPython (decision 8 in -`AGENTS.md`). The wasmJs target today runs a GIL, no-threads CPython 3.14.2 +`AGENTS.md`). The wasmJs target embedded a GIL, no-threads CPython 3.14.2 until #175 ([`wasm-design.md`](wasm-design.md)). No prebuilt free-threaded CPython with pthreads exists -for Emscripten, so the workflow `.github/workflows/build-ft-wasm.yml` builds one with -CPython's own driver and checks that it runs threads without the GIL under node. It does not -change `wasm.yml`, `python-multiplatform/scripts/wasm/build-cpython.sh` or the runtime the -wasmJs suite uses. +for Emscripten, so this project builds one with CPython's own driver. The sections below describe +the experiment's archive layout and the questions it was run to answer; the "Open" list is as it +stood before the runs. ## What is built @@ -143,7 +146,7 @@ and `wasmTable`, so a lost edit fails the build instead of the probe. The workflow step `Embedding probe (no main)` runs after the archive upload, so a probe failure or hang does not lose the archive: -`timeout 600 node .github/scripts/ft-wasm/embed-probe.mjs `. It prints one +`timeout 600 node python-multiplatform/scripts/wasm/embed-probe.mjs `. It prints one `[x] PASS|FAIL` line per check and `FT-WASM-EMBED-PROBE-OK` only if all pass; on a timeout (exit 124) the step reports the last check line printed. @@ -179,7 +182,7 @@ Kotlin-side memory import). - Whether `EMCC_CFLAGS=-pthread` is enough for libffi and mpdec, and whether the `-sUSE_BZIP2` port links into a shared-memory build, is a prediction. - Whether the JS trampoline fallback is enough, and what it costs per call compared with the - wasm-gc trampoline (`WasmCallTrampolineTest` covers only the current GIL build). + wasm-gc trampoline (`WasmCallTrampolineTest` was written against the GIL build). - Only node is exercised; no browser (which also needs cross-origin isolation for `SharedArrayBuffer`). - The smoke test checks that four threads run and join with the GIL off. It is not a @@ -246,7 +249,7 @@ an exported C function). No new dependency, workflow or kind of artefact. - An exception raised in Kotlin reaches the Python thread. **Implemented (2026-11-25, `feat/175-wasm-thread-upcalls`, not yet run).** -- `.github/scripts/ft-wasm/_pm_upcall.c`, built into the 3.15t runtime by `build-wasm.sh` through +- `python-multiplatform/scripts/wasm/_pm_upcall.c`, built into the 3.15t runtime by `build-wasm.sh` through the build tree's `Modules/Setup.local`. It declares `Py_MOD_GIL_NOT_USED`, without which its import would re-enable the GIL. Exports `pm_upcall_dispatch`, `pm_upcall_set_target`, `pm_upcall_dispatch_index`; `build-wasm.sh` checks all three and that the module is built in. diff --git a/docs/platforms/python-version-acquisition.md b/docs/platforms/python-version-acquisition.md index 325fa57b5..15d5ad28f 100644 --- a/docs/platforms/python-version-acquisition.md +++ b/docs/platforms/python-version-acquisition.md @@ -153,7 +153,7 @@ tests without throwing; the other flavour fails naming #158, as for `includeDir` A consumer that builds against `python-multiplatform` must know which CPython it embeds (issue #61). The answer is published three ways. The version is `pythonVersion` in `gradle.properties`; whether the build is free-threaded differs by platform (desktop 3.15t since #158, Android, androidNative and -iOS 3.15t since #328, wasm GIL until #175), so each published artefact states its own. +iOS 3.15t since #328, wasm 3.15t since #175), so each published artefact states its own. * **Extension** `pythonMultiplatform` (`python.multiplatform.gradle.EmbeddedPythonVersion`): `pythonVersion` (`3.15.0`), `majorMinor` (`3.15`), `freeThreaded`. One value per project: the diff --git a/docs/platforms/wasm-design.md b/docs/platforms/wasm-design.md index 0d8619594..368ee3c92 100644 --- a/docs/platforms/wasm-design.md +++ b/docs/platforms/wasm-design.md @@ -18,7 +18,7 @@ has a browser wasm target. `wasmWasi` is not a target (when last assessed it was |---|---|---| | How Kotlin reaches CPython | Raw Stable ABI symbols as `@WasmImport`s against the Emscripten module's own wasm exports, **no JS in the call path** | Preserves the exact object model (`NativePointer`, `PyObject`) of every other target; a high-level Pyodide-style JS API (`pyodide.runPython`, `PyProxy`) would replace the whole object model with `JsAny` wrappers and covers almost none of the ~330 C functions | | Memory | **One linear memory, CPython's.** Kotlin imports Emscripten's `Module.wasmMemory` as its `intrinsics.memory` | Needs Kotlin ≥ 2.4.20-Beta2, whose `wasmJs` modules **import** `intrinsics.memory` (`min=0, max=none`); releases up to 2.4.10 exported an unbounded memory, which Emscripten cannot import ([`../archive/wasm-youtrack-issue.md`](../archive/wasm-youtrack-issue.md)). The free-threaded pthreads build's memory is **shared**, which that non-shared import cannot take, so the build rewrites the import after the link (SPEC T-7, below) | -| Where CPython comes from | **Our own Emscripten build**, `python-multiplatform/scripts/wasm/build-cpython.sh`: CPython **3.14.2**, Emscripten **5.0.3**, matched to the `pyemscripten_2026_0` platform of PEP 783 | No distributor ships a `python.wasm` exporting `wasmExports,wasmMemory`. The version is deliberately not the 3.14.x pinned for native targets (`pythonVersion` in `gradle.properties`); see `docs/design/ecosystem.md` | +| Where CPython comes from | **Our own Emscripten build**, `python-multiplatform/scripts/wasm/build-cpython.sh`: free-threaded CPython **3.15.0t** with pthreads, Emscripten **5.0.3**, matched to the `pyemscripten_2026_0` platform of PEP 783 (owner, #175, 2026-10-04: "The wasm interpreter is also 3.15t, built by us ... with pthreads"; leader, Decision 10 (a) a1 and (b) b1, 2026-11-26) | No distributor ships a free-threaded pthreads `python.wasm`, nor one exporting `wasmExports,wasmMemory`. A shared memory needs a cross-origin isolated page in a browser (SPEC T-8); see `docs/platforms/free-threaded-wasm.md` | | C shim / composition | **None** | The hops that composition amortised are gone; measured gain ≤ 2.9 ns per operation (below). It also removes a second build pipeline | | `EXPORTED_FUNCTIONS` list | **Not needed** | `-sMAIN_MODULE` is `LINKABLE`, so the whole Stable ABI is exported (all 310 C symbols `EmbedAPI.kt` declared at the time were found in the build's 8287 exports). The build adds `wasmExports,wasmMemory` to `-sEXPORTED_RUNTIME_METHODS`, which is not ABI-sensitive | | Upcalls (Python → Kotlin) | `@WasmExport` trampolines placed in CPython's `__indirect_function_table` with `WebAssembly.Table.set`; the table index is the C function pointer. Routing is by data (a handle in `self`/`closure`), through the generated table, as on every platform | A funcref is a funcref: `call_indirect` reaches the Kotlin export directly. Measured 3.1 ns vs 10.9 ns for the `addFunction` + JS-closure route | @@ -105,21 +105,25 @@ Corrections that came out of measuring (they changed the design): ## The interpreter build and the platform tag -`python-multiplatform/scripts/wasm/build-cpython.sh` builds CPython 3.14.2 with CPython's own `Tools/wasm/emscripten` driver -plus the changes that make it claim `pyemscripten_2026_0` (PEP 783): +`python-multiplatform/scripts/wasm/build-cpython.sh` builds free-threaded CPython 3.15.0 (`--disable-gil --enable-wasm-pthreads`) +with CPython's own `Platforms/emscripten` driver plus the changes that make it claim `pyemscripten_2026_0` +(PEP 783). The thread-specific changes (pthread flags, the JS call trampoline under a shared memory, +the `_pm_upcall` module, `ac_cv_func_ppoll=no`) are listed in the script's header: | | stock Tier 3 build | this build | |---|---|---| | Unwinding ABI `-fwasm-exceptions -sSUPPORT_LONGJMP=wasm` at compile **and** link | absent | **present, this is the one that gates loading a compiled wheel** (the side module imports the `__cpp_exception` tag) | -| `PYEMSCRIPTEN_PLATFORM_VERSION` | not defined anywhere in CPython 3.14.2 | defined via a patch to `sysconfig` (`_ALWAYS_STR`; otherwise `int('2026_0') == 20260` silently yields the tag `pyemscripten_20260_wasm32`) | +| `PYEMSCRIPTEN_PLATFORM_VERSION` | not defined anywhere in CPython 3.15.0 (nor 3.14.2) | defined via a patch to `sysconfig` (`_ALWAYS_STR`; otherwise `int('2026_0') == 20260` silently yields the tag `pyemscripten_20260_wasm32`) | | `wasmExports,wasmMemory,wasmTable` in `-sEXPORTED_RUNTIME_METHODS` | no | yes (not ABI-sensitive) | | `lzma`, `zstd`, OpenSSL | missing | **still missing**, ABI-sensitive per Pyodide's flag list but they did not gate the wheel tested; costs `_lzma`, `_zstd`, `_hashlib`, `_ssl` | -Evidence: a real PyPI wheel, `pydantic_core-2.48.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl`, imports -and runs on this build (`validate_python(42) -> 42`, a `ValidationError` raised and caught, the +Evidence, from the 3.14.2 GIL build this replaced: a real PyPI wheel, `pydantic_core-2.48.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl`, imported +and ran on that build (`validate_python(42) -> 42`, a `ValidationError` raised and caught, the exception exercises the unwinding ABI), and fails with `tag import requires a WebAssembly.Tag` on the stock build. This is one wheel and one code path; it does not show that every compiled extension -loads. `WasmCompiledWheelTest` runs it (`python-multiplatform/scripts/wasm/build-cpython.sh wheels` fetches the pinned wheels); +loads. A cp314 wheel does not load in 3.15t, so `WasmCompiledWheelTest` now waits for a pypackpack-built +cp315t wheel (leader, Decision 10 (c) c1, 2026-11-26; pypackpack #82) and until then reports a named +skip that fails under `-PrequireWasmRuntime` (`python-multiplatform/scripts/wasm/build-cpython.sh wheels` pins none yet); `WasmInterpreterAbiTest` checks the claims, with `python-multiplatform/scripts/wasm/build-cpython.sh stock` as the negative control. Emscripten is pinned to 5.0.3 because that is what the platform specifies, and installing it replaces `~/emsdk/upstream` in place (a global setting). diff --git a/docs/roadmap/ROADMAP.md b/docs/roadmap/ROADMAP.md index 86f1f06fb..a39b74b85 100644 --- a/docs/roadmap/ROADMAP.md +++ b/docs/roadmap/ROADMAP.md @@ -182,7 +182,8 @@ free-threaded ones, are pinned in `python-checksums.properties`. - **9.1 `autoDrainInterval`'s default on the GIL build, open (decision).** Today `if (embedsFreeThreadedPython) 32 else 0` (`Python3.kt`), so on by default on desktop, Android and - iOS (#328) and off only on wasm until #175; once wasm is free-threaded this question closes. Off means a pure C-API embedder never + iOS (#328), and on wasm since #175 flipped `embedsFreeThreadedPython` there; with no GIL platform + left this question closes when that lands in develop. Off means a pure C-API embedder never runs the cyclic collector: 20 000+ cyclic objects left with the automatic path off against ~1 970 with it on (`docs/investigations/gc-scheduling-investigation.md` §6–§7). On means a `__del__` or weakref callback can run at a `withGIL` exit the caller did not ask to yield from. The checkpoint @@ -197,7 +198,8 @@ free-threaded ones, are pinned in `python-checksums.properties`. `freeThreaded=true`; the python.org and BeeWare GIL mobile archives and their pins are gone. Left: an Android emulator run (`AndroidFreeThreadedBuildTest`, the instrumented suite, the androidNative suite) and an iOS simulator run (`IosFreeThreadedBuildTest`, the ios-consumer fixture, sample DEMO - 1/8) with `Py_GIL_DISABLED` observed at run time; then wasm (#175). SPEC N-1. + 1/8) with `Py_GIL_DISABLED` observed at run time; then wasm (#175: `embedsFreeThreadedPython` is + true on wasmJs and `build-cpython.sh` builds 3.15t with pthreads; CI evidence is 10.1). SPEC N-1. ## 10. WASM @@ -210,12 +212,13 @@ cycles, interning and `Py_ssize_t` are closed (`PM/wasmJsTest/`: `WasmFinalizati (`docs/platforms/wasm-design.md`). Old §10c/§10d (browser test, CI split) are closed; their open remainder is 10.1. -- **10.1 The wasm test suite does not run in CI, open.** `.github/workflows/wasm.yml` runs the - `test` job only when the repository variable `WASM_RUNTIME_URL` is set. It is not set (observed - 2026-10-03: `gh variable list` empty; the latest `develop` run shows "WasmJS Node + browser tests: - skipped", compile job green). What closes it is uploading the - `python-multiplatform-wasm-runtime` zip (7.0 MB) somewhere a runner can fetch and setting the - variable; see also 15.1. +- **10.1 The wasm test suite does not run in CI, in progress (#175).** `.github/workflows/wasm.yml` + ran the `test` job only when the repository variable `WASM_RUNTIME_URL` was set, and it never was + (observed 2026-10-03: `gh variable list` empty; "WasmJS Node + browser tests: skipped"). Leader, + Decision 11 (a), 2026-11-26: "wasm.yml's test job runs build-cpython.sh itself, output in + actions/cache keyed on the script and _pm_upcall.c hashes. No release asset." The job now does + that; it closes when a dispatched `ci.yml` shows the job green. Until pypackpack #82 ships a cp315t + wheel, `WasmCompiledWheelTest` fails it by name (Decision 10 (c) c1). - **10.2 `suspend` upcalls and `asyncio` on wasm, open.** SPEC U-5 is `planned` on wasm (no threads), and `import asyncio` traps the instance (`asyncio.run` wants `socketpair`); the sample skips section 7 there (`sample/src/wasmJsMain/.../bindings/ProxyDemo.wasmJs.kt`). diff --git a/python-multiplatform-gradle-plugin/src/main/kotlin/python/multiplatform/gradle/EmbeddedPythonVersion.kt b/python-multiplatform-gradle-plugin/src/main/kotlin/python/multiplatform/gradle/EmbeddedPythonVersion.kt index 11033e031..73f70d64c 100644 --- a/python-multiplatform-gradle-plugin/src/main/kotlin/python/multiplatform/gradle/EmbeddedPythonVersion.kt +++ b/python-multiplatform-gradle-plugin/src/main/kotlin/python/multiplatform/gradle/EmbeddedPythonVersion.kt @@ -12,7 +12,7 @@ import org.gradle.api.Project * - as the classpath resource [RESOURCE_PATH] (read from the jar/AAR, no Gradle needed). * * One instance describes one build of CPython. A project whose platforms embed different builds - * (issues #158, #328: desktop, Android and iOS 3.15t, wasm a GIL build until #175) passes a per-variant + * (issues #158, #328, #175: desktop, Android, iOS and wasm 3.15t) passes a per-variant * `freeThreadedFor` to [publishAttributes] / [register], so each published variant states the build * it really carries, and renders one resource per artefact. */ diff --git a/python-multiplatform/build.gradle.kts b/python-multiplatform/build.gradle.kts index 161348d81..0e4b71ac6 100644 --- a/python-multiplatform/build.gradle.kts +++ b/python-multiplatform/build.gradle.kts @@ -68,8 +68,10 @@ val configuredPythonVersion = project.property("pythonVersion").toString() // `-PpythonFreeThreaded` switch that used to choose it is gone. Android (arm64-v8a, x86_64), // androidNative and iOS embed the project's own 3.15t builds from the GitHub release // `cpython-t-mobile` (#328; leader 2026-11-13: no opt-in flag on mobile, 3.15t is the -// only build). Only wasm still embeds a GIL build, until #175. Which build each platform embeds is -// the `embedsFreeThreadedPython` expect/actual in the library, not a build-wide flag. +// only build). wasm embeds the project's own 3.15t with pthreads, built by +// `python-multiplatform/scripts/wasm/build-cpython.sh` (#175; leader, Decision 10 (a) a1, 2026-11-26). +// Which build each platform embeds is the `embedsFreeThreadedPython` expect/actual in the library, +// not a build-wide flag. if (project.findProperty("pythonFreeThreaded") != null) { throw GradleException( "-PpythonFreeThreaded was removed (issue #158): desktop always embeds the free-threaded " + @@ -695,22 +697,20 @@ extensions.add( * `docs/platforms/python-version-acquisition.md` "Published version". * * Per platform since #158: the desktop jar, the AAR and every Kotlin/Native klib (macosArm64, - * linuxX64, iOS, androidNative) embed 3.15t (#158, #328); only wasm still embeds a GIL build, until - * #175. So the free-threaded attribute is decided per published variant (false on the wasm ones), - * and the jar and the AAR each get their own resource. Shared metadata variants carry no CPython and + * linuxX64, iOS, androidNative) embed 3.15t (#158, #328), and so do the wasmJs ones since #175. The + * free-threaded attribute is still decided per published variant (true on every one that carries a + * CPython), and the jar and the AAR each get their own resource. Shared metadata variants carry no CPython and * get no free-threaded attribute. The `pythonMultiplatform` extension holds one value, the - * free-threaded one every non-wasm platform embeds, and the per-variant attributes are the + * free-threaded one every platform embeds, and the per-variant attributes are the * per-platform truth. (Extension and metadata rules: agent proposal, not confirmed.) */ val embeddedPythonVersion = EmbeddedPythonVersion(configuredPythonVersion, freeThreaded = true) -// `android` covers the AAR's variants and androidNativeArm64/X64, `ios` iosArm64, iosX64 and -// iosSimulatorArm64. Anything else that is not metadata (the wasmJs variants) is GIL. -val freeThreadedVariantPrefixes = listOf("desktop", "macosArm64", "linuxX64", "mingwX64", "android", "ios") +// Every variant that carries a CPython is free-threaded since #175 made wasmJs 3.15t (the last GIL +// one); metadata variants carry none and get no attribute. embeddedPythonVersion.register(project) { configurationName -> when { - freeThreadedVariantPrefixes.any { configurationName.startsWith(it) } -> true configurationName.startsWith("metadata") || "Metadata" in configurationName -> null - else -> false + else -> true } } @@ -2048,7 +2048,8 @@ listOf("Arm64" to "arm64-v8a", "X64" to "x86_64").forEach { (targetSuffix, abi) // top-level `await`, so Emscripten is fully instantiated before the import object is built. // // The CPython build itself is produced by `python-multiplatform/scripts/wasm/build-cpython.sh` (also reachable as the -// `buildWasmPython` task below) -- CPython 3.14.2 matched to `pyemscripten_2026_0` (PEP 783), +// `buildWasmPython` task below) -- free-threaded CPython 3.15.0 (3.15t) with pthreads, on Emscripten +// 5.0.3, matched to `pyemscripten_2026_0` (PEP 783), // relinked with `wasmExports,wasmMemory` added to `-sEXPORTED_RUNTIME_METHODS`. Without those two the // 8287 wasm exports are present in the binary but unreachable from JS, so there is nothing to hand // `@WasmImport`; neither appears in PEP 783's ABI-sensitive list. Unlike every other platform's @@ -2067,12 +2068,12 @@ val wasmPythonDir: String = (project.findProperty("wasmPythonDir")?.toString() /** * Builds the CPython Emscripten runtime into `.caches/` and stages it at the default * [wasmPythonDir]. Long (a full CPython cross build) and needs network the first time (emsdk 5.0.3 - * and the CPython 3.14.2 checkout), so nothing depends on it: the wasm tasks keep their + * and the CPython 3.15.0 checkout), so nothing depends on it: the wasm tasks keep their * skip-with-a-message contract when it has not been run. */ val buildWasmPython by tasks.registering(Exec::class) { group = "python" - description = "Builds CPython 3.14.2 for wasm32-emscripten (pyemscripten_2026_0) into .caches/" + description = "Builds free-threaded CPython 3.15t with pthreads for wasm32-emscripten (pyemscripten_2026_0) into .caches/" val script = rootProject.layout.projectDirectory.file("python-multiplatform/scripts/wasm/build-cpython.sh").asFile commandLine("bash", script.absolutePath, "all") } @@ -2263,7 +2264,7 @@ val stageWasmBrowserRuntime by tasks.registering { // second place to keep in step, and `cpython.mjs` already reads the version out of the // running interpreter to decide where in MEMFS it goes. val stdlibZip = pythonDir.listFiles() - ?.firstOrNull { it.name.matches(Regex("""python\d+\.\d+\.zip""")) } + ?.firstOrNull { it.name.matches(Regex("""python\d+\.\d+t?\.zip""")) } ?: throw GradleException( "no python..zip in $pythonDir. A browser has no NODEFS, so the " + "standard library has to travel as the zip CPython's own web example fetches; " + @@ -2675,7 +2676,7 @@ tasks.withType().co // silently made every wasm test depend on a CPython **source checkout** sitting next to the // build directory; staging it here is what lets `wasmPythonDir` be an unpacked // `python-multiplatform-wasm-runtime` artefact, which is the only form CI can obtain. - val stdlibZip = pythonDir.listFiles()?.firstOrNull { it.name.matches(Regex("""python\d+\.\d+\.zip""")) } + val stdlibZip = pythonDir.listFiles()?.firstOrNull { it.name.matches(Regex("""python\d+\.\d+t?\.zip""")) } copy { from(pythonDir) { include("python.mjs", "python.wasm") } if (stdlibZip != null) from(stdlibZip) diff --git a/python-multiplatform/karma.config.d/cpython.js b/python-multiplatform/karma.config.d/cpython.js index fe678d2dd..5dce25735 100644 --- a/python-multiplatform/karma.config.d/cpython.js +++ b/python-multiplatform/karma.config.d/cpython.js @@ -31,7 +31,7 @@ const staged = path.resolve(config.basePath, 'kotlin'); // a second place to keep in step with the CPython build (`cpython.mjs` already reads the version out // of the running interpreter to decide where in MEMFS the zip goes). const stdlibZip = fs.existsSync(staged) - ? fs.readdirSync(staged).find((name) => /^python\d+\.\d+\.zip$/.test(name)) + ? fs.readdirSync(staged).find((name) => /^python\d+\.\d+t?\.zip$/.test(name)) : undefined; const runtimeFiles = ['python.mjs', 'python.wasm', stdlibZip] @@ -68,3 +68,12 @@ if (stdlibZip) { // is paid on every red build. Measured: the `node:fs` break below took 2m07s at 120 s. config.browserNoActivityTimeout = 60000; config.captureTimeout = 60000; + +// SPEC T-8: the free-threaded runtime has a shared memory, which the browser grants only to a +// cross-origin isolated page, and cpython.mjs refuses to start otherwise. Karma's server sends the +// two headers on everything it serves (the runner page, its iframe and the scripts), so the test +// page is isolated. Same-origin subresources need nothing more under require-corp. +config.customHeaders = (config.customHeaders || []).concat([ + { match: '.*', name: 'Cross-Origin-Opener-Policy', value: 'same-origin' }, + { match: '.*', name: 'Cross-Origin-Embedder-Policy', value: 'require-corp' }, +]); diff --git a/.github/scripts/ft-wasm/_pm_upcall.c b/python-multiplatform/scripts/wasm/_pm_upcall.c similarity index 100% rename from .github/scripts/ft-wasm/_pm_upcall.c rename to python-multiplatform/scripts/wasm/_pm_upcall.c diff --git a/python-multiplatform/scripts/wasm/build-cpython.sh b/python-multiplatform/scripts/wasm/build-cpython.sh index de8cd3da2..1b2248dce 100755 --- a/python-multiplatform/scripts/wasm/build-cpython.sh +++ b/python-multiplatform/scripts/wasm/build-cpython.sh @@ -1,91 +1,116 @@ #!/bin/bash -# CPython 3.14.2 for wasm32-emscripten, ABI-matched to pyemscripten_2026_0 (PEP 783), and staged as -# the runtime python-multiplatform's wasmJs target runs against. +# Free-threaded CPython 3.15.0 (--disable-gil) with pthreads for wasm32-emscripten, on Emscripten +# 5.0.3 with the pyemscripten_2026_0 unwinding ABI, staged as the runtime python-multiplatform's +# wasmJs target runs against (#175). # -# python-multiplatform/scripts/wasm/build-cpython.sh build + zip + verify + stage (needs network the first time) +# python-multiplatform/scripts/wasm/build-cpython.sh build + zip + verify + smoke + stage + probe (needs network the first time) # python-multiplatform/scripts/wasm/build-cpython.sh zip rebuild only the stdlib zip of an existing build (no emsdk) -# python-multiplatform/scripts/wasm/build-cpython.sh verify check an existing build and its zip carry the ABI claims +# python-multiplatform/scripts/wasm/build-cpython.sh verify check an existing build and its zip carry the ABI and thread claims +# python-multiplatform/scripts/wasm/build-cpython.sh smoke run smoke.py (threads, upcalls, proxy slots) under the build tree's python.sh # python-multiplatform/scripts/wasm/build-cpython.sh stage copy python.wasm, python.mjs and the zip to the runtime dir -# python-multiplatform/scripts/wasm/build-cpython.sh wheels download the pinned compiled wheels the wasm suite loads -# python-multiplatform/scripts/wasm/build-cpython.sh stock build a STOCK PEP 776 interpreter as a negative control +# python-multiplatform/scripts/wasm/build-cpython.sh probe run embed-probe.mjs against the staged runtime (Python without main, as the library runs it) +# python-multiplatform/scripts/wasm/build-cpython.sh wheels download the pinned compiled wheels the wasm suite loads (none yet, see below) +# python-multiplatform/scripts/wasm/build-cpython.sh stock build a STOCK interpreter (CPython's own driver defaults) as a negative control +# +# Which CPython, and why. Owner, 2026-10-04, on #175: "The wasm interpreter is also 3.15t, built by us +# (tools/wasm/build-cpython.sh) with pthreads; not Pyodide's GIL build ... Cost accepted: Pyodide's +# emscripten wheels do not load; compiled dependencies are built by pypackpack for wasm." The leader +# approved Decision 10 on 2026-11-26 (team report pmp-binder.md): (a) a1, this script builds 3.15t with +# pthreads; (b) b1, "one Emscripten 5.0.3 for PMP wasm and pypackpack #82"; (c) c1, the compiled-wheel +# test moves to a pypackpack-built cp315t wheel when #82 produces one. The thread build's flags and +# patches come from .github/scripts/ft-wasm/build-wasm.sh, whose CI runs proved them (build-ft-wasm +# 45704188042 on 5.0.3: smoke test in both layouts, embedding probe a to d); that script is deleted +# once wasm.yml is green on this one. # # Everything lands inside this repository, under the git-ignored `.caches/`: # # .caches/emsdk emsdk, pinned to 5.0.3 (override: EMSDK) -# .caches/wasm-build/cpython314 CPython checkout + cross build (override: CPYTHON_CHECKOUT) +# .caches/wasm-build/cpython315t CPython checkout + cross build (override: CPYTHON_CHECKOUT) # .caches/wasm-runtime the three files the library needs (override: WASM_RUNTIME_DIR) -# .caches/wasm-wheels pinned pyemscripten_2026_0 wheels (override: WASM_WHEELS_DIR) -# .caches/wasm-build/cpython314-stock, .caches/wasm-runtime-stock the `stock` control +# .caches/wasm-wheels pinned wheels (override: WASM_WHEELS_DIR) +# .caches/wasm-build/cpython315-stock, .caches/wasm-runtime-stock the `stock` control # # `.caches/wasm-runtime` is the default `wasmPythonDir` in python-multiplatform/build.gradle.kts, so # after one run of this script `./gradlew :python-multiplatform:wasmJsNodeTest` runs the suite with # no flags. It is also exactly the layout of an unpacked `python-multiplatform-wasm-runtime` zip. # -# Why this is a build and not a download (unlike every other platform's CPython): no distributor -# ships a python.wasm with `wasmExports,wasmMemory` in -sEXPORTED_RUNTIME_METHODS, which is the one -# addition this library needs so its @WasmImport declarations have something to bind to. +# Why this is a build and not a download: no distributor ships a free-threaded pthreads python.wasm, +# and none with `wasmExports,wasmMemory` in -sEXPORTED_RUNTIME_METHODS, which is what the library's +# @WasmImport declarations bind to. # -# What separates this from a stock PEP 776 build (`Tools/wasm/emscripten build`), in order of how -# much work each is: +# What separates this from CPython's own driver defaults (`Platforms/emscripten build`): # -# 1. unwinding ABI -fwasm-exceptions -sSUPPORT_LONGJMP=wasm, at compile AND link. This is the one -# that gates wheel loading: python.wasm must export the __cpp_exception and -# __c_longjmp tags every pyemscripten_2026_0 side module imports. Without it: -# LinkError: Import "env" "__cpp_exception": tag import requires a WebAssembly.Tag -# 2. tag claim PYEMSCRIPTEN_PLATFORM_VERSION, which does not exist in CPython 3.14.2. -# `packaging` reads it to emit the platform tag. See the sysconfig patch below. -# 3. JS reachability wasmExports/wasmMemory/wasmTable in -sEXPORTED_RUNTIME_METHODS. Not -# ABI-sensitive; needed only so Kotlin has something to bind @WasmImport to. -# 4. NOT DONE lzma, zstd and OpenSSL are still missing. ABI-sensitive per the Pyodide flag -# list, but they did not gate the wheel tested (pydantic_core 2.48.0). +# 1. unwinding ABI -fwasm-exceptions -sSUPPORT_LONGJMP=wasm, at compile AND link: python.wasm must +# export the __cpp_exception and __c_longjmp tags pyemscripten_2026_0 side modules +# import. Without it: LinkError: Import "env" "__cpp_exception": tag import requires +# a WebAssembly.Tag +# 2. tag claim PYEMSCRIPTEN_PLATFORM_VERSION, which CPython 3.15.0 does not define either. The +# wheel tag becomes cp315-cp315t-pyemscripten_2026_0_wasm32; the cp315t ABI tag is +# what keeps those wheels apart from the GIL build's (agent proposal for pypackpack +# #82, not confirmed). +# 3. threads --disable-gil --enable-wasm-pthreads, -pthread at compile and link, +# -sPTHREAD_POOL_SIZE=8 (Thread.start() blocks until the thread runs, and a Worker +# cannot start while the JS thread that asked for it is blocked), +# -sMAXIMUM_MEMORY=2GB (a shared memory needs a maximum), libffi and mpdec rebuilt +# with -pthread (wasm-ld refuses non-atomic objects in a shared-memory link), and a +# free-threaded build Python. +# 4. trampoline Python/emscripten_trampoline.c's wasm-gc trampoline imports a non-shared memory, +# so under a shared memory it falls back to the JS trampoline (patch_trampoline). +# 5. _pm_upcall a built-in module (beside this script) that routes upcalls and proxy slots made on +# a pthread to the main runtime thread, where Kotlin runs; see its header. +# 6. JS reachability wasmExports/wasmMemory/wasmTable/addFunction/removeFunction in +# -sEXPORTED_RUNTIME_METHODS. Not ABI-sensitive; needed so Kotlin can bind. +# 7. no ppoll ac_cv_func_ppoll=no: 3.15's select.poll() prefers ppoll(), which Emscripten links +# as an ENOSYS stub, so poll() always raised and selectors fell back to select(). +# 8. NOT DONE lzma, zstd and OpenSSL are still missing (as in the 3.14.2 build this replaces). # # TRAP: the driver hardcodes CFLAGS=-DPY_CALL_TRAMPOLINE -sUSE_BZIP2 in its configure argv and # appends user args AFTER; autoconf takes the last assignment, so the full string must be repeated or # -DPY_CALL_TRAMPOLINE is silently dropped. # -# TRAP: the stdlib zip is not rebuilt by `make-host`. The build this script replaces was patched -# after its zip had been made, so the zip it shipped carried neither patch: under the library the -# interpreter reported PYEMSCRIPTEN_PLATFORM_VERSION = None. `zip` therefore always runs after the -# patches, and `verify` checks the zip, not only the build tree. +# TRAP: every Makefile edit goes into Makefile AND Makefile.pre. Adding _pm_upcall to +# Modules/Setup.local makes make re-run makesetup, which regenerates Makefile from Makefile.pre and +# silently drops an edit made to Makefile alone (pmp17's embedding probe: Module.wasmMemory undefined). # -# Emscripten is pinned to 5.0.3 because that is what pyemscripten_2026_0 specifies (Pyodide -# Makefile.envs at tag 314.0.4: PYODIDE_EMSCRIPTEN_VERSION ?= 5.0.3, PYODIDE_ABI_VERSION ?= 2026_0, -# PYVERSION ?= 3.14.2). +# TRAP: the stdlib zip is not rebuilt by `make-host`, so `zip` always runs after the patches, and +# `verify` checks the zip, not only the build tree. set -euo pipefail ROOT="$(cd "$(dirname "$0")/../../.." && pwd)" +HERE="$ROOT/python-multiplatform/scripts/wasm" CACHES="$ROOT/.caches" -CPYTHON_TAG=v3.14.2 -CPYTHON_COMMIT=df793163d5821791d4e7caf88885a2c11a107986 +CPYTHON_TAG=v3.15.0 +CPYTHON_COMMIT=d220409a13b77de7a6c30abe16ea90db01528edc EMSCRIPTEN_VERSION=5.0.3 PLATFORM_VERSION=2026_0 EMSDK="${EMSDK:-$CACHES/emsdk}" -CHECKOUT="${CPYTHON_CHECKOUT:-$CACHES/wasm-build/cpython314}" +CHECKOUT="${CPYTHON_CHECKOUT:-$CACHES/wasm-build/cpython315t}" RUNTIME_DIR="${WASM_RUNTIME_DIR:-$CACHES/wasm-runtime}" BUILD="$CHECKOUT/cross-build/wasm32-emscripten/build/python" -NATIVE_PYTHON="$CHECKOUT/cross-build/build/python.exe" -ZIP_NAME=python3.14.zip +PREFIX="$CHECKOUT/cross-build/wasm32-emscripten/prefix" +# The native build interpreter is `python` on Linux and `python.exe` on macOS (CPython's configure +# names it so on a case-insensitive volume, where `python` would collide with the `Python/` directory). +native_python() { + local d="$CHECKOUT/cross-build/build" + if [ -x "$d/python.exe" ]; then echo "$d/python.exe"; else echo "$d/python"; fi +} +ZIP_NAME=python3.15t.zip ZIP="${STDLIB_ZIP:-$BUILD/$ZIP_NAME}" ABI_FLAGS="-fwasm-exceptions -sSUPPORT_LONGJMP=wasm" +HOST_CFLAGS="-DPY_CALL_TRAMPOLINE -sUSE_BZIP2 $ABI_FLAGS -pthread" +HOST_LDFLAGS="$ABI_FLAGS -pthread -sPTHREAD_POOL_SIZE=8 -sMAXIMUM_MEMORY=2GB" # --- the wheels the suite loads ----------------------------------------------------------------------- -# `wasmJsTest/.../WasmCompiledWheelTest` imports a real compiled pyemscripten_2026_0 wheel and calls -# into it -- the claim the ABI flags above exist for. The wheels are not checked in; they are -# downloaded here by URL and accepted only with the sha256 below. Both pins were read from PyPI's -# JSON API (https://pypi.org/pypi///json, `urls[].digests.sha256`): -# -# pydantic-core 2.48.0 Rust/PyO3, cp314-cp314-pyemscripten_2026_0_wasm32 -- the compiled one -# typing-extensions 4.16.0 pure Python; pydantic-core 2.48.0 requires typing-extensions>=4.14.1 -# -# " ", one per line. +# `wasmJsTest/.../WasmCompiledWheelTest` imports a real compiled wheel and calls into it. Decision 10 +# (c) c1 (leader, 2026-11-26): it moves to a pypackpack-built cp315t wheel when pypackpack #82 produces +# one; until then the list is empty and the test reports a named skip, which fails under +# -PrequireWasmRuntime (never a silent pass). The cp314 pydantic-core wheel pinned for the 3.14.2 build +# cannot load into 3.15t. Format: " ", one per line. WHEELS_DIR="${WASM_WHEELS_DIR:-$CACHES/wasm-wheels}" -WHEELS=( - "pydantic_core-2.48.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl https://files.pythonhosted.org/packages/19/70/b7b9042d5e745d3893f8b5597a00727325d0f41dd5e5fd8875335d876770/pydantic_core-2.48.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl 4fc45a49334c54541cbc97bf416d9300b4b1d3b2840dfb079b1123dc3f9ef5a6" - "typing_extensions-4.16.0-py3-none-any.whl https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl 481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8" -) +WHEELS=() die() { echo "build-cpython: $*" >&2; exit 1; } @@ -105,8 +130,8 @@ ensure_emsdk() { # shellcheck disable=SC1091 source "$EMSDK/emsdk_env.sh" > /dev/null 2>&1 emcc --version | head -1 - emcc --version | head -1 | grep -q "$EMSCRIPTEN_VERSION" || - die "emcc is not $EMSCRIPTEN_VERSION; pyemscripten_2026_0 needs exactly that version" + emcc --version | head -1 | grep -q " $EMSCRIPTEN_VERSION " || + die "emcc is not $EMSCRIPTEN_VERSION; Decision 10 (b) pins exactly that version" } ensure_checkout() { @@ -118,6 +143,7 @@ ensure_checkout() { head="$(git -C "$CHECKOUT" rev-parse HEAD)" [ "$head" = "$CPYTHON_COMMIT" ] || die "$CHECKOUT is at $head, expected $CPYTHON_TAG ($CPYTHON_COMMIT)" + [ -d "$CHECKOUT/Platforms/emscripten" ] || die "no Platforms/emscripten in $CHECKOUT" } # --- 2a. PYEMSCRIPTEN_PLATFORM_VERSION has to survive sysconfig's Makefile parser -------------------- @@ -140,72 +166,136 @@ if "PYEMSCRIPTEN_PLATFORM_VERSION" not in t: PATCH } +# --- 4. call trampoline under shared memory ------------------------------------------------------------- +# Python/emscripten_trampoline.c instantiates a wasm-gc trampoline module in pre-run. It is compiled +# with -Wl,--import-memory and no -pthread, so it imports a NON-shared env.memory; giving it the shared +# wasmMemory of a pthread build is a link error, and the `new WebAssembly.Instance` call is outside the +# try block, so start-up throws. Its addFunction pointer would also exist only in the main thread's +# table. When the memory is shared, return 0, which selects the existing JS trampoline. Asserted, so an +# upstream change fails the build instead of silently skipping the patch. +patch_trampoline() { + python3 - "$CHECKOUT/Python/emscripten_trampoline.c" <<'PATCH' +import sys +from pathlib import Path +p = Path(sys.argv[1]); t = p.read_text() +marker = "pmp-175: shared memory" +if marker not in t: + old = "function getPyEMTrampolinePtr() {\n" + new = (old + + " // " + marker + ": the wasm-gc trampoline imports non-shared memory and its\n" + " // addFunction pointer is valid only on this thread; use the JS trampoline.\n" + " if (typeof SharedArrayBuffer !== \"undefined\" && wasmMemory.buffer instanceof SharedArrayBuffer) {\n" + " return 0;\n" + " }\n") + assert t.count(old) == 1, "getPyEMTrampolinePtr changed shape; re-check the patch" + p.write_text(t.replace(old, new)) + print("patched Python/emscripten_trampoline.c (shared memory -> JS trampoline)") +PATCH +} + # --- the native build Python, libffi and mpdec --------------------------------------------------------- -# `configure-host` asserts on the native build interpreter's lib.* directory and links against the -# wasm libffi/mpdec in the prefix, none of which exists in a fresh checkout. The tree this script -# was first run against had been built by the driver's own `build` beforehand, which is why only -# configure-host/make-host appeared here and a fresh checkout failed at configure-host. +# The build Python is free-threaded too. libffi and mpdec get -pthread through EMCC_CFLAGS (emcc appends +# it to every invocation), checked by the archives' target_features section ("+", 7, "atomics"). ensure_prerequisites() { - if [ ! -x "$NATIVE_PYTHON" ]; then + if [ ! -x "$(native_python)" ]; then ( cd "$CHECKOUT" && - python3 Tools/wasm/emscripten configure-build-python && - python3 Tools/wasm/emscripten make-build-python ) + python3 Platforms/emscripten configure-build-python -- --disable-gil && + python3 Platforms/emscripten make-build-python ) fi - if [ ! -f "$CHECKOUT/cross-build/wasm32-emscripten/prefix/lib/libffi.a" ]; then - ( cd "$CHECKOUT" && python3 Tools/wasm/emscripten make-libffi ) + "$(native_python)" -c 'import sysconfig; assert sysconfig.get_config_var("Py_GIL_DISABLED") == 1, "the build Python is not free-threaded"' + if [ ! -f "$PREFIX/lib/libffi.a" ]; then + ( cd "$CHECKOUT" && EMCC_CFLAGS="-pthread" python3 Platforms/emscripten make-libffi ) fi - if [ ! -f "$CHECKOUT/cross-build/wasm32-emscripten/prefix/lib/libmpdec.a" ]; then - ( cd "$CHECKOUT" && python3 Tools/wasm/emscripten make-mpdec ) + if [ ! -f "$PREFIX/lib/libmpdec.a" ]; then + ( cd "$CHECKOUT" && EMCC_CFLAGS="-pthread" python3 Platforms/emscripten make-mpdec ) fi + local lib + for lib in "$PREFIX/lib/libffi.a" "$PREFIX/lib/libmpdec.a"; do + python3 -c 'import sys; sys.exit(0 if b"+\x07atomics" in open(sys.argv[1], "rb").read() else 1)' "$lib" || + die "$lib was not compiled with atomics (-pthread); delete it and rebuild" + done } -# --- 2b + 3. Makefile edits, before the first link ---------------------------------------------------- -# Split in two because `stock` takes only the second: the platform claim is ABI, the runtime methods -# are not (neither name is in PEP 783's ABI-sensitive list) and the library cannot bind without them. +# --- 2b + 6. Makefile edits, before the first link ---------------------------------------------------- +# Both go into Makefile and Makefile.pre (see the TRAP above). Split in two because `stock` takes only +# the second: the platform claim is ABI, the runtime methods are not. patch_makefile() { patch_makefile_platform patch_makefile_reachability } patch_makefile_platform() { - python3 - "$BUILD/Makefile" "$PLATFORM_VERSION" <<'PATCH' + python3 - "$PLATFORM_VERSION" "$BUILD/Makefile" "$BUILD/Makefile.pre" <<'PATCH' import sys from pathlib import Path -p = Path(sys.argv[1]); version = sys.argv[2]; t = p.read_text() -if "\nPYEMSCRIPTEN_PLATFORM_VERSION" not in t: - i = t.index("CONFIGURE_CFLAGS=\t") - t = t[:i] + f"PYEMSCRIPTEN_PLATFORM_VERSION=\t{version}\n" + t[i:] - print(f"Makefile: PYEMSCRIPTEN_PLATFORM_VERSION={version}") -p.write_text(t) +version = sys.argv[1] +for arg in sys.argv[2:]: + p = Path(arg); t = p.read_text() + if "\nPYEMSCRIPTEN_PLATFORM_VERSION" not in t: + i = t.index("CONFIGURE_CFLAGS=\t") + t = t[:i] + f"PYEMSCRIPTEN_PLATFORM_VERSION=\t{version}\n" + t[i:] + print(f"{p.name}: PYEMSCRIPTEN_PLATFORM_VERSION={version}") + p.write_text(t) PATCH } patch_makefile_reachability() { - python3 - "$BUILD/Makefile" <<'PATCH' + python3 - "$BUILD/Makefile" "$BUILD/Makefile.pre" <<'PATCH' +import re import sys from pathlib import Path -p = Path(sys.argv[1]); t = p.read_text() -old = "-sEXPORTED_RUNTIME_METHODS=FS,callMain,ENV,HEAPU32,TTY" -new = old + ",wasmExports,wasmMemory,wasmTable,addFunction,removeFunction" -if old in t and "wasmExports" not in t: - t = t.replace(old, new) - print("Makefile: runtime methods exposed for @WasmImport") -assert "wasmExports" in t, "EXPORTED_RUNTIME_METHODS changed shape; re-check the patch" -p.write_text(t) +RUNTIME = ("wasmExports", "wasmMemory", "wasmTable", "addFunction", "removeFunction") +def add(m): + items = m.group(2).split(",") + return m.group(1) + ",".join(items + [x for x in RUNTIME if x not in items]) +for arg in sys.argv[1:]: + p = Path(arg); t = p.read_text() + t, n = re.subn(r"(-sEXPORTED_RUNTIME_METHODS=)(\S+)", add, t) + assert n >= 1, f"no -sEXPORTED_RUNTIME_METHODS= in {p.name}; the link line changed shape, re-check the patch" + p.write_text(t) + print(f"{p.name}: runtime methods exposed for @WasmImport in {n} list(s)") PATCH } +# --- 5. the _pm_upcall built-in module ------------------------------------------------------------------ +# Built in statically through the build tree's Modules/Setup.local (configure leaves an empty one; +# makesetup finds the source under $(srcdir)/Modules). +add_pm_upcall() { + cp "$HERE/_pm_upcall.c" "$CHECKOUT/Modules/_pm_upcall.c" + grep -q '^_pm_upcall ' "$BUILD/Modules/Setup.local" 2>/dev/null || + printf '*static*\n_pm_upcall _pm_upcall.c\n' >> "$BUILD/Modules/Setup.local" + # make re-runs makesetup only when Setup.local is NEWER than Makefile, and the Makefile patches above + # are written within the same second on a fast machine, so the module was silently left out (seen + # locally: verify found no pm_* exports). Date the Makefile back so the regeneration always happens; + # it rebuilds Makefile from the patched Makefile.pre. + python3 -c 'import os, sys, time; t = time.time() - 10; os.utime(sys.argv[1], (t, t))' "$BUILD/Makefile" +} + do_build() { ensure_emsdk ensure_checkout + patch_trampoline ensure_prerequisites patch_sysconfig ( cd "$CHECKOUT" && - python3 Tools/wasm/emscripten configure-host --clean \ - "CFLAGS=-DPY_CALL_TRAMPOLINE -sUSE_BZIP2 $ABI_FLAGS" \ - "LDFLAGS=$ABI_FLAGS" ) + python3 Platforms/emscripten configure-host --clean --host-runner node -- \ + "CFLAGS=$HOST_CFLAGS" \ + "LDFLAGS=$HOST_LDFLAGS" \ + ac_cv_func_ppoll=no \ + --disable-gil --enable-wasm-pthreads ) + # ac_cv_func_ppoll=no: 3.15's select.poll() calls ppoll() whenever configure finds it, and + # Emscripten links ppoll but stubs it (system/lib/libc/emscripten_syscall_stubs.c, UNIMPLEMENTED), + # so every poll().poll() raised OSError ENOSYS and selectors fell back to SelectSelector (seen + # locally: WasmSelectorsImportTest). Without ppoll it calls poll(), which Emscripten implements. + # CPython's config.site-wasm32-emscripten does not list it. + ! grep -Eq '^#define HAVE_PPOLL 1' "$BUILD/pyconfig.h" || + die "configure still found ppoll(); Emscripten's is a stub that returns ENOSYS" + grep -Eq '^CONFIGURE_LDFLAGS_NODIST=.*-sUSE_PTHREADS' "$BUILD/Makefile" || + die "configure did not enable wasm pthreads (no -sUSE_PTHREADS in LDFLAGS_NODIST)" + grep -Eq '^ABIFLAGS=[[:space:]]*t$' "$BUILD/Makefile" || die "host Makefile ABIFLAGS is not t" patch_makefile - ( cd "$CHECKOUT" && python3 Tools/wasm/emscripten make-host ) + add_pm_upcall + ( cd "$CHECKOUT" && python3 Platforms/emscripten make-host ) } # --- the stdlib zip --------------------------------------------------------------------------------- @@ -216,7 +306,7 @@ do_build() { mk_var() { sed -n -E "s/^$1=[[:space:]]*(.*)$/\1/p" "$BUILD/Makefile" | head -1; } do_zip() { - [ -x "$NATIVE_PYTHON" ] || die "no native build interpreter at $NATIVE_PYTHON; run a full build first" + [ -x "$(native_python)" ] || die "no native build interpreter at $(native_python); run a full build first" [ -f "$BUILD/pybuilddir.txt" ] || die "no $BUILD/pybuilddir.txt; run a full build first" local host_platform machdep multiarch abiflags builddir work host_platform="$(mk_var _PYTHON_HOST_PLATFORM)" @@ -237,7 +327,7 @@ do_zip() { _PYTHON_SYSCONFIGDATA_PATH="$BUILD/$builddir" \ PYTHONPATH="$CHECKOUT/Lib" \ PYTHONPYCACHEPREFIX="$work/pycache" \ - "$NATIVE_PYTHON" "$CHECKOUT/Tools/wasm/emscripten/wasm_assets.py" \ + "$(native_python)" "$CHECKOUT/Platforms/emscripten/wasm_assets.py" \ --buildroot "$work" --prefix / -o "$ZIP" ) rm -rf "$work" } @@ -260,15 +350,60 @@ console.log(tags.join(",")); ' "$1" } +# Prints the memory python.wasm uses and fails unless it is shared with a declared maximum. +check_shared_memory() { + node - "$1" <<'NODE' +const b = require("fs").readFileSync(process.argv[2]); +const leb = (i) => { let r = 0, s = 0; for (;;) { const x = b[i++]; r += (x & 0x7f) * 2 ** s; s += 7; if (!(x & 0x80)) return [r, i]; } }; +const str = (i) => { let n; [n, i] = leb(i); return [b.slice(i, i + n).toString(), i + n]; }; +const limits = (i) => { const flags = b[i++]; let min, max = null; [min, i] = leb(i); if (flags & 1) [max, i] = leb(i); return [{ flags, min, max }, i]; }; +let i = 8, mem = null; +while (i < b.length && !mem) { + const id = b[i++]; let size; [size, i] = leb(i); const end = i + size; + if (id === 2) { let n, j; [n, j] = leb(i); + for (let k = 0; k < n && !mem; k++) { let m, f; [m, j] = str(j); [f, j] = str(j); const kind = b[j++]; + if (kind === 0) { [, j] = leb(j); } + else if (kind === 1) { j++; [, j] = limits(j); } + else if (kind === 2) { let l; [l, j] = limits(j); mem = { where: `import ${m}.${f}`, ...l }; } + else if (kind === 3) { j += 2; } + else if (kind === 4) { j++; [, j] = leb(j); } + else throw new Error(`unknown import kind ${kind}`); } } + if (id === 5) { let j; [, j] = leb(i); const [l] = limits(j); mem = { where: "defined", ...l }; } + i = end; +} +if (!mem) { console.error("no memory found"); process.exit(1); } +const shared = (mem.flags & 2) !== 0; +console.log(`python.wasm memory: ${mem.where} shared=${shared} min=${mem.min} max=${mem.max} pages`); +process.exit(shared && mem.max !== null ? 0 : 1); +NODE +} + do_verify() { [ -f "$BUILD/python.wasm" ] || die "no $BUILD/python.wasm" [ -f "$ZIP" ] || die "no $ZIP" - local tags + local tags name tags="$(exported_tags "$BUILD/python.wasm")" echo "exported wasm tags: ${tags:-NONE}" for t in __cpp_exception __c_longjmp; do case ",$tags," in *",$t,"*) ;; *) die "missing tag $t: unwinding ABI NOT matched" ;; esac done + check_shared_memory "$BUILD/python.wasm" || die "python.wasm has no shared memory with a maximum" + grep -q '^#define Py_GIL_DISABLED 1' "$BUILD/pyconfig.h" || die "pyconfig.h does not define Py_GIL_DISABLED" + # The link must really export the runtime names (Emscripten writes Module["wasmMemory"]=wasmMemory + # only for an exported name); an edit lost to a Makefile regeneration fails here. + for name in wasmExports wasmMemory wasmTable addFunction removeFunction; do + grep -q "Module\[\"$name\"\]=" "$BUILD/python.mjs" || + die "python.mjs does not export Module.$name (the EXPORTED_RUNTIME_METHODS patch was lost)" + done + node - "$BUILD/python.wasm" <<'NODE' || die "python.wasm does not export the _pm_upcall functions" +const m = new WebAssembly.Module(require("fs").readFileSync(process.argv[2])); +const names = new Set(WebAssembly.Module.exports(m).map((e) => e.name)); +const want = ["pm_upcall_dispatch", "pm_upcall_set_target", "pm_upcall_dispatch_index", + "pm_tp_traverse", "pm_tp_clear", "pm_tp_dealloc", "pm_proxy_slot_index", "pm_proxy_set_slot_target"]; +const missing = want.filter((n) => !names.has(n)); +console.log(`python.wasm _pm_upcall exports: ${want.filter((n) => names.has(n)).join(",")}${missing.length ? " MISSING " + missing.join(",") : ""}`); +process.exit(missing.length ? 1 : 0); +NODE python3 - "$ZIP" "$PLATFORM_VERSION" <<'CHECK' import sys, zipfile z = zipfile.ZipFile(sys.argv[1]); version = sys.argv[2] @@ -278,14 +413,48 @@ assert data, "the stdlib zip has no _sysconfigdata module" blob = z.read(data[0]) assert b"PYEMSCRIPTEN_PLATFORM_VERSION" in blob and version.encode() in blob, \ f"{data[0]} in the zip does not carry PYEMSCRIPTEN_PLATFORM_VERSION={version}: the zip predates the Makefile patch" +assert b"Py_GIL_DISABLED" in blob, f"{data[0]} in the zip has no Py_GIL_DISABLED" assert b"PYEMSCRIPTEN_PLATFORM_VERSION" in z.read("sysconfig/__init__.pyc"), \ "sysconfig in the zip lacks the _ALWAYS_STR patch: the tag would read pyemscripten_20260" print(f"stdlib zip: {data[0]} claims {version}; sysconfig keeps it a str") CHECK } +# GIL off at run time, four real threads, upcalls and proxy slots from Python threads, under the build +# tree's python.sh (Python's main thread is a pthread there, -sPROXY_TO_PTHREAD). +do_smoke() { + [ -x "$BUILD/python.sh" ] || die "no $BUILD/python.sh; run a full build first" + local out + out="$(dirname "$ZIP")/smoke.log" + "$BUILD/python.sh" "$HERE/smoke.py" > "$out" 2>&1 || { cat "$out"; die "smoke.py failed"; } + cat "$out" + grep -q '^FT-WASM-SMOKE-OK ' "$out" || die "smoke.py did not print FT-WASM-SMOKE-OK" +} + +# Python without main, the way the library runs it, against the staged runtime: a shared memory a +# Kotlin module can import, Py_Initialize from the JS main thread, threads, and smoke.py in that layout. +# The probe runs Python with PYTHONHOME at its root and its threads read lib/python3.15t/os.py as a +# file, so the root gets the source standard library (without test/) and the build's sysconfigdata. +do_probe() { + [ -f "$RUNTIME_DIR/python.mjs" ] || die "no staged runtime in $RUNTIME_DIR; run stage first" + local root lib + root="$(mktemp -d "$(dirname "$ZIP")/probe.XXXXXX")" + lib="$root/lib/python3.15t" + cp "$RUNTIME_DIR/python.mjs" "$RUNTIME_DIR/python.wasm" "$root/" + mkdir -p "$lib/lib-dynload" + tar -C "$CHECKOUT/Lib" --exclude='./test' --exclude='__pycache__' -cf - . | tar -C "$lib" -xf - + cp "$BUILD/$(cat "$BUILD/pybuilddir.txt")"/_sysconfigdata_*.py "$lib/" + node "$HERE/embed-probe.mjs" "$root" > "$root.log" 2>&1 || true + cat "$root.log" + grep -q '^FT-WASM-EMBED-PROBE-OK$' "$root.log" || die "embedding probe failed (log: $root.log)" + rm -rf "$root" "$root.log" +} + do_stage() { mkdir -p "$RUNTIME_DIR" + # A runtime directory left by the 3.14.2 build holds python3.14.zip; two zips would leave the + # staging to pick one by directory order. + rm -f "$RUNTIME_DIR"/python*.zip cp "$BUILD/python.wasm" "$BUILD/python.mjs" "$RUNTIME_DIR/" cp "$ZIP" "$RUNTIME_DIR/$ZIP_NAME" echo "staged into $RUNTIME_DIR" @@ -300,6 +469,10 @@ sha256_of() { do_wheels() { mkdir -p "$WHEELS_DIR" local entry name url sha dest got + if [ "${#WHEELS[@]}" -eq 0 ]; then + echo "no wasm wheels pinned: WasmCompiledWheelTest waits on a pypackpack-built cp315t wheel (pypackpack #82, Decision 10 c1)" + return 0 + fi for entry in "${WHEELS[@]}"; do read -r name url sha <<< "$entry" dest="$WHEELS_DIR/$name" @@ -320,33 +493,37 @@ do_wheels() { } # --- stock: the negative control --------------------------------------------------------------------- -# CPython's own PEP 776 build, with exactly one addition: the runtime methods the library binds -# through (patch_makefile_reachability). No unwinding ABI, no PYEMSCRIPTEN_PLATFORM_VERSION, no -# sysconfig patch. Point the suite at it and the two tests that exist for the ABI must fail: +# CPython 3.15.0 built by its own driver's defaults (GIL, no pthreads), with exactly one addition: the +# runtime methods the library binds through (patch_makefile_reachability). No unwinding ABI, no +# PYEMSCRIPTEN_PLATFORM_VERSION, no sysconfig patch. Point the suite at it and the test that exists for +# the ABI must fail: # # ./gradlew :python-multiplatform:wasmJsNodeTest -PwasmPythonDir=.caches/wasm-runtime-stock \ -# --tests '*WasmInterpreterAbiTest*' --tests '*WasmCompiledWheelTest*' +# --tests '*WasmInterpreterAbiTest*' # # WasmInterpreterAbiTest no __cpp_exception tag; PYEMSCRIPTEN_PLATFORM_VERSION is None -# WasmCompiledWheelTest LinkError: ... "__cpp_exception": tag import requires a WebAssembly.Tag # # A separate checkout, not a second build directory: configure-host --clean wipes the one build # directory a checkout has, and the sysconfig patch lives in the checkout's Lib/. do_stock() { - CHECKOUT="${STOCK_CPYTHON_CHECKOUT:-$CACHES/wasm-build/cpython314-stock}" + CHECKOUT="${STOCK_CPYTHON_CHECKOUT:-$CACHES/wasm-build/cpython315-stock}" RUNTIME_DIR="${STOCK_WASM_RUNTIME_DIR:-$CACHES/wasm-runtime-stock}" BUILD="$CHECKOUT/cross-build/wasm32-emscripten/build/python" - NATIVE_PYTHON="$CHECKOUT/cross-build/build/python.exe" + ZIP_NAME=python3.15.zip ZIP="$BUILD/$ZIP_NAME" ensure_emsdk ensure_checkout if grep -q PYEMSCRIPTEN_PLATFORM_VERSION "$CHECKOUT/Lib/sysconfig/__init__.py"; then die "$CHECKOUT carries the ABI build's sysconfig patch; the stock control needs a clean checkout" fi - ensure_prerequisites - ( cd "$CHECKOUT" && python3 Tools/wasm/emscripten configure-host --clean ) + if [ ! -x "$(native_python)" ]; then + ( cd "$CHECKOUT" && python3 Platforms/emscripten configure-build-python && + python3 Platforms/emscripten make-build-python ) + fi + ( cd "$CHECKOUT" && python3 Platforms/emscripten make-libffi && python3 Platforms/emscripten make-mpdec ) + ( cd "$CHECKOUT" && python3 Platforms/emscripten configure-host --clean --host-runner node ) patch_makefile_reachability - ( cd "$CHECKOUT" && python3 Tools/wasm/emscripten make-host ) + ( cd "$CHECKOUT" && python3 Platforms/emscripten make-host ) do_zip # The control is only a control if it really lacks what the ABI build verifies. local tags @@ -359,12 +536,14 @@ do_stock() { } case "${1:-all}" in - all) do_build; do_zip; do_verify; do_stage; do_wheels ;; + all) do_build; do_zip; do_verify; do_smoke; do_stage; do_probe; do_wheels ;; build) do_build ;; zip) do_zip ;; verify) do_verify ;; + smoke) do_smoke ;; stage) do_stage ;; + probe) do_probe ;; wheels) do_wheels ;; stock) do_stock ;; - *) die "unknown command '$1' (all | build | zip | verify | stage | wheels | stock)" ;; + *) die "unknown command '$1' (all | build | zip | verify | smoke | stage | probe | wheels | stock)" ;; esac diff --git a/.github/scripts/ft-wasm/embed-probe.mjs b/python-multiplatform/scripts/wasm/embed-probe.mjs similarity index 100% rename from .github/scripts/ft-wasm/embed-probe.mjs rename to python-multiplatform/scripts/wasm/embed-probe.mjs diff --git a/.github/scripts/ft-wasm/smoke.py b/python-multiplatform/scripts/wasm/smoke.py similarity index 96% rename from .github/scripts/ft-wasm/smoke.py rename to python-multiplatform/scripts/wasm/smoke.py index 21d86cc40..e796c3d86 100644 --- a/.github/scripts/ft-wasm/smoke.py +++ b/python-multiplatform/scripts/wasm/smoke.py @@ -14,6 +14,11 @@ assert sysconfig.get_config_var("Py_GIL_DISABLED") == 1, "not a free-threaded build" assert sys._is_gil_enabled() is False, "the GIL is enabled at run time" +# select.poll() must reach Emscripten's poll(), not its ppoll() stub (ENOSYS); build-cpython.sh +# configures with ac_cv_func_ppoll=no. selectors picks PollSelector only when this call works. +import select +assert select.poll().poll(0) == [], "select.poll().poll(0) did not return []" + N_THREADS = 4 N_ITER = 200_000 results = [None] * N_THREADS diff --git a/python-multiplatform/src/commonMain/kotlin/python/multiplatform/EmbeddedPythonBuild.kt b/python-multiplatform/src/commonMain/kotlin/python/multiplatform/EmbeddedPythonBuild.kt index b383d0f51..bc6b13c3e 100644 --- a/python-multiplatform/src/commonMain/kotlin/python/multiplatform/EmbeddedPythonBuild.kt +++ b/python-multiplatform/src/commonMain/kotlin/python/multiplatform/EmbeddedPythonBuild.kt @@ -9,7 +9,8 @@ package python.multiplatform * option. Baseline is CPython 3.15t." The desktop half landed first (leader, 2026-11-13: "flip the * desktop default to 3.15t now, before the #377 alpha03 release"); Android, androidNative and iOS * followed under #328 with the project's own 3.15t builds (release `cpython-t-mobile`; leader - * 2026-11-13: no opt-in flag on mobile). wasm still embeds a GIL build until #175. So: + * 2026-11-13: no opt-in flag on mobile). wasm followed under #175 with the project's own 3.15t + * built with pthreads (`scripts/wasm/build-cpython.sh`; leader, Decision 10 (a) a1, 2026-11-26). So: * * | Source set | Targets | Embeds | * |---------------------|---------------------------------|---------------| @@ -18,13 +19,13 @@ package python.multiplatform * | `androidMain` | Android (ART) | 3.15t | * | `artMain` | `androidNativeArm64`, `X64` | 3.15t | * | `iosMain` | iOS | 3.15t | - * | `wasmJsMain` | `wasmJs` | GIL | + * | `wasmJsMain` | `wasmJs` | 3.15t | * * It used to be one `BuildConfig.pythonFreeThreaded` shared by every target, which could not * express the transition: flipping it for desktop made Android look for `lib/python3.15t`, a - * directory its GIL prefix did not have. With every non-wasm platform free-threaded it stays an - * `expect`, because wasm is still the exception (agent proposal, not confirmed: drop the - * `expect` once #175 makes wasm free-threaded too). A plain (non-`inline`) `expect val`, so the + * directory its GIL prefix did not have. Every platform is free-threaded since #175, and it stays + * an `expect` for now (agent proposal, not confirmed: collapse it to a constant in a follow-up; + * the desktop and wasm cycle-collection tests still branch on it). A plain (non-`inline`) `expect val`, so the * intermediate-source-set crash in `commonMain/README.md` does not apply. * * Everything CPython names after itself follows from this through [Versions.abiFlags]: the shared diff --git a/python-multiplatform/src/commonMain/kotlin/python/multiplatform/Versions.kt b/python-multiplatform/src/commonMain/kotlin/python/multiplatform/Versions.kt index ef50c3d80..c7ac2cf2f 100644 --- a/python-multiplatform/src/commonMain/kotlin/python/multiplatform/Versions.kt +++ b/python-multiplatform/src/commonMain/kotlin/python/multiplatform/Versions.kt @@ -52,7 +52,7 @@ class Versions private constructor(val versionString: String) { * * This is a property of the *build*, not of the version -- 3.15 ships in both flavours out of * the same source tree -- and of the *platform*: desktop (JVM and Kotlin/Native), Android, - * androidNative and iOS embed 3.15t (issues #158, #328), wasm a GIL build until #175. So it + * androidNative, iOS and wasm embed 3.15t (issues #158, #328, #175). So it * comes from the per-platform [embedsFreeThreadedPython] rather than from [versionString]. */ val abiFlags: String diff --git a/python-multiplatform/src/commonMain/kotlin/python/multiplatform/ffi/Python3.kt b/python-multiplatform/src/commonMain/kotlin/python/multiplatform/ffi/Python3.kt index e99dc9f68..f9028edae 100644 --- a/python-multiplatform/src/commonMain/kotlin/python/multiplatform/ffi/Python3.kt +++ b/python-multiplatform/src/commonMain/kotlin/python/multiplatform/ffi/Python3.kt @@ -881,8 +881,9 @@ def __pmp_run_file__(path, argv): * released since the previous one, so a workload that never drops a wrapper never pays. * * Which build that is depends on the platform ([python.multiplatform.embedsFreeThreadedPython]): - * desktop, Android, androidNative and iOS embed 3.15t (issues #158, #328), so this defaults to - * on there; wasm embeds a GIL build until #175, so it defaults to off there. + * desktop, Android, androidNative, iOS and wasm embed 3.15t (issues #158, #328, #175), so this + * defaults to on everywhere the library ships today; the GIL branch below is kept for the + * `expect`'s other value. * * Defaults to on for free-threaded builds, where deferred release is the defect described on * [drainPendingReleases], a build with the global lock frees a *plain* reference the diff --git a/python-multiplatform/src/commonTest/kotlin/python/multiplatform/VersionsTest.kt b/python-multiplatform/src/commonTest/kotlin/python/multiplatform/VersionsTest.kt index fc49790de..e9895c58f 100644 --- a/python-multiplatform/src/commonTest/kotlin/python/multiplatform/VersionsTest.kt +++ b/python-multiplatform/src/commonTest/kotlin/python/multiplatform/VersionsTest.kt @@ -15,10 +15,10 @@ import kotlin.test.assertTrue * * These assertions are written against the per-platform [embedsFreeThreadedPython] rather than * hard-coding one flavour, because the flavour differs by platform: desktop, Android, - * androidNative and iOS embed 3.15t (issues #158, #328), wasm a GIL build until #175. The platform + * androidNative, iOS and wasm embed 3.15t (issues #158, #328, #175). The platform * test source sets pin the literal value for their platform (`DesktopFreeThreadedBuildTest`, * `DesktopNativeFreeThreadedBuildTest`, `AndroidFreeThreadedBuildTest`, - * `AndroidNativeFreeThreadedBuildTest`, `IosFreeThreadedBuildTest`, `WasmGilBuildTest`), which is + * `AndroidNativeFreeThreadedBuildTest`, `IosFreeThreadedBuildTest`, `WasmFreeThreadedBuildTest`), which is * what a wrong actual would fail. */ class VersionsTest { diff --git a/python-multiplatform/src/desktopTest/kotlin/python/multiplatform/DesktopFreeThreadedBuildTest.kt b/python-multiplatform/src/desktopTest/kotlin/python/multiplatform/DesktopFreeThreadedBuildTest.kt index f8533abaf..d5104d756 100644 --- a/python-multiplatform/src/desktopTest/kotlin/python/multiplatform/DesktopFreeThreadedBuildTest.kt +++ b/python-multiplatform/src/desktopTest/kotlin/python/multiplatform/DesktopFreeThreadedBuildTest.kt @@ -20,7 +20,7 @@ import kotlin.test.assertTrue * * What this cannot find: what Android, androidNative, iOS and wasm embed. Their literal values are * pinned in their own test source sets (`AndroidFreeThreadedBuildTest`, - * `AndroidNativeFreeThreadedBuildTest`, `IosFreeThreadedBuildTest`, `WasmGilBuildTest`). + * `AndroidNativeFreeThreadedBuildTest`, `IosFreeThreadedBuildTest`, `WasmFreeThreadedBuildTest`). */ class DesktopFreeThreadedBuildTest { diff --git a/python-multiplatform/src/wasmJsMain/README.md b/python-multiplatform/src/wasmJsMain/README.md index 360880eb5..474a34e67 100644 --- a/python-multiplatform/src/wasmJsMain/README.md +++ b/python-multiplatform/src/wasmJsMain/README.md @@ -1,9 +1,14 @@ # wasmJsMain, rules -Kotlin/Wasm reaching CPython 3.14 built for `wasm32-emscripten`, through `@WasmImport` against a +Kotlin/Wasm reaching free-threaded CPython 3.15t built with pthreads for `wasm32-emscripten` +(`python-multiplatform/scripts/wasm/build-cpython.sh`, #175), through `@WasmImport` against a **shared linear memory**. Not a JavaScript bridge: there is no JS frame in either the call path or the data path. +That the loaded interpreter really is free-threaded (`t` ABI flags, `Py_GIL_DISABLED`, +`sys._is_gil_enabled()` false) is `WasmFreeThreadedBuildTest`; that a shared-memory runtime refuses to +boot in a page that is not cross-origin isolated (SPEC T-8) is `WasmCrossOriginIsolationTest`. + Everything below is measured. The standalone `wasm-experiment/` that first took the measurements was retired into this source set and `python-multiplatform/scripts/wasm/` (it remains in git history: `git log -- wasm-experiment`); `docs/platforms/wasm-design.md` holds the current decisions and numbers, and diff --git a/python-multiplatform/src/wasmJsMain/kotlin/python/multiplatform/EmbeddedPythonBuild.wasmJs.kt b/python-multiplatform/src/wasmJsMain/kotlin/python/multiplatform/EmbeddedPythonBuild.wasmJs.kt index 798ce6f03..bfc176abb 100644 --- a/python-multiplatform/src/wasmJsMain/kotlin/python/multiplatform/EmbeddedPythonBuild.wasmJs.kt +++ b/python-multiplatform/src/wasmJsMain/kotlin/python/multiplatform/EmbeddedPythonBuild.wasmJs.kt @@ -1,4 +1,7 @@ package python.multiplatform -/** wasmJs runs a GIL CPython built for wasm32-emscripten until #175. See the `expect` in commonMain. */ -internal actual val embedsFreeThreadedPython: Boolean = false +/** + * wasmJs embeds free-threaded CPython 3.15t built for wasm32-emscripten with pthreads + * (`scripts/wasm/build-cpython.sh`, #175). See the `expect` in commonMain. + */ +internal actual val embedsFreeThreadedPython: Boolean = true diff --git a/python-multiplatform/src/wasmJsMain/resources/cpython.mjs b/python-multiplatform/src/wasmJsMain/resources/cpython.mjs index 665487ad5..3e5f42803 100644 --- a/python-multiplatform/src/wasmJsMain/resources/cpython.mjs +++ b/python-multiplatform/src/wasmJsMain/resources/cpython.mjs @@ -1,4 +1,4 @@ -// Boots the CPython 3.14.2 Emscripten build and re-exports its raw wasm functions as ES module +// Boots the free-threaded CPython 3.15.0 Emscripten build (3.15t with pthreads, #175) and re-exports its raw wasm functions as ES module // bindings, which is the shape `@WasmImport(module, name)` resolves against. // // Two settings in CPython's link line make this possible, neither of them in PEP 783's @@ -95,10 +95,14 @@ function installStdlibZip(Module, bytes) { const versionInt = Module.HEAPU32[Module._Py_Version >>> 2]; const major = (versionInt >>> 24) & 0xff; const minor = (versionInt >>> 16) & 0xff; + // getpath's landmark carries the ABI thread flag: lib/python315t.zip and lib/python3.15t for the + // free-threaded build, lib/python315.zip for a GIL one. Py_Version does not say which, so the + // flag is read off the staged zip's name (python3.15t.zip), which the build names after it. + const abiThread = /t\.zip$/.test(String(STDLIB_ZIP_URL)) ? "t" : ""; // Without this, getpath complains that it cannot find exec-prefix. It is a marker directory // only; this build has no dynamically loaded stdlib extensions. - Module.FS.mkdirTree(`/lib/python${major}.${minor}/lib-dynload/`); - Module.FS.writeFile(`/lib/python${major}${minor}.zip`, new Uint8Array(bytes), { canOwn: true }); + Module.FS.mkdirTree(`/lib/python${major}.${minor}${abiThread}/lib-dynload/`); + Module.FS.writeFile(`/lib/python${major}${minor}${abiThread}.zip`, new Uint8Array(bytes), { canOwn: true }); } // The Node settings. NODEFS still mounts the real filesystem -- tests reach host paths through it -- @@ -597,7 +601,10 @@ function readCString(ptr) { const heap = new Uint8Array(M.wasmMemory.buffer); let end = ptr; while (heap[end] !== 0) end++; - return decoder.decode(heap.subarray(ptr, end)); + // slice, not subarray: the memory is a SharedArrayBuffer on the 3.15t pthreads build, and a + // browser's TextDecoder rejects a view of shared memory ("must not be shared"); node accepts it, + // so only wasmJsBrowserTest saw this. The copy is the length of one C name. + return decoder.decode(heap.slice(ptr, end)); } export function pmpRegisterUpcall(namePtr) { @@ -618,7 +625,7 @@ export function pmpRegisterUpcall(namePtr) { } // Upcalls from Python threads (#175 step 2). A free-threaded runtime built with the `_pm_upcall` -// module (.github/scripts/ft-wasm/_pm_upcall.c) exports a dispatcher whose table index is the +// module (python-multiplatform/scripts/wasm/_pm_upcall.c) exports a dispatcher whose table index is the // same in every pthread Worker; an index from pmpRegisterUpcall exists only in the main thread's // table. Optional, so -1 (and a no-op) on a runtime without it, which keeps today's direct entry. export function pmpUpcallDispatchIndex() { diff --git a/python-multiplatform/src/wasmJsTest/kotlin/python/multiplatform/WasmFreeThreadedBuildTest.kt b/python-multiplatform/src/wasmJsTest/kotlin/python/multiplatform/WasmFreeThreadedBuildTest.kt new file mode 100644 index 000000000..65c39431a --- /dev/null +++ b/python-multiplatform/src/wasmJsTest/kotlin/python/multiplatform/WasmFreeThreadedBuildTest.kt @@ -0,0 +1,37 @@ +package python.multiplatform + +import python.multiplatform.ffi.PythonTestFixture +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * SPEC T-1 (issue #175): wasmJs embeds the free-threaded CPython 3.15t with pthreads, built by + * `python-multiplatform/scripts/wasm/build-cpython.sh` (Decision 10 a1, leader 2026-11-26). + * + * Red before the change: `embedsFreeThreadedPython` was `false` in `wasmJsMain`, so `abiFlags` was `""`, + * and the staged runtime was the 3.14.2 GIL build. (This replaces `WasmGilBuildTest`, which pinned the + * GIL build until #175.) + */ +class WasmFreeThreadedBuildTest { + + @Test + fun wasmReportsTheFreeThreadedAbi() { + val v = Versions.currentVersion + assertEquals("t", v.abiFlags, "wasmJs embeds CPython ${v.compactVersionString}t (#175)") + assertEquals(v.compactVersionString + "t", v.taggedVersionString) + } + + @Test + fun theLoadedInterpreterIsReallyFreeThreaded() = PythonTestFixture.withInterpreter { + assertEquals( + "1", + PythonTestFixture.eval("__import__('sysconfig').get_config_var('Py_GIL_DISABLED')").toString(), + "the staged python.wasm is a GIL build; it must be the free-threaded one (#175)", + ) + assertEquals( + "False", + PythonTestFixture.eval("__import__('sys')._is_gil_enabled()").toString(), + "the GIL is enabled at run time; the free-threaded build must run without it (#175)", + ) + } +} diff --git a/python-multiplatform/src/wasmJsTest/kotlin/python/multiplatform/WasmGilBuildTest.kt b/python-multiplatform/src/wasmJsTest/kotlin/python/multiplatform/WasmGilBuildTest.kt deleted file mode 100644 index e634832d1..000000000 --- a/python-multiplatform/src/wasmJsTest/kotlin/python/multiplatform/WasmGilBuildTest.kt +++ /dev/null @@ -1,22 +0,0 @@ -package python.multiplatform - -import kotlin.test.Test -import kotlin.test.assertEquals - -/** - * Issue #158 moved desktop to the free-threaded CPython 3.15t, and #328 moved Android, androidNative - * and iOS; wasmJs still embeds the GIL build until #175. This pins that neither change leaked here. - * - * Not red before the change: wasmJs was GIL before and is GIL after. It is the guard against the - * naive implementation (flipping one shared `BuildConfig.pythonFreeThreaded`), under which - * `abiFlags` reads `"t"` here and the runtime looks for a `python3.15t` that wasmJs does not ship. - */ -class WasmGilBuildTest { - - @Test - fun wasmStillReportsTheGilAbi() { - val v = Versions.currentVersion - assertEquals("", v.abiFlags, "wasmJs embeds the GIL CPython until #175") - assertEquals(v.compactVersionString, v.taggedVersionString) - } -} diff --git a/python-multiplatform/src/wasmJsTest/kotlin/python/multiplatform/browser/WasmBrowserRuntimeTest.kt b/python-multiplatform/src/wasmJsTest/kotlin/python/multiplatform/browser/WasmBrowserRuntimeTest.kt index 60ef5ca95..b6c9fa8f7 100644 --- a/python-multiplatform/src/wasmJsTest/kotlin/python/multiplatform/browser/WasmBrowserRuntimeTest.kt +++ b/python-multiplatform/src/wasmJsTest/kotlin/python/multiplatform/browser/WasmBrowserRuntimeTest.kt @@ -95,7 +95,8 @@ class WasmBrowserRuntimeTest { """ import sys, json, os assert sys.prefix == '/', 'sys.prefix is ' + sys.prefix - zip_name = '/lib/python%d%d.zip' % sys.version_info[:2] + # getpath's landmark carries the ABI flags: /lib/python315t.zip on 3.15t. + zip_name = '/lib/python%d%d%s.zip' % (*sys.version_info[:2], sys.abiflags) assert os.path.exists(zip_name), zip_name + ' is not in the filesystem' assert json.__file__.startswith(zip_name), json.__file__ """.trimIndent() diff --git a/python-multiplatform/src/wasmJsTest/kotlin/python/multiplatform/ref/WasmCycleCollectionTest.kt b/python-multiplatform/src/wasmJsTest/kotlin/python/multiplatform/ref/WasmCycleCollectionTest.kt index 66cf5dc39..69d6a17c0 100644 --- a/python-multiplatform/src/wasmJsTest/kotlin/python/multiplatform/ref/WasmCycleCollectionTest.kt +++ b/python-multiplatform/src/wasmJsTest/kotlin/python/multiplatform/ref/WasmCycleCollectionTest.kt @@ -15,6 +15,7 @@ import python.multiplatform.ffi.ProxyTypeFactory import python.multiplatform.ffi.PyObject import python.multiplatform.ffi.Python3 import python.multiplatform.ffi.withGIL +import python.multiplatform.embedsFreeThreadedPython import python.multiplatform.reflection.ClassLookup import python.multiplatform.reflection.HandleTable import python.multiplatform.reflection.ReflectedClass @@ -65,7 +66,22 @@ class WasmCycleCollectionTest { HandleTable.releaseAll() } - private fun refCount(objPtr: Int): Int = Pointer(objPtr.toUInt()).loadInt() + /** + * `Py_REFCNT` at [objPtr], for whichever object header this build has. Offset 0 is `ob_refcnt` + * only on a build with the global lock. The free-threaded header (`Include/object.h`) starts + * with `ob_tid`; on wasm32 the count is split between `uint32 ob_ref_local` at +8 and + * `Py_ssize_t ob_ref_shared` at +12, shifted left by `_Py_REF_SHARED_SHIFT` (2). This is the + * wasm32 port of `desktopTest/CycleCollectionTest.typeRefCount`, whose offsets (+12, +16) are + * the 64-bit ones. + */ + private fun refCount(objPtr: Int): Int = + if (!embedsFreeThreadedPython) { + Pointer(objPtr.toUInt()).loadInt() + } else { + val local = Pointer((objPtr + 8).toUInt()).loadInt() + val shared = Pointer((objPtr + 12).toUInt()).loadInt() + local + (shared shr 2) + } @Test fun theProxyTypeIsBuiltAndItsSlotsAreRealFunctionPointers() { @@ -134,6 +150,10 @@ class WasmCycleCollectionTest { assertTrue(ProxyTypeFactory.createProxyType() != 0L) val typePtr = ProxyType.proxyTypePtr + // Free-threaded only: a heap type carries `_PyGC_BITS_DEFERRED`, so `_Py_INCREF_TYPE` in + // `PyType_GenericAlloc` is deferred and the count does not move until a collection + // materialises it (desktopTest/CycleCollectionTest's KDoc has the measurements). + if (embedsFreeThreadedPython) python.native.ffi.bindings.PyGC_Collect() val liveBefore = HandleTable.liveCount val typeRefBefore = refCount(typePtr) @@ -155,6 +175,7 @@ class WasmCycleCollectionTest { liveBefore + rounds, HandleTable.liveCount, "setup failed: $rounds handles should be rooted while the proxies are alive" ) + if (embedsFreeThreadedPython) python.native.ffi.bindings.PyGC_Collect() val typeRefAlive = refCount(typePtr) assertEquals( typeRefBefore + rounds, typeRefAlive, diff --git a/python-multiplatform/src/wasmJsTest/kotlin/python/native/ffi/emscripten/WasmCompiledWheelTest.kt b/python-multiplatform/src/wasmJsTest/kotlin/python/native/ffi/emscripten/WasmCompiledWheelTest.kt index bb4da7064..9c5e55cf2 100644 --- a/python-multiplatform/src/wasmJsTest/kotlin/python/native/ffi/emscripten/WasmCompiledWheelTest.kt +++ b/python-multiplatform/src/wasmJsTest/kotlin/python/native/ffi/emscripten/WasmCompiledWheelTest.kt @@ -21,6 +21,11 @@ import python.multiplatform.ffi.PythonTestFixture * * LinkError: Import #204 "env" "__cpp_exception": tag import requires a WebAssembly.Tag * + * Decision 10 (c) c1 (leader, 2026-11-26): the runtime is now 3.15t, so the cp314 wheel below no longer + * loads; this test moves to a pypackpack-built cp315t wheel when pypackpack #82 produces one (the body is + * then rewritten for that wheel). Until then it reports a named skip, and fails under + * `-PrequireWasmRuntime=true`, never a silent pass. + * * The wheels are not in the repository. `python-multiplatform/scripts/wasm/build-cpython.sh wheels` downloads them by URL * with pinned sha256 into `.caches/wasm-wheels`, and the test task extracts them next to the test * bundle. Without them this test skips with that instruction, and under `-PrequireWasmRuntime=true` @@ -38,9 +43,10 @@ class WasmCompiledWheelTest { ) val site = PMP_TEST_SITE_PACKAGES?.toString() if (site == null) { - val message = "no pyemscripten_2026_0 wheels found in ${PMP_TEST_WHEELS_DIR?.toString()}. " + - "Run python-multiplatform/scripts/wasm/build-cpython.sh wheels -- it downloads the pinned pydantic-core and " + - "typing-extensions wheels there -- and re-run this task." + val message = "no cp315t pyemscripten_2026_0 wheel in ${PMP_TEST_WHEELS_DIR?.toString()}: " + + "waiting on a pypackpack-built cp315t wheel (pypackpack #82, Decision 10 c1, leader " + + "2026-11-26). The cp314 pydantic-core wheel the 3.14.2 runtime loaded cannot load into " + + "3.15t, and no cp315t wheel is pinned in build-cpython.sh's WHEELS yet." if (required.toBoolean()) { fail("$message -PrequireWasmRuntime=true was passed, so this is a failure rather than a skip.") } From d8f332a695472fbd116414b53413d08428b1708b Mon Sep 17 00:00:00 2001 From: BREW <81044362+b-re-w@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:19:03 +0900 Subject: [PATCH 2/3] Fix: CPython's JSPI fd_read/poll path runs only under its promising main, so poll() in a pthread no longer throws SuspendError on node 24 ci.yml run 45742320989 (node 24.22.3): smoke.py's select.poll() in its pthread main threw 'SuspendError: trying to suspend without WebAssembly.promising'. Node 24 has JSPI on by default and Python/emscripten_syscalls.c took the suspending path whenever WebAssembly.promising existed; node 22 has no JSPI, which is why it passed locally. build-cpython.sh now patches the guards to require the promising main of this JS context. Part of #175 --- .../scripts/wasm/build-cpython.sh | 34 ++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/python-multiplatform/scripts/wasm/build-cpython.sh b/python-multiplatform/scripts/wasm/build-cpython.sh index 1b2248dce..a02591f39 100755 --- a/python-multiplatform/scripts/wasm/build-cpython.sh +++ b/python-multiplatform/scripts/wasm/build-cpython.sh @@ -62,7 +62,9 @@ # -sEXPORTED_RUNTIME_METHODS. Not ABI-sensitive; needed so Kotlin can bind. # 7. no ppoll ac_cv_func_ppoll=no: 3.15's select.poll() prefers ppoll(), which Emscripten links # as an ENOSYS stub, so poll() always raised and selectors fell back to select(). -# 8. NOT DONE lzma, zstd and OpenSSL are still missing (as in the 3.14.2 build this replaces). +# 8. JSPI I/O Python/emscripten_syscalls.c takes its JSPI fd_read/poll path only under the +# promising main(); in a pthread or an embedder it threw SuspendError on node 24. +# 9. NOT DONE lzma, zstd and OpenSSL are still missing (as in the 3.14.2 build this replaces). # # TRAP: the driver hardcodes CFLAGS=-DPY_CALL_TRAMPOLINE -sUSE_BZIP2 in its configure argv and # appends user args AFTER; autoconf takes the last assignment, so the full string must be repeated or @@ -193,6 +195,35 @@ if marker not in t: PATCH } +# CPython's Python/emscripten_syscalls.c routes fd_read and poll through JSPI (a promise and +# WebAssembly.Suspending) whenever the engine has WebAssembly.promising, which node 24 has by default. +# Suspending works only below the promising wrapper CPython puts around main(). A pthread is not below +# it, and neither is an embedder that never calls main(), so there the first poll() threw +# "SuspendError: trying to suspend without WebAssembly.promising" (#542 CI run 45742320989, node +# 24.22.3: smoke.py's select.poll() in its pthread main; node 22 has no JSPI and passed). The patch +# marks the promising main in this JS context and takes the async path only under it; everywhere else +# fd_read and poll go to Emscripten's synchronous implementations. +patch_syscalls() { + python3 - "$CHECKOUT/Python/emscripten_syscalls.c" <<'PATCH' +import sys +from pathlib import Path +p = Path(sys.argv[1]); t = p.read_text() +marker = "pmp-542: JSPI only under the promising main" +if marker not in t: + guard = " if (!WebAssembly.promising) {\n return null;\n }\n" + assert t.count(guard) == 2, "the fd_read/poll JSPI guards changed shape; re-check the patch" + t = t.replace(guard, + " // " + marker + " (pthreads and embedders are not below it).\n" + " if (!WebAssembly.promising || !Module.__pmPromisingMain) {\n" + " return null;\n }\n") + old = " orig.sym = (...args) => {\n" + assert t.count(old) == 1, "the promising main wrapper changed shape; re-check the patch" + t = t.replace(old, old + " Module.__pmPromisingMain = true; // " + marker + "\n") + p.write_text(t) + print("patched Python/emscripten_syscalls.c (JSPI fd_read/poll only under the promising main)") +PATCH +} + # --- the native build Python, libffi and mpdec --------------------------------------------------------- # The build Python is free-threaded too. libffi and mpdec get -pthread through EMCC_CFLAGS (emcc appends # it to every invocation), checked by the archives' target_features section ("+", 7, "atomics"). @@ -275,6 +306,7 @@ do_build() { ensure_emsdk ensure_checkout patch_trampoline + patch_syscalls ensure_prerequisites patch_sysconfig ( cd "$CHECKOUT" && From 427560207e2c74d3666513b473c7bb92ee50eb4b Mon Sep 17 00:00:00 2001 From: BREW <81044362+b-re-w@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:26:20 +0900 Subject: [PATCH 3/3] Fix: wasm.yml runs the wasmJs suites with --continue, so a red node suite no longer hides the browser suite Run 45829018834: wasmJsNodeTest failed on the expected WasmCompiledWheelTest and Gradle stopped before wasmJsBrowserTest ran. The step still fails when either suite does. Part of #175 --- .github/workflows/wasm.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/workflows/wasm.yml b/.github/workflows/wasm.yml index 94d78555b..47e2d9732 100644 --- a/.github/workflows/wasm.yml +++ b/.github/workflows/wasm.yml @@ -141,6 +141,11 @@ jobs: # to repeat the original defect: if either task would skip -- no interpreter, or no # Chromium-family browser for karma -- the build fails naming what was missing, instead of # reporting success having run nothing. + # + # `--continue`: one suite's failure must not hide the other's result. Without it a red + # wasmJsNodeTest (run 45829018834: only WasmCompiledWheelTest, Decision 10 (c) c1) stopped Gradle + # before wasmJsBrowserTest ran, and the browser suite reported nothing. The step still fails + # when either suite does. - name: Run wasmJs tests run: | ./gradlew \ @@ -148,6 +153,7 @@ jobs: :python-multiplatform:wasmJsBrowserTest \ -PwasmPythonDir="$WASM_RUNTIME_DIR" \ -PrequireWasmRuntime=true \ + --continue \ --console=plain # Belt to the guard's braces, and it guards a different failure: a task that *runs* but