Skip to content

ci(plugin-tests): policy + lint script for plugin-test quality (Phase 5 of #992 plan) - #1001

Merged
robcohen merged 4 commits into
mainfrom
feat/plugin-testing-policy
May 5, 2026
Merged

robcohen merged 4 commits into
mainfrom
feat/plugin-testing-policy

Conversation

@robcohen

@robcohen robcohen commented May 5, 2026 •

Copy link
Copy Markdown
Member

Phase 5 of the plugin-testing-quality plan from #992. Standing policy + CI gate for the bug class that produced the original issue.

Why

The chain that allowed #992 to ship:

  1. (partial) upstream test port (only the cost path, not @ / @@)
  2. assert!(price_count >= 1) — accepted both 1 and 100 emissions
  3. Two parallel implementations (plugin vs query) that drifted because nothing tied them together
  4. is_total: bool consumed without exhaustive matching

Phases 0a–0c and 2 fixed those structurally. This PR codifies the policies so the next plugin doesn't reintroduce the bug shape.

What ships

CONTRIBUTING.md — "Plugin testing requirements" section

Five policies for plugin contributions:

  1. Test matrix, not happy path
  2. Strict count assertions (assert_eq!, never >=)
  3. No (partial) test ports
  4. Differential coverage where applicable (drop a fixture under tests/compatibility/files/plugin/<name>/ — the harness from feat(compat): plugin differential harness via BQL fixtures (Phase 2 of #992 plan) #1000 picks it up)
  5. Type-driven exhaustive matching (use match on enum-shaped inputs)

For numeric plugins specifically: at least one proptest case.

scripts/check-plugin-test-quality.sh

CI lint enforcing the two most mechanical policies. Catches three semantically-identical weak-assertion shapes:

All three accept "1 emission OR 100", which is exactly the failure mode that hid #992.

For (partial) test ports, matches the literal Converted from … (partial) shape that historically marked half-done ports.

Both checks have an explicit per-match allowlist:

  • // allow weak-count: <reason> (used legitimately on the registry-list test where the count grows with each plugin)
  • // allow partial: <reason> (escape hatch for unrelated (partial) substrings)

The lookback for the allow annotation reads up to 5 lines above the match using a bash loop with sed -n — replaced an earlier awk block parser that lost violations when multiple matches fell inside the same context window.

Per the project's feedback_no_error_swallowing.md, grep is invoked with explicit exit-code handling that distinguishes "no matches" (exit 1, fine) from real errors (exit 2+, hard-fail with a message). No 2>/dev/null || true.

CI integration

New Plugin Test Quality job in .github/workflows/ci.yml:

  • Runs on every PR, not gated on should_build — policy/script/CONTRIBUTING changes need linting too
  • Listed in the build aggregator's needs: with an explicit if [[ result != "success" ]]; then exit 1 — so branch protection on build enforces it as a real merge gate

Pre-push hook

Wired into .pre-commit-config.yaml as a pre-push stage so contributors catch violations locally before opening a PR. Sub-second cost.

Test tightening (knock-on)

Two existing assertions in native_plugins_test.rs (test_no_unused_warns_on_unused_account, test_zerosum_requires_config) used assert!(!output.errors.is_empty(), ...). Tightened to assert_eq!(output.errors.len(), 1, ...) to match the new lint and the spirit of the policy.

Verified

$ ./scripts/check-plugin-test-quality.sh
=== Checking plugin-test-quality policies ===

[1/2] weak count assertions
  OK

[2/2] '(partial)' test port labels
  OK

=== All plugin-test-quality policies pass ===

The single legitimate assert!(... >= N) in the test file is test_registry_list_all — annotated with // allow weak-count: registry-shape test per the policy. All 88 native_plugins_test tests pass after the assertion tightening.

Related

🤖 Generated with Claude Code

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

github-actions Bot commented May 5, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 32ms ± 0.4ms 21.4 MB
beancount 796.8ms ± 8.7ms 50.3 MB
Comparison 24.9x faster 2.4x less

vs main branch (2026-05-05)

Metric main this PR Change
Time 32.2ms 32ms -0.6% ✅
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 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 is Phase 5 of the #992 plugin-testing-quality plan: it codifies plugin test-quality policies (docs + CI lint) and further reduces drift risk by centralizing implicit-price math into a shared core helper used by both the query path and the native implicit_prices plugin.

Changes:

  • Add rustledger_core::extract_per_unit_price (with unit tests) and refactor both the query price path and the native plugin to use it.
  • Strengthen implicit_prices plugin tests to assert strict emitted outputs across @, @@, cost, and “none” cases.
  • Add a new scripts/check-plugin-test-quality.sh lint and wire it into CI, plus document plugin testing requirements in CONTRIBUTING.md.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
scripts/check-plugin-test-quality.sh Adds a lint script to flag weak count assertions and (partial) test port labels.
crates/rustledger-query/src/price.rs Refactors implicit price extraction to use the shared core helper.
crates/rustledger-plugin/tests/native_plugins_test.rs Replaces weak-count plugin assertions with strict emitted-price assertions and adds more cases.
crates/rustledger-plugin/src/native/plugins/implicit_prices.rs Refactors plugin to delegate per-unit math to the shared helper.
crates/rustledger-core/src/lib.rs Exposes the new implicit_prices module and re-exports the helper.
crates/rustledger-core/src/implicit_prices.rs Introduces the shared per-unit extraction helper with tests.
CONTRIBUTING.md Documents the new plugin testing policies and requirements.
.github/workflows/ci.yml Adds a CI job to run the new plugin-test-quality lint.

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

Comment thread scripts/check-plugin-test-quality.sh Resolved
Comment thread scripts/check-plugin-test-quality.sh Resolved
Comment thread CONTRIBUTING.md Resolved
Comment thread scripts/check-plugin-test-quality.sh Resolved
Comment thread .github/workflows/ci.yml Resolved
Comment thread CONTRIBUTING.md Resolved
@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!

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
robcohen force-pushed the feat/plugin-testing-policy branch from cae66cd to d889857 Compare May 5, 2026 16:48
robcohen and others added 2 commits May 5, 2026 12:40
…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]>
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
robcohen force-pushed the feat/plugin-testing-policy branch from d889857 to 48496c7 Compare May 5, 2026 17:42
robcohen and others added 2 commits May 5, 2026 13:07
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]>
… 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]>
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