Skip to content

fix(query): quantize SUM-aggregate text output via GROUP BY currency - #1022

Merged
robcohen merged 5 commits into
mainfrom
fix/issue-988-sum-aggregate-precision
May 7, 2026
Merged

robcohen merged 5 commits into
mainfrom
fix/issue-988-sum-aggregate-precision

Conversation

@robcohen

@robcohen robcohen commented May 7, 2026

Copy link
Copy Markdown
Member

Summary

SUM(number) GROUP BY currency (and equivalent implicit-grouping patterns) emit a Value::Number that carries no currency context, so text rendering went through the fallback format_default path that preserves rust_decimal's natural scale. When inputs had varying scales (e.g. one 0.00 + one 5.213), the sum kept the wider scale and rendered 0.000 / 5.213 instead of bean-query's 0.00 / 5.21. Of the ~99 post-#986 BQL compat mismatches, ~15 fell into this bucket.

Why Option B, not Option A

Issue #988 recommended Option A (quantize at aggregation time). But that conflicts with its own AC #4: "CSV/JSON output of aggregates remains lossless" — quantizing in the aggregator mutates inputs for all output paths, not just text. JSON consumers parsing exact decimal scales would see truncated values.

This PR implements Option B as described in the issue body: plumb GROUP BY currency through to the renderer, quantize at text-render time only.

Implementation

  • QueryResult gains row_group_keys: Vec<Option<Vec<Value>>> — a parallel sidecar to rows. Aggregate path populates it via the new add_aggregate_row(row, group_key); non-aggregate path still calls add_row(row) and gets None slots.
  • cmd/query/output.rs::write_text looks up the row's sidecar, finds the first currency-shaped string in the GROUP BY key (heuristic: uppercase initial, [A-Z0-9'._-], ≤24 chars), and passes it as a hint to a new format_value_with_hint.
  • format_value_with_hint routes Value::Number cells through DisplayContext::format(n, currency) when a hint is present — per-currency precision via the same path used for Value::Amount.
  • CSV / JSON / beancount renderers still call format_value unchanged → lossless preserved → AC refactor: extract validate_transaction into focused helper functions #4 satisfied.

Test plan

  • 4 new unit tests in cmd::query::output::tests:
    • test_looks_like_currency_accepts_typical_currencies / ..._rejects_non_currencies — pin the heuristic
    • test_format_value_with_hint_routes_number_through_per_currency_ctx — pins the central dispatch: Value::Number(0.000) renders as \"0.00\" with USD hint vs \"0.000\" without
    • test_format_value_with_hint_unknown_currency_falls_back_safely — defense-in-depth for false-positive currency detection
  • All 131 rustledger-query lib tests still pass.
  • All existing rustledger --lib cmd::query tests still pass.
  • cargo clippy --all-features --all-targets -- -D warnings clean.
  • cargo fmt --all -- --check clean.
  • Pre-push hooks all green.
  • Maintainer: run the BQL compat harness from the issue's reproduction steps to confirm the ~15 precision-only mismatches resolve.

What's NOT changed

Closes #988.

🤖 Generated with Claude Code

`SUM(number) GROUP BY currency` (and equivalent implicit-grouping
patterns) emit a `Value::Number` that carries no currency context, so
text rendering went through the fallback `format_default` path that
preserves rust_decimal's natural scale. When inputs had varying scales
(e.g. one 0.00 + one 5.213), the sum kept the wider scale and rendered
`0.000` / `5.213` instead of bean-query's `0.00` / `5.21`. Of the ~99
post-#986 BQL compat mismatches, ~15 fell into this bucket.

Issue #988 recommended Option A (quantize at aggregation time), but
that conflicts with its own AC #4 ("CSV/JSON output of aggregates
remains lossless") — quantizing in the aggregator mutates inputs for
ALL output paths, not just text. This PR implements Option B as
described in the issue body: plumb GROUP BY currency through to the
renderer, quantize at text-render time only.

Implementation:
- `QueryResult` gains `row_group_keys: Vec<Option<Vec<Value>>>` — a
  parallel sidecar to `rows`. Aggregate path populates it via the new
  `add_aggregate_row(row, group_key)`; non-aggregate path still calls
  `add_row(row)` and gets `None` slots.
- `cmd/query/output.rs::write_text` looks up the row's sidecar, finds
  the first currency-shaped string in the GROUP BY key (heuristic:
  uppercase initial, `[A-Z0-9'._-]`, ≤24 chars), and passes it as a
  hint to a new `format_value_with_hint`.
- `format_value_with_hint` routes `Value::Number` cells through
  `DisplayContext::format(n, currency)` when a hint is present —
  per-currency precision via the same path used for `Value::Amount`.
- CSV / JSON / beancount renderers still call `format_value`
  unchanged: lossless preserved, satisfying AC #4.

Tests added in cmd::query::output:
- `test_looks_like_currency_accepts_typical_currencies`
- `test_looks_like_currency_rejects_non_currencies`
- `test_format_value_with_hint_routes_number_through_per_currency_ctx`
  — pins the central dispatch: same Value::Number(0.000) renders as
  "0.00" with USD hint vs "0.000" without.
- `test_format_value_with_hint_unknown_currency_falls_back_safely` —
  defense-in-depth for false-positive currency detection.

All 131 rustledger-query tests still pass; existing rustledger CLI
query snapshots unchanged.

Closes #988.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings May 7, 2026 19:01
@robcohen
robcohen requested a review from a team as a code owner May 7, 2026 19:01

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 BQL text-output precision mismatches for queries like SUM(number) GROUP BY currency by preserving GROUP BY key context through execution and using it at render time to quantize Value::Number via per-currency DisplayContext (while keeping CSV/JSON lossless).

Changes:

  • Added QueryResult.row_group_keys (sidecar parallel to rows) and an add_aggregate_row API to carry GROUP BY keys through aggregation.
  • Updated aggregate execution to populate the sidecar with each aggregated row’s GROUP BY key.
  • Updated text rendering to detect a currency-like string in the GROUP BY key and route Value::Number formatting through a new format_value_with_hint path; added unit tests for the heuristic/dispatch.

Reviewed changes

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

File Description
crates/rustledger/src/cmd/query/output.rs Text renderer now recovers a per-row currency hint from GROUP BY keys and formats Value::Number with per-currency precision via format_value_with_hint + adds tests.
crates/rustledger-query/src/executor/types.rs QueryResult gains a row_group_keys sidecar and an add_aggregate_row method to record GROUP BY keys alongside rows.
crates/rustledger-query/src/executor/execution.rs Aggregation loop now passes GROUP BY keys into QueryResult via add_aggregate_row.

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

@github-actions

github-actions Bot commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 29.8ms ± 0.3ms 21.6 MB
beancount 871ms ± 8.6ms 50.2 MB
Comparison 29.2x faster 2.3x less

vs main branch (2026-05-07)

Metric main this PR Change
Time 34.2ms 29.8ms -12.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

@codecov

codecov Bot commented May 7, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.22280% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-query/src/executor/execution.rs 66.66% 2 Missing ⚠️
crates/rustledger-query/src/executor/types.rs 98.96% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

Metric Result
Check Compatibility 99%
BQL Compatibility 74%
Full AST Match 99%
Total Files 786
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

robcohen and others added 2 commits May 7, 2026 14:22
…int gate

Copilot flagged four issues on the original commit. All real:

1. **`row_group_keys` desynchronizes after ORDER BY / LIMIT.** The
   sidecar is parallel to `rows`, but `sort_results` and the four
   `result.rows.truncate(limit)` sites mutated only `rows` — after
   sort or pagination, `row_group_keys[i]` no longer corresponded
   to row `i`, so currency hints would be applied to the wrong rows.
   Fixed by encapsulating the invariant inside `QueryResult`:
   - New `QueryResult::truncate(len)` truncates both vectors.
   - New `QueryResult::sort_by(F)` pair-sorts both vectors via a
     single `mem::take` + `zip` + `sort_by` + push-back, with
     `debug_assert_eq!` guarding the lengths.
   - `sort.rs` and all four LIMIT sites now go through these helpers.

2. **False-positive currency hint silently STRIPS trailing zeros.**
   `DisplayContext::format(n, currency)` falls back to
   `n.normalize().to_string()` when the currency has no tracked
   precision — `normalize()` strips trailing zeros, turning `0.000`
   into `0`. So a heuristic-only currency check ("uppercase, looks
   right") would render output WORSE than the pre-fix state for
   any unrecognized currency-shaped string in a GROUP BY key.
   Fixed by gating on `ctx.get_precision(s).is_some()` in the new
   `currency_hint_for_row` helper — only currencies with tracked
   precision become hints. Test
   `test_currency_hint_for_row_filters_untracked_currencies` pins
   the contract end-to-end (USD with samples → hint; MADEUP without
   samples → no hint, even though it passes the shape check).

3. **Hint-extraction logic was duplicated** between the width-pass
   and the row-print pass in `write_text`. Factored out into the
   new `currency_hint_for_row(result, row_idx, ctx)` helper.

4. **(Implicit) `looks_like_currency` docstring overstated safety.**
   The original comment claimed false positives were "no-op";
   they're not, per #2 above. Rewrote the docstring to call out
   the two-step gate (shape check + precision check) and pointer
   to the `currency_hint_for_row` site that enforces it.

Net change: +119 / -55 across 4 files. All 131 query tests still
pass; new test pins the precision-gate contract.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Self-review of #1022 surfaced real gaps that Copilot's first pass
missed. All addressed in this commit; no production-code behavior
change beyond visibility tightening and the `debug_assert!` →
`assert!` upgrade in `QueryResult::sort_by`.

API hardening:
- `QueryResult::row_group_keys` marked `#[doc(hidden)]` and the
  invariant (parallel to `rows`, never reach in directly) is now in
  the struct's docstring. New public accessor `group_key(row_idx)`
  is the canonical read path; the renderer goes through it instead
  of touching the field.
- `sort_by`'s `debug_assert_eq!` is now an unconditional `assert!`
  with a descriptive message — the lockstep invariant is load-bearing
  for correctness, not a debug-only sanity check.

Test coverage:
- `test_sort_by_keeps_row_group_keys_in_lockstep` — pins ORDER BY
  preserves row↔key alignment.
- `test_truncate_keeps_row_group_keys_in_lockstep` — pins LIMIT.
- `test_add_row_and_add_aggregate_row_mixed` — pins the invariant
  across interleaved aggregate/non-aggregate inserts.
- `test_add_aggregate_row_empty_key_records_none` — pins the
  empty-key-becomes-None contract.
- `test_csv_aggregate_output_preserves_unquantized_decimal` — pins
  AC #4 lossless contract for CSV.
- `test_json_aggregate_output_preserves_unquantized_decimal` — same
  for JSON.
- `test_beancount_aggregate_output_preserves_unquantized_decimal` —
  same for beancount output.
- `test_text_aggregate_output_quantizes_via_currency_hint` — pins
  the divergence: text quantizes, the others don't.
- `test_e2e_sum_group_by_currency_text_output_matches_per_currency_precision`
  — full pipeline: real BQL through Executor + write_text. The
  canary that fires if anyone reverts `add_aggregate_row` to
  `add_row` in the executor (helper-level tests stay green in that
  scenario; this one wouldn't).

Docs:
- Multi-currency-column GROUP BY rare-case behavior now documented
  on `add_aggregate_row` and the renderer's `currency_hint_for_row`.
- Misleading "two `0.00 USD` values sum to `0.000`" example replaced
  with the real cause (mixed-scale inputs like `0.000` + several
  `0.00`s).
- "Caught by Copilot review on PR #1022" self-references dropped —
  they would read awkwardly post-merge.

135 query tests + 11 renderer tests pass. Clippy + fmt clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen and others added 2 commits May 7, 2026 14:56
Closes the 13 items from the second deep review of #1022. No
production-behavior change beyond the visibility tightening, the
heuristic narrowing, and the debug-only tripwire — all defensive.

Encapsulation:
- A: `row_group_keys` demoted from `pub` (with `#[doc(hidden)]`) to
  `pub(crate)`. External crates now MUST go through `group_key()`,
  closing the loophole where the renderer (or a future contributor)
  could violate the parallel-vector invariant by direct field access.

Heuristic & perf:
- B: `looks_like_currency` lower bound bumped from 1 to 2. Single
  uppercase letters aren't real currencies; the precision gate would
  filter them anyway, but tightening the heuristic makes the intent
  clearer and shrinks the false-positive surface.
- C: per-row currency hints now resolved ONCE into a `Vec<Option<&str>>`
  before the width-calc and print passes, instead of recomputed per
  pass. Eliminates duplicate work + duplicated extraction code.

Safety net:
- L: `format_value_with_hint` gains a `debug_assert!` inside the
  `Value::Number + hint` branch that fires if a caller forgets the
  precision-gate filter. Discovered (and fixed) a false-fire when
  width-calc passes the hint to non-Number cells — the assert now
  scopes correctly to the dispatch branch where the hint is consumed.

Test cleanups:
- D: vacuous JSON assertion (`A || A`) replaced with a single clean
  check using raw strings + clearer reasoning comment.
- E: dead `let _ = ctx;` in JSON test removed (write_json doesn't
  take a DisplayContext, so building one is dead code).
- F: CSV assertion no longer relies on `\n` substring matching —
  parses by lines + commas, robust to CRLF on any platform.
- G: e2e test asserts on the SUM cell anchored by row position +
  whitespace tokenization, instead of a global negative substring
  scan that could false-fire on unrelated `0.0001`-shaped output.
- H: dropped the last "Copilot review on PR #1022" self-reference
  from a test docstring.

New coverage:
- I: `test_e2e_implicit_group_by_currency_text_output_quantized` —
  pins the implicit-GROUP-BY path (`SELECT currency, SUM(number)`
  without `GROUP BY`) also populates `row_group_keys`. Different
  executor code path (`extract_implicit_group_by_exprs`) that the
  explicit-GROUP-BY e2e test wouldn't catch.
- J: `test_sort_by_panics_on_lockstep_violation` — `#[should_panic]`
  test that deliberately corrupts the parallel-vector invariant and
  verifies `sort_by`'s `assert_eq!` actually fires.
- K: `test_currency_hint_for_row_finds_currency_in_multi_column_group_by_key`
  — pins the documented contract that `find_map` over the GROUP BY
  key correctly skips non-currency-shaped strings (account names) to
  reach the currency.

Docs:
- M: `add_row` docstring expanded to explain the sidecar consequence.

136 query tests + 13 renderer tests pass. Clippy + fmt clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Items from the third deep review of #1022. All polish; no production
behavior change.

1. Multi-currency-key first-wins test
   The previous test only verified "currency is found in multi-column
   key" — it would pass under "first match", "last match", or any
   matching strategy. New test
   `test_currency_hint_for_row_first_currency_wins_when_multiple` uses
   a key with TWO currency-shaped + tracked-precision strings (`[EUR,
   USD]` and reversed `[USD, EUR]`) so the assertion discriminates
   iteration order. Pins the contract documented on `add_aggregate_row`.

2. `sort_by` pre-allocation
   `Vec::reserve_exact(n)` on the now-empty `rows` and `row_group_keys`
   before the push-back loop. Skips incremental-grow allocations.
   Sub-millisecond at typical N; trivial cleanup.

3. `currency_hints` cache short-circuit
   Skip the per-row hint Vec allocation entirely when the result has
   no aggregate rows (the common case for non-aggregate queries).
   New `QueryResult::has_aggregate_rows()` accessor encapsulates the
   check (rather than reaching into `pub(crate)` field). Access pattern
   in the renderer changes to `currency_hints.get(i).copied().flatten()`
   so the empty-Vec case returns `None` cleanly.

4. Cache-lifetime documentation
   One-paragraph comment on the `currency_hints` declaration explaining
   the borrow constraint (`&str` entries borrow from `result`; safe
   while `result` is `&`-borrowed). Future refactors that mutate
   `result` mid-stream would break this; the comment makes the
   constraint visible without reading the borrow checker's mind.

5. Direct `add_row` test
   `test_add_row_records_none_in_sidecar` standalone (was covered
   indirectly by the mixed-row test). Pins the contract isolated from
   other helpers' behavior.

6. `group_key` returns `&[Value]` not `&Vec<Value>`
   Callers no longer tied to the specific container type. Test
   assertions updated to use `Some(&[...][..])` for the slice
   coercion. Also tightens `pub(crate) row_group_keys` access:
   external consumers MUST go through `group_key()` /
   `has_aggregate_rows()` accessors.

137 query tests + 14 renderer tests pass. Clippy + fmt clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen enabled auto-merge (squash) May 7, 2026 20:23
@robcohen
robcohen merged commit ecfb949 into main May 7, 2026
35 checks passed
@robcohen
robcohen deleted the fix/issue-988-sum-aggregate-precision branch May 7, 2026 20:26
robcohen added a commit that referenced this pull request May 8, 2026
…back (#1033)

* fix(query): per-currency precision through PIVOT via column-name fallback

Closes #1023.

PR #1022 fixed #988 (SUM-aggregate text output matching bean-query's
per-currency precision) by carrying the GROUP BY currency in a per-row
sidecar. PIVOT regressed it: `apply_pivot` builds new rows via
`add_row` (not `add_aggregate_row`), so the sidecar drops to `None`
and the renderer can't recover the precision context.

After PIVOT, the GROUP BY currency moves into column position — each
pivoted column's name IS the currency code. The renderer can read it
from there.

Implementation:
- New `column_currency_hints` precomputed once per write_text invocation,
  symmetrical to the existing `currency_hints` row sidecar lookup. Uses
  the same `looks_like_currency` + `ctx.get_precision().is_some()`
  guard, so an untracked column-named "USD" still falls back safely
  (without the guard, `DisplayContext::format` strips trailing zeros
  via `normalize()`, making output WORSE than the unfixed state).
- Per-cell hint resolution: row sidecar wins over column-name fallback
  (the sidecar came from the actual GROUP BY key; the column name is a
  heuristic). Width-calc and print passes use the same precedence so
  rendered widths match rendered values.

Bonus: pre-existing column/row length mismatch in `apply_pivot`. The
column header included the value column ("SUM") but the row builder
explicitly excluded it from `group_cols`, leaving rows one cell short.
JSON output silently dropped the SUM cell. Fixed by also excluding
`value_col_idx` from `new_columns` so columns and rows agree on shape.
This blocked the e2e PIVOT test for #1023, so it had to be fixed here
rather than as a separate issue.

Tests:
- 3 new unit tests in `cmd::query::output::tests`:
  - `test_text_pivoted_column_uses_column_name_as_currency_hint`
  - `test_text_pivoted_column_with_untracked_currency_falls_back_safely`
    — pins the false-positive guard
  - `test_row_sidecar_wins_over_column_name_fallback`
- 1 new e2e test through Executor + write_text.
- New BQL compat fixture `sum-by-account-pivot-by-currency` in
  bql-queries.toml so #1000's harness catches future regressions.

511 query tests + 18 renderer tests pass. Clippy + fmt clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(query): address self-review on #1033

Five real concerns from the deep review, plus the pre-existing items
filed as #1034 follow-up.

- `resolve_cell_hint` helper: width-calc and print pass now share one
  function for the row-then-column precedence. Was duplicated with a
  "must match" comment — exactly the invariant a helper locks in.
- Multi-currency PIVOT test (`test_text_pivoted_multi_currency_uses_per_column_precision`):
  USD (2dp) + JPY (0dp) on the same row, each pivoted column uses its
  own precision. The implementation always handled this correctly; now
  pinned by a test.
- Defensive regression test (`test_non_pivoted_currency_named_column_inherits_fallback_quantization`):
  pins behavior of a non-pivoted query whose column happens to be aliased
  as a tracked currency code. Today's contract is that the fallback DOES
  apply — same as PIVOT. Future tightening would be a deliberate change.
- Compat fixture removed from `bql-queries.toml`. Local verification
  against bean-query revealed bean-query's `PIVOT BY` takes TWO columns
  (pivot value + group key) where rledger takes ONE — the tools produce
  structurally different output, so a row-by-row diff would be
  permanently red. Replaced the fixture with a comment pointing to #1034
  where the reconciliation is tracked.
- PR body updated to call out the apply_pivot column-shape fix as a
  user-visible behavioral change for ALL PIVOT queries (pre-fix the SUM
  column was eating the pivoted USD value, USD column was empty).

Pre-existing items 6+7 from the review (empty-columns underflow,
degenerate value==pivot case) filed as #1034.

20 renderer tests pass. Clippy + fmt clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(query): use targets.len() for value_col_idx in apply_pivot

Address Copilot review on #1033: `apply_pivot` was using
`result.columns.len() - 1` to find the value column, which incorrectly
identifies a hidden ORDER BY column as the value column when the
caller has appended hidden cols (via `find_hidden_order_by_targets`
in execute_select). Fix uses `targets.len() - 1` (last visible target),
since hidden cols are always appended AFTER the visible select
targets.

Defensive `targets.is_empty()` fallback retains the old behavior
rather than panicking — the parser/planner should reject pivot_by
with empty targets, but the function shouldn't trust that.

Surfaced a deeper related bug while writing a regression test: the
strip-hidden-columns step in execute_select truncates from the END
post-PIVOT, but apply_pivot moves hidden cols out of trailing
position into group_cols, so the strip removes the pivot value column
instead. That bug is orthogonal to value_col_idx — both need fixing
for PIVOT + ORDER BY (hidden) to work correctly. Filed as item 4 on
#1034 alongside the other PIVOT robustness gaps from the review.

The value_col_idx fix on its own is correct and necessary; without it
the hidden column's values end up in pivoted output cells (e.g. dates
where SUM values should be). The strip bug just means we can't easily
write a passing integration test for the combined path until #1034
item 4 lands.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(query): backtick group_key in test doc to satisfy clippy doc-markdown

CI clippy runs `--all-targets` which catches doc-comment lints in test
modules; my local clippy run only covered the lib targets and missed
this one. The fix is one missing pair of backticks around `group_key`
in the new pivoted-column test's docstring.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (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.

BQL: residual precision-only divergences in SUM-aggregate output (~15 queries)

2 participants