Repository navigation
test(compat): add a capital-gains fuzzer, gated in CI - #2127
Conversation
`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
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
📊 Benchmark Results
vs base, measured in this run
A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: What do these numbers mean?
|
There was a problem hiding this comment.
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_ledgeralways creates at least one positive-quantity sale (the first sale date is after the earliest lot), so a regression that drops every disposal makescheck_report, both term-rule runs, and year filtering vacuous and returns no finding. Carry the expected sale/disposal count out ofgen_ledgerand 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
--yearis 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: nullandheld_days: null(the existingreport_capgains_test.rsfixture covers this), but this oracle unconditionally callsdate.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 evaluatesNone > 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 Yresponse passes. Runcheck_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 throughcheck_report. A regression that mis-partitions or mis-summarizes--long-term-days 365output would therefore pass the sweep even though those are the tax totals being guarded. Apply the report invariant checks tofixedas 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_termcase 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_reportassumesacquiredandheld_daysare 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.
✅ Compatibility Test Results
What's tested
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
|
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 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 2. 3. Evidence for each, rather than assertion
400 seeds at CI's PR setting: still clean. |
report capgainsproduces numbers people put on a tax return and had no generative coverage at all — the word does not appear anywhere inscripts/ortests/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.pychecks the budget report:gain == proceeds - cost_basis, per rowheld_days == sold - acquired--year Yreturns the disposals sold in Y and nothing else--long-term-days Nis 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 spanDeliberately 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-testplants six malformed reports and requires each to be caught, and blindingcheck_reporttoreturn []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_termrests onjiffresolving a Feb-29 acquisition to Feb-28 — the module comment says so, and nothing checked it.long_term_calendar_rule_handles_leap_yearuses a span that crosses a leap day, which is a different thing from a lot bought on one. Ajiffupgrade 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.ymlfollowing the booking and budget fuzzers exactly —--self-testfirst, then the sweep,continue-on-errorwith 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 asmain, none in the new steps.🤖 Generated with Claude Code
https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr