Skip to content

feat(report): render numbers through the ledger DisplayContext (U4) - #1750

Merged
robcohen merged 3 commits into
mainfrom
feat/reports-display-context
Jul 10, 2026
Merged

robcohen merged 3 commits into
mainfrom
feat/reports-display-context

Conversation

@robcohen

Copy link
Copy Markdown
Member

What

Balance-style reports (balances, balsheet, income, holdings, networth) now render numbers through the ledger's DisplayContext — per-currency inferred precision (MostCommon policy), option "display_precision" overrides, and render_commas — instead of raw Decimal Display. This is U4, the last deferred item from the Phase-1 sweep.

Why

Raw Display precision is an artifact of booking arithmetic, not ledger convention. An integer-written posting in a 2dp ledger rendered as 100 USD in reports where bean-query prints 100.00 USD — and where our own BQL output has been context-aware since #961/#985. Reports were the one CLI surface where the precision/locale machinery didn't reach.

How

LoadedReport carries the loader's DisplayContext (same threading pattern as account_types in #1731); the five reports format every units number and total via format_amount_number. One rendering per report — text, CSV, and JSON arms print the same formatted string. Lot-cost annotations keep their existing Display form (pinned to bean-query's Position string in #1728/#1733) — only units and totals change.

User-visible change (flagged like #1728)

Numbers in report output can change: integer-scale amounts pad to the ledger's conventional precision (100 → 100.00 in a 2dp ledger), over-scale outliers quantize to the mode, and display_precision/render_commas options now take effect in reports. CSV/JSON consumers see the same formatted strings as text.

Verification

  • Byte-identical to beancount 3.2.3 bean-query BALANCES on a mixed-precision fixture — in both directions of the MostCommon policy: a 2dp-dominant ledger pads the integer transfer to 100.00; an integer-dominant ledger renders 2400 (my first test fixture got this wrong and the implementation matched bean-query, not the test — the mode wins, exactly as upstream).
  • New integration test pins the padded rendering and text/CSV consistency.
  • Full CLI suite green, including the chore(test): pin BQL BALANCES == report balances on netted reductions #1733 query == report realization-parity guard — which now compares two context-formatted surfaces instead of one formatted and one raw.
  • clippy clean on 1.96 and 1.97; fmt clean.

🤖 Generated with Claude Code

Balance-style reports (balances, balsheet, income, holdings, networth)
printed raw Decimal Display, whose precision is an artifact of booking
arithmetic rather than ledger convention: an integer-written posting
in a 2dp ledger showed "100 USD" where bean-query (and our own BQL
output, context-aware since #961/#985) shows "100.00 USD".

LoadedReport now carries the loader's DisplayContext (per-currency
inferred precision under the MostCommon policy, display_precision
overrides, render_commas) and the five reports format every units
number and total through format_amount_number — one rendering shared
by text, CSV, and JSON arms. Lot-cost annotations keep their existing
Display form (pinned to bean-query's Position string in #1728/#1733).

Verified byte-identical against beancount 3.2.3 bean-query BALANCES on
a mixed-precision fixture, including both directions of the MostCommon
policy: 2dp-dominant ledgers pad integers to 100.00, integer-dominant
ledgers render 2400 — matching bean-query in each case. New
integration test pins the padded rendering and CSV consistency; full
CLI suite (incl. the #1733 query==report parity guard) green.

Co-Authored-By: Claude Fable 5 <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner July 10, 2026 14:46
Copilot AI review requested due to automatic review settings July 10, 2026 14:46
@codecov

codecov Bot commented Jul 10, 2026 •

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 35.3ms ± 0.8ms 23.8 MB
beancount 785.6ms ± 8.8ms 50.6 MB
Comparison 22.3x faster 2.1x less

vs main branch (2026-07-10)

Metric main this PR Change
Time 33.7ms 35.3ms +4.7% ✅
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

This PR updates balance-style CLI reports to render all unit/total numbers via the loader’s DisplayContext (MostCommon per-currency precision inference, display_precision override, and render_commas), aligning report output with existing BQL/bean-query formatting behavior.

Changes:

  • Thread DisplayContext through LoadedReport and into balances, balsheet, income, holdings, and networth renderers.
  • Replace raw Decimal rendering with DisplayContext::format_amount_number for per-currency quantized/padded formatting across text/CSV/JSON outputs.
  • Add an integration test pinning padded rendering and text/CSV consistency for reports.

Reviewed changes

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

Show a summary per file
File Description
crates/rustledger/tests/report_display_context_test.rs Adds integration coverage for context-aware report rendering (text + CSV).
crates/rustledger/src/cmd/report_cmd/mod.rs Threads loader DisplayContext through LoadedReport and report dispatch.
crates/rustledger/src/cmd/report_cmd/balances.rs Uses DisplayContext formatting for balances row amounts.
crates/rustledger/src/cmd/report_cmd/balsheet.rs Uses DisplayContext formatting for per-account amounts and net worth totals.
crates/rustledger/src/cmd/report_cmd/income.rs Uses DisplayContext formatting for per-account amounts and net income totals.
crates/rustledger/src/cmd/report_cmd/holdings.rs Uses DisplayContext formatting for units and cost basis.
crates/rustledger/src/cmd/report_cmd/networth.rs Uses DisplayContext formatting for net worth amounts across periods.

💡 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 811
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

…eview)

render_commas puts thousands separators inside formatted numbers, so
every CSV arm writing them raw produced rows with extra columns — all
five reports now csv_escape the numeric fields (RFC-4180 quoting).
Also the balsheet Net Worth CSV row gains its empty trailing cost
field to match the five-column header. New test drives
option "render_commas" "TRUE" end-to-end and asserts quoted amounts
plus quote-aware column counts on every row.

Co-Authored-By: Claude Fable 5 <[email protected]>
robcohen added a commit that referenced this pull request Jul 10, 2026
…1751)

The #1749 workflow pin collided with rust-toolchain.toml's
channel = "stable": rustup's file-based override BEATS the toolchain
dtolnay installs targets for, so cargo ran under the auto-installed
"stable" toolchain while wasm32-wasip2 std was added only to the
"1.97.0" install — Component Parity failed on #1750 with "can't find
crate for `std`". Invisible on #1749's own CI because workflow-only
changes skip the component jobs (should_build gate).

rust-toolchain.toml now pins the same version, with LOCKSTEP notes in
both places so a future bump moves them together. Verified locally:
the file override resolves to 1.97.0 and the wasip2 component builds.

Co-authored-by: Claude Fable 5 <[email protected]>
@robcohen
robcohen enabled auto-merge (squash) July 10, 2026 16:24
@robcohen
robcohen merged commit be86bf5 into main Jul 10, 2026
42 checks passed
@robcohen
robcohen deleted the feat/reports-display-context branch July 10, 2026 16:32
@robcohen robcohen mentioned this pull request Jul 11, 2026
robcohen added a commit that referenced this pull request Jul 29, 2026
Deep review of #1893 found a third surface with the same defect and showed
the per-writer approach was the cause, not a one-off.

## `query --format beancount` put separators in ledger text

It emitted `1,234,567.89 USD` — ledger source, from the command whose sibling
`format` strips separators precisely because ledger text has one canonical
form. Pre-existing on main, and the previous commit's own documentation made
it a contradiction.

## `report --format csv` and `--format json` did too

The first commit fixed `query`'s CSV only. `report` has its own format enum
and its own eight call sites passing the raw ledger context, so `report -f
json` emitted `"amount": "1,234,567.89"` — a separator inside a JSON numeric
string.

## The cause: the rule was re-derived per writer

Five places independently decided whether separators apply — the core
formatter, and each of the four query writers — with nothing asserting
agreement, so they had drifted apart. That is the anti-pattern CLAUDE.md's
Canonical-Function Discipline describes.

`OutputSurface` (Human / Machine / LedgerText) now states the rule once, and
`DisplayContext::for_surface` applies it. Both commands resolve the context
ONCE at their dispatch point, so every writer takes a context it can use
verbatim. Each command's `From<OutputFormat>` is an exhaustive match, so a new
output format must declare which kind of consumer it serves rather than
inheriting whatever the previous arm did.

`for_surface` narrows ONLY the separator flag — precision is a property of the
data and is identical on every surface, asserted by a test.

## A superseded test, not a deleted one

`csv_amounts_with_render_commas_are_quoted` (#1750) failed, and it encoded a
genuine earlier review catch: separator-bearing CSV fields must be quoted per
RFC-4180 or rows grow extra columns. The quoting was correct; #1892 showed
that correctly-quoted `"2,357.65"` is still rejected by ordinary decimal
parsers.

Omitting separators subsumes that concern — no comma in the field means no
quoting, so no column can split — so the test is rewritten rather than
removed, keeping its column-count assertion and citing both issues.

## Verification

Sabotage-verified: mapping `Beancount` to `Human` fails the new test.

With `render_commas` unset — every existing ledger — output is byte-identical
to main across 20 command/format combinations. With it set, only the intended
surfaces change:

    query text      1,234,567.89     report -f text   1,234,567.89
    query csv       1234567.89       report -f csv    1234567.89
    query json      1234567.89       report -f json   1234567.89
    query beancount 1234567.89       format           1234567.89

4290 tests pass; clippy clean at 1.97.0; `cargo doc -D warnings` clean.

Refs #1892
robcohen added a commit that referenced this pull request Jul 29, 2026
…faces (#1893)

Answers #1892 and fixes the inconsistencies investigating it exposed.

`format` stripping thousands separators is DELIBERATE — the formatter's job is
one canonical on-disk representation and `,` is locale-ambiguous — and it was
already pinned by tests. But `render_commas` was applied ad hoc per writer, and
the surfaces had drifted apart:

- `query` text: `SUM(number)` rendered separators while `SUM(position)` did
  not, in the same query. The flag only arrived as a side effect of the
  Number-column precision inheritance (#954), so Position/Inventory columns
  silently missed it.
- `query --format csv` emitted `"1,234,567.89"` while JSON emitted
  `1234567.89`. Both are machine interchange; the separator forces quoting and
  is then rejected by ordinary decimal parsers.
- `query --format beancount` put separators in LEDGER TEXT, contradicting
  `format`.
- `report --format csv`/`json` did the same, including a separator inside a
  JSON numeric string.

`OutputSurface` (Human / Machine / LedgerText) now states the rule once and
`DisplayContext::for_surface` applies it; both commands resolve the context at
their single dispatch point. Each `From<OutputFormat>` is exhaustive, so a new
output format must declare which consumer it serves. `for_surface` returns
`Cow` and borrows unless the flag must change, so the common paths — a ledger
without `render_commas`, and any human-facing surface — cost nothing.

`csv_amounts_with_render_commas_are_quoted` (#1750) is superseded rather than
deleted: it encoded a real review catch (separator-bearing CSV fields must be
quoted or rows grow columns). Omitting separators subsumes that concern, and
its column-count assertion is retained.

docs/reference/options.md now documents which surfaces render separators and
why `format` does not, including that a separator-bearing file is permanently
"unformatted" to `format --check` and needs one `rledger format` run.

With `render_commas` unset — every existing ledger — output is byte-identical
to main across 20 command/format combinations.

Refs #1892
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