Repository navigation
test: add comprehensive integration tests for loader crate - #5
Merged
Merged
Conversation
robcohen
force-pushed
the
test/loader-coverage
branch
from
January 6, 2026 16:52
8e3acee to
f3bf789
Compare
Add 10 integration tests covering all major loader functionality: - test_load_simple_file: Basic file loading with options - test_load_with_include: Include file resolution - test_load_include_cycle_detection: Cycle detection in includes - test_load_missing_include: Graceful handling of missing includes - test_load_with_plugins: Plugin directive collection - test_load_with_parse_errors: Error recovery and collection - test_load_nonexistent_file: IO error handling - test_loader_reuse: Loader instance behavior - test_source_map_line_lookup: Source mapping for errors - test_duplicate_include_ignored: Deduplication of includes Includes 8 test fixture files for various scenarios. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
robcohen
force-pushed
the
test/loader-coverage
branch
from
January 6, 2026 16:55
f3bf789 to
08d62cb
Compare
robcohen
added this pull request to the merge queue
Jan 6, 2026
robcohen
added a commit
that referenced
this pull request
Jan 14, 2026
test: add comprehensive integration tests for loader crate
robcohen
added a commit
that referenced
this pull request
Jan 14, 2026
test: add comprehensive integration tests for loader crate
robcohen
added a commit
that referenced
this pull request
Jan 18, 2026
- Extract DEFAULT_CURRENCIES constant in completion.rs (comment #4) - Use appropriate error codes: MethodNotFound for unknown methods, InternalError for handler failures (comment #5) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
3 tasks
robcohen
added a commit
that referenced
this pull request
Mar 31, 2026
Issue #1: Fix release asset names to include version Issue #5: Add docs for `add` and `config` commands Issue #6: Add missing CLI options to check/query docs check command: added -q/--quiet, -C/--no-cache, -a/--auto, --plugin query command: added -F/--query-file, -o/--output, -m/--numberify, -q/--no-errors, beancount format option Co-Authored-By: Claude Opus 4.5 <[email protected]>
robcohen
added a commit
that referenced
this pull request
Mar 31, 2026
Issue #1: Fix release asset names to include version Issue #5: Add docs for `add` and `config` commands Issue #6: Add missing CLI options to check/query docs check command: added -q/--quiet, -C/--no-cache, -a/--auto, --plugin query command: added -F/--query-file, -o/--output, -m/--numberify, -q/--no-errors, beancount format option Co-Authored-By: Claude Opus 4.5 <[email protected]>
robcohen
added a commit
that referenced
this pull request
Mar 31, 2026
Fixes several issues identified in PR #624 review: 1. Yahoo f64 precision (issue #3): Use pattern matching with serde_json::Value::Number to preserve decimal precision instead of converting through f64. 2. ECB cross-rate handling (issue #2): Rewrite fetch_price to correctly handle EUR→X, X→EUR, and X→Y cross-rate conversions. 3. --source-cmd early return (issue #4): Move external command handling after symbol discovery so -f flag works with --source-cmd. 4. Hardcoded timeout (issue #7): Use config timeout for --source-cmd instead of hardcoded 30 seconds. 5. External source naming (issue #8): Derive source name from command binary name instead of always returning "external". Add with_name() constructor for configured sources. 6. Unknown sources warning (issue #5): Track and report unknown sources in fallback chains when price fetching fails. 7. Timeout limitation (issue #6): Document that timeout is stored but not enforced due to std::process::Command limitations. Co-Authored-By: Claude Opus 4.5 <[email protected]>
robcohen
added a commit
that referenced
this pull request
Apr 12, 2026
- Fix #1: Build SourceMap with buffer content in single-file mode so run_plugins() can preserve directive source locations - Fix #2: Anchor Python plugin warning to the plugin directive span and filter by current_file_id to avoid noise in multi-file mode - Fix #3: Only show plugin errors in the main file (file_id 0) to prevent duplication across open documents - Fix #4: Correct diagnostic message — non-native plugins are skipped in LSP, not "may be slower" (run_plugins only runs native plugins) - Fix #5: Merge fresh buffer plugin declarations with ledger plugins, mirroring the directive overlay approach for unsaved edits Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
robcohen
added a commit
that referenced
this pull request
Apr 23, 2026
…tability - Change ValidationOptions.document_dirs from Vec<String> to Vec<PathBuf> to store resolved paths instead of raw values - Add #[non_exhaustive] to ValidationOptions to prevent breaking changes when new fields are added - Resolve document paths against source_map base_dir in run_validation() and build_validation_options_from_loader() to match run_plugins() behavior - Use Path::join() instead of string concatenation for portable paths - Fix test to use doc_subdir.join() instead of format! for path construction Addresses Copilot review comments #1, #2, #3, #4, #5, #7 on PR #899
robcohen
added a commit
that referenced
this pull request
Apr 23, 2026
…tability - Change ValidationOptions.document_dirs from Vec<String> to Vec<PathBuf> to store resolved paths instead of raw values - Add #[non_exhaustive] to ValidationOptions to prevent breaking changes when new fields are added - Resolve document paths against source_map base_dir in run_validation() and build_validation_options_from_loader() to match run_plugins() behavior - Use Path::join() instead of string concatenation for portable paths - Fix test to use doc_subdir.join() instead of format! for path construction Addresses Copilot review comments #1, #2, #3, #4, #5, #7 on PR #899
robcohen
added a commit
that referenced
this pull request
Apr 23, 2026
…tability - Change ValidationOptions.document_dirs from Vec<String> to Vec<PathBuf> to store resolved paths instead of raw values - Add #[non_exhaustive] to ValidationOptions to prevent breaking changes when new fields are added - Resolve document paths against source_map base_dir in run_validation() and build_validation_options_from_loader() to match run_plugins() behavior - Use Path::join() instead of string concatenation for portable paths - Fix test to use doc_subdir.join() instead of format! for path construction Addresses Copilot review comments #1, #2, #3, #4, #5, #7 on PR #899
robcohen
added a commit
that referenced
this pull request
Apr 23, 2026
…tability - Change ValidationOptions.document_dirs from Vec<String> to Vec<PathBuf> to store resolved paths instead of raw values - Add #[non_exhaustive] to ValidationOptions to prevent breaking changes when new fields are added - Resolve document paths against source_map base_dir in run_validation() and build_validation_options_from_loader() to match run_plugins() behavior - Use Path::join() instead of string concatenation for portable paths - Fix test to use doc_subdir.join() instead of format! for path construction Addresses Copilot review comments #1, #2, #3, #4, #5, #7 on PR #899
robcohen
added a commit
that referenced
this pull request
May 5, 2026
…harness
1. **Plugin-fixture prioritization actually works now.** Pre-fix the
filter `f.startswith("plugin/")` ran against `valid`, which is a
list of basenames (the upstream check workflow stores
`file_path.name` only — `.github/workflows/compat.yml` does
`FileResult(file=file_path.name, ...)`). The filter never matched,
so plugin fixtures could be silently dropped by `--max-files`.
Restructured: resolve every basename to a Path via `find_file`
FIRST, then prioritize on the resolved Path's `.parts` containing
`"plugins"`. Verified with `--max-files 2` against 3 plugin
fixtures: harness now correctly reports
"Testing against 3 files (3 plugin fixtures + 0 other)".
Side effect: this also addresses the silent-collision risk in
`find_file` (issue #5 from the review) — basenames are resolved
exactly once, and the resolved path is what we work with from
then on.
2. **Renamed `plugin/` → `plugins/`** to match the existing per-
category convention used by `.github/workflows/compat.yml`'s
`get_category` (line 198). Pre-fix these fixtures were classified
as `other` in the per-category dashboard; now they correctly land
in `plugins`.
3. **README updated** to reflect that `plugins/` is committed
in-tree (an exception to the rest of `files/` which is downloaded
on demand via `fetch-compat-test-files.sh`). Added a "How to add
a new plugin's fixtures" subsection.
4. **`.gitignore` un-ignores intermediate directories** under
`plugins/`. Pre-fix only `!plugins/` and `!plugins/**/*.beancount`
were set, but Git's "cannot re-include a file if a parent dir is
excluded" rule meant new nested dirs (e.g.
`plugins/<new_plugin>/`) were still ignored — the existing
`implicit_prices/` dir only worked because someone presumably
used `git add -f` originally. Added `!plugins/**/` so adding new
plugin subdirectories works mechanically.
Verified: `mkdir plugins/synthetic_test && touch
plugins/synthetic_test/foo.beancount && git status` now shows
the file as untracked (was: silently ignored).
5. (Knock-on) Updated callers that referenced the old path:
`CONTRIBUTING.md` (2 occurrences) and `tests/compatibility/
bql-queries.toml` (1 comment) both rewritten plugin/ → plugins/.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen
added a commit
that referenced
this pull request
May 5, 2026
…#992 plan) (#1000) * feat(compat): plugin differential harness via BQL fixtures (Phase 2 of #992 plan) Extends the existing BQL compat harness (scripts/compat-bql-test.py) to surface plugin-emitted directives, so divergences between rledger's and bean-check's plugin implementations show up as BQL mismatches at PR time — no new infrastructure needed. ## Approach: leverage the existing harness The compat-bql-test.py harness already runs bean-query and rledger query against every fixture in tests/compatibility/files/. Plugin fixtures with `plugin "..."` directives load with that plugin enabled in BOTH tools; we just need: 1. Fixtures under `tests/compatibility/files/plugin/<plugin>/` that exercise specific plugin code paths. 2. BQL queries that surface plugin output (e.g. `SELECT * FROM #prices` for plugins that emit Price directives). 3. Plugin fixtures prioritized in the harness's MAX_FILES sampling so they always get tested. That's the whole change. ~50 LoC in the script, plus 3 fixtures. ## Fixtures (implicit_prices, the #992 motivator) - cost_only.beancount: plain `{cost}` path, expect 2 prices - total_annotation.beancount: `@@` path (issue #992), expect 1 price - annotation_and_cost.beancount: both present, annotation wins, expect 2 prices total Script changes: - Two new BQL queries: count-prices-from-plugin (catches double-emit / missing-emit) and prices-from-plugin-by-date (catches @@ vs @ confusion). - Plugin-fixture prioritization: plugin/* fixtures bypass the random --max-files truncation. Without this, 3 plugin fixtures could be excluded from a 30-file sample. - MIN_CORPUS_SIZE bumped from 13 → 15 for the new queries. ## Verified locally Ran the harness against all three fixtures using rledger v0.14.1+ (pre-#997 — the buggy version). The harness flagged every bug: total_annotation.beancount count-prices-from-plugin: py=1 rs=2 cost_only.beancount count-prices-from-plugin: py=2 rs=4 annotation_and_cost.beancount count-prices-from-plugin: py=2 rs=5 After #997 lands, these mismatches will all resolve to 0. The harness is a regression test for #997 and a forward-going divergence detector for any future plugin work. ## Wiring into CI The existing .github/workflows/compat.yml already runs the BQL harness on every PR. Adding fixtures + queries automatically extends coverage without changes to the workflow file. CI will diff plugin output the next time it runs. ## Future plugins To add coverage for another plugin (e.g. sell_gains, unrealized): 1. Drop fixtures under `tests/compatibility/files/plugin/<name>/`. 2. Optionally add queries to bql-queries.toml that surface that plugin's emitted directives. The harness handles the rest. Mirrors Phase 1 of the plugin-testing plan but with mechanical comparison instead of manual test ports. ## Related - #992 — the bug that motivated the plan - #997 — Phase 0a fix - #998 — Phase 0b audit - #999 — Phase 0c type-safety view enum Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * test: add plugin differential fixtures (followup to 39ff54d) The previous commit added the harness wiring but the fixture files themselves were silently rejected by the .gitignore that excludes the (downloaded) compat corpus. Whitelist plugin/** so in-tree fixtures ship with the repo. Three implicit_prices fixtures committed: - cost_only.beancount - total_annotation.beancount (issue #992 reproducer) - annotation_and_cost.beancount (the double-emit case) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * test: exclude beancount .cache sidecars from plugin fixtures * fix(compat): address all five review findings on plugin differential harness 1. **Plugin-fixture prioritization actually works now.** Pre-fix the filter `f.startswith("plugin/")` ran against `valid`, which is a list of basenames (the upstream check workflow stores `file_path.name` only — `.github/workflows/compat.yml` does `FileResult(file=file_path.name, ...)`). The filter never matched, so plugin fixtures could be silently dropped by `--max-files`. Restructured: resolve every basename to a Path via `find_file` FIRST, then prioritize on the resolved Path's `.parts` containing `"plugins"`. Verified with `--max-files 2` against 3 plugin fixtures: harness now correctly reports "Testing against 3 files (3 plugin fixtures + 0 other)". Side effect: this also addresses the silent-collision risk in `find_file` (issue #5 from the review) — basenames are resolved exactly once, and the resolved path is what we work with from then on. 2. **Renamed `plugin/` → `plugins/`** to match the existing per- category convention used by `.github/workflows/compat.yml`'s `get_category` (line 198). Pre-fix these fixtures were classified as `other` in the per-category dashboard; now they correctly land in `plugins`. 3. **README updated** to reflect that `plugins/` is committed in-tree (an exception to the rest of `files/` which is downloaded on demand via `fetch-compat-test-files.sh`). Added a "How to add a new plugin's fixtures" subsection. 4. **`.gitignore` un-ignores intermediate directories** under `plugins/`. Pre-fix only `!plugins/` and `!plugins/**/*.beancount` were set, but Git's "cannot re-include a file if a parent dir is excluded" rule meant new nested dirs (e.g. `plugins/<new_plugin>/`) were still ignored — the existing `implicit_prices/` dir only worked because someone presumably used `git add -f` originally. Added `!plugins/**/` so adding new plugin subdirectories works mechanically. Verified: `mkdir plugins/synthetic_test && touch plugins/synthetic_test/foo.beancount && git status` now shows the file as untracked (was: silently ignored). 5. (Knock-on) Updated callers that referenced the old path: `CONTRIBUTING.md` (2 occurrences) and `tests/compatibility/ bql-queries.toml` (1 comment) both rewritten plugin/ → plugins/. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
robcohen
added a commit
that referenced
this pull request
May 17, 2026
…ew tests Six Copilot inline comments triaged: | # | Issue | Status | |---|-------|--------| | 1 | max_memory unenforced | already fixed in 41dc97c (on older commit) | | 2 | fuel calc can overflow u64 | FIXED | | 3 | input length truncates >4 GiB; no output cap | FIXED (output cap was 41dc97c; input cap here) | | 4 | typed_func errors masquerade as MissingExport | FIXED | | 5 | CSV projection doc claims full but ships subset | FIXED (doc) | | 6 | "duplicated here" comment lies about implementation | FIXED | # Fuel saturation (Copilot #2) `config.max_time_secs.max(1) * 1_000_000` would panic in debug and silently wrap in release for very large `max_time_secs` (technically possible at u64 values >18T, which is ~580K years — extreme but the wrap is a real bug). Now uses `saturating_mul` — `u64::MAX` clamps to `u64::MAX` which `set_fuel` accepts as "effectively unlimited." # Input length cap (Copilot #3) Added `MAX_INPUT_BYTES` (64 MiB, symmetric with `MAX_OUTPUT_BYTES`) and `WasmImporterError::InputTooLarge { len, max }`. Extracted the check into a `const fn validate_input_size(len) -> Result<u32, _>` helper so the cap can be unit-tested without standing up wasmtime and allocating 64 MiB. The host caps before the `as u32` cast so a truncated input can't corrupt the import. # ExportSignatureMismatch (Copilot #4) Previously `get_typed_func::<u32, u32>("alloc").map_err(|_| MissingExport("alloc"))` collapsed two distinct failure modes into one misleading error. Since `validate_module` proves presence by name at load time, any subsequent typed_func failure is necessarily a signature mismatch — surfaced now as `WasmImporterError::ExportSignatureMismatch { name, source }` which names the export and chains the wasmtime type-mismatch detail. Applied at all 3 typed_func sites (`alloc`, the dispatched entry, `metadata`). # CSV projection honesty (Copilot #5) `CsvConfig` has 18 fields; this PR projects 8 (the simple String/bool/number ones). Updated `build_wasm_input` and `project_csv_config_into_options` docs to say "subset" + list exactly what's projected and what's deferred to wave 2.3e (column specs, locale, mappings — encoding decisions best driven by a real WASM CSV importer, not guessed here). No behavior change. # Stale duplication comment (Copilot #6) The comment in `output_to_import_result` claimed the wrapper→directive converter was "duplicated here so this crate doesn't need to depend on the full `rustledger-plugin` graph" — but the code actually calls `rustledger_plugin::convert::wrapper_to_directive` directly, with the explicit dep added in this PR's Cargo.toml. Rewrote to say "delegates … so the WASM importer path and directive-plugin path share a single converter." # Tests 3 new wasm:: tests (158 importer total, was 155): - validate_input_size_accepts_at_cap_and_rejects_above — boundary test for MAX_INPUT_BYTES and the InputTooLarge surface. - fuel_calc_saturates_instead_of_overflowing — regression for Copilot #2; loads with u64::MAX max_time_secs and asserts no panic + successful execution. - wrong_signature_export_surfaces_export_signature_mismatch — WAT module with metadata: () -> i32 (wrong: should be -> i64); asserts ExportSignatureMismatch { name: "metadata" } rather than the previously-misleading MissingExport. # Verification - 26 wasm:: tests pass (was 23) - 158/158 rustledger-importer tests pass - cargo check --workspace --all-targets clean - cargo clippy --workspace --all-targets -- -D warnings clean - cargo fmt --all -- --check clean Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen
added a commit
that referenced
this pull request
May 17, 2026
* feat(importer): WasmImporter host loader (wave 2.3b) Host-side loader for `.wasm` importer modules. Implements the `Importer` trait by serializing inputs to MessagePack, calling into the module via wasmtime, and deserializing outputs. # Sandbox model Mirrors `rustledger-plugin/src/runtime.rs`: - All imports rejected at load time — no WASI, fs, net, env, syscalls - Memory limit (default 256 MiB) and fuel-based time limit (default 30s) - Fresh `Store` per call — concurrent extracts don't share state - Module + Engine shared via `Arc` — `WasmImporter` is cheap to clone # Wire protocol WASM module exports: `memory`, `alloc(u32) -> u32`, `metadata() -> u64`, `identify(ptr,len) -> u64`, `extract(ptr,len) -> u64`, `extract_enriched(ptr,len) -> u64`. All u64 returns pack `(out_ptr << 32) | out_len`. `ImporterConfig` (CSV-specific fields) is projected into the wire format's free-form `options: HashMap<String, String>`. Trade-off documented inline: keeps the ABI minimal at the cost of string parsing in the guest. `extract_enriched` round-trips `EnrichmentWrapper`/`AlternativeWrapper`; the `method: String` field parses via `parse_method()` with unknown strings falling back to `Default` — forward-compat for hosts adding new categorization methods. `metadata` is called once at load and cached for `name()`/`description()`, avoiding wasmtime instantiation on every property access. Errors/warnings round-trip via `PluginError` reusing the same shape the directive-plugin path uses (`LedgerError::location` flows naturally). # Verification - 4 `wasm::tests::*` pass (validate_module rejects imports / missing exports, parse_method round-trip + unknown fallback) - `cargo check --workspace --all-targets` clean - `cargo clippy --workspace --all-targets -- -D warnings` clean - `cargo fmt --all -- --check` clean # What's next (waves 2.3c-2.3e) - 2.3c: registry discovery (`--wasm-importer` flag + directory scan) - 2.3d: guest macros re-exported from `rustledger-plugin-types` - 2.3e: reference sample importer + integration tests Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(importer): WasmImporter — enforce memory cap + output bound + zero-legacy review fixes Addresses the 8 issues from the deep PR review of #1131. Changes are scoped to wasm.rs (no API surface changes for downstream crates). # Security / soundness **Memory limit now actually enforced.** Added `MemoryLimiter` implementing `wasmtime::ResourceLimiter`, wired via `Store::limiter()`. Without this, `WasmRuntimeConfig::max_memory` was silently ignored — a malicious or buggy WASM importer could `memory.grow` until the host OOMed. (The same gap exists in `rustledger-plugin/src/runtime.rs`; fixing both is queued as a separate follow-up to keep this PR focused on the importer path.) **Output size capped.** New `MAX_OUTPUT_BYTES` (64 MiB) plus `WasmImporterError::OutputTooLarge`. Previously a module returning `out_len = u32::MAX` would trigger a ~4 GiB `Vec` allocation before `memory.read` ever ran. Validated centrally in a new `read_packed_output` helper shared by all entry points. **Fuel clamped at min 1.** `max_time_secs = 0` previously produced `fuel = 0` → immediate trap on first instruction. Now `.max(1) * 1_000_000`. Regression test pins this. # Correctness **PluginError severity preserved on the wire.** Refactored ad-hoc `format!(...)` calls into `format_plugin_error()` which prefixes the formatted line with the severity ("error " vs "warning ") so a fatal-but-recoverable importer error remains distinguishable from informational chatter in the shared `warnings` channel. **Orphan-colon bug fixed.** Previous formatter produced `": message"` when both `source_file` and `line_number` were `None`, and `":42: message"` when only `line_number` was set. New formatter builds the location segment conditionally: `"file:42: msg"` / `"file: msg"` / `"line 42: msg"` / `"msg"`. **Fingerprint round-trip now works.** `EnrichmentWrapper.fingerprint` (hex string) is parsed back into `Fingerprint` via `from_hex`. Malformed hex surfaces as a bridge warning instead of silently dropping to `None`. Closes the comment-flagged "wave 2.3+" deferral — this *is* wave 2.3b. **parse_method no longer silently degrades.** Returns `Result<_, &str>` instead of `_`; unknown method strings surface as warnings naming the unknown value. This is the exact failure mode Copilot caught in #1130 (`merchant_dict` underscore typo vs `merchant-dict` hyphen wire encoding) — silent fallback would have re-introduced it. # Tests 15 wasm:: tests now pass (was 4): - 3 pre-existing (validate_module imports/exports, basic parse_method) - `parse_method_round_trips_via_as_meta_value` — guards drift between the host enum and the wire-format string set - `parse_method_unknown_surfaces_the_unknown_string` — pins the no-silent-degradation contract - 5 `format_plugin_error_*` — full / warning / orphan-colon-free / file-only / line-only-uses-human-phrasing - `end_to_end_wat_module_round_trips_all_entry_points` — minimal WAT module with pre-baked MessagePack outputs, exercises metadata + identify + extract + extract_enriched end-to-end through wasmtime - `oversized_output_is_rejected_before_allocation` — module returns `out_len = u32::MAX`, host rejects at load (via metadata) - `memory_limiter_rejects_grow_above_max` — direct unit test of `ResourceLimiter::memory_growing` boundary behavior - `zero_max_time_secs_does_not_starve_fuel` — regression for the fuel-clamp # Verification - 147/147 rustledger-importer tests pass (was 132) - cargo check --workspace --all-targets clean - cargo clippy --workspace --all-targets -- -D warnings clean - cargo fmt --all -- --check clean Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(importer): WasmImporter — cap tables + close review coverage gaps Addresses the 4 substantive issues + polish from the second-round review of #1131. # Security **Table growth now bounded.** Added `MAX_TABLE_ELEMENTS` (1M) + limiter enforcement. wasmtime accounts `Memory` and `Table` separately; without this, `table.grow` would bypass the memory limiter. Each ref-typed slot is pointer-sized, so the cap puts a ~8 MiB worst-case ceiling on indirect-call tables — well under the memory cap but plenty for any plausible dispatch pattern. # Coverage **`initial_memory_above_cap_is_rejected_via_limiter_wiring`** — pins the `store.limiter(|s| &mut s.limiter)` wiring against refactor regression. Previous test (`memory_limiter_rejects_grow_above_max`) only exercised the trait method directly. New test loads a module declaring 5000 pages (320 MiB) initial memory against a 64 MiB cap and asserts instantiation fails — proves wasmtime is actually consulting our limiter at instance creation. **`table_limiter_rejects_grow_above_max`** — direct trait-method test for the new table cap boundary. # Refactor **Extracted `bridge_enriched_output` free function** from `WasmImporter::extract_enriched`. The lossy paths (unknown method strings, malformed fingerprint hex) were buried inside the trait-method body, untestable without wasmtime scaffolding. Now the wasmtime round-trip and the wire-format bridge are independent concerns. Also documented the warning-emission order (bridge → output.warnings → output.errors) on the function rustdoc — it's a contract any downstream consumer that filters warnings depends on. 5 new bridge tests: - `bridge_round_trips_valid_fingerprint_hex` — closes the fingerprint-untested gap. Uses `Fingerprint::compute` + `to_hex` + bridge → assert host-side fingerprint equals original. - `bridge_warns_on_malformed_fingerprint_hex_and_drops_to_none` — pins the bridge-warning emission for the malformed-hex path. - `bridge_warns_on_unknown_method_and_falls_back_to_default` — uses `"merchant_dict"` (underscore typo, exact #1130 bug shape) to demonstrate the no-silent-degradation contract. - `bridge_warns_on_unknown_method_in_alternative` — same path but in the `alternatives` slot, verifies the distinguishing "alternative" text. - `bridge_warning_ordering_is_bridge_then_output_warnings_then_errors` — pins the documented order. **`output_to_import_result_uses_severity_aware_formatter`** — integration test proving `format_plugin_error` is wired into the production path, not just unit-tested. A refactor switching back to raw `format!()` would regress this. # Polish - Switched `parse_method_round_trips_via_as_meta_value` from `mem::discriminant` to plain `assert_eq!` — CategorizationMethod derives PartialEq, so the discriminant indirection was unwarranted. - Added caveat comment on test fixture's bump allocator that real importers must bounds-check `bump + size` against memory bounds and call `memory.grow` (subject to limiter approval). # Verification - 155/155 rustledger-importer tests (was 147; +8 new in this commit) - 23 wasm::tests pass (was 15) - cargo check --workspace --all-targets clean - cargo clippy --workspace --all-targets -- -D warnings clean - cargo fmt --all -- --check clean Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(importer): address Copilot review of #1131 — 5 valid issues + 3 new tests Six Copilot inline comments triaged: | # | Issue | Status | |---|-------|--------| | 1 | max_memory unenforced | already fixed in 41dc97c (on older commit) | | 2 | fuel calc can overflow u64 | FIXED | | 3 | input length truncates >4 GiB; no output cap | FIXED (output cap was 41dc97c; input cap here) | | 4 | typed_func errors masquerade as MissingExport | FIXED | | 5 | CSV projection doc claims full but ships subset | FIXED (doc) | | 6 | "duplicated here" comment lies about implementation | FIXED | # Fuel saturation (Copilot #2) `config.max_time_secs.max(1) * 1_000_000` would panic in debug and silently wrap in release for very large `max_time_secs` (technically possible at u64 values >18T, which is ~580K years — extreme but the wrap is a real bug). Now uses `saturating_mul` — `u64::MAX` clamps to `u64::MAX` which `set_fuel` accepts as "effectively unlimited." # Input length cap (Copilot #3) Added `MAX_INPUT_BYTES` (64 MiB, symmetric with `MAX_OUTPUT_BYTES`) and `WasmImporterError::InputTooLarge { len, max }`. Extracted the check into a `const fn validate_input_size(len) -> Result<u32, _>` helper so the cap can be unit-tested without standing up wasmtime and allocating 64 MiB. The host caps before the `as u32` cast so a truncated input can't corrupt the import. # ExportSignatureMismatch (Copilot #4) Previously `get_typed_func::<u32, u32>("alloc").map_err(|_| MissingExport("alloc"))` collapsed two distinct failure modes into one misleading error. Since `validate_module` proves presence by name at load time, any subsequent typed_func failure is necessarily a signature mismatch — surfaced now as `WasmImporterError::ExportSignatureMismatch { name, source }` which names the export and chains the wasmtime type-mismatch detail. Applied at all 3 typed_func sites (`alloc`, the dispatched entry, `metadata`). # CSV projection honesty (Copilot #5) `CsvConfig` has 18 fields; this PR projects 8 (the simple String/bool/number ones). Updated `build_wasm_input` and `project_csv_config_into_options` docs to say "subset" + list exactly what's projected and what's deferred to wave 2.3e (column specs, locale, mappings — encoding decisions best driven by a real WASM CSV importer, not guessed here). No behavior change. # Stale duplication comment (Copilot #6) The comment in `output_to_import_result` claimed the wrapper→directive converter was "duplicated here so this crate doesn't need to depend on the full `rustledger-plugin` graph" — but the code actually calls `rustledger_plugin::convert::wrapper_to_directive` directly, with the explicit dep added in this PR's Cargo.toml. Rewrote to say "delegates … so the WASM importer path and directive-plugin path share a single converter." # Tests 3 new wasm:: tests (158 importer total, was 155): - validate_input_size_accepts_at_cap_and_rejects_above — boundary test for MAX_INPUT_BYTES and the InputTooLarge surface. - fuel_calc_saturates_instead_of_overflowing — regression for Copilot #2; loads with u64::MAX max_time_secs and asserts no panic + successful execution. - wrong_signature_export_surfaces_export_signature_mismatch — WAT module with metadata: () -> i32 (wrong: should be -> i64); asserts ExportSignatureMismatch { name: "metadata" } rather than the previously-misleading MissingExport. # Verification - 26 wasm:: tests pass (was 23) - 158/158 rustledger-importer tests pass - cargo check --workspace --all-targets clean - cargo clippy --workspace --all-targets -- -D warnings clean - cargo fmt --all -- --check clean Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(importer): rustdoc — drop private-item intra-doc links in public docs CI Documentation job (rustdoc with -Dwarnings) caught two intra-doc links from public-API surface to private items, which I introduced in the previous commit: - `OutputTooLarge` variant doc → `MAX_OUTPUT_BYTES` (private const) - `InputTooLarge` variant doc → `MAX_INPUT_BYTES` (private const) `rustdoc::private_intra_doc_links` denies these because the rendered docs would be useless to library consumers: the link target isn't visible to them. The fix: drop the `[`…`]` link syntax for plain backticks, and inline the literal byte value (64 MiB) so the doc is self-contained. Also fixed two adjacent rustdoc warnings that surface under `--document-private-items` (not CI-blocking, but cheap to address): - `Option<String>` in a doc comment was parsed as an HTML tag — wrapped in backticks. - `[`CategorizationMethod::Default`]` on the private `parse_method` fn — switched to plain backticks for consistency with the visible text approach. Verification: `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-importer` clean. clippy + 26 wasm tests still green. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * refactor(plugin,importer): shared wasmtime sandbox config + 5 review fixes Addresses the second-round deep review of #1131. Adds a workspace- shared sandbox configuration module and applies the remaining substantive review items. # New: rustledger_plugin::sandbox (workspace-wide #6) New module exporting: - `sandbox_config()` — wasmtime Config with rustledger's locked-down feature set: - Enabled: consume_fuel + (defaults) wasm_simd, wasm_bulk_memory, wasm_reference_types, wasm_multi_value, wasm_extended_const, wasm_relaxed_simd - Explicitly disabled (security): wasm_threads, wasm_shared_everything_threads (concurrency bypass), wasm_multi_memory, wasm_memory64 (ABI/limiter invariants), wasm_component_model (we use custom MessagePack ABI), wasm_gc, wasm_function_references, wasm_stack_switching, wasm_tail_call (unused complexity / shrink attack surface) - `shared_engine()` — process-wide `Arc<Engine>` via OnceLock. wasmtime docs recommend one Engine per process; sharing amortizes JIT/cache cost across all WASM-loaded modules. 3 unit tests pin the contract: `shared_engine` returns the same Arc, modules requiring `wasm_threads` (shared memory) fail to compile, modules requiring `wasm_multi_memory` fail to compile. # rustledger-plugin/runtime.rs: adopt shared engine (#6) Both `Plugin::load` and `Plugin::load_bytes` now use `sandbox::shared_engine()` instead of constructing their own fuel-only Config + Engine. Same security posture as importer. # rustledger-importer/wasm.rs: review fixes 1-4, 7, 8, 9 **Item 1: identify() silently swallows errors.** Now logs to stderr on failure, naming the importer + path + underlying error. Trait contract still returns bool (matches OFX/CSV), but guest authors get a signal for ExportSignatureMismatch / InputTooLarge / traps instead of "never matches with no clue why." **Item 2: MissingExport("memory") was dead code at call time.** `validate_module` proves memory presence at load, so the `.ok_or(MissingExport("memory"))` was unreachable post-load. Now `.expect("validate_module verified `memory` export at load")` — documents the invariant rather than guarding a real failure path. **Item 3: warning-order doc on output_to_import_result.** Mirrored the rustdoc section from bridge_enriched_output describing emission order (output.warnings → output.errors via format_plugin_error), plus a note that bridge_enriched_output additionally emits per- entry bridge warnings first. **Item 4: file-read error typing.** `extract` and `extract_enriched` now construct `WasmImporterError::Io { path, source }` and convert via anyhow at the trait boundary, symmetric with `load_with_config`. The typed variant is unreachable to external callers (trait erases to anyhow) but eliminates the inside-the-crate inconsistency. **Item 7: load_embedded helper.** New `WasmImporter::load_embedded(name_for_diagnostics, bytes)` for embedders shipping `.wasm` inside a binary. Wraps `load_from_bytes` with `WasmRuntimeConfig::default()` so the common case is a single call instead of having to invent a `PathBuf` + pass a default config. **Item 8: runtime_config() accessor.** `WasmImporter` now exposes `pub const fn runtime_config() -> WasmRuntimeConfig` for diagnostics — useful when a user sees an `InputTooLarge { max: 67108864 }` and wants to confirm the cap matches the importer's intended config. **Item 9: make_store unreachable-fuel comment.** The `set_fuel(...)?` propagation only fires when `consume_fuel(false)`, which our shared sandbox config never sets. Added a comment explaining the path is defensive (so a future refactor flipping the flag surfaces an error rather than panicking). # wasm.rs: refactor consequences - WasmImporter no longer constructs its own Engine + Config; pulls from `sandbox::shared_engine()` instead. Removes ~10 lines. - Two pre-existing tests that built throwaway Engines for `validate_module` testing now use `sandbox::shared_engine()` — shorter and exercises the same wiring real loads use. # Verification - 107 + 176 + 8 rustledger-plugin tests pass (3 new in sandbox) - 26 rustledger-importer wasm tests pass (unchanged count) - 158 total rustledger-importer tests pass - cargo check --workspace --all-targets clean - cargo clippy --workspace --all-targets -- -D warnings clean - cargo fmt --all -- --check clean - RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps clean Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * docs(sandbox): note breaking change + harden tests + richer init panic Addresses the four substantive items from the second-round review of the sandbox refactor in 52dd0b6. # Doc (#1): breaking-change notice Added a "Breaking change for user WASM plugins" section to the `sandbox` module rustdoc, naming the five most impactful disabled proposals (`wasm_threads`, `wasm_multi_memory`, `wasm_memory64`, `wasm_component_model`, `wasm_gc`). Plugin authors targeting earlier rustledger versions will see a wasmtime validation error at load time and need to recompile against the new sandbox profile. # Panic message (#2): preserve wasmtime error `shared_engine` previously used `.expect("failed to build shared wasmtime engine")`, which swallowed the underlying error detail. Now uses `.unwrap_or_else(|e| panic!("wasmtime engine init failed: {e}"))` so a process-start failure preserves the cause for debugging. Still a panic (same semantics); just more useful when it fires. # Regression coverage (#3): 3 new tests Added rejection tests for three more disabled features: - `sandbox_config_rejects_memory64_module` — `(memory i64 1)` - `sandbox_config_rejects_component_module` — `(component)` top-level - `sandbox_config_rejects_gc_module` — `(type $s (struct …))` Sandbox test count: 3 → 6. The remaining disabled flags (`wasm_function_references`, `wasm_stack_switching`, `wasm_tail_call`, `wasm_shared_everything_threads`) are minor variants of the tested ones; explicit tests would be duplicative. # Maintenance comment (#4): wasmtime upgrade audit Added a MAINTENANCE NOTE atop `sandbox_config` calling out that wasmtime's `Config::new()` defaults evolve across versions and new proposals routinely land as default-on. On every wasmtime bump in `Cargo.toml`, this function must be re-audited against wasmtime's release notes — wasmtime has no "deny by default" mode, so the audit is structurally required, not optional. # Verification - 6/6 sandbox tests pass (3 new in this commit) - cargo clippy --workspace --all-targets -- -D warnings clean - cargo fmt --all -- --check clean Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * refactor(plugin,importer): lift limiter to sandbox + complete review polish Closes the substantive gap from the third-round review: the workspace- shared sandbox refactor (52dd0b6) only addressed Engine config, not per-Store limiter wiring. The plugin runtime still ignored `max_memory` even after the sandbox module landed. This commit lifts the entire enforcement stack into `rustledger_plugin::sandbox` so both call sites get identical per-Store enforcement. # Item 1 (substantive): per-Store enforcement now workspace-wide Moved from `rustledger-importer/src/wasm.rs` to `rustledger-plugin/src/sandbox.rs`: - `pub struct MemoryLimiter` (with `MemoryLimiter::new` ctor) - `pub struct StoreState` - `pub const MAX_TABLE_ELEMENTS: usize` - `pub fn make_sandboxed_store(engine, max_memory, max_time_secs) -> wasmtime::Result<Store<StoreState>>` — wires the limiter, clamps zero fuel, saturating-multiplies to avoid u64 overflow `Plugin::execute` in `runtime.rs` now uses `make_sandboxed_store` instead of constructing an unmetered `Store<()>` + bare `store.set_fuel(config.max_time_secs * 1_000_000)`. The multiplication could previously overflow and the limiter was never wired — both fixed in one motion. `wasm.rs::make_store` becomes a thin `WasmImporterError`-adapting wrapper. 3 new sandbox unit tests: - `make_sandboxed_store_wires_fuel_and_limiter` - `make_sandboxed_store_clamps_zero_max_time_secs` - `make_sandboxed_store_saturates_huge_max_time_secs` The two now-duplicated wasm.rs unit tests (`memory_limiter_…`, `table_limiter_…`) are removed — sandbox.rs has authoritative coverage. `wasm.rs::initial_memory_above_cap_is_rejected_via_limiter_wiring` remains as the integration test proving the importer side wires the helper correctly. # Item 2: accessor tests - `load_embedded_uses_name_as_path_and_default_config` — locks in the diagnostic-name → `path()` flow and default-config behavior. - `runtime_config_returns_the_loaded_config` — locks in the `runtime_config()` accessor against custom configs. # Item 3: manual Debug impl for WasmImporter Hand-rolled `impl std::fmt::Debug for WasmImporter` printing path/name/description/config (skipping wasmtime's Module/Engine which produce noisy version-dependent output). New `debug_impl_does_not_panic_and_redacts_wasmtime_types` test asserts that the redaction holds. # Item 4: hardcoded caps comment Added a NOTE block above `MAX_OUTPUT_BYTES`/`MAX_INPUT_BYTES` explaining that the caps are per-process, not per-importer, and that per-importer tunability is a v1.0 surface decision. # Item 5: MAINTENANCE NOTE moved to rustdoc `sandbox_config`'s wasmtime-upgrade-re-audit note moved from an inline body comment to a rustdoc `# Maintenance: re-audit on every wasmtime bump` section so `cargo doc` surfaces it. # Item 7: breaking-change doc lists all 8 disabled flags Expanded the "Breaking change for user WASM plugins" section in `sandbox.rs` to enumerate all 8 disabled proposals (`wasm_threads`, `wasm_shared_everything_threads`, `wasm_multi_memory`, `wasm_memory64`, `wasm_component_model`, `wasm_gc`, `wasm_function_references`, `wasm_stack_switching`, `wasm_tail_call`) instead of just the 5 most impactful. # Verification - 11 sandbox tests pass (was 6; +3 make_sandboxed_store + +2 MemoryLimiter moved over from wasm.rs) - 27 wasm:: tests pass (was 26; +3 new accessors/Debug, -2 duplicates moved to sandbox) - 115 rustledger-plugin tests total - 158 rustledger-importer tests total - cargo check --workspace --all-targets clean - cargo clippy --workspace --all-targets -- -D warnings clean - cargo fmt --all -- --check clean - RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps clean Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(plugin): align validator with sandbox, auto-validate on load, plug exec memory test Addresses the fourth-round review of #1131 — closes the workspace- consistency loose ends on the plugin runtime side. # Item 1 — `validate_plugin_module` uses sandbox config Previously `validate_plugin_module` constructed `Engine::default()`, which has wasmtime's defaults (e.g. `wasm_threads(true)`). A module using `wasm_threads` would pass validate but then fail `Plugin::load_bytes` because the runtime uses the locked-down `sandbox::sandbox_config()`. Users got contradictory answers. Fixed: validate uses `Engine::new(&sandbox::sandbox_config())` so the answer matches what the runtime will actually accept. # Item 3 — Auto-validate on plugin load Extracted a `fn validate_loaded_module(&Module) -> Result<()>` inner helper. `validate_plugin_module(bytes)` and the new auto- validation path in `Plugin::load`/`load_bytes` both call it, avoiding the double-compile that would happen if load called the public `validate_plugin_module(bytes)` directly. Both `Plugin::load` paths now run `validate_loaded_module(&module)` right after `Module::new`, so missing exports surface at load time with the existing "must export 'X'" message instead of showing up later as misleading "must export 'X' function" errors from `get_typed_func` failures in `execute()`. # Item 2 — `Plugin::execute` distinguishes wrong signature from missing Now that presence is proven at load: - `get_memory(...).ok_or_else(...)` becomes `.expect("validate_loaded_module verified ...")` — invariant, not failure path. - `get_typed_func::<...>(...).context("plugin must export ...")?` becomes `.context("plugin export `X` has wrong signature (expected fn(...))")` — accurate, since absence was already ruled out. Mirrors the importer's `ExportSignatureMismatch` story without adding a new error variant (plugin runtime is anyhow-based; just better context strings). # Item 4 — Plugin::execute memory cap integration test New `execute_rejects_initial_memory_above_max_memory_cap` in runtime.rs's tests: declares 5000 pages (320 MiB) initial memory in a WAT module, runs it via `Plugin::execute` with a 64 MiB `max_memory` config, asserts the call fails. Mirrors the importer's `initial_memory_above_cap_is_rejected_via_limiter_wiring` test for the plugin runtime path — proves the `make_sandboxed_store` limiter wiring actually applies to plugins, not just importers. # Item 6 — Inline wasm.rs::make_store wrapper `make_store` was a one-line adapter (`make_sandboxed_store` plus `.map_err(runtime_err)`). Inlined at the two call sites in `call_msgpack_with` and `call_metadata` — the local conversion is more honest than a helper that exists only to shorten the line slightly. # Verification - 116 rustledger-plugin tests (was 115; +1 memory-cap integration) - 27 rustledger-importer wasm:: tests (unchanged; inlining is a zero-test-impact refactor) - 159 rustledger-importer tests total - 11 sandbox:: tests (unchanged) - cargo check --workspace --all-targets clean - cargo clippy --workspace --all-targets -- -D warnings clean - cargo fmt --all -- --check clean Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(plugin): wrong-sig test + doc/contract polish from fifth-round review Closes the small loose ends from the fifth-round deep review of #1131. All changes scoped to runtime.rs. # Item 1: test for wrong-signature export New `execute_surfaces_wrong_signature_on_alloc`: WAT module with `alloc(i64) -> i64` instead of `alloc(u32) -> u32`. Presence check passes (the export exists), so the failure surfaces inside `execute()` with the new "wrong signature" context. Pre-PR this read "plugin must export 'alloc' function" — misleading, since it DID export it. Pins the contract so a future refactor that collapses the load-time validation can't silently re-introduce the misleading message. # Item 2: drop redundant type info from sig context Was: "plugin export `alloc` has wrong signature (expected fn(u32) -> u32)" "plugin export `process` has wrong signature (expected fn(u32, u32) -> u64)" Now: "plugin export `alloc` has wrong signature" "plugin export `process` has wrong signature" wasmtime's underlying error already says expected-vs-found types — our context was duplicating it and would have lied if the ABI ever changes. Comment explains why we don't repeat the type info. # Item 4: doc note on RuntimeConfig — applied at execute, not load Made explicit that `Plugin::load`/`load_bytes` accept a `&RuntimeConfig` for API symmetry but ignore it. Only `Plugin::execute` consumes the caps, via `make_sandboxed_store`. The field-level docs now also point at the helper. # Item 5: symmetric `invalid plugin` context on Module::new Previously: `Module::new` failure → "failed to compile <path>", `validate_loaded_module` failure → "invalid plugin <path>". Inconsistent prefix for two failure modes of the same load operation. Now both use "invalid plugin <path>" so log scrapers / error-classifying code can use one prefix. Same in `load_bytes`: bare wasmtime error → "invalid plugin `name`" wrapping. # Item 7: tighten memory-cap test assertion `execute_rejects_initial_memory_above_max_memory_cap` previously asserted `!msg.is_empty()` — too weak. Now lowercases the message and asserts `msg.contains("memory") || msg.contains("limit")`, which would have failed if the limiter wiring silently broke (error would be about an unrelated issue, not memory). Still tolerates wasmtime wording variance across versions. # Verification - 117 rustledger-plugin tests (was 116, +1 wrong-signature) - 159 rustledger-importer tests - 11 sandbox tests - cargo check --workspace --all-targets clean - cargo clippy --workspace --all-targets -- -D warnings clean - cargo fmt --all -- --check clean Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * test(plugin): symmetric coverage for fuel clamp + process wrong-sig Closes the small coverage gaps from the sixth-round review. # Test additions - `execute_surfaces_wrong_signature_on_process` — sibling to `_on_alloc`. WAT with `process(i32, i32) -> i32` (should be `(u32, u32) -> u64`). Asserts the error message contains `process` + `wrong signature`. Covers the second of two `get_typed_func` call sites in `Plugin::execute`. - `execute_with_zero_max_time_secs_clamps_to_min_fuel` — proves the `make_sandboxed_store` fuel-clamp fix is reachable through the plugin runtime path, not just the importer. WAT returns `(ptr=0, len=0)` which can't deserialize as PluginOutput; reaching the decode step proves no fuel-trap fired during execute. New `assert_not_fuel_trap` helper checks the error is the expected decode failure, not a "fuel"/"trap" wasmtime error. - `execute_with_max_max_time_secs_saturates_fuel` — equivalent for the `saturating_mul` fix. `u64::MAX` config previously panicked in debug / wrapped in release; now saturates via the shared helper. The shared helper has these tests in `sandbox::tests`. The plugin versions are integration tests that prove the wiring from `Plugin::execute` into the helper stays correct against future refactor — if anyone reverts `Plugin::execute` to manual `Store::new + set_fuel`, both fuel bugs return and at least one of these tests fails. # Polish - Test imports tightened: `use crate::types::PluginOptions` at the top of `mod tests` instead of fully-qualified inline. # Deferred - wasm.rs file split into `wasm/{mod,limits,bridge,error,runtime}.rs` was a candidate fix but is a 2000-line refactor that belongs in its own focused PR — mid-stream is bad practice. Logged as a known follow-up. - Commit squash (10 commits → ~3) is merger preference; GitHub's squash-merge handles this at merge time. Not destructively rewriting history. # Verification - 120 rustledger-plugin tests (was 117; +3 new) - 159 rustledger-importer tests (unchanged) - 11 sandbox tests - cargo check --workspace --all-targets clean - cargo clippy --workspace --all-targets -- -D warnings clean - cargo fmt --all -- --check clean Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
5 tasks done
robcohen
added a commit
that referenced
this pull request
Jun 10, 2026
Addresses 10 deep-review findings + 5 Copilot inline comments (all converging on the same byte-identity / doc-drift / cache- reach themes). ## Correctness - `format_source_with_parsed` now falls back to `format_source(source)` when `parse_result.errors` is non- empty. Preserves byte-identity for inputs whose CST diverges from what `format_source`'s pre-parse normalization would produce — concretely, bare-`\r` (classic Mac) line terminators that `crlf_to_lf_outside_strings` normalizes but `parse_via_cst` does not. Without this fallback, classic-Mac sources would emit different text on the cached path vs format_source. - Defensive length-check `debug_assert_eq!` catches the most common form of `(parse_result, source)` mismatched pair (different documents have different lengths). Released as `debug_assert_eq!` so release builds pay no cost; debug builds panic on mismatched pair. New test `format_source_with_parsed_panics_on_length_mismatch` pins the debug-build behavior. ## More cache reach - CLI `try_format_source` (the entry that backs `rledger format`) switched from `format_source(source)` to `format_source_with_parsed(&result, source)`. The CLI was the one consumer round-1 missed — same shape as the LSP/FFI/WASM migrations. - `rledger doctor roundtrip` switched similarly. On a project of 200 included files the doctor pass roughly halves its parsing cost. ## Test fixture expansion Added three new fixtures to `format_source_with_parsed_matches_format_source`: - **BOM + CRLF combination** — Windows-authored ledger with a UTF-8 BOM. - **Parse-error file** — exercises the new error-gate fallback. - **Bare-CR line terminators** — classic-Mac source; exercises the fallback (`parse_via_cst` errors out on bare CR). ## Hot-path costs - `assert_eq!` → `debug_assert_eq!` in `format_node_with_alignment` and `format_node_range_with_alignment`. The bare `format_node` / `format_node_range` delegates already validated kind via `SourceFile::cast`, so on the most common call path (bare → with_alignment) the assert was a redundant release-build cost. External direct callers still get a debug-build panic on wrong-kind input. ## Rustdoc fixes (Copilot inline #1 / #3 / #4 / #5) - Three rustdoc cites pointed at non-existent tests: `compute_alignment_matches_parseresult_cache` (lib.rs:309, format.rs:858 in `compute_alignment`, convert.rs:272 inline comment) and `format_node_range_with_alignment_matches_uncached` (format.rs:812). Renamed to point at actual test names (`parse_result_alignment_cache::*` and `format_node_range_matches_format_node_range_with_alignment`). - `compute_alignment(node)` doc claim corrected: the function takes `&SourceFile`, not `&SyntaxNode`. Updated to `compute_alignment(&SourceFile::cast(node).unwrap())` in both occurrence sites. - `syntax_node().cast::<SourceFile>()` invalid turbofish in rustdoc fixed to `SourceFile::cast(syntax_node()).unwrap()`. ## Public API path consistency (Copilot inline #2) `ParseResult::alignment` field type spelled as `crate::format::PostingAlignment` (via the public re-export surface) instead of `crate::cst::format::PostingAlignment` (the internal module path). Matches the documented "sole import path" convention in `crate::format` module rustdoc. ## CHANGELOG naming rationale tightened Cited the live existing `rustledger_core::Alignment` (an unrelated workspace type used by the legacy typed-Directive emitter) as the concrete reason for naming the new type `PostingAlignment` instead of bare `Alignment`. Round-1 only mentioned hypothetical future collisions. ## Stale rustdoc reference `Alignment::default()` → `PostingAlignment::default()` in the `format_node_with_alignment` rustdoc. ## Criterion benchmark New `bench_format_source_vs_with_parsed` group in `benches/parser_bench.rs`. Compares `format_source(s)` against `format_source_with_parsed(&pre_parsed, s)` on 10 / 100 / 1000 transaction synthetic ledgers. Provides an executable witness for the PR's perf claim. ## Verified - `cargo test -p rustledger-parser -p rustledger-lsp -p rustledger-ffi-wasi -p rustledger --all-features` — 224 LSP lib + 263 parser lib + 58 FFI lib + integration suites green (parser: 262 -> 263 with the new debug-build panic test). - `cargo clippy --workspace --all-features --all-targets -- -D warnings` clean. - `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser -p rustledger-lsp --no-deps` clean. - Baseline manifest unchanged. Refs #1299. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen
added a commit
that referenced
this pull request
Jun 10, 2026
…es (#1299) * chore(deps): #1262 unyank aes 0.9.0 -> 0.9.1 cargo deny check surfaced aes 0.9.0 (transitive via zip 8.6.0 -> rustledger-plugin) as a yanked version. cargo update -p aes resolves to 0.9.1, the immediate successor that drops the yank mark. Lockfile-only change, no source diff in the workspace, no semver impact on rustledger-plugin or its consumers. cargo deny check now reports advisories ok, bans ok, licenses ok, sources ok across the workspace. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * feat(parser,lsp): cache formatter alignment on ParseResult Pre-compute the formatter's file-wide alignment columns at parse time and stash them on `ParseResult::alignment`, so hot formatting paths (notably the LSP `range_formatting` fallback shipped in #1298) don't re-walk every posting in the file on every call. ## Background `format_node` and `format_node_range` (in `rustledger-parser/src/cst/format.rs`) run a pre-pass over every Transaction's postings to compute file-wide alignment columns: `number_col` (where the right-justified number field starts) and `number_width` (max rendered width of any number). The pre-pass is `O(N_postings_in_file)` per call. This is fine for the CLI's one-shot `rledger format`, but the LSP `range_formatting` fallback path can be invoked per-keystroke by format-on-type clients while the user is editing through a parse error. A 10k-directive ledger with a typo means we walked 10k directives' postings on every key press. The PR #1298 review flagged this as a real concern (deferred at the time as acceptable). ## What's in this PR ### Parser - `format::Alignment` is now `pub` + `#[non_exhaustive]` + `Copy`, with public `number_col` / `number_width` fields. Construction via `Alignment::default()` is supported externally; the `#[non_exhaustive]` attribute reserves the right to add fields later without breaking downstream `match` arms. - `format::compute_alignment(&SourceFile) -> Alignment` is now `pub` so consumers can pre-compute independently. - `ParseResult::alignment: Alignment` populated by `parse_via_cst` during the existing `walk_descendants_once` pass. Same canonical- payload exclusion pattern as `syntax_root`: bound in the destructure for compiler-enforced exhaustiveness, discarded from the canonical hash. Pinned by `canonical_payload_excludes_alignment`. - Two new `_with_alignment` variants: `format::format_node_with_alignment(node, alignment) -> String` and `format::format_node_range_with_alignment(node, range, alignment)`. The bare `format_node` / `format_node_range` delegate to them after computing alignment internally — no behavior change for existing callers, just a new opt-in fast path. - Equivalence pinned: `format_node_equals_format_node_with_alignment` and `format_node_range_matches_format_node_range_with_alignment` assert byte-identical output across representative fixtures. The cache's freshness vs. a fresh `compute_alignment` call is pinned by `parse_result_alignment_cache::*` (6 fixtures including empty source, open-only, single transaction, multi-transaction with varying widths, arithmetic amounts, and a parse-error file). ### LSP - `fallback_cst_snap_edit` in `range_formatting.rs` now calls `format_node_range_with_alignment(&node, cst_range, parse_result.alignment)` instead of `format_node_range(&node, cst_range)`. The per-call `O(N_postings)` walk is gone; per-fallback cost is now `O(N_cst_nodes covered by the user's range)`, independent of file size. ### Deps - `cargo update -p aes` to unyank the transitive dependency `aes 0.9.0 -> 0.9.1`. Surfaced by `cargo deny check`. Lockfile-only, no source diff anywhere in the workspace. ## Why both in one PR The dependency unyank is a single-line lockfile change that would otherwise sit in its own trivial PR. Keeping it next to the substantive change is a closing housekeeping pass; the two commits are clean (`chore(deps):` + `feat(parser,lsp):`) so they can be split during review if desired. ## Verified - `cargo test -p rustledger-parser -p rustledger-lsp --all-features` (224 LSP lib + 260 parser lib green; parser format module suite went 250 -> 260 with the 10 new tests spread across `cst::format::tests`, `parse_result_alignment_cache`, `canonical_payload_excludes_alignment`). - `cargo clippy --workspace --all-features --all-targets -- -D warnings` clean. - `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser -p rustledger-lsp --no-deps` clean. - `cargo deny check` now reports `advisories ok, bans ok, licenses ok, sources ok`. - Baseline manifest unchanged (the canonical-payload exclusion works as designed; the new test pins it executably). Refs #1262 (post-completion follow-up flagged in the closing comment). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * chore: regenerate cargo-vet exemptions * fix(parser,lsp,ffi,wasm): #1299 round-1 review findings Addresses 10 deep-review findings on PR #1299. Same root cause for the largest one: the original PR optimized only the rare parse-error LSP fallback path; the much more common Format-on- Save / FFI format.source / WASM ParsedLedger::format paths still re-parsed the source and re-walked every posting, leaving the cache mostly dead code. ## Cache reaches the happy path now - New public entry `format::format_source_with_parsed(&ParseResult, &str)` reuses the cached `syntax_root` AND `alignment`, skipping both the duplicate parse and the duplicate alignment walk. - LSP `handle_formatting` / `format_document` switched to `format_source_with_parsed`. The Format-on-Save / format-on- type-clean-file paths now pay only the per-call emit cost. - FFI `format.source` (rustledger-ffi-wasi/src/jsonrpc/router.rs) switched: it already produced `parse_result` for the error gate; the second parse via `format_source` is gone. - WASM `ParsedLedger::format` (already-cached `parse_result` field) and `api::format_source` (already-produced `parse_result`) both switched. - Byte-identical output pinned by new `format_source_with_parsed_matches_format_source` test across LF / CRLF / BOM-prefixed fixtures. The two paths produce the same canonical text because the canonical form is rebuilt from typed values rather than echoing trivia. ## Type rename: Alignment -> PostingAlignment The public type was just introduced this week (no shipped consumers); the cheapest moment to rename. `Alignment` is too generic for `rustledger_parser::format::Alignment` and would compete with future text-justification or memory-layout helpers. `PostingAlignment` is qualified by its semantic purpose. Re- export, struct definition, field type on `ParseResult::alignment`, all internal `align: Alignment` parameter sites, and the `canonical_payload_excludes_alignment` test all updated. ## Cast cleanup in _with_alignment fns `format_node_with_alignment` and `format_node_range_with_alignment` each replaced their `SourceFile::cast(node.clone()).expect(...)` + misleading `let _ = source_file;` precondition with `assert_eq!(node.kind(), SyntaxKind::SOURCE_FILE)`. Saves the redundant Arc-bump clone on every hot-path call (the bare `format_node` delegate already validated the kind) while keeping the same panic guarantee for direct external callers. The `format_node_with_alignment` body now uses `node.children_with_tokens()` directly instead of `source_file.syntax().children_with_tokens()`. ## Docs - `compute_alignment` rustdoc grew a `Tree-shape precondition` section documenting the must-be-just-parsed contract: hand-built partial trees and ERROR_NODE-wrapped transactions silently fall back to `PostingAlignment::default()`. Behavior pinned by the new `parse_result_alignment_cache::mid_transaction_error_node` test. - `ParseResult::alignment` rustdoc grew a `Producer-only cache invariant` section explaining what happens if a consumer mutates `directives` / `syntax_root` without refreshing the cache, and pointing them at `compute_alignment` for the manual refresh. - CHANGELOG entry rewritten to list the three public entry points (node, node_range, source), document the `PostingAlignment` naming choice, and capture the producer-only invariant. ## Tests - Existing 10 cache-equivalence tests still pass. - 1 new test pins `format_source_with_parsed` byte-identity vs `format_source` across LF / CRLF / BOM fixtures. - 1 new test pins cache equivalence under mid-transaction ERROR_NODE recovery — the scenario the LSP fallback actually traverses during format-on-type. ## Verified - `cargo test -p rustledger-parser -p rustledger-lsp -p rustledger-ffi-wasi --all-features` — 224 LSP lib + 262 parser lib + 58 FFI lib + integration suites green (parser: 260 -> 262 with the 2 new tests). - `cargo clippy --workspace --all-features --all-targets -- -D warnings` clean. - `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser -p rustledger-lsp -p rustledger-ffi-wasi -p rustledger-wasm --no-deps` clean. - Baseline manifest unchanged. Refs #1299. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(parser,lsp,cli): #1299 round-2 review findings + Copilot inline Addresses 10 deep-review findings + 5 Copilot inline comments (all converging on the same byte-identity / doc-drift / cache- reach themes). ## Correctness - `format_source_with_parsed` now falls back to `format_source(source)` when `parse_result.errors` is non- empty. Preserves byte-identity for inputs whose CST diverges from what `format_source`'s pre-parse normalization would produce — concretely, bare-`\r` (classic Mac) line terminators that `crlf_to_lf_outside_strings` normalizes but `parse_via_cst` does not. Without this fallback, classic-Mac sources would emit different text on the cached path vs format_source. - Defensive length-check `debug_assert_eq!` catches the most common form of `(parse_result, source)` mismatched pair (different documents have different lengths). Released as `debug_assert_eq!` so release builds pay no cost; debug builds panic on mismatched pair. New test `format_source_with_parsed_panics_on_length_mismatch` pins the debug-build behavior. ## More cache reach - CLI `try_format_source` (the entry that backs `rledger format`) switched from `format_source(source)` to `format_source_with_parsed(&result, source)`. The CLI was the one consumer round-1 missed — same shape as the LSP/FFI/WASM migrations. - `rledger doctor roundtrip` switched similarly. On a project of 200 included files the doctor pass roughly halves its parsing cost. ## Test fixture expansion Added three new fixtures to `format_source_with_parsed_matches_format_source`: - **BOM + CRLF combination** — Windows-authored ledger with a UTF-8 BOM. - **Parse-error file** — exercises the new error-gate fallback. - **Bare-CR line terminators** — classic-Mac source; exercises the fallback (`parse_via_cst` errors out on bare CR). ## Hot-path costs - `assert_eq!` → `debug_assert_eq!` in `format_node_with_alignment` and `format_node_range_with_alignment`. The bare `format_node` / `format_node_range` delegates already validated kind via `SourceFile::cast`, so on the most common call path (bare → with_alignment) the assert was a redundant release-build cost. External direct callers still get a debug-build panic on wrong-kind input. ## Rustdoc fixes (Copilot inline #1 / #3 / #4 / #5) - Three rustdoc cites pointed at non-existent tests: `compute_alignment_matches_parseresult_cache` (lib.rs:309, format.rs:858 in `compute_alignment`, convert.rs:272 inline comment) and `format_node_range_with_alignment_matches_uncached` (format.rs:812). Renamed to point at actual test names (`parse_result_alignment_cache::*` and `format_node_range_matches_format_node_range_with_alignment`). - `compute_alignment(node)` doc claim corrected: the function takes `&SourceFile`, not `&SyntaxNode`. Updated to `compute_alignment(&SourceFile::cast(node).unwrap())` in both occurrence sites. - `syntax_node().cast::<SourceFile>()` invalid turbofish in rustdoc fixed to `SourceFile::cast(syntax_node()).unwrap()`. ## Public API path consistency (Copilot inline #2) `ParseResult::alignment` field type spelled as `crate::format::PostingAlignment` (via the public re-export surface) instead of `crate::cst::format::PostingAlignment` (the internal module path). Matches the documented "sole import path" convention in `crate::format` module rustdoc. ## CHANGELOG naming rationale tightened Cited the live existing `rustledger_core::Alignment` (an unrelated workspace type used by the legacy typed-Directive emitter) as the concrete reason for naming the new type `PostingAlignment` instead of bare `Alignment`. Round-1 only mentioned hypothetical future collisions. ## Stale rustdoc reference `Alignment::default()` → `PostingAlignment::default()` in the `format_node_with_alignment` rustdoc. ## Criterion benchmark New `bench_format_source_vs_with_parsed` group in `benches/parser_bench.rs`. Compares `format_source(s)` against `format_source_with_parsed(&pre_parsed, s)` on 10 / 100 / 1000 transaction synthetic ledgers. Provides an executable witness for the PR's perf claim. ## Verified - `cargo test -p rustledger-parser -p rustledger-lsp -p rustledger-ffi-wasi -p rustledger --all-features` — 224 LSP lib + 263 parser lib + 58 FFI lib + integration suites green (parser: 262 -> 263 with the new debug-build panic test). - `cargo clippy --workspace --all-features --all-targets -- -D warnings` clean. - `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser -p rustledger-lsp --no-deps` clean. - Baseline manifest unchanged. Refs #1299. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]> Co-authored-by: rustledger-bot[bot] <257329324+rustledger-bot[bot]@users.noreply.github.com>
robcohen
added a commit
that referenced
this pull request
Jun 19, 2026
Follow-up to the review on #1435. Instead of running the plugin and relabeling the failure by name-shape, detect a bare module-name reference *before* invoking the runtime: - Correctness (#1): the old error-path relabel discarded the real error `e` for any dotted/non-.py name — masking genuine failures such as a corrupt runtime download (`PythonRuntime::new()` fails before module discovery). Now module names are rejected up front, so the `Err(e)` arm only fires for real plugin files and surfaces `e` verbatim (E8002). - Altitude (#2): no runtime is downloaded/compiled (and no "10-100x slower" warning printed) for a request that is rejectable from the name alone. - Reuse/consistency (#3): both E8004 sites now share `module_ref_message`, so the "not supported by module name; reference the file directly" guidance is identical everywhere. - Discriminator (#4): one `is_python_module_name` helper using `eq_ignore_ascii_case`, not the pre-lowercased `ext` (fixes a latent case-sensitivity coupling). - Docs (#5): document E8002/E8004/E8005 in docs/reference/errors.md. - Cleanup (#6,#7): static example path (drops the dead `unwrap_or` and the `./.py` trailing-dot edge); drop the redundant `is_python_available()` guard (`suggest_module_path` already handles a missing interpreter). fmt + clippy (-D warnings, python-plugins) clean; loader suite 64/64. Co-Authored-By: Claude Opus 4.8 <[email protected]>
robcohen
added a commit
that referenced
this pull request
Jun 19, 2026
* fix(loader): actionable error for module-name Python plugin refs A Python plugin declared by module name (beancount's `plugin "pkg.mod"`) is unsupported by design — only file-path references load (see `discover_module_source`). It routes into the Python-plugin branch (the name contains a dot), runs, and fails inside `execute_module`, surfacing as `E8002: Python plugin 'pkg.mod' execution failed: Python plugin module not found: pkg.mod` — doubly misleading, reading as a venv/PYTHONPATH problem the user cannot fix. Detect the bare-module-name case in the error path and emit an actionable `E8004` instead: name the unsupported form and point at the file path, resolving it via system Python (`suggest_module_path`) when possible, else a generic hint that also notes the sandbox cannot see the host venv (the plugin must be self-contained). This also unifies the code with the parallel unknown-plugin branch (both `E8004`). The existing `suggest_module_path`/`E8004` hint was unreachable for real module names because they always contain a dot and were diverted into the Python branch first. Closes #1432 (Gap 1). Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(plugins): document Python plugin file-path + self-contained model Gaps 2-3 of #1432. Document that: - Built-in names resolve to the native Rust plugin regardless of the `beancount.plugins.` prefix (so `plugin "beancount.plugins.auto_accounts"` is unchanged), but a custom Python plugin must be referenced by file path — the module-name form is rejected. - Python plugins run in a CPython-WASI sandbox that never mounts the host venv / site-packages, so they must be self-contained (stdlib + the bundled beancount compat shim); anything heavier needs a native Rust plugin. Adds a "Referencing a Python Plugin" + "Plugin Sandbox" section to docs/reference/plugins.md and a file-path note to docs/migration/from-beancount.md (clarifying that the existing auto_accounts example works because it resolves to a native plugin, not Python). Co-Authored-By: Claude Opus 4.8 <[email protected]> * refactor(loader): reject module-name plugins up front; address review Follow-up to the review on #1435. Instead of running the plugin and relabeling the failure by name-shape, detect a bare module-name reference *before* invoking the runtime: - Correctness (#1): the old error-path relabel discarded the real error `e` for any dotted/non-.py name — masking genuine failures such as a corrupt runtime download (`PythonRuntime::new()` fails before module discovery). Now module names are rejected up front, so the `Err(e)` arm only fires for real plugin files and surfaces `e` verbatim (E8002). - Altitude (#2): no runtime is downloaded/compiled (and no "10-100x slower" warning printed) for a request that is rejectable from the name alone. - Reuse/consistency (#3): both E8004 sites now share `module_ref_message`, so the "not supported by module name; reference the file directly" guidance is identical everywhere. - Discriminator (#4): one `is_python_module_name` helper using `eq_ignore_ascii_case`, not the pre-lowercased `ext` (fixes a latent case-sensitivity coupling). - Docs (#5): document E8002/E8004/E8005 in docs/reference/errors.md. - Cleanup (#6,#7): static example path (drops the dead `unwrap_or` and the `./.py` trailing-dot edge); drop the redundant `is_python_available()` guard (`suggest_module_path` already handles a missing interpreter). fmt + clippy (-D warnings, python-plugins) clean; loader suite 64/64. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(loader): recognize forward-slash plugin paths on Windows + unit tests Addresses the Copilot review note: is_python_module_name checked only std::path::MAIN_SEPARATOR (`\` on Windows), so a forward-slash file ref like "plugins/foo" could be misclassified as a module name there. Check both `/` and the platform separator. Adds direct unit tests for is_python_module_name (module vs .py vs path-separated vs existing-file, case-insensitive ext) and module_ref_message (both the resolved-path and fallback branches — also covering the line codecov flagged). Co-Authored-By: Claude Opus 4.8 <[email protected]> --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
This was referenced Jul 1, 2026
robcohen
added a commit
that referenced
this pull request
Nov 27, 2026
The parse-error harness compares syntax errors; this compares what rledger and beancount.loader.load_file make of a well-formed ledger after a FULL load: booking under every method, interpolation, prices, tolerances and rounding, pads and balance assertions, options and includes, plugins. - crates/rustledger-loader/examples/semantic_snapshot.rs: rledger side of pta-standards ptadiff semantic protocol (ptadiff-snapshot/1). Loads through Loader::load and process as rledger check does, every field read from the function that owns it. - rustledger_booking::account_balances (+ RealizeError): the realization the balance reports print, moved out of the CLI so the snapshot reads the same one; the CLI wrapper calls it. - scripts/compat-semantic-parity.py + tests/baselines/semantic-parity.manifest: pinned 10k generated ledgers + the compat corpus; per-category and per-deviation counts and every mismatching ledger pinned; --check fails on regressions, --update ratchets. - scripts/semantic_parity_hooks.py: rledger deliberate differences as data, each pointing at docs/reference/compatibility.md (two new sections: plugins in included files, currency_accounts posting order; #5 extended for custom amounts). - compat.yml: Semantic parity job. 97.7% of judged ledgers match; the rest is clustered into 16 categories. Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen
added a commit
that referenced
this pull request
Nov 27, 2026
… CI (#3071) * feat(compat): semantic differential against beancount 3.2.3, gated in CI The parse-error harness compares syntax errors; this compares what rledger and beancount.loader.load_file make of a well-formed ledger after a FULL load: booking under every method, interpolation, prices, tolerances and rounding, pads and balance assertions, options and includes, plugins. - crates/rustledger-loader/examples/semantic_snapshot.rs: rledger side of pta-standards ptadiff semantic protocol (ptadiff-snapshot/1). Loads through Loader::load and process as rledger check does, every field read from the function that owns it. - rustledger_booking::account_balances (+ RealizeError): the realization the balance reports print, moved out of the CLI so the snapshot reads the same one; the CLI wrapper calls it. - scripts/compat-semantic-parity.py + tests/baselines/semantic-parity.manifest: pinned 10k generated ledgers + the compat corpus; per-category and per-deviation counts and every mismatching ledger pinned; --check fails on regressions, --update ratchets. - scripts/semantic_parity_hooks.py: rledger deliberate differences as data, each pointing at docs/reference/compatibility.md (two new sections: plugins in included files, currency_accounts posting order; #5 extended for custom amounts). - compat.yml: Semantic parity job. 97.7% of judged ledgers match; the rest is clustered into 16 categories. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(compat): pin the semantic manifest in a venv with beancount alone, as CI runs it A third-party plugin the oracle cannot import leaves a ledger unjudged; the first pin came from a venv that had some installed. Co-Authored-By: Claude Opus 5.5 <[email protected]> * chore(compat): pin ptadiff to pta-standards main (rustledger/pta-standards#77) The tooling/differential tree is identical to the feature-branch commit it replaces, so no count changes. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
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.
Summary
Add 10 integration tests covering all major loader functionality:
test_load_simple_file: Basic file loading with optionstest_load_with_include: Include file resolutiontest_load_include_cycle_detection: Cycle detection in includestest_load_missing_include: Graceful handling of missing includestest_load_with_plugins: Plugin directive collectiontest_load_with_parse_errors: Error recovery and collectiontest_load_nonexistent_file: IO error handlingtest_loader_reuse: Loader instance behaviortest_source_map_line_lookup: Source mapping for errorstest_duplicate_include_ignored: Deduplication of includesIncludes 8 test fixture files for various scenarios.
Test plan
cargo clippypasses