Skip to content

refactor(plugin-types): typed PriceAnnotationView for exhaustive matching (Phase 0c of #992 plan) - #999

Merged
robcohen merged 4 commits into
mainfrom
refactor/plugin-types-price-annotation-enum
May 5, 2026
Merged

robcohen merged 4 commits into
mainfrom
refactor/plugin-types-price-annotation-enum

Conversation

@robcohen

@robcohen robcohen commented May 5, 2026

Copy link
Copy Markdown
Member

Phase 0c of the plan from #992. Defense-in-depth follow-up to #997.

Why

PR #997 fixed issue #992 (implicit_prices plugin emitting `@@` total amounts as per-unit prices) by adding explicit `is_total` handling. But the type system didn't catch the original bug — the consumer just ignored the `is_total: bool` field and the compiler had no opinion.

This PR adds the type-safety lever: a typed `PriceAnnotationView` enum that forces exhaustive matching at consumer sites. New code that needs to distinguish per-unit from total `MUST` use `view()`, and missing match arms become compile errors.

Approach: view enum, not full conversion

Two options were on the table:

  1. Convert `PriceAnnotationData` itself from struct to enum.
  2. Keep the struct (it's the wire format), add a `view()` enum accessor.

Option 1 would break WASM plugin wire-format compatibility and force ~12 consumer sites to update mechanically. Option 2 gets the same compile-time safety where it matters (new code can opt in) without touching the wire format or existing consumers. Chose option 2.

API

```rust
pub enum PriceAnnotationView<'a> {
Unit(&'a AmountData),
Total(&'a AmountData),
UnitIncomplete { number: Option<&'a str>, currency: Option<&'a str> },
TotalIncomplete { number: Option<&'a str>, currency: Option<&'a str> },
}

impl PriceAnnotationData {
pub fn view(&self) -> PriceAnnotationView<'_> { ... }
}
```

The struct's `is_total`/`amount`/`number`/`currency` fields and serialization are unchanged.

Updated `implicit_prices` to use the view

The plugin code from #997 now matches on `view()`:

```rust
match posting.price.as_ref().map(PriceAnnotationData::view) {
Some(PriceAnnotationView::Unit(amount)) => { /* per-unit / },
Some(PriceAnnotationView::Total(amount)) => { /
divide by units */ },
Some(PriceAnnotationView::UnitIncomplete | TotalIncomplete) | None => ...,
}
```

The pre-#997 version of this code — which read `.amount` and ignored `.is_total` — wouldn't compile against the view enum. The bug class is closed at the type level for any consumer that opts in to `view()`.

Tests

All 5 implicit_prices regression tests from #997 still pass (including the #992 reproducer). No new tests — this is a structural refactor, not a behavior change.

Stacking

This PR is stacked on #997. Merge #997 first.

Related

🤖 Generated with Claude Code

@robcohen
robcohen requested a review from a team as a code owner May 5, 2026 12:59
Copilot AI review requested due to automatic review settings May 5, 2026 12:59
@github-actions

github-actions Bot commented May 5, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 30.5ms ± 1.1ms 21.8 MB
beancount 917.9ms ± 8.2ms 50.4 MB
Comparison 30.1x faster 2.3x less

vs main branch (2026-05-05)

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

@codecov

codecov Bot commented May 5, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 64.00000% with 9 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-plugin-types/src/lib.rs 38.46% 8 Missing ⚠️
...edger-plugin/src/native/plugins/implicit_prices.rs 91.66% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented May 5, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR tightens implicit-price handling around issue #992 by introducing a typed PriceAnnotationView API and routing implicit-price extraction through shared core logic, while keeping the plugin wire format stable.

Changes:

  • Adds PriceAnnotationView plus PriceAnnotationData::view() so plugin-side consumers can distinguish @ vs @@ via exhaustive matching.
  • Centralizes per-unit implicit-price extraction in rustledger_core::extract_per_unit_price and updates both the query path and native implicit_prices plugin to use it.
  • Expands implicit_prices regression coverage with stricter plugin-level assertions.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
crates/rustledger-query/src/price.rs Refactors query-side implicit price extraction to use the shared core helper.
crates/rustledger-plugin/tests/native_plugins_test.rs Adds stricter implicit_prices test helpers and regression cases.
crates/rustledger-plugin/src/native/plugins/implicit_prices.rs Updates the native plugin to use the typed view and shared extraction logic.
crates/rustledger-plugin-types/src/lib.rs Introduces PriceAnnotationView and the view() accessor on PriceAnnotationData.
crates/rustledger-core/src/lib.rs Exposes the new shared implicit-price module/helper.
crates/rustledger-core/src/implicit_prices.rs Adds shared implicit-price extraction logic and unit tests.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread crates/rustledger-query/src/price.rs Resolved
@robcohen
robcohen force-pushed the refactor/plugin-types-price-annotation-enum branch from 1458246 to e3c1de5 Compare May 5, 2026 16:30
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
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]>
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
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]>
robcohen and others added 2 commits May 5, 2026 12:45
…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]>
…lure

`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.
@robcohen
robcohen force-pushed the refactor/plugin-types-price-annotation-enum branch from e3c1de5 to a90cd30 Compare May 5, 2026 17:51
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 and others added 2 commits May 5, 2026 13:50
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]>
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
robcohen merged commit 53a99a5 into main May 5, 2026
32 checks passed
@robcohen
robcohen deleted the refactor/plugin-types-price-annotation-enum branch May 5, 2026 19:07
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants