Skip to content

fix(query): keep source order in five system tables, as bean-query does - #2165

Merged
robcohen merged 5 commits into
mainfrom
fix/bql-source-order-v2
Aug 27, 2026
Merged

robcohen merged 5 commits into
mainfrom
fix/bql-source-order-v2

Conversation

@robcohen

@robcohen robcohen commented Aug 27, 2026 •

Copy link
Copy Markdown
Member

What

#balances, #commodities, #events, #notes and #documents sorted by
(date, account|type|name). beancount orders entries by (date, lineno), so
bean-query returns rows sharing a date in the order they were written — and
ours came back reordered.

2020-02-05 event "zeta" "z"
2020-01-20 event "alpha" "a"
2020-02-05 event "beta" "b"
row 1 row 2 row 3
bean-query alpha zeta beta
rledger (before) alpha beta zeta

How

Sort by date alone. sort_by_key is stable and resolved_directives yields
source order, so rows sharing a date come back in the order they were written
— which is why #entries and #transactions, which never applied a secondary
key, already agreed with bean-query.

This matches beancount's (date, lineno) within a single file. It does
not match across an include: beancount compares the raw line number without
regard to which file it came from, so line 1 of an included file sorts ahead
of line 3 of its parent, while we keep each file's directives together.
main orders these the same way, so that gap is pre-existing and neither
caused nor fixed here — filed as #2166. An earlier draft of this PR claimed
an unqualified (date, lineno) match; that was wrong.

What is NOT changed, and why

Two tables have the same shape but cannot be fixed this way. Both are
documented at the code rather than left to look like oversights.

#prices — its rows come from price_db, whose outer map is an
FxHashMap keyed by base currency. Iteration is grouped by currency in
arbitrary order and no source position survives, so the secondary key is the
only thing making that table deterministic at all. Dropping it would trade a
wrong-but-stable order for an unstable one.

I had already changed it before catching this. An empirical check against
bean-query passed — by coincidence, on a two-currency fixture — and
test_prices_table_deterministic_ordering is what actually caught it. That
test earned its keep.

#accounts — built from an FxHashMap, so there is no source order to
restore, and it diverges from bean-query more deeply than ordering:
bean-query's open column is a full Open(...) repr where ours is a date,
and we carry two extra columns. Separate problem.

Verification

All seven sorted tables compared against bean-query on a fixture where source
order differs from every sort key — six match, #prices correctly still
differs.

Two limits worth stating: the BQL compat suite exits 0 without running any
comparison unless a check phase ran first, so I am not counting it as a clean
signal here; and the local corpus has one file containing a note directive
and none containing balance, so it cannot exercise this change. CI runs the
full fetched corpus.

Tests

test_balances_table_deterministic_ordering and
test_commodities_table_deterministic_ordering pinned the old order and now
pin the new one. They still test determinism — just anchored to the source
rather than to the name.

Closes #2163

`#balances`, `#commodities`, `#events`, `#notes` and `#documents` sorted
by `(date, account|type|name)`. beancount orders entries by
`(date, lineno)`, so bean-query returns rows sharing a date in the order
they were written, and ours came back reordered:

    2020-02-05 event "zeta" "z"
    2020-02-05 event "beta" "b"

    bean-query:  zeta, beta      rledger (before):  beta, zeta

Sorting by date alone fixes it. `sort_by_key` is stable and
`resolved_directives` yields source order, so the result is exactly
`(date, lineno)` -- which is why `#entries` and `#transactions`, which
never applied a secondary key, already agreed.

`#prices` is deliberately NOT changed, though it has the same shape. Its
rows come from `price_db`, whose outer map is an `FxHashMap` keyed by
base currency: iteration is grouped by currency in arbitrary order and no
source position survives. The secondary key is the only thing making that
table deterministic, so dropping it would trade a wrong-but-stable order
for an unstable one. `test_prices_table_deterministic_ordering` caught
this after I had already changed it, and an empirical check against
bean-query had passed by coincidence on a two-currency fixture.

`#accounts` is also unchanged and is a separate problem: it is built from
an `FxHashMap`, so it has no source order to restore, and it diverges
from bean-query more deeply than ordering (bean-query's `open` column is
a full `Open(...)` repr; ours is a date, plus we carry two extra
columns).

The two ordering tests that pinned the old behavior now pin the new one.
They still test determinism -- just anchored to the source rather than to
the name.

Closes #2163
Self-review catch (#2165). The comment claimed sorting by date alone
"reproduces beancount's (date, lineno) entry order". That holds within
one file and breaks across an `include`: beancount compares the raw line
number without regard to which file it came from, so line 1 of an
included file sorts ahead of line 3 of its parent, while we keep each
file's directives together.

Verified against `main`, which orders these the same way -- the gap is
pre-existing and neither caused nor fixed here. Tracked as #2166.

The comment also still said `sort_by` after clippy moved the code to
`sort_by_key`.

Same defect class Copilot caught on #2161: a comment claiming more
bean-query parity than the code delivers.

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

Updates rustledger-query system table row ordering to match bean-query/beancount semantics: within the same date, preserve source (lineno) order rather than applying a secondary sort key, fixing visible row reordering in #balances, #commodities, #events, #notes, and #documents.

Changes:

  • Adjust system table sorting to sort_by_key(date) only (stable), relying on the directive stream’s source order for tie-breaking.
  • Add/adjust integration tests to pin source-order behavior within a date across the affected tables and update existing deterministic-ordering assertions.
  • Document (in code and tests) why #prices intentionally keeps a secondary key due to FxHashMap-backed iteration without source position.

Reviewed changes

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

File Description
crates/rustledger-query/src/executor/system_tables.rs Drops secondary sort keys for five system tables (keeps #prices deterministic via secondary key) to preserve source order within the same date.
crates/rustledger-query/tests/bql_integration_test.rs Updates existing ordering tests and adds a regression test covering source-order preservation within a date for the five affected system tables.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@github-actions

github-actions Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 48.5ms ± 4.2ms 777.3ms ± 27.3ms 16.0x 55.1 MB / 50.0 MB
investment 72.3ms ± 5.8ms 2877.6ms ± 75.0ms 39.8x 59.0 MB / 58.0 MB
fifo 71.1ms ± 1.2ms 17590.1ms ± 809.2ms 247.3x 59.2 MB / 58.0 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 48.3ms ± 4.2ms 48.5ms ± 4.2ms +0.5% ✅ within noise 55.0 MB → 55.1 MB (+0.3%)
investment 71.1ms ± 3.2ms 72.3ms ± 5.8ms +1.8% ✅ within noise 59.1 MB → 59.0 MB (-0.1%)
fifo 72.5ms ± 4.2ms 71.1ms ± 1.2ms -1.9% ✅ within noise 61.1 MB → 59.2 MB (-3.2%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 2.7ms, investment 3.0ms, fifo 1.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 Aug 27, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

…rectly

Self-review catch (#2165). Two related problems.

The comments explained the fix as "we sort by date, stability preserves
source order". That is not the mechanism. The loader already delivers
directives in beancount's (date, SORT_ORDER, lineno) order -- `#entries`
never sorts and still comes back ordered, and a file declaring five kinds
on one date in reverse order still queries back in SORT_ORDER. So on the
loader path the sort is a no-op. The bug was never a missing sort; it was
an extra one, a secondary key re-ordering rows that were already right.

The sort does real work only when an `Executor` is built directly from a
caller-supplied slice, as the tests do. Nothing covered that: deleting
the `#notes` sort outright passed the entire suite. The new test builds
out-of-date-order directives by hand and is confirmed to fail when the
sort is removed from #notes, #commodities and #events.

Verified against bean-query that mixed directive kinds sharing a date
already agree, which the PR asserted but had not checked.
@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 170 masked)
Full AST Match 100%
Total Files 811
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

Self-review catch (#2165). The test added in the previous commit to close
a coverage gap closed it only partially: it exercised #notes,
#commodities and #events, so deleting the #balances or #documents sort
still passed all 407 tests.

Each of the five is now confirmed individually -- removing any one sort
fails this test, checked one at a time.
@robcohen
robcohen enabled auto-merge (squash) August 27, 2026 13:51
#2166 investigated and closed as working-as-intended. The comment said
the cross-file gap was "tracked separately", which reads as pending work.
It is a deliberate divergence.

beancount sorts by raw `lineno` with no record of which file it came
from, so adding two comment lines to an included file reorders query
results. Measured across 0, 1 and 2 comment lines: bean-query flips at
two, ours is stable at all three. Replicating that would make row order
depend on incidental formatting of a file the query does not name.

Within a single file `lineno` is meaningful, which is why #2163 matched
bean-query and this does not.
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: five system tables sort rows by a secondary key; bean-query preserves source order

2 participants