Repository navigation
test(compat): add a returns fuzzer, gated in CI - #2143
Conversation
`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
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
There was a problem hiding this comment.
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 labeledcloser: 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 aTemporaryDirectorycontext 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.
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
|
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 2. A run that compared nothing exited 0. Both engines turn load and execution failures into 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 4. The 5. 6. The self-test never exercised the dirty verdicts. Right — it only ran a clean seed, so deleting either comparison would have left 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 — And one overclaim corrected in the text rather than the codeThe PR described a "flow-list differential". Verification1000 seeds still agree, self-test passes, actionlint unchanged from |
`_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
report returnsanswers "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_irrrunsfsolvefrom a fixed seed against an objective with two spurious roots:npv(-(2+t)) == -npv(t)mirrors every true root, and every term underflows asr -> -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
configure.pyleavesdividend_accountsempty 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_flowsomits the terminal valuation. Onlytruncate_and_merge_cash_flowsappends 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 ACMEdeliberately: beangrow'sfind_accountsonly 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:
-100%asymptote → self-test failsI 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.ymlon the same pattern as the booking and capgains fuzzers —--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 (~16s), 2000 nightly from the run id.beangrowadded to the compat job's pip install. actionlint reports the same three findings asmain.🤖 Generated with Claude Code
https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr