Skip to content

feat(compat): plugin differential harness via BQL fixtures (Phase 2 of #992 plan) - #1000

Merged
robcohen merged 5 commits into
mainfrom
feat/plugin-differential-harness
May 5, 2026
Merged

robcohen merged 5 commits into
mainfrom
feat/plugin-differential-harness

Conversation

@robcohen

@robcohen robcohen commented May 5, 2026 •

Copy link
Copy Markdown
Member

Phase 2 of the plugin-testing-quality plan (see #992).

Summary

Extends the existing BQL compat harness to surface plugin-emitted directives, so divergences between rledger's and bean-check's plugin implementations show up as BQL mismatches at PR time — no new infrastructure needed.

Approach: leverage what's already there

The compat-bql-test.py harness already runs bean-query and rledger query against every fixture in tests/compatibility/files/. Plugin fixtures with plugin "..." directives load with that plugin enabled in BOTH tools; we just need:

  1. Fixtures under tests/compatibility/files/plugins/<plugin>/ that exercise specific plugin code paths.
  2. BQL queries that surface plugin output (e.g. SELECT * FROM #prices).
  3. Plugin fixtures prioritized in the harness's MAX_FILES sampling so they always get tested.

That's the whole change. ~50 LoC in the script + 3 fixtures.

Fixtures (implicit_prices)

  • cost_only.beancount — {cost} path, expect 2 prices
  • total_annotation.beancount — @@ path (issue [Compat]: implicit price is wrong #992 reproducer), expect 1 price
  • annotation_and_cost.beancount — both present, annotation wins, expect 2 prices total

Script changes

  • Two new BQL queries in bql-queries.toml:
  • Plugin-fixture prioritization done by resolved Path, not basename. The upstream check workflow's JSONL stores file_path.name only, so the original startswith("plugin/") filter against basenames never matched. Fixed by resolving every basename to a Path via find_file first, then prioritizing on "plugins" in path.parts.
  • MIN_CORPUS_SIZE bumped 13 → 15 for the new queries

Directory layout & gitignore

  • Fixtures live at tests/compatibility/files/plugins/<plugin>/ (matches the existing per-category convention used by .github/workflows/compat.yml::get_category so they count toward the plugins per-category metric, not other).
  • .gitignore un-ignores !plugins/, !plugins/**/, AND !plugins/**/*.beancount — the middle **/ is required so Git can recurse into nested per-plugin subdirectories. Without it, git add would silently skip new fixture dirs unless invoked with -f.
  • README documents the in-tree-fixture exception with a "How to add a new plugin's fixtures" subsection.

Verified locally — caught the #992 bugs against pre-#997 rledger

The harness was developed against rledger v0.14.1 (pre-#997). All three #992 bug shapes surfaced as BQL mismatches:

total_annotation.beancount     count-prices-from-plugin: py=1 rs=2  ← @@ bug
cost_only.beancount            count-prices-from-plugin: py=2 rs=4  ← double-emit bug
annotation_and_cost.beancount  count-prices-from-plugin: py=2 rs=5  ← both bugs

Now that #997 has merged, this PR's harness functions as a regression test for #997 AND a forward-going divergence detector for any future plugin work. CI runs the harness on every PR and any new mismatch fails the job.

CI

.github/workflows/compat.yml already runs the BQL harness on every PR. Adding fixtures + queries automatically extends coverage. No workflow changes needed.

Future plugins

To add coverage for another plugin (e.g. sell_gains, unrealized):

  1. Drop fixtures under tests/compatibility/files/plugins/<name>/
  2. Optionally add queries to bql-queries.toml that surface that plugin's directives

The harness handles the rest. This replaces a lot of Phase 1 manual test-port work with mechanical comparison.

Related

🤖 Generated with Claude Code

Copilot AI review requested due to automatic review settings May 5, 2026 13:51
@robcohen
robcohen requested a review from a team as a code owner May 5, 2026 13:51

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

Extends the existing compatibility BQL harness so plugin-generated directives, especially implicit_prices, can be compared between bean-query and rledger during normal CI. This fits into the broader compatibility test suite by turning the #992 bug class into a differential regression check without adding a separate test runner.

Changes:

  • Adds three in-repo implicit_prices fixtures covering cost-only, @@ total annotation, and annotation-vs-cost precedence.
  • Adds two #prices BQL queries to surface plugin-emitted prices in the existing corpus.
  • Updates the harness and fixture tracking so plugin fixtures are intended to stay in the sampled file set and in git.

Reviewed changes

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

Show a summary per file
File Description
tests/compatibility/files/plugin/implicit_prices/total_annotation.beancount New reproducer fixture for the @@ total-price bug from #992.
tests/compatibility/files/plugin/implicit_prices/cost_only.beancount New fixture covering cost-derived implicit price emission.
tests/compatibility/files/plugin/implicit_prices/annotation_and_cost.beancount New fixture covering annotation precedence over cost and double-emit regression.
tests/compatibility/files/.gitignore Starts tracking in-repo plugin fixtures under the compatibility corpus tree.
tests/compatibility/bql-queries.toml Adds two new #prices queries for plugin directive comparison.
scripts/compat-bql-test.py Raises the corpus floor and changes file selection to try to prioritize plugin fixtures.

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

Comment thread scripts/compat-bql-test.py Resolved
Comment thread tests/compatibility/files/.gitignore Resolved
Comment thread tests/compatibility/files/.gitignore Resolved
Comment thread tests/compatibility/files/.gitignore 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!

@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 added a commit that referenced this pull request May 5, 2026
…Phase 5 of #992 plan)

Standing policy and CI gate for the bug class that produced #992.

## CONTRIBUTING.md additions

New "Plugin testing requirements" section codifies:

1. Test matrix, not "happy path" — cover every input variant
2. Strict count assertions (`assert_eq!`, never `>=`) — `>= N` accepts
   both correct emission AND over-emission, which is exactly how #992
   shipped (the original test was `assert!(price_count >= 1)`)
3. No `(partial)` test ports — port the whole upstream test or
   document each skipped case
4. Differential coverage where applicable — drop a fixture under
   `tests/compatibility/files/plugin/<name>/` and the harness from
   PR #1000 picks it up automatically
5. Type-driven exhaustive matching — use `match` on enum-shaped
   inputs, don't manually extract a discriminator

For numeric plugins specifically: at least one proptest case covering
an algebraic invariant (round-trip, sum-invariance, etc.).

## scripts/check-plugin-test-quality.sh

CI lint that enforces the two most mechanical policies:

- Weak count assertions (`assert!(... >= N)` / `> N`).
- `(partial)` test port labels.

Has an explicit allowlist mechanism: prefix the assertion with
`// allow weak-count: <reason>` to opt out (e.g. registry-shape tests
where the count grows with each plugin addition).

awk-based block parsing so it can read up to 5 lines of leading
comments to find the allow annotation.

## CI integration

New `Plugin Test Quality` job in .github/workflows/ci.yml runs the
script on every PR. Sits next to the existing Unsafe Invariant check.
Fast (sub-second), no compilation dependency.

## Test file allowlist

The single legitimate `assert!(... >= N)` in the test file is the
registry-list test (`assert!(plugins.len() >= 13)`) — count grows as
plugins are added. Annotated with `// allow weak-count: registry-shape
test` per the new policy.

## Stacked on #997

This PR depends on #997 (Phase 0a fix) — that PR rewrites the
implicit_prices test, removing the `(partial)` label that would
otherwise fail policy 2. After #997 merges, the rebase is clean.

## Related

- #992 — the bug that motivated the plan
- #997 — Phase 0a fix
- #998 — Phase 0b audit (Phase 1 backlog)
- #999 — Phase 0c type-safety view enum
- #1000 — Phase 2 differential harness

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 5, 2026
…Phase 5 of #992 plan)

Standing policy and CI gate for the bug class that produced #992.

## CONTRIBUTING.md additions

New "Plugin testing requirements" section codifies:

1. Test matrix, not "happy path" — cover every input variant
2. Strict count assertions (`assert_eq!`, never `>=`) — `>= N` accepts
   both correct emission AND over-emission, which is exactly how #992
   shipped (the original test was `assert!(price_count >= 1)`)
3. No `(partial)` test ports — port the whole upstream test or
   document each skipped case
4. Differential coverage where applicable — drop a fixture under
   `tests/compatibility/files/plugin/<name>/` and the harness from
   PR #1000 picks it up automatically
5. Type-driven exhaustive matching — use `match` on enum-shaped
   inputs, don't manually extract a discriminator

For numeric plugins specifically: at least one proptest case covering
an algebraic invariant (round-trip, sum-invariance, etc.).

## scripts/check-plugin-test-quality.sh

CI lint that enforces the two most mechanical policies:

- Weak count assertions (`assert!(... >= N)` / `> N`).
- `(partial)` test port labels.

Has an explicit allowlist mechanism: prefix the assertion with
`// allow weak-count: <reason>` to opt out (e.g. registry-shape tests
where the count grows with each plugin addition).

awk-based block parsing so it can read up to 5 lines of leading
comments to find the allow annotation.

## CI integration

New `Plugin Test Quality` job in .github/workflows/ci.yml runs the
script on every PR. Sits next to the existing Unsafe Invariant check.
Fast (sub-second), no compilation dependency.

## Test file allowlist

The single legitimate `assert!(... >= N)` in the test file is the
registry-list test (`assert!(plugins.len() >= 13)`) — count grows as
plugins are added. Annotated with `// allow weak-count: registry-shape
test` per the new policy.

## Stacked on #997

This PR depends on #997 (Phase 0a fix) — that PR rewrites the
implicit_prices test, removing the `(partial)` label that would
otherwise fail policy 2. After #997 merges, the rebase is clean.

## Related

- #992 — the bug that motivated the plan
- #997 — Phase 0a fix
- #998 — Phase 0b audit (Phase 1 backlog)
- #999 — Phase 0c type-safety view enum
- #1000 — Phase 2 differential harness

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 5, 2026
… 5 of #992 plan) (#1001)

* ci(plugin-tests): codify plugin-test-quality policies + lint script (Phase 5 of #992 plan)

Standing policy and CI gate for the bug class that produced #992.

## CONTRIBUTING.md additions

New "Plugin testing requirements" section codifies:

1. Test matrix, not "happy path" — cover every input variant
2. Strict count assertions (`assert_eq!`, never `>=`) — `>= N` accepts
   both correct emission AND over-emission, which is exactly how #992
   shipped (the original test was `assert!(price_count >= 1)`)
3. No `(partial)` test ports — port the whole upstream test or
   document each skipped case
4. Differential coverage where applicable — drop a fixture under
   `tests/compatibility/files/plugin/<name>/` and the harness from
   PR #1000 picks it up automatically
5. Type-driven exhaustive matching — use `match` on enum-shaped
   inputs, don't manually extract a discriminator

For numeric plugins specifically: at least one proptest case covering
an algebraic invariant (round-trip, sum-invariance, etc.).

## scripts/check-plugin-test-quality.sh

CI lint that enforces the two most mechanical policies:

- Weak count assertions (`assert!(... >= N)` / `> N`).
- `(partial)` test port labels.

Has an explicit allowlist mechanism: prefix the assertion with
`// allow weak-count: <reason>` to opt out (e.g. registry-shape tests
where the count grows with each plugin addition).

awk-based block parsing so it can read up to 5 lines of leading
comments to find the allow annotation.

## CI integration

New `Plugin Test Quality` job in .github/workflows/ci.yml runs the
script on every PR. Sits next to the existing Unsafe Invariant check.
Fast (sub-second), no compilation dependency.

## Test file allowlist

The single legitimate `assert!(... >= N)` in the test file is the
registry-list test (`assert!(plugins.len() >= 13)`) — count grows as
plugins are added. Annotated with `// allow weak-count: registry-shape
test` per the new policy.

## Stacked on #997

This PR depends on #997 (Phase 0a fix) — that PR rewrites the
implicit_prices test, removing the `(partial)` label that would
otherwise fail policy 2. After #997 merges, the rebase is clean.

## Related

- #992 — the bug that motivated the plan
- #997 — Phase 0a fix
- #998 — Phase 0b audit (Phase 1 backlog)
- #999 — Phase 0c type-safety view enum
- #1000 — Phase 2 differential harness

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

* fix(ci): address Copilot review on plugin-test-quality (#1001)

Three classes of fixes from Copilot review:

1. Lint script regex was too narrow:
   - Caught x.count() >= N only with a leading space before the operator
     (missed x.count()>=N)
   - Missed precomputed counts like assert!(price_count >= 1) — which
     was the EXACT shape of the #992 bug. The new regex matches three
     forms: method calls, no-whitespace variants, and precomputed
     *_count/*_len/*_size (or bare count/len/size) idents.

2. Lint script awk block parser dropped violations when multiple
   matches fell inside the same grep -B 5 context window. Replaced
   with a bash loop that does an explicit per-match sed lookback. Also
   covers the new precomputed-count pattern, which the awk block
   couldn't have matched anyway.

3. CI gate gap: plugin-test-quality ran but wasn't in the build
   aggregator needs list, so branch protection enforcing only build
   would let policy violations merge. Added it to needs, added an
   explicit success check, and removed its should_build gate so it
   also runs on docs-only / policy-only PRs (which are precisely the
   PRs that touch the lint script).

Also corrected two CONTRIBUTING.md inaccuracies:
  - PriceAnnotationData::view() example referred to an API that
    doesn't exist on this branch (it is introduced in PR #999).
    Reworded so the rule is API-agnostic and the example is flagged
    as forward-looking.
  - Mutation-survival ≤ 10% claim said CI enforces — currently CI
    runs cargo mutants and warns; the blocking gate is Phase 3 work.

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

* fix(ci): address all items from second deep review of #1001

Seven items, fixed in one commit since they all touch the same lint
script + its policy doc:

1. **No more `2>/dev/null || true`** (the blocking item). Per
   `feedback_no_error_swallowing.md`, this idiom previously caused
   two npm releases to silently fail. The script now:
   - Hard-fails up front if `TESTS_DIR` doesn't exist (was: silent
     pass, because grep + missing dir + `|| true` reported "OK")
   - Wraps grep in a `grep_or_die` helper that distinguishes exit 1
     ("no matches", fine) from exit 2+ ("real error", abort with a
     descriptive message)

2. **Pre-push hook wired in**. Script's docstring claimed it ran as
   a pre-push step but no `.pre-commit-config.yaml` entry existed.
   Added one — sub-second cost, runs alongside the existing
   cargo-check + unsafe-invariant pre-push hooks.

3. **Lint coverage extended to two more weak-assertion shapes** that
   are semantically identical to the #992 bug:
   - `assert_ne!(x.len(), 0)` (and precomputed-count variants)
   - `assert!(!x.is_empty())`
   Combined with the existing `>=`/`>` shape, the lint now catches
   all three forms of "accept 1 OR 100 emissions".

4. **`(partial)` lint tightened to specific shape**. Was a broad
   `(partial)` substring match — would false-positive on unrelated
   comments like `(partial overlap with foo)`. Now matches the
   historical bad pattern `Converted from … (partial)` only, with
   `// allow partial: <reason>` as an opt-out for the rare false
   positive.

5. **Robust path parsing**. Replaced `${match%%:*}` parameter
   expansion (which assumed no `:` in file paths) with
   `IFS=: read -r file lineno _` which is equally portable and
   handles any path correctly.

6. **PR description updated** (separate, via `gh pr edit`) — the old
   description still claimed "awk-based block parsing" which was
   replaced with bash-loop + sed in the previous round.

7. **Removed redundant `[[:space:]]*`** after `[^)]*` in the regex
   (the latter already matches whitespace greedily).

Knock-on test changes: extending the lint to catch
`assert!(!output.errors.is_empty(), ...)` flagged two existing
sites in `native_plugins_test.rs`:

- `test_no_unused_warns_on_unused_account` — tightened to
  `assert_eq!(output.errors.len(), 1, "exactly one error for the
  single unused account")`. The follow-up `iter().any(...)` check
  was simplified to `errors[0].message.contains(...)` since we know
  the count exactly now.
- `test_zerosum_requires_config` — same tightening pattern.

Both tests still pass (verified with full `cargo test -p
rustledger-plugin --test native_plugins_test`: 88 passed, 0 failed).

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

* test(ci): self-test the plugin-test-quality lint + close two coverage gaps

Three follow-up items from the third deep review of #1001:

1. **Self-test for the lint script** (the most important addition).
   The regexes are now non-trivial enough that a typo or accidental
   pattern deletion would silently disable detection. A new
   `scripts/test-plugin-test-quality.sh` generates synthetic test
   files in a temp dir, points the lint at them via `TESTS_DIR`,
   and asserts that each known-bad shape is caught and each
   known-clean shape is not.

   21 cases total covering: all four weak-assert shapes, the
   allow-annotation opt-out (with reason and without), positive
   shapes that must NOT fire, the partial-port shape and its
   false-positive guard, and the missing-`TESTS_DIR` hard-fail
   regression test.

   Wired into the existing `Plugin Test Quality` CI job as a
   pre-step so a broken lint script fails CI before the lint
   itself runs.

   Required a small change to the lint script: `TESTS_DIR` is now
   read from the env (defaulting to the real tests dir) so the
   self-test can override it.

2. **Allow annotations now require a non-empty reason**. Pre-fix,
   `// allow weak-count:` (no reason) would silently bypass the
   lint. The whole point of the opt-out is to force the author to
   articulate WHY a weak assertion is acceptable. Tightened
   `has_allow_above` from `grep -q "$annotation"` to
   `grep -qE "${annotation}:[[:space:]]*\S"` — annotation followed
   by `:` followed by at least one non-whitespace character.

   The existing `// allow weak-count: registry-shape test — ...`
   annotation in `test_registry_list_all` still passes (verified).

3. **Fourth weak-assert shape caught**: `assert!(x.len() != 0)` /
   `assert!(price_count != 0)` — semantically identical to shape B
   (`assert_ne!`) but written as an inequality. Doesn't exist in
   the codebase today but the self-test pins it so a future
   contributor can't accidentally introduce the gap.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
robcohen and others added 4 commits May 5, 2026 13:57
…#992 plan)

Extends the existing BQL compat harness (scripts/compat-bql-test.py)
to surface plugin-emitted directives, so divergences between rledger's
and bean-check's plugin implementations show up as BQL mismatches at
PR time — no new infrastructure needed.

## Approach: leverage the existing harness

The compat-bql-test.py harness already runs bean-query and rledger
query against every fixture in tests/compatibility/files/. Plugin
fixtures with `plugin "..."` directives load with that plugin enabled
in BOTH tools; we just need:

1. Fixtures under `tests/compatibility/files/plugin/<plugin>/` that
   exercise specific plugin code paths.
2. BQL queries that surface plugin output (e.g. `SELECT * FROM #prices`
   for plugins that emit Price directives).
3. Plugin fixtures prioritized in the harness's MAX_FILES sampling
   so they always get tested.

That's the whole change. ~50 LoC in the script, plus 3 fixtures.

## Fixtures (implicit_prices, the #992 motivator)

- cost_only.beancount: plain `{cost}` path, expect 2 prices
- total_annotation.beancount: `@@` path (issue #992), expect 1 price
- annotation_and_cost.beancount: both present, annotation wins,
  expect 2 prices total

Script changes:

- Two new BQL queries: count-prices-from-plugin (catches
  double-emit / missing-emit) and prices-from-plugin-by-date (catches
  @@ vs @ confusion).
- Plugin-fixture prioritization: plugin/* fixtures bypass the random
  --max-files truncation. Without this, 3 plugin fixtures could be
  excluded from a 30-file sample.
- MIN_CORPUS_SIZE bumped from 13 → 15 for the new queries.

## Verified locally

Ran the harness against all three fixtures using rledger v0.14.1+
(pre-#997 — the buggy version). The harness flagged every bug:

  total_annotation.beancount  count-prices-from-plugin: py=1 rs=2
  cost_only.beancount         count-prices-from-plugin: py=2 rs=4
  annotation_and_cost.beancount count-prices-from-plugin: py=2 rs=5

After #997 lands, these mismatches will all resolve to 0. The
harness is a regression test for #997 and a forward-going
divergence detector for any future plugin work.

## Wiring into CI

The existing .github/workflows/compat.yml already runs the BQL
harness on every PR. Adding fixtures + queries automatically extends
coverage without changes to the workflow file. CI will diff plugin
output the next time it runs.

## Future plugins

To add coverage for another plugin (e.g. sell_gains, unrealized):

1. Drop fixtures under `tests/compatibility/files/plugin/<name>/`.
2. Optionally add queries to bql-queries.toml that surface that
   plugin's emitted directives.

The harness handles the rest. Mirrors Phase 1 of the plugin-testing
plan but with mechanical comparison instead of manual test ports.

## Related

- #992 — the bug that motivated the plan
- #997 — Phase 0a fix
- #998 — Phase 0b audit
- #999 — Phase 0c type-safety view enum

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The previous commit added the harness wiring but the fixture files
themselves were silently rejected by the .gitignore that excludes
the (downloaded) compat corpus. Whitelist plugin/** so in-tree
fixtures ship with the repo.

Three implicit_prices fixtures committed:
- cost_only.beancount
- total_annotation.beancount (issue #992 reproducer)
- annotation_and_cost.beancount (the double-emit case)

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

1. **Plugin-fixture prioritization actually works now.** Pre-fix the
   filter `f.startswith("plugin/")` ran against `valid`, which is a
   list of basenames (the upstream check workflow stores
   `file_path.name` only — `.github/workflows/compat.yml` does
   `FileResult(file=file_path.name, ...)`). The filter never matched,
   so plugin fixtures could be silently dropped by `--max-files`.

   Restructured: resolve every basename to a Path via `find_file`
   FIRST, then prioritize on the resolved Path's `.parts` containing
   `"plugins"`. Verified with `--max-files 2` against 3 plugin
   fixtures: harness now correctly reports
   "Testing against 3 files (3 plugin fixtures + 0 other)".

   Side effect: this also addresses the silent-collision risk in
   `find_file` (issue #5 from the review) — basenames are resolved
   exactly once, and the resolved path is what we work with from
   then on.

2. **Renamed `plugin/` → `plugins/`** to match the existing per-
   category convention used by `.github/workflows/compat.yml`'s
   `get_category` (line 198). Pre-fix these fixtures were classified
   as `other` in the per-category dashboard; now they correctly land
   in `plugins`.

3. **README updated** to reflect that `plugins/` is committed
   in-tree (an exception to the rest of `files/` which is downloaded
   on demand via `fetch-compat-test-files.sh`). Added a "How to add
   a new plugin's fixtures" subsection.

4. **`.gitignore` un-ignores intermediate directories** under
   `plugins/`. Pre-fix only `!plugins/` and `!plugins/**/*.beancount`
   were set, but Git's "cannot re-include a file if a parent dir is
   excluded" rule meant new nested dirs (e.g.
   `plugins/<new_plugin>/`) were still ignored — the existing
   `implicit_prices/` dir only worked because someone presumably
   used `git add -f` originally. Added `!plugins/**/` so adding new
   plugin subdirectories works mechanically.

   Verified: `mkdir plugins/synthetic_test && touch
   plugins/synthetic_test/foo.beancount && git status` now shows
   the file as untracked (was: silently ignored).

5. (Knock-on) Updated callers that referenced the old path:
   `CONTRIBUTING.md` (2 occurrences) and `tests/compatibility/
   bql-queries.toml` (1 comment) both rewritten plugin/ → plugins/.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen force-pushed the feat/plugin-differential-harness branch from bf37085 to f05a1a5 Compare May 5, 2026 19:05
@robcohen
robcohen merged commit 2e2566f into main May 5, 2026
30 of 31 checks passed
@robcohen
robcohen deleted the feat/plugin-differential-harness branch May 5, 2026 19:19
robcohen added a commit that referenced this pull request May 8, 2026
…back (#1033)

* fix(query): per-currency precision through PIVOT via column-name fallback

Closes #1023.

PR #1022 fixed #988 (SUM-aggregate text output matching bean-query's
per-currency precision) by carrying the GROUP BY currency in a per-row
sidecar. PIVOT regressed it: `apply_pivot` builds new rows via
`add_row` (not `add_aggregate_row`), so the sidecar drops to `None`
and the renderer can't recover the precision context.

After PIVOT, the GROUP BY currency moves into column position — each
pivoted column's name IS the currency code. The renderer can read it
from there.

Implementation:
- New `column_currency_hints` precomputed once per write_text invocation,
  symmetrical to the existing `currency_hints` row sidecar lookup. Uses
  the same `looks_like_currency` + `ctx.get_precision().is_some()`
  guard, so an untracked column-named "USD" still falls back safely
  (without the guard, `DisplayContext::format` strips trailing zeros
  via `normalize()`, making output WORSE than the unfixed state).
- Per-cell hint resolution: row sidecar wins over column-name fallback
  (the sidecar came from the actual GROUP BY key; the column name is a
  heuristic). Width-calc and print passes use the same precedence so
  rendered widths match rendered values.

Bonus: pre-existing column/row length mismatch in `apply_pivot`. The
column header included the value column ("SUM") but the row builder
explicitly excluded it from `group_cols`, leaving rows one cell short.
JSON output silently dropped the SUM cell. Fixed by also excluding
`value_col_idx` from `new_columns` so columns and rows agree on shape.
This blocked the e2e PIVOT test for #1023, so it had to be fixed here
rather than as a separate issue.

Tests:
- 3 new unit tests in `cmd::query::output::tests`:
  - `test_text_pivoted_column_uses_column_name_as_currency_hint`
  - `test_text_pivoted_column_with_untracked_currency_falls_back_safely`
    — pins the false-positive guard
  - `test_row_sidecar_wins_over_column_name_fallback`
- 1 new e2e test through Executor + write_text.
- New BQL compat fixture `sum-by-account-pivot-by-currency` in
  bql-queries.toml so #1000's harness catches future regressions.

511 query tests + 18 renderer tests pass. Clippy + fmt clean.

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

* test(query): address self-review on #1033

Five real concerns from the deep review, plus the pre-existing items
filed as #1034 follow-up.

- `resolve_cell_hint` helper: width-calc and print pass now share one
  function for the row-then-column precedence. Was duplicated with a
  "must match" comment — exactly the invariant a helper locks in.
- Multi-currency PIVOT test (`test_text_pivoted_multi_currency_uses_per_column_precision`):
  USD (2dp) + JPY (0dp) on the same row, each pivoted column uses its
  own precision. The implementation always handled this correctly; now
  pinned by a test.
- Defensive regression test (`test_non_pivoted_currency_named_column_inherits_fallback_quantization`):
  pins behavior of a non-pivoted query whose column happens to be aliased
  as a tracked currency code. Today's contract is that the fallback DOES
  apply — same as PIVOT. Future tightening would be a deliberate change.
- Compat fixture removed from `bql-queries.toml`. Local verification
  against bean-query revealed bean-query's `PIVOT BY` takes TWO columns
  (pivot value + group key) where rledger takes ONE — the tools produce
  structurally different output, so a row-by-row diff would be
  permanently red. Replaced the fixture with a comment pointing to #1034
  where the reconciliation is tracked.
- PR body updated to call out the apply_pivot column-shape fix as a
  user-visible behavioral change for ALL PIVOT queries (pre-fix the SUM
  column was eating the pivoted USD value, USD column was empty).

Pre-existing items 6+7 from the review (empty-columns underflow,
degenerate value==pivot case) filed as #1034.

20 renderer tests pass. Clippy + fmt clean.

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

* fix(query): use targets.len() for value_col_idx in apply_pivot

Address Copilot review on #1033: `apply_pivot` was using
`result.columns.len() - 1` to find the value column, which incorrectly
identifies a hidden ORDER BY column as the value column when the
caller has appended hidden cols (via `find_hidden_order_by_targets`
in execute_select). Fix uses `targets.len() - 1` (last visible target),
since hidden cols are always appended AFTER the visible select
targets.

Defensive `targets.is_empty()` fallback retains the old behavior
rather than panicking — the parser/planner should reject pivot_by
with empty targets, but the function shouldn't trust that.

Surfaced a deeper related bug while writing a regression test: the
strip-hidden-columns step in execute_select truncates from the END
post-PIVOT, but apply_pivot moves hidden cols out of trailing
position into group_cols, so the strip removes the pivot value column
instead. That bug is orthogonal to value_col_idx — both need fixing
for PIVOT + ORDER BY (hidden) to work correctly. Filed as item 4 on
#1034 alongside the other PIVOT robustness gaps from the review.

The value_col_idx fix on its own is correct and necessary; without it
the hidden column's values end up in pivoted output cells (e.g. dates
where SUM values should be). The strip bug just means we can't easily
write a passing integration test for the combined path until #1034
item 4 lands.

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

* fix(query): backtick group_key in test doc to satisfy clippy doc-markdown

CI clippy runs `--all-targets` which catches doc-comment lints in test
modules; my local clippy run only covered the lib targets and missed
this one. The fix is one missing pair of backticks around `group_key`
in the new pivoted-column test's docstring.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants