Repository navigation
fix(query): give WASM and FFI queries the same sources and balance discrepancies as the CLI - #2857
Merged
Merged
Conversation
…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]>
Contributor
📊 Benchmark Results
vs base, measured in this run
A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: What do these numbers mean?
|
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
Contributor
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
…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]>
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
; 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 whilerledger queryfilled them:filename,linenoandlocationcolumns;meta('lineno')andentry_meta('filename');#balances.discrepancy.One constructor for every host.
Executor::for_ledger(directives, source_map, LedgerContext)inrustledger-queryis now used by the CLI, all WASM entry points and all FFI entry points.LedgerContextcarries the account types, booking method, summary accounts and aBalanceDiscrepanciessource:Unavailable;Known(list);Lazy, computed only when a query reads the column.Discrepancies without validating every load. WASM
queryMultiFilenow validates, asrledger querydoes, 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_fromdefers the work until the compiled query readsdiscrepancy. ASELECT *, a subquery or aCREATE TABLE ASover#balancescounts, decided from the query AST rather than its text.ParsedLedger.rustledger_loader::recompute_balance_discrepancies, which re-runs the loader's own validating pipeline over the source map's files. That makes the result exactlyLedger::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.Matching bean-query (beanquery 0.2.0), checked on the issues' ledgers:
locationpath:4(CLI), NULL (WASM, FFI)path:4:, bean-query's trailing colon, on every surfacefilenameof an in-memory source<string>, as beancount'sload_stringnames it#entries: thepadline; postings: thebalanceline they satisfy, as bean-query reports them<auto_accounts>, line = its position in the plugin's output; a Python plugin'snew_metadata('<myplug>', 7),<myplug>, 7query-file/batch-file<string>, includes unresolvedload-fileconfines them); a duplicate include is reported beside the rowsThe only directives with no origin are entries an embedder hands in (
query-entries,session.from-entries) and aLedger.fromCache, which keeps no source map.Supporting changes:
rustledger-booking:PadResult::padding_originsrecords each padding transaction's pad and balance.merge_with_padding_spanneduses them.rustledger-query:spanned_from_partsis the one place kept spans go back onto plain directives (WASM and FFI).ParsedLedger,Ledgerandquerykeep directive spans.ParsedLedgercache payload gainsdirective_spans, so the WASM cache goes to v70.Ledger.fromCachekeeps no source map, so its source columns read NULL.LoadResultandFileLoadkeep the loader's source map.<string>(it was<source>, never user-visible).<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:for_ledger;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,sessionfrom source and from file, all matching bean-query;query-entriesreading NULL;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).cargo teston booking, loader, query, wasm, ffi-wasi, ffi-component and rustledger with--all-features: all pass;-D warnings, rustdoc-Dwarningswith private items, andcargo 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 oldlocationand pad values were the"test.beancount:1","f.bean:7"and empty-filename assertions this PR updates.Review round 1
-30 USDfor an assertion that passes. It now keys by opened path. The drift guard gained the symlink case (a real symlink in a tempdir).<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 thefileof WASM load errors there), so placeholders survive.query-file/batch-fileload the file as a file (includes resolved and confined), instead of querying the text as an unnamed source.extra_plugins, which the loader runs after the file's own in the post-booking pass, asfrom_fileran them.BalanceDiscrepancies::recomputed_fromnow takes the load options.queryMultiFileleaves advisory-only codes out (E1004), throughrustledger_validate::is_advisory_only_code, asrledger querydoes. The MCP server'squery_filenow 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.rustledger:[email protected](behavior change on every query entry point and onquery-file/batch-file);scripts/check-wit-version-bump.shandcheck-wit-version-citations.shpass.docs/reference/bql.mddescribeslocationasfilename:lineno:and where pad and plugin directives are located.ParsedLedgerandLedgerbuild the spanned, pad-expanded directives once per ledger instead of per query.Verification on 8b0450e:
cargo teston 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 --checkclean.Review round 2
query-file,batch-file,session.from-file): these read NULL becauseload_file_with_fsflattened the loader's placeholder locations to<unknown>, 0.FileLoadnow 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, soSELECT type, filename, lineno FROM #entriesgivesopen, <auto_accounts>, 0/1as 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, andfromCacheregisters them again, so a restored ledger names the plugin like a fresh one. WASM cache bumped to v71. New node test.meta, but it never sent the filename or lineno of a new entry back. A new entry now carries them, sonew_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.LoadError::leaves_ledger_complete(true only for a duplicate include), andLedgerError::leaves_ledger_completeexposes it. WASMqueryMultiFiledelegates to it. FFIquery-file,batch-fileand a session from a file answer over a duplicate include and report it inerrorsbeside the rows; session plugins still run. Any other load error still refuses (tested with../outside.beancount). No WIT signature change.query-file/batch-filehave no opt-out, so an include outside the root (or behind a symlink pointing out) is now a load error with no rows;Failed to load file: ..., where it wasFailed to read file ...;batch-filerepeats the load errors in each query;batch-file'sloadhas theload-fileshape...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 reportsFile glob "../other.beancount" does not match any files.Ledgerrestored withfromCachekeeps no source, so its source columns and discrepancies read NULL, as on main. Fixing it would mean archiving the source files in theLedgerpayload.Verification on da6ba21:
cargo teston 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 --checkclean; both WIT version scripts pass.Review round 3
LoadError::leaves_ledger_completeis 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 andrledger queryanswer over both, and FFIquery-file,batch-file,session.from-fileand WASMqueryMultiFilenow 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.queryMultiFileuseleaves_ledger_complete, whilerledger queryrefuses 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 teston 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 --checkclean; both WIT version scripts pass.Closes #2823
Closes #2825
🤖 Generated with Claude Code