Skip to content

feat(display): MOST_COMMON precision policy for bean-query parity - #986

Merged
robcohen merged 6 commits into
mainfrom
feat/display-most-common-precision
May 5, 2026
Merged

robcohen merged 6 commits into
mainfrom
feat/display-most-common-precision

Conversation

@robcohen

@robcohen robcohen commented May 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Implements Python bean-query's default precision behavior in rledger's DisplayContext, addressing ~63% of remaining BQL compatibility mismatches.

Local harness: 71% → 78% match rate; ~50% reduction in display-precision divergences. Discounting an unrelated cost-spec brace-format bug, BQL parity reaches 96.4%.

What changed

DisplayContext now stores a per-currency frequency distribution of dp counts and exposes a Precision policy:

  • Precision::MostCommon (new default) — mode of the dp histogram. Matches Python bean-query.
  • Precision::Maximum — highest dp ever observed. Matches Python's Precision.MAXIMUM. Suitable for price-display.

Why

Python bean-query renders RGAGX 128.99 USD (2dp); rledger rendered 128.990 (3dp). Python uses MOST_COMMON inference (mainstream 2dp postings dominate); rledger used MAX (a single 3dp sample wins). Same data, different policy.

beanquery#275 closed wontfix; @blais commented:

"I think that this is related to the no1 issue with beancount, which is the lack of a straightforward, explicit precision setting instead of relying on inference. Once that's in there, this will get resolved."

So matching MOST_COMMON inference is the right step for output parity, while rledger's existing option "display_precision" already delivers the explicit-precision lever blais points to.

Subordinate fixes

  1. quantize pads scale upward — Decimal::round_dp only rounds DOWN; rescale then pads to exactly the target scale.
  2. Loader includes price annotations in the dist — under MostCommon, outliers don't dominate the mode, so the previous exclusion is no longer needed and removing it improves Python parity. Edge case worth flagging: a small file with more Price directives than postings for a given currency could see the mode shift toward the price precision. Python beancount has identical behavior (parity, not regression); use option "display_precision" "USD" 2 to pin it explicitly if needed.
  3. Naked-Decimal columns observe their own values — Value::Number columns now populate a __default__ bucket; matches Python DecimalRenderer's per-column dp tracking.
  4. format_default uses each value's natural scale — matches Python's f'{value:<width}' per-row formatting. Falls back to padding only when value scale is 0 (preserves issue BQL output ignores DisplayContext, breaks per-currency precision #954).

Audit: only one caller affected

Only the BQL renderer (crates/rustledger/src/cmd/query/output.rs) calls format/format_amount/quantize on a DisplayContext. rledger format and report commands use raw Decimal::Display, so this change does not affect their output — no opt-back-into-Maximum path needed in callers.

Tests

  • 10 new unit tests in display_context.rs pinning policy semantics, tie-break, fixed-precision interaction, naked-decimal bucket priority, and BQL output ignores DisplayContext, breaks per-currency precision #954 fallback.
  • Updated 2 existing format_default tests to reflect the new natural-scale rendering.
  • New regression fixture tests/regressions/display-precision-most-common.beancount from beanquery#275.

All 30 display_context tests + full rustledger workspace test suite pass. Clippy clean. Fmt clean.

Test plan

  • cargo test -p rustledger-core passes
  • cargo test -p rustledger passes
  • cargo clippy --all-features --all-targets -- -D warnings clean
  • cargo fmt --all -- --check clean
  • Local BQL harness: 322/450 → 351/450 (+29 matches)
  • Bean-price compat harness still green (different code path, sanity check)

🤖 Generated with Claude Code

Implements Python `bean-query`'s default precision behavior in rledger's
DisplayContext, addressing ~63% of remaining BQL compatibility mismatches
(local harness: 71% → 78% match rate, ~50% reduction in display-precision
divergences).

## What changed

`DisplayContext` now tracks a per-currency frequency distribution of
decimal-place counts (a `BTreeMap<u32, u32>`) instead of just the maximum
observed dp. A new `Precision` policy enum selects how that distribution
collapses to a single per-currency precision:

- `Precision::MostCommon` (default) — the mode of the dp histogram.
  Matches Python `bean-query`'s `Precision.MOST_COMMON` default.
- `Precision::Maximum` — the highest dp ever observed. Matches Python's
  `Precision.MAXIMUM`. Suitable for price-display formatting where
  preserving the highest-precision sample is the explicit goal.

Mode tie-break favors the larger dp on equal counts, matching
`beancount.core.distribution.Distribution.mode`'s ascending-order
iteration with `count >= max_count`.

## Why

Python `bean-query` renders `Assets:US:Vanguard:RGAGX 128.99 USD` (2dp)
where rledger rendered `128.990` (3dp). The divergence is because
rledger inferred USD precision = MAX = 3 (from a single 3dp sample
elsewhere in the file), while bean-query inferred MOST_COMMON = 2 (the
hundreds of mainstream 2dp postings dominated). Same ledger, same data,
different display policy.

beancount#beanquery#275 closed wontfix; @blais commented in that thread:

> "I think that this is related to the no1 issue with beancount, which
> is the lack of a straightforward, explicit precision setting instead
> of relying on inference. Once that's in there, this will get resolved."

So matching bean-query's MOST_COMMON inference is the right step for
output parity, while rledger's existing `option "display_precision"`
already delivers the explicit-precision lever blais points to.

## Subordinate fixes (needed to make the policy switch actually work)

1. **`quantize` now pads scale upward** (`display_context.rs:quantize`).
   `Decimal::round_dp(dp)` only rounds DOWN — it doesn't pad. Pre-fix,
   `quantize(150.67, "USD")` with USD precision=4 returned 150.67
   (scale 2), defeating the bean-query parity. Now uses
   `round_dp(dp).rescale(dp)` to produce exactly the target scale.

2. **Loader now includes price annotations** (`loader/lib.rs:build_display_context`).
   Pre-fix excluded posting `@` prices and `Price` directives to avoid
   inflating the MAX precision with high-dp computed exchange rates.
   Under MostCommon those outliers don't dominate the mode, so the
   exclusion is no longer needed and removing it improves parity with
   Python (which always observes prices).

3. **Naked-Decimal columns observe their own values** (`output.rs:update_column_context`).
   `Value::Number` columns (e.g. `cost_number`, `SUM(number)`) now add
   their values to a `__default__` bucket in the column DisplayContext,
   matching Python `bean-query`'s per-column `DecimalRenderer` (which
   tracks dp independently of the per-currency dctx). Pre-fix only
   inherited from the ledger ctx, which made a USD `cost_number` column
   render at VBMPX's 3dp precision.

4. **`format_default` uses each value's natural scale** instead of
   imposing uniform precision across the column (matches Python's
   `f'{value:<width}'` per-row formatting). Falls back to
   `default_precision()` padding only when the value has scale 0 — this
   preserves issue #954's `SUM(0.00) → "0.00"` behavior.

## Compatibility validation

Ran the BQL harness (`scripts/compat-bql-test.py`) locally on 30 test
files × 15 queries:

| Variant            | Match rate     | Mismatches |
|--------------------|----------------|------------|
| Baseline           | 322/450 (71%)  | 128        |
| Final              | 351/450 (78%)  | 99         |

Of the 99 remaining mismatches:
- 83 are an unrelated cost-spec brace-format bug (`{ 152.41 USD}` vs
  `{152.41 USD}` — leading space). Out of scope; tracked separately.
- 15 are deeper precision issues that need per-renderer logic (also
  out of scope for this PR).
- 1 is a real value-diff (booking-time precision).

Discounting the brace-format bug, this puts BQL parity at 96.4% on the
local corpus.

## Audit: what else uses DisplayContext?

Only the BQL renderer (`crates/rustledger/src/cmd/query/output.rs`)
calls `format`/`format_amount`/`quantize` on a DisplayContext. The
format command (`rledger format`) and report commands use raw
`Decimal::Display`, so this change does not affect their output —
no opt-back-into-Maximum path needed in callers.

## Tests

- 5 new unit tests in `display_context.rs` pinning policy semantics:
  - `mode_picks_most_common_dp`
  - `mode_tie_break_favors_larger_dp` (Python parity)
  - `mode_outlier_does_not_dominate` (the 28dp pathological case)
  - `switching_to_maximum_returns_max`
  - `fixed_precision_overrides_both_policies`
  - `update_from_merges_distributions_not_just_max`
  - `update_from_does_not_propagate_precision_policy`
  - `quantize_pads_scale_upward`
  - `default_precision_prefers_default_bucket_over_max_of_modes`
  - `default_precision_falls_back_when_default_bucket_empty` (#954 path)
- Updated existing `test_format_default_*` tests to reflect the new
  natural-scale rendering.
- New regression fixture `tests/regressions/display-precision-most-common.beancount`
  exercising the SUM(position) parity case from beanquery#275.

All 30 display_context tests + full rustledger workspace test suite
pass. Clippy clean. Fmt clean.

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

codecov Bot commented May 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.87234% with 9 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger/src/cmd/query/output.rs 50.00% 5 Missing ⚠️
...rates/rustledger/src/cmd/doctor/display_context.rs 96.61% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented May 4, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 31.6ms ± 1.1ms 21.8 MB
beancount 837.1ms ± 1.8ms 50.3 MB
Comparison 26.5x faster 2.3x less

vs main branch (2026-05-04)

Metric main this PR Change
Time 33.8ms 31.6ms -6.5% 🟢
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

Adds a new default precision-inference policy to DisplayContext to better match Python bean-query rendering semantics, improving BQL output parity by using a “most common decimals” approach rather than always using the maximum observed scale.

Changes:

  • Introduces per-currency decimal-place histograms and a Precision policy (MostCommon default, Maximum opt-in) in DisplayContext.
  • Updates BQL text output column-context inference to record “naked decimal” (Value::Number) samples into a __default__ bucket and format via format_default.
  • Extends loader DisplayContext population to include posting price annotations and Price directives; adds a regression fixture.

Reviewed changes

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

File Description
tests/regressions/display-precision-most-common.beancount Adds a regression fixture covering MOST_COMMON mode behavior for BQL parity.
crates/rustledger/src/cmd/query/output.rs Updates per-column context inference and formatting for naked-decimal query result columns.
crates/rustledger-loader/src/lib.rs Populates display-context precision data from posting price annotations and price directives.
crates/rustledger-core/src/display_context.rs Implements histogram-based precision inference with configurable policy and updates quantize/default formatting behaviors + tests.

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

@github-actions

github-actions Bot commented May 4, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

Metric Result
Check Compatibility 99%
BQL Compatibility 96%
Full AST Match 99%
Total Files 783
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 3, 2026 22:51
CI Documentation job failed with `unresolved link to get_precision` —
the bare [`get_precision`] form requires a fully-qualified path
(`Self::get_precision` or `DisplayContext::get_precision`) inside doc
comments outside an impl block. Two occurrences fixed.

Verified locally with `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-core --no-deps`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Round-out of PR #986 review feedback. All changes compose with the
existing MostCommon precision policy work.

## DisplayContext diagnostic API

Adds public methods so tooling can introspect the underlying dp
distribution without internal access:

- `currencies()` — iterate observed currencies (skips the
  __default__ sentinel, returns deterministic-sorted order).
- `histogram(currency)` — return `Vec<(u32, u32)>` of (dp, count)
  pairs in ascending dp order. Empty for unknown currencies.
- `precision_under(currency, policy)` — query precision under a
  specific policy without mutating active state. Useful for showing
  Mode-vs-Max side-by-side.
- `has_fixed_precision(currency)` — check whether a currency has a
  fixed override (from `option "display_precision"`).

Re-export `Precision` and `DEFAULT_CURRENCY` from rustledger_core
for external callers (the doctor command needs them).

## doctor display-context: distribution view

Rewrote `rledger doctor display-context` to use the loader's actual
DisplayContext (was building its own MAX-only view) and to surface
the distribution. Sample output:

  USD:
    effective: 2 dp
    distribution: dp=0: 5, dp=2: 141
    mode (MostCommon): 2
    max (Maximum):     4

  VBMPX:
    effective: 3 dp
    distribution: dp=3: 4

`mode` and `max` are shown side-by-side only when they differ — when
they're equal it'd just be visual noise. Fixed overrides are flagged
with `(FIXED via option "display_precision")`.

## Test: integer column stays integer

Pinned per the PR review's "minor concern" — a naked-decimal column
where every observed value has scale 0 (integer count column from
e.g. `SELECT account, SUM(units)`) should render integers, not pad
to some fractional precision borrowed from an unrelated currency.
The __default__ bucket's mode = 0 → no padding, natural rendering.

7 new diagnostic-API tests pin the new methods (currencies, histogram,
precision_under, has_fixed_precision) plus their interaction with
fixed overrides and the __default__ sentinel.

## docs/commands/query.md: precision section

New "Output precision" section explaining:
- How precision is inferred (MostCommon mode of the per-currency
  dp distribution, matches Python bean-query).
- How to inspect the inferred precision and distribution
  (`rledger doctor display-context`).
- How to override inference explicitly
  (`option "display_precision"`).
- The naked-decimal column behavior (per-column tracking +
  natural-scale rendering, with the issue #954 zero-pad fallback).

This is the user-facing companion to the implementation work — gives
people a way to understand and override precision behavior without
having to read the source.

## Verification

- 38 display_context unit tests (was 30; +8 new).
- Full rustledger workspace test suite green (467 tests).
- `cargo clippy --all-features --all-targets -- -D warnings` clean.
- `cargo fmt --all -- --check` clean.
- `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-core --no-deps` clean.
- `rledger doctor display-context` manually verified against
  beanahead/tests_resources_example_ledger.beancount; output matches
  the docs sample.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen and others added 3 commits May 4, 2026 14:34
…w on #986)

Two issues from Copilot's review of PR #986:

## Bug fix: per-cell update_from compounds histogram counts

`update_column_context` was calling `col_ctx.update_from(ledger_ctx)`
for EVERY `Value::Number` cell. After PR #986 changed `update_from`
from max-merge to add-merge (summing counts), the per-cell call
inflated the ledger's sample frequencies by N (number of rows). In
pathological cases, this could shift the column's effective mode
relative to a one-time inheritance.

Fix: hoist the inheritance out of the per-cell loop. In `write_text`,
track per-column whether the ledger ctx has already been inherited;
only merge once when the first `Value::Number` cell is observed in
that column. Removes the corresponding `update_from` call from
`update_column_context` (the function now only observes the cell's
own value into the `__default__` bucket).

`update_column_context` retains the `ledger_ctx` parameter — it's
still used for the `Value::Amount` / `Value::Position` /
`Value::Inventory` arms to quantize values via the ledger's
per-currency precision before observing into the column ctx.

New test `test_update_from_is_not_idempotent_under_add_merge` pins
the semantics that motivated the guard: 1 merge gives 10x2dp samples,
2 merges give 20x2dp samples. Counts compound. Future readers will
understand why the per-cell guard exists.

## Doc accuracy: default_precision behavior

Updated the `default_precision` doc comment to match the actual
post-#986 implementation:

1. Prefers the `__default__` bucket when populated (BQL renderer
   per-column observations).
2. Falls back to max-of-effective-precisions across other currencies
   (issue #954 path — aggregate-of-zero with no naked-decimal samples
   still gets the column's expected dp).
3. Returns 0 for an empty context.

Old wording implied step 2 was the only behavior, which would mislead
callers integrating with the new __default__ path.

## Verification

- 39 display_context unit tests (was 38; +1 idempotency test).
- Full rustledger workspace test suite green.
- Clippy clean, fmt clean.
- CI compat result on prior commit: BQL 91% → 96% (full corpus),
  Check 99%, AST 99%. The per-row inflation could only have shifted
  edge cases — most ledgers don't have a column where the inflation
  meaningfully changes the mode — but pinning correctness is worth it.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two coverage / polish fixes from the pre-merge review.

## Doctor display-context: extracted + tested

Refactored `cmd_display_context` to split file-loading from rendering:
the new `render_display_context` helper takes a `&DisplayContext` plus
a label string and writes to any `&mut impl Write`, so the rendering
logic is unit-testable against manually-constructed contexts without
disk I/O.

7 new unit tests cover the previously-uncovered branches:
- empty context → "No currencies observed."
- single currency → effective + distribution shown, no mode/max block
  (when they're equal, the side-by-side comparison would just be noise)
- mode != max → side-by-side block fires
- fixed override → labeled "(fixed override)"
- render_commas on/off → header line surfaced or omitted
- fixed-only currency (no observed samples) → listed without dist line
- multiple currencies → listed in alphabetical order

Codecov flagged the doctor module as the bulk of uncovered lines on
PR #986; this addresses that.

## Bug fix: misleading "via option" label

The previous label `(FIXED via option "display_precision")` was wrong
when the override came from a programmatic `set_fixed_precision` call
rather than a parsed option. Softened to `(fixed override)` —
source-agnostic, accurate in both paths.

## Test gap: precision_under with fixed=0

The pre-merge agent review flagged that no test covered
`set_fixed_precision(c, 0)`. New test
`test_precision_under_returns_zero_when_fixed_is_zero` pins that both
policies (and `get_precision`) return `Some(0)` when the override is 0.
Regression-tests against a future refactor where `Some(0)` might be
mistakenly treated as "no fixed override".

## Verification

- 40 display_context unit tests (was 39; +1 fixed=0 test).
- 8 doctor display-context unit tests (was 0; new module test mod).
- Full rustledger workspace test suite green (467 + 8 = 475 tests).
- Clippy clean, fmt clean, rustdoc clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen merged commit 8e78bce into main May 5, 2026
36 checks passed
@robcohen
robcohen deleted the feat/display-most-common-precision branch May 5, 2026 01:04
robcohen added a commit that referenced this pull request May 7, 2026
…1020)

`rledger query` rendered positions with a leading space inside the
cost-spec braces (`{ 128.99 USD}`), diverging from `bean-query`
(`{128.99 USD}`). Of the 99 BQL compat mismatches discovered
alongside #986, 83 were this single rendering bug.

Root cause: two `format!(" {{ {}}}", ...)` calls in the query output
path expanded to `" { COST}"`. The core `format_cost_spec` helper in
`rustledger-core` was already correct (`format!("{{{}}}", ...)`); the
divergence was local to the BQL output formatter.

Changes:
- `crates/rustledger/src/cmd/query/output.rs:279,346` — drop the
  leading space inside the braces so output matches `bean-query`.
- Add unit tests for both the `Value::Position` and `Value::Inventory`
  rendering paths so a future format-string change can't silently
  regress this — no snapshot tests pinned the buggy output, which is
  how it shipped in the first place.

Closes #987.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 7, 2026
…1022)

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

`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]>

* fix(query): address PR #1022 review — sidecar sync + false-positive hint 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]>

* test(query): close test gaps + tighten invariants from deep review

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]>

* refactor(query): apply remaining deep-review improvements (13 items)

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]>

* refactor(query): apply review #3 fixes (6 items)

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]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 7, 2026
…rect (#1024)

Issue #989 reported six BQL value-diff mismatches. Investigation found
that five no longer reproduce (resolved by #986/#987/#988). The single
remaining case is an upstream beanquery bug:

  bean-query's FIRST(balance) returns different values for the same
  query and data depending on which other aggregators are in the
  SELECT list. The `balance` column mutates a shared accumulator and
  FIRST short-circuits operand evaluation after the first row,
  leaving the accumulator stale for later groups.

Filed upstream as beanquery#279. rledger's pre-computed-per-row
balance is correct and SELECT-shape-independent.

Excluding the fixture from compat closes the harness divergence.
The file is a deliberately-malformed `_invalid_journal` test fixture
from jbms/beancount-import; excluding it loses no real coverage.

Closes #989.

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.

2 participants