Skip to content

fix(query): head results the way bean-query does - #2170

Merged
robcohen merged 4 commits into
mainfrom
fix/bql-header-casing
Aug 27, 2026
Merged

robcohen merged 4 commits into
mainfrom
fix/bql-header-casing

Conversation

@robcohen

@robcohen robcohen commented Aug 27, 2026 •

Copy link
Copy Markdown
Member

What

bean-query and rustledger disagreed on how to name result columns. Three
rules, each measured against bean-query 3.x:

target bean-query ours (before)
SELECT DATE date DATE
SELECT DaTe date DaTe
SELECT DATE AS D d D
SELECT date AS LatestDate latestdate LatestDate
SELECT count(date) count(date) count
SELECT SUM(number) SUM(number) SUM
SELECT sum(NUMBER) sum(NUMBER) sum

So: identifiers (bare columns and aliases) are lowercased; a function target
is headed by its source text, case intact.

This matters for anything consuming our CSV by header name. A script written
against bean-query reads the narration field, gets NARRATION from us, and
misses it with no error.

The issue understated it twice

#2164 was filed about casing of bare columns. Measuring first showed:

  • aliases are lowercased too — the issue explicitly assumed they must be
    preserved, and that was wrong
  • we dropped function arguments entirely — a separate bug, not casing

Lowercasing broke ORDER BY, and that took two fixes

ORDER BY and PIVOT BY resolve against result headers by exact match, so
ORDER BY DATE stopped finding the now-lowercase date column. bean-query
accepts that query and it worked before this change — a real regression,
caught because it was the risk the issue itself flagged.

Then a subtler one. find_hidden_order_by_targets uses the alias field as
an internal naming mechanism
, appending a hidden column named by its
expression's source text (MIN(date)). Blanket alias-lowercasing renamed it
to min(date) while the lookup still searched for MIN(date), so
ORDER BY MIN(date) on a hidden column failed. That is a genuinely broken
internal contract, not an expectation change, and
test_pivot_by_with_order_by_on_hidden_column_works caught it.

Both fixed by one find_column helper — exact match first, then
case-insensitive — shared by all five ORDER BY / PIVOT BY lookup sites.
Exact-first so an exact hit still wins if two columns differ only by case. The
column_indices map it replaces is now dead and removed, dropping a map
allocation per sort.

Test changes

Six failed. Five were expectation updates that now match bean-query
(sum → sum(number), ["account","Balance","Converted"] →
["account","balance","converted"]), including one stale comment that
documented the old naming explicitly. The sixth was the real hidden-column
breakage above.

The CLI aggregate snapshot moves SUM → SUM(position). Confirmed that is
what bean-query emits for that exact query rather than assumed.

Verification

  • Each of the three naming rules and the case-insensitive lookup has a test,
    and each was confirmed to fail against its own unfixed code — reverted
    separately, not together.
  • Header comparison run against bean-query directly across nine query shapes.
  • Booked-value gate clean (known 34, found 34, new 0); corpus_parity
    divergences still exactly 20, matching main (pre-existing corpus_parity diverges under workspace feature unification when the debug component wasm is present #1809).
  • clippy at CI's 1.97, fmt, typos, rustdoc clean; full workspace tests pass.

Scope, checked rather than assumed

Unchanged by this PR, verified against a main build:

  • SELECT * headers — they come from the table's column list, not
    expr_to_name
  • postfix targets — meta['k'] heads meta['k'], matching bean-query
  • window functions — ROW_NUMBER() OVER (...) still heads ROW_NUMBER,
    deliberately not the source text the Function arm now uses. OVER is a
    rustledger extension with no bean-query behaviour to match, and the full
    source text as a header would help nobody. Documented at the code so it does
    not read as an oversight; alias it (AS rn) for a different name.

Two aliases differing only by case now collapse to one header
(SELECT date AS A, account AS a heads a,a), as does a column colliding
with an alias. Both match bean-query exactly, checked directly since this is a
collision the change introduces.

Downstream surfaces

Checked against a main build rather than reasoned about:

  • JOURNAL, BALANCES and PRINT are unchanged — they carry fixed
    column names and never reach expr_to_name.

  • -f json changes, because the header is both the columns entry and
    the per-row object key:

    main:  {"columns": ["COUNT"],       "rows": [{"COUNT": 1}]}
    this:  {"columns": ["COUNT(date)"], "rows": [{"COUNT(date)": 1}]}
    

    A consumer doing row.COUNT now needs row["COUNT(date)"]. bean-query has
    no JSON format (beancount|csv|text only), so there is nothing to match
    here; keeping the key identical to the CSV header is the consistent choice,
    but it is a visible wire change worth stating. The wire-format bindings
    freshness check passes — column names are data, not schema.

  • The rustfava component test fails on snapshot drift ('sum(day)' vs
    'sum'), which is this change landing, not a defect.

Known remaining gap

Literal and binary-expression targets still head as colN where bean-query
prints the expression (number + 1, NOT (number > 0)). Not fixed here
because expr.to_string() — the mechanism this PR uses for functions —
renders (number + 1) and "lit", so it would still not match. bean-query
prints with minimal parentheses, measured; ours parenthesizes every binary
node, and Display is also what names the synthetic hidden ORDER BY columns,
so it cannot simply be changed. Filed as #2171 with the measurements.

Shipping the partial version was considered and rejected: it buys no
compatibility while churning affected headers a second time.

Left alone

SELECT DATE AS D FROM #notes ORDER BY d fails on main and still fails
here — a different lookup path (subquery result columns) with the same
case-sensitivity shape. Pre-existing, verified against a clean main build,
and out of scope for this change.

Closes #2164

Three naming rules, each measured against bean-query 3.x rather than
inferred:

  bare column  ->  the column's own name, lowercased: `SELECT DATE`
                   heads `date`
  alias        ->  lowercased, including mixed case: `AS LatestDate`
                   heads `latestdate`
  function     ->  the target's SOURCE TEXT, case intact: `sum(NUMBER)`
                   stays `sum(NUMBER)`

We echoed the query's spelling for the first two and emitted only the
bare function name for the third, so `SELECT count(date)` headed `count`
where bean-query heads `count(date)`. Anything reading our CSV by header
name -- a script written against bean-query -- missed the field silently.

The third rule is not what the issue described. #2164 was filed about
casing alone; measuring first turned up the dropped arguments, and that
aliases are lowercased too, which the issue had explicitly assumed must
be preserved.

Lowercasing exposed a second problem. ORDER BY and PIVOT BY resolved
against result headers by exact match, so `ORDER BY DATE` stopped
finding the now-lowercase `date` column -- a query bean-query accepts and
that worked before this change. Worse, `find_hidden_order_by_targets`
uses the alias field as an internal naming mechanism, naming a hidden
column by its expression's source text (`MIN(date)`); lowercasing that
alias broke `ORDER BY MIN(date)` against it.

Both are fixed by one `find_column` helper, exact match first and then
case-insensitive, shared by the five ORDER BY / PIVOT BY lookup sites.
Exact-first so an exact hit still wins when two columns differ only by
case. Its `column_indices` map is now dead and removed.

The CLI aggregate snapshot moves from `SUM` to `SUM(position)`, which is
what bean-query emits for that query; confirmed directly rather than
assumed.
@robcohen
robcohen requested a review from a team as a code owner August 27, 2026 17:50
Copilot AI lite review requested due to automatic review settings August 27, 2026 17:50
@codecov

codecov Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 65.51724% with 10 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-query/src/executor/sort.rs 52.38% 10 Missing ⚠️

📢 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.

Pull request overview

Aligns rustledger BQL result column headers with bean-query 3.x semantics so downstream consumers (notably CSV header-based scripts) get consistent, compatible column names, while preserving query correctness for ORDER BY / PIVOT BY.

Changes:

  • Normalize result headers so bare columns and aliases are lowercased, while function targets use the expression text (including arguments).
  • Make ORDER BY / PIVOT BY column resolution prefer exact matches, then fall back to case-insensitive matching via a shared helper.
  • Update/extend integration and snapshot tests to match the new bean-query-compatible naming behavior.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
crates/rustledger/tests/snapshots/cli_snapshot_test__query_aggregate_output.snap Updates CLI snapshot header to reflect function-target header (SUM(position)).
crates/rustledger-query/tests/bql_integration_test.rs Updates expectations and adds regression tests for header naming + case-insensitive ORDER BY resolution.
crates/rustledger-query/src/executor/sort.rs Introduces find_column helper and applies it across ORDER BY / PIVOT BY lookup paths; removes per-sort column index map allocation.
crates/rustledger-query/src/executor/mod.rs Adjusts SELECT header generation: aliases and bare columns are lowercased; functions use expression text.
crates/rustledger-query/src/executor/execution.rs Mirrors alias-lowercasing behavior in execution-path column naming.

💡 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 50.3ms ± 6.7ms 822.5ms ± 1.2ms 16.4x 55.1 MB / 50.1 MB
investment 68.6ms ± 2.7ms 2956.0ms ± 65.5ms 43.1x 59.1 MB / 58.1 MB
fifo 70.5ms ± 5.9ms 15401.5ms ± 178.7ms 218.5x 59.0 MB / 58.0 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 47.3ms ± 2.2ms 50.3ms ± 6.7ms +6.3% ✅ within noise 55.1 MB → 55.1 MB (-0.0%)
investment 69.1ms ± 2.2ms 68.6ms ± 2.7ms -0.6% ✅ within noise 59.1 MB → 59.1 MB (-0.0%)
fifo 68.9ms ± 3.2ms 70.5ms ± 5.9ms +2.3% ✅ within noise 61.0 MB → 59.0 MB (-3.3%)

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

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

Review catch on #2170. `find_column` fell back to
`eq_ignore_ascii_case`, but the headers it searches were produced by
Unicode `to_lowercase` in `expr_to_name` and the alias path. The two
halves disagreed for any non-ASCII identifier:

    SELECT date AS DÄTE FROM #notes ORDER BY DÄTE

heads the result `däte`, then failed to find it. bean-query rejects that
query outright, so there is no external behavior at stake -- but
accepting an alias, lowercasing it, and then not finding it is incoherent
on its own terms.

Confirmed to fail when the comparison is put back to ASCII-only.

The exact-match fast path is unchanged, so the allocating comparison only
runs when a query writes a name in a different case than the header.
Review note on #2170. The Function arm heads a result with the target's
source text; the Window arm deliberately does not. `OVER` is a
rustledger extension with no bean-query behavior to match, and
`ROW_NUMBER() OVER (PARTITION BY account ORDER BY date)` as a header
helps nobody. Verified unchanged from main rather than assumed.
Review note on #2170. bean-query names a literal or binary-expression
target by printing the expression; we emit colN. The obvious fix --
expr.to_string(), as the Function arm now uses -- renders (number + 1)
and "lit" where bean-query gives number + 1 and 'lit', because
bean-query prints with minimal parentheses and ours parenthesizes every
binary node.

Display is also what names the synthetic hidden ORDER BY columns, so it
cannot be changed without care. Tracked in #2171 rather than shipped
half-matching.
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: result headers echo the query's casing; bean-query normalizes to the column name

2 participants