Repository navigation
fix(query,docs): apply render_commas consistently across output surfaces - #1893
Conversation
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 Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
📊 Benchmark Results
vs main branch (2026-07-29)
What do these numbers mean?
|
There was a problem hiding this comment.
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:
querytext: propagaterender_commasas table-level presentation policy so columns containingPosition/Inventoryhonor it the same wayNumbercolumns do.query --format csv: explicitly suppressrender_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, andquery --format beancount), which makes the summary misleading. Expanding the table to cover allreport/queryformats 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.
✅ Compatibility Test Results
What's tested
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
Deep review — found a third affected surface and a design flawPushed as
|
| 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.
There was a problem hiding this comment.
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). Inexecute_query, this clone happens even when the output format is JSON, but the JSON writer ignoresctxentirely, 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
|
Both review points addressed. The So the docs sentence now holds for every machine-readable surface rather than needing to be narrowed. The suppressed low-confidence note about Behaviour is unchanged across all seven command/format combinations. 4291 tests, clippy clean at 1.97.0, docs clean. |
There was a problem hiding this comment.
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_separatorstest loops over CSV/JSON/Beancount formats but always callswrite_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_queryalways builds a surface-adjustedDisplayContextviafor_surface(...)even for JSON output, butwrite_jsondoes not use a display context. Whenrender_commasis set and--format jsonis selected, this can trigger an unnecessaryDisplayContextclone (and relies on borrowing a temporaryCow). Consider resolving the context only for the formats that actually consume it and passingctx.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 {
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.
Answers #1892 and fixes the two inconsistencies that investigating it turned up.
The question: is
formatstripping separators deliberate?Yes, and it is pinned by tests — not an oversight.
rustledger-ffi-component/src/convert.rsstates the policy outright, and two tests inrustledger-core/src/format/mod.rssetrender_commas(true)and assert the formatter emits none (number_display_context_pads_without_separators,number_display_context_threads_through_directives). The loader only callsset_render_commason the display path, never the format path.The reporter's inference from #1807/#1750 was reasonable — display options do reach the formatter — but
render_commasis excluded on purpose while precision is not.Two things that were genuinely wrong
SUM(position)ignored the flag whileSUM(number)honored it, in the same query and the same output format:Per-column
DisplayContexts start empty, and the ledger context was merged in only on the firstValue::Numbercell — that inheritance exists to give naked decimal columns a precision fallback (#954).render_commaswas 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.
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.mddescribedrender_commaswith no scope at all, which is why expectingformatto 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" toformat --check(exit 1), so a CI gate needsrledger formatrun once to canonicalize. The parser accepts separators on input either way, so existing files keep loading.Verification
report1,234,567.89 USDquerytextsum(number)1,234,567.89querytextsum(position)1234567.89 USD1,234,567.89 USDquery -f csv"1,234,567.89"1234567.89query -f json1234567.89format1234567.89Both tests sabotage-verified — each fails with its fix removed.
With
render_commasunset (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 warningsclean.