Skip to content

fix: recompile the Python cwasm cache when it can't be deserialized - #1811

Merged
robcohen merged 2 commits into
mainfrom
fix/python-cwasm-cache-invalidate
Jul 19, 2026
Merged

robcohen merged 2 commits into
mainfrom
fix/python-cwasm-cache-invalidate

Conversation

@robcohen

Copy link
Copy Markdown
Member

What

The precompiled CPython-WASI module cache (~/.cache/rustledger/python-wasi/python.cwasm) was loaded with Module::deserialize_file, and any failure propagated as a hard PythonError, failing every python-plugin load.

wasmtime's serialized module format is explicitly version-specific, so a warm cache written by an older wasmtime is rejected by deserialize_file after a wasmtime upgrade — and the workspace bumps wasmtime regularly (46 landed recently). The symptom was Python runtime unavailable: WASM runtime error: failed deserialization for .../python.cwasm, with no recovery short of the user manually deleting the file. A truncated prior write (process killed mid-fs::write) fails the same way.

Fix

Extract the cache decision into load_or_compile_cached_module: a cache that exists but fails to deserialize is now discarded and recompiled (overwriting it with fresh bytes), never propagated. A missing cache compiles as before. The cache write stays best-effort — a write failure just means the next run recompiles, never a load failure.

How this came up

Surfaced during the #1809 investigation (the corpus_parity divergence): one of the four diverging fixtures failed on exactly this stale-cache error on the feature-unified native side. That test-harness scoping issue is handled separately; this PR fixes the underlying robustness bug it exposed, which is real and user-facing (any user with a warm python-plugin cache across a wasmtime bump).

Test

cached_module_recompiles_when_cache_is_unusable — hermetic, using a 1-instruction synthetic wat module instead of the 50+ MiB CPython download (same pattern as the existing #1234 memory-cap test). Covers cold cache → compile+populate, warm cache → fast deserialize, corrupted cache → recompile-and-recover (the #1809 failure), and confirms the cache is healthy again afterward.

cargo test -p rustledger-plugin --features python-plugins green; clippy/doc clean under both the featured and featureless builds.

🤖 Generated with Claude Code

https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU

The precompiled CPython-WASI module cache
(~/.cache/rustledger/python-wasi/python.cwasm) was loaded with
Module::deserialize_file and any failure propagated as a hard
PythonError, bricking every python-plugin load. wasmtime's serialized
module format is version-specific, so a warm cache written by an older
wasmtime is rejected after a wasmtime upgrade (the workspace bumps
wasmtime regularly) — surfacing as
"Python runtime unavailable: failed deserialization for .../python.cwasm"
until the user manually deleted the file. A truncated prior write fails
identically.

Extract the cache decision into load_or_compile_cached_module: a cache
that fails to deserialize is now discarded and recompiled (overwriting
it), never propagated. Hermetic regression test using a 1-instruction
synthetic module (no CPython download) covers cold/warm/corrupt-recover.

Surfaced by #1809's investigation of the corpus_parity divergence; that
test-harness issue is handled separately.
Copilot AI review requested due to automatic review settings July 19, 2026 12:20
@robcohen
robcohen requested a review from a team as a code owner July 19, 2026 12:20
@codecov

codecov Bot commented Jul 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.73469% with 13 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-plugin/src/python/runtime.rs 86.73% 13 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 32.2ms ± 0.3ms 23.8 MB
beancount 789.1ms ± 3.7ms 50.7 MB
Comparison 24.5x faster 2.1x less

vs main branch (2026-07-19)

Metric main this PR Change
Time 35ms 32.2ms -8.0% 🟢
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Improves robustness of the CPython-WASI precompiled module cache used by rustledger-plugin’s Python runtime by recompiling when the on-disk .cwasm cache can’t be deserialized, avoiding hard failures across wasmtime upgrades or cache corruption.

Changes:

  • Extracted cache handling into load_or_compile_cached_module, with “deserialize if possible, otherwise recompile” behavior.
  • Added a hermetic unit test covering cold-cache, warm-cache, and corrupted-cache recovery paths using a tiny synthetic wasm module.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 811
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

robcohen added a commit that referenced this pull request Jul 19, 2026
corpus_parity compares the featureless component wasm's load errors
against the native rustledger_ffi_wasi::helpers::load_source reference.
Under cargo test --workspace, feature unification compiles that native
reference WITH python-plugins/wasm-plugins (the rustledger CLI enables
them by default), so on a fixture declaring such a plugin it attempts
the plugin and reports a real error, while the always-featureless
component reports "requires the ...-plugins feature". Same function, two
feature builds — an artifact, not a component regression. The divergence
is invisible to CI (which never builds the debug wasm in a --workspace
job) but breaks the local full-suite workflow for anyone who has.

Skip a fixture when the component emits the plugin-feature-gate sentinel:
it exercises a surface the featureless component structurally cannot
implement. Keying on the component's sentinel rather than a source
`plugin "..."` scan keeps NATIVE-Rust plugins (which the featureless
component DOES run) in the compared set. The skip is surfaced as its own
count in the summary line (no silent cap), and applies uniformly whether
or not features are unified.

The stale-cwasm-cache robustness bug this investigation also exposed is
fixed separately in #1811.

Closes #1809.
Deep review (+ Copilot) flagged the first cut relied on unsafe
Module::deserialize_file returning a clean Err for stale/garbage bytes —
but wasmtime's own docs say deserializing untrusted bytes "may trick
Wasmtime into arbitrary code execution" (it is UB, not a guaranteed
Err). The recover-on-Err mechanism and the "we only read our own cache"
Safety claim were both unsound.

Redesign so deserialize_file only ever runs on a same-engine, complete,
header-valid artifact:

- compat_cache_path keys the cache filename by
  Engine::precompile_compatibility_hash() (wasmtime guarantees a matching
  hash deserializes), so a cross-wasmtime-version / cross-config artifact
  resolves to a different path and is never opened — cache miss, recompile.
- The SAFE Engine::detect_precompiled_file header check runs before the
  unsafe call; garbage / truncated-below-header / component files are
  treated as a miss and recompiled, never deserialized.
- write_cache_atomically writes a temp file + atomic rename, so a
  killed-mid-write or a concurrent writer never leaves a partial .cwasm.
- An unwritable cache dir is surfaced (was a silent forever-recompile),
  and the recompile messages no longer misdiagnose every cause as a
  wasmtime upgrade.

The Safety doc now describes the two gates honestly; the residual UB
surface is body-preserving bit-rot, the irreducible wasmtime caveat.
Test rewritten to exercise the SAFE detect-reject path (garbage is
rejected by detect_precompiled_file, not by hoping deserialize errors),
plus a compat_cache_path keying/determinism test.
robcohen added a commit that referenced this pull request Jul 19, 2026
)

* test: skip plugin-feature-gated fixtures in corpus_parity (#1809)

corpus_parity compares the featureless component wasm's load errors
against the native rustledger_ffi_wasi::helpers::load_source reference.
Under cargo test --workspace, feature unification compiles that native
reference WITH python-plugins/wasm-plugins (the rustledger CLI enables
them by default), so on a fixture declaring such a plugin it attempts
the plugin and reports a real error, while the always-featureless
component reports "requires the ...-plugins feature". Same function, two
feature builds — an artifact, not a component regression. The divergence
is invisible to CI (which never builds the debug wasm in a --workspace
job) but breaks the local full-suite workflow for anyone who has.

Skip a fixture when the component emits the plugin-feature-gate sentinel:
it exercises a surface the featureless component structurally cannot
implement. Keying on the component's sentinel rather than a source
`plugin "..."` scan keeps NATIVE-Rust plugins (which the featureless
component DOES run) in the compared set. The skip is surfaced as its own
count in the summary line (no silent cap), and applies uniformly whether
or not features are unified.

The stale-cwasm-cache robustness bug this investigation also exposed is
fixed separately in #1811.

Closes #1809.

* test: tighten the corpus_parity plugin-feature skip (deep-review findings)

The first cut keyed the skip on the component's error alone, which the
deep review flagged as too weak. Tighten:

- Skip only when the component gated AND native did NOT gate. Requiring
  !native_gated stops the over-skip in a featureless native build
  (-p ...-tests, no feature unification), where both sides emit the same
  gate message and legitimately compare EQUAL — those fixtures stay
  covered (305 compared / 0 skipped) instead of being dropped, while the
  unified --workspace build still skips the 4 (301 compared / 4 skipped).
- Match the exact "requires the {python,wasm}-plugins feature" phrases
  rather than the loose "-plugins feature" substring, so a "Plugin not
  found" error echoing a plugin name can't trigger an over-skip.
- Collapse guards: bound skipped_plugin_feature (<=30) and require most
  fixtures to be compared (>= files/2), so a component regression that
  emitted the gate broadly trips an assert instead of silently shrinking
  the compared set to a green-but-empty run.
- Drift guard test plugin_feature_gate_message_is_stable: loads a Python
  plugin through the featureless component and asserts the exact phrase
  the skip matches, so a rustledger-loader reword fails there loudly
  rather than breaking the corpus test spuriously.
@robcohen
robcohen enabled auto-merge (squash) July 19, 2026 13:56
@robcohen
robcohen merged commit 93d799b into main Jul 19, 2026
56 checks passed
@robcohen
robcohen deleted the fix/python-cwasm-cache-invalidate branch July 19, 2026 13:56
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