Skip to content

fix(query): ORDER BY an expression finds the column it names - #2215

Merged
robcohen merged 2 commits into
mainfrom
fix/bql-order-by-expression
Sep 1, 2026
Merged

robcohen merged 2 commits into
mainfrom
fix/bql-order-by-expression

Conversation

@robcohen

@robcohen robcohen commented Sep 1, 2026

Copy link
Copy Markdown
Member

Closes #2177.

$ rledger query f.bean "SELECT number + 1 FROM #postings ORDER BY number + 1"
error: ORDER BY expression not found in SELECT: (number + 1)

$ bean-query -f csv f.bean "SELECT number + 1 FROM #postings ORDER BY number + 1"
number + 1
-9.00
-2.00
 4.00
11.00

The header and the lookup spelled the same expression two ways: ast::header_name gives number + 1, Display parenthesizes and gives (number + 1), and sort_results looked up by Display. find_column's case-insensitive fallback cannot bridge that — the spellings differ by punctuation, not case. Before #2175 the header was col0, so the lookup missed for a different reason; the query has never worked.

Why both sites move together

sort_results looks the target up. find_hidden_order_by_targets names the synthetic column when the expression is not reachable in the projection. Changing one alone trades one miss for another — a hidden column named by Display is invisible to a lookup by header_name.

Each half has a test only it satisfies:

mutation result
revert the lookup to Display 3 of 4 tests fail
revert only the hidden-column naming exactly the hidden-column test fails

The neighbouring paths, re-verified rather than trusted

The issue asked for this explicitly, since the hidden-column machinery needed repair twice in #2170. Measured against bean-query (beanquery 0.2.0), row for row:

query result
ORDER BY 1, ORDER BY 2 (ordinals) match
ORDER BY account, number (multi-key) match
ORDER BY number DESC match
GROUP BY account ORDER BY sum(number) match
SELECT account AS a ORDER BY number + 1 (hidden column) match
SELECT number > 0 ORDER BY number > 0 match

Wildcard unchanged: SELECT * FROM #postings ORDER BY date output is byte-identical to main. (It differs from bean-query — 31 columns to its 5 — but that predates this PR and is untouched by it.)

Numbers differ from bean-query only by its right-alignment padding in CSV (, 10.00 against ,10.00), which is pre-existing and independent of ordering.

Corpus

order-by-expression joins tests/compatibility/bql-queries.toml, verified to be real coverage rather than decoration: run through the harness it reports match: True, and match: False when the lookup is reverted.

Note for #2176 / #2180

Sorting needed no ordering work — compare_values_for_sort already handles booleans and is total. This was purely the name lookup.

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

`SELECT number + 1 ORDER BY number + 1` failed with `ORDER BY expression
not found in SELECT: (number + 1)`. The header and the lookup spelled
the same expression two ways: `ast::header_name` gives `number + 1`,
`Display` parenthesizes and gives `(number + 1)`, and `sort_results`
looked up by `Display`.

`find_column`'s case-insensitive fallback cannot bridge that -- the two
spellings differ by punctuation, not case. Before #2175 the header was
`col0`, so the lookup missed for a different reason; the query has never
worked.

Both sites move together, and that is not tidiness. `sort_results` looks
the target up, and `find_hidden_order_by_targets` NAMES the synthetic
column when the expression is not reachable in the projection. Changing
one alone trades one miss for another: a hidden column named by
`Display` is invisible to a lookup by `header_name`. Each half has a
test only it satisfies -- reverting the lookup fails three of four,
reverting the naming fails exactly the hidden-column one.

The issue asked for the neighboring paths to be re-verified rather than
trusted, so they were, against bean-query: ordinals (`ORDER BY 1`,
`ORDER BY 2`), multi-key, DESC, aggregate targets, and an aliased target
whose ORDER BY needs the hidden column all match row for row. The
wildcard is unchanged -- `SELECT *` output is byte-identical to main.

Numbers differ from bean-query only by its right-alignment padding in
CSV (`, 10.00` against `,10.00`), which is pre-existing and independent
of ordering.

`order-by-expression` joins the BQL compat corpus, verified to be real
coverage: it reports `match: True`, and `match: False` when the lookup
is reverted.

Closes #2177
Copilot AI lite review requested due to automatic review settings September 1, 2026 05:35
@robcohen
robcohen requested a review from a team as a code owner September 1, 2026 05:35
@codecov

codecov Bot commented Sep 1, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

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.

🟡 Changes recommended

sort_results still resolves Expr::Function ORDER BY targets via Display rather than header_name, which can keep ORDER BY-on-function-expressions broken and inconsistent with the new hidden-column naming.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

Fixes BQL ORDER BY <expression> resolution by aligning ORDER BY target lookup and hidden sort-column naming with the same renderer used for SELECT headers (ast::header_name), matching bean-query behavior and adding regression coverage.

Changes:

  • Use ast::header_name when resolving ORDER BY expression targets (and when naming synthetic hidden ORDER BY columns).
  • Add a dedicated rustledger-query regression test suite for ORDER BY-on-expression scenarios (selected expression, hidden sort key, ordinals, boolean comparisons).
  • Extend the compatibility corpus with an order-by-expression query to prevent regressions.
File summaries
File Description
tests/compatibility/bql-queries.toml Adds a corpus query ensuring ORDER BY expression lookup matches header spelling.
crates/rustledger-query/tests/order_by_expression_test.rs Introduces regression tests covering ORDER BY expression resolution, hidden-column behavior, and ordinals.
crates/rustledger-query/src/executor/sort.rs Updates ORDER BY resolution to use header spelling (header_name) for expression targets.
crates/rustledger-query/src/executor/execution.rs Ensures hidden ORDER BY columns are named using the same spelling that ORDER BY lookup expects.
Review details
  • Files reviewed: 4/4 changed files
  • Comments generated: 2
  • Review effort level: Lite

💡 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 Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 50.4ms ± 3.5ms 859.3ms ± 11.0ms 17.0x 55.1 MB / 50.1 MB
investment 74.9ms ± 4.1ms 3485.1ms ± 106.3ms 46.5x 59.2 MB / 57.9 MB
fifo 74.8ms ± 4.3ms 18547.0ms ± 1022.5ms 247.9x 61.0 MB / 57.7 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 52.5ms ± 4.7ms 50.4ms ± 3.5ms -3.9% ✅ within noise 55.0 MB → 55.1 MB (+0.1%)
investment 74.0ms ± 3.9ms 74.9ms ± 4.1ms +1.3% ✅ within noise 59.2 MB → 59.2 MB (+0.1%)
fifo 75.1ms ± 4.0ms 74.8ms ± 4.3ms -0.3% ✅ within noise 61.1 MB → 61.0 MB (-0.2%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 2.6ms, investment 2.5ms, fifo 2.6ms), 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

@github-actions

github-actions Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 99% (raw 93%, 169 masked)
Full AST Match 100%
Total Files 812
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 Sep 1, 2026

Copy link
Copy Markdown
Member Author

Correcting my own claim on this PR, and reporting what checking it turned up.

I said the paths the issue named were re-verified. PIVOT BY was not — the issue listed wildcard, PIVOT BY and ordinals, and I checked the first and third. Done now:

PIVOT BY behaves identically on main and this branch, so the change does not touch it. That is what the issue wanted confirmed, and it holds.

But checking it found a pre-existing bug, filed as #2216: PIVOT BY is silently ignored when the query has a FROM clause.

SELECT ... GROUP BY account, year PIVOT BY account, year
  -> columns ["account", "2024"]                    pivoted

SELECT ... FROM #postings GROUP BY account, year PIVOT BY account, year
  -> columns ["account", "year", "sum(number)"]     not pivoted

Neither the parser nor apply_pivot is at fault — the parser populates pivot_by for the FROM form, and apply_pivot produces the right shape on the other one. The FROM <table> execution path returns before reaching the pivot step.

That also explains a wrong turn earlier in this review: my first PIVOT check used the CLI, which writes FROM #postings, so it looked like PIVOT BY was unimplemented rather than skipped on one path.

No change to this PR — #2216 is independent and pre-existing.

Review feedback, and correct. I changed the arm that handles binary
expressions and left `Expr::Function` on `Display`, which parenthesizes
its arguments the same way. So `abs(number + 1)` still looked for
`abs((number + 1))` against an `abs(number + 1)` header.

`abs(number)` resolves either way, which is how the gap hid: the
argument has to be COMPOUND before the two spellings part company, and
every function case I had reached for was a bare column.

Both arms now name the target the way the header does.

Two tests rather than one, so a regression tells you which case broke:
the compound-argument form, and the bare-column form that worked before.
Reverting only this arm fails exactly the first.

Swept wider against bean-query while here -- `number * 2`, unary
`-number`, `ORDER BY <expr> DESC`, a function as a secondary sort key,
and an aliased target sorted by its alias all match row for row.
@robcohen

robcohen commented Sep 1, 2026

Copy link
Copy Markdown
Member Author

Both comments were right, and the first one was a real gap.

Expr::Function still used Display. I changed the binary-expression arm and left the function arm alone, so abs(number + 1) still looked for abs((number + 1)) against an abs(number + 1) header:

$ rledger query f.bean "SELECT abs(number + 1) FROM #postings ORDER BY abs(number + 1)"
error: ORDER BY expression not found in SELECT: abs((number + 1))

abs(number) resolves either way, which is exactly how it hid — the argument has to be compound before the two spellings part company, and every function case I reached for was a bare column. Both arms now name the target the way the header does.

And the test gap you named was the reason I missed it. There are now two tests, not one, so a regression says which case broke: the compound-argument form and the bare-column form. Reverting only the function arm fails exactly the first, and leaves the other five passing.

Swept wider against bean-query while in there — number * 2, unary -number, ORDER BY <expr> DESC, a function as a secondary sort key, and an aliased target sorted by its alias all match row for row.

@robcohen
robcohen merged commit 7957523 into main Sep 1, 2026
57 of 60 checks passed
@robcohen
robcohen deleted the fix/bql-order-by-expression branch September 1, 2026 14:03
robcohen added a commit that referenced this pull request Sep 20, 2026
…n divergence (#2359)

`order-by-expression` hits the same bean-query grouping gap already registered
for these three fava-investor fixtures on a dozen other queries: they set
`option "render_commas" "True"`, beancount consumes the option and we honor it,
and beanquery never reads it. `SELECT number + 1` returns `-1399999` from
bean-query against our `-1,399,999`, identical once the separators come out.

The pairs went unpinned only because the query postdates the block, having been
added in #2215 for #2177. These were three of the seven unmasked mismatches the
suite has been reporting at every coverage level (#2358); the remaining four are
two files of upstream's 1e-7 plugin drift and two uncharacterized scale
differences, which stay unmasked.


Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

Co-authored-by: Claude Opus 5 (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: ORDER BY on an expression target fails; the header and the lookup spell it differently

2 participants