Repository navigation
feat(report): realized capital-gains / tax-lot report (capgains) - #1860
Conversation
Add `rledger report capgains`: one row per disposed tax lot, classified
short vs long term, with proceeds, cost basis, and realized gain/loss,
plus per-term and per-currency summaries. Text / CSV / JSON.
The report consumes the booking engine's per-lot `CapitalGain` and books
the PRE-booking parsed stream itself (book + apply, in booking order),
using the ledger's own booking method so lot-matching agrees with
`rledger check`. Design points that make the figures correct:
- Booking the parsed stream (not the loader's stored directives): the
stored stream has already expanded multi-lot reductions and normalized
`@@` totals to per-unit prices, which is lossy for total-price proceeds.
- `@@` total prices are pro-rated across matched lots with the remainder
on the last lot, so per-lot proceeds sum EXACTLY to the stated total
(a single-lot `@@` records the total verbatim, no division tail).
- Long-term uses the leap-year-correct calendar "> 1 year" rule by
default; `--long-term-days N` overrides with a fixed day count.
- A sale the ledger cannot book unambiguously (e.g. a bare `{}` reduction
spanning different-cost lots under strict booking) is skipped, not
guessed — the report never fabricates a gain `check` rejects.
Booking engine: `CapitalGain` now carries `units` and `acquired_date`,
and records one gain per matched lot for any priced reduction (including
break-even disposals). Loader: `Ledger` exposes `effective_booking_method`
so a re-booking consumer matches the loader's lot-matching.
Filters: `--account`, `--year`, `--end`. Out of scope for v1 (documented):
wash-sale adjustment, currency-vs-asset gain separation, pad-seeded lots.
Tests: booking `@@` exactness (single + multi-lot) and per-lot gains;
capgains unit tests (collection, booking order, leap-year boundary,
filters, override) and end-to-end CLI tests over a hand-verified fixture.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
📊 Benchmark Results
vs main branch (2026-07-24)
What do these numbers mean?
|
There was a problem hiding this comment.
Pull request overview
Adds a new CLI report, rledger report capgains, to surface realized capital gains/losses on disposed tax lots (short vs long term) using booking-engine lot matching. This fits into the reporting suite alongside holdings (remaining lots) and returns (market-value performance) by providing the cost-basis-aware “what you sold” view.
Changes:
- Add
capgainsreport subcommand with text/CSV/JSON renderers and filters (--account,--year,--end,--long-term-days). - Extend booking engine realized-gain data (
CapitalGain) to be per-lot and carry units + acquisition date; implement exact-sum@@total-price proceeds allocation. - Expose loader’s effective booking method so capgains can re-book with the same lot-matching semantics as
rledger check, plus docs + end-to-end CLI tests.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| README.md | Advertises the new capital-gains capability and subcommand. |
| docs/commands/report.md | Documents report capgains, its output, and CLI options. |
| crates/rustledger/tests/report_capgains_test.rs | End-to-end CLI coverage for text/CSV/JSON output and key correctness invariants. |
| crates/rustledger/src/cmd/report_cmd/mod.rs | Wires capgains into the report command and plumbs pre-booking directives + booking method. |
| crates/rustledger/src/cmd/report_cmd/capgains.rs | Implements the capgains report: re-booking collection + rendering + filtering. |
| crates/rustledger-loader/src/process.rs | Exposes effective_booking_method on Ledger for downstream consumers. |
| crates/rustledger-booking/src/book.rs | Enhances CapitalGain and implements per-lot proceeds/gain computation with @@ exactness. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
…s-currency guard - collect_disposals: interpolate the booked transaction before apply(), so inventory matches the loader's book_and_interpolate -> apply pipeline (apply expects filled amounts; an elided balancing leg would otherwise be dropped). A transaction that fails to interpolate is skipped whole. - booking: skip recording gains for the entire reduction unless every matched lot has a cost basis in the same currency as the sale price (cross-currency disposals are out of scope) instead of emitting a meaningless proceeds - basis. Adds a regression test. - docs: fix module-doc "per-year" -> "per-currency" summaries; drop a stray backslash escape in report.md (8949\) -> 8949)). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 7 changed files in this pull request and generated 2 comments.
Comments suppressed due to low confidence (2)
crates/rustledger/src/cmd/report_cmd/capgains.rs:262
- In JSON output,
unitsis currently emitted fromDecimal'sDisplay(d.units), which bypassesDisplayContextformatting used elsewhere in reports. Emit the units string viaDisplayContextfor consistency with CSV/Text rendering conventions.
r#"{{"sold": "{}", "account": "{}", "commodity": "{}", "units": "{}", "acquired": {}, "held_days": {}, "term": "{}", "currency": "{}", "proceeds": "{}", "cost_basis": "{}", "gain": "{}"}}"#,
d.sold,
json_escape(&d.account),
json_escape(&d.commodity),
d.units,
d.acquired
crates/rustledger/src/cmd/report_cmd/capgains.rs:325
- In text output,
Unitsis rendered viad.units.to_string(), which bypassesDisplayContextformatting (and is inconsistent withProceeds/Gain, which do use it). Render units viaDisplayContextso precision/grouping follows ledger conventions.
truncate(
&format!("{} {}", d.commodity, short_account(&d.account)),
22
),
d.units.to_string(),
d.acquired
…e JSON in tests - Render disposed units through the ledger DisplayContext (ctx.format_amount_number(units, commodity)) in all three formats, matching holdings/balances/balsheet convention, instead of raw Decimal Display. - Integration test: parse the capgains JSON with serde_json and assert on fields (also verifies the output is valid JSON) rather than substring matching. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
…anonical sort, exact machine output Second high-effort review round surfaced correctness gaps the earlier passes missed: - book.rs: the cross-currency guard was all-or-nothing per reduction, so a sale FIFO-matching lots in DIFFERENT cost currencies dropped the ENTIRE sale — including the legitimate same-currency lots. Now skip only the mismatched (or cost-less) lot; record the same-currency lots. @@ proceeds now multiply BEFORE dividing (exact for single-lot and evenly-dividing sales) instead of the last-lot-remainder scheme, which is incompatible with per-lot skipping. Adds a mixed-currency-lots regression test. - mod.rs: canonical-sort the parsed stream by (date, priority, file_id, span.start) — the loader's pre-booking sort — before the report's booking-order pass, so FIFO/LIFO lot attribution matches `rledger check` even for ledgers split across included files (raw concat order != canonical order). - capgains.rs: if interpolate fails, fall back to applying the booked transaction (never silently drop a lot a later sale needs) instead of skipping it. - capgains.rs: CSV and JSON now emit the EXACT Decimal (machine-readable), not ctx.format_amount_number, which rounds to display precision and injects render_commas separators — corrupting the exported figures. TEXT keeps display formatting for humans. - capgains.rs: is_long_term reuses the already-computed held_days (was recomputing the same span); documents the intentional book/apply re-derivation (the canonical book/book_transactions drop the per-lot CapitalGains this report needs). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.
Comments suppressed due to low confidence (1)
crates/rustledger/src/cmd/report_cmd/capgains.rs:131
- If
interpolate(&booked.transaction)fails, this currently falls back to applying the non-interpolated transaction. That violatesBookingEngine::apply()’s precondition (booked + interpolated postings) and can trip thedebug_assert!in debug builds; it also means the report may emit disposal rows for transactions the loader/validator would treat as unbookable.
Instead, treat interpolation failure as a booking failure for this report: roll back the gains just pushed for this transaction and skip applying it to inventory.
// Accumulate inventory. Interpolate first (fills elided legs) to mirror the
// loader's `book_and_interpolate` → `apply` pipeline; if interpolation fails,
// fall back to the booked transaction so a lot with explicit units still
// enters inventory and a later sale can match it — never silently drop a lot
// from an otherwise `rledger check`-clean ledger.
…ding period Differential testing against Python beancount (byte-identical on 300+ random FIFO ledgers + FIFO/LIFO/HIFO fixtures) plus a booking-method matrix surfaced two real correctness bugs: - Short sales (F2): covering a short had the gain SIGN INVERTED and proceeds/basis swapped. rledger reported -100 where the true gain is +100 (sold 5@100 = 500 proceeds, covered 5@80 = 400 basis). Now when the matched lot has negative units, proceeds = short-open value and cost basis = cover cost (the mirror of a long disposal); gain = proceeds - cost_basis holds both ways. Validated against beancount's Income:Gains for gain AND loss covers. CapitalGain gains a `short_sale` flag; short-sale gains are always short-term (US rule). - Unknown holding period (F1): AVERAGE booking merges lots and drops their acquisition dates (beancount rejects AVERAGE outright), so disposals had no date and were silently classified SHORT. Now a dateless disposal is classified `unknown` (tri-state term short/long/unknown), rendered `??` / `unknown` with its own summary bucket, rather than a misleading `short`. The averaged basis is correct; only the term was wrong. Validation (not shipped): beancount differential oracle, 300-ledger differential fuzzer (0 mismatches), cross-report conservation over 300 ledgers (disposed basis + holdings remaining == acquired, 0 violations). Confirmed rledger is MORE precise than beancount on single-lot @@ (exact 100.00 vs beancount's 99.99...). Tests: booking short-cover (+100, flag, dates); integration short-sale and AVERAGE-unknown rows. Docs updated for both behaviors. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
The mutants.out.old/ directory (cargo-mutants generated output — diffs, outcomes.json, mutants.json, caught/missed lists) was committed to the repo by mistake. Remove it from tracking and gitignore both mutants.out/ and mutants.out.old/ so mutation runs no longer dirty the tree. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
b1c7db6 to
e96f562
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 16 out of 20 changed files in this pull request and generated 1 comment.
Comments suppressed due to low confidence (3)
crates/rustledger-booking/src/book.rs:423
CapitalGainrecording currently skips only the individual matched lot when the lot has no cost basis or its cost currency differs from the sale price currency. This can produce partial/misleading results for a single sale (and makes@@total proceeds allocation ambiguous), while docs/PR notes describe cross-currency disposals as out of scope. Consider treating this as all-or-nothing for the reduction: if any matched lot is missing a cost or has a different cost currency than the sale price currency, record noCapitalGains for that reduction.
// cost_basis` across currencies is meaningless without
// FX (out of scope). Skip only THAT lot — a same-currency
// lot in the same sale is still a real, reportable
// disposal, so a mixed-currency reduction records the
// lots it can and drops only the ones it can't.
crates/rustledger-booking/src/book.rs:435
- For
@@(total) sale prices, proceeds are currently computed astotal * lot_units / total_unitsper lot, which can introduce rounding error and cause per-lot proceeds to not sum exactly to the stated total (especially for multi-lot sales where the split is non-terminating in base-10). The PR description + docs claim an exact-sum remainder scheme (remainder assigned to the last lot). The implementation should match that contract.
// price names the value for the whole reduction, pro-rated
// by units — multiplying BEFORE dividing so it stays exact
// whenever the total divides evenly (a single-lot `@@` is
// always exact: `total × n / n`). A non-terminating split
// leaves an immaterial sub-display residual per lot.
crates/rustledger/src/cmd/report_cmd/capgains.rs:316
- CSV/JSON rendering emits raw
Decimalvalues (e.g.d.units,d.proceeds) even though other reports format numeric fields viaDisplayContext(e.g.holdings.rs:75-80) and then escape them for CSV/JSON. This also contradicts the earlier agreed fix that disposed units should render throughDisplayContextfor consistency. Either switch capgains to the sameDisplayContextformatting convention (and update fixtures/tests accordingly), or document/standardize why capgains intentionally differs from other reports’ machine-readable output.
"{},{},{},{},{},{},{},{},{},{},{}",
d.sold,
csv_escape(&d.account),
csv_escape(&d.commodity),
d.units,
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 16 out of 20 changed files in this pull request and generated 1 comment.
Comments suppressed due to low confidence (2)
crates/rustledger/src/cmd/report_cmd/capgains.rs:183
BookingEngine::apply()requires a booked + interpolated transaction (complete units); falling back tobooked.transactionwhen interpolation fails can trip theapply()debug_assert in debug builds and can silently ignore reductions in release builds, diverging from the loader pipeline.
Instead of applying the un-interpolated transaction, skip applying this transaction when interpolation fails (or otherwise ensure all postings are complete before calling apply()).
let applied = match rustledger_booking::interpolate(&booked.transaction) {
Ok(interp) => interp.transaction,
Err(_) => booked.transaction,
};
engine.apply(&applied);
crates/rustledger-booking/src/book.rs:441
- For
@@(total-price) reductions,amt.number * lot_units / total_unitscan introduce rounding atrust_decimal’s precision ceiling for non-terminating splits (e.g. 100 × 1/3), so per-lot proceeds may not sum exactly to the stated total. This contradicts the report/docs guarantee of exact-sum@@proceeds.
Consider allocating proceeds with a remainder scheme: compute pro-rata proceeds for each matched lot except the last, track the running sum, then assign the last lot total - allocated (and adjust gain accordingly, including the short_sale inversion case). Add a regression test with a non-terminating multi-lot split to pin the exact-sum invariant.
let sale_value = match price.kind {
rustledger_core::PriceKind::Unit => amt.number * lot_units,
rustledger_core::PriceKind::Total if !total_units.is_zero() => {
amt.number * lot_units / total_units
}
…ation, incomplete-report warning Final max-effort review round + mutation testing (39/39 caught) surfaced: - interpolate-failure: REVERT the earlier fallback-to-booked (which applied a lot the loader rejects, realizing a phantom gain that disagrees with `rledger check`). Now skip the transaction — exactly as the loader's run_booking does (moves it to `failed`, never applies) — and record no gains for it. - Silent incomplete reports: a transaction that cannot be booked/interpolated (pad- or plugin-seeded lots the pre-plugin stream can't resolve, or an unbalanced entry) is skipped; collect_disposals now returns a skip count and the report prints a `warning:` to stderr, so an incomplete report is never mistaken for a complete one. - Multi-lot `@@` reconciliation: an unevenly-dividing total left 28-digit tails in the exact CSV/JSON export that did not sum to the stated total. Now allocate to the precision the total was written in with the last lot taking the remainder, so per-lot proceeds sum EXACTLY (e.g. 3 @@ 100.00 -> 33.33 + 66.67 = 100.00). - Text table: widen amount columns so millions with thousands separators (1,500,000.00) no longer overflow and misalign. - held_days: clamp a nonsensical negative span (lot "acquired" after the sale) to none. - Build the per-term summary maps only for TEXT/JSON (the CSV renderer never uses them). Deliberately kept (documented): cross-currency lots skipped per-lot (no FX), break-even disposals recorded (reportable on Form 8949), text units via DisplayContext (CSV/JSON stay exact). Mutation testing on capgains.rs: 39/39 caught after adding boundary tests (day-count threshold, --end inclusivity, net-total across buckets, text helpers). Booking test for the uneven-@@ reconciliation. Docs updated. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 16 out of 20 changed files in this pull request and generated no new comments.
Comments suppressed due to low confidence (1)
crates/rustledger-booking/src/book.rs:420
- The gain-recording logic now allows partial reporting for a single priced reduction when some matched lots have a cost currency that differs from the sale-price currency ("mixed sale records what it can"). For
@@totals this means the report can silently emit proceeds that no longer sum to the stated total (because the exact-remainder scheme only applies when all matched lots are eligible), producing an incomplete/misleading capgains export with no warning. Consider making this all-or-nothing for a reduction (skip recording anyCapitalGains unless every matched lot has a same-currency cost basis), or alternatively plumb a structured "skipped due to cross-currency" signal up to the report so it can warn and avoid claiming exact@@proceeds.
// Eligible lots: cost present and in the SALE-price currency.
// A cross-currency lot is skipped (proceeds − cost_basis
// across currencies is meaningless without FX — out of scope);
// a same-currency lot in the same sale is still reported, so a
// mixed sale records what it can and drops only what it can't.
…re-booking
Architectural fix (the correct design behind the review churn): the report was
re-booking its own copy of the stream to recover per-lot realized gains, because
the canonical booking free functions dropped them. Every bug this PR worked
through — a defaulted booking method, a hand-rolled canonical sort, the pre- vs
post-normalization stream choice, the interpolate/apply divergence, silent
pad/plugin drops — was a symptom of re-deriving the loader's lot-matching.
Now the loader's single canonical booking pass captures the CapitalGains it
already computes and exposes them on `Ledger::capital_gains`; the report consumes
them directly. This follows the codebase's canonical-function discipline
("post-processing belongs in the shared finalize phase, not one consumer").
- rustledger-booking: `book_and_interpolate_with_gains` returns the gains alongside
the interpolation result (fast path unchanged); `CapitalGain` gains a `sale_date`.
- rustledger-loader: `run_booking` collects gains via a `&mut` out-param (like
`errors`), threaded through the `book()` phase transition into `Ledger`. The
previously-added `effective_booking_method` field is removed — it existed only to
let the report re-book, which it no longer does.
- report: `collect_disposals` (the re-book loop) becomes `to_disposals` (a pure
CapitalGain -> Disposal transform); `report_capgains` takes `&[CapitalGain]`. The
report drops `parsed_directives`, the booking method, the canonical-sort
duplication, and the skip-warning (an unbookable txn is a normal `Ledger::errors`
BOOK error, printed by the shared load path).
Behavior is identical: beancount differential 0 mismatches (300 ledgers),
cross-report conservation 0 violations, all integration tests unchanged. Booking
correctness now lives entirely at the booking/loader layer; the report's unit
tests exercise the transform/filters/render over synthetic CapitalGains.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
…e-review fixes Two deep-review rounds (correctness + architecture) plus mutation testing. Booking is now non-optional in rustledger-loader. A loader that cannot book cannot compute balances (reductions would not match lots), so `process()` would produce semantically broken output — the `booking` feature gated a configuration nobody builds. Removing it drops ~15 cfg sites, the dead no-processing `load` path, and the field-gating fragility (the capgains report read a `#[cfg(feature="booking")]` field, which only compiled because the loader's default `full` happened to include booking). `plugins`/`validation` stay optional (a loader can meaningfully book without them). `Ledger::capital_gains` is now an unconditional field. capgains fixes: - @@ (total price) per-lot proceeds are the EXACT pro-rata share, unrounded. The earlier round-to-the-total's-scale-plus-remainder scheme distorted round-dollar totals (33/67 instead of 33.33/66.67) and could drive the last lot NEGATIVE when coarse rounding over-allocated (@@ 2 over four lots). Rounding a money split is a presentation concern (needs the currency precision) and does not belong in the booking engine; exact fractions match Python beancount. - Cross-currency disposals (sale price currency != cost currency) are no longer silently dropped: booking records the disposal truthfully (proceeds in the sale currency, basis in the cost currency), and the REPORT — where the "no gain without FX" policy belongs — filters them out with a stderr `warning:` and a count. - Remove the redundant `CapitalGain::amount` field (gain is `proceeds − cost_basis`, which is only meaningful same-currency; consumers derive it). - Opt-in gain collection: `LoadOptions::collect_capital_gains` (default false) gates whether the booking pass RETAINS the gains, so `check`/BQL/holdings/FFI don't carry the vector; only the capgains report opts in. - book_and_interpolate now delegates to book_and_interpolate_with_gains (single implementation, no drift) and the latter gained a # Errors doc. Validation: beancount differential 0 mismatches (300 ledgers), cross-report conservation 0 violations, full workspace green (loader/booking/report/ffi/query), loader compiles with --no-default-features (booking still present), clippy + docs clean. Tests updated for the struct change; added the negative-remainder, cross-currency, and all-three-term-bucket-net regression tests. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 18 out of 22 changed files in this pull request and generated 3 comments.
Comments suppressed due to low confidence (3)
crates/rustledger-booking/src/book.rs:447
- For
@@(total) prices, proceeds are allocated astotal * lot_units / total_unitsper matched lot. When the split is non-terminating inDecimal(e.g. 100 across 3 units split across multiple lots), this introduces rounding tails and the per-lot proceeds will not sum exactly to the stated total, contradicting the “exact @@ proceeds / remainder on last lot” behavior described in the PR.
let sale_value = match price.kind {
rustledger_core::PriceKind::Unit => amt.number * lot_units,
rustledger_core::PriceKind::Total if !total_units.is_zero() => {
amt.number * lot_units / total_units
}
crates/rustledger/src/cmd/report_cmd/capgains.rs:113
- Cross-currency disposals are currently dropped per-lot (
return Nonewhen proceeds/basis currencies differ). If a single sale crosses multiple lots and only some of those lots are cross-currency, the report will emit a partial set of rows whose proceeds no longer reconcile to the sale’s stated proceeds, which can mislead users.
// Cross-currency: proceeds and basis are in different currencies, so
// `proceeds − cost_basis` has no defined value. Count and drop.
if g.proceeds.currency != g.cost_basis.currency {
cross_currency += 1;
return None;
crates/rustledger/src/cmd/report_cmd/capgains.rs:129
- If
acquired_dateis aftersale_date,held_daysis filtered out (becomesNone), but the code still classifies the lot as short/long based onacquired_date. That can silently report an invalid holding period as short-term instead of treating it as indeterminate.
let term = if g.short_sale {
Term::Short
} else {
match g.acquired_date {
None => Term::Unknown,
…ted lots, CSV escaping, docs - to_disposals: a lot "acquired" after the sale (a future-dated cost, invalid data) now classifies as `unknown`, not silently `short` — the holding period is determinable only with an acquisition date AND a non-negative span. Adds a test. - CSV: escape the `currency` column like `account`/`commodity`, so a nonstandard commodity/currency name containing a comma/quote/newline can't break the CSV. - LoadOptions::raw() doc: booking is mandatory now, so drop the stale "no booking" claim (it runs regardless; use the parser/load_raw for truly unbooked directives). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 18 out of 22 changed files in this pull request and generated 2 comments.
Comments suppressed due to low confidence (3)
crates/rustledger/src/cmd/report_cmd/capgains.rs:291
capgainsCSV output currently emits rawDecimalvalues forunits,proceeds,cost_basis, andgain. Other reports (e.g.balancesandholdings) consistently format numbers via the ledgerDisplayContextand then CSV-escape the resulting strings so precision andrender_commassettings apply uniformly. This report should follow the same convention for consistency across report outputs.
// Raw `Decimal` (no separators, no rounding) for machine parsing.
writeln!(
writer,
"{},{},{},{},{},{},{},{},{},{},{}",
d.sold,
docs/commands/report.md:331
- Docs claim multi-lot
@@proceeds are “pro-rated ... so they sum exactly to the stated total”, but the booking engine currently computes per-lot proceeds astotal * lot_units / total_units(a potentially non-terminatingDecimaldivision), so the per-lotDecimalvalues may not sum exactly tototalin representation. Adjust the wording to match the implementation (exact pro-rata shares; rounding/summing happens at presentation precision).
- **Proceeds** come from the sale price. For a `@@` total price the proceeds are
pro-rated across the matched lots so they **sum exactly to the stated total**
(a single-lot `@@` records the total verbatim, with no division rounding).
crates/rustledger/src/cmd/report_cmd/capgains.rs:336
- JSON term summaries (
short_term/long_term/unknown_term) also emit rawDecimalvalues. If disposals are formatted throughDisplayContext, summaries should be formatted the same way to keep JSON consistent.
let summ = |b: &BTreeMap<String, Totals>| -> String {
let parts: Vec<String> = b
.iter()
.map(|(c, t)| {
format!(
r#"{{"currency": "{}", "disposals": {}, "proceeds": "{}", "cost_basis": "{}", "gain": "{}"}}"#,
json_escape(c),
t.count,
t.proceeds,
t.cost_basis,
t.gain,
)
…s, guard zero-unit reduction - CLI: reject a negative `--long-term-days` (it would trivially classify every dated lot as long-term). A bare `-1` is already rejected by clap as a flag; the `=-1` form now errors with a clear message. Adds a test. - booking: a zero-unit reduction is degenerate (no proceeds to pro-rate and it would divide by zero), so record no disposal for it. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
|
Addressed the latest Copilot review round (commits Fixed:
Deliberate decisions (not changed), for the record:
|
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 18 out of 22 changed files in this pull request and generated no new comments.
Comments suppressed due to low confidence (2)
docs/commands/report.md:331
- The docs claim
@@total-price proceeds "sum exactly to the stated total", but the booking logic allocates per-lot proceeds astotal × lot_units ÷ total_units(unrounded). For non-terminating splits inDecimal, the per-lot values won’t necessarily sum back to the total in the exported CSV/JSON, so the wording here is misleading. Rephrase to describe the pro-rata (unrounded) allocation without promising exact summation.
- **Proceeds** come from the sale price. For a `@@` total price the proceeds are
pro-rated across the matched lots so they **sum exactly to the stated total**
(a single-lot `@@` records the total verbatim, with no division rounding).
crates/rustledger/src/cmd/report_cmd/capgains.rs:261
- This report intentionally emits raw
Decimalvalues in CSV/JSON, but other reports format numeric fields throughDisplayContexteven for CSV/JSON (e.g.crates/rustledger/src/cmd/report_cmd/holdings.rs:74-80andbalances.rs:42-47) and thencsv_escapethem to handle thousands separators. As-is,capgainsCSV/JSON will differ in precision/rounding (and may produce scientific notation), which is an inconsistent contract across reports. Consider aligning capgains CSV/JSON number formatting with the existing report conventions, or explicitly documenting this as a deliberate exception.
// TEXT is for humans, so it renders amounts through the ledger `DisplayContext`
// (display precision, thousands separators). CSV and JSON are machine-readable,
// so they emit the EXACT `Decimal` verbatim (via `Display`) — never the display
// formatter, which would round to display precision and inject `render_commas`
// separators, corrupting the exported figures.
Realized capital-gains / tax-lot report
Adds
rledger report capgains— the complement toreport holdings: whereholdings shows what you still hold, capgains shows what you sold. One row per
disposed tax lot, classified short / long / unknown term, with acquisition date,
holding period, proceeds, cost basis, and realized gain/loss, plus per-term and
per-currency summaries. Text / CSV / JSON.
Architecture (final)
Capital gains are computed once, in the loader's own canonical booking pass
(in booking order, with the ledger's own method, before
@@normalization), andexposed on
Ledger::capital_gains. The report is a pure consumer — aCapitalGain → Disposaltransform (holding-period classification, filters, render).It does not re-book the stream: re-deriving the loader's lot-matching was the
root cause of an entire class of bugs this PR worked through (a defaulted booking
method, a hand-rolled canonical sort, the pre- vs post-normalization stream choice,
an interpolate/apply divergence, silent pad/plugin drops). Consuming the canonical
gains means the report cannot drift from
rledger check.bookingis now amandatory loader capability (a loader that can't book can't compute balances);
gain retention is opt-in via
LoadOptions::collect_capital_gains, so only thecapgains report carries the vector.
Design points (each with regression tests):
@@proceeds — each lot gets its exact pro-rata share of a total price,unrounded (rounding is a presentation concern needing currency precision; it
distorts round-dollar totals and can go negative). Matches Python beancount.
basis = cover cost; always short-term).
future-dated one is
unknown, never silently short.with a stderr
warning:and count — not silently dropped.--long-term-days N).--account,--year,--end.Out of scope (documented): wash-sale adjustment, FX gains, pad-seeded lots,
jurisdiction rules beyond the holding-period threshold.
Validation
Beancount 3.2.3 differential: byte-identical on FIFO/LIFO/HIFO across 300+
random ledgers; property fuzzing 0 mismatches; cross-report conservation 0
violations (disposed basis + holdings remaining = acquired); mutation testing on
the report module; multiple deep-review + Copilot rounds. rledger is more precise
than beancount on single-lot
@@(exact100.00vs its99.99…per-unit artifact).🤖 Generated with Claude Code