Repository navigation
fix(plugin): correct @@ total-price handling and double-emit bug (closes #992) - #997
Merged
Merged
Conversation
#992) Two bugs in `implicit_prices` plugin, root cause: parallel-implementations divergence between the BQL query path and the plugin path. The query path was correct; the plugin had its own less-careful reimplementation. ## Bug 1: `@@` total amounts emitted as per-unit prices For `Assets:Insurance -27,204.53 BAM @@ 15,152.07 EUR`, the plugin emitted `1 BAM = 15,152.07 EUR` instead of `1 BAM = 0.557 EUR`. Off by a factor of `units.abs()`. The plugin read `posting.price.amount` directly without checking the `is_total` field on `PriceAnnotationData`. ## Bug 2: Plugin double-emitted prices on postings with both `@` and `{cost}` A posting like `5 ABC {1.25 EUR} @ 1.40 EUR` produced two `Price` directives (1.40 from annotation + 1.25 from cost) — back-to-back, no `else`. Should be one (annotation wins). ## Fix: shared helper in rustledger-core New `rustledger_core::extract_per_unit_price` — pure function over primitives (Decimals, bools, Options) that encodes the priority rule once: 1. Price annotation (with @@-to-per-unit conversion via `total / units.abs()`) 2. Cost spec (`number_per` direct, `number_total` divided by units) 3. None Both `rustledger_query::price::add_implicit_prices_from_transaction` AND `rustledger_plugin::native::plugins::implicit_prices::ImplicitPricesPlugin::process` now call the helper. Single source of truth eliminates the divergence by construction. The helper uses primitives (not rich types) because the two callers have different transaction representations: query uses `core::Transaction` with rust_decimal numbers, plugin uses `plugin_types::TransactionData` with String numbers (for serialization stability). Each caller extracts its primitives, calls the helper, and emits in its native format. ## Tests 13 new unit tests on the helper itself (`rustledger-core/src/implicit_prices.rs`): - @ unit annotation, @@ total annotation (incl. the #992 reproducer) - Tie-breaking when annotation+cost both present - Zero-units edge cases - Falls-through behavior for incomplete annotations 5 new plugin-level tests replacing the old single "(partial)" test: - test_implicit_prices_from_cost (strict assert_eq, was assert!(>= 1)) - test_implicit_prices_from_unit_annotation (@ path) - test_implicit_prices_from_total_annotation_issue_992 (the #992 regression) - test_implicit_prices_annotation_and_cost_emits_one_not_two - test_implicit_prices_emits_nothing_for_plain_transfer The new tests all use a strict `assert_eq!` on the `Vec<(currency, number, quote_currency)>` returned by a new `implicit_prices_emitted` helper. The old `assert!(price_count >= 1)` shape silently masked both bugs because it accepted both correct and over-emission. ## Verification - 13 new helper tests pass - 5 new plugin tests pass (including the #992 reproducer) - Existing query-path tests (14) all still pass - Full workspace test suite green - Clippy clean, fmt clean Closes #992. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Contributor
📊 Benchmark Results
vs main branch (2026-05-05)
What do these numbers mean?
|
Contributor
There was a problem hiding this comment.
Pull request overview
This PR centralizes implicit-price extraction in rustledger-core so the query path and native implicit_prices plugin share one implementation, addressing the @@ total-price regression from issue #992 and the plugin’s double-emission bug.
Changes:
- Added
rustledger_core::extract_per_unit_priceand re-exported it fromrustledger-core. - Refactored both the query price database and native
implicit_pricesplugin to call the shared helper. - Expanded plugin/core tests around implicit price extraction and the #992 regression scenarios.
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
crates/rustledger-query/src/price.rs |
Swaps query-side implicit price extraction to the shared core helper and updates quote-currency selection logic around it. |
crates/rustledger-plugin/tests/native_plugins_test.rs |
Replaces the older loose implicit-prices test with stricter plugin-focused regression cases and a shared assertion helper. |
crates/rustledger-plugin/src/native/plugins/implicit_prices.rs |
Refactors the native plugin to parse posting primitives, call the shared helper, and emit a single derived price per posting. |
crates/rustledger-core/src/lib.rs |
Exposes the new implicit-prices module and re-exports the shared helper. |
crates/rustledger-core/src/implicit_prices.rs |
Adds the shared extraction helper plus focused unit tests for annotation/cost precedence and total-price handling. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Contributor
|
| Metric | Result |
|---|---|
| Check Compatibility | 99% |
| BQL Compatibility | 96% |
| Full AST Match | 99% |
| Total Files | 783 |
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
This was referenced May 5, 2026
Addresses 4 of 4 inline comments from Copilot's review of PR #997. ## Real bug: currency-source mismatch on @@-fall-through-to-cost Pre-fix, when an `@@` total annotation was unusable (e.g. zero units), `extract_per_unit_price` correctly fell through to the cost spec for the per-unit value — but the calling code unconditionally picked the quote currency from `annotation_currency.or(cost_currency)`. Result: `0 ABC {50 USD} @@ 100 EUR` emitted `(50, EUR)` instead of `(50, USD)`. Fix: helper now returns `(Decimal, ImplicitPriceSource)` where `ImplicitPriceSource` is an enum {Annotation, Cost} indicating which input branch produced the value. Both callers (query path and plugin) match on the source and pair the quote currency with the same branch. This couples the two decisions (number-source and currency-source) at the type level, so the same class of bug can't reappear. ## Test isolation: implicit_prices_emitted no longer relies on filename Pre-fix the helper filtered output directives by `filename: None` to identify plugin-generated ones. But the test fixture's `make_price` helper also sets `filename: None`, so any test with an explicit input price would have miscounted. Fix: helper now takes both `input` and `output`, computes the multiset difference. Whatever's in output but not input is the plugin's contribution. New test `test_implicit_prices_emitted_excludes_input_price_directives` pins this property. ## New: cost.number_total regression test Pre-fix the plugin handled `cost.number_total` (the `{{TOTAL CURRENCY}}` syntax) but no test exercised the string-parsing branch. New test `test_implicit_prices_from_cost_total` covers it. ## Plugin: tie annotation_currency to successful number parse Pre-fix the plugin captured `annotation_currency` even when `Decimal::from_str` on the annotation amount failed. If the helper fell back to a cost-derived value, the caller would still emit the annotation's currency. Fix: only set `amount_currency` when `amount_decimal.is_some()`. ## Verification - 5 → 8 implicit_prices tests (3 new) - 13 → 13 helper unit tests (signatures updated for tuple return) - Full workspace test suite green - Clippy clean, fmt clean Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen
added a commit
that referenced
this pull request
May 5, 2026
…matching Phase 0c of the plugin-testing-quality plan. Defense-in-depth follow-up to #997 which fixed issue #992 (implicit_prices plugin emitted @@ totals as per-unit prices because nothing forced the consumer to read is_total). Keep `PriceAnnotationData` as a flat struct (it's the wire format for WASM plugins — converting to an enum would break serialization compatibility for too little gain). Instead, add a typed-enum view accessor: pub enum PriceAnnotationView<'a> { Unit(&'a AmountData), Total(&'a AmountData), UnitIncomplete { number, currency }, TotalIncomplete { number, currency }, } impl PriceAnnotationData { pub fn view(&self) -> PriceAnnotationView<'_> { ... } } New consumers that need to handle per-unit-vs-total differently MUST match on `view()` — exhaustive matching is enforced by the compiler. The original bug (consumer ignores `is_total`, treats `@@` as `@`) is now a compile error if the consumer uses `view()`. Converting PriceAnnotationData itself to an enum would: 1. Break the WASM plugin wire format (serialization stability matters for external plugins built against rustledger-plugin-types). 2. Force every existing consumer (12+ sites across 6 files) to be updated mechanically — a lot of churn for the same compile-time safety the view enum provides. The view enum gives the type-safety property where it matters (new code, opt-in) without touching the wire format or existing consumers. The plugin from #997 now matches on `view()` directly instead of manually pulling `is_total` out: match posting.price.as_ref().map(PriceAnnotationData::view) { Some(PriceAnnotationView::Unit(amount)) => { ... }, Some(PriceAnnotationView::Total(amount)) => { /* divide */ ... }, Some(PriceAnnotationView::UnitIncomplete | TotalIncomplete) | None => ..., } Same behavior, but if someone later adds a fifth annotation kind, the `match` is now non-exhaustive and the compiler refuses to build. The pre-#997 version of this code (which read `.amount` and ignored `.is_total`) would not compile against the view enum at all. All 5 implicit_prices regression tests from #997 still pass. No new tests — this is a structural refactor, not a behavior change. - #992 — original bug - #997 — Phase 0a fix - #998 — Phase 0b audit (priorities for Phase 1+) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen
added a commit
that referenced
this pull request
May 5, 2026
…Phase 5 of #992 plan) Standing policy and CI gate for the bug class that produced #992. ## CONTRIBUTING.md additions New "Plugin testing requirements" section codifies: 1. Test matrix, not "happy path" — cover every input variant 2. Strict count assertions (`assert_eq!`, never `>=`) — `>= N` accepts both correct emission AND over-emission, which is exactly how #992 shipped (the original test was `assert!(price_count >= 1)`) 3. No `(partial)` test ports — port the whole upstream test or document each skipped case 4. Differential coverage where applicable — drop a fixture under `tests/compatibility/files/plugin/<name>/` and the harness from PR #1000 picks it up automatically 5. Type-driven exhaustive matching — use `match` on enum-shaped inputs, don't manually extract a discriminator For numeric plugins specifically: at least one proptest case covering an algebraic invariant (round-trip, sum-invariance, etc.). ## scripts/check-plugin-test-quality.sh CI lint that enforces the two most mechanical policies: - Weak count assertions (`assert!(... >= N)` / `> N`). - `(partial)` test port labels. Has an explicit allowlist mechanism: prefix the assertion with `// allow weak-count: <reason>` to opt out (e.g. registry-shape tests where the count grows with each plugin addition). awk-based block parsing so it can read up to 5 lines of leading comments to find the allow annotation. ## CI integration New `Plugin Test Quality` job in .github/workflows/ci.yml runs the script on every PR. Sits next to the existing Unsafe Invariant check. Fast (sub-second), no compilation dependency. ## Test file allowlist The single legitimate `assert!(... >= N)` in the test file is the registry-list test (`assert!(plugins.len() >= 13)`) — count grows as plugins are added. Annotated with `// allow weak-count: registry-shape test` per the new policy. ## Stacked on #997 This PR depends on #997 (Phase 0a fix) — that PR rewrites the implicit_prices test, removing the `(partial)` label that would otherwise fail policy 2. After #997 merges, the rebase is clean. ## Related - #992 — the bug that motivated the plan - #997 — Phase 0a fix - #998 — Phase 0b audit (Phase 1 backlog) - #999 — Phase 0c type-safety view enum - #1000 — Phase 2 differential harness Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Addresses all four review findings on PR #997: 1. **Structural fix for the currency-pairing bug** (was: caller-side match on ImplicitPriceSource). The helper is now generic over the currency type T and takes annotation/cost descriptors with the currency embedded: fn extract_per_unit_price<T>( units_number: Decimal, annotation: Option<(bool, Decimal, T)>, cost: Option<(Option<Decimal>, Option<Decimal>, T)>, ) -> Option<(Decimal, T)> The returned (Decimal, T) is paired by construction — there is no way for a caller to accidentally re-pair the value with the wrong currency. ImplicitPriceSource is removed (it existed only to fix the bug at the call site, which is now structurally impossible). 2. **Query-path regression test** for the zero-units fall-through currency-pairing case. Mirrors the plugin-side test that already existed. Pins the behavior on the query side so a future caller-side refactor cannot silently regress it. 3. **Doc clarification on per-vs-total cost tie-break**. The resolution-order list now explicitly states number_per takes precedence over number_total within the cost-spec branch (matching Python beancount). 4. **Doc clarification on the @@ divide step** (moot, as ImplicitPriceSource is gone, but the helper docs now describe the @ vs @@ handling explicitly). Net effect on call sites: the plugin and query callers each shrink by ~30 lines (no more annotation_currency / cost_currency tracking, no more match on a discriminator). All 13 helper unit tests + 8 plugin tests + 6 query implicit-price tests pass. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Three minor items from second deep review of #997: 1. Plugin caller: rename inner closure parameters to avoid shadowing the outer `annotation` / `cost` bindings (`|annotation|` -> `|a|`, `|cost|` -> `|c|`). Matches the query caller's existing style. 2. Helper docstring: in beancount terminology "amount" already means "(number, currency)", so the phrase "if both an amount and a currency are present" reads circularly. Switched to "a parsed number and currency". 3. Module doc no longer self-references PR #997 by number — once merged, the bug-class explanation reads more naturally as "making mismatched (number, currency) pairs impossible to construct" without the meta-reference to its own review. No code changes. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen
enabled auto-merge (squash)
May 5, 2026 17:21
robcohen
added a commit
that referenced
this pull request
May 5, 2026
…Phase 5 of #992 plan) Standing policy and CI gate for the bug class that produced #992. ## CONTRIBUTING.md additions New "Plugin testing requirements" section codifies: 1. Test matrix, not "happy path" — cover every input variant 2. Strict count assertions (`assert_eq!`, never `>=`) — `>= N` accepts both correct emission AND over-emission, which is exactly how #992 shipped (the original test was `assert!(price_count >= 1)`) 3. No `(partial)` test ports — port the whole upstream test or document each skipped case 4. Differential coverage where applicable — drop a fixture under `tests/compatibility/files/plugin/<name>/` and the harness from PR #1000 picks it up automatically 5. Type-driven exhaustive matching — use `match` on enum-shaped inputs, don't manually extract a discriminator For numeric plugins specifically: at least one proptest case covering an algebraic invariant (round-trip, sum-invariance, etc.). ## scripts/check-plugin-test-quality.sh CI lint that enforces the two most mechanical policies: - Weak count assertions (`assert!(... >= N)` / `> N`). - `(partial)` test port labels. Has an explicit allowlist mechanism: prefix the assertion with `// allow weak-count: <reason>` to opt out (e.g. registry-shape tests where the count grows with each plugin addition). awk-based block parsing so it can read up to 5 lines of leading comments to find the allow annotation. ## CI integration New `Plugin Test Quality` job in .github/workflows/ci.yml runs the script on every PR. Sits next to the existing Unsafe Invariant check. Fast (sub-second), no compilation dependency. ## Test file allowlist The single legitimate `assert!(... >= N)` in the test file is the registry-list test (`assert!(plugins.len() >= 13)`) — count grows as plugins are added. Annotated with `// allow weak-count: registry-shape test` per the new policy. ## Stacked on #997 This PR depends on #997 (Phase 0a fix) — that PR rewrites the implicit_prices test, removing the `(partial)` label that would otherwise fail policy 2. After #997 merges, the rebase is clean. ## Related - #992 — the bug that motivated the plan - #997 — Phase 0a fix - #998 — Phase 0b audit (Phase 1 backlog) - #999 — Phase 0c type-safety view enum - #1000 — Phase 2 differential harness Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen
added a commit
that referenced
this pull request
May 5, 2026
…matching Phase 0c of the plugin-testing-quality plan. Defense-in-depth follow-up to #997 which fixed issue #992 (implicit_prices plugin emitted @@ totals as per-unit prices because nothing forced the consumer to read is_total). Keep `PriceAnnotationData` as a flat struct (it's the wire format for WASM plugins — converting to an enum would break serialization compatibility for too little gain). Instead, add a typed-enum view accessor: pub enum PriceAnnotationView<'a> { Unit(&'a AmountData), Total(&'a AmountData), UnitIncomplete { number, currency }, TotalIncomplete { number, currency }, } impl PriceAnnotationData { pub fn view(&self) -> PriceAnnotationView<'_> { ... } } New consumers that need to handle per-unit-vs-total differently MUST match on `view()` — exhaustive matching is enforced by the compiler. The original bug (consumer ignores `is_total`, treats `@@` as `@`) is now a compile error if the consumer uses `view()`. Converting PriceAnnotationData itself to an enum would: 1. Break the WASM plugin wire format (serialization stability matters for external plugins built against rustledger-plugin-types). 2. Force every existing consumer (12+ sites across 6 files) to be updated mechanically — a lot of churn for the same compile-time safety the view enum provides. The view enum gives the type-safety property where it matters (new code, opt-in) without touching the wire format or existing consumers. The plugin from #997 now matches on `view()` directly instead of manually pulling `is_total` out: match posting.price.as_ref().map(PriceAnnotationData::view) { Some(PriceAnnotationView::Unit(amount)) => { ... }, Some(PriceAnnotationView::Total(amount)) => { /* divide */ ... }, Some(PriceAnnotationView::UnitIncomplete | TotalIncomplete) | None => ..., } Same behavior, but if someone later adds a fifth annotation kind, the `match` is now non-exhaustive and the compiler refuses to build. The pre-#997 version of this code (which read `.amount` and ignored `.is_total`) would not compile against the view enum at all. All 5 implicit_prices regression tests from #997 still pass. No new tests — this is a structural refactor, not a behavior change. - #992 — original bug - #997 — Phase 0a fix - #998 — Phase 0b audit (priorities for Phase 1+) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen
added a commit
that referenced
this pull request
May 5, 2026
… 5 of #992 plan) (#1001) * ci(plugin-tests): codify plugin-test-quality policies + lint script (Phase 5 of #992 plan) Standing policy and CI gate for the bug class that produced #992. ## CONTRIBUTING.md additions New "Plugin testing requirements" section codifies: 1. Test matrix, not "happy path" — cover every input variant 2. Strict count assertions (`assert_eq!`, never `>=`) — `>= N` accepts both correct emission AND over-emission, which is exactly how #992 shipped (the original test was `assert!(price_count >= 1)`) 3. No `(partial)` test ports — port the whole upstream test or document each skipped case 4. Differential coverage where applicable — drop a fixture under `tests/compatibility/files/plugin/<name>/` and the harness from PR #1000 picks it up automatically 5. Type-driven exhaustive matching — use `match` on enum-shaped inputs, don't manually extract a discriminator For numeric plugins specifically: at least one proptest case covering an algebraic invariant (round-trip, sum-invariance, etc.). ## scripts/check-plugin-test-quality.sh CI lint that enforces the two most mechanical policies: - Weak count assertions (`assert!(... >= N)` / `> N`). - `(partial)` test port labels. Has an explicit allowlist mechanism: prefix the assertion with `// allow weak-count: <reason>` to opt out (e.g. registry-shape tests where the count grows with each plugin addition). awk-based block parsing so it can read up to 5 lines of leading comments to find the allow annotation. ## CI integration New `Plugin Test Quality` job in .github/workflows/ci.yml runs the script on every PR. Sits next to the existing Unsafe Invariant check. Fast (sub-second), no compilation dependency. ## Test file allowlist The single legitimate `assert!(... >= N)` in the test file is the registry-list test (`assert!(plugins.len() >= 13)`) — count grows as plugins are added. Annotated with `// allow weak-count: registry-shape test` per the new policy. ## Stacked on #997 This PR depends on #997 (Phase 0a fix) — that PR rewrites the implicit_prices test, removing the `(partial)` label that would otherwise fail policy 2. After #997 merges, the rebase is clean. ## Related - #992 — the bug that motivated the plan - #997 — Phase 0a fix - #998 — Phase 0b audit (Phase 1 backlog) - #999 — Phase 0c type-safety view enum - #1000 — Phase 2 differential harness Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(ci): address Copilot review on plugin-test-quality (#1001) Three classes of fixes from Copilot review: 1. Lint script regex was too narrow: - Caught x.count() >= N only with a leading space before the operator (missed x.count()>=N) - Missed precomputed counts like assert!(price_count >= 1) — which was the EXACT shape of the #992 bug. The new regex matches three forms: method calls, no-whitespace variants, and precomputed *_count/*_len/*_size (or bare count/len/size) idents. 2. Lint script awk block parser dropped violations when multiple matches fell inside the same grep -B 5 context window. Replaced with a bash loop that does an explicit per-match sed lookback. Also covers the new precomputed-count pattern, which the awk block couldn't have matched anyway. 3. CI gate gap: plugin-test-quality ran but wasn't in the build aggregator needs list, so branch protection enforcing only build would let policy violations merge. Added it to needs, added an explicit success check, and removed its should_build gate so it also runs on docs-only / policy-only PRs (which are precisely the PRs that touch the lint script). Also corrected two CONTRIBUTING.md inaccuracies: - PriceAnnotationData::view() example referred to an API that doesn't exist on this branch (it is introduced in PR #999). Reworded so the rule is API-agnostic and the example is flagged as forward-looking. - Mutation-survival ≤ 10% claim said CI enforces — currently CI runs cargo mutants and warns; the blocking gate is Phase 3 work. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(ci): address all items from second deep review of #1001 Seven items, fixed in one commit since they all touch the same lint script + its policy doc: 1. **No more `2>/dev/null || true`** (the blocking item). Per `feedback_no_error_swallowing.md`, this idiom previously caused two npm releases to silently fail. The script now: - Hard-fails up front if `TESTS_DIR` doesn't exist (was: silent pass, because grep + missing dir + `|| true` reported "OK") - Wraps grep in a `grep_or_die` helper that distinguishes exit 1 ("no matches", fine) from exit 2+ ("real error", abort with a descriptive message) 2. **Pre-push hook wired in**. Script's docstring claimed it ran as a pre-push step but no `.pre-commit-config.yaml` entry existed. Added one — sub-second cost, runs alongside the existing cargo-check + unsafe-invariant pre-push hooks. 3. **Lint coverage extended to two more weak-assertion shapes** that are semantically identical to the #992 bug: - `assert_ne!(x.len(), 0)` (and precomputed-count variants) - `assert!(!x.is_empty())` Combined with the existing `>=`/`>` shape, the lint now catches all three forms of "accept 1 OR 100 emissions". 4. **`(partial)` lint tightened to specific shape**. Was a broad `(partial)` substring match — would false-positive on unrelated comments like `(partial overlap with foo)`. Now matches the historical bad pattern `Converted from … (partial)` only, with `// allow partial: <reason>` as an opt-out for the rare false positive. 5. **Robust path parsing**. Replaced `${match%%:*}` parameter expansion (which assumed no `:` in file paths) with `IFS=: read -r file lineno _` which is equally portable and handles any path correctly. 6. **PR description updated** (separate, via `gh pr edit`) — the old description still claimed "awk-based block parsing" which was replaced with bash-loop + sed in the previous round. 7. **Removed redundant `[[:space:]]*`** after `[^)]*` in the regex (the latter already matches whitespace greedily). Knock-on test changes: extending the lint to catch `assert!(!output.errors.is_empty(), ...)` flagged two existing sites in `native_plugins_test.rs`: - `test_no_unused_warns_on_unused_account` — tightened to `assert_eq!(output.errors.len(), 1, "exactly one error for the single unused account")`. The follow-up `iter().any(...)` check was simplified to `errors[0].message.contains(...)` since we know the count exactly now. - `test_zerosum_requires_config` — same tightening pattern. Both tests still pass (verified with full `cargo test -p rustledger-plugin --test native_plugins_test`: 88 passed, 0 failed). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * test(ci): self-test the plugin-test-quality lint + close two coverage gaps Three follow-up items from the third deep review of #1001: 1. **Self-test for the lint script** (the most important addition). The regexes are now non-trivial enough that a typo or accidental pattern deletion would silently disable detection. A new `scripts/test-plugin-test-quality.sh` generates synthetic test files in a temp dir, points the lint at them via `TESTS_DIR`, and asserts that each known-bad shape is caught and each known-clean shape is not. 21 cases total covering: all four weak-assert shapes, the allow-annotation opt-out (with reason and without), positive shapes that must NOT fire, the partial-port shape and its false-positive guard, and the missing-`TESTS_DIR` hard-fail regression test. Wired into the existing `Plugin Test Quality` CI job as a pre-step so a broken lint script fails CI before the lint itself runs. Required a small change to the lint script: `TESTS_DIR` is now read from the env (defaulting to the real tests dir) so the self-test can override it. 2. **Allow annotations now require a non-empty reason**. Pre-fix, `// allow weak-count:` (no reason) would silently bypass the lint. The whole point of the opt-out is to force the author to articulate WHY a weak assertion is acceptable. Tightened `has_allow_above` from `grep -q "$annotation"` to `grep -qE "${annotation}:[[:space:]]*\S"` — annotation followed by `:` followed by at least one non-whitespace character. The existing `// allow weak-count: registry-shape test — ...` annotation in `test_registry_list_all` still passes (verified). 3. **Fourth weak-assert shape caught**: `assert!(x.len() != 0)` / `assert!(price_count != 0)` — semantically identical to shape B (`assert_ne!`) but written as an inequality. Doesn't exist in the codebase today but the self-test pins it so a future contributor can't accidentally introduce the gap. 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 5, 2026
…#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]>
robcohen
added a commit
that referenced
this pull request
May 5, 2026
…hing (Phase 0c of #992 plan) (#999) * refactor(plugin-types): add typed PriceAnnotationView for exhaustive matching Phase 0c of the plugin-testing-quality plan. Defense-in-depth follow-up to #997 which fixed issue #992 (implicit_prices plugin emitted @@ totals as per-unit prices because nothing forced the consumer to read is_total). Keep `PriceAnnotationData` as a flat struct (it's the wire format for WASM plugins — converting to an enum would break serialization compatibility for too little gain). Instead, add a typed-enum view accessor: pub enum PriceAnnotationView<'a> { Unit(&'a AmountData), Total(&'a AmountData), UnitIncomplete { number, currency }, TotalIncomplete { number, currency }, } impl PriceAnnotationData { pub fn view(&self) -> PriceAnnotationView<'_> { ... } } New consumers that need to handle per-unit-vs-total differently MUST match on `view()` — exhaustive matching is enforced by the compiler. The original bug (consumer ignores `is_total`, treats `@@` as `@`) is now a compile error if the consumer uses `view()`. Converting PriceAnnotationData itself to an enum would: 1. Break the WASM plugin wire format (serialization stability matters for external plugins built against rustledger-plugin-types). 2. Force every existing consumer (12+ sites across 6 files) to be updated mechanically — a lot of churn for the same compile-time safety the view enum provides. The view enum gives the type-safety property where it matters (new code, opt-in) without touching the wire format or existing consumers. The plugin from #997 now matches on `view()` directly instead of manually pulling `is_total` out: match posting.price.as_ref().map(PriceAnnotationData::view) { Some(PriceAnnotationView::Unit(amount)) => { ... }, Some(PriceAnnotationView::Total(amount)) => { /* divide */ ... }, Some(PriceAnnotationView::UnitIncomplete | TotalIncomplete) | None => ..., } Same behavior, but if someone later adds a fifth annotation kind, the `match` is now non-exhaustive and the compiler refuses to build. The pre-#997 version of this code (which read `.amount` and ignored `.is_total`) would not compile against the view enum at all. All 5 implicit_prices regression tests from #997 still pass. No new tests — this is a structural refactor, not a behavior change. - #992 — original bug - #997 — Phase 0a fix - #998 — Phase 0b audit (priorities for Phase 1+) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * docs(plugin-types): drop cross-crate doc-link to avoid CI rustdoc failure `rustledger-plugin-types` doesn't depend on `rustledger-core`, so the intra-doc-link `[`rustledger_core::extract_per_unit_price`]` couldn't be resolved. CI rustdoc failed under -D warnings. Replaced with a backtick'd name + parenthetical pointer to where the helper lives. Same information, no broken link. * test(plugin-types): cover all four PriceAnnotationView arms Closes the codecov gap on PR #999 (64% patch coverage flagged the view() function and its incomplete-variant arms). The plugin-level integration tests exercise Unit and Total indirectly through implicit_prices, but UnitIncomplete and TotalIncomplete had no direct coverage. A future refactor of the underlying (is_total, amount, number, currency) field layout could silently change the view() dispatch without any test catching it. 9 new tests in `crates/rustledger-plugin-types/src/lib.rs::tests`: - view_unit_complete (`@ AMOUNT`) - view_total_complete (`@@ AMOUNT`) - view_unit_incomplete_number_only (`@ NUMBER`) - view_unit_incomplete_currency_only (`@ CURRENCY`) - view_unit_incomplete_neither (bare `@`) - view_total_incomplete_number_only (`@@ NUMBER`) - view_total_incomplete_currency_only (`@@ CURRENCY`) - view_total_incomplete_neither (bare `@@`) - view_amount_present_takes_priority_over_number_currency_fields (pins precedence: `amount` wins over loose number/currency fields) Each test exhaustively matches on the result so adding a new variant to PriceAnnotationView would be a compile error in the test, not a runtime miss. 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 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]>
This was referenced May 6, 2026
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.
Closes #992. Phase 0a of the plugin-testing-quality plan.
Bugs
The
implicit_pricesplugin had two bugs, both from being a separateimplementation of the same logic that already exists in
rustledger-query::price::add_implicit_prices_from_transaction:@@total amounts emitted as per-unit prices. For-27,204.53 BAM @@ 15,152.07 EUR, the plugin emitted1 BAM = 15,152.07 EURinstead of1 BAM = 0.557 EUR. Off by afactor of
units.abs(). The plugin readposting.price.amountdirectly without checking the
is_totalfield onPriceAnnotationData.Double-emit when both
@and{cost}are present. A postinglike
5 ABC {1.25 EUR} @ 1.40 EURproduced twoPricedirectivesinstead of one (annotation should win).
A third bug was caught during review:
@@fall-through. A postinglike
0 ABC {50 USD} @@ 100 EUR(zero units make the@@totalunusable, so the per-unit value falls through to the cost) was
emitted as
(50, EUR)instead of(50, USD)— the value camefrom the cost but the currency was still picked from the dropped
annotation. Affected the query path too.
Fix
New
rustledger_core::extract_per_unit_price<T>— generic helperthat encodes the priority rule once, used by both the BQL query
path AND the native
implicit_pricesplugin. Single source oftruth; divergence impossible by construction.
The helper is generic over the currency type so the two callers can
keep using their own representations (
InternedStrfor the querypath,
Stringfor the plugin's serializable types). The signaturebinds the currency to its value at the type level:
Returning
(Decimal, T)means a caller cannot accidentally re-pairthe per-unit value with the wrong currency — that's bug 3 made
structurally impossible.
Tests
13 unit tests on the helper (
crates/rustledger-core/src/implicit_prices.rs):unit annotations, total annotations, the [Compat]: implicit price is wrong #992 reproducer specifically,
tie-breaks when both annotation and cost present (annotation wins;
within cost,
number_perwins overnumber_total), zero-units edgecases, fall-through behavior for incomplete annotations, and the
currency-pairing fall-through (bug 3).
8 plugin-level tests replacing the old single "(partial)" test.
All use strict
assert_eq!on theVec<(currency, number, quote_currency)>returned by animplicit_prices_emittedhelper(computed as multiset diff
output_prices − input_prices, soexplicit input price directives don't get counted as plugin output):
test_implicit_prices_from_cost—{cost.number_per}pathtest_implicit_prices_from_cost_total—{{cost.number_total}}pathtest_implicit_prices_from_unit_annotation—@pathtest_implicit_prices_from_total_annotation_issue_992— bug 1 regressiontest_implicit_prices_annotation_and_cost_emits_one_not_two— bug 2 regressiontest_implicit_prices_zero_unit_total_falls_through_to_cost_currency— bug 3 regressiontest_implicit_prices_emits_nothing_for_plain_transfertest_implicit_prices_emitted_excludes_input_price_directives— pins themultiset-diff isolation of the test helper itself
15 query-path tests all green, including a new
test_implicit_price_zero_units_total_annotation_uses_cost_currencythat pins bug 3's behavior on the query side independently of the
helper's internals (so a future caller-side refactor cannot silently
regress it).
The old
assert!(price_count >= 1)shape silently masked bothoriginal bugs because it accepted both correct AND over-emission;
all new tests use strict equality.
Why this happened in the first place
This is Phase 0a of a broader plan to prevent the next plugin bug.
See the issue tracking the rest of the work for details on:
is_total: boolto a real enum so consumers musthandle both arms — the type system would have caught Bug 1; refactor(plugin-types): typed PriceAnnotationView for exhaustive matching (Phase 0c of #992 plan) #999)
bean-check, mutation testing, property tests, standing policy)
Verification
-27204.53 BAM @@ 15152.07 EUR)now produces exactly one price:
BAM 0.5569... EUR. Bug 1 fixed.@and{cost}emit exactly one price (theannotation amount). Bug 2 fixed.
@@ X EURwith{Y USD}cost emits(Y, USD). Bug 3 fixed.🤖 Generated with Claude Code