Skip to content

Repair the runtime baseline for Golem - #1

Merged
noise64 merged 20 commits into
mainfrom
runtime-baseline
Dec 3, 2026
Merged

noise64 merged 20 commits into
mainfrom
runtime-baseline

Conversation

@noise64

@noise64 noise64 commented Nov 16, 2026 •

Copy link
Copy Markdown

Touches GOL-1850 (PY-02): runtime repairs that the Golem Python SDK needs. It does not resolve the issue.

Runtime repairs for the Golem Python SDK, on top of upstream 5382383. This is the first of two stacked fork PRs; the second adds the persisted prepare/assemble API.

  • CPython 3.14.10. The build downloads the python.org 3.14.10 tarball instead of a patched 3.14.0 checkout, and checks the SHA-256 of the CPython, zlib and SQLite tarballs. cpython-patches/ carries the WASI patches that 3.14.10 does not include: dynamic linking (GH-142234), sys/ioctl.h in socketmodule.c, and a deallocation depth bound (below). zlib moves to 1.3.2 and SQLite to 3.54.1.
  • dlopen table. wit-component 0.258.3 comes from the golemcloud/wasm-tools fork at 801650b (branch golem-2.0), through [patch.crates-io]. The fork counts only the symbols that it writes, so the table size matches its entries when a library exports exception tags. The other 0.258.3 crates (wasmparser, wasm-encoder, wit-parser, wasm-metadata, wit-dylib) still come from crates.io. Builds now fetch the fork from GitHub.
  • CPython cache identity. build.rs records the SHA-256 of the CPython sources: the release tarball, the name and content of each patch (line endings normalized), and the zlib and SQLite tarballs. It writes the identity to componentize-py-source-identity in cpython/ when it extracts and patches the tarball, and in cpython/builddir/wasi when it links libpython3.14.so. The file name is not hidden, because the CI artifact upload leaves out hidden files. A library or tree without that identity, or with another one, fails the build, and the error tells you to delete cpython/. A partly patched tree from an interrupted build is removed before extraction, and only *.patch files in cpython-patches/ are applied. Before, an existing cpython/ skipped the download, the checksum and the patches, and an existing libpython3.14.so skipped the build. A warm checkout then packaged an older runtime. The CI artifact cpython/builddir/wasi carries the identity, so the Test jobs reuse the Populate build.
  • Checked lowering. The runtime checks each value against its WIT type before it lowers it. A bad import argument raises TypeError, OverflowError or ValueError that names the argument, and the host does not see a call. A bad export result traps with a message that names the export. Integer and float checks extract the value as the lowering does, so numpy.int64 and other objects with __index__ or __float__ pass. Before, out-of-range integers wrapped and a moved handle reached the host as handle 0. The three trap_on_empty_* tests become reject_moved_*: a second use of a moved handle now raises ValueError in the guest.
  • Resource finalization. The destructor of an exported resource releases the Python object, and dropping an owned handle drops the handle. Finalizers now run.
  • Support libraries. The linker reads each extension's dylink.0 needed list and links the named support libraries from the Python path, or libsetjmp.so from the WASI SDK. Before, an extension that used setjmp/longjmp failed to link.
  • Pre-initialization inputs. The hash seed and random bytes come from a digest of the linked component, the app name and the files of each Python path entry, so apps built from the same libraries get different values. The clock is fixed, bytecode is not written and build directories get a fixed mtime. Two builds of the same input still differ in a small number of bytes; this is not solved yet.
  • C stack size. CPython measures only the linear-memory C stack, but the engine's call stack grows several times faster for the same C recursion. On an engine with a 1 MiB max_wasm_stack, deep repr, json, pickle and Python __repr__ recursion trapped before CPython raised RecursionError. --stack-size (and stack_size in the library API) sets the C stack. The default stays at the linker's 1 MiB, because the correct value depends on the engine. With 96 KiB on Golem's engine, every measured kind raises RecursionError, at a lower depth.
  • Deallocation depth. On WASI, _Py_Dealloc and the trashcan count nested deallocations and defer past depth 50, because the stack-margin check does not see the engine's stack. Before, freeing a deeply nested list trapped.

Known gaps: --stack-size accepts any value, including 0 or a value that is not a multiple of 16. The CPython cache identity does not cover the WASI SDK version or the configure and link recipe. The same owned handle passed twice in one call passes the check, and the host receives handle 0 for the second use.

Not in this PR: cancellation and the asyncio functions that raise NotImplementedError, Wasm exceptions on the Golem engine (needs exceptions in the shared engine), and a PyO3 extension that aborts on panic.

Verification

On this head, 7389c59 (Linux x86_64, local):

  • cargo test --release -- --skip http_p3_example: passed (118 lib, 21 bindings, 9 componentize tests).
  • bash .github/workflows/lint.sh: passed.
  • Before the removal, the source files and libdl.so of vendor/wit-component were byte-identical to the wit-component crate of wasm-tools 801650b. Cargo.lock changes only by the source line of wit-component, and no crate name and version has two sources.
  • The CPython cache cases ran at an earlier head of Persist prepared bindings and assemble apps with them #2, 59406fd, which has the same build.rs identity code as this branch. This branch adds the removal of a partly patched tree and the *.patch filter; no case exercised these two. The wit-component change does not touch build.rs.
    • A warm upstream-era cpython/ with libpython3.14.so and no identity fails before packaging, and the library is not changed.
    • A libpython3.14.so with no identity file next to it fails the same way.
    • A fresh checkout downloads, patches and builds, and writes the same identity into cpython/ and cpython/builddir/wasi.
    • A second build with the same identity reuses the library (same SHA-256 and mtime, no download).
    • A changed patch fails with the old and the expected identity. When the patch is restored, the library is reused.
    • A patch with CRLF line endings has the same identity, and the library is reused.
    • A changed patch with no library fails on the source identity of cpython/.
    • Only cpython/builddir/wasi restored without hidden files, as the CI artifact does: the build reuses it, with no download.
  • In the cache cases, LOCAL_TARBALL_DIR, a local build.rs change that is not in this PR, read the SQLite tarball from a local copy, because sqlite.org is not reachable from the build machine; the checksum is still checked.
  • Not run: http_p3_example, because its port is taken on the build machine.
  • CI: run 45834795648 on this head passed Populate cache and Test on Linux, macOS and Windows.

Verify the CPython, zlib and SQLite source tarballs by SHA-256 and carry the
WASI patches that 3.14.10 does not include in cpython-patches/. Update zlib to
1.3.2 and SQLite to 3.54.1.
wit-component 0.258.3 counts a library's exports, including Wasm tags it does
not write into the dlopen symbol table. A library exporting a tag, such as
__c_longjmp from setjmp/longjmp support, then makes the loader read past its
symbols. Carry wit-component with the one-line fix until it is released.
Lowering a Python value that does not match its WIT type used to panic part
way through, for example with an out-of-range int. Check the whole value first:
an import call raises TypeError, OverflowError or ValueError naming the
argument before the host sees a call, and an export whose result does not match
traps with a message naming the value.
The handle table holds a strong reference to an exported resource's Python
object, but the destructor did nothing, so objects whose handles the host
dropped were never finalized. Release the reference in the destructor, and drop
the handle when an owned handle returns to the guest instead of leaking it.
An extension may depend on a shared library that is not itself an extension,
such as libsetjmp.so or a libjpeg.so shipped next to it. Link each library that
a linked library names in its dylink.0 needed list, from the Python path or the
WASI SDK's libsetjmp.so, under the name its dependents use. Libraries that
nothing needs are not linked.
Pre-initialization saves the application's state into the component, so host
entropy, time and file writes during it made each build different. Derive the
hash seed and random bytes from the linked component, give the guest a clock
that starts at the Unix epoch, stop it from writing bytecode into the source
directories, and give the directories created for the build fixed times.
CPython defers a deallocation when its measured C stack margin is small, but
on WebAssembly that margin covers only the linear-memory stack. Freeing a
deeply nested list exhausted the engine's call stack first. Count nested
deallocations instead and defer at depth 50.
CPython raises RecursionError when the linear-memory C stack is nearly full,
but the engine's own call stack is separate and grows several times faster
for the same C recursion. The --stack-size option, and stack_size in the
library API, let the caller size the C stack so that RecursionError comes
first for its engine's call stack.
setup-python has no 3.14.0 build for the current ubuntu-latest image, so the
Test jobs failed before building. 3.14.10 is published for every runner in
the matrix and matches the CPython release that the build uses.
build.rs reused an existing cpython/ without the release tarball, its
checksum or the patches, and an existing libpython3.14.so without a
build. A checkout that had built other sources packaged that older
runtime. It now records the SHA-256 of the CPython, zlib and SQLite
tarballs and of each patch in cpython/ and cpython/builddir/wasi, and
fails on a tree or library with another identity or none.
The checks before lowering accepted only int and float instances, but
the lowering takes any object with __index__ or __float__, such as
numpy.int64. They now extract the value as the lowering does and keep
the TypeError and OverflowError messages.

Pre-initialization entropy came from the linked component alone, so
every app without native extensions got the same hash seed and random
bytes. It now also covers the app name and the files of each Python
path entry.

build.rs removes a partly patched CPython tree before extracting, and
applies only *.patch files.
The dlopen symbol-count fix is merged into the golem-2.0 branch of
golemcloud/wasm-tools. The patch now pins that commit instead of the
vendored copy, which is removed. Its source is the same as the vendored
copy, and its sibling crates still come from crates.io.
@noise64
noise64 marked this pull request as ready for review November 30, 2026 12:41

vigoo commented Dec 1, 2026 •

Copy link
Copy Markdown

Review of 5382383...7389c59 (PR #1 only; PR #2 is stacked on this branch and was excluded).

Recheck at 2d06fbe: all four findings are resolved, including the newly created output-directory case. See the follow-up with verification evidence. These findings were posted as one conversation comment, so there are no individual GitHub review threads to resolve. This records resolution of the findings, not a formal PR approval.

Original findings, retained for context:

  1. High — propagate the stack size to the stub linker. src/lib.rs:869–872 passes stack_size to link_libraries, but not to stubwasi::link_stub_modules. With --stub-wasi and a nondefault --stack-size, initialization uses the custom memory layout while the final stub component uses the default 1 MiB layout. In the pinned linker, library memory_base addresses depend on stack size and are immutable globals. component-init-transform copies the initialized memory and mutable globals into the stub component, but preserves its immutable globals. Those addresses therefore disagree with the snapshot, causing wrong data or invalid memory accesses. Pass the same stack size to both linkers and add an execution test combining these options. This finding is based on tracing the pinned linker and transform; the combination was not executed end to end.

  2. High — include the support archive in the publishing build script. src/prelink.rs:65–67 unconditionally requires OUT_DIR/libsetjmp.so.zst, but alt-build.rs never copies that archive into OUT_DIR. stage.sh replaces build.rs with alt-build.rs for published crates. Copying the archive into the staged package root does not satisfy this include_bytes!, so a clean staged build fails. Add the archive to alt-build.rs and verify a clean staged build. An artifact-list comparison confirmed that libsetjmp.so.zst is the sole required archive missing from that list; a full staged build was not run.

  3. Medium — normalize numeric values once instead of executing conversions twice. runtime/src/check.rs:264–272 extracts and discards the numeric value, then MyCall extracts it again during lowering. __index__ and __float__ can execute Python code, so the second conversion need not return the checked value or even succeed. A native probe using the pinned PyO3 0.28.3 and a stateful __index__ checked 40 but lowered 41; the baseline's single extraction lowers 40. If the second conversion raises, lowering instead reaches unwrap and traps. Record properties have the same repeated-read risk. Normalize once, lower the normalized value, and add a stateful-converter regression test. The probe did not execute a whole guest invocation.

  4. Medium — exclude the output artifact from the build digest. src/lib.rs:1434–1447 hashes every file below python_path, including an existing output file. With the default -p . and -o app.wasm, the previous output feeds into the next build's hash/random seed even when the application sources and linked libraries are unchanged. A probe running the exact extracted build_digest function confirmed that creating only app.wasm changes the digest. Exclude the output artifact, define the intended source-input set, and test consecutive builds with output inside python_path. This is distinct from the acknowledged residual nondeterministic bytes: it explicitly changes initialization seeds.

The maintainer assessment is that these repairs generally fit the existing mechanisms, but publishing is an overlooked consumer, combined-option coverage is missing, and preflight validation incorrectly assumes repeatable Python callbacks.

Verification: formatting passed, and GitHub run 45834795648 passed for this exact head on Linux, macOS, and Windows. The focused digest and numeric-conversion probes passed with the results above. The full runtime suite was not rerun locally. No product code was changed during review.

@noise64
noise64 marked this pull request as draft December 1, 2026 14:30

noise64 commented Dec 1, 2026

Copy link
Copy Markdown
Author
  1. High — include the support archive in the publishing build script.

Fixed in 87f80f2.

noise64 commented Dec 2, 2026

Copy link
Copy Markdown
Author
  1. High — propagate the stack size to the stub linker.

Fixed in e2500a6. link_stub_modules now takes the stack size and passes it to the linker, and both componentize routes give it the same value as link_libraries. The new test stub_wasi_keeps_the_stack_size builds a --stub-wasi component with the default stack and with a 2 MiB stack, instantiates it with no WASI, and checks a string that initialization computed. Without the fix, the 2 MiB case traps with an out-of-bounds memory access in dlmalloc during the first export call, so your trace holds in execution.

noise64 commented Dec 2, 2026

Copy link
Copy Markdown
Author
  1. Medium — normalize numeric values once instead of executing conversions twice.

Fixed in b47da7e. check now returns the value to lower: it runs each conversion that can execute Python code once (__index__, __float__, __bool__, record field reads) and builds the value from the results, so lowering reads only what the check accepted. Imported resource handles stay the original objects, because lowering moves the handle out of them. A map whose keys convert to one value is now rejected instead of lowering as one entry. lower_numbers now uses a converter that returns the next number on each call, for an import argument and for a resource constructor, and the new lower_record returns a record whose field property does the same. Without the fix they lower 41 and 148 instead of 40 and 146.

noise64 commented Dec 2, 2026

Copy link
Copy Markdown
Author
  1. Medium — exclude the output artifact from the build digest.

Fixed in 04db4a7. build_digest skips the output path, resolved through its parent directory because the file need not exist yet. The new test output_in_the_python_path_is_not_a_build_input builds twice into the Python path entry and checks that a value from os.urandom at initialization is the same, then adds a source file and checks that it changes. Without the fix the second build gives another value. On prepared-assets, BuildEntropy::for_inputs takes the output path too; Assembler passes None, because it writes no output.

@noise64
noise64 marked this pull request as ready for review December 2, 2026 10:51

vigoo commented Dec 2, 2026 •

Copy link
Copy Markdown

Resolved at 2d06fbe. The output parent is now created before hashing. A local probe using the exact digest function and the revised caller ordering confirms stable digests for both an existing parent and a newly created nested parent; adding a source file still changes the digest. The expanded end-to-end regression test covers dist/app.wasm with no initial dist. Exact-head CI run 46901476225 passed that test and the other three review-related tests on Linux, macOS, and Windows. Formatting passed locally. Full guest and staged-build checks were not rerun locally. A failed build can now leave an empty output directory, an acceptable consequence of creating it earlier. No additional defect was found in this revision.

Earlier finding and evidence, retained for context:

Rechecked at 87f80f2. Findings 1–3 from the original review are resolved: both linkers receive the stack size, the publishing build copies libsetjmp.so.zst, and lowering consumes normalized values.

Finding 4 remains partially unresolved — medium: creating the output directory changes the next build's seed.

With -p . -o dist/app.wasm and no dist directory initially, the first digest contains no dist entry. Writing the output creates that directory. On the second build, src/lib.rs:1448–1455 hashes the directory marker, even though it correctly skips app.wasm. The initialization seed therefore changes despite unchanged application sources and linked libraries.

A local probe executing the exact updated build_digest confirmed both sides:

Unchanged source, output created: digest changed = false
Unchanged source, new output directory created: digest changed = true

The third digest equals the second once the directory exists. Create the output parent before hashing, or otherwise define a stable output-directory policy, and extend output_in_the_python_path_is_not_a_build_input to cover a previously absent nested output directory. This was reproduced at the digest-function boundary, not with a whole guest build.

Verification of the other fixes: formatting passed; the publishing archive-list comparison now reports no missing files. Exact-head CI run 46678902430 passed on Linux, macOS, and Windows; its logs confirm lower_numbers, lower_record, stub_wasi_keeps_the_stack_size, and output_in_the_python_path_is_not_a_build_input passed. The full guest suite and clean staged build were not rerun locally.

noise64 commented Dec 2, 2026

Copy link
Copy Markdown
Author

Finding 4 remains partially unresolved — medium: creating the output directory changes the next build's seed.

Fixed in ae177ab. componentize now creates the output's parent directory before build_digest, so the first build's digest already sees it. output_in_the_python_path_is_not_a_build_input now also builds twice into dist/app.wasm in a new Python path entry without dist, and checks that the os.urandom value from initialization is the same. Without the fix that assertion fails. A build that fails after this point can leave the empty output directory behind.

@vigoo vigoo left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All four review findings are resolved at this head. Rechecked the fixes and regression coverage; exact-head CI passed on Linux, macOS, and Windows. Local formatting and focused digest checks passed. The full guest suite and clean staged build were not rerun locally.

@noise64
noise64 merged commit 32b3566 into main Dec 3, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants