Skip to content

test(plugin): full test matrices for unrealized, sell_gains, capital_gains_classifier - #1007

Merged
robcohen merged 3 commits into
mainfrom
feat/capital-gains-test-matrices
May 6, 2026
Merged

robcohen merged 3 commits into
mainfrom
feat/capital-gains-test-matrices

Conversation

@robcohen

@robcohen robcohen commented May 5, 2026

Copy link
Copy Markdown
Member

test(plugin): full test matrices for unrealized, sell_gains, capital_gains_classifier

Phase 1 of the #992 plan (tracked in #1002). Three Tier-1 plugins
each got a comprehensive test matrix replacing the trivial
"doesn't error" / "no-config passthrough" stubs they had before.

What's covered

unrealized (1 test → 8 tests + 1 proptest)

Plugin computes (market_price - cost_basis) * units per position
and emits warnings (NOT directives) when |delta| > $0.01. Matrix:

  • gain (market > cost) → 1 warning with positive number
  • loss (market < cost) → 1 warning with negative number
  • market == cost → silent (pins the threshold)
  • no price directive → silent
  • zero position (buy then full sell) → silent
  • multi-buy aggregation → uses weighted-average cost basis
  • non-USD quote currency → silent (pins the hardcoded USD assumption)
  • custom gains_account → currently unused in output (pins so a
    future change to emit actual directives is caught)

Property test: across 64 cases of (units, cost_per, market_price),
the warning amount equals (market - cost) * units exactly when
above the 0.01 threshold, and no warning fires when below.

sell_gains (1 test → 7 tests)

Plugin warns when a sale (negative units with cost+price) has a
non-zero expected gain but no Income:* / Expenses:* posting. Matrix:

  • sale missing gains posting → 1 warning (existing, kept)
  • sale with Income:Capital-Gains posting → silent
  • sale with Expenses:* posting → silent (plugin treats either as ok)
  • buy (positive units) → silent regardless
  • sale at exactly cost (zero gain) → silent
  • sale without cost or price → silent (preconditions not met)
  • two sales sharing one Income posting → both covered (documents
    the per-transaction, not per-posting, check — quirky but pinned)

capital_gains_classifier::long_short (1 test → 6 tests)

Rebooks generic Income:.*Capital-Gains postings into :Short / :Long
based on holding period. Matrix:

  • no config → passthrough
  • malformed config → passthrough
  • valid config but no matching posting → unchanged
  • 6-month hold → classified as :Short
  • 2.5-year hold → classified as :Long
  • cost spec without date → unchanged (pins the date-required branch)

capital_gains_classifier::gain_loss (1 test → 6 tests)

Renames matching postings to :Gains (negative units) or :Losses
(non-negative). Matrix:

  • no config → passthrough
  • malformed config → passthrough
  • negative posting → :Gains
  • positive posting → :Losses
  • non-matching account → unchanged
  • zero posting → :Losses (pins the >= 0 boundary)

Verified

  • cargo test -p rustledger-plugin --test native_plugins_test:
    112 passed (was 88, +24 new tests + 1 proptest = 25 entries)
  • scripts/check-plugin-test-quality.sh: OK (lint policies pass)
  • scripts/test-plugin-test-quality.sh: 28/28 (lint self-test)
  • cargo clippy -p rustledger-plugin --all-features --all-targets:
    clean

Deferred follow-ups

  • Differential fixtures under tests/compatibility/files/plugins/
    for these plugins. Local nix env has a Python regex circular
    import bug that prevents bean-check from loading
    beancount.plugins.unrealized / .sellgains, so we can't verify
    fixtures parse on the Python side without env work. The
    beancount_reds_plugins.capital_gains_classifier package isn't
    in the nix env at all. Will be a follow-up once the environment
    is sorted.

Closes part of #1002 (Tier 1: 3 of 11 plugins covered).

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

…gains_classifier

Phase 1 of the #992 plan (tracked in #1002). Three Tier-1 plugins
each got a comprehensive test matrix replacing the trivial
"doesn't error" / "no-config passthrough" stubs they had before.

## What's covered

### `unrealized` (1 test → 8 tests + 1 proptest)

Plugin computes `(market_price - cost_basis) * units` per position
and emits warnings (NOT directives) when |delta| > $0.01. Matrix:

- gain (market > cost) → 1 warning with positive number
- loss (market < cost) → 1 warning with negative number
- market == cost → silent (pins the threshold)
- no price directive → silent
- zero position (buy then full sell) → silent
- multi-buy aggregation → uses weighted-average cost basis
- non-USD quote currency → silent (pins the hardcoded USD assumption)
- custom gains_account → currently unused in output (pins so a
  future change to emit actual directives is caught)

Property test: across 64 cases of (units, cost_per, market_price),
the warning amount equals `(market - cost) * units` exactly when
above the 0.01 threshold, and no warning fires when below.

### `sell_gains` (1 test → 7 tests)

Plugin warns when a sale (negative units with cost+price) has a
non-zero expected gain but no Income:* / Expenses:* posting. Matrix:

- sale missing gains posting → 1 warning (existing, kept)
- sale with Income:Capital-Gains posting → silent
- sale with Expenses:* posting → silent (plugin treats either as ok)
- buy (positive units) → silent regardless
- sale at exactly cost (zero gain) → silent
- sale without cost or price → silent (preconditions not met)
- two sales sharing one Income posting → both covered (documents
  the per-transaction, not per-posting, check — quirky but pinned)

### `capital_gains_classifier::long_short` (1 test → 6 tests)

Rebooks generic Income:.*Capital-Gains postings into :Short / :Long
based on holding period. Matrix:

- no config → passthrough
- malformed config → passthrough
- valid config but no matching posting → unchanged
- 6-month hold → classified as :Short
- 2.5-year hold → classified as :Long
- cost spec without date → unchanged (pins the date-required branch)

### `capital_gains_classifier::gain_loss` (1 test → 6 tests)

Renames matching postings to :Gains (negative units) or :Losses
(non-negative). Matrix:

- no config → passthrough
- malformed config → passthrough
- negative posting → :Gains
- positive posting → :Losses
- non-matching account → unchanged
- zero posting → :Losses (pins the >= 0 boundary)

## Verified

- `cargo test -p rustledger-plugin --test native_plugins_test`:
  112 passed (was 88, +24 new tests + 1 proptest = 25 entries)
- `scripts/check-plugin-test-quality.sh`: OK (lint policies pass)
- `scripts/test-plugin-test-quality.sh`: 28/28 (lint self-test)
- `cargo clippy -p rustledger-plugin --all-features --all-targets`:
  clean

## Deferred follow-ups

- Differential fixtures under `tests/compatibility/files/plugins/`
  for these plugins. Local nix env has a Python `regex` circular
  import bug that prevents `bean-check` from loading
  `beancount.plugins.unrealized` / `.sellgains`, so we can't verify
  fixtures parse on the Python side without env work. The
  `beancount_reds_plugins.capital_gains_classifier` package isn't
  in the nix env at all. Will be a follow-up once the environment
  is sorted.

Closes part of #1002 (Tier 1: 3 of 11 plugins covered).

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

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 Tier-1 native plugin test suite by replacing prior “no error” stubs with comprehensive, branch-covering test matrices for sell_gains, unrealized, and capital_gains_classifier (long_short and gain_loss).

Changes:

  • Expanded SellGainsPlugin tests to cover sales vs buys, zero-gain sales, missing preconditions, and “shared Income/Expenses posting” behavior.
  • Expanded UnrealizedPlugin tests into a full matrix plus a proptest asserting the core gain/loss invariant and threshold behavior.
  • Added matrices for CapitalGainsLongShortPlugin and CapitalGainsGainLossPlugin, covering config/no-config, malformed config, and key classification branches.

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

@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

📊 Benchmark Results

Tool Time Memory
rustledger 35ms ± 1.1ms 21.8 MB
beancount 795.2ms ± 17.5ms 50.3 MB
Comparison 22.7x faster 2.3x less

vs main branch (2026-05-06)

Metric main this PR Change
Time 30.9ms 35ms +13.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

@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 added a commit that referenced this pull request May 5, 2026
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]>
robcohen and others added 2 commits May 6, 2026 08:53
Five items from the inline review:

1. **Wrong claim in sell_gains matrix doc.** Said "two sales sharing
   one Income posting → ONE warning suppressed", but it's actually
   ZERO warnings (both sales are considered covered by the single
   Income posting because `has_gain_posting` is per-transaction).
   Reworded.

2. **Imprecise unrealized matrix doc.** Said the threshold is
   `|market - cost_basis| > 0.01`, but the plugin computes
   `|(units * market_price) - cost_basis| > 0.01`. Updated.

3. **Proptest claimed coverage it didn't have.** Doc said the test
   exercises "fractional prices" and "edge values near the
   threshold", but generators were `u32` so the only sub-threshold
   case was exact equality. Switched to cents-based generators
   (`Decimal::new(cents, 2)`) so fractional prices and near-
   threshold values are actually probed. The test still asserts
   the same algebraic invariant; it just probes a richer space.

4. **Off-by-one-year doc in long_short matrix.** Said
   "entry_date - cost_date > 1 year → long", but the plugin treats
   `years_held >= 1` (with month/day boundary) as long. Reworded
   to match actual logic.

5. **`test_capital_gains_long_short_no_cost_date_unchanged` was
   passing for the wrong reason.** The transaction had no
   `Income:Capital-Gains` posting, so the plugin took the early
   "no matching postings → passthrough" branch — the cost-date
   logic was never reached. Rewrote the test to include a generic
   Income:Capital-Gains posting AND a reduction with no cost date,
   then pinned the *actual* observed behavior:

   The plugin currently DROPS the generic Income:Capital-Gains
   posting and emits no :Short/:Long replacement, leaving the
   transaction unbalanced. This is almost certainly a plugin bug
   (it should fall through cleanly or surface an error). The test
   pins the current behavior and notes in a comment that a future
   fix should update this assertion.

   Renamed the test to
   `test_capital_gains_long_short_no_cost_date_drops_generic_posting`
   to reflect what it actually pins.

## Verified

- 112/112 tests pass (count unchanged — one test renamed, internal
  changes only)
- Lint OK, clippy clean

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Self-review follow-up to the Copilot fixes — items 1 and 2 from
the post-Copilot audit.

## Item 1: amount assertions in long_short and gain_loss tests

Pre-fix the tests verified the *account* of the rebooked posting
but never the *amount*. Same shape of weakness as #992: a bug in
the gain calculation could silently rebook to the right account
with a wrong number and the test would still pass.

Tightened five tests:

- `test_capital_gains_long_short_classifies_short_term`: assert
  posting amount = `(cost - price) * |units|` = -500
- `test_capital_gains_long_short_classifies_long_term`: same
- `test_capital_gains_gain_loss_negative_renames_to_gains`: assert
  units value -100 preserved through the rename
- `test_capital_gains_gain_loss_positive_renames_to_losses`: assert
  units value 100 preserved
- `test_capital_gains_gain_loss_zero_renames_to_losses`: assert
  units value 0 preserved (boundary case)

## Item 2: multi-buy proptest for unrealized

`prop_unrealized_warning_amount_matches_units_times_delta` only
covered single-buy scenarios. Multi-buy aggregation has its own
arithmetic (cumulative units + cumulative cost basis) that wasn't
proptested.

Added `prop_unrealized_aggregates_two_buys_correctly`:

  expected_gain = (units_a + units_b) * market
                  - (cost_a*units_a + cost_b*units_b)

64 random cases across cents-based generators (matching the
existing single-buy proptest's cents convention).

## Verified

- 113/113 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 6de69ab into main May 6, 2026
31 checks passed
@robcohen
robcohen deleted the feat/capital-gains-test-matrices branch May 6, 2026 14:13
robcohen added a commit that referenced this pull request May 6, 2026
…_accrual (#1008)

* 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]>

* test(plugin): address Copilot review on #1008

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(plugin): tighten posting/sign/link assertions + box_accrual proptest

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]>

---------

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

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
…st date

Closes #1010.

## Bug

The `long_short` capital-gains classifier silently dropped the
generic `Income:Capital-Gains` posting from a transaction whenever
any reduction posting (cost+units+price) had `cost.date == None`.

Trace:

1. `has_generic = true` → plugin enters the rewrite path
2. `reductions` is non-empty → past the early-return
3. The reduction loop's `if let Some(cost_date) = cost_date` skips
   gain accumulation when the date is missing → `short_gains` and
   `long_gains` stay at 0
4. `new_postings` is built by FILTERING OUT the matching generic
   postings
5. Both `short_gains != 0` and `long_gains != 0` are false → no
   :Short / :Long replacement is emitted
6. The synthesized transaction is pushed with the generic
   Income:Capital-Gains posting silently removed → unbalanced

## Fix

Detect the condition early and fall through the entire transaction
unchanged. Right after parsing `entry_date`:

    let any_missing_cost_date = reductions.iter().any(|p| {
        p.cost.as_ref()
            .and_then(|c| c.date.as_ref())
            .and_then(|d| d.parse::<NaiveDate>().ok())
            .is_none()
    });
    if any_missing_cost_date {
        new_directives.push(directive);
        continue;
    }

Matches the early-return pattern already used elsewhere in the
plugin when classification is impossible (e.g., unparsable
`entry_date`).

## Test

Renamed and inverted
`test_capital_gains_long_short_no_cost_date_drops_generic_posting`
→ `..._passes_through_unchanged`. Now asserts:

- No :Short or :Long replacement is emitted (gains stay at 0)
- The generic `Income:Capital-Gains` posting IS preserved
- The transaction's full posting count is unchanged (3 → 3)

Pre-fix the test pinned the buggy behavior with a comment noting
"this is almost certainly a plugin bug." The PR that introduced
the test (#1007) is referenced in the issue.

## Verified

- 143/143 plugin integration tests pass
- Lint OK, clippy clean

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

Closes #1010.

## Bug

The `long_short` capital-gains classifier silently dropped the
generic `Income:Capital-Gains` posting from a transaction whenever
any reduction posting (cost+units+price) had `cost.date == None`.

Trace:

1. `has_generic = true` → plugin enters the rewrite path
2. `reductions` is non-empty → past the early-return
3. The reduction loop's `if let Some(cost_date) = cost_date` skips
   gain accumulation when the date is missing → `short_gains` and
   `long_gains` stay at 0
4. `new_postings` is built by FILTERING OUT the matching generic
   postings
5. Both `short_gains != 0` and `long_gains != 0` are false → no
   :Short / :Long replacement is emitted
6. The synthesized transaction is pushed with the generic
   Income:Capital-Gains posting silently removed → unbalanced

## Fix

Detect the condition early and fall through the entire transaction
unchanged. Right after parsing `entry_date`:

    let any_missing_cost_date = reductions.iter().any(|p| {
        p.cost.as_ref()
            .and_then(|c| c.date.as_ref())
            .and_then(|d| d.parse::<NaiveDate>().ok())
            .is_none()
    });
    if any_missing_cost_date {
        new_directives.push(directive);
        continue;
    }

Matches the early-return pattern already used elsewhere in the
plugin when classification is impossible (e.g., unparsable
`entry_date`).

## Test

Renamed and inverted
`test_capital_gains_long_short_no_cost_date_drops_generic_posting`
→ `..._passes_through_unchanged`. Now asserts:

- No :Short or :Long replacement is emitted (gains stay at 0)
- The generic `Income:Capital-Gains` posting IS preserved
- The transaction's full posting count is unchanged (3 → 3)

Pre-fix the test pinned the buggy behavior with a comment noting
"this is almost certainly a plugin bug." The PR that introduced
the test (#1007) is referenced in the issue.

## Verified

- 143/143 plugin integration tests pass
- Lint OK, clippy 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