Skip to content

test(compat): add a returns fuzzer, gated in CI - #2143

Merged
robcohen merged 4 commits into
mainfrom
feat/returns-fuzzer
Aug 25, 2026
Merged

robcohen merged 4 commits into
mainfrom
feat/returns-fuzzer

Conversation

@robcohen

Copy link
Copy Markdown
Member

report returns answers "what did this portfolio earn". It is hard to eyeball, easy to get subtly wrong, and had no generative coverage. It also has two independently wrong-able halves — extraction (which postings are cash flows, and what they are worth) and the solve (the rate that zeroes their NPV) — so this checks both, from three directions.

beangrow is the partner for extraction, not the oracle for the rate

beangrow is an independent implementation from the beancount project over the same ledgers, so agreement on the flow list is real evidence rather than a restatement of our own logic.

But it is not trustworthy for the rate, and this does not treat it as such. Its compute_irr runs fsolve from a fixed seed against an objective with two spurious roots: npv(-(2+t)) == -npv(t) mirrors every true root, and every term underflows as r -> -1. It reports "converged" on both. On a two-transaction profitable position it answers -100% where the true IRR is +102.28% — filed upstream as beancount/beangrow#51 from this work.

So the rate is adjudicated by an independent bisection solve over the same flows, bracketed away from the asymptote, and a divergence names which engine the referee agrees with.

Verdicts stay separate — EXTRACTION, SOLVER, AGREE — so a flow-list difference is never mistaken for a solver difference.

Two traps, both of which produced false divergences first

  • beangrow's configure.py leaves dividend_accounts empty when a dividend never touches the asset account, while rledger is told them via -n. Without configuring it, the comparison pits a configured engine against an unconfigured one: 13 false positives in 60 seeds.
  • ad.cash_flows omits the terminal valuation. Only truncate_and_merge_cash_flows appends it. Reading the raw list turned every open position into a spurious divergence and reported -41% against a true +21.87%.

The generated ledger declares commodity ACME deliberately: beangrow's find_accounts only considers an account whose leaf names a declared commodity, so without it the config infers zero investments and the whole comparison is vacuous rather than clean.

Result

1000 seeds, zero divergences of either kind.

A clean sweep proves nothing unless the harness can report dirty, so each check is shown to fail:

  • making the referee return the -100% asymptote → self-test fails
  • dropping beangrow's terminal flow → extraction check fires on every affected seed

I also rejected one mutation as inconclusive rather than counting it: blinding the extraction comparison left 40/40 agreeing, which only means those seeds had no difference to detect. Planting an actual difference is what proves the check.

CI

Wired into compat.yml on the same pattern as the booking and capgains fuzzers — --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 (~16s), 2000 nightly from the run id. beangrow added to the compat job's pip install. actionlint reports the same three findings as main.

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

`report returns` answers "what did this portfolio earn". It is hard to
eyeball, easy to get subtly wrong, and had no generative coverage. It also
has two independently wrong-able halves: EXTRACTION, deciding which postings
are cash flows and what they are worth, and the SOLVE, finding the rate that
zeroes their net present value. This checks both, from three directions.

beangrow is the differential partner for extraction: an independent
implementation from the beancount project over the same ledgers, so agreement
on the flow list is evidence rather than a restatement of our own logic.

beangrow is NOT the oracle for the RATE, and this does not treat it as one.
Its `compute_irr` runs `fsolve` from a fixed seed against an objective with
two spurious roots -- `npv(-(2+t)) == -npv(t)` mirrors every true root, and
every term underflows as `r -> -1` -- and it reports "converged" on both. On
a two-transaction profitable position it answers -100% where the true IRR is
+102.28% (beancount/beangrow#51, filed from this work). So the rate is
adjudicated by an independent bisection solve over the SAME flows, bracketed
away from the asymptote, and a divergence names which engine the referee
agrees with.

Verdicts are kept separate -- EXTRACTION, SOLVER, AGREE -- so a flow-list
difference is never mistaken for a solver difference.

Two traps are handled explicitly, both of which produced false divergences
before being fixed:

  beangrow's `configure.py` leaves `dividend_accounts` EMPTY when a dividend
    never touches the asset account, while rledger is told them via `-n`.
    Without configuring it, the comparison pits a configured engine against an
    unconfigured one: 13 false positives in 60 seeds.
  `ad.cash_flows` omits the terminal valuation; only
    `truncate_and_merge_cash_flows` appends it. Reading the raw list turned
    every open position into a spurious divergence, and gave -41% against a
    true +21.87%.

The generated ledger declares `commodity ACME` because beangrow's
`find_accounts` only considers an account whose LEAF names a declared
commodity. Without it the config infers zero investments and the whole
comparison is vacuous rather than clean.

RESULT: 1000 seeds, zero divergences of either kind.

Each check is shown to be able to FAIL, since a clean sweep proves nothing
otherwise: making the referee return the -100% asymptote fails the self-test,
and dropping beangrow's terminal flow fires the extraction check on every
affected seed. A run is ~0.04s, so 400 seeds on a PR costs ~16s.

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 25, 2026 02:38
Copilot AI lite review requested due to automatic review settings August 25, 2026 02:38
Comment thread scripts/compat-returns-fuzz.py Fixed
Comment thread scripts/compat-returns-fuzz.py Fixed
@codecov

codecov Bot commented Aug 25, 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

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

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 a seeded differential fuzzer for report returns, comparing extraction and IRR results against beangrow and an independent solver.

Changes:

  • Generates investment ledgers and validates return calculations.
  • Adds self-tests and extraction/solver verdicts.
  • Integrates beangrow and PR/nightly CI fuzzing gates.

Reviewed changes

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

File Review findings
scripts/compat-returns-fuzz.py Moderate (4 votes): skipped executions can produce a false 0/0 agreed success. Moderate (3 votes): self-tests do not exercise dirty extraction or solver verdicts. Moderate (4 votes): referee output is not checked against want. Moderate (3 votes): fixed upper bracket can exclude generated IRRs. Moderate (4 votes): extraction comparison omits dated flow structure. Moderate (3 votes): bisection lacks a safe root-selection strategy for non-monotone NPVs.
.github/workflows/compat.yml Critical (2 votes): the scheduled fuzz step runs after checkout of a compatibility branch without scripts/ or target/, causing the nightly gate to fail. Move the step before that checkout or move the commit step afterward.
Suppressed comments (2)

scripts/compat-returns-fuzz.py:245

  • The enclosing condition has already established that abs(ours_rate - ref * 100) > TOLERANCE, so the true branch here is unreachable and every solver divergence is labeled closer: referee. That diagnostic cannot identify which engine the referee supports as described; either compare both engine rates to the referee or remove this misleading label.
        if ref is not None and abs(ours_rate - ref * 100) > TOLERANCE:
            closer = "rledger" if abs(ours_rate - ref * 100) < TOLERANCE else "referee"
            return "solver", [

scripts/compat-returns-fuzz.py:177

  • Every seed creates a new mkdtemp() cache directory and never removes it. The scheduled 2,000-run sweep therefore leaves 2,000 cache directories (and any files beangrow writes) in the runner's temporary area, while also preventing cache reuse. Use a TemporaryDirectory context for this per-seed cache.
    adata = investments.extract(
        entries, om["dcontext"], config, END, False, tempfile.mkdtemp()
    )

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

Comment thread .github/workflows/compat.yml Resolved
Comment thread scripts/compat-returns-fuzz.py Resolved
Comment thread scripts/compat-returns-fuzz.py Resolved
Comment thread scripts/compat-returns-fuzz.py Resolved
Comment thread scripts/compat-returns-fuzz.py Resolved
Comment thread scripts/compat-returns-fuzz.py Resolved
Comment thread scripts/compat-returns-fuzz.py Resolved
All seven were real, and several are the exact failure modes this harness
exists to catch, which is the uncomfortable part.

1. The nightly gate could never have run. The step sat AFTER "Commit results
   to compatibility branch", which checks out an orphan branch with no
   `scripts/` and no `target/`. The hazard is documented at compat.yml:819
   for the budget fuzz and I anchored on the GATE rather than on the other
   fuzzers. Moved to sit beside Booking and Capital gains, before the
   checkout.

2. A run that compared NOTHING exited 0. Both engines turn load and execution
   failures into `skip`, so an incompatible beangrow API would print
   "0/0 agreed" and pass. Now an executed count of zero fails, as does
   skipping more than half the seeds.

3. The referee gave up on steep returns. A fixed 10,000% upper bracket missed
   a 20-day 10.00 -> 16.50 sale, which annualizes past 900,000%; `bisect_irr`
   returned None and the solver check silently skipped precisely the cases
   most likely to break a Newton solver. The bracket now grows.

4. The `closer:` label was unreachable. Reaching that branch already means
   rledger differs from the referee by more than tolerance, so the ternary
   could only ever print "referee" while reading as though it had adjudicated.
   Removed in favor of both rates and their delta.

5. The self-test computed the hand-checked rate and never compared it, so it
   accepted any non-None result including a wrong one. CodeQL flagged the
   unused variable; the variable was the symptom, the missing assertion was
   the defect. It now asserts the rate to 1e-6.

6. The self-test never exercised the EXTRACTION or SOLVER branches, only
   "agree". Deleting either comparison left it green. It now drives both with
   planted values. Writing that caught a further error of mine: the first
   fixture put a terminal flow in the distributions column.

7. Bisection assumed one sign change. A series with several has several real
   roots, and picking one arbitrarily would let the referee adjudicate toward
   a root rledger never claimed. It now scans the bracket and declines when
   the count is not exactly one, which is honest where a confident wrong
   answer would not be.

Also corrected an overclaim rather than the code: the PR described a
"flow-list differential", but `report returns --format json` exposes
aggregates and a count, not dated flows, so a change preserving all sums AND
the count while moving a flow's DATE is invisible. The docstring now says so
and names what would close it. The count is now compared, which it was not.

Verified: 1000 seeds still agree, self-test passes, and forcing every seed to
skip now exits 1 with "the gate proved nothing".

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

Copy link
Copy Markdown
Member Author

All seven correct, all seven fixed in 887181f. Several are the exact failure modes this harness exists to catch, which is the uncomfortable part of the review.

1. The nightly gate could never have run. The step sat after Commit results to compatibility branch, which checks out an orphan branch with no scripts/ and no target/. That hazard is documented at compat.yml:819 for the budget fuzz, I read it while writing the step, and I still anchored on the gate rather than on the other fuzzers. Moved to sit beside Booking and Capital gains, before the checkout.

2. A run that compared nothing exited 0. Both engines turn load and execution failures into skip, so an incompatible beangrow API would print 0/0 agreed and pass. Now an executed count of zero fails, as does skipping more than half the seeds. Verified: forcing every seed to skip exits 1 with the gate proved nothing.

3. The referee gave up on steep returns. Correct about the magnitude — a 20-day 10.00 → 16.50 sale annualizes past 900,000%, far past the fixed 10,000% bracket, so bisect_irr returned None and the solver check silently skipped exactly the cases most likely to break a Newton solver. The bracket now grows geometrically.

4. The closer: label was unreachable. Reaching that branch already means rledger differs from the referee by more than tolerance, so the ternary could only print referee while reading as though it had adjudicated between two engines. Replaced with both rates and their delta.

5. want computed and never compared. The self-test accepted any non-None result, including a wrong bisection. CodeQL flagged the unused variable; the variable was the symptom and the missing assertion was the defect. It now asserts to 1e-6.

6. The self-test never exercised the dirty verdicts. Right — it only ran a clean seed, so deleting either comparison would have left --self-test green. It now drives both branches with planted values. Writing that caught a further error of mine: my first planted fixture put a terminal flow in the distributions column, and the self-test told me so.

7. Bisection assumed a single sign change. A series with several has several real roots, and picking one arbitrarily would let the referee adjudicate toward a root rledger never claimed. It now scans the bracket and declines when the count is not exactly one — None means "no verdict", which is honest where a confident wrong answer is not.

And one overclaim corrected in the text rather than the code

The PR described a "flow-list differential". report returns --format json exposes aggregates and a count, not dated flows, so a change preserving all three sums and the count while moving a flow's DATE is invisible to it. The docstring now states that limit and names what would close it (a diagnostic flow dump from rledger). The count is now compared, which it was not before.

Verification

1000 seeds still agree, self-test passes, actionlint unchanged from main (3 findings, all pre-existing).

Comment thread scripts/compat-returns-fuzz.py Fixed
Comment thread scripts/compat-returns-fuzz.py Fixed
robcohen and others added 2 commits August 25, 2026 12:43
`_Stub` was left from an earlier draft that built stand-in engine results as
objects; the planted cases use plain dicts, so nothing referenced it. CodeQL
flagged it as an unused local.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Self-review of the previous commit. The guard that declines to rule on a
series with several roots was added to prevent the referee adjudicating
toward a root rledger never claimed, and then never exercised: the self-test
covered NO sign change but not SEVERAL, so removing the guard left it green.

It also carried a risk of its own. `None` means "no verdict", so a guard that
fires often would silently switch the solver check off, which is the exact
failure mode it was written to prevent. Measured before adding the check:
0 of 300 generated seeds decline.

Two cases now, both shown to fail. Removing the guard fails the multi-root
case; making it always fire trips the rate check at 30/30 as well as three
other assertions, which is the shape a genuinely broken referee has.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen merged commit 07d2f15 into main Aug 25, 2026
44 checks passed
@robcohen
robcohen deleted the feat/returns-fuzzer branch August 25, 2026 13:34
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.

3 participants