Skip to content

test(plugin): test matrices for forecast, rx_txn, effective_date, box_accrual - #1008

Merged
robcohen merged 4 commits into
mainfrom
feat/transaction-emitter-test-matrices
May 6, 2026
Merged

robcohen merged 4 commits into
mainfrom
feat/transaction-emitter-test-matrices

Conversation

@robcohen

@robcohen robcohen commented May 5, 2026

Copy link
Copy Markdown
Member

test(plugin): test matrices for transaction-emitter plugins

Phase 1 of #992 plan (tracked in #1002). Four Tier-1 plugins each
got integration test matrices replacing minimal happy-path stubs.

Coverage

forecast (2 → 7 tests)

Plugin matches #-flagged transactions with bracketed recurrence
patterns, replicates them at generated dates, strips the bracket.
Matrix covers each interval (DAILY/WEEKLY/MONTHLY) plus the
control words (REPEAT, UNTIL, SKIP) and the "no pattern" passthrough.
Strict equality on count + dates instead of >= N.

rx_txn (2 → 5 tests)

Plugin adds final = "None" and roll = "True" to #rx_txn-tagged
transactions, preserving any pre-existing values. Matrix:

  • tagged → adds both metadata (was: has_final OR has_roll weak
    assertion; now strict on both keys + their default values)
  • untagged → no metadata mutation
  • existing metadata preserved (not overwritten)
  • partial pre-set: only the missing key is filled
  • works alongside other tags

effective_date (2 → 5 tests)

Plugin moves postings to their effective dates via holding accounts.
Matrix covers no-metadata passthrough, future-effective-date (uses
'later' holding), past-effective-date (uses 'earlier' holding),
unconfigured prefix passthrough, and custom config remapping.

box_accrual (2 → 5 tests)

Plugin splits :Capital-Losses postings across years by day count.
Matrix:

  • no synthetic_loan_expiry metadata → unchanged
  • multi-year split → exactly N postings per year, sum preserves
    total exactly (pins the "final segment is remainder" invariant)
  • same-year span → no split
  • no Capital-Losses posting → unchanged
  • multiple Capital-Losses postings → unchanged (plugin only handles
    exactly 1)

Verified

  • 88 → 102 plugin integration tests (+14)
  • scripts/check-plugin-test-quality.sh: OK
  • scripts/test-plugin-test-quality.sh: 28/28
  • cargo clippy -p rustledger-plugin --all-features --all-targets:
    clean

Lint follow-up noted

The existing test_forecast_expands_recurring_transaction had a
weak assert!(txn_count >= 3, ...) shape that the lint missed
because it's multi-line and PAT_A doesn't have a multi-line variant
yet (PAT_B/C/D got their multi-line counterparts in #1005, but
PAT_A's wasn't needed at the time). Tightened to assert_eq!(.count(), 3, ...) here. Adding ML_PAT_A is a small follow-up — the
file-wide refactor wasn't in scope for this PR.

Closes 4 more entries in #1002 (Tier 1: forecast, rx_txn,
effective_date, box_accrual). 7 of 11 Tier 1 plugins now
covered after this PR + the open #1007.

Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]

Phase 1 of #992 plan (tracked in #1002). Four Tier-1 plugins each
got integration test matrices replacing minimal happy-path stubs.

## Coverage

### `forecast` (2 → 7 tests)

Plugin matches `#`-flagged transactions with bracketed recurrence
patterns, replicates them at generated dates, strips the bracket.
Matrix covers each interval (DAILY/WEEKLY/MONTHLY) plus the
control words (REPEAT, UNTIL, SKIP) and the "no pattern" passthrough.
Strict equality on count + dates instead of `>= N`.

### `rx_txn` (2 → 5 tests)

Plugin adds `final = "None"` and `roll = "True"` to `#rx_txn`-tagged
transactions, preserving any pre-existing values. Matrix:
- tagged → adds both metadata (was: `has_final OR has_roll` weak
  assertion; now strict on both keys + their default values)
- untagged → no metadata mutation
- existing metadata preserved (not overwritten)
- partial pre-set: only the missing key is filled
- works alongside other tags

### `effective_date` (2 → 5 tests)

Plugin moves postings to their effective dates via holding accounts.
Matrix covers no-metadata passthrough, future-effective-date (uses
'later' holding), past-effective-date (uses 'earlier' holding),
unconfigured prefix passthrough, and custom config remapping.

### `box_accrual` (2 → 5 tests)

Plugin splits `:Capital-Losses` postings across years by day count.
Matrix:
- no `synthetic_loan_expiry` metadata → unchanged
- multi-year split → exactly N postings per year, sum preserves
  total exactly (pins the "final segment is remainder" invariant)
- same-year span → no split
- no Capital-Losses posting → unchanged
- multiple Capital-Losses postings → unchanged (plugin only handles
  exactly 1)

## Verified

- 88 → 102 plugin integration tests (+14)
- `scripts/check-plugin-test-quality.sh`: OK
- `scripts/test-plugin-test-quality.sh`: 28/28
- `cargo clippy -p rustledger-plugin --all-features --all-targets`:
  clean

## Lint follow-up noted

The existing `test_forecast_expands_recurring_transaction` had a
weak `assert!(txn_count >= 3, ...)` shape that the lint missed
because it's multi-line and PAT_A doesn't have a multi-line variant
yet (PAT_B/C/D got their multi-line counterparts in #1005, but
PAT_A's wasn't needed at the time). Tightened to `assert_eq!(.count(),
3, ...)` here. Adding `ML_PAT_A` is a small follow-up — the
file-wide refactor wasn't in scope for this PR.

Closes 4 more entries in #1002 (Tier 1: `forecast`, `rx_txn`,
`effective_date`, `box_accrual`). 7 of 11 Tier 1 plugins now
covered after this PR + the open #1007.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings May 5, 2026 22:00
@robcohen
robcohen requested a review from a team as a code owner May 5, 2026 22:00

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 strengthens the rustledger-plugin native plugin integration tests by replacing minimal “happy-path” coverage with matrix-style tests for four Tier-1 plugins (rx_txn, effective_date, forecast, box_accrual), aiming to pin exact counts and key invariants.

Changes:

  • Expanded rx_txn integration tests to cover tagged/untagged behavior plus default-metadata fill vs. preserve semantics.
  • Expanded effective_date integration tests to cover future/past effective dates, unconfigured prefix passthrough, and custom config remapping.
  • Expanded forecast and box_accrual integration tests to assert exact expansion/splitting counts and key invariants (dates, narration stripping, sum preservation).

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

@github-actions

github-actions Bot commented May 5, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 29ms ± 0.4ms 22 MB
beancount 846.7ms ± 8ms 50.6 MB
Comparison 29.2x faster 2.3x less

vs main branch (2026-05-06)

Metric main this PR Change
Time 30.9ms 29ms -6.1% 🟢
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

✅ All modified and coverable lines are covered by tests.

📢 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 88%
Full AST Match 99%
Total Files 786
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

robcohen and others added 2 commits May 6, 2026 09:00
Five items from the inline review:

1. **`test_rx_txn_preserves_existing_metadata` didn't check `roll`.**
   Test asserted the existing `final` value was preserved but never
   the `roll` value, so the plugin could overwrite `roll` while
   leaving `final` intact and the test would still pass. Added
   strict equality on `roll`'s value too.

2. **`test_rx_txn_works_alongside_other_tags` only asserted `final`
   was added.** Same asymmetry — if the plugin failed to add `roll`
   when other tags were present, the test wouldn't catch it.
   Added an explicit `roll` presence assertion.

3. **`make_txn_with_effective_date` parameter name was misleading.**
   Named `expense_account` but tests pass `Liabilities:CreditCard`
   etc. Renamed to `target_account` and clarified the doc comment
   that the helper accepts any account (the plugin's behavior
   depends on whether the prefix matches the holding-account map).

4. **Several forecast tests didn't assert `output.errors.is_empty()`.**
   `test_forecast_weekly_repeat`, `..._daily_repeat`,
   `..._monthly_until_inclusive`, `..._skip_increases_stride`,
   `..._no_pattern_in_narration_kept_unchanged` all skipped the
   error-free assertion. A regression where the plugin starts
   emitting errors but produces the right counts would have
   slipped through. Added `assert!(output.errors.is_empty())` to
   each.

5. **`test_effective_date_custom_config_remaps_prefix` only checked
   the holding-account Open was generated.** A partial regression
   could still produce an Open while failing to spawn the
   effective-date transaction OR failing to post to the remapped
   account. Tightened to assert all three:
   - Open for `Liabilities:Hold:Liab*` is generated
   - Exactly one transaction is spawned at the effective date
   - That transaction's postings reference the remapped holding
     account

## Verified

- 102/102 tests pass (count unchanged — only assertions strengthened)
- Lint OK, clippy clean

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…test

Self-review follow-up to the Copilot fixes — items 3, 4, 5, 6 from
the post-Copilot audit.

## Item 3: box_accrual proptest for sum-preservation

`test_box_accrual_multi_year_splits_preserve_total` only tested one
specific input (-1000.00 over 2024-07-01 → 2026-06-30). The "sum of
splits == original total" invariant is purely algebraic and should
hold for any (total, start, expiry) tuple — perfect proptest material.

Added `prop_box_accrual_split_amounts_preserve_total` (64 cases):
- random total in cents (negative, $0.01 to $100,000)
- random start month/day in 2024
- random extra-years span (1-5)
- random expiry month/day

Asserts `sum(split_amounts) == original_total` exactly. The plugin's
"final segment is total - sum(rounded_priors)" logic is what
guarantees this; a rounding bug under any specific (total, days)
combination would surface here.

## Item 4: forecast tests didn't verify postings preserved

`test_forecast_monthly_repeat_emits_exactly_n_transactions` checked
counts and dates but never asserted that the replicated transactions
preserved the original postings (account/units/currency/flag). A
bug that mangled postings while replicating dates would have passed.

Tightened with a per-emitted-txn loop checking:
- narration cleanly stripped of bracket pattern (existing assertion,
  now applied to every emitted txn, not just the first)
- forecast flag `#` preserved
- exactly 2 postings, with right accounts and amounts
- units number and currency on each posting

## Item 5: effective_date hold-posting sign-flip not verified

`create_opposite_posting` is the plugin's negation primitive. The
existing `test_effective_date_future_uses_later_holding_account`
asserted the holding-account Open and the effective-date txn count,
but never that the hold posting's units were the SIGN-FLIPPED
version of the original target posting. A regression in
`create_opposite_posting` (e.g., copy instead of negate) would have
left the new transaction unbalanced and the test would still pass.

Added: assert hold posting on the effective-date txn has
units `-25 USD` (vs `+25 USD` on the original).

## Item 6: effective_date link generation not verified

The plugin generates a unique link tying the original txn to the
new effective-date txn. None of the integration tests checked it.

Added to the same future-date test:
- original txn has exactly one link
- effective-date txn has exactly one link
- both links are the same string
- link starts with `edate-` (matches the generator format)

## Verified

- 103/103 tests pass (+1 from new proptest)
- Lint OK, clippy clean

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen merged commit 31eb939 into main May 6, 2026
31 checks passed
@robcohen
robcohen deleted the feat/transaction-emitter-test-matrices branch May 6, 2026 14:20
robcohen added a commit that referenced this pull request May 6, 2026
…ses, zerosum, check_average_cost

Phase 1 of #992 plan (closes the remaining 4 of 11 Tier 1 plugins
in #1002). All four plugins had only one trivial integration test
each — usually with weak count assertions — and now have full
matrices with strict equality checks plus property tests for the
two with clean algebraic invariants.

## Coverage

### `generate_base_ccy_prices` (1 → 5 tests, +1 proptest)

Plugin reads existing prices and emits derived `(C, base)` entries
when chains `(C, X)` + `(X, base)` exist. Matrix:

- no config → passthrough (was: lone test with weak `> 2` count)
- ETH→EUR + EUR→USD → exactly one ETH→USD = 2200, count + amount
  + currency all asserted strictly
- target price already exists → no duplicate
- prices already in base currency → no derivation

Proptest `prop_generate_base_ccy_prices_multiplies_chain_exactly`
pins the multiplicative invariant: derived rate = `(C→X) * (X→base)`
for any cents-based pair of rates.

### `split_expenses` (1 → 4 tests, +1 proptest)

Plugin splits any Expenses:* posting (whose account doesn't
already include a member name) into N proportional sub-postings
with `__automatic__: True` metadata, plus emits Open directives
for the new sub-accounts.

Matrix:

- no config → passthrough
- 2 members, $100 → $50 each (was: weak `>= 2` posting count;
  now strict on amounts, currencies, metadata, and emitted Opens)
- account already contains a member name → unchanged, no
  __automatic__ added
- non-Expenses posting (Income/Assets) → unchanged

Proptest `prop_split_expenses_sum_preserves_total` pins:
sum(splits) = (amount/N) * N for random (amount, member_count).

### `zerosum` (1 → 4 tests)

Plugin matches paired postings in zero-sum accounts within a
configurable date window and moves them to a "matched" account.

Matrix:

- missing config → 1 error (existing test, kept)
- pair within 30-day window → both halves move to matched account,
  none remain in zerosum
- pair outside the window → unmatched, both remain in zerosum
- single unmatched posting → remains in zerosum

(No proptest — the matching/window/account-substitution logic is
discrete enough that the example matrix is the right shape.)

### `check_average_cost` (1 → 5 tests)

Plugin warns when a reducing posting's cost differs from the
account's running average by more than `tolerance`. Critical
constraint: only checked for accounts opened with `NONE` booking
(the lot-management-by-author case from #907).

Added `make_open_with_booking` helper. Matrix:

- correct sale at average cost → silent
- sale below average by 33% (default tolerance is 1%) → 1 warning
  mentioning the account and commodity
- STRICT-booking account → skipped entirely (issue #907 false-
  positive guard)
- account with `booking: None` → also skipped (only NONE-booking
  is checked)
- custom tolerance: 40% deviation within a 50% tolerance → silent

## Verified

- 124 → 143 plugin integration tests (+19 new + 2 proptests)
- `scripts/check-plugin-test-quality.sh`: OK
- `scripts/test-plugin-test-quality.sh`: 28/28
- `cargo clippy -p rustledger-plugin --all-features --all-targets`:
  clean

## Tightened from existing weak shapes

Two existing tests had weak count assertions in the multi-line form
that PAT_A's missing multi-line variant doesn't catch (#1011):

- `test_generate_base_ccy_prices_creates_derived_price`:
  `assert!(price_count > 2)` → strict count + amount
- `test_split_expenses_divides_by_members`: `assert!(...len() >= 2)`
  → strict count + amounts + metadata

Both replaced by stronger assertions in the new matrices.

## #1002 progress

After this PR: **all 11 Tier 1 plugins covered** (capital_gains
family in #1007, transaction-emitter family in #1008, this
numeric/emits family completes the set).

Closes part of #1002.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 6, 2026
…ses, zerosum, check_average_cost (#1012)

Phase 1 of #992 plan (closes the remaining 4 of 11 Tier 1 plugins
in #1002). All four plugins had only one trivial integration test
each — usually with weak count assertions — and now have full
matrices with strict equality checks plus property tests for the
two with clean algebraic invariants.

## Coverage

### `generate_base_ccy_prices` (1 → 5 tests, +1 proptest)

Plugin reads existing prices and emits derived `(C, base)` entries
when chains `(C, X)` + `(X, base)` exist. Matrix:

- no config → passthrough (was: lone test with weak `> 2` count)
- ETH→EUR + EUR→USD → exactly one ETH→USD = 2200, count + amount
  + currency all asserted strictly
- target price already exists → no duplicate
- prices already in base currency → no derivation

Proptest `prop_generate_base_ccy_prices_multiplies_chain_exactly`
pins the multiplicative invariant: derived rate = `(C→X) * (X→base)`
for any cents-based pair of rates.

### `split_expenses` (1 → 4 tests, +1 proptest)

Plugin splits any Expenses:* posting (whose account doesn't
already include a member name) into N proportional sub-postings
with `__automatic__: True` metadata, plus emits Open directives
for the new sub-accounts.

Matrix:

- no config → passthrough
- 2 members, $100 → $50 each (was: weak `>= 2` posting count;
  now strict on amounts, currencies, metadata, and emitted Opens)
- account already contains a member name → unchanged, no
  __automatic__ added
- non-Expenses posting (Income/Assets) → unchanged

Proptest `prop_split_expenses_sum_preserves_total` pins:
sum(splits) = (amount/N) * N for random (amount, member_count).

### `zerosum` (1 → 4 tests)

Plugin matches paired postings in zero-sum accounts within a
configurable date window and moves them to a "matched" account.

Matrix:

- missing config → 1 error (existing test, kept)
- pair within 30-day window → both halves move to matched account,
  none remain in zerosum
- pair outside the window → unmatched, both remain in zerosum
- single unmatched posting → remains in zerosum

(No proptest — the matching/window/account-substitution logic is
discrete enough that the example matrix is the right shape.)

### `check_average_cost` (1 → 5 tests)

Plugin warns when a reducing posting's cost differs from the
account's running average by more than `tolerance`. Critical
constraint: only checked for accounts opened with `NONE` booking
(the lot-management-by-author case from #907).

Added `make_open_with_booking` helper. Matrix:

- correct sale at average cost → silent
- sale below average by 33% (default tolerance is 1%) → 1 warning
  mentioning the account and commodity
- STRICT-booking account → skipped entirely (issue #907 false-
  positive guard)
- account with `booking: None` → also skipped (only NONE-booking
  is checked)
- custom tolerance: 40% deviation within a 50% tolerance → silent

## Verified

- 124 → 143 plugin integration tests (+19 new + 2 proptests)
- `scripts/check-plugin-test-quality.sh`: OK
- `scripts/test-plugin-test-quality.sh`: 28/28
- `cargo clippy -p rustledger-plugin --all-features --all-targets`:
  clean

## Tightened from existing weak shapes

Two existing tests had weak count assertions in the multi-line form
that PAT_A's missing multi-line variant doesn't catch (#1011):

- `test_generate_base_ccy_prices_creates_derived_price`:
  `assert!(price_count > 2)` → strict count + amount
- `test_split_expenses_divides_by_members`: `assert!(...len() >= 2)`
  → strict count + amounts + metadata

Both replaced by stronger assertions in the new matrices.

## #1002 progress

After this PR: **all 11 Tier 1 plugins covered** (capital_gains
family in #1007, transaction-emitter family in #1008, this
numeric/emits family completes the set).

Closes part of #1002.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 6, 2026
…tions (#1013)

Closes #1011.

## What

`scripts/check-plugin-test-quality.sh` had multi-line variants for
shapes B (`assert_ne!`), C (`!is_empty()`), and D (`!= 0`) added in
#1005. Shape A — `assert!(x.len() >= N)` / precomputed-count — only
had its single-line PAT_A. So a multi-line write of the original
#992 bug shape:

    assert!(
        txn_count >= 3,
        "forecast should expand to at least 3 transactions"
    );

slipped past the lint. PR #1008 caught one such instance by hand;
PR #1012 caught two more.

## Fix

Added `ML_PAT_A` mirroring single-line `PAT_A` with the same
count-shaped LHS restriction (`COUNT_LHS`) and the negative
lookbehind for `prop_assert!`/`debug_assert!` that the other
multi-line patterns already use:

    ML_PAT_A='(?<!\w)assert!\(\s*'"$COUNT_LHS"'\s*(?:>|>=)\s*\d+'

Wired into the existing `find_multiline_in_rs` call.

## Knock-on: tightened one existing test

The new pattern caught a real instance in
`test_check_drained_adds_balance_assertions_on_close`:

    assert!(
        balance_count > 0,
        "should insert balance assertions after close"
    );

The plugin emits exactly one balance assertion per (closed account,
currency); test setup has one Close on Assets:Bank with USD only,
so we expect 1. Tightened to `assert_eq!(.count(), 1, ...)`.

## Self-test

Extended `scripts/test-plugin-test-quality.sh` with 4 new cases
(28 → 32 total):
- multi-line `assert!(\n    x.len() >= 1,\n    "msg"\n)`
- multi-line `assert!(\n    price_count >= 1\n)` (the actual #992 shape)
- multi-line `assert!(\n    x.count() > 0\n)`
- false-positive guard: multi-line `prop_assert!(\n    x.len() >= 1\n)`
  must NOT fire

## Verified

- 143/143 plugin tests pass (one pre-existing test tightened, no new
  test functions)
- `scripts/check-plugin-test-quality.sh`: OK (clean on current main)
- `scripts/test-plugin-test-quality.sh`: 32/32
- `cargo clippy -p rustledger-plugin --all-features --all-targets`:
  clean

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