Skip to content

feat(report): realized capital-gains / tax-lot report (capgains) - #1860

Merged
robcohen merged 11 commits into
mainfrom
feat/capgains-report
Jul 24, 2026
Merged

robcohen merged 11 commits into
mainfrom
feat/capgains-report

Conversation

@robcohen

@robcohen robcohen commented Jul 24, 2026 •

Copy link
Copy Markdown
Member

Realized capital-gains / tax-lot report

Adds rledger report capgains — the complement to report holdings: where
holdings 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.

Realized capital gains
===============================================================================
Sold       Commodity / account      Units  Acquired    Term   Proceeds       Gain
-------------------------------------------------------------------------------
2024-03-01 AAPL Stock                   8  2020-01-01    LT       1200        400
2024-04-01 AAPL Stock                   2  2020-01-01    LT        350        150
2024-04-01 AAPL Stock                   2  2023-06-01    ST        350        110
-------------------------------------------------------------------------------
Short-term    1 disposals   proceeds          350   gain          110 USD
Long-term     2 disposals   proceeds         1550   gain          550 USD
TOTAL       net realized gain          660 USD

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), and
exposed on Ledger::capital_gains. The report is a pure consumer — a
CapitalGain → Disposal transform (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. booking is now a
mandatory loader capability (a loader that can't book can't compute balances);
gain retention is opt-in via LoadOptions::collect_capital_gains, so only the
capgains report carries the vector.

Design points (each with regression tests):

  • Exact @@ 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.
  • Short positions — covering a short is a disposal (proceeds = short-open value,
    basis = cover cost; always short-term).
  • Unknown holding period — a lot with no acquisition date (AVERAGE cost) or a
    future-dated one is unknown, never silently short.
  • Cross-currency disposals (sale price currency ≠ cost currency) are omitted
    with a stderr warning: and count — not silently dropped.
  • Leap-year-correct ST/LT (calendar "> 1 year" by default; --long-term-days N).
  • Filters: --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 @@ (exact 100.00 vs its 99.99… per-unit artifact).

🤖 Generated with Claude Code

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
@robcohen
robcohen requested a review from a team as a code owner July 24, 2026 03:51
Copilot AI review requested due to automatic review settings July 24, 2026 03:51
@github-actions

github-actions Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 36ms ± 1.2ms 23.9 MB
beancount 803.7ms ± 6.4ms 50.6 MB
Comparison 22.3x faster 2.1x less

vs main branch (2026-07-24)

Metric main this PR Change
Time 27.7ms 36ms +30.0% 🔴
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

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 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 capgains report 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.

Comment thread crates/rustledger-booking/src/book.rs Resolved
Comment thread docs/commands/report.md Resolved
@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 812
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

@codecov

codecov Bot commented Jul 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.00995% with 16 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger/src/cmd/report_cmd/capgains.rs 97.05% 13 Missing ⚠️
crates/rustledger-booking/src/book.rs 99.35% 2 Missing ⚠️
crates/rustledger/src/cmd/report_cmd/mod.rs 96.77% 1 Missing ⚠️

📢 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
Copilot AI review requested due to automatic review settings July 24, 2026 04:10

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

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, units is currently emitted from Decimal's Display (d.units), which bypasses DisplayContext formatting used elsewhere in reports. Emit the units string via DisplayContext for 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, Units is rendered via d.units.to_string(), which bypasses DisplayContext formatting (and is inconsistent with Proceeds/Gain, which do use it). Render units via DisplayContext so 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
Copilot AI review requested due to automatic review settings July 24, 2026 04:19

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

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

…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
Copilot AI review requested due to automatic review settings July 24, 2026 11:45

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

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 violates BookingEngine::apply()’s precondition (booked + interpolated postings) and can trip the debug_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.

Comment thread crates/rustledger-booking/src/book.rs Resolved
Copilot AI review requested due to automatic review settings July 24, 2026 13:01
robcohen and others added 2 commits July 24, 2026 13:02
…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
@robcohen
robcohen force-pushed the feat/capgains-report branch from b1c7db6 to e96f562 Compare July 24, 2026 13:03

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

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

  • CapitalGain recording 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 no CapitalGains 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 as total * lot_units / total_units per 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 Decimal values (e.g. d.units, d.proceeds) even though other reports format numeric fields via DisplayContext (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 through DisplayContext for consistency. Either switch capgains to the same DisplayContext formatting 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,

Comment thread crates/rustledger-loader/src/process.rs Resolved
Copilot AI review requested due to automatic review settings July 24, 2026 13:07

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

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 to booked.transaction when interpolation fails can trip the apply() 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_units can introduce rounding at rust_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
Copilot AI review requested due to automatic review settings July 24, 2026 13:32

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

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 any CapitalGains 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
Copilot AI review requested due to automatic review settings July 24, 2026 14:51

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

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

…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
Copilot AI review requested due to automatic review settings July 24, 2026 15:40

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

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 as total * lot_units / total_units per matched lot. When the split is non-terminating in Decimal (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 None when 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_date is after sale_date, held_days is filtered out (becomes None), but the code still classifies the lot as short/long based on acquired_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,

Comment thread crates/rustledger-loader/Cargo.toml Resolved
Comment thread crates/rustledger-loader/src/process.rs Resolved
…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
Copilot AI review requested due to automatic review settings July 24, 2026 16:07

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

Copilot reviewed 18 out of 22 changed files in this pull request and generated 5 comments.

Comment thread crates/rustledger-booking/src/book.rs Resolved
Comment thread crates/rustledger-booking/src/book.rs Resolved
Comment thread docs/commands/report.md Resolved
Comment thread crates/rustledger-booking/src/book.rs Resolved
Copilot AI review requested due to automatic review settings July 24, 2026 16:27

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

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

  • capgains CSV output currently emits raw Decimal values for units, proceeds, cost_basis, and gain. Other reports (e.g. balances and holdings) consistently format numbers via the ledger DisplayContext and then CSV-escape the resulting strings so precision and render_commas settings 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 as total * lot_units / total_units (a potentially non-terminating Decimal division), so the per-lot Decimal values may not sum exactly to total in 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 raw Decimal values. If disposals are formatted through DisplayContext, 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
Copilot AI review requested due to automatic review settings July 24, 2026 16:46
@robcohen

Copy link
Copy Markdown
Member Author

Addressed the latest Copilot review round (commits 745f14c0, bd7aa02c):

Fixed:

  • Future-dated acquisition (negative span) → classified unknown, not silently short.
  • Zero-unit reduction → records no disposal (degenerate; guards the @@ division).
  • Negative --long-term-days → rejected with a clear error (the =-1 form; bare -1 is already a clap flag error).
  • CSV currency column now escaped like account/commodity.
  • LoadOptions::raw() doc no longer claims "no booking" (booking is mandatory now).
  • PR description rewritten to the final architecture (consumes Ledger::capital_gains, does not re-book).

Deliberate decisions (not changed), for the record:

  • @@ allocation is exact pure pro-rata, not a remainder scheme. An earlier round did use round-to-scale + last-lot-remainder; it was removed because it distorted round-dollar totals (33/67 vs 33.33/66.67) and could drive the last lot negative. Exact fractions match Python beancount; the docs/tests now say "exact pro-rata share," not "sums exactly." The uneven-split and coarse-scale (@@ 2 over four lots) regression tests pin this.
  • CSV/JSON emit raw exact Decimal, not DisplayContext. This is intentional for a tax report: the display formatter rounds to display precision (losing exact cents) and injects render_commas separators (which would corrupt CSV/JSON). Machine output must be exact.
  • Removing the booking feature is an intentional breaking change. Booking is fundamental — a loader that can't book can't compute balances — so it's now mandatory rather than a no-op feature.

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

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 as total × lot_units ÷ total_units (unrounded). For non-terminating splits in Decimal, 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 Decimal values in CSV/JSON, but other reports format numeric fields through DisplayContext even for CSV/JSON (e.g. crates/rustledger/src/cmd/report_cmd/holdings.rs:74-80 and balances.rs:42-47) and then csv_escape them to handle thousands separators. As-is, capgains CSV/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.

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