Skip to content

refactor: the source-text query surfaces answer by the file-based rule - #2889

Merged
robcohen merged 5 commits into
mainfrom
fix/source-query-rule
Nov 7, 2026
Merged

robcohen merged 5 commits into
mainfrom
fix/source-query-rule

Conversation

@robcohen

@robcohen robcohen commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Behavior changes (read first)

Each change below answers where the surface refused. None refuses where it answered. The rule is #2881's: a query refuses on a parse error or a booking failure, and otherwise answers with every load error reported beside the rows.

Surface Before After
FFI query, batch, session constructor (source text) refused on any load error, a plugin warning included; batch said Cannot execute query: parse errors exist whatever the cause answer over a plugin's error or warning, reporting it in errors ahead of the rows (as batch-file does); still refuse on a parse or booking error. A refused batch now says Cannot execute query: a load error leaves the ledger incomplete (a parse or booking error); see the load errors
WASM query(source) and balances refused on any severity-error (has_fatal): a plugin's error, or an include the text cannot resolve answer, reporting them; still refuse on a parse or booking error
WASM ParsedLedger.query (fresh and fromCache) refused on any load error, a plugin warning included answers, its result's errors leading with the load's errors and option diagnostics, as the free query reports them (review round 1); still refuses on a parse or booking error
WASM Ledger.query (#2861) answered with errors: [], the load's errors only in getErrors() answers with the ledger's errors leading the result's errors (review round 1), so the two classes agree
MCP query, balances, report tools error response whenever the result held a severity-error; a warning was dropped from an answer follow the wasm result: an error response only when there are no columns, listing every error, the load's warnings included. Diagnostics are shown beside the rows, as query_file shows them

Compatibility notes:

  • No released API refuses more. ParsedLedger.query already refused on booking errors, because they were in its load-error list, so nothing became stricter.
  • The one released string that changed is the FFI batch refusal message. Nothing in the repo matched on it.
  • The MCP server runs on the published @rustledger/wasm in CI. Its tool-level change (showing diagnostics and following the wasm's refusal) applies to any wasm version. The new answers over a plugin error need the next wasm release. Details under Verification.

bean-query 0.2.0 (rustledger-compat image)

Case bean-query
plugin "beancount.plugins.check_commodity" with an undeclared USD <check_commodity>:0: Missing Commodity directive for 'USD' in 'Assets:Cash', then the rows, exit 0
unknown plugin (beancount.plugins.nosuchplugin) import traceback reported, then the rows, exit 0
posting to an unopened account Invalid reference to unknown account, then the rows, exit 0. Not a source-text case: the source-text surfaces load with validate: false, so a validation error is never among their load errors and is not tested here (FFI batch lists it in load.errors only)
parse error, booking error answers, dropping the entry. rledger deliberately refuses (#1908, #1987), unchanged

What changed

  • rustledger-ffi-wasi: helpers::LoadResult gained error_blocks_queries (parallel to errors, from LedgerError::blocks_queries; a failed load is true) and blocks_queries().

  • rustledger-ffi-component:

    • query, batch and SessionState::from_source decide with blocks_queries().
    • Answered results carry the load's errors ahead of the query's own.
    • WIT rustledger:[email protected], API_VERSION 3.18. The docs for query, batch, the session constructor and session.query state the rule and the old behavior.
  • rustledger-wasm:

  • MCP: the new queryResponse helper is the one rule for query, balances, report and query_file, which already followed it.

  • A clippy fix in the existing guard. cargo clippy --workspace --all-features --all-targets -- -D warnings failed on main (refactor: one rule for when a query answers despite load errors #2881) with single_match_else in the FFI guard's check. It now uses if let.

  • Drift guard: query_answer_rule/cases.rs gained:

    • a source_text flag on each case: a single file with no includes, run by the source-text surfaces. Source text has no files beside it to include: the FFI lists an include unresolved, and WASM reports it missing.
    • a new plugin error case, which applies to every surface, the file ones included.

    It now runs through:

    • FFI query, batch and a session from source: exact rows plus the reported error. A refused batch must carry BATCH_REFUSED and a non-empty load.errors.
    • WASM query(source), and ParsedLedger.query fresh and from cache.
    • A separate WASM test for an unresolved include in source text.
    • MCP tests, which cannot include! the table, so they repeat the source-text answers at tool level. They also pin queryResponse on the answered and refused result shapes.

Verification

Each guard fails with its fix reverted:

Reverted Failing test and message
FFI query_loaded / from_source back to !errors.is_empty() test_source_queries_answer_or_refuse_by_the_shared_rule: plugin error via query: QueryResult { columns: [], rows: [], ... }
WASM query back to has_fatal plugin error via query: rows [] and include in source text via query: rows []
WASM ParsedLedger.query back to !parse_errors.is_empty() plugin error via ParsedLedger.query: rows []
MCP handlers.ts back to main answers over a plugin's diagnostic, showing it beside the rows

The cached flag is guarded by the booking-error case: a restored ledger that answered would return pay, buy1, buy2.

MCP against both wasm builds. npm ci && npm run build && npm test passes 134 tests (128 before) on the published @rustledger/wasm 0.24.0, and again with this branch's wasm (wasm-pack build --target web) copied into node_modules. node_modules was restored afterward. Against the branch wasm:

  • query(source) over the plugin error answers ["pay"] with Missing Commodity directive ....
  • An unresolved include answers ["pay"] with failed to read file x.beancount ....

Commands run:

  • cargo test --workspace --all-features
  • cargo clippy --workspace --all-features --all-targets -- -D warnings
  • RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps
  • cargo fmt --check
  • wasm-pack test --node (all pass, including the three query-rule tests)
  • cargo check -p rustledger-wasm --target wasm32-unknown-unknown
  • scripts/check-wit-version-bump.sh (3.17.0 -> 3.18.0)
  • scripts/check-wit-version-citations.sh

Version numbers. Right before pushing, origin/main had WASM cache 76, loader cache 59 and WIT 3.17.0. No open PR branch sets 77 or 3.18.0, and the CHANGELOG has one v77 note.

How to test

cargo test -p rustledger-loader --all-features --test query_answer_rule_test
cargo test -p rustledger --all-features --test query_answer_rule_test
cargo test -p rustledger-ffi-component --all-features query_answer_rule
(cd crates/rustledger-wasm && wasm-pack test --node)
(cd packages/mcp-server && npm ci && npm run build && npm test)

Review round 1

  • The WASM refusal guard can now trip. check asserted a refusal as "no rows plus some errors". For ParsedLedger.query those errors came from getErrors(), so query_blocked: false on the parse-error path (helpers.rs:161) passed every guard: a ledger with no entries answers with no rows.
    • A refusal must now have no columns, and an answer must have the query's one column narration.
    • The load error must appear in the result's own errors. check no longer takes getErrors().
    • With that mutation, wasm-pack test --node now fails: a refusal has no columns: parse error via query: columns ["narration"], rows [].
  • ParsedLedger.query reports its load errors. It answered with errors: [] over a plugin's error, an unknown plugin or an unresolved include. Its result's errors now lead with the load's errors and option diagnostics, on every path (answer, BQL parse error, execution error), as the free query() reports them.
    • Validation errors stay in getErrors() only, because the free query() does not validate either.
    • The method doc and the .d.ts (lib.rs) say so.
  • Ledger.query (refactor: one rule for when a query answers despite load errors #2861) now matches. It answered with errors: [] too, the ledger's errors reachable only through getErrors(). Its answers now carry the ledger's errors as well. This is additive: the rows are unchanged. It is in the behavior table above and in the CHANGELOG. Both classes go through execute_query, which now takes the load errors.
  • Nits:
    • The bean-query table's unopened-account row now says it is not a source-text case. Those surfaces load with validate: false, so a validation error is never among their load errors.
    • The WIT batch doc (and the Rust doc) now say each query repeats the load's parse, booking and plugin errors. Semantic validation errors are in load.errors only.
    • MCP queryResponse lists every error, the load's warnings included, when it refuses or the BQL query fails. A synthetic test pins this.
    • The MCP test comments no longer misattribute the plugin behavior: 0.24.0's check_commodity reports a warning, and main's reports an error.
  • Cache: origin/main is still at WASM cache 76. fix(parser): report the metadata shapes beancount rejects #2888, which also takes 77, is still open, so this PR keeps 77. Whichever of the two merges second needs to move to 78.
  • Merged origin/main (test(plugin): keep the back-to-back timeout test independent of machine load #2886).
  • Checks:
    • cargo test --workspace --all-features: 6496 pass.
    • Workspace clippy -D warnings, RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps, cargo fmt --check.
    • wasm-pack test --node: all pass.
    • MCP npm run build && npm test: 134 pass.

Review round 2

  • Breaking entry added to the CHANGELOG. In 0.24.0, answers from Ledger.query and ParsedLedger.query always had errors: []. They can now carry errors: a failed balance assertion, a missing include, a plugin's error, an option diagnostic.
    • An embedder doing if (r.errors.length) throw now fails on ordinary ledgers.
    • The entry tells callers to recognize a refusal by an empty columns, not by a non-empty errors.
  • The ParsedLedger.query refusal now matches the free query. It returned only the load errors. It now adds the option diagnostics, as reported_errors() does.
  • The QueryResult.errors doc (types.rs) says a result with columns is an answer whatever errors holds, and that a refusal has no columns. The bindings were regenerated with scripts/regen-bindings.sh: index.d.ts, index.schema.json, types.py.
  • Cache: origin/main is still at WASM 76 and fix(parser): report the metadata shapes beancount rejects #2888 is still open, so this PR keeps 77. Whichever merges second moves to 78.
  • Checks:
    • cargo test -p rustledger-wasm --all-features and wasm-pack test --node: all pass.
    • clippy (wasm), RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps, cargo fmt --check.
  • Commit 4500c4a63c8. origin/main had not moved, so there was no merge.

Merge with #2888

Closes #2882

🤖 Generated with Claude Code

#2881 gave every file-based query surface one rule for when a query
answers despite load errors (`LedgerError::blocks_queries`): refuse on a
parse error or a booking failure, otherwise answer and report every load
error beside the rows, as bean-query 0.2.0 answers over a plugin's error.
The source-text surfaces kept rules of their own, each stricter:

- FFI `query`, `batch` and a session from source refused on any load
  error, a plugin warning included, and `batch` said "parse errors
  exist" whatever the cause;
- WASM `query(source)` (and `balances`) refused on any severity-error,
  a plugin's or an unresolved include's;
- WASM `ParsedLedger.query` refused on any load error;
- the MCP `query`, `balances` and `report` tools refused whenever the
  result held an error, and dropped warnings from an answer.

Each now decides with the canonical predicate: the FFI helpers'
`LoadResult` carries `error_blocks_queries`, the WASM `ProcessedLedger`
carries `query_blocked`, `ParsedLedger` archives `query_refused` (WASM
cache v77), and the MCP tools share `queryResponse`. Answered FFI results
report the load errors ahead of the query's own, as `batch-file` does.
WIT `rustledger:[email protected]`, API_VERSION 3.18.

The shared drift-guard table gains a `source_text` flag and a plugin-error
case, and runs through FFI `query`, `batch` and a session from source, and
WASM `query` and `ParsedLedger.query` fresh and from cache, with exact rows
and the reported error. The MCP tests repeat the source-text answers.

Also fixes a `clippy::single_match_else` in the FFI guard's `check`, which
failed `cargo clippy --workspace --all-targets -D warnings` on main.

Closes #2882

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner November 7, 2026 07:23
@codecov

codecov Bot commented Nov 7, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 49.9ms ± 0.9ms 807.0ms ± 13.2ms 16.2x 42.8 MB / 50.9 MB
investment 79.8ms ± 6.8ms 2898.7ms ± 21.3ms 36.3x 58.9 MB / 59.2 MB
fifo 73.1ms ± 0.7ms 14661.4ms ± 77.1ms 200.6x 54.9 MB / 59.0 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 49.3ms ± 0.2ms 49.9ms ± 0.9ms +1.1% ✅ within noise 42.5 MB → 42.8 MB (+0.7%)
investment 76.0ms ± 1.4ms 79.8ms ± 6.8ms +4.9% ✅ within noise 59.0 MB → 58.9 MB (-0.1%)
fifo 73.4ms ± 1.1ms 73.1ms ± 0.7ms -0.5% ✅ within noise 54.7 MB → 54.9 MB (+0.3%)

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

@github-actions

github-actions Bot commented Nov 7, 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 3 commits November 7, 2026 08:20
…lls a refusal by its columns

Review round 1 of #2889.

- The WASM drift guard asserted a refusal as "no rows, some errors", so a
  ledger that failed to parse (no entries, so no rows either) passed with
  its refusal removed: `query_blocked: false` on the parse-error path
  survived. A refusal must now have no columns, an answer the query's one
  column, and the load error must be in the result's own `errors`.
- `ParsedLedger.query` answered with `errors: []` over a plugin's error or
  an unresolved include, so a caller reading the result got partial rows
  with nothing saying so. Its result's `errors` now lead with the load's
  errors and option diagnostics, as the free `query` reports them.
  `Ledger.query` (#2861) answered the same way; its answers now carry the
  ledger's errors too. Method docs and the `.d.ts` say so.
- The WIT `batch` doc no longer says each query repeats every load error:
  semantic validation errors are in `load.errors` only.
- MCP `queryResponse` keeps the load's warnings beside a refusal or a BQL
  error, and a test comment no longer misattributes the 0.24.0 plugin
  behavior.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d document reading a result by its columns

Review round 2 of #2889.

- A refused `ParsedLedger.query` returned only the load errors; it now
  adds the option diagnostics, as the free `query` refuses with
  `reported_errors()`.
- The `QueryResult.errors` doc (and the generated bindings) says a result
  with columns is an answer whatever `errors` holds, and that a refusal
  has no columns.
- CHANGELOG Breaking entry: `Ledger.query` and `ParsedLedger.query`
  answers can now carry `errors`, which 0.24.0 never did; recognize a
  refusal by empty `columns`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
#2888 took WASM cache v77 (loader v60). This branch's ParsedLedger payload
change moves to v78, its note after #2888's; LOADER_CACHE_VERSION_PIN is 60,
as main's loader cache is.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen merged commit 8ff3527 into main Nov 7, 2026
61 of 62 checks passed
@robcohen
robcohen deleted the fix/source-query-rule branch November 7, 2026 16:23
robcohen added a commit to MoTechnicalities/rustledger that referenced this pull request Nov 7, 2026
Brings in rustledger#2885-rustledger#2889. The only conflict was CHANGELOG.md, in Breaking
and in Fixed, where both sides added entries; both are kept.

Co-Authored-By: Claude Opus 5.5 <[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.

refactor: source-text query surfaces still use their own answer-despite-errors rules

1 participant