Repository navigation
fix(ffi): route load_source through the canonical pipeline - #1462
Conversation
The string-input FFI load surface (`load_source`, backing `ledger.load`, `ledger.validate`, and `ledger.query`) was a hand-rolled second loader — parse + a manual booking loop — that drifted from the canonical `process::load` pipeline (`sort → synth → book → regular → finalize`). Two phases were silently missing: 1. The post-booking REGULAR plugin pass. File-declared `plugin "..."` directives for regular plugins (`rename_accounts`, `split_expenses`, `currency_accounts`, `unrealized`, …) never ran when a ledger was loaded from source text. Confirmed: a ledger with `rename_accounts` returned the pre-rename account through `load_source`. 2. The date sort. Directives booked and surfaced in file order, not date order. This was the same class of bug as the synth-pass gap fixed in #1404 — which patched in one `run_plugins(PreBookingSynth)` call rather than removing the duplicate. `load_file` was already collapsed onto the canonical loader; only `load_source` remained hand-rolled because the string surface has no filesystem to resolve `include`s against. Collapse `load_source` onto the canonical pipeline via an in-memory VFS: build a `VirtualFileSystem` holding the source as `<source>`, run `Loader::with_filesystem(..).load()` + `process(.., validate:false)`, and rebuild the wire DTO from the returned `Ledger`. `validate:false` preserves this surface's load-only error contract (booking errors surface; semantic validation stays the `ledger.validate` endpoint's job). Declared includes are recovered from a parse for the DTO and stubbed as empty files in the VFS so include resolution is a no-op — preserving the historical "list includes, don't resolve, don't error" behavior (an unresolved include must not emit a parse-phase error, which would suppress validation). Any future pipeline phase now reaches the FFI for free. Regression tests in `tests/load_regular_plugins.rs` cover regular-plugin execution, date sorting, and include listing through `load_source`. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
📊 Benchmark Results
vs main branch (2026-06-20)
What do these numbers mean?
|
There was a problem hiding this comment.
Pull request overview
This PR fixes behavioral drift in the FFI string-input loading surface (load_source, backing ledger.load/validate/query) by routing it through the same canonical loader pipeline as file-based loads (sort → synth → book → regular plugins → finalize) via an in-memory VirtualFileSystem. This ensures file-declared regular plugins run and directives are date-sorted for source-loaded ledgers, matching native loader behavior.
Changes:
- Reworks
load_sourceto userustledger_loader::Loader + process(..)through an in-memory VFS, stubbing declared includes to preserve “list includes, don’t resolve, don’t error” behavior. - Rebuilds the FFI DTO (
directives,spanned_directives, options, plugins, includes) from the processedLedgeroutput rather than a hand-rolled booking loop. - Adds regression tests asserting (1) file-declared regular plugins run, (2) directives are date-sorted, and (3) includes are listed without spurious resolution errors.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| crates/rustledger-ffi-wasi/src/helpers.rs | Collapses load_source onto the canonical loader pipeline using an in-memory VFS; rebuilds wire DTO from the processed Ledger. |
| crates/rustledger-ffi-wasi/tests/load_regular_plugins.rs | Adds regression tests covering regular plugin execution, date-sorting, and include-listing behavior for load_source. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| let ledger = match rustledger_loader::Loader::new() | ||
| .with_filesystem(Box::new(vfs)) | ||
| .load(std::path::Path::new("<source>")) | ||
| .map_err(|e| e.to_string()) | ||
| .and_then(|raw| rustledger_loader::process(raw, &load_opts).map_err(|e| e.to_string())) | ||
| { | ||
| Ok(ledger) => ledger, | ||
| Err(e) => { | ||
| // Fatal load/process failure is unexpected for an in-memory source, | ||
| // but surface it rather than panicking. | ||
| return LoadResult { | ||
| directives: Vec::new(), | ||
| spanned_directives: Vec::new(), | ||
| directive_lines: Vec::new(), | ||
| line_lookup: lookup, | ||
| errors: vec![Error::new(e)], | ||
| options: LedgerOptions::default(), | ||
| plugins: Vec::new(), | ||
| includes, | ||
| }; | ||
| } | ||
| }; |
| } | ||
| } | ||
| } | ||
| let errors: Vec<Error> = ledger.errors.iter().map(ledger_error_to_ffi).collect(); |
| for inc in &includes { | ||
| // Empty stub: include resolution becomes a no-op, so a bare source with | ||
| // `include` directives lists them (above) without emitting a parse-phase | ||
| // "file not found" error that would suppress `ledger.validate`. | ||
| vfs.add_file(inc.path.as_str(), ""); | ||
| } |
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
…_source Addresses Copilot review on #1462 (the load_source pipeline collapse): 1. Warning severity dropped. `ledger_error_to_ffi` hardcoded `severity: "error"`. Now that load_source routes through the full pipeline, plugin *warnings* (e.g. the `unrealized` plugin's gain/loss notices) flow through `ledger.errors` and were surfacing to FFI consumers as errors. Map `ErrorSeverity::Warning` → wire `"warning"`. 2. Glob include paths errored. The previous empty-VFS-stub approach used the literal include path as the key, which cannot match a glob pattern (`[ab].bean` won't match the literal file `[ab].bean`), producing a `GlobNoMatch` parse-phase error that broke the "list includes, don't resolve, don't error" contract. Replace stubbing with a targeted filter that drops parse-phase resolution failures (file-not-found / glob no-match) for declared include paths — uniform across literal and glob includes, and narrow enough never to mask a real syntax error. 3. Fatal-fallback error misclassified. The fatal load/process fallback built a default (parse-phase) `Error`; a fatal process/plugin failure would then be classified as a parse error and suppress `ledger.validate`/`query`. Tag it `validate`. Tests in `tests/load_regular_plugins.rs` cover warning-severity preservation and glob-include suppression. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…_source (#1463) * fix(ffi): preserve warning severity + robust include handling in load_source Addresses Copilot review on #1462 (the load_source pipeline collapse): 1. Warning severity dropped. `ledger_error_to_ffi` hardcoded `severity: "error"`. Now that load_source routes through the full pipeline, plugin *warnings* (e.g. the `unrealized` plugin's gain/loss notices) flow through `ledger.errors` and were surfacing to FFI consumers as errors. Map `ErrorSeverity::Warning` → wire `"warning"`. 2. Glob include paths errored. The previous empty-VFS-stub approach used the literal include path as the key, which cannot match a glob pattern (`[ab].bean` won't match the literal file `[ab].bean`), producing a `GlobNoMatch` parse-phase error that broke the "list includes, don't resolve, don't error" contract. Replace stubbing with a targeted filter that drops parse-phase resolution failures (file-not-found / glob no-match) for declared include paths — uniform across literal and glob includes, and narrow enough never to mask a real syntax error. 3. Fatal-fallback error misclassified. The fatal load/process fallback built a default (parse-phase) `Error`; a fatal process/plugin failure would then be classified as a parse error and suppress `ledger.validate`/`query`. Tag it `validate`. Tests in `tests/load_regular_plugins.rs` cover warning-severity preservation and glob-include suppression. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(ffi): normalize path separators when matching include errors Addresses Copilot on #1463: the loader renders paths via Path::display(), which uses backslashes on Windows, while declared include paths use forward slashes. Normalize both sides to / before matching so the include-resolution error filter works regardless of platform separator. Co-Authored-By: Claude Opus 4.8 <[email protected]> --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
v0.17.0 regression (#1462): `7 USD @@ 10 EUR` surfaced through the FFI component (rustfava) as the raw total price (10) instead of the Beancount per-unit price (10/7 ≈ 1.428). `rledger check` was unaffected. Root cause: the @@→@ normalization (`normalize_prices`) lived ONLY in the CLI `check.rs`, not in the loader's shared `process()` pipeline. When #1462 routed the FFI/MCP surface through that shared pipeline to deduplicate the loader, it lost the normalization the CLI still did separately — so `process()` returned a `Finalized` ledger that wasn't actually finalized. The price invariant was a per-consumer responsibility: the classic drift category (cf. #1648). Fix — put the invariant in the type, not the consumer: - Call `normalize_prices` in the `finalize` transition (LateValidated → Finalized). It runs AFTER Late validation, so exact totals still survive for the precise balance-residual check (#1240) — the reason normalization is deferred rather than done during booking. - `Finalized` is the only publicly-exposed phase and `process()` is the only path to a `Ledger`, so 'prices are normalized' is now an invariant every consumer (CLI, FFI/MCP component, BQL) gets by construction — none can drift. - Remove the now-redundant normalize loop (+ unused import) from `check.rs`. Tests: - Loader: `process()`/finalize normalizes `@@` to per-unit (invariant; no wasm). - FFI component parity: the component surfaces `7 USD @@ 10 EUR` as per-unit 1.42857…, matching `check` — the CLI-vs-FFI parity guard. No regressions: 16 FFI parity + 92 loader + 105 booking + 362 CLI + 163 query + 104 ops tests pass; clippy -D warnings clean. Co-authored-by: Claude Opus 4.8 <[email protected]>
…'s component (#1679) Every FFI bug in the v0.17-v0.19 arc (#1462, #1656, #1663, #1666, #1667, #1668) was found by rustfava AFTER a release shipped. New advisory workflow: on PRs touching the embedding surface or the engine crates behind it, build the wasip2 component from the PR, check out rustfava@main, and run its Python test suite against that wasm via the RUSTLEDGER_COMPONENT_WASM override — moving discovery from post-release to pre-merge. Deliberately NOT in the required build gate: an intentional WIT break (e.g. the 3.2.0 host.decrypt import) legitimately fails here until rustfava adopts the new contract; red is the signal, not a merge blocker. Co-authored-by: Claude Opus 4.8 <[email protected]>
What
The string-input FFI load surface —
load_source, which backsledger.load,ledger.validate, andledger.query— was a hand-rolled second loader (parse + a manual booking loop) that drifted from the canonicalprocess::loadpipeline. Two phases were silently missing for source-loaded ledgers (what an editor/embedder with buffer text uses):plugin "rename_accounts"/split_expenses/currency_accounts/unrealized/ … never ran.Confirmed empirically before the fix:
load_filewas already correct (it routes throughrustledger_loader::load). This is the same class of drift as the synth-pass gap fixed in #1404, which patched in onerun_pluginscall rather than removing the duplicate — leaving symptoms #2 and #3 waiting.How
Collapse
load_sourceonto the canonical pipeline via an in-memory VFS (the approachload_filealready uses):VirtualFileSystemholding the source as<source>, runLoader::with_filesystem(..).load()thenprocess(.., validate:false), and rebuild the wire DTO from the returnedLedger.validate:falsepreserves the surface's load-only error contract (booking errors surface; semantic validation staysledger.validate's job — the parse-vs-validate phase tagging downstream handlers rely on is preserved byledger_error_to_ffi).includes are recovered from a parse for the DTO and stubbed as empty files in the VFS, so resolution is a no-op — preserving the historical "list includes, don't resolve, don't error" behavior (an unresolved include must not emit a parse-phase error, which would suppress validation).Net: deletes the hand-rolled booking loop and manual option extraction; any future pipeline phase now reaches the FFI for free. The component crate (
rustledger-ffi-component) delegates toload_sourceand inherits the fix.Tests
tests/load_regular_plugins.rs:load_source_runs_file_declared_regular_plugin—rename_accountsrewrites postings (was the confirmed bug).load_source_sorts_directives_by_date— out-of-file-order txns surface date-sorted.load_source_lists_includes_without_resolution_error— declared include listed, no spurious not-found error.Verify
rustledger-ffi-wasisuites +rustledger-ffi-component+rustledger-loaderpass.cargo clippy --all-features --all-targetsclean;cargo fmt --checkclean.🤖 Generated with Claude Code