Skip to content

fix(query,docs): apply render_commas consistently across output surfaces - #1893

Merged
robcohen merged 3 commits into
mainfrom
fix/render-commas-coverage
Jul 29, 2026
Merged

robcohen merged 3 commits into
mainfrom
fix/render-commas-coverage

Conversation

@robcohen

Copy link
Copy Markdown
Member

Answers #1892 and fixes the two inconsistencies that investigating it turned up.

The question: is format stripping separators deliberate?

Yes, and it is pinned by tests — not an oversight. rustledger-ffi-component/src/convert.rs states the policy outright, and two tests in rustledger-core/src/format/mod.rs set render_commas(true) and assert the formatter emits none (number_display_context_pads_without_separators, number_display_context_threads_through_directives). The loader only calls set_render_commas on the display path, never the format path.

The reporter's inference from #1807/#1750 was reasonable — display options do reach the formatter — but render_commas is excluded on purpose while precision is not.

Two things that were genuinely wrong

SUM(position) ignored the flag while SUM(number) honored it, in the same query and the same output format:

SELECT account, sum(number)    ->  Assets:Bank    1,234,567.89
SELECT account, sum(position)  ->  Assets:Bank   1234567.89 USD

Per-column DisplayContexts start empty, and the ledger context was merged in only on the first Value::Number cell — that inheritance exists to give naked decimal columns a precision fallback (#954). render_commas was riding along as a side effect, so any column holding a Position or Inventory never received it. It is presentation policy for the whole table, so it is now set on every column context directly; the Number-only precision inheritance is untouched.

CSV emitted separators; JSON did not.

csv  -> Assets:Bank,"1,234,567.89"
json -> "1234567.89"

Both are machine interchange. The separator forces the field to be quoted and is then rejected by ordinary decimal parsers — it broke the reporter's reconciliation script. CSV now matches JSON. Precision is untouched; only the separator is suppressed.

Documentation

docs/reference/options.md described render_commas with no scope at all, which is why expecting format to honor it was reasonable. It now carries a per-surface table and the rationale, including the consequence the reporter identified: a separator-bearing file is permanently "unformatted" to format --check (exit 1), so a CI gate needs rledger format run once to canonicalize. The parser accepts separators on input either way, so existing files keep loading.

Verification

surface before after
report 1,234,567.89 USD unchanged
query text sum(number) 1,234,567.89 unchanged
query text sum(position) 1234567.89 USD 1,234,567.89 USD
query -f csv "1,234,567.89" 1234567.89
query -f json 1234567.89 unchanged
format 1234567.89 unchanged (by design)

Both tests sabotage-verified — each fails with its fix removed.

With render_commas unset (every existing ledger), output is byte-identical to main across text/csv/json for both query shapes; with it set, only the two intended surfaces change. The BQL compat harness does not set the option, so it is unaffected.

4288 tests · clippy clean at the CI-pinned 1.97.0 · cargo doc -D warnings clean.

From #1892, which asked whether `format` stripping thousands separators is
deliberate. It is — `format_plain` ignores the flag by design and two tests
pin it — but investigating turned up two genuine inconsistencies and a
documentation gap.

## `SUM(position)` ignored the flag while `SUM(number)` honored it

One query, one output format, two different renderings:

    SELECT account, sum(number)    ->  Assets:Bank    1,234,567.89
    SELECT account, sum(position)  ->  Assets:Bank   1234567.89 USD

Per-column `DisplayContext`s start empty, and the ledger context was merged in
ONLY on the first `Value::Number` cell (that inheritance exists to give naked
decimal columns a precision fallback, #954). `render_commas` rode along as a
side effect, so columns holding a Position or Inventory never received it.

It is presentation policy for the whole table, not a per-column precision
fact, so it is now set on every column context directly. The Number-only
precision inheritance is untouched.

## CSV emitted separators; JSON did not

    csv  -> Assets:Bank,"1,234,567.89"
    json -> "1234567.89"

Both are machine interchange. The separator forces the field to be quoted and
is then rejected by ordinary decimal parsers — it broke the reporter's
reconciliation script. CSV now matches JSON. Precision is untouched; only the
separator is suppressed.

## Documentation

`docs/reference/options.md` described the option with no scope, so expecting
`format` to honor it was entirely reasonable. It now states which surfaces
render separators and why `format` does not, including the consequence the
reporter identified: a separator-bearing file is permanently "unformatted" to
`format --check`, so a CI gate needs `rledger format` run once to canonicalize.

## Verification

Both tests sabotage-verified. With `render_commas` unset — every existing
ledger — output is byte-identical to main across text/csv/json for both query
shapes; with it set, only the two intended surfaces change.

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

Refs #1892
@codecov

codecov Bot commented Jul 29, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 41.5ms ± 3.1ms 24 MB
beancount 753.7ms ± 7.7ms 50.6 MB
Comparison 18.2x faster 2.1x less

vs main branch (2026-07-29)

Metric main this PR Change
Time 37.3ms 41.5ms +11.3% 🔴
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 addresses render_commas inconsistencies across rledger query output surfaces and clarifies the intended policy in the user-facing options reference. It makes query text output apply separators consistently across value kinds, and ensures query CSV output never emits thousands separators (to remain parse-friendly and consistent with JSON).

Changes:

  • query text: propagate render_commas as table-level presentation policy so columns containing Position/Inventory honor it the same way Number columns do.
  • query --format csv: explicitly suppress render_commas (while keeping display precision behavior) to avoid producing separator-bearing numeric fields.
  • Documentation: expand and clarify the per-surface behavior of render_commas.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
docs/reference/options.md Documents per-surface render_commas behavior and rationale.
crates/rustledger/src/cmd/query/output.rs Applies render_commas consistently in query text across column kinds; suppresses separators in query CSV; adds regression tests.
Comments suppressed due to low confidence (1)

docs/reference/options.md:122

  • The per-surface table omits some output formats that do emit separators today (e.g. report --format csv/json, and query --format beancount), which makes the summary misleading. Expanding the table to cover all report/query formats would align the docs with actual behavior.
| Surface | Separators? |
|---------|-------------|
| `report`, `query` (text) | yes, when the option is set |
| `query --format csv` / `json` | **no** — these are machine interchange, and a separator breaks ordinary decimal parsers |
| `format` (the file on disk) | **no** — see below |

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

Comment thread docs/reference/options.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

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
Copilot AI review requested due to automatic review settings July 29, 2026 15:34
@robcohen

Copy link
Copy Markdown
Member Author

Deep review — found a third affected surface and a design flaw

Pushed as c978a3b7.

query --format beancount was putting separators in ledger text

1,234,567.89 USD — emitted as beancount source, by the same binary whose format command strips separators precisely because ledger text has one canonical form. Pre-existing on main, but the first commit's own documentation turned it into a contradiction.

report -f csv / -f json had the identical defect

I fixed query's CSV and stopped there. report has its own format enum and 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, which is the worse of the two.

The cause was structural

Five places independently decided whether separators apply — the core formatter plus each of the four query writers — with nothing asserting agreement. They had already drifted. Fixing CSV in isolation was treating a symptom.

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 an exhaustive match, so a new output format has to declare which kind of consumer it serves instead of inheriting whatever the previous arm did. for_surface narrows only the separator flag — precision is a property of the data and is identical everywhere, which a test asserts.

One test superseded rather than deleted

csv_amounts_with_render_commas_are_quoted (#1750) failed under the change, and it encoded a real earlier review catch: separator-bearing CSV fields must be quoted per RFC-4180 or rows grow extra columns. That quoting was correct — #1892 just showed that a correctly-quoted "2,357.65" is still rejected by ordinary decimal parsers. Omitting separators subsumes the concern (no comma, no quoting, no split column), so the test is rewritten with its column-count assertion retained and both issues cited. Deleting it would have been how the original bug comes back.

Final matrix

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

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.

4290 tests · clippy clean at 1.97.0 · cargo doc -D warnings clean.

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.

Comments suppressed due to low confidence (2)

crates/rustledger/src/cmd/query/output.rs:44

  • DisplayContext::for_surface() clones the full context (histograms + fixed precisions). In execute_query, this clone happens even when the output format is JSON, but the JSON writer ignores ctx entirely, so this is unnecessary work on the JSON path (and can be noticeable in a query REPL).
    // Output results using display context for consistent number formatting.
    // `render_commas` is resolved ONCE here, against the surface being written,
    // so each writer receives a context it can use verbatim (#1892).
    let ctx = &settings.display_context.for_surface(settings.format.into());
    match settings.format {

crates/rustledger/src/cmd/query/output.rs:1932

  • This test claims to cover CSV/JSON/Beancount “surface resolution”, but it always calls write_csv, so it never actually exercises the JSON or beancount writers. That means regressions (e.g., JSON starting to format via a context that renders commas) would slip through despite the test name and docstring.
        for format in [
            super::super::OutputFormat::Csv,
            super::super::OutputFormat::Json,
            super::super::OutputFormat::Beancount,
        ] {

…hing

From Copilot's low-confidence note on #1893, which was right.

`DisplayContext::for_surface` cloned the whole context — including the
per-currency histograms — on every query and every report, even when the flag
did not change. The JSON writer ignores the context entirely, so that path paid
for a clone it never read.

It now returns `Cow` and borrows unless separators actually have to be
suppressed. The two common cases are the free ones: a ledger that never set
`render_commas` (almost all of them) and any human-facing surface. Only a
machine or ledger-text surface on a comma-rendering ledger clones.

Behavior is unchanged on all seven command/format combinations; a test pins
which cases borrow so the property cannot silently regress.

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

Refs #1892
Copilot AI review requested due to automatic review settings July 29, 2026 15:46
@robcohen

Copy link
Copy Markdown
Member Author

Both review points addressed.

The docs/reference/options.md comment is already fixed. It landed at 14:38Z against ce540774 (14:32Z); c978a3b7 an hour later fixed exactly that — report's CSV/JSON were using the raw ledger context via eight call sites and did emit separators. Worth saying that Copilot found that gap independently, at the same time my own deep review did, which is decent corroboration that it was the real problem rather than a stylistic quibble. Verified on the current head:

report -f csv   ->  1234567.89
report -f json  ->  1234567.89

So the docs sentence now holds for every machine-readable surface rather than needing to be narrowed.

The suppressed low-confidence note about for_surface cloning was correct, and is fixed in 567616a3. It cloned the whole context — per-currency histograms included — on every query and report, even when the flag didn't change, and the JSON writer never reads the context at all. It now returns Cow and borrows unless separators actually have to be suppressed, so the two common cases are free: a ledger that never set render_commas (almost all of them) and any human-facing surface. A test pins which cases borrow so it can't silently regress.

Behaviour is unchanged across all seven command/format combinations. 4291 tests, clippy clean at 1.97.0, docs clean.

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.

Comments suppressed due to low confidence (2)

crates/rustledger/src/cmd/query/output.rs:1923

  • The machine_surfaces_never_emit_thousands_separators test loops over CSV/JSON/Beancount formats but always calls write_csv, so it doesn't actually exercise the JSON and beancount writers. This can pass even if those formats regress. Consider dispatching to the correct writer per format and tailoring assertions (e.g. only require "no quotes" for CSV).
            let mut out = Vec::new();
            write_csv(&result, &mut out, false, &ctx).expect("write");
            let csv = String::from_utf8(out).expect("utf8");

crates/rustledger/src/cmd/query/output.rs:44

  • execute_query always builds a surface-adjusted DisplayContext via for_surface(...) even for JSON output, but write_json does not use a display context. When render_commas is set and --format json is selected, this can trigger an unnecessary DisplayContext clone (and relies on borrowing a temporary Cow). Consider resolving the context only for the formats that actually consume it and passing ctx.as_ref() explicitly.

This issue also appears on line 1921 of the same file.

    // Output results using display context for consistent number formatting.
    // `render_commas` is resolved ONCE here, against the surface being written,
    // so each writer receives a context it can use verbatim (#1892).
    let ctx = &settings.display_context.for_surface(settings.format.into());
    match settings.format {

@robcohen
robcohen merged commit e0b8d48 into main Jul 29, 2026
53 checks passed
@robcohen
robcohen deleted the fix/render-commas-coverage branch July 29, 2026 16:11
robcohen added a commit that referenced this pull request Jul 30, 2026
Closes the two gaps this PR had been recording as known instead of
fixing.

**`query --format beancount` now honors `render_commas`.** The rule
lives in one place — `OutputSurface::renders_thousands_separators` —
and `LedgerText => false` was right when #1893 wrote it, because
`format` stripped separators unconditionally and pinning ledger text to
"never groups" is what stopped the two producers of ledger text from
disagreeing. This PR then taught `format --ledger` to group, which put
them back in disagreement, the other way round. The premise #1893 was
defending — ledger text has one canonical form — is the premise this PR
deliberately abandoned: grouped numerals are Beancount syntax, so the
parser and not the file is the machine boundary. Only `Machine` refuses
now, and that refusal still outranks any ledger or per-commodity
declaration. Beancount agrees: `grammar.py` calls
`dcontext.set_commas(options["render_commas"])` during the parse and
`printer.py` renders through that same context.

**Editor formatting groups too.** Format-on-save, range formatting and
the Align Amounts command all resolve a `GroupingStyle` from the loaded
ledger, so the reporter — who edits in VS Code — is actually reached;
`--ledger` alone only fixed their CLI. Options come from the journal
ROOT, which is what makes it work on an `include`d buffer with no
options of its own. `LedgerState::grouping_style_for` is the single
gate, and it falls back to ungrouped for a file no journal includes and
for a ledger that has not loaded yet. The four entry points share
`with_grouping_style` rather than each re-deriving the lock-and-gate
dance.

Grouping cannot reuse the alignment cached on `ParseResult`: it was
measured ungrouped and a separator is wider, so the currency column
would sit three characters off per separator. Both formatting paths
re-measure when grouping is on and keep the cached fast path otherwise —
grouping is opt-in, so the per-keystroke path is unaffected. Added
`format_node_range_grouped`, which measures and emits together so a
caller cannot pair a style with the wrong alignment.

Tests: the included-buffer inheritance and both fallbacks; format-on-
save groups and is idempotent; the default style still strips; grouped
output stays aligned; `query --format beancount` groups and honors a
per-commodity opt-out. Each was checked against a sabotaged
implementation to confirm it can fail — the alignment one catches
exactly the cached-alignment reuse described above.
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