Skip to content

fix(query): order BALANCES rows by account_sortkey - #2492

Merged
robcohen merged 3 commits into
mainfrom
fix/bql-balances-sortkey
Oct 8, 2026
Merged

robcohen merged 3 commits into
mainfrom
fix/bql-balances-sortkey

Conversation

@robcohen

@robcohen robcohen commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

What changed

BALANCES rows were ordered by account name. bean-query's BALANCES is sugar for SELECT account, sum(position) ... GROUP BY account ORDER BY account_sortkey(account), so it orders by account type first (Assets, Liabilities, Equity, Income, Expenses, honoring name_* renames), then name. execute_balances now sorts by (account_type_index, name), the same config-aware classifier ACCOUNT_SORTKEY uses. Values are unchanged; only row order moves.

tests/compatibility/bql-queries.toml: balances-by-account now has preserve_order = true, so the differential compares the order too (it compared BALANCES as a set, which is why this went unregistered). No KNOWN_* registry entry needed changing.

Verification

  • bean-query 0.2.0 / beancount 3.2.3 on a ledger with option "name_income" "Revenue" and accounts in all five types: Assets:Bank, Liabilities:Card, Equity:Opening, Revenue:Salary, Expenses:Food, Expenses:Rent, with and without FROM ... WHERE. rledger now gives the same.
  • New crates/rustledger-query/tests/balances_account_order_test.rs (2 tests) fails without the fix (got plain name order) and passes with it.
  • Local BQL compat harness (scripts/compat-bql-test.py, 36 files x 19 queries) with the order-sensitive balances-by-account: 0 real mismatches, balances-by-account 35/35.
  • cargo test -p rustledger-query --all-features, the CLI's BALANCES tests (report_display_context_test, query_report_realization_parity_test, decimal_overflow_test, report_capgains_test), workspace clippy -D warnings, cargo doc -D warnings clean.

rustfava check

rustfava tests against PR component goes from the known 5 failures to 8 (671 passed). The 3 new ones are rustfava snapshots that pinned the old name order of BALANCES rows: test_core_query_shell.py::test_query_balances, ::test_query_to_file, and test_json_api.py::test_api_query_result[balances from year = 2014-balances]. I rebuilt both sides of all three diffs from the CI log. Each holds the same set of rows (the same accounts and amounts) in a new order. Liabilities:* moves ahead of Equity:*, and Income:* ahead of Expenses:*, which is bean-query's order. The JSON test's diff also shows 130 vs 130.0, but Python compares those as equal; only the order fails it. Those snapshots need regenerating in rustfava once this lands.

Harness self-check and new fixtures (commit 4462c96)

Correction to my first review comment. I said only 2 of 35 files could tell the two orders apart. That came from the partial corpus I had locally. Re-run on the full fetched corpus (740 files, CI's file order, 150-file budget), with balances-by-account order-sensitive:

balances-by-account real mismatches
main 184e9d1 45 (43 corpus files + both new fixtures)
this branch 0

So the check already catches the bug broadly in CI, and the harness can report dirty. The two in-tree fixtures added under tests/compatibility/files/bql/ (with a .gitignore exception like costs/ and interpolation/) still pull their weight: they do not depend on the downloaded corpus (which changes upstream and is capped at 150 files per run), and they pin both the default roots and renamed roots in files built for this check:

  • balances_account_order.beancount: all five account types, every one reachable from BALANCES FROM has_account('Assets').
  • balances_renamed_roots.beancount: name_liabilities "Debts", name_equity "Capital", name_income "Revenue", name_expenses "Spending". Plain name order (Capital before Debts) and an order with the roots hardcoded both differ from bean-query's.

Main fails balances-by-account on both fixtures and this branch passes. Both pass bean-check, rledger check, the format idempotence check and the bean-format roundtrip. I added their two lines to the parser and CST corpus manifests, inserted where a full regen puts them, and left everything else in each manifest untouched. STRICT_BASELINE=1 passes on both.

Other surfaces

  • wasm balances(), the FFI component and MCP all run BALANCES through the executor, and each calls set_account_types, so they follow the new order, including name_* renames.
  • rledger report balances stays in name order. That is beancount v2 bean-report balances order (checked: Assets, Equity, Expenses, Liabilities, Revenue). It is not BQL and has no bean-query counterpart, so it does not change. balsheet groups by type itself.
  • JOURNAL is ordered by date. PIVOT follows ORDER BY or sorts by key (BQL: PIVOT BY orders its columns by row order (ORDER BY), bean-query sorts them by value #2440). A SELECT ... GROUP BY account with no ORDER BY makes no order promise. None of them should follow this change.

Closes #2409

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

BALANCES sorted rows by account name, so Expenses came before
Liabilities. bean-query's BALANCES is GROUP BY account ORDER BY
account_sortkey(account): account type first (honoring name_* renames),
then name. The compat corpus now compares balances-by-account in order.

Closes #2409

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen requested a review from a team as a code owner October 7, 2026 20:29
@github-actions

github-actions Bot commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 48.6ms ± 1.5ms 902.6ms ± 16.8ms 18.6x 51.0 MB / 49.8 MB
investment 77.3ms ± 3.2ms 3189.2ms ± 35.3ms 41.3x 54.9 MB / 58.2 MB
fifo 76.7ms ± 1.2ms 15676.0ms ± 59.3ms 204.5x 55.2 MB / 57.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 48.9ms ± 4.8ms 48.6ms ± 1.5ms -0.7% ✅ within noise 51.0 MB → 51.0 MB (-0.0%)
investment 74.4ms ± 2.8ms 77.3ms ± 3.2ms +3.8% ✅ within noise 54.9 MB → 54.9 MB (-0.0%)
fifo 75.4ms ± 1.5ms 76.7ms ± 1.2ms +1.6% ✅ within noise 55.2 MB → 55.2 MB (+0.0%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 2.3ms, investment 1.9ms, fifo 0.9ms), and is at least 5%.
10,000 transactions per shape · 20 runs, 3 warmup · hyperfine

What do these numbers mean?
  • simple — Two-posting transfers, one currency. The historical workload — keep as the floor, not as the benchmark.
  • investment — Cost specs, per-unit prices and lot reductions. Exercises booking and inventory, which simple leaves at 0.3%.
  • fifo — Bare {} reductions against a FIFO account — how FIFO sells are normally written. The other four shapes reach the ordered-selection path twice in 2k transactions between them, so it was effectively unprofiled until it turned out to be quadratic (plan_ordered scans every lot per reduction: FIFO ledgers are quadratic (8.8s at 20k transactions) #2083).
  • vs base: the PR and the base-branch commit it is built on, built and measured in the same job
  • RSS: peak resident set size, a single sample — reported without a verdict because there is no spread to test it against
  • A shape with no beancount column is one bean-check reports errors on; it is timed for rledger only

@codecov

codecov Bot commented Oct 7, 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 Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 179 masked)
Full AST Match 100%
Total Files 819
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
    The headline is the EFFECTIVE rate, after pairs where beanquery
    itself is wrong are masked. raw is the same run with nothing
    masked. A widening gap means the registry grew, not that rledger
    changed.
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

@robcohen

robcohen commented Oct 8, 2026 •

Copy link
Copy Markdown
Member Author

Review (final: 3 passes)

Corrected (pass 2): on the full corpus, main fails order-sensitive balances-by-account on 45 files and this branch on 0. My pass-1 figure of "2 of 35" came from a partial local corpus.

Fixtures (4462c96): tests/compatibility/files/bql/ adds one ledger with all five account types and one with renamed roots.

rustfava (8 failed / 671 passed) is exactly the 5 known plus 3 expected.

  • Known (also red on docs(query): resolve the private intra-doc links in rustledger-query #2494): test_core_tree.py::test_tree_cap, test_json_api.py::test_api_errors, test_api[options-…], test_api[balance_sheet-…], test_api[balance_sheet_with_cost-…].
  • Expected, BALANCES row order: test_core_query_shell.py::test_query_balances, test_core_query_shell.py::test_query_to_file, test_json_api.py::test_api_query_result[balances from year = 2014-balances]. Pure reordering, checked.

Code (pass 3): no change needed. The sort uses the same config-aware account_type_index as ACCOUNT_SORTKEY.

For @robcohen: regenerate those 3 rustfava snapshots after merge.

Integration (final heads, plus #2487, #2490 and #2491, merged onto main 184e9d1 in a scratch tree with its own target dir): the only conflicts are in CHANGELOG.md, one hunk per merge at the top of ### Fixed; keep both entries. #2487's manifest lines and #2492's merge cleanly. On the combined tree:

  • query tests pass (804 across 37 binaries)
  • STRICT_BASELINE=1 parser and CST baselines pass
  • workspace clippy is clean, and the private-items docs show 0 errors
  • the full-corpus BQL harness reports 0 real mismatches (150 files in CI order, fixtures included)

Merge order: #2494 → #2489 → #2492 → #2493; #2487, #2490 and #2491 can go anywhere. Nothing is order-dependent.

Review follow-up. Only 2 of 35 corpus files distinguished name order
from account_sortkey order, so the order-sensitive balances-by-account
check barely bit. Add two in-tree fixtures under
tests/compatibility/files/bql/: one with all five account types, one
with renamed roots via name_* options. main's binary fails
balances-by-account on both; this branch passes. Parser and CST
manifests gain the two entries.

Refs #2409

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
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 BALANCES orders rows by account name, beanquery by account_sortkey

1 participant