Skip to content

fix(query): give WASM and FFI queries the same sources and balance discrepancies as the CLI - #2857

Merged
robcohen merged 5 commits into
mainfrom
fix/wasm-ffi-query-sources
Nov 4, 2026
Merged

robcohen merged 5 commits into
mainfrom
fix/wasm-ffi-query-sources

Conversation

@robcohen

@robcohen robcohen commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

; a duplicate include, an include cycle or an empty include glob is reported beside the rows |## What changed

Every WASM query entry point (query, queryMultiFile, ParsedLedger, Ledger) and every FFI one (query, batch, query-file, batch-file, session) built a bare query executor with no source map and no balance discrepancies. On rustfava's default path and in @rustledger/wasm, these read NULL while rledger query filled them:

  • the filename, lineno and location columns;
  • meta('lineno') and entry_meta('filename');
  • #balances.discrepancy.

One constructor for every host. Executor::for_ledger(directives, source_map, LedgerContext) in rustledger-query is now used by the CLI, all WASM entry points and all FFI entry points. LedgerContext carries the account types, booking method, summary accounts and a BalanceDiscrepancies source:

  • Unavailable;
  • Known(list);
  • Lazy, computed only when a query reads the column.

Discrepancies without validating every load. WASM queryMultiFile now validates, as rledger query does, and stops only on a booking failure; validation diagnostics come back alongside the rows. The other WASM and FFI paths keep their load-only contract:

  • BalanceDiscrepancies::recomputed_from defers the work until the compiled query reads discrepancy. A SELECT *, a subquery or a CREATE TABLE AS over #balances counts, decided from the query AST rather than its text.
  • The work runs at most once per executor, and once per FFI session, batch or ParsedLedger.
  • It calls the new rustledger_loader::recompute_balance_discrepancies, which re-runs the loader's own validating pipeline over the source map's files. That makes the result exactly Ledger::balance_discrepancies: no second copy of the balance check, and no disk reads, since files decrypted by the host are already plain text in the source map.
  • An ordinary query costs nothing extra.

Matching bean-query (beanquery 0.2.0), checked on the issues' ledgers:

Column Before Now
location path:4 (CLI), NULL (WASM, FFI) path:4:, bean-query's trailing colon, on every surface
filename of an in-memory source NULL <string>, as beancount's load_string names it
a pad's synthesized transaction empty filename and line 0, every surface #entries: the pad line; postings: the balance line they satisfy, as bean-query reports them
a directive a plugin created empty filename and line 0 where the plugin located it, as in beancount: <auto_accounts>, line = its position in the plugin's output; a Python plugin's new_metadata('<myplug>', 7), <myplug>, 7
FFI query-file / batch-file <string>, includes unresolved the real files, includes resolved (confined as load-file confines them); a duplicate include is reported beside the rows
a directive with no origin at all empty filename and line 0 NULL

The only directives with no origin are entries an embedder hands in (query-entries, session.from-entries) and a Ledger.fromCache, which keeps no source map.

Supporting changes:

  • rustledger-booking: PadResult::padding_origins records each padding transaction's pad and balance. merge_with_padding_spanned uses them.
  • rustledger-query: spanned_from_parts is the one place kept spans go back onto plain directives (WASM and FFI).
  • WASM:
    • ParsedLedger, Ledger and query keep directive spans.
    • The ParsedLedger cache payload gains directive_spans, so the WASM cache goes to v70.
    • A Ledger.fromCache keeps no source map, so its source columns read NULL.
  • FFI:
    • LoadResult and FileLoad keep the loader's source map.
    • The in-memory VFS file is named <string> (it was <source>, never user-visible).
    • File sessions rebuild spans from each directive's line and file after session plugins run, so plugins that add or drop directives can't misalign them.
    • The <stdin> label in session entry output is unchanged; it doesn't reach query results.

How to test

  • cargo test -p rustledger-query --test ledger_context_test:
    • source columns and the accessors through for_ledger;
    • known discrepancies;
    • the lazy source runs only for queries that read the column, at most once per executor (8 query shapes);
    • pad locations;
    • spanned_from_parts.
  • cargo test -p rustledger-loader --test recompute_balance_discrepancies_test. This is the drift guard: recomputed discrepancies equal the validating load's. It covers every in-tree ledger, a dedicated ledger with several failing assertions (same account and date with different amounts, a pad, a tolerance pass, two currencies), and an assertion in an included file.
  • cargo test -p rustledger-ffi-component query_sources:
    • query, batch, session from source and from file, all matching bean-query;
    • query-entries reading NULL;
    • a drift guard showing the FFI session answers what the CLI path (a validating load plus for_ledger) answers on the same file.
  • cd crates/rustledger-wasm && wasm-pack test --node -- --test wasm_query_sources: 5 passed (query, queryMultiFile, ParsedLedger, ParsedLedger.fromCache, Ledger.fromFiles).
  • Locally:
    • cargo test on booking, loader, query, wasm, ffi-wasi, ffi-component and rustledger with --all-features: all pass;
    • clippy -D warnings, rustdoc -Dwarnings with private items, and cargo fmt --check: clean.

Not run against main: the new tests call APIs that don't exist there (for_ledger, recompute_balance_discrepancies, padding_origins), so they can't compile on main. The NULLs on main are what #2823 and #2825 report. The CLI's old location and pad values were the "test.beancount:1", "f.bean:7" and empty-filename assertions this PR updates.

Review round 1

  • Symlinked includes: the discrepancy rerun keyed its files by identity (symlinks resolved) while the loader resolves includes against the opened path, so behind a symlinked directory it dropped the included files and reported -30 USD for an assertion that passes. It now keys by opened path. The drift guard gained the symlink case (a real symlink in a tempdir).
  • Plugin-created directives now name the plugin, matching bean-query 0.2.0 (<auto_accounts>, lines 0 and 1): the executor resolves the loader's placeholder locations. WASM single-string loads keep the loader's source map (the in-memory file is now <string>, which also becomes the file of WASM load errors there), so placeholders survive.
  • FFI query-file / batch-file load the file as a file (includes resolved and confined), instead of querying the text as an unnamed source.
  • Session plugins: an FFI session's discrepancy rerun passes the session's plugins as extra_plugins, which the loader runs after the file's own in the post-booking pass, as from_file ran them. BalanceDiscrepancies::recomputed_from now takes the load options.
  • MCP: queryMultiFile leaves advisory-only codes out (E1004), through rustledger_validate::is_advisory_only_code, as rledger query does. The MCP server's query_file now fails only when the query could not run (no columns: a parse or booking failure, or a bad query) and shows diagnostics beside the rows, so a ledger with a failing assertion still answers. Two vitest cases pin it; they also pass against the published 0.24.0.
  • WIT contract bumped to rustledger:[email protected] (behavior change on every query entry point and on query-file / batch-file); scripts/check-wit-version-bump.sh and check-wit-version-citations.sh pass.
  • Docs: docs/reference/bql.md describes location as filename:lineno: and where pad and plugin directives are located.
  • Perf: WASM ParsedLedger and Ledger build the spanned, pad-expanded directives once per ledger instead of per query.

Verification on 8b0450e: cargo test on booking, loader, query, wasm, ffi-wasi, ffi-component and rustledger (--all-features): 176 result lines, 0 failed; wasm-pack test --node -- --test wasm_query_sources: 5 passed; mcp-server vitest: 126 passed; clippy -D warnings, rustdoc -Dwarnings, cargo fmt --check clean.

Review round 2

  • Plugin-created directives through a file (FFI query-file, batch-file, session.from-file): these read NULL because load_file_with_fs flattened the loader's placeholder locations to <unknown>, 0. FileLoad now carries each directive's placeholder (name, line); a session from a file passes it through its own plugins and resolves it back to the placeholder id, so SELECT type, filename, lineno FROM #entries gives open, <auto_accounts>, 0/1 as the CLI and bean-query do. Entry output keeps <unknown>, 0, the generated-entry fingerprint embedders key on. Tested for all three, with and without a session plugin.
  • ParsedLedger.fromCache: the cache payload now carries the source map's placeholder locations in id order, and fromCache registers them again, so a restored ledger names the plugin like a fresh one. WASM cache bumped to v71. New node test.
  • Python plugins: the bridge already had the entry's meta, but it never sent the filename or lineno of a new entry back. A new entry now carries them, so new_metadata('<myplug>', 7) reports <myplug>, 7, as bean-query does, through the loader's placeholder path. A modified entry keeps its input's location, as before. Test: python_plugin_wasi::a_created_entry_is_located_at_its_meta.
  • Duplicate includes on the FFI file paths: the rule now lives in the loader, LoadError::leaves_ledger_complete (true only for a duplicate include), and LedgerError::leaves_ledger_complete exposes it. WASM queryMultiFile delegates to it. FFI query-file, batch-file and a session from a file answer over a duplicate include and report it in errors beside the rows; session plugins still run. Any other load error still refuses (tested with ../outside.beancount). No WIT signature change.
  • Docs: the CHANGELOG and the WIT comments now cover the rest of the file-path change:
    • includes are confined, and query-file / batch-file have no opt-out, so an include outside the root (or behind a symlink pointing out) is now a load error with no rows;
    • the load-failure message is now Failed to load file: ..., where it was Failed to read file ...;
    • batch-file repeats the load errors in each query;
    • batch-file's load has the load-file shape.
  • Symlink test comment: now says the loader resolves .. lexically (loader: includes are resolved next to a symlink's target; beancount resolves them next to the link #2635). beancount 3.2.3 resolves it physically and reports File glob "../other.beancount" does not match any files.
  • Known limit, documented: a WASM Ledger restored with fromCache keeps no source, so its source columns and discrepancies read NULL, as on main. Fixing it would mean archiving the source files in the Ledger payload.

Verification on da6ba21: cargo test on booking, loader, query, wasm, ffi-wasi, ffi-component, plugin and rustledger (--all-features): 186 result lines, 0 failed, the CPython WASI suite included (the new Python test fails without the fix); wasm-pack test --node -- --test wasm_query_sources: 6 passed; clippy -D warnings, rustdoc -Dwarnings, cargo fmt --check clean; both WIT version scripts pass.

Review round 3

  • LoadError::leaves_ledger_complete is now true for an include cycle (the file included again was already read) and an include glob matching nothing, as well as a duplicate include. bean-query and rledger query answer over both, and FFI query-file, batch-file, session.from-file and WASM queryMultiFile now do too. Tests: test_file_queries_answer_over_a_complete_ledger_load_error (all three cases on the three FFI file paths, plus a confined include that still refuses), query_multi_file_answers_over_a_cycle_and_an_empty_glob (node), and the WASM predicate test now pins both as non-fatal.
  • The docs and WIT comments now state each surface's rule: the FFI file paths and queryMultiFile use leaves_ledger_complete, while rledger query refuses only on a parse or booking error, so it also answers over a missing include. Unifying these rules is out of scope here; it is being filed separately.

Verification on 3714857: cargo test on loader, wasm, ffi-wasi, ffi-component and rustledger (--all-features): 98 result lines, 0 failed; wasm-pack test --node -- --test wasm_query_sources: 7 passed; clippy -D warnings, rustdoc -Dwarnings, cargo fmt --check clean; both WIT version scripts pass.

Closes #2823
Closes #2825

🤖 Generated with Claude Code

…screpancies as the CLI

Every WASM query entry point (query, queryMultiFile, ParsedLedger,
Ledger) and every FFI one (query, batch, the file variants, session)
built a bare executor with no source map and no discrepancies, so
filename / lineno / location, the source metadata accessors and
#balances.discrepancy read NULL there while the CLI filled them.

- rustledger-query: `Executor::for_ledger(directives, source_map,
  LedgerContext)` is the one constructor the CLI, WASM and FFI use.
  `BalanceDiscrepancies::{Unavailable, Known, Lazy}`; a lazy source runs
  only when the compiled query reads the column (a SELECT *, subquery or
  CREATE TABLE AS over #balances counts), at most once per executor, and
  `recomputed_from` memoizes across a session or batch.
  `spanned_from_parts` puts kept spans back on plain directives.
  `location` is `path:line:`, as bean-query prints it. A directive with
  no file in the source map has no location (NULL, not "" and 0).
- rustledger-loader: `recompute_balance_discrepancies` re-runs the
  loader's own validating pipeline over the source map's files, so a
  load-only embedder gets exactly `Ledger::balance_discrepancies`.
- rustledger-booking: `PadResult::padding_origins`; a pad's synthesized
  transaction is located at its pad (#entries) and its postings at the
  balance they satisfy, as bean-query reports them.
- WASM: queryMultiFile validates and stops only on a booking failure,
  as `rledger query` does. Single-string sources are named `<string>`.
  ParsedLedger cache payload gains directive spans (WASM cache v70).
- FFI: LoadResult / FileLoad keep the source map; the in-memory VFS
  file is named `<string>`; sessions keep spans (file sessions rebuild
  them from line and file after session plugins run).

Closes #2823
Closes #2825

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner November 4, 2026 05:32
@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 32.8ms ± 1.3ms 493.1ms ± 12.3ms 15.0x 34.5 MB / 51.2 MB
investment 53.2ms ± 7.3ms 1672.4ms ± 28.0ms 31.5x 44.6 MB / 59.1 MB
fifo 48.8ms ± 1.1ms 8508.8ms ± 296.0ms 174.5x 40.8 MB / 58.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 34.7ms ± 4.9ms 32.8ms ± 1.3ms -5.3% ✅ within noise 34.6 MB → 34.5 MB (-0.0%)
investment 52.5ms ± 1.7ms 53.2ms ± 7.3ms +1.3% ✅ within noise 44.6 MB → 44.6 MB (+0.1%)
fifo 49.4ms ± 0.8ms 48.8ms ± 1.1ms -1.3% ✅ within noise 40.6 MB → 40.8 MB (+0.6%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 2.3ms, investment 3.4ms, fifo 0.6ms), 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

@codecov

codecov Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.64356% with 29 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-query/src/executor/mod.rs 79.83% 25 Missing ⚠️
crates/rustledger-loader/src/process.rs 50.00% 3 Missing ⚠️
crates/rustledger-loader/src/lib.rs 96.15% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Nov 4, 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 826
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

robcohen and others added 2 commits November 4, 2026 01:28
…eries, MCP

- recompute_balance_discrepancies keys its rerun's files by the path each
  was opened by, as the loader resolves includes: behind a symlinked
  directory the identity path dropped the included files and reported a
  discrepancy for an assertion that passes.
- A plugin-created directive names its plugin, as bean-query does
  (`<auto_accounts>`, line = its position in the plugin's output): the
  executor resolves the loader's placeholder locations. WASM single-string
  loads keep the loader's source map (the VFS file is now `<string>`), so
  the placeholders survive there too.
- FFI `query-file` / `batch-file` load the ledger as a file (includes
  resolved, confined as `load-file` confines them) instead of querying the
  text as an unnamed source.
- An FFI session's discrepancy rerun runs the session's plugins after the
  file's own, as `from_file` ran them (`recomputed_from` takes the load
  options).
- `queryMultiFile` leaves advisory-only codes out, through
  `is_advisory_only_code` as `rledger query` does; the MCP server's
  `query_file` fails only when the query could not run and shows
  diagnostics beside the rows.
- WASM `ParsedLedger` / `Ledger` build the spanned, pad-expanded
  directives once per ledger.
- WIT contract rustledger:[email protected]; docs: `location` is
  `filename:lineno:`, and where plugin and pad directives are located.

Part of #2823, #2825.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ache

Review round 2 of #2857:

- FFI query-file, batch-file and session.from-file resolve the loader's
  placeholder locations, so a directive a plugin created names the plugin
  (<auto_accounts>, 0) instead of NULL; entry output keeps <unknown>, 0.
- ParsedLedger.fromCache restores the placeholders (WASM cache v71).
- A Python plugin's new entry carries its meta filename / lineno, so
  new_metadata("<myplug>", 7) reports <myplug>, 7 as bean-query does.
- A duplicate include no longer stops the FFI file queries; the rule is
  the loader's new LoadError::leaves_ledger_complete, which WASM
  queryMultiFile now shares.
- Document confinement, the load-failure message, batch-file's load
  shape and repeated load errors; correct the symlink test comment.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen and others added 2 commits November 4, 2026 03:27
LoadError::leaves_ledger_complete was true only for a duplicate include,
so FFI query-file, batch-file, session.from-file and WASM queryMultiFile
returned no rows over an include cycle (the file included again was
already read) or an include glob matching nothing, where bean-query and
rledger query answer. Both now count. Tests on the FFI file paths and
queryMultiFile; the docs and WIT comments state which rule each surface
uses (rledger query refuses only on parse or booking errors).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…urces

# Conflicts:
#	CHANGELOG.md
#	crates/rustledger-wasm/src/cache.rs
@robcohen
robcohen enabled auto-merge (squash) November 4, 2026 14:22
@robcohen
robcohen merged commit b577efe into main Nov 4, 2026
68 of 69 checks passed
@robcohen
robcohen deleted the fix/wasm-ffi-query-sources branch November 4, 2026 14:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant