Skip to content

fix(ci): catch multi-line weak-count assertions in plugin-test lint - #1005

Merged
robcohen merged 2 commits into
mainfrom
fix/lint-multiline-is-empty
May 5, 2026
Merged

robcohen merged 2 commits into
mainfrom
fix/lint-multiline-is-empty

Conversation

@robcohen

@robcohen robcohen commented May 5, 2026

Copy link
Copy Markdown
Member

fix(ci): catch multi-line weak-count assertions in plugin-test lint

The lint script's regex was line-anchored (grep -rEn), so the
multi-line form of assert!(...) slipped through:

assert!(
    !output.errors.is_empty(),
    "should warn about X"
);

This is the more common form when the assertion has a message arg.
A scan of the current test file found 5 such uncaught instances —
each one is the same shape as the #992 bug (accepts "1 OR 100"
silently).

Fix

Added a Python-based multi-line scan alongside the existing bash
grep. Python's re.DOTALL cleanly handles cross-line matches and
preserves correct line numbers; bash + grep can't easily do both.

Three new multi-line patterns mirror the single-line PAT_B/C/D
shapes. The single-line patterns also got a (^|[^[:alnum:]_])
word-boundary prefix and the multi-line ones got (?<!\w) — so
prop_assert!(!x.is_empty()) and debug_assert!(!x.is_empty())
no longer false-positive (they contain the substring assert!(
but are semantically different).

The script now needs Python 3 — already a dep for several other
scripts (compat-bql-test.py, trace_to_rust_test.py).

Tightened tests

Five existing tests had the multi-line !is_empty() shape:

  • test_check_commodity_undeclared (line 1755)
  • test_auto_tag_adds_tag_for_expense (line 3054)
  • test_pedantic_runs_multiple_validators (line 3134)
  • test_sell_gains_warns_missing_gains_posting (line 3220)
  • test_commodity_attr_error_with_missing_required_attr (line 3277)

All five now use assert_eq!(x.len(), 1, ...) since each scenario
emits exactly one error/warning/tag. Verified locally (88/88 plugin
tests pass).

Self-test

Extended scripts/test-plugin-test-quality.sh with 5 new cases
(21 → 26 total): 3 multi-line shape cases + 2 false-positive
guards (prop_assert!, debug_assert! must not fire).

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 20:10
Copilot AI review requested due to automatic review settings May 5, 2026 20:10

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 improves the CI/pre-push “plugin test quality” lint so it also detects weak count assertions written in the common multi-line assert!(...) form (especially when a message argument is present). It also tightens several plugin integration tests to use strict assert_eq!(..., 1, ...) instead of weak !is_empty() checks, and extends the lint self-test to cover the new multi-line detection and boundary false-positive guards.

Changes:

  • Add a Python re.DOTALL-based multi-line scanner to scripts/check-plugin-test-quality.sh, alongside the existing grep -rEn pass.
  • Extend scripts/test-plugin-test-quality.sh with new multi-line cases and “must not match” guards for prop_assert! / debug_assert!.
  • Tighten 5 assertions in native_plugins_test.rs from “non-empty” to exact count checks (len() == 1) and adjust message checks accordingly.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.

File Description
scripts/test-plugin-test-quality.sh Adds new self-test cases for multi-line weak-assert shapes and false-positive guards.
scripts/check-plugin-test-quality.sh Adds Python multi-line scanning and word-boundary guards to improve weak count assertion detection.
crates/rustledger-plugin/tests/native_plugins_test.rs Replaces weak “non-empty” assertions with strict len() == 1 checks in several tests.

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

Comment thread scripts/check-plugin-test-quality.sh Resolved
@github-actions

github-actions Bot commented May 5, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 32.9ms ± 2.1ms 21.5 MB
beancount 805.4ms ± 12.2ms 50.5 MB
Comparison 24.5x faster 2.3x less

vs main branch (2026-05-05)

Metric main this PR Change
Time 32.2ms 32.9ms +2.2% ✅
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 89%
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 robcohen self-assigned this May 5, 2026
Two real findings:

1. **`ML_PAT_B` and `ML_PAT_D` were too broad.** Single-line PAT_B/D
   restrict the LHS to count-shaped expressions (`.count()`/`.len()`/
   `.size()` calls or `*_count`/`*_len`/`*_size` idents) — but my
   multi-line equivalents matched ANY `assert_ne!(<expr>, 0)` /
   `assert!(<expr> != 0)`. So `assert_ne!(balance, 0)` would have
   false-positively tripped the lint.

   Extracted a shared `COUNT_LHS` PCRE alternation and embedded it
   in both ML_PAT_B and ML_PAT_D, mirroring the single-line shape.

   Two new self-test cases pin the false-positive guard:
   - `assert_ne!(balance, 0)` (non-count) does NOT fire
   - `assert!(balance != 0)` (non-count) does NOT fire

2. **`if let` with no `else` could silently pass the test.** The
   `test_auto_tag_adds_tag_for_expense` test had:

       if let DirectiveData::Transaction(data) = &txn.data {
           assert_eq!(data.tags.len(), 1, ...);
       }

   If `txn.data` were ever a non-Transaction variant (impossible
   given the preceding `directive_type == "transaction"` filter,
   but defense-in-depth), the assertion would never run and the
   test would silently pass. Replaced with `let ... else { panic!()
   }` so the impossible state is loud.

Self-test: 26 → 28 cases. Plugin tests: still 88/88.
@robcohen
robcohen enabled auto-merge (squash) May 5, 2026 20:38
@robcohen
robcohen merged commit 5902755 into main May 5, 2026
31 checks passed
@robcohen
robcohen deleted the fix/lint-multiline-is-empty branch May 5, 2026 20:43
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 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
…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