Skip to content

fix(plugin): run Python plugins via __plugins__ under the host time budget - #2525

Merged
robcohen merged 11 commits into
mainfrom
fix/python-plugin-runtime
Oct 9, 2026
Merged

robcohen merged 11 commits into
mainfrom
fix/python-plugin-runtime

Conversation

@robcohen

@robcohen robcohen commented Oct 8, 2026 •

Copy link
Copy Markdown
Member

What was wrong

No Python plugin could run on main, and no test ran one through the CPython-on-WASI runtime, so CI stayed green. Fixing that, and then an adversarial review of the new path (scale, sandbox, real ecosystem plugins, every plugin entry point), turned up these:

  1. Fuel. The fixed 600M budget is half of CPython's startup (1.24G), so even a passthrough plugin trapped.
  2. Entry points. The plugin was called by the literal name plugin, not through __plugins__.
  3. Escaping. Entries were spliced into a Python '''…''' literal, so a narration with " or \ broke their JSON.
  4. Metadata. The compat layer read a meta key the wire never has. Plugins saw no metadata (no filename/lineno, none of the ledger's keys), every round trip dropped all transaction and posting metadata, and a plugin that set metadata failed to decode.
  5. Errors and locations. A beancount plugin's own error namedtuples (source message entry) were reported as str(tuple) with no location. Separately, a Python plugin's whole output was re-inserted (Delete+Insert), so every later diagnostic about those entries lost its location: a failing balance, the next plugin's errors.
  6. Sandbox (security). /work was preopened read-write: a plugin could write 1 GiB of host temp space for 0.07 s of budget, so a ledger from someone else could fill /tmp (tmpfs, i.e. RAM). Its stderr was the host's (unbounded). / was the whole runtime cache dir. All three were exposed by this PR's first commit, the first in which plugins actually ran.
  7. Scale. The whole input JSON string, the parsed dicts and the namedtuples were all held at once. About 50k transactions exhausted the 256 MiB sandbox cap.
  8. Limit messages. A WASM plugin or importer out of fuel said only all fuel consumed, and out of memory a bare unreachable trap. Python's uncaught exceptions gave only a wasm backtrace.
  9. Built-in Python plugins were unreachable, and wrong. execute_builtin (check_commodity, leafonly) had no caller: python:leafonly was refused as a module name. Python check_commodity counted an open's currencies as declared, so it missed what beancount flags. Python leafonly reported each posting instead of each account.
  10. Concurrent first runs raced on one fixed download temp file and one extraction target. One process could see a half-written python.wasm.

What changed

Budget: the host's seconds, the shared conversion, no Python multiplier

  • sandbox::fuel_for_secs is the one seconds-to-fuel conversion. WASM plugins, importers and Python all use it.
  • PythonRuntime::with_max_time_secs is new, and run_with_max_time_secs threads the budget to Python. So [plugins] max_time_secs, --plugin-max-time-secs and LoadOptions::plugin_max_time_secs all govern Python.

Measured (fuel via store.get_fuel(), sandbox memory via the instance's memory size):

Workload Fuel CPU Sandbox memory
startup + passthrough, 3 entries 1.24G 0.2 s 40 MiB
passthrough, 5k txns 3.99G 0.8 s 40 MiB
passthrough, 20k txns 12.2G 3.3 s 50 MiB
passthrough, 50k txns 28.8G 8.1 s 104 MiB
passthrough, 100k txns 56.7G 16 s 162 MiB
tag every txn, 100k txns 60.0G 22 s 205 MiB
passthrough, 200k / 300k txns — — over 256 MiB: clear memory error
5M-iteration loop 6.81G 1.1 s

CPython runs at 3–6G fuel per CPU-second, the same range as other wasm. FUEL_PER_SECOND's conservative 1G therefore keeps its "stops within N seconds" promise, and a multiplier would break it.

Decision: keep the 30 s default, consistent with WASM. (Round 2 made the memory cap configurable; see below.) That covers ~50k transactions at ~0.55M fuel each. A fuel trap now tells a big-ledger user exactly how much to add: the plugin exceeded its 30-second time budget (rledger raises it with --plugin-max-time-secs or [plugins] max_time_secs); moving 100002 entries into Python and back takes about 62 seconds of it before the plugin does any work. Memory, not time, is the hard ceiling for very large ledgers. The cap holds ~180k transactions, so an SFC-size 316k ledger cannot run a Python plugin. Round 2 makes the cap a host setting (below).

Entry points: beancount's run_transformations

  • The plugin is exec'd into its own module object, seeded with the compat names.
  • Each item of __plugins__ runs in order: a string via getattr, otherwise the callable itself.
  • Each gets (entries, options_map[, config]). An exception is reported, and the next function gets the pre-exception entries.

Deliberate divergences (correctness first), documented in the docstring, docs and CHANGELOG:

  • No __plugins__: runs nothing, as beancount does, but with a warning.
  • Listed name not defined: an error naming it, and nothing runs. Beancount aborts the load with an AttributeError.
  • __plugins__ = "name" (a string) and non-callable items are errors.

Python data path

  • Inputs: files, never Python source.
  • Streaming: one entry per line both ways, so the input string never sits next to its objects.
  • Metadata: typed (Decimal, date, Amount), with filename/lineno as in beancount. Unchanged values keep their wire type.
  • Output tracing: an entry the plugin returned or rebuilt (it still holds that input's meta, as _replace keeps it) becomes Modify(i). It keeps its span; only genuinely new entries are Insert.
  • Errors: serialize_errors reads .message / .source from any error object, so located errors match bean-check (file:line: message).
  • Compat shim: adds data.filter_txns and amount.CURRENCY_RE. Stand-in modules are named, so a missing import reads cannot import name 'realization' from 'beancount.core', and that line is surfaced in the error.

Sandbox

  • The guest sees exactly /lib (the stdlib) and /work (its inputs), both read-only.
  • Its result goes over stdout, captured in a capped pipe (2× input + 64 MiB). Plugin prints are redirected to stderr, so they cannot corrupt the result.
  • stderr is captured, capped at 4 MiB, and forwarded.
  • The temp dir is deleted on every path, including traps.
  • Probed from inside, the guest cannot read the ledger dir, $HOME, /etc/passwd or /work/../.., cannot write anywhere, cannot make symlinks, and cannot open sockets or run subprocesses.
  • WASM plugins and importers get no imports at all, so a guest importing WASI is refused at load. The load error now shows the cause instead of invalid plugin.

Limits, uniformly

sandbox::explain_limit / time_budget_exceeded give one wording for all three sandboxed kinds: it exceeded its N-second time budget (rledger raises it with --plugin-max-time-secs or [plugins] max_time_secs), or it ran out of the 256 MiB sandbox memory limit. MemoryLimiter::growth_denied records the refusal. rledger survives and reports with exit 1, never killed.

python: forms

Real ecosystem plugins vs bean-check

I ran the plugins' own source files, copied from beancount 3.x and beancount_reds_plugins, on the same ledgers.

Same result as bean-check:

  • check_commodity: same two errors and messages.
  • unique_prices: same error, at the same line.
  • coherent_cost, onecommodity: clean on both.
  • rename_accounts (reds): same balances.
  • An order, config and exception plugin: same narrations and error.

Different from bean-check: leafonly and noduplicates need beancount.core.realization / compare, which the shim doesn't provide. They now fail with that ImportError named. The built-in python:leafonly covers the first.

Plugin conformance matrix (crates/rustledger/tests/plugin_conformance.rs)

Every kind × entry point, each asserting the plugin's effect (a diagnostic, a tag, an imported transaction) in the command's output:

  • native via directive (check/query/report), via --native-plugin, and beancount.plugins.* resolving native;
  • a real wasm_plugin_main! guest via directive (check/query/report) and --plugin;
  • Python file via directive (check/query/report), plus the python:./x.py, python:module (refused) and python:<builtin> forms;
  • native + Python together (with_plugins.beancount);
  • a wasm_importer_main! guest via extract --wasm-importer.

The previously unused tests/fixtures/python-plugins fixtures are used here; they gained __plugins__.

Limits for each sandboxed kind (WASM plugin, Python plugin, WASM importer):

  • the default budget suffices;
  • a tight budget traps via the flag AND the config file, with the budget-and-how-to-raise message;
  • memory past 256 MiB gives a clean memory error;
  • isolation;
  • located errors;
  • metadata round trip, an output cap, print to stderr, and locations preserved after a plugin.

The guests (tests/fixtures/conformance/, a standalone workspace) are built for wasm32 by the test itself, once. The Python-gated cargo tests job installs the wasm32 target and runs the matrix with RLEDGER_REQUIRE_WASM32=1 and RLEDGER_REQUIRE_PYTHON_WASI=1, which make a skip a failure, and greps its log for both skip markers. 24 tests, 3.5 s once warm.

Fail-without-fix. I applied 19 mutations, one at a time, and each was caught. Each line is the mutation, then the tests that failed:

  • native arm returns nothing → 4 native tests
  • WASM arm returns nothing → 4 WASM tests
  • Python arm returns nothing → 12 Python tests
  • python: builtin route removed → the builtin test
  • --native-plugin ignored → its test
  • --plugin ignored → its test
  • --wasm-importer ignored → 4 importer tests
  • budget not threaded, for each of WASM / Python / importer → that kind's budget test
  • memory limiter off → all 3 memory tests
  • /work writable → isolation
  • preopen widened to the cache root → isolation
  • stdout uncapped → output-cap test
  • prints to the result stream → print test
  • serialize_errors reading only ValidationError → located-errors test
  • old meta key → metadata test
  • output re-inserted instead of traced → 2 location tests
  • __plugins__ ignored → 6 tests

The original 7 python_plugin_wasi tests all fail on main.

Second review round (92b44b9): attacking the sandbox

Attack Before Now
time.sleep(10**9) (waiting burns no fuel) hung rledger indefinitely stopped on the clock at the time budget: guest runs async on its own thread, yields every 10M fuel, dropped at the deadline
runaway recursion host thread stack (8 MiB) < guest's 16 MiB wasm stack: SIGABRT, no diagnostics ends in the guest (fiber stack): "recursed past the sandbox's call stack" or out of memory
open files in a loop uncapped host fds, reached the 1024 ulimit -n WASI resource table capped at 256: "held more than 256 files open"
output with no result line read as "ran nothing", input kept silently error: "output ends before its result"
plugin returns an invalid entry (WASM or Python, pre-existing) processing pipeline failed, exit 2, all diagnostics lost error, plugin's changes discarded, load goes on
threads / stdin / huge line / invalid UTF-8 / NUL / bad or duplicate indexes / 100k-deep JSON — already contained (no threads, empty stdin, capped pipes, clean decode errors)

wasmtime is 49.0.2, which has the RUSTSEC-2026-0321 poll_oneoff fix; WASM plugins and importers import nothing, so they cannot block.

Memory cap as a host setting: [plugins] max_memory_mb / --plugin-max-memory-mb (1–4096), threaded like the time budget (LoadOptions::plugin_max_memory_mb, ResolvedPlugin::run_with_limits with PluginLimits), never the ledger's. A 300k-transaction ledger runs a Python plugin at --plugin-max-memory-mb 1024 --plugin-max-time-secs 1000 (72 s CPU).

Native leafonly: counts children named by any directive (open, close, balance, pad, note, document, postings), as beancount's realization does, so a parent whose child is only opened is reported, matching bean-check. test_pedantic_runs_multiple_validators had encoded the miss (its one expected error was the commodity's) and is corrected.

Matrix: 33 tests, 10/10 green locally, green cold (empty CPython cache, no prebuilt guests, 15 s). It runs in the required, non-path-filtered Python-gated cargo tests check. 11 more mutations were each caught: no deadline, uncapped table, truncated output accepted, invalid entry aborting, memory cap not threaded (×3), config key or flag ignored, leafonly reverted.

Third review round (5ec918d)

  • Plugin text is escaped. Plugin- and importer-supplied text (messages, claimed file names, Python prints and exceptions, WASM failure text, importer warnings and names) has its control characters escaped. rustledger_plugin::untrusted does the escaping and a conformance case covers each channel.
  • Python plugin inputs are private. The work dir is 0700 on Unix; it followed the umask and survives a Ctrl-C.
  • Fewer threads. Each guest's tokio runtime is capped at 2 blocking threads.
  • Lifecycle is tested. Timed-out plugins back to back, followed by another: each is reported, the next runs, and no thread or temp file is left.
  • No performance regression. Against a separately built 0b25a35, measured with CPU time:
    • passthrough, 20k transactions: 2.93–3.02 s before, 2.85–3.05 s now;
    • passthrough, 100k transactions: 15.0–15.2 s before, 15.1–15.2 s now.
  • Platforms.
    • The code type-checks for Windows (gnu) and both macOS architectures.
    • Release binaries ship with no plugin runtime on any platform; they are built with --no-default-features, which predates this PR.
    • No CI job runs the plugin paths on macOS or Windows.
  • Memory ceiling. 4096 MiB is the wasm32 address-space limit; 3.5 GiB was verified to work at 4096. The MiB-to-bytes arithmetic is safe on 32-bit hosts.

Fourth review round (aad87fe)

  • Gap found: a WASM module's own text (here, its import names) still reached the terminal raw, in errors from extract --wasm-importer, importer directory scans and check --plugin. check --plugin also dropped the error's cause entirely. Fix: importer error messages that carry module text are now escaped: forbidden import, runtime trap, compile error and decode error. check --plugin reports the escaped cause. A test covers each path.
  • Escaping now also covers bidi override, embedding and isolate characters and U+2028/2029. It is idempotent (no double-escaping), and right-to-left and other non-ASCII text is preserved.
  • Checked, nothing to fix:
    • the 0700 work dir is created atomically with its mode (mkdir with a mode, not create-then-chmod);
    • the 2-thread runtime cap cannot deadlock the guest or starve the deadline;
    • JSON output deliberately carries the escaped text.

Fifth review round (d81c8b2)

I went through every message site that interpolates module or guest text.

  • Error chains re-printed raw. rledger printed the full anyhow chain, and the importer's trap and decode errors carried their raw source in it. Two crafted modules showed this: a trap whose backtrace names a function from the module's name section, and a decode error quoting an unknown variant. Fix: the top-level error printers in rledger and ag-rledger now escape the chain.
  • More unescaped messages: the invalid-entry reason, the enriched-importer bridge warnings, and the hot-reload warning each quoted guest text. All three are now escaped.
  • Resource-cap message wording: it now says it counts "open files and pending polls".

Also run

  • cargo fmt
  • cargo clippy --workspace --all-features --all-targets -D warnings
  • cargo test --all-features:
    • rustledger-plugin: 377 passed
    • rustledger-importer: 250
    • rustledger-loader: 258
    • rustledger: 967
  • cargo doc -D warnings for all four crates

Closes #2500

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

…udget

No Python plugin could run (#2500):

- The Python runtime's fixed 600M fuel was half of what CPython needs
  to start (measured 1.22G), so even a passthrough plugin trapped with
  "all fuel consumed". Python plugins now get the host's seconds
  budget (`[plugins] max_time_secs`, `--plugin-max-time-secs`,
  `LoadOptions::plugin_max_time_secs`), converted by the shared
  `sandbox::fuel_for_secs` with no Python multiplier: measured, CPython
  runs 3-6G fuel per CPU-second, the range other wasm runs at. The
  default 30 s covers startup 25x and a plugin over ~65k transactions.
- Entry points were looked up by the literal name `plugin`. A plugin
  file now runs as beancount's loader runs a module: each item of
  `__plugins__` in order (a name via getattr, or a callable), with the
  config string when present. No `__plugins__` runs nothing, with a
  warning; a listed name the module lacks is an error naming it.
- Entries were spliced into Python source as a string literal, so a
  narration with a quote or backslash broke their JSON. Inputs now go
  through files.

Adds end-to-end tests through the CPython WASI runtime, run in the
Python-gated cargo tests job, which fails if they skip.

Closes #2500

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen requested a review from a team as a code owner October 8, 2026 17:45
@github-actions

github-actions Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 44.9ms ± 1.7ms 816.7ms ± 3.4ms 18.2x 51.1 MB / 50.2 MB
investment 69.7ms ± 1.9ms 3064.1ms ± 47.4ms 43.9x 57.3 MB / 58.1 MB
fifo 66.3ms ± 1.0ms 15375.2ms ± 95.0ms 231.8x 55.1 MB / 58.0 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 43.9ms ± 0.3ms 44.9ms ± 1.7ms +2.3% ✅ within noise 51.1 MB → 51.1 MB (-0.0%)
investment 68.5ms ± 1.0ms 69.7ms ± 1.9ms +1.8% ✅ within noise 57.1 MB → 57.3 MB (+0.4%)
fifo 66.6ms ± 2.5ms 66.3ms ± 1.0ms -0.5% ✅ within noise 55.1 MB → 55.1 MB (+0.1%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.8ms, investment 0.9ms, fifo 1.2ms), and is at least 5%.
10,000 transactions per shape · 20 runs, 3 warmup · hyperfine

What do these numbers mean?
  • simple — Two-posting transfers, one currency. The historical workload — keep as the floor, not as the benchmark.
  • investment — Cost specs, per-unit prices and lot reductions. Exercises booking and inventory, which simple leaves at 0.3%.
  • fifo — Bare {} reductions against a FIFO account — how FIFO sells are normally written. The other four shapes reach the ordered-selection path twice in 2k transactions between them, so it was effectively unprofiled until it turned out to be quadratic (plan_ordered scans every lot per reduction: FIFO ledgers are quadratic (8.8s at 20k transactions) #2083).
  • vs base: the PR and the base-branch commit it is built on, built and measured in the same job
  • RSS: peak resident set size, a single sample — reported without a verdict because there is no spread to test it against
  • A shape with no beancount column is one bean-check reports errors on; it is timed for rledger only

@github-actions

github-actions Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 179 masked)
Full AST Match 100%
Total Files 819
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
    The headline is the EFFECTIVE rate, after pairs where beanquery
    itself is wrong are masked. raw is the same run with nothing
    masked. A widening gap means the registry grew, not that rledger
    changed.
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

Review round on #2525 (Python plugins, #2500):

- Metadata: the compat layer read a `meta` key the wire never has, so
  plugins saw no metadata and every round trip dropped it. It now
  arrives typed, with filename/lineno as in beancount, and returns
  with the plugin's changes.
- Errors: beancount-style error namedtuples are reported as message at
  source location, as bean-check does, and entries a plugin returns
  keep their source location (Modify, not Delete+Insert).
- Sandbox: /work was writable (1 GiB of host temp for 0.07 s of
  budget) and stderr was the host's. The guest now sees only /lib and
  /work, read-only; the result goes over a capped stdout, stderr is
  capped. Inputs/outputs stream one entry per line: 100k transactions
  fit the 256 MiB cap, where ~50k exhausted it.
- Limits: WASM plugins, WASM importers and Python plugins all say
  which limit ran out (time budget with how to raise it, or memory).
- python:leafonly / python:check_commodity reach the built-in Python
  plugins, which now match beancount's checks and messages.
- Concurrent first runs no longer race on the runtime download.
- Compat: data.filter_txns, amount.CURRENCY_RE, named stand-in
  modules; an uncaught exception's message is surfaced.

Adds tests/plugin_conformance.rs: every plugin kind through every
entry point (check/query/report, --native-plugin, --plugin, python:
forms, extract --wasm-importer) plus each sandboxed kind's limits,
run in the Python-gated job with RLEDGER_REQUIRE_WASM32 and
RLEDGER_REQUIRE_PYTHON_WASI so it cannot skip.

Refs #2500

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen

robcohen commented Oct 8, 2026 •

Copy link
Copy Markdown
Member Author

Adversarial review of this PR

Round 1 was fixed in 0b25a35, round 2 in 92b44b9, round 3 in 5ec918d, round 4 in aad87fe, round 5 in d81c8b2 and round 6 in 4155386 (a test only). The PR body has the measurements.

Security

Round 1

  • The Python guest could write to the host. /work was read-write: 1 GiB of host temp cost 0.07 s of budget, and stderr was the host's, unbounded. Fix: the guest sees only /lib and /work, read-only. The result goes over a capped stdout, and stderr is capped at 4 MiB.

Round 2: attacking the round-1 fix

  • A sleeping plugin hung the host. Waiting burns no fuel, so time.sleep(10**9) hung rledger indefinitely. Fix: the guest runs async on a thread of its own, under a wall-clock deadline equal to its time budget (it yields every 10M fuel).
  • A deep recursion aborted the host. The guest ran on the host thread's stack, which is smaller than its 16 MiB wasm stack, so rledger died with SIGABRT and no diagnostics. Fix: on the fiber, the recursion ends in the guest with a message.
  • Open files were uncapped host descriptors. A plugin reached the 1024 ulimit -n. Fix: the guest's WASI resource table is capped at 256.
  • Truncated output was trusted. Output cut short was read as "the plugin ran nothing". Fix: it is now an error.
  • A bad entry aborted the whole load. Any WASM or Python plugin returning an invalid entry stopped everything with processing pipeline failed (exit 2, every other diagnostic lost). This was pre-existing on main for WASM. Fix: the plugin's changes are discarded with an error, and the load goes on.

Checked and not exploitable

  • wasmtime version: 49.0.2, which has the RUSTSEC-2026-0321 poll_oneoff fix. WASM plugins and importers import nothing, so they cannot block.
  • Threads: RuntimeError: can't start new thread.
  • Memory bounds: stdin is empty. stdout is capped at 2×input + 64 MiB, and stderr at 4 MiB, by trapping writes past the cap; both buffer only up to their cap.
  • Hostile output to the decoder: a 50 MB single line, invalid UTF-8, NUL bytes, out-of-range, negative or duplicate entry indexes, and 100k-deep JSON nesting are each rejected cleanly or treated as inserts. None crashes the decoder.

Correctness (round 1)

  • Dropped metadata. Plugins never saw metadata, and every round trip dropped it.
  • Lost error details. Errors lost their message and location, and later diagnostics lost theirs too.
  • Built-in plugins. python:leafonly and python:check_commodity were unreachable, and both were wrong.
  • First-run download race. Concurrent first runs raced on the download.

Memory cap (round 2)

  • The fix: [plugins] max_memory_mb / --plugin-max-memory-mb (1 to 4096). It is threaded like the time budget (LoadOptions::plugin_max_memory_mb, ResolvedPlugin::run_with_limits) and, like it, is never the ledger's to set. The out-of-memory message says how to raise it.
  • Measured: a 300k-transaction (SFC-size) ledger runs a Python plugin with --plugin-max-memory-mb 1024 --plugin-max-time-secs 1000, in 72 s of CPU.

Native leafonly (round 2)

  • The bug: a parent whose child is only opened was missed. Children now come from every directive that names an account, as in beancount's realization, which also makes the check linear.
  • A test had hidden it: test_pedantic_runs_multiple_validators expected one error, and the one it got was the commodity's. The leaf violation the test is named for went undetected. The test is corrected.

Conformance matrix

  • Size: 39 tests, about 5.5 s warm and 15 s cold.
  • Flakiness: 10 consecutive local runs, all green.
  • Cold start: with an empty CPython cache and no prebuilt guests it is green, so there is no cache dependency. CI has no rust-cache either, so it is always cold.
  • Required check: the matrix runs in Python-gated cargo tests, a required check that is not path-filtered. RLEDGER_REQUIRE_WASM32 and RLEDGER_REQUIRE_PYTHON_WASI make a skip a failure.
  • Mutation testing: 30 mutations in total (19 in round 1, 11 in round 2), each caught. The round-2 set: no clock deadline, uncapped resource table, truncated output accepted, a bad entry aborting the load, the memory cap not threaded for each of the three kinds, the config key or flag ignored, and leafonly reverted.

Round 3: reviewing the round-2 machinery

Platforms

  • Release binaries ship without any plugin runtime. Every GitHub release binary, on every platform, is built with --no-default-features, so none of them include the Python or WASM plugin runtimes or the WASM importer. This predates this PR. On macOS and Windows the new code therefore runs only for cargo install / source builds.
  • No CI job exercises the plugin paths on macOS or Windows. The only non-Linux CI job runs cargo test -p rustledger-lsp, and the LSP is native-plugin-only.
  • What I checked: cargo check -p rustledger (default features, so the async guest, fibers and tokio are all in) is clean for x86_64-pc-windows-gnu, aarch64-apple-darwin and x86_64-apple-darwin.
  • Nothing is Unix-only by construction. The one Unix API, the 0700 permission below, is gated cfg(unix). Fibers, tokio's current-thread runtime and CPython-WASI are all supported by wasmtime on those targets.
  • But none of it has been run there. Recommendation: add a non-required, nightly or workflow_dispatch macOS + Windows job that runs plugin_conformance and python_plugin_wasi. I have not added it.

Lifecycle

  • Timeout, back to back, and SIGINT: when the deadline fires, the guest future is dropped, the runtime goes with it, and the scoped thread is joined. Two Python plugins timed out back to back, followed by a third, behave correctly: each is reported, the next one runs, the process ends promptly, and no temp files are left. That case is now a test.
  • SIGINT exits at once (code 130). It leaves the plugin's temp dir behind, which holds the ledger's entries.
    • Found: that dir followed the umask (0775 here), so other local users could read it.
    • Fix: it is now 0700 on Unix. Test added.
    • No Ctrl-C cleanup handler was added.
  • Thread count: one call started up to 26 tokio blocking threads. The pool is now capped at 2.

Performance: I built a 0b25a35 binary separately and measured the same workloads:

Workload 0b25a35 CPU Now CPU
passthrough, 20k transactions (3 runs each) 2.93–3.02 s 2.85–3.05 s
passthrough, 100k transactions 15.0–15.2 s 15.1–15.2 s
startup 0.19 s 0.19 s

No regression.

Control characters, fixed in this PR. This covers plugin- and importer-supplied text: messages, claimed file names, Python prints and exceptions, WASM failure text, importer warnings, and importer name and description. Their control characters are now escaped (\u{1b}); messages keep newline and tab. One rustledger_plugin::untrusted module does the escaping, and a conformance case covers each channel. Ledger strings remain a separate follow-up.

  • Coverage caveat: the check --plugin rendering in check.rs is escaped too, but no test reaches it, because the guest can't receive a config string via --plugin.

The 4096 MiB memory ceiling

  • Why 4096: it is the wasm32 address-space limit (65536 pages). CPython-WASI declares no memory maximum, and with --plugin-max-memory-mb 4096 a plugin held 3.5 GiB.
  • What that covers: at about 1.2 KB per transaction, 4 GiB covers about 3M transactions, so a 1M-transaction ledger fits. Going higher would need memory64, which neither the CPython build nor the WASM plugin ABI supports.
  • 32-bit hosts: MiB → bytes uses u64 saturating_mul, then usize::try_from(..).unwrap_or(usize::MAX), so there is no overflow on a 32-bit host.

Mutation testing: I applied 6 more mutations, and each was caught: the work dir following the umask, plus each escaping site removed in turn (plugin message, claimed file name, guest stderr, Python run error, importer warning). That makes 36 across all rounds.

Round 4: reviewing what round 3 added

Escaping

  • Gap found: a WASM module's own text (here, its import names) still reached the terminal raw. It got through in load errors from extract --wasm-importer and from importer directory scans. check --plugin printed only invalid plugin, so it never showed the cause at all. Fix: importer error messages that carry module text are now escaped: forbidden import, runtime trap (whose backtrace includes function names from the module), compile error and decode error. check --plugin now shows the cause, escaped. A test covers all four paths; it doesn't cover the runtime-trap and decode messages specifically.
  • Character coverage: C0, DEL and C1 (U+0080–9F) were already escaped, and so is a lone \r. Bidirectional override, embedding and isolate characters (U+202A–E, U+2066–9) and U+2028/2029 are now escaped too. Right-to-left text and zero-width characters are kept on purpose: they can mislead only as any text can.
  • No double-escaping: escaping is idempotent, because its output contains no character it escapes. A unit test checks this. Non-ASCII text such as Hebrew or accented letters passes through unchanged.
  • JSON output keeps the escaped form. These messages are display text, and the usual JSON consumers (CI annotations, editors, web UIs) show them verbatim. Sending raw controls would push the sanitizing onto every one of them. serde would still emit DEL and C1 raw.
  • Not escaped here: strings in entries a plugin returns (narrations, metadata) shown by query and report. The parser and beancount both accept raw control characters in ledger strings, and the plugin is named by the ledger itself. So such a string is no different from one the ledger author wrote directly, and it falls under the ledger-strings follow-up. Line numbers are integers.

0700 work directory: created atomically with that mode. tempfile uses DirBuilder::mode, i.e. mkdir with the mode, so there is no window before a chmod. The guest writes nothing; its preopens are read-only. The only other files written are the CPython download/extract staging and the .cwasm cache, both in the user's own cache directory. The cache is written via temp file and atomic rename, and is header-checked before it is loaded.

2-thread cap: no deadlock or starvation.

  • Why: the guest is single-threaded wasm, so its WASI calls run one at a time. The deadline timer runs on the runtime driver, not on the blocking pool.
  • Tried: a select() loop over 10 open files for 100k iterations finished normally, with no leaked pollables. Re-reading a file in a loop and a 1000 s select() were each stopped at the 3 s deadline (3.01 s wall).
  • Minor wording issue, not changed: select() over about 100 files also fills the 256-entry WASI resource table, because pollables count too. That is correct behavior, but the message says "files open" when the count is really "files and pollables".

#2536 is another lane's PR (fix/effective-date-open-order), not mine.

Mutation testing: I applied 2 more mutations (removing the forbidden-import escape, removing the check --plugin escape), and each was caught. That makes 38 across all rounds.

Round 5: every remaining place guest text reaches output

The sweep: I went through every format!, anyhow!, bail!, #[error], context and eprintln! site in the plugin runtime, dispatch, sandbox, Python runtime, importer, loader, and the CLI's plugin and importer reporting.

Already safe

  • Escaped where they are shown: the plugin runtime's forbidden-import and failure messages (by the loader, or by check --plugin), and all PythonError text (by the loader).
  • Host text or integers only: paths, sizes, caps, ABI versions, and the export signatures, whose names are &'static.
  • invalid directive: {e:?}: Debug already escapes control characters.

Leaks found and fixed

  • Error chains re-printed raw. rledger printed an error's whole anyhow chain ({e:#}). The importer's runtime and decode errors keep their wasmtime/rmp error as #[source], so the raw text came back in the chain even though their own Display was escaped. Two crafted modules showed it: a trap whose backtrace names a function from the module's name section, and an unknown variant quoted by serde's Display. Fix: rledger's top-level error printer, and ag-rledger's error envelope, now escape the whole chain.
  • Invalid-entry message quoted the bad value raw. That is the message added in round 2, e.g. a date. Now escaped.
  • Enriched-importer bridge warnings quoted the importer's method and fingerprint strings raw. Today only library callers reach this; the CLI does not. Now escaped.
  • Plugin hot-reload failure warning quoted the module's imports raw. Now escaped; there is no test for it.

Left as is

  • booking error … (date, "narration") quotes a ledger string; it goes with the ledger-strings follow-up.

Message wording: the resource-cap message now reads "held more than 256 open files and pending polls at once".

Tests and mutation testing

  • New tests: crafted trap and decode modules, an invalid-entry value carrying controls, and a unit test for the bridge warnings.
  • I applied 3 more mutations, one per new escape (top-level chain, invalid-entry value, bridge warnings), and each was caught; that makes 41 across all rounds.
  • The matrix is now 39 tests.

Round 6: convergence check

Does escaping the whole chain change normal output? No.

  • How I checked: I built origin/main separately and compared its output with this branch's, byte for byte. The cases were:
    • a parse error;
    • a booking error with a non-ASCII narration and account names;
    • missing files under a non-ASCII path, for check, report and extract;
    • a BQL syntax error with a tab;
    • a config TOML error whose snippet contains a tab and ü.
  • Result: every case is identical. The only difference is the binary's own name in a usage line.
  • On a terminal: run under a pty, the colored output (38 escape sequences) is also byte-identical. Colors come from the diagnostic renderer, not from the error chains render_error sees.
  • Why it holds: escaping keeps \n and \t, and host error text has no other control characters.

Paths that bypass render_error: none left that carry guest text.

Hot-reload escape: now tested. The warning text comes from a new function, reload_failure_warning, with a unit test that fails if the escape is removed. Hot reload is library-only; no binary calls it.

Conclusion: nothing else real found. Everything still unescaped is ledger text, tracked in #2538.

Decisions for you

  1. Default time budget stays 30 s. This also sets the wall-clock bound for Python.
  2. CI on macOS and Windows. Whether to add the non-required plugin job recommended above.

Follow-ups (not filed)

  • Message differences: native and Python plugin messages and severities differ, for example check_commodity.
  • Compat shim: add realization / compare, which beancount's own leafonly and noduplicates need.
  • Ledger strings: Escape control characters in ledger strings on output #2538.
  • CI: the macOS and Windows plugin job recommended above.

robcohen and others added 5 commits October 8, 2026 20:37
…p a host setting

Second review round on #2525 (#2500), attacking the sandbox:

- A Python plugin's sleep burned no fuel, so time.sleep(10**9) hung
  rledger. The guest now runs async on its own thread and fiber under
  a wall-clock deadline of its time budget.
- A deep recursion overflowed the host thread's stack (smaller than
  the guest's) and aborted rledger with SIGABRT. On the fiber it ends
  in the guest with a message.
- Each open file was an uncapped host descriptor (a plugin reached the
  1024 ulimit). The guest's WASI resource table is capped at 256.
- Output without its result line was read as "ran nothing"; it is now
  an error. A plugin returning an invalid entry (WASM or Python)
  aborted the whole load with exit 2; its changes are now discarded
  with an error and the load goes on.
- The sandbox memory cap is a host setting: [plugins] max_memory_mb /
  --plugin-max-memory-mb (1-4096), threaded like the time budget via
  LoadOptions::plugin_max_memory_mb and ResolvedPlugin::run_with_limits.
  A 300k-transaction ledger runs a Python plugin at 1024 MiB.
- Native leafonly counts children named by any directive, as
  beancount's realization does, so a parent whose child is only opened
  is reported; a pedantic test that encoded the miss is corrected.

Each fix has a plugin_conformance case that fails without it.

Refs #2500

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Third review round on #2525 (#2500):

- Plugin- and importer-supplied text (messages, claimed file names,
  Python prints and exceptions, importer warnings, names) reached the
  terminal raw, so control sequences could clear the screen, retitle
  it or overwrite lines. rustledger_plugin::untrusted escapes control
  characters (keeping newline and tab in messages) everywhere that
  text is rendered.
- The Python plugin's work directory, which holds the ledger's
  entries and survives a Ctrl-C, followed the umask (0775); it is now
  0700 on Unix.
- The guest's tokio runtime is limited to 2 blocking threads (one
  call used to start dozens).

Measured: passthrough 20k and 100k transactions cost the same CPU as
0b25a35 (within 1%). Back-to-back Python plugins after a deadline
leave no threads or temp files; conformance cases cover both.

Refs #2500

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Fourth review round on #2525 (#2500):

- A WASM module's import names reached the terminal raw in load
  errors from extract --wasm-importer, importer directory scans and
  check --plugin (which also dropped the cause). Importer error
  messages that carry the module's text (forbidden imports, runtime
  traps, compile and decode errors) are now escaped, and check
  --plugin reports the escaped cause.
- The untrusted-text escaping also covers the bidirectional override,
  embedding and isolate characters and the Unicode line separators;
  right-to-left text and zero-width characters are kept, and the
  escaping is idempotent.

Refs #2500

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
robcohen and others added 4 commits October 9, 2026 02:42
Fifth review round on #2525 (#2500), an inventory of every message
site that quotes module or guest text:

- rledger printed an error's whole anyhow chain, and the importer
  errors' sources (a trap backtrace naming the module's functions, a
  decode error quoting what it returned) re-entered the chain raw. The
  top-level error printers of rledger and ag-rledger now escape the
  chain.
- The "plugin returned an entry that is not valid" reason quotes the
  plugin's value; the enriched importer's bridge warnings quote its
  method and fingerprint strings; a hot-reload failure quotes the
  module's imports. All escaped.
- The resource-cap message says it counts open files and pending
  polls, which is what the WASI table holds.

Refs #2500

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Sixth review round on #2525 (#2500): the plugin hot-reload warning's
escape had no test. Its text now comes from reload_failure_warning,
unit-tested with a forbidden import name carrying a control sequence.

Refs #2500

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
robcohen added a commit that referenced this pull request Oct 20, 2026
…tput (#2710)

Ledger strings (narrations, payees, metadata, comments, document paths)
reached the terminal raw in check diagnostics (message and miette
snippet), query tables and report text. They are now escaped with
rustledger_plugin::untrusted's rule (#2525), as are price fetch-failure
lines. Data output keeps the value: CSV, PRINT, -f beancount and format
write it as is; JSON escapes DEL, C1, bidi controls and line separators as
\uXXXX, which decode to the same string. extract neutralizes control
characters in imported text (tab/newline to a space, others to U+FFFD)
with a warning naming the row and field, and `rledger lint control-chars`
reports the ones already in a ledger (#2538).


Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
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.

Python plugins don't run: PYTHON_FUEL too small for CPython startup, and entry points ignore __plugins__

1 participant