Skip to content

fix(ffi): route load_source through the canonical pipeline - #1462

Merged
robcohen merged 1 commit into
mainfrom
fix/ffi-load-source-canonical
Jun 20, 2026
Merged

robcohen merged 1 commit into
mainfrom
fix/ffi-load-source-canonical

Conversation

@robcohen

Copy link
Copy Markdown
Member

What

The string-input FFI load surface — load_source, which backs 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. Two phases were silently missing for source-loaded ledgers (what an editor/embedder with buffer text uses):

  1. The regular (post-booking) plugin pass — file-declared plugin "rename_accounts" / split_expenses / currency_accounts / unrealized / … never ran.
  2. The date sort — directives booked and surfaced in file order.

Confirmed empirically before the fix:

FFI load_source posting accounts: ["Assets:Cash,Expenses:Old"]
renamed_applied=false  stale_old_remains=true   ← rename_accounts did NOT run

load_file was already correct (it routes through rustledger_loader::load). This is the same class of drift as the synth-pass gap fixed in #1404, which patched in one run_plugins call rather than removing the duplicate — leaving symptoms #2 and #3 waiting.

How

Collapse load_source onto the canonical pipeline via an in-memory VFS (the approach load_file already uses):

  • Build a VirtualFileSystem holding the source as <source>, run Loader::with_filesystem(..).load() then process(.., validate:false), and rebuild the wire DTO from the returned Ledger.
  • validate:false preserves the surface's load-only error contract (booking errors surface; semantic validation stays ledger.validate's job — the parse-vs-validate phase tagging downstream handlers rely on is preserved by ledger_error_to_ffi).
  • Declared 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 to load_source and inherits the fix.

Tests

tests/load_regular_plugins.rs:

  • load_source_runs_file_declared_regular_plugin — rename_accounts rewrites 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

  • 3 new regression tests + all 8 rustledger-ffi-wasi suites + rustledger-ffi-component + rustledger-loader pass.
  • cargo clippy --all-features --all-targets clean; cargo fmt --check clean.

🤖 Generated with Claude Code

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]>
@robcohen
robcohen requested a review from a team as a code owner June 20, 2026 23:38
Copilot AI review requested due to automatic review settings June 20, 2026 23:38
@codecov

codecov Bot commented Jun 20, 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

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 35.1ms ± 1.3ms 23.6 MB
beancount 920.5ms ± 11.3ms 50.5 MB
Comparison 26.2x faster 2.1x less

vs main branch (2026-06-20)

Metric main this PR Change
Time 41.3ms 35.1ms -15.0% 🟢
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

@robcohen
robcohen merged commit b8dd7a0 into main Jun 20, 2026
41 checks passed
@robcohen
robcohen deleted the fix/ffi-load-source-canonical branch June 20, 2026 23:43

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_source to use rustledger_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 processed Ledger output 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.

Comment on lines +122 to +143
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,
};
}
};

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in # (the review landed just after #1462 auto-merged).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correction: addressed in #1463.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correction: addressed in #1463.

}
}
}
let errors: Vec<Error> = ledger.errors.iter().map(ledger_error_to_ffi).collect();

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in # (the review landed just after #1462 auto-merged).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correction: addressed in #1463.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correction: addressed in #1463.

Comment on lines +112 to 117
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(), "");
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in # (the review landed just after #1462 auto-merged).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correction: addressed in #1463.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correction: addressed in #1463.

@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 792
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

robcohen added a commit that referenced this pull request Jun 20, 2026
…_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]>
robcohen added a commit that referenced this pull request Jun 21, 2026
…_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]>
robcohen added a commit that referenced this pull request Jun 30, 2026
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]>
robcohen added a commit that referenced this pull request Jul 1, 2026
…'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]>
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.

2 participants