Skip to content

test(compat): add a capital-gains fuzzer, gated in CI - #2127

Merged
robcohen merged 2 commits into
mainfrom
feat/capgains-fuzzer
Aug 24, 2026
Merged

robcohen merged 2 commits into
mainfrom
feat/capgains-fuzzer

Conversation

@robcohen

Copy link
Copy Markdown
Member

report capgains produces numbers people put on a tax return and had no generative coverage at all — the word does not appear anywhere in scripts/ or tests/ tooling. It also classifies each closed lot from the surviving lot's acquisition date, so it consumes whatever booking decides, and booking produced two real bugs in the last few weeks (#2097, #2115). A wrong term, or a lot attributed to the wrong acquisition, still balances, still reports no error, and still looks entirely plausible.

beancount has no capgains report, so there is no differential partner. This checks properties and the binary against itself, the way compat-budget-fuzz.py checks the budget report:

  • gain == proceeds - cost_basis, per row
  • the term buckets partition the disposals exactly, by count and by sum — a row that reaches neither bucket vanishes from the totals a reader looks at while every individual row still checks out
  • held_days == sold - acquired
  • --year Y returns the disposals sold in Y and nothing else
  • --long-term-days N is exactly "held > N days", which is checkable; the default calendar rule is a different function, so the two are compared against each other and may differ only where a leap day falls in the span

Deliberately not asserted: a hard answer for a 29 February acquisition. The one-year anniversary of 2020-02-29 is genuinely ambiguous, conventions differ, and asserting a guess would encode this script's opinion as the specification. Those spans are generated and reported under --leap-report.

Result: 1000 seeds, zero findings

Recording that as a negative result rather than quietly moving on. The arithmetic, the partition, held_days, both term rules and the year filter all hold over ~2500 disposals.

A clean sweep is worthless without evidence the harness can fail, so: --self-test plants six malformed reports and requires each to be caught, and blinding check_report to return [] fails five of them. Coverage was measured rather than assumed — 766 disposals over 300 seeds, 481 short / 285 long, 426 within 360–372 days of the boundary, 109 leap-day acquisitions, all four booking methods represented.

Two things came out of building it

The generator oversold. It drew sale quantities from the ledger total rather than from what was held on the sale date, so 9% of runs died on Not enough units — ledgers rledger rightly refuses, which tests nothing and hides how much coverage was lost. Capping by units available at the sale date took errors 27 → 0, disposals 682 → 766, near-boundary cases 368 → 426.

A dependency behaviour was unpinned. is_long_term rests on jiff resolving a Feb-29 acquisition to Feb-28 — the module comment says so, and nothing checked it. long_term_calendar_rule_handles_leap_year uses a span that crosses a leap day, which is a different thing from a lot bought on one. A jiff upgrade resolving to Mar-1 instead would move the boundary a day and silently change the term of every affected disposal, on a figure that goes to a tax return.

Now pinned. The mutation matters here: a general one-day shift of the anniversary is caught by the existing test and proves nothing about this case, so I used a Feb-29-specific mutation (resolve to Mar-1) — that fails the new test and only the new test.

CI

Wired into compat.yml following the booking and budget fuzzers exactly — --self-test first, then the sweep, continue-on-error with the verdict in a step output, and a separate gate carrying a reproduce command. 400 seeds on a PR (~15s), 2000 nightly from the run id. actionlint reports the same three findings as main, none in the new steps.

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

`report capgains` produces numbers people put on a tax return and had NO
generative coverage: the word does not appear anywhere in scripts/ or
tests/ tooling. It also classifies each closed lot from the SURVIVING lot's
acquisition date, so it consumes whatever booking decides -- and booking
produced two real bugs in the last few weeks (#2097, #2115). A wrong term
or a lot attributed to the wrong acquisition still balances, still reports no error, and still
looks entirely plausible.

beancount has no capgains report, so there is no differential partner. This
checks properties and the binary against itself, the way the budget fuzzer
does:

  - gain == proceeds - cost_basis, per row
  - the term buckets partition the disposals exactly, by count and by sum
  - held_days == sold - acquired
  - `--year Y` returns the disposals sold in Y and nothing else
  - `--long-term-days N` is exactly "held > N days", which is checkable;
    the DEFAULT calendar rule is a different function, so the two are
    compared and may differ ONLY where a leap day falls in the span

Deliberately not asserted: a hard answer for a 29 February acquisition. The
anniversary is genuinely ambiguous and asserting a guess would encode this
script's opinion as the specification. Those spans are generated and
reported under `--leap-report`.

RESULT: 1000 seeds, zero findings. Recording that as a negative result --
the arithmetic, the partition, held_days, both term rules and the year
filter all hold over ~2500 disposals.

Two things did come out of building it.

The generator first oversold: it drew quantities from the ledger total
rather than from what was held ON THE SALE DATE, so 9% of runs died on
"Not enough units" -- ledgers rledger rightly refuses, testing nothing.
Capping by units available at the sale date took errors 27 -> 0, disposals
682 -> 766 and near-boundary cases 368 -> 426 over 300 seeds.

And `is_long_term` rests on jiff resolving a Feb-29 acquisition to Feb-28,
which the module comment states and nothing checked:
`long_term_calendar_rule_handles_leap_year` uses a span that CROSSES a leap
day, not a lot bought ON one. A jiff upgrade resolving to Mar-1 instead
would move the boundary a day and silently change the term of every
affected disposal. Pinned now -- and a Feb-29-specific mutation fails the
new test and only it, where a general one-day shift is caught by the
existing test and proves nothing about this case.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen requested a review from a team as a code owner August 24, 2026 11:53
Copilot AI lite review requested due to automatic review settings August 24, 2026 11:53
@codecov

codecov Bot commented Aug 24, 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 Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 48.4ms ± 6.9ms 711.4ms ± 5.3ms 14.7x 55.1 MB / 50.0 MB
investment 67.5ms ± 1.5ms 2757.9ms ± 31.8ms 40.9x 58.9 MB / 58.1 MB
fifo 67.7ms ± 5.5ms 15840.9ms ± 146.2ms 234.0x 61.0 MB / 57.8 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 45.3ms ± 1.8ms 48.4ms ± 6.9ms +6.9% ✅ within noise 55.0 MB → 55.1 MB (+0.2%)
investment 67.9ms ± 3.8ms 67.5ms ± 1.5ms -0.7% ✅ within noise 59.1 MB → 58.9 MB (-0.3%)
fifo 66.3ms ± 2.9ms 67.7ms ± 5.5ms +2.2% ✅ within noise 61.1 MB → 61.0 MB (-0.2%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 3.2ms, investment 1.8ms, fifo 2.8ms), and is at least 5%.
10,000 transactions per shape · 20 runs, 3 warmup · hyperfine

What do these numbers mean?
  • simple — Two-posting transfers, one currency. The historical workload — keep as the floor, not as the benchmark.
  • investment — Cost specs, per-unit prices and lot reductions. Exercises booking and inventory, which simple leaves at 0.3%.
  • fifo — Bare {} reductions against a FIFO account — how FIFO sells are normally written. The other four shapes reach the ordered-selection path twice in 2k transactions between them, so it was effectively unprofiled until it turned out to be quadratic (plan_ordered scans every lot per reduction: FIFO ledgers are quadratic (8.8s at 20k transactions) #2083).
  • vs base: the PR and the base-branch commit it is built on, built and measured in the same job
  • RSS: peak resident set size, a single sample — reported without a verdict because there is no spread to test it against
  • A shape with no beancount column is one bean-check reports errors on; it is timed for rledger only

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

Adds property-based fuzzing for report capgains, a Feb. 29 classification regression test, and CI integration.

Changes:

  • Generates ledgers and validates capital-gains properties.
  • Pins leap-day term behavior.
  • Runs PR and nightly fuzzing with CI gating.

Reviewed changes

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

File Summary Final review comments
scripts/compat-capgains-fuzz.py Capital-gains fuzzer and property checks Three moderate issues: incomplete term partition validation (3 votes), incomplete override row comparison (2 votes), and --leap-report diagnostics incorrectly causing failures (2 votes).
crates/rustledger/src/cmd/report_cmd/capgains.rs Leap-day term-rule regression test No final comments.
.github/workflows/compat.yml CI fuzzing and failure gate No final comments.
Suppressed comments (7)

scripts/compat-capgains-fuzz.py:302

  • An empty report is accepted as clean here. gen_ledger always creates at least one positive-quantity sale (the first sale date is after the earliest lot), so a regression that drops every disposal makes check_report, both term-rule runs, and year filtering vacuous and returns no finding. Carry the expected sale/disposal count out of gen_ledger and assert it before accepting the report.
        rep = run_capgains(rledger, path, [])
        if rep == ERROR:
            # A ledger rledger refuses is not a capgains finding: booking
            # errors are the booking fuzzer's subject, not this one.
            return []

scripts/compat-capgains-fuzz.py:277

  • This only tests years observed in the unfiltered report. A generated ledger can have all sales in one year, so --year is never invoked for an empty year; an implementation returning a row for an unrelated year in that case would pass. Include a guaranteed absent year and validate the filtered summaries, not just disposal row dates and counts, to make the filter property complete.
    years = {date.fromisoformat(r["sold"]).year for r in rep.get("disposals", [])}
    problems: list[str] = []
    for year in sorted(years):
        got = run_capgains(rledger, path, ["--year", str(year)])

scripts/compat-capgains-fuzz.py:202

  • The report intentionally emits dateless AVERAGE disposals with acquired: null and held_days: null (the existing report_capgains_test.rs fixture covers this), but this oracle unconditionally calls date.fromisoformat(r["acquired"]). If the generator exercises the supported unknown-term bucket, the fuzzer crashes instead of checking it; the fixed-day oracle later also evaluates None > 365. Handle unknown rows explicitly and add a dateless/AVERAGE generated case.
        acquired = date.fromisoformat(r["acquired"])
        sold = date.fromisoformat(r["sold"])
        if r["held_days"] != (sold - acquired).days:

scripts/compat-capgains-fuzz.py:282

  • For a filtered report, this only checks that direct disposal rows have the requested year and the expected count. It never validates the filtered term summaries, so a bug that leaves all-year bucket totals in a --year Y response passes. Run check_report(got) for each filtered response before checking its rows.
        rows = got.get("disposals", [])
        stray = [r for r in rows if date.fromisoformat(r["sold"]).year != year]

scripts/compat-capgains-fuzz.py:243

  • The fixed-rule report is only checked for each row's term; its bucket counts and totals are never passed through check_report. A regression that mis-partitions or mis-summarizes --long-term-days 365 output would therefore pass the sweep even though those are the tax totals being guarded. Apply the report invariant checks to fixed as well.
    default = run_capgains(rledger, path, [])
    fixed = run_capgains(rledger, path, ["--long-term-days", "365"])
    if isinstance(default, str) or isinstance(fixed, str):
        return ["capgains failed to run"]

scripts/compat-capgains-fuzz.py:287

  • The filter oracle checks only the returned count and each row's sale year. Replacing one disposal with a different disposal from the same year—or changing its acquisition, units, basis, gain, or term—passes with the same count, despite the stated "nothing else moves" property. Compare canonicalized row multisets from the unfiltered report and the filtered report instead of only these two projections.
        rows = got.get("disposals", [])
        stray = [r for r in rows if date.fromisoformat(r["sold"]).year != year]
        if stray:
            problems.append(f"--year {year} returned {len(stray)} row(s) from another year")
        want = len([r for r in rep["disposals"] if date.fromisoformat(r["sold"]).year == year])
        if len(rows) != want:
            problems.append(f"--year {year} returned {len(rows)} row(s), unfiltered has {want}")

scripts/compat-capgains-fuzz.py:65

  • The report has a valid unknown_term case for lots without acquisition dates (for example, AVERAGE booking), but this generator selects only FIFO/LIFO/HIFO/STRICT, so no generated report can exercise that bucket. Worse, check_report assumes acquired and held_days are non-null and would raise instead of checking such a row. Either add an unknown-term generation case and make the checker handle null dates, or explicitly remove unknown from the claimed coverage.
CASH = "USD"
COMMODITIES = ["ACME", "HOOL", "CORP"]
METHODS = ["FIFO", "LIFO", "HIFO", "STRICT"]

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread scripts/compat-capgains-fuzz.py Resolved
Comment thread scripts/compat-capgains-fuzz.py Resolved
Comment thread scripts/compat-capgains-fuzz.py Resolved
@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 170 masked)
Full AST Match 100%
Total Files 811
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
    The headline is the EFFECTIVE rate, after pairs where beanquery
    itself is wrong are masked. raw is the same run with nothing
    masked. A widening gap means the registry grew, not that rledger
    changed.
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

All three reported by Copilot on #2127, all three real.

1. The partition check was not a partition check. The term buckets hold one
   summary object per CURRENCY carrying a `disposals` count, not one object
   per disposal, so `len(bucket)` counted currencies. The only count
   assertion fired when EVERY bucket was empty, and the totals loop skipped
   `unknown_term` entirely. A dropped row, a wrong `disposals` count, or a
   missing unknown-term entry all passed.

   It now compares count, proceeds, cost_basis and gain per (term, currency)
   in both directions, so a bucket with no rows behind it and rows that reach
   no bucket are both failures. The claim in the PR body that this checked
   the partition "by count and by sum" was true of the description and not of
   the code.

2. `--long-term-days 365` was compared row by row with a dict lookup, and a
   miss was treated as agreement. If the override dropped a disposal, only
   the survivors were compared and the run stayed clean. The row sets are now
   compared first, and rows present on one side only are reported.

3. `--leap-report` appended to `problems`, so the documented diagnostic mode
   made every leap-day disposal a failure and exited 1 on ledgers the
   generator produces deliberately. Those notes are now collected separately,
   printed under their own heading, and never change the verdict.

Evidence for each:

  - `--self-test` grows from 6 planted reports to 9, adding a wrong
    `disposals` count, a bucket with no rows, and unknown-term rows reaching
    no bucket. Blinding `check_report` to `return []` fails 8 of them.
  - Making `run_capgains` drop one row when `--long-term-days` is passed now
    reports the drop on every affected seed; it was silent before.
  - `--leap-report` over 60 seeds exits 0, reports 21 leap-day acquisitions
    under their own heading, and leaves the run 60/60 clean.

400 seeds, CI's PR setting: still clean.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen

Copy link
Copy Markdown
Member Author

All three correct, all three fixed in 9072fed. Taking them in turn.

1. The partition check was not a partition check. You are right that the buckets hold one summary object per currency with a disposals count, so len(bucket) counted currencies, the only count assertion fired when every bucket was empty, and the totals loop skipped unknown_term altogether. A dropped row, a wrong disposals count, or a missing unknown-term entry all passed.

Worth saying plainly: the PR body claimed this checked the partition "by count and by sum". That was true of the description and not of the code.

It now compares disposals, proceeds, cost_basis and gain per (term, currency) in both directions, so a bucket with no rows behind it and rows reaching no bucket are each a failure.

2. other is None treated a dropped row as agreement. Correct, and it is the worse of the three, because the failure it hides is exactly the kind the script exists to find. The row sets are now compared before any term comparison, and rows present on only one side are reported with an example key.

3. --leap-report failed the run it was meant to inspect. Also correct. The notes went into problems, so the documented diagnostic mode exited 1 on ledgers the generator produces on purpose. They are now collected separately, printed under their own heading, and never affect the verdict.

Evidence for each, rather than assertion

  • --self-test grows from 6 planted reports to 9, adding a wrong disposals count, a bucket with no rows behind it, and unknown-term rows reaching no bucket. Blinding check_report to return [] fails 8 of the 9.
  • For (2), making run_capgains drop one row when --long-term-days is passed now reports the drop on every affected seed. Before the change the same mutation was completely silent, which is the hole you described.
  • For (3), --leap-report over 60 seeds exits 0, reports 21 leap-day acquisitions under their own heading, and leaves the run 60/60 clean. Previously each of those 21 was a failure.

400 seeds at CI's PR setting: still clean.

@robcohen
robcohen merged commit 81fad51 into main Aug 24, 2026
49 checks passed
@robcohen
robcohen deleted the feat/capgains-fuzzer branch August 24, 2026 14:40
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