Skip to content

fix(query): head expression targets the way bean-query renders them - #2175

Merged
robcohen merged 5 commits into
mainfrom
fix/bql-expression-headers
Aug 28, 2026
Merged

robcohen merged 5 commits into
mainfrom
fix/bql-expression-headers

Conversation

@robcohen

@robcohen robcohen commented Aug 28, 2026 •

Copy link
Copy Markdown
Member

What

SELECT number + 1 headed col0. SELECT 'lit' headed col0. A name that
identifies nothing, and one a script reading our CSV by header cannot find.

query bean-query before after
SELECT 1 1 col0 1
SELECT 'lit' 'lit' col0 'lit'
SELECT number + 1 number + 1 col0 number + 1
SELECT (number + 1) * 2 (number + 1) * 2 col0 (number + 1) * 2
SELECT sum(number + 1) sum(number + 1) sum((number + 1)) sum(number + 1)

bean-query renders the tree faithfully, not minimally

This is why #2171 was filed rather than fixed inline in #2164. The obvious
implementation — parenthesize by precedence — disagrees with bean-query:

(number > 0) AND (number < 5)   both pairs KEPT, though precedence needs neither
number + 1 * 2                  nothing added
NOT number > 0                  nothing added
number - (1 - 2)                kept
((number + 1))                  -> number + 1, only the outer pair dropped

So bean-query preserves the parentheses the query wrote and adds none, except
around the whole target. Every expectation here was read off bean-query 3.x
rather than derived.

Why not just use Display

Display parenthesizes every binary node and double-quotes strings. That is
correct for what it is used for — naming the synthetic hidden ORDER BY columns,
where round-tripping is what matters, and which #2170 repaired — and wrong for
a header. Display is untouched; ast::header_name is separate.

A divergence #2164 left behind

Function targets were headed with Display, so sum(number + 1) headed
sum((number + 1)). I did not catch it there because my testing used only
simple column arguments. Same renderer fixes it.

Unary operators

UnaryOperator's Display bakes in its own spacing and position: NOT
is prefix with a trailing space, - is prefix with none, and IS NULL /
IS NOT NULL are postfix with a leading space. Formatting them uniformly
as prefix produced NOT x and IS NULL x.

A CSV bug this exposed

Headers could not contain a comma before this change — they were identifiers
or colN. Now SELECT number IN (1, 2) heads number IN (1, 2), and
write_csv was joining header names raw while escaping every value:

ours:       ['number IN (1', ' 2)']      <-- two fields for one column
bean-query: ['number IN (1, 2)']

A consumer reads more headers than there are columns and misaligns every field
after it, with no error. Fixed with the same escape_csv the value rows
already used, which also brings the three IN shapes into agreement with
bean-query.

Cleanup

colN is gone, so expr_to_name no longer needs the target index. The
parameter and both enumerate() calls went with it.

Verification

  • 24 header shapes compared against bean-query, all matching, and re-run
    after each refactor rather than assumed.
  • Unit tests cover the rendering rules directly, confirmed to fail when the
    parenthesizing, the postfix position, or the top-level stripping is reverted
    — checked one at a time.
  • Booked-value gate clean (known 34, found 34, new 0); corpus_parity
    divergences still exactly 20, matching main.
  • clippy at CI's 1.97, fmt, typos, rustdoc clean; 415 tests pass.

Closes #2171

`SELECT number + 1` headed `col0`, `SELECT 'lit'` headed `col0`. A name
that identifies nothing, and one a script reading our CSV by header cannot
find at all.

bean-query renders the parse tree FAITHFULLY. It keeps the parentheses
the query wrote, including ones precedence does not require, and adds
none of its own:

    (number > 0) AND (number < 5)  ->  both pairs kept
    number + 1 * 2                 ->  nothing added
    NOT number > 0                 ->  nothing added
    ((number + 1))                 ->  number + 1, outer pair dropped

That is measured, not derived. Minimal parenthesization by precedence was
the obvious implementation and it disagrees on the first case, which is
why #2171 was filed rather than fixed inline.

The new `ast::header_name` renders that way. It is deliberately NOT
`Display`: `Display` parenthesizes every binary node and double-quotes
strings, which is right for what it is used for -- naming the synthetic
hidden ORDER BY columns, where round-tripping matters -- and wrong for a
header. `Display` is untouched.

This also fixes a divergence #2164 left behind and I did not catch there:
function targets were headed with `Display`, so `sum(number + 1)` headed
`sum((number + 1))`. My testing on that PR used only simple column
arguments.

Unary operators needed care. `UnaryOperator`'s Display bakes in its own
spacing and position -- `NOT ` prefix with a trailing space, `-` prefix
with none, and ` IS NULL` / ` IS NOT NULL` POSTFIX with a leading space.
Formatting them uniformly as prefix produced `NOT  x` and `IS NULL x`.

`colN` is gone, so `expr_to_name` no longer needs the target index; the
parameter and both `enumerate()` calls are removed.

24 header shapes checked against bean-query, all matching. Unit tests
cover the rendering rules directly and were confirmed to fail when the
parenthesizing, the postfix position, or the top-level stripping is
reverted.

Closes #2171
Copilot AI lite review requested due to automatic review settings August 28, 2026 20:00
@robcohen
robcohen requested a review from a team as a code owner August 28, 2026 20:00
@codecov

codecov Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.20690% with 8 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-query/src/ast.rs 79.48% 8 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

This PR updates rustledger-query’s result-column header naming so expression targets (literals, unary/binary expressions, and function calls) are headed using a bean-query-compatible renderer (ast::header_name) instead of defaulting to colN or relying on Display.

Changes:

  • Introduces ast::header_name / header_fragment to render header text in a way intended to match bean-query’s column headings (preserving user-written parentheses, stripping only top-level wrapping parens).
  • Switches Executor::expr_to_name to use header_name for functions and all non-identifier expressions, removing the colN fallback and dropping the now-unused target index plumbing.
  • Adds unit tests that compare a set of header shapes against expected bean-query renderings.

Reviewed changes

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

File Description
crates/rustledger-query/src/ast.rs Adds header_name rendering logic for expression-based headers.
crates/rustledger-query/src/executor/mod.rs Routes expression-to-header naming through ast::header_name; removes colN naming/index usage.
crates/rustledger-query/src/executor/execution.rs Updates target iteration and calls into the new expr_to_name signature (no index).
crates/rustledger-query/src/executor/tests.rs Adds direct unit coverage for ast::header_name against expected header renderings.
Suppressed comments (1)

crates/rustledger-query/src/ast.rs:681

  • Expr::Subscript headers always render the key as ['{key}']. Since keys are parsed as generic string literals, they can come from double-quoted input and contain an unpaired ' (e.g. ["o'clock"]), which this renderer would turn into ['o'clock'] and misrepresent the original expression. Consider the same “unpaired quote ⇒ use double quotes” rule as for string literals.
        Expr::Subscript { operand, key } => {
            format!("{}['{key}']", header_fragment(operand))
        }

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

Comment thread crates/rustledger-query/src/ast.rs Resolved
@github-actions

github-actions Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

🔴 Slower than base on: simple

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 49.9ms ± 6.1ms 727.9ms ± 1.6ms 14.6x 55.2 MB / 49.9 MB
investment 71.1ms ± 4.0ms 2779.9ms ± 23.1ms 39.1x 59.1 MB / 58.0 MB
fifo 67.4ms ± 4.6ms 16034.2ms ± 222.6ms 238.0x 61.0 MB / 57.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 46.5ms ± 3.8ms 49.9ms ± 6.1ms +7.2% 🟡 slower 55.3 MB → 55.2 MB (-0.1%)
investment 71.0ms ± 3.9ms 71.1ms ± 4.0ms +0.1% ✅ within noise 59.0 MB → 59.1 MB (+0.0%)
fifo 68.6ms ± 5.0ms 67.4ms ± 4.6ms -1.8% ✅ within noise 61.1 MB → 61.0 MB (-0.1%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 3.2ms, investment 2.5ms, 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 #2175 from Copilot. Every string literal was rendered
single-quoted, so a value containing a single quote produced 'o'clock' --
not a well-formed literal, and not what the query wrote.

Now double-quoted when the value contains a single quote and no double
quote. That case also happens to agree with bean-query.

Full parity is out of reach here and is filed as #2176: bean-query echoes
the quote character the query used, and Literal::String does not record
which it was, so "dq" still heads 'dq'.

Confirmed the test fails when the condition is forced false.
Review catch on #2175. `write_csv` escaped every value but joined the
header names raw. That was harmless while headers were identifiers or
`colN`; this PR makes them able to contain commas -- `SELECT number IN
(1, 2)` heads `number IN (1, 2)` -- and an unescaped one splits in two:

    ours:       ['number IN (1', ' 2)']
    bean-query: ['number IN (1, 2)']

A consumer then reads more headers than there are columns and misaligns
every field after it, with no error anywhere. Now escaped with the same
helper the value rows already used, which also makes the three `IN`
shapes match bean-query.

Confirmed the test fails against the unescaped join.
Self-review catch on #2175. `ast` is a `pub mod`, so declaring
`pub fn header_name` put an internal rendering helper into
rustledger-query's API surface. Every caller is in this crate -- two arms
of `expr_to_name` and one test -- so it is `pub(crate)` now.

Nothing outside could have depended on it yet; it was added in this same
PR.
Sixth review pass on #2175 found no defect; this locks in what it
verified.

Nested calls in both directions (sum(neg(number)), length(payee) + 1),
the wildcard argument (count(*)), and the postfix targets
(entry.narration, meta['k'], entry.meta['k']) all match bean-query but
had no test.

The postfix ones are worth pinning specifically: expr_to_name routes them
through Display rather than header_name, for the ORDER BY reason in
#1800. The two renderings agree on these shapes, so the split is not
observable -- this keeps it that way, and would catch it if either
renderer moved.
@robcohen
robcohen merged commit fe2dc8c into main Aug 28, 2026
59 of 60 checks passed
@robcohen
robcohen deleted the fix/bql-expression-headers branch August 28, 2026 22:11
robcohen added a commit that referenced this pull request Sep 1, 2026
`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
robcohen added a commit that referenced this pull request Sep 1, 2026
* fix(query): ORDER BY an expression finds the column it names

`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

* fix(query): the function arm of the ORDER BY lookup had the same bug

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 added a commit that referenced this pull request Sep 2, 2026
…2229)

`SELECT "dq"` headed `'dq'`. bean-query names such a column by
reproducing the literal as typed, quote character included. Closes #2176.

`Literal::String` did not record which quote the source used, so the
header had to guess: single quotes unless the value contained one. It
now carries a `QuotedString`, and the header echoes what was written.
Verified against beanquery 0.2.0 -- `'plain'`, `"dq"`, `"o'clock"`,
`'it''s'`, `'say "hi"'`, and the same inside a call like
`length('abc')`, all agree.

The body is reproduced VERBATIM, as bean-query does: `'it''s'` heads
`'it''s'`, the doubled quote left as written rather than re-escaped.
That matches the value semantics already pinned in
`string_literal_escapes_test.rs`, where `''` stays in the value.

Quote style is source provenance, not part of the value, so
`QuotedString` implements `PartialEq` and `Hash` on the text alone --
`'x'` and `"x"` are the same string, and AST equality must not depend on
typing style. Same reasoning as `Spanned`, which keeps equality on its
value rather than its span. Pinned, including the Hash/Eq agreement a
`HashMap` keyed on literals would need.

`quote` is `None` for a literal built in code rather than parsed, which
has no style to echo; those keep the #2175 fallback, so that fix is
untouched. `Display` echoes the source quote too, which makes a parsed
literal round-trip as written -- the issue notes this may matter more
than the header does -- and still falls back to double quotes.

`string_literal` now delegates to the new `quoted_string_literal`
instead of restating the grammar. The two arms were about to be
duplicated, and a fix applied to one and not the other would make a
literal parse differently depending on which caller reached it.

The header and `Display` paths are controlled separately: making either
ignore the recorded style fails tests, and the equality test fails if
`PartialEq` starts comparing it.
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: literal and binary-expression targets head as colN; bean-query prints the expression

2 participants