Skip to content

feat(returns): expose session.returns on the WIT component (Phase 3, #1847) - #1849

Merged
robcohen merged 11 commits into
mainfrom
feat/returns-session-wit
Jul 22, 2026
Merged

robcohen merged 11 commits into
mainfrom
feat/returns-session-wit

Conversation

@robcohen

Copy link
Copy Markdown
Member

What

Phase 3 of the investment-returns feature (#1814): expose the rustledger-returns engine to embedders via a new session.returns operation on the WIT component contract (rustledger:[email protected]). A host (rustfava) can now chart money-weighted (XIRR) and time-weighted (TWR) returns over a held ledger without re-deriving cash-flow extraction or the returns math.

This is the demand-driven first increment of Phase 3. The speculative BQL #returns virtual table (the issue's second bullet, explicitly "only if composable-query demand appears") is not included — it stays deferred until asked for. The rustfava chart itself is downstream (separate repo).

The operation

returns: func(investments: list<string>, income: list<string>, currency: string, end-date: string)
  -> result<returns-result, string>;

record returns-result {
  cash-flows: u32,
  invested: string,          // decimal strings, full precision (like amount.number)
  distributions: string,
  current-value: string,
  money-weighted: option<f64>, // annualized fractions; none when undefined
  time-weighted: option<f64>,
}
  • investments / income are account-name prefixes defining the scope boundary (mirroring the CLI's --investments / --income).
  • currency — empty falls back to the ledger's first operating_currency, matching the CLI's --currency-optional behavior.
  • end-date (YYYY-MM-DD) is the horizon + terminal-valuation date. Required, unlike the CLI's today-default — a component has no reliable clock.
  • Fallible: empty/unparseable end-date, no resolvable reporting currency, held load errors, or an unpriceable boundary/terminal flow → err(message).

How it shares the engine (no re-derivation)

SessionState::returns reuses the same booked, pad-expanded stream session.query already builds (the returns engine's documented input contract, via the padded OnceCell) and builds the PriceDatabase the same way the CLI's report returns does — so the boundary runs the exact rustledger_returns::compute_returns the CLI runs, over identical inputs.

The one duplicated piece is the trivial PriceDbOracle adapter (PriceDatabase → the returns crate's PriceOracle trait). It already exists at the CLI composition root; rustledger-returns is a leaf crate (no rustledger-query dep) so the adapter can't live beside the trait, and the CLI's is pub(super). Per canonical-function discipline the deliberate duplicate is documented at both sites with cross-references; both are pure pass-throughs to PriceDatabase::convert, so the compiler enforces agreement.

Tests

  • Native drift guard (convert.rs::returns_tests::returns_matches_direct_engine): session.returns equals a direct compute_returns over the same booked+padded stream and price index — catches any wiring divergence (wrong stream, dropped scope arg, mis-mapped field). Plus fallback/bad-date/no-currency/load-error paths.
  • WASM parity drift guard (parity.rs::session_returns_matches_native_engine): the component's returns across the wasm boundary equals the native engine. Decimal fields (rust_decimal → deterministic) match byte-for-byte; the two f64 rates within tolerance (wasm vs native float ULP).

Version

package rustledger:[email protected] → @3.9.0; API_VERSION "3.8" → "3.9" (kept in lockstep — the version_matches_wit_package parity test + CI wit-version-gate enforce this).

How to test

cargo test -p rustledger-ffi-component returns_tests
cargo build -p rustledger-ffi-component --target wasm32-wasip2
cargo test -p rustledger-ffi-component-tests session_returns_matches_native_engine

Part of #1814. Advances #1847 (BQL table intentionally still open).

Phase 3 of the investment-returns feature (#1814): add a typed `returns`
operation to the `session` resource on the WIT contract
(`rustledger:[email protected]` -> `@3.9.0`), so an embedder (rustfava) can chart
money-weighted (XIRR) and time-weighted (TWR) returns over a held ledger
without re-deriving cash-flow extraction or the returns math.

`SessionState::returns` reuses the same booked, pad-expanded stream `query`
builds (the returns engine's input contract, via the `padded` cell) and builds
the `PriceDatabase` the same way the CLI's `report returns` does, then calls
`rustledger_returns::compute_returns` — the boundary runs the exact engine over
identical inputs, so it cannot drift from the CLI. `investments`/`income` are
the scope prefixes; `currency` empty falls back to the first
`operating_currency`; `end-date` is required (a component has no clock).
Fallible on bad date / no currency / load errors / unpriceable flow.

The `PriceDbOracle` adapter is a deliberate, compiler-enforced duplicate of the
CLI's (the returns crate is a leaf without a query dep), documented at both
sites per canonical-function discipline.

Drift guards both directions: a native test pins `session.returns` against a
direct `compute_returns` over the same inputs, and a wasm parity test pins the
component's result against the native engine across the boundary (decimals exact,
rates within tolerance for wasm-vs-native float). API_VERSION bumped in lockstep
(the version-parity test + CI wit-version-gate enforce it).

The speculative BQL `#returns` table (the issue's second bullet) stays deferred
until composable-query demand appears. Advances #1847.
@robcohen
robcohen requested a review from a team as a code owner July 22, 2026 12:12
Copilot AI review requested due to automatic review settings July 22, 2026 12:12
@github-actions

github-actions Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 34.8ms ± 0.7ms 24.1 MB
beancount 782.6ms ± 6.7ms 50.7 MB
Comparison 22.5x faster 2.1x less

vs main branch (2026-07-21)

Metric main this PR Change
Time 33.5ms 34.8ms +3.9% ✅
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

Exposes the investment-returns engine (rustledger-returns) to embedders by adding a new session.returns operation to the rustledger-ffi-component WIT contract (bumping rustledger:ledger to 3.9.0 / API_VERSION to 3.9), plus native + wasm parity drift-guard tests to ensure the component wiring cannot diverge from the canonical engine.

Changes:

  • Add session.returns(...) -> result<returns-result, string> and the returns-result record to the WIT contract; bump WIT/package + runtime API version to 3.9.
  • Implement SessionState::returns in rustledger-ffi-component, wiring booked+padded directives + a PriceDatabase adapter into rustledger_returns::compute_returns.
  • Add drift-guard tests: native (in convert.rs) and wasm parity (in ffi-component-tests) to compare the component surface against direct engine execution.

Reviewed changes

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

Show a summary per file
File Description
crates/rustledger/src/cmd/report_cmd/returns.rs Documents the deliberate PriceDbOracle adapter duplication across CLI and component roots.
crates/rustledger-ffi-component/wit/world.wit Bumps WIT package to 3.9.0; adds returns-result type and session.returns operation + docs.
crates/rustledger-ffi-component/src/lib.rs Bumps API_VERSION to 3.9; wires the generated session.returns guest call into SessionState::returns.
crates/rustledger-ffi-component/src/convert.rs Implements SessionState::returns, adds PriceDbOracle adapter and native drift-guard tests.
crates/rustledger-ffi-component/Cargo.toml Adds rustledger-returns dependency to the component crate.
crates/rustledger-ffi-component-tests/tests/parity.rs Adds wasm-boundary parity drift guard for session.returns.
crates/rustledger-ffi-component-tests/Cargo.toml Adds deps needed for native-engine reference computation in parity tests.
Cargo.lock Updates lockfile for new workspace dependency edges.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@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

…nent

Addresses the deep review of the session.returns PR:

- Extract the returns wiring into `rustledger_query::{scope_returns,
  scopes_returns}` (Finding 3). The CLI's `report returns` and the component's
  `session.returns` both duplicated the same composition — build the
  PriceDatabase, adapt it to the returns engine's PriceOracle, build the Scope,
  call compute_returns — each with its own `PriceDbOracle` copy. Both surfaces
  now call the single shared helper, so they cannot compute different figures
  for the same ledger, and there is one price-oracle adapter instead of two.
  The drift guards now pin the component against that shared helper (i.e.
  against the CLI's returns path), not against a private re-implementation.

- session.returns no longer traps on recovered load errors (Finding 1). The
  resource's documented contract is that load failures surface via
  info().errors, not a trap (see from-file), and session.format — the sibling
  result<_,string> op — already computes over the held directives regardless.
  returns now matches that convention and the CLI report, which prints load
  errors to stderr and still renders. The WIT/# Errors docs and the load-error
  test are updated to the proceed-and-surface behavior.

- Document that the returns-result decimal fields are RAW, full-precision
  strings (matching amount.number), NOT display-formatted like the CLI's
  rendered report — no thousands separators or precision padding; the host
  formats for its locale (Finding 2). This is the correct convention for a
  programmatic surface, so it is documented rather than changed.

- Note that the usize->u32 cash_flows clamp is unreachable defensive code, not
  a lossy path (Finding 4).

Finding 5 (the parity test skips without the wasm artifact) follows the
file-wide convention and is exercised by the "Component Parity (wasip2)" CI job.

Tests: CLI returns 15 unit + 1 integration; component 28 native (incl. the
proceed-on-recovered-errors case) + the wasm parity drift guard; query 170.
Copilot AI review requested due to automatic review settings July 22, 2026 13:12

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 10 out of 11 changed files in this pull request and generated 1 comment.

Second review pass on #1849 found that dropping the load-error guard (the
first-pass response to "match the CLI / the not-a-trap convention") exposed a
real hazard: the loader re-merges a booking-FAILED transaction into the held
directives in its un-booked shape, and session.returns REALIZES inventory over
them. Realizing an un-booked reduction (over-sell with no matching lot)
`debug_assert`-traps the booking engine in debug and silently over-sells in
release — a wrong figure a host would chart as truth.

The correct reading of the WIT contract's "load failures surface via
info().errors, NOT a trap" is that a realizing op must NOT risk that trap:
returning a clean `Err` IS surfacing, not trapping. `session.query` guards for
exactly this reason; `format`/`filter`/`clamp` don't realize, so they proceed.
So reinstate the guard — with a comment explaining why returns follows query,
not format — and add a regression test on an actual booking failure (buy 5,
sell 10 with empty cost) that would abort the native test without the guard.

Also from the review:
- Centralize the price-oracle adapter as `PriceDatabase::as_oracle()`, removing
  the third (CLI-test) copy; the shared helpers and the CLI test now share one
  adapter (Finding 8).
- Add the missing `# Errors` section to `scopes_returns` (Finding 6).

Findings 2 (drift guard scoped to the shared helper) and 5 (per-scope
PriceDatabase rebuild) are unchanged: the guard pins component→shared-helper
which the CLI also calls, and the single-scope rebuild is not a regression (the
component builds the index per call as it did before the refactor).

Tests: component 29 native (incl. the booking-error trap guard) + parity 24;
CLI returns 15+1; query 170. clippy + doc clean.
Copilot AI review requested due to automatic review settings July 22, 2026 13: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 11 out of 12 changed files in this pull request and generated 1 comment.

Comment thread crates/rustledger-query/src/price.rs Resolved
… trap

Third review pass found the reinstated guard was incomplete: it only covers
from_source/from_file sessions. `from_entries`/`from_entries_with_options` set
`errors: vec![]` and don't run booking, so an over-sell in held entries bypassed
the guard and reached the realization; and the CLI `report returns` has the
identical exposure with no guard at all. The root cause is that the returns
realization traps (debug) / silently over-sells (release) on the un-booked
transactions the loader re-merges into `Ledger.directives`.

Fix it at the source, closing all three paths (from_source, from_entries, CLI):

- rustledger-booking: add a fallible `BookingEngine::try_apply` that returns
  `Err` the moment a reduction has no matching lot, instead of `debug_assert`ing
  / ignoring. `apply` keeps its exact contract (ignore-and-continue), now sharing
  one `apply_posting` core with `try_apply` so the two can't drift.
- rustledger-returns: the three realization sites use `try_apply` and surface a
  new `ExtractError::UnbookedInput`; compute_returns / twr / *_multi now return a
  clean `Err` on a contract-violating stream rather than trapping. The now-stale
  `# Panics` sections are reframed accordingly.

With the engine fix the trap is impossible, so both surfaces error cleanly: the
component's guard stays (early-out + parity with `query`) but is no longer the
only thing standing between an un-booked entry set and a wasm trap.

Regression tests that would ABORT without the fix: returns-crate
`unbooked_oversell_errors_not_traps`; component
`returns_from_entries_oversell_errors_not_traps` (the bypassed from_entries
path); CLI `compute_group_errors_on_unbooked_oversell_not_traps` (the
pre-existing CLI exposure).

Tests: booking 110, returns 60, loader 95, validate 103 (apply refactor
downstream-safe); component 7 returns + parity 24; CLI 16+1; query 170. clippy +
doc clean.
Copilot AI review requested due to automatic review settings July 22, 2026 14:23

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 13 out of 14 changed files in this pull request and generated 4 comments.

Comment thread crates/rustledger-query/src/returns.rs Resolved
Comment thread crates/rustledger-query/src/returns.rs Resolved
Comment thread crates/rustledger-query/src/returns.rs Resolved
Fourth review pass. The booking-engine refactor's blast radius came back clean,
but two engine-fix interactions survived:

- Public `twr` could swallow `UnbookedInput` into `Ok(None)`. `twr_from_values`
  short-circuits to `Ok(None)` at an earlier non-positive / wiped-out sub-period
  (a documented lazy behavior for MissingPrice), which can return before the loop
  reaches a later un-booked flow value — so a broken ledger was reported as
  "n/a" instead of erroring. `compute_returns` is protected by its eager terminal
  valuation, but standalone `twr` (public) was not. Add an eager scan that
  surfaces `UnbookedInput` before the lazy short-circuits; `MissingPrice` stays
  lazy (a later price gap is genuinely irrelevant once the chain is undefined).
  Regression test `twr_surfaces_unbooked_despite_earlier_short_circuit`.

- Doc accuracy: `scope_returns`' stale `# Panics` (the engine now returns
  `Err`, doesn't panic; the cross-referenced section was removed) and
  `scopes_returns`' `# Errors` (omitted `UnbookedInput`) are corrected. Both now
  state that `UnbookedInput` is NOT per-scope: the booking pass is shared, so a
  contract-violating ledger fails every scope — `report returns --by-group`
  errors wholesale rather than rendering a partial report over a broken ledger,
  consistent with single-scope `report returns`. This is deliberate (a partial
  report would need per-scope booking isolation and mask a broken ledger), now
  documented on `compute_returns_multi`.

Tests: returns 61; component 7 returns; CLI 16. clippy + doc clean. No
production change outside rustledger-returns (twr) + docs.
Copilot AI review requested due to automatic review settings July 22, 2026 14:50

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 13 out of 14 changed files in this pull request and generated 1 comment.

… fava

Fifth review pass. The booking-engine change came back clean; the surviving
correctness item was that the shared realization books EVERY account, so
switching to try_apply made an over-sell in an account OUTSIDE the returns scope
abort the whole report — where release builds previously ignored it and still
valued the in-scope accounts.

Prior art decides it: the beancount ecosystem is lenient — the loader always
returns entries alongside errors, and fava renders reports over
loaded-with-errors entries with errors surfaced separately. rledger mirrors this
(`check` is the strict gate; `report returns` prints errors and proceeds). So a
booking error OUTSIDE the returns scope should not block an in-scope report.

- rustledger-booking: expose `BookingEngine::try_apply_posting` (the per-posting
  core `apply`/`try_apply` already share), so a consumer can realize a subset of
  a transaction's postings.
- rustledger-returns: the three realization sites now book only the postings
  they will VALUE (in-scope Investment accounts) via a new `apply_scoped` helper.
  An over-sell outside the scope is skipped, not fatal; an in-scope over-sell
  still surfaces as `UnbookedInput` (its valuation would otherwise be wrong).
  Clean-ledger output is byte-identical (out-of-scope postings never touched the
  valued inventories). Test: `out_of_scope_oversell_does_not_abort_report`.

- rustledger-ffi-component: with the engine trap-safe and out-of-scope errors
  skipped, the `self.errors` guard made session.returns STRICTER than the CLI
  (refusing on any load error). Remove it so the component computes over the held
  directives exactly as the CLI renders — the fava model, errors via
  info().errors — with the engine providing safety. session.returns and CLI
  `report returns` now agree on every ledger, broken or not. Component tests
  updated: proceeds over a recovered parse error; an in-scope over-sell still
  errs (now via the engine, no guard).

Also clarified (from the review) that the twr eager UnbookedInput scan is inert
for compute_returns (protected by its eager current_value) and kept only for the
standalone public twr contract.

Tests: booking 110, returns 62, loader 95, validate 103; component 7 + parity
24; CLI returns 16. clippy + doc clean.
Copilot AI review requested due to automatic review settings July 22, 2026 15:37

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 13 out of 14 changed files in this pull request and generated 1 comment.

Comment thread crates/rustledger-query/src/returns.rs Resolved
…nput

Sixth review pass. The scope-filter's fundamental soundness held (an in-scope
account's lot-matching never depends on a skipped out-of-scope posting — lots
are per-account), but three real issues surfaced:

- --by-group could error a CLEAN group. `investment_values_multi` books the
  UNION of every scope's investment accounts in one shared pass, so an over-sell
  in group A's account errored and stamped `UnbookedInput` into EVERY scope —
  including a clean, disjoint group B that values fine on its own (and does via
  the single-scope path and the unsorted fallback). Fix: on a booking error the
  shared pass now degrades to the per-scope realization (exactly the unsorted
  fallback), so only the group owning the un-booked reduction errors. Test
  `multi_isolates_oversell_to_the_owning_scope` (date-sorted, so it exercises
  the shared pass, not the fallback).

- Silent understatement on elided in-scope input. `try_apply_posting` skips a
  posting whose units aren't `Complete`, so an un-booked in-scope leg (elided,
  not yet interpolated — reachable via a raw `from_entries` set) was dropped
  from the valuation with no error. `apply_scoped` now surfaces an in-scope
  non-`Complete` posting as `UnbookedInput` rather than understating. Test
  `elided_in_scope_posting_errors_not_understates`.

- Dead code. `BookingEngine::try_apply` (whole-transaction) had zero callers
  after the pass-5 switch to per-posting `try_apply_posting`; removed, and the
  two doc cross-references + the `apply` debug-assert hint repointed.

Clean-ledger output stays byte-identical (out-of-scope postings never touched
the valued inventories; the union pass equals per-scope on a clean stream).

Tests: booking 110, returns 64, loader 95, validate 103; component 7 + parity
24; CLI 16. clippy + doc clean.
Copilot AI review requested due to automatic review settings July 22, 2026 16:04

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 13 out of 14 changed files in this pull request and generated no new comments.

Comments suppressed due to low confidence (1)

crates/rustledger-query/src/price.rs:560

  • as_oracle currently returns the concrete PriceDbOracle type and is marked const, which unnecessarily exposes the adapter type in the public API and makes it harder to change the adapter implementation later without a breaking change. Since this method is newly introduced, consider returning an opaque impl PriceOracle instead (and dropping const).
    #[must_use]
    pub const fn as_oracle(&self) -> PriceDbOracle<'_> {
        PriceDbOracle(self)
    }

Eighth review pass (a coherence review of the strict-clean revert; the refuted
finding confirmed the strict behavior is intended). Three items:

- Elided un-booked postings silently understated (CONFIRMED correctness). The
  strict-clean contract is "un-booked ledger -> clean Err", and an unmatched
  reduction already surfaces via the fallible realization. But `try_apply` SKIPS
  a non-Complete (elided / uninterpolated) posting, so an un-booked in-scope
  investment leg was dropped from the valuation with no error — a silently
  understated figure, the exact thing strict-clean exists to prevent. Add an
  `apply_booked` helper (used at all three realization sites) that rejects a
  transaction with any elided posting as `UnbookedInput`, alongside the existing
  over-sell detection. Test `unbooked_elided_posting_errors_not_understates`.

- The `twr` eager `UnbookedInput` scan lived in the shared `twr_from_values` hot
  path, where it's inert for `compute_returns` (protected by its eager
  `end_value?`). Moved it to the standalone public `twr` wrapper — the only path
  that needs it — off the per-scope hot path. The unit test is retargeted from
  `twr_from_values` to the public `twr`.

- Fixed the stale module `# Input contract` doc that still claimed un-booked
  reductions are "silently dropped into wrong inventory" — they now surface as
  `UnbookedInput`.

(Out of scope: the reviewer also flagged the #1848 XIRR golden constants having
no CI guard re-running the reference script — pre-existing on main, not this PR.)

Tests: returns 62; component 7 + parity 24; CLI 16. clippy + doc clean.
Copilot AI review requested due to automatic review settings July 22, 2026 17:21

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 13 out of 14 changed files in this pull request and generated 2 comments.

Comment thread crates/rustledger-booking/src/book.rs Resolved
…_markdown)

CI pins clippy 1.97.0, whose `doc_markdown` lint is stricter than the nix-pinned
1.96.0 used locally — it flags `compute_group` / `scope_returns` in a test doc
comment as needing backticks. This tripped the CI Clippy check (has been red
since the engine-fix commit; local per-crate clippy under 1.96.0 didn't catch
it). No behavior change.
Copilot AI review requested due to automatic review settings July 22, 2026 17:38

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 13 out of 14 changed files in this pull request and generated no new comments.

…docs

- The component's no-reporting-currency error used a `\` line-continuation with
  an indented next line, embedding a run of spaces into the message. Collapse to
  a single-line literal.
- `apply_booked`'s elided-input error now names the offending account (via
  `find` instead of `any`), not just the transaction date.
- `BookingEngine::try_apply` rustdoc: clarify it catches an unmatched reduction
  but still SKIPS an elided/uninterpolated posting (like `apply`), so a caller
  that must reject elided input checks `units` itself (as the returns realization
  does in `apply_booked`).

No behavior change beyond the two message strings.
Copilot AI review requested due to automatic review settings July 22, 2026 18:20

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 13 out of 14 changed files in this pull request and generated no new comments.

@robcohen
robcohen merged commit 043720a into main Jul 22, 2026
124 checks passed
@robcohen
robcohen deleted the feat/returns-session-wit branch July 22, 2026 19:02
@codecov

codecov Bot commented Jul 22, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.96907% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-booking/src/book.rs 96.77% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

robcohen added a commit that referenced this pull request Jul 23, 2026
Net-units valuation isolates scopes — each sums only its own accounts — so one
group hitting an unvaluable input (an in-scope account with an elided posting, or
a commodity with no price) no longer has to fail the whole report. This finishes
the #1850 §4 CLI rendering that the net-units core (#1851) unblocked.

Previously the `--by-group` path `?`-aborted on the first per-scope error (the
#1849 seventh-review finding), nuking the TOTAL and every other group. Now each
scope is computed independently and a failure becomes a row-level `n/a` marker
with a stderr warning naming the group and reason, while the computable groups
render their figures. Only if EVERY row (TOTAL included) is unvaluable does the
report fail loudly — there is then nothing to show.

- report_returns: build `Vec<GroupRow>` (Ok | Unvaluable{label, reason}) instead
  of `?`-aborting; warn per unavailable scope; bail only when all are unvaluable.
- render_grouped: render `n/a` in every figure column for an unvaluable row
  (text/CSV); JSON keeps a stable schema — every row gains an `error` field
  (`null` when computed, the reason string when not) with `null` figures.
- Tests: a direct render_grouped test (text + JSON schema) and an end-to-end
  report_returns --by-group test (one valuable group + one elided-in-scope group
  → partial render, TOTAL n/a, report succeeds).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
robcohen added a commit that referenced this pull request Jul 23, 2026
#1850 §6 (with §5 edge cases): a suite exercising net-units returns over the
imperfect/imported ledgers this effort targets, through the SHARED
scope_returns/scopes_returns composition (the exact path the CLI and the WIT
component take), so it also pins real PriceDatabase price resolution.

Cases (crates/rustledger-query/tests/messy_returns_test.rs):
- over-sell of an empty-cost {} lot → net −5, valued at market (−600), tolerated;
- missing opening buy (importer started mid-history) → short net position;
- clean empty-cost {} reduction → net units valued identically;
- falling prices → a real NEGATIVE money- and time-weighted rate (beangrow
  CRASHES here — beangrow#4 / #16; our Newton+Brent xirr returns Option<f64>);
- near-total loss → defined large-negative rate, no crash;
- missing intermediate price (late first price) → MWR computes from cash flows +
  priced terminal, TWR degrades to None (not an error) — the §5 missing-price
  policy;
- per-scope isolation: an elided in-scope scope fails alone (UnbookedInput) while
  a clean scope computes, over one shared accumulation (what --by-group relies on).

Also corrects the scope_returns/scopes_returns doc comments (§2), which still
carried the #1849 strict-clean language — now contradicted by the net-units
model: cost-basis/lot errors are tolerated, and UnbookedInput is PER-SCOPE, not a
whole-ledger abort.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
robcohen added a commit that referenced this pull request Jul 23, 2026
Net-units valuation isolates scopes — each sums only its own accounts — so one
group hitting an unvaluable input (an in-scope account with an elided posting, or
a commodity with no price) no longer has to fail the whole report. This finishes
the #1850 §4 CLI rendering that the net-units core (#1851) unblocked.

Previously the `--by-group` path `?`-aborted on the first per-scope error (the
#1849 seventh-review finding), nuking the TOTAL and every other group. Now each
scope is computed independently and a failure becomes a row-level `n/a` marker
with a stderr warning naming the group and reason, while the computable groups
render their figures. Only if EVERY row (TOTAL included) is unvaluable does the
report fail loudly — there is then nothing to show.

- report_returns: build `Vec<GroupRow>` (Ok | Unvaluable{label, reason}) instead
  of `?`-aborting; warn per unavailable scope; bail only when all are unvaluable.
- render_grouped: render `n/a` in every figure column for an unvaluable row
  (text/CSV); JSON keeps a stable schema — every row gains an `error` field
  (`null` when computed, the reason string when not) with `null` figures.
- Tests: a direct render_grouped test (text + JSON schema) and an end-to-end
  report_returns --by-group test (one valuable group + one elided-in-scope group
  → partial render, TOTAL n/a, report succeeds).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
robcohen added a commit that referenced this pull request Jul 23, 2026
#1850 §6 (with §5 edge cases): a suite exercising net-units returns over the
imperfect/imported ledgers this effort targets, through the SHARED
scope_returns/scopes_returns composition (the exact path the CLI and the WIT
component take), so it also pins real PriceDatabase price resolution.

Cases (crates/rustledger-query/tests/messy_returns_test.rs):
- over-sell of an empty-cost {} lot → net −5, valued at market (−600), tolerated;
- missing opening buy (importer started mid-history) → short net position;
- clean empty-cost {} reduction → net units valued identically;
- falling prices → a real NEGATIVE money- and time-weighted rate (beangrow
  CRASHES here — beangrow#4 / #16; our Newton+Brent xirr returns Option<f64>);
- near-total loss → defined large-negative rate, no crash;
- missing intermediate price (late first price) → MWR computes from cash flows +
  priced terminal, TWR degrades to None (not an error) — the §5 missing-price
  policy;
- per-scope isolation: an elided in-scope scope fails alone (UnbookedInput) while
  a clean scope computes, over one shared accumulation (what --by-group relies on).

Also corrects the scope_returns/scopes_returns doc comments (§2), which still
carried the #1849 strict-clean language — now contradicted by the net-units
model: cost-basis/lot errors are tolerated, and UnbookedInput is PER-SCOPE, not a
whole-ledger abort.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
robcohen added a commit that referenced this pull request Jul 23, 2026
…1851)

* feat(returns): value net units at market, not lot-matched inventory

Money-weighted (XIRR) and time-weighted returns depend on cash flows and
terminal market value (net units × price), never on cost-basis lots. So the
returns engine no longer realizes holdings through the lot-matching
BookingEngine — which traps/over-sells on an unmatched reduction — but sums
each account's complete posting units per commodity WITHOUT lot-matching and
values the net at market.

This makes a cost-basis/lot error a non-event for the report: an over-sell, or
an empty-cost `{}` sale with no matching lot (the common state of imported
brokerage data), simply nets the units — possibly negative — and is valued at
market, like beancount + beangrow. `rledger check` remains the validator. The
one input net-units genuinely cannot value is an in-scope account with an
elided/uninterpolated posting (its net units are unknown), which still surfaces
as ExtractError::UnbookedInput.

This reverses the strict-clean broken-ledger behavior shipped in #1849 (any
booking error → clean Err), which research showed blocks the common
imported-ledger workflow beangrow serves correctly (see reframed #1850).

- extract.rs: NetUnits accumulator replaces the BookingEngine in
  investment_value_at / investment_values_at / investment_values_multi; the
  apply pass can no longer error (valuation errors move per-date/per-scope, so
  UnbookedInput is now per-scope in the --by-group path).
- Drop the rustledger-booking dependency from rustledger-returns; remove the
  now-dead BookingEngine::try_apply from rustledger-booking.
- Rewrite the #1849 strict-clean tests (returns, CLI, FFI component) to assert
  the tolerant net-units behavior: an over-sell nets negative and values at
  market; only an elided in-scope posting errors.
- Clean-ledger output is byte-identical (existing drift guards stay green).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU

* fix(returns): error on elided boundary leg; align docs + drift guard (review)

Addresses a deep-review pass over the #1850 stack.

CORRECTNESS (the blocker): extract_flows silently dropped an elided/uninterpolated
EXTERNAL (boundary cash) leg of a portfolio-touching transaction, so a re-merged
booking-failed txn whose cash leg could not be interpolated (empty-cost {} buy)
valued the complete investment leg at market with NO matching outflow — a wrong
money-weighted return / understated `invested`, returned Ok. The pre-net-units
path errored on this. Now extract_flows surfaces it as UnbookedInput, the flows
counterpart of value_investment_scopes

* docs(returns): sweep stale booked wording; broaden elided-error contract (review 2)

Second review pass found documentation drift left by the booked -> interpolated
contract reframe, plus a contract narrowed too far after the elided-external-leg
fix. No behavior change.

- extract.rs module header (lines 1, 4) still said "turn a booked ledger" /
  "Given a booked directive stream"; extract_flows body doc said "Expects the
  booked, pad-expanded stream". Both now say interpolated, matching the rewritten
  input-contract section and the tolerant net-units model.
- The UnbookedInput variant doc, extract_cash_flows # Errors, the FFI returns()
  # Errors, and world.wit all described the error as firing only for an in-scope
  elided holding. The elided-external-leg fix also fires it for an external
  boundary leg (unknown cash flow), so all four now name BOTH shapes.
- FFI returns() rustdoc + the session.returns drift-guard comment still said
  "over the same booked, pad-expanded stream" -> interpolated (booking not
  required; net units valued at market).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU

* fix(returns): clearer elided-units error text; add per-scope isolation test (copilot)

Addresses Copilot review threads on #1851:
- The elided-units errors said "un-booked (elided)", which evokes lot-matching;
  reworded both (extract_flows + value_investment_scope) to "elided/uninterpolated",
  matching what the net-units path actually rejects.
- Added compute_returns_multi_isolates_an_unvaluable_scope: over one shared
  accumulation, a scope with an elided in-scope account errors UnbookedInput while
  a disjoint clean scope still computes Ok — the per-scope isolation --by-group
  partial rendering depends on.
- Fixed a grammar slip in the UnbookedInput variant doc ("input that net-units").

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request Jul 23, 2026
Net-units valuation isolates scopes — each sums only its own accounts — so one
group hitting an unvaluable input (an in-scope account with an elided posting, or
a commodity with no price) no longer has to fail the whole report. This finishes
the #1850 §4 CLI rendering that the net-units core (#1851) unblocked.

Previously the `--by-group` path `?`-aborted on the first per-scope error (the
#1849 seventh-review finding), nuking the TOTAL and every other group. Now each
scope is computed independently and a failure becomes a row-level `n/a` marker
with a stderr warning naming the group and reason, while the computable groups
render their figures. Only if EVERY row (TOTAL included) is unvaluable does the
report fail loudly — there is then nothing to show.

- report_returns: build `Vec<GroupRow>` (Ok | Unvaluable{label, reason}) instead
  of `?`-aborting; warn per unavailable scope; bail only when all are unvaluable.
- render_grouped: render `n/a` in every figure column for an unvaluable row
  (text/CSV); JSON keeps a stable schema — every row gains an `error` field
  (`null` when computed, the reason string when not) with `null` figures.
- Tests: a direct render_grouped test (text + JSON schema) and an end-to-end
  report_returns --by-group test (one valuable group + one elided-in-scope group
  → partial render, TOTAL n/a, report succeeds).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
robcohen added a commit that referenced this pull request Jul 23, 2026
…§4) (#1852)

* feat(returns): render --by-group partial report on unvaluable scopes

Net-units valuation isolates scopes — each sums only its own accounts — so one
group hitting an unvaluable input (an in-scope account with an elided posting, or
a commodity with no price) no longer has to fail the whole report. This finishes
the #1850 §4 CLI rendering that the net-units core (#1851) unblocked.

Previously the `--by-group` path `?`-aborted on the first per-scope error (the
#1849 seventh-review finding), nuking the TOTAL and every other group. Now each
scope is computed independently and a failure becomes a row-level `n/a` marker
with a stderr warning naming the group and reason, while the computable groups
render their figures. Only if EVERY row (TOTAL included) is unvaluable does the
report fail loudly — there is then nothing to show.

- report_returns: build `Vec<GroupRow>` (Ok | Unvaluable{label, reason}) instead
  of `?`-aborting; warn per unavailable scope; bail only when all are unvaluable.
- render_grouped: render `n/a` in every figure column for an unvaluable row
  (text/CSV); JSON keeps a stable schema — every row gains an `error` field
  (`null` when computed, the reason string when not) with `null` figures.
- Tests: a direct render_grouped test (text + JSON schema) and an end-to-end
  report_returns --by-group test (one valuable group + one elided-in-scope group
  → partial render, TOTAL n/a, report succeeds).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU

* fix(returns): assert the by-group JSON error field structurally (review)

The render_grouped_marks_unvaluable_rows JSON check ended in a substring OR
(... || json.contains "un-booked") — the reason text matched anywhere in the
blob, so a malformed or misplaced error key would still pass green (the
substring-proxy anti-pattern CLAUDE.md calls out). Parse the JSON and assert the
error FIELD structurally: the computed row's error is null with figures present,
the unvaluable row and the TOTAL carry the exact reason on error with every
figure null — the stable schema a consumer actually branches on.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU

* fix(returns): exit non-zero on a partial --by-group report (review 2)

Second review pass, finding [0]: the §4 partial render turned EVERY per-scope
error non-fatal, including MissingPrice — so a --by-group report with one
unpriceable group emitted an n/a row and exited 0, where the single-scope path
(and origin/main) exited non-zero. CSV/text carry no error column, so a pipeline
gating on exit status treated a silently-incomplete report as full success.

Now report_returns still RENDERS the computable rows + n/a markers, then returns
Err so the CLI exits non-zero — the incomplete-report signal for pipelines (JSON
also carries a per-row `error` field; the exit code is the only machine-readable
signal for CSV/text). Only a fully-computable report exits 0; an all-unvaluable
report still bails before rendering as before.

Tests: the end-to-end unit test now asserts the partial output is written AND the
call returns Err; a new subprocess test (by_group_partial_report_renders_but_exits_nonzero)
pins the actual non-zero exit + partial stdout + stderr reason.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU

* fix(returns): sanitize user-controlled group label in the unavailable warning (copilot)

The per-scope unavailable warning printed the raw returns-group label, which is
user-controlled and can carry control chars / newlines (log/terminal injection —
spoofed lines, escape sequences). Route it through sanitize_display, the same
guard the grouping warnings already use. The error text is grammar-constrained
(account names / currencies), so it needs no sanitizing.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request Jul 23, 2026
#1850 §6 (with §5 edge cases): a suite exercising net-units returns over the
imperfect/imported ledgers this effort targets, through the SHARED
scope_returns/scopes_returns composition (the exact path the CLI and the WIT
component take), so it also pins real PriceDatabase price resolution.

Cases (crates/rustledger-query/tests/messy_returns_test.rs):
- over-sell of an empty-cost {} lot → net −5, valued at market (−600), tolerated;
- missing opening buy (importer started mid-history) → short net position;
- clean empty-cost {} reduction → net units valued identically;
- falling prices → a real NEGATIVE money- and time-weighted rate (beangrow
  CRASHES here — beangrow#4 / #16; our Newton+Brent xirr returns Option<f64>);
- near-total loss → defined large-negative rate, no crash;
- missing intermediate price (late first price) → MWR computes from cash flows +
  priced terminal, TWR degrades to None (not an error) — the §5 missing-price
  policy;
- per-scope isolation: an elided in-scope scope fails alone (UnbookedInput) while
  a clean scope computes, over one shared accumulation (what --by-group relies on).

Also corrects the scope_returns/scopes_returns doc comments (§2), which still
carried the #1849 strict-clean language — now contradicted by the net-units
model: cost-basis/lot errors are tolerated, and UnbookedInput is PER-SCOPE, not a
whole-ledger abort.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
robcohen added a commit that referenced this pull request Jul 23, 2026
* test(returns): messy-imported-ledger suite; correct query returns docs

#1850 §6 (with §5 edge cases): a suite exercising net-units returns over the
imperfect/imported ledgers this effort targets, through the SHARED
scope_returns/scopes_returns composition (the exact path the CLI and the WIT
component take), so it also pins real PriceDatabase price resolution.

Cases (crates/rustledger-query/tests/messy_returns_test.rs):
- over-sell of an empty-cost {} lot → net −5, valued at market (−600), tolerated;
- missing opening buy (importer started mid-history) → short net position;
- clean empty-cost {} reduction → net units valued identically;
- falling prices → a real NEGATIVE money- and time-weighted rate (beangrow
  CRASHES here — beangrow#4 / #16; our Newton+Brent xirr returns Option<f64>);
- near-total loss → defined large-negative rate, no crash;
- missing intermediate price (late first price) → MWR computes from cash flows +
  priced terminal, TWR degrades to None (not an error) — the §5 missing-price
  policy;
- per-scope isolation: an elided in-scope scope fails alone (UnbookedInput) while
  a clean scope computes, over one shared accumulation (what --by-group relies on).

Also corrects the scope_returns/scopes_returns doc comments (§2), which still
carried the #1849 strict-clean language — now contradicted by the net-units
model: cost-basis/lot errors are tolerated, and UnbookedInput is PER-SCOPE, not a
whole-ledger abort.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU

* docs(returns): fix scope_returns booked wording + elided-error contract (review 2)

Second review pass doc drift, query composition root:
- scope_returns summary said "from a booked, pad-expanded stream" -> interpolated
  (booking not required; net units valued at market).
- scope_returns/scopes_returns # Errors described UnbookedInput as firing only for
  an in-scope elided holding; the elided-external-leg fix also fires it for an
  external boundary leg (unknown cash flow), so both now name BOTH shapes.

Doc-only; no behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
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