Skip to content

fix(query): PIVOT BY applies when the query names a table - #2218

Merged
robcohen merged 4 commits into
mainfrom
fix/pivot-with-from-clause
Sep 1, 2026
Merged

robcohen merged 4 commits into
mainfrom
fix/pivot-with-from-clause

Conversation

@robcohen

@robcohen robcohen commented Sep 1, 2026

Copy link
Copy Markdown
Member

Closes #2216.

PIVOT BY was silently dropped by any query with a FROM clause. It parsed, it validated, and the un-pivoted result came back with no error. Since rledger query is normally written with an explicit table, the CLI could not pivot at all:

$ rledger query f.bean "SELECT account, year, sum(number) FROM #postings GROUP BY account, year PIVOT BY account, year"
account,year,sum(number)          <- not pivoted
Assets:A,2024,7.00

$ bean-query -f csv f.bean "<same>"
account/year,2024
Assets:A, 7.00

Four tails, one pivot

path sort pivot limit
execute_select (no FROM) ✓ ✓ ✓
execute_select_from_table ✓ — ✓
execute_aggregate_from_table ✓ — ✓
execute_select_from_subquery ✓ — ✓

Neither the parser nor apply_pivot was at fault — the parser populates pivot_by for the FROM form, and apply_pivot produces the right shape when reached. The step was simply absent from three tails.

Two fixed, one deliberately not

Both additions sit in the slot execute_select uses (after ORDER BY and the hidden-column strip, before LIMIT), and each is reachable and improves something different:

  • execute_aggregate_from_table — the reported case. The pivot applies and the rows match bean-query.
  • execute_select_from_table — cannot pivot, since PIVOT BY requires GROUP BY. But it now says so, with the same message the no-FROM path gives, instead of ignoring the clause. bean-query answers that input with a Python traceback, so an error beats both.

The subquery path is left alone. Our parser rejects FROM (SELECT ...) outright, so nothing can reach it carrying a pivot. A branch no test can exercise is worse than a documented gap — the table above lives in the test file for whoever adds the next pipeline step.

Controls

mutation result
remove the execute_select_from_table insertion the without-GROUP BY test fails
remove the execute_aggregate_from_table insertion the other two fail

Each insertion has a test only it satisfies. A third test pins that the FROM and no-FROM forms produce the same shape — the bug was precisely that they had drifted.

Left for #2217

Headers still differ: account against bean-query's account/year, and value columns reversed (sum(number) / 2024 against 2024/sum(number)). That is labeling on an otherwise-correct result, it changes the currently-working no-FROM path too, and it deserves its own review.

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

`PIVOT BY` was silently dropped by any query with a `FROM` clause. It
parsed, it validated, and then the un-pivoted result came back with no
error. Since `rledger query` is normally written with an explicit table,
that was the form users hit -- the CLI could not pivot at all.

Four execution paths run ORDER BY and LIMIT; only one ran PIVOT:

    execute_select (no FROM)        sort  PIVOT  limit
    execute_select_from_table       sort   --    limit
    execute_aggregate_from_table    sort   --    limit
    execute_select_from_subquery    sort   --    limit

Neither the parser nor `apply_pivot` was at fault: the parser populates
`pivot_by` for the FROM form, and `apply_pivot` produces the right shape
when it is reached. The step was simply absent from three tails.

Two of the three now have it, in the same slot `execute_select` uses --
after ORDER BY and the hidden-column strip, before LIMIT. Both are
reachable and each improves something different:

  * `execute_aggregate_from_table` is the reported case; the pivot now
    applies and the rows match bean-query.
  * `execute_select_from_table` cannot pivot, since PIVOT BY requires
    GROUP BY -- but it now SAYS so, with the same message the no-FROM
    path gives, instead of ignoring the clause. bean-query answers that
    input with a Python traceback, so an error beats both.

The subquery path is deliberately left alone. Our parser rejects
`FROM (SELECT ...)` outright, so nothing can reach it carrying a pivot,
and a branch no test can exercise is worse than a documented gap -- the
table above is in the test file for whoever adds the next pipeline step.

Each insertion has a test only it satisfies: removing the table-path one
fails the without-GROUP-BY test, removing the aggregate-path one fails
the other two.

Headers still differ from bean-query -- `account` against `account/year`,
and value columns reversed. That is how the output is labeled on a
result that is otherwise correct, it changes the currently-working
no-FROM path too, and it is filed as #2217 rather than folded in here.

Closes #2216
@robcohen
robcohen requested a review from a team as a code owner September 1, 2026 14:28
Copilot AI lite review requested due to automatic review settings September 1, 2026 14:28
@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.

🟢 Approval recommended

The changes address a confirmed silent-wrong-output bug and add targeted regression tests to prevent recurrence with minimal behavioral risk.

Pull request overview

Fixes a correctness gap in rustledger-query’s BQL execution pipeline where PIVOT BY was parsed/validated but not applied for queries that specify a table via FROM, restoring pivot functionality for the typical rledger query ... FROM #postings CLI usage.

Changes:

  • Apply PIVOT BY in the FROM <table> aggregate execution path so pivoted results are produced instead of silently returning the un-pivoted shape.
  • Apply PIVOT BY in the non-aggregate FROM <table> path so PIVOT BY without GROUP BY errors (matching the existing no-FROM behavior) instead of being ignored.
  • Add focused regression tests that (a) reproduce the reported case, (b) prevent drift between FROM and no-FROM execution shapes, and (c) pin the diagnostic for missing GROUP BY.
File summaries
File Description
crates/rustledger-query/src/executor/execution.rs Adds the missing apply_pivot step to the relevant FROM-clause execution tails in the same pipeline position used by the no-FROM path.
crates/rustledger-query/tests/pivot_with_from_test.rs Adds regression tests ensuring pivot shape parity between FROM and no-FROM, and ensuring PIVOT BY without GROUP BY is rejected for FROM queries.
Review details
  • Files reviewed: 2/2 changed files
  • Comments generated: 1
  • 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 51.9ms ± 3.7ms 663.0ms ± 3.8ms 12.8x 55.0 MB / 50.0 MB
investment 75.4ms ± 3.4ms 2427.3ms ± 49.0ms 32.2x 59.1 MB / 58.0 MB
fifo 72.7ms ± 4.1ms 13845.6ms ± 195.0ms 190.4x 61.2 MB / 57.8 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 51.5ms ± 3.9ms 51.9ms ± 3.7ms +0.9% ✅ within noise 55.0 MB → 55.0 MB (-0.1%)
investment 75.4ms ± 3.0ms 75.4ms ± 3.4ms -0.0% ✅ within noise 59.0 MB → 59.1 MB (+0.2%)
fifo 72.3ms ± 1.9ms 72.7ms ± 4.1ms +0.6% ✅ within noise 63.0 MB → 61.2 MB (-2.9%)

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

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

… one

Review feedback, and correct. I wrote one comment and pasted it into two
places, so `execute_aggregate_from_table` claimed the pivot runs "after
ORDER BY and the hidden-column strip". That path has no strip -- zero
mentions of `num_hidden` -- because `find_hidden_order_by_targets`
materializes nothing for an aggregate query: an ORDER BY target there
must already be in GROUP BY or be an aggregate, so it is projected
already.

Each comment now describes the path it is in, and each states the thing
a reader of that path needs:

  * the aggregate path says why there is no strip to sit after;
  * the table path says that reaching `apply_pivot` from there ALWAYS
    ends in `PivotWithoutGroupBy`, since the function returns early to
    the aggregate path whenever `group_by.is_some()`. Verified against
    that routing condition rather than assumed. Calling `apply_pivot`
    anyway, rather than raising the error inline, keeps one source of
    truth for the validation rules and their wording.
@robcohen

robcohen commented Sep 1, 2026

Copy link
Copy Markdown
Member Author

Correct, and fixed in the follow-up commit.

I wrote one comment and pasted it into both places, so execute_aggregate_from_table claimed the pivot runs "after ORDER BY and the hidden-column strip". That path has no strip — zero mentions of num_hidden — because find_hidden_order_by_targets materializes nothing for an aggregate query: an ORDER BY target there must already be in GROUP BY or be an aggregate, so it is projected already.

Each comment now describes the path it is in, and says the thing a reader of that path needs:

  • the aggregate path explains why there is no strip to sit after;
  • the table path records that reaching apply_pivot from there always ends in PivotWithoutGroupBy, since the function returns early to the aggregate path whenever group_by.is_some(). I checked that routing condition rather than assuming it.

On the second point: calling apply_pivot anyway, instead of raising the error inline, keeps one source of truth for the validation rules and their wording — the alternative would be a second copy of the message to drift.

Found probing the newly reachable path with inputs I had not tried. Two
ways of emptying the same query disagreed about its shape:

    WHERE  <no match> ... PIVOT BY   ->  account, year, sum(number)
    HAVING <no match> ... PIVOT BY   ->  account

bean-query reports the pivoted shape for both.

The aggregate path returned early when GROUP BY produced no groups,
skipping ORDER BY, PIVOT and LIMIT. Two of those are no-ops on zero
rows, which is presumably why the shortcut looked safe. PIVOT is not: it
reshapes the COLUMNS, so the early return was the difference between the
two spellings above.

The tail is now a named function both exits go through, which is a
stronger guarantee than remembering to duplicate three steps. Its doc
records why the empty case cannot skip it, and the no-strip note moved
there with it.

Verified the change does not simply drop columns from every empty
result: the same query WITHOUT a pivot still reports all three, and that
is asserted alongside. Restoring the early return fails the new test and
leaves the other three passing.
`execute_aggregate_from_table` states in a comment that a pure aggregate
over zero matching rows still yields one row -- COUNT(*) is 0, SUM is
NULL -- while a GROUP BY over zero rows yields none. Nothing pinned it.
Every other `count(*)` test runs on data that matches.

That mattered here: the branch is one arm of the if/else whose other arm
this PR rewrote, and the only thing that caught it still holding was a
hand comparison against `main`.

The first version of this test was worthless. It passed against BOTH
mutations of that branch -- removing the one-row rule, and extending it
to GROUP BY -- because the queries had no `FROM` clause and so ran
through `execute_select` instead. A test for a code path the query never
reaches.

With `FROM #postings` it fails against each mutation, and the reason is
recorded in the test so the next person does not drop the clause as
noise.

Also records that the one-row rule is a deliberate divergence:
bean-query returns NO row for `SELECT count(*)` over an empty filter.
@robcohen
robcohen merged commit c0efe66 into main Sep 1, 2026
57 of 60 checks passed
@robcohen
robcohen deleted the fix/pivot-with-from-clause branch September 1, 2026 17:21
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: PIVOT BY is silently ignored when the query has a FROM clause

2 participants