Skip to content

fix(query): MIN and MAX order booleans, false before true - #2212

Merged
robcohen merged 2 commits into
mainfrom
fix/bql-boolean-minmax
Sep 1, 2026
Merged

robcohen merged 2 commits into
mainfrom
fix/bql-boolean-minmax

Conversation

@robcohen

@robcohen robcohen commented Sep 1, 2026

Copy link
Copy Markdown
Member

Closes #2183.

$ rledger query f.bean "SELECT max(number > 0) FROM #postings"
error: type error: cannot compare values        # before

$ bean-query -f csv f.bean "SELECT max(number > 0) FROM #postings"
TRUE

Python orders False < True and its max/min inherit that, so MAX over booleans is any and MIN is all. bean-query gets it for free; we had to define the order.

The boundary is the interesting part

The order is defined for the aggregate path only, and that is measured, not assumed. bean-query refuses the operators on the very same values:

$ bean-query f.bean "SELECT (number > 0) < (number > 5) FROM #postings"
CompilationError: operator "less(bool, bool)" not supported

So compare_values — which backs < and > — keeps rejecting booleans. Defining the order there would accept a query bean-query rejects at compile time, a divergence in the opposite direction from the one being fixed.

That split is expressible only because value_less_than is reached from nowhere but MIN/MAX; I checked its call sites before touching it.

Verification

End to end against beanquery 0.2.0 / beancount 3.2.3, through the real bean-query CLI:

SELECT MAX(number > 0), MIN(number > 0)
  bean-query:  TRUE,FALSE
  rustledger:  TRUE,FALSE

Byte for byte. That query joins tests/compatibility/bql-queries.toml, whose header asks for an entry whenever an aggregation function changes.

Worth noting: my first comparison used beanquery's Python API plus csv.writer, which printed True/False and looked like a mismatch. That bypasses bean-query's own renderer — the CLI prints TRUE/FALSE, matching #2182. The oracle has to be the CLI when output format is what's under test.

Controls

mutation result
remove the boolean arm from value_less_than fails
also add it to compare_values fails

The second is the one worth having: it stops the order being extended to the operators later as an obvious tidy-up.

Numbers still aggregate unchanged (max(number) → 10, min(number) → -10), so the new arm shadows nothing.

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

`SELECT max(number > 0)` was a type error. bean-query answers TRUE,
because Python orders `False < True` and its `max`/`min` inherit that,
so MAX over booleans is `any` and MIN is `all`.

The order is defined for the aggregate path ONLY, and that boundary is
measured rather than assumed. bean-query refuses the operators on the
same values:

    SELECT (number > 0) < (number > 5) FROM #postings
    -> CompilationError: operator "less(bool, bool)" not supported

so `compare_values`, which backs `<` and `>`, keeps rejecting them.
Defining the order there would accept a query bean-query rejects at
compile time -- a divergence in the opposite direction from the one
being fixed. `value_less_than` is reached only by MIN/MAX, which is what
makes the split expressible at all.

Checked end to end against beanquery 0.2.0: `SELECT MAX(number > 0),
MIN(number > 0)` emits `TRUE,FALSE` from both tools, byte for byte. That
query joins the BQL compat corpus, which asks for one whenever an
aggregation function changes.

Three tests, each verified to fail on its own mutation: removing the
boolean arm, and adding it to `compare_values` as well. The second is
the one worth having -- it stops the order being extended to the
operators later as an obvious tidy-up.

Closes #2183
Copilot AI lite review requested due to automatic review settings September 1, 2026 03:17
@robcohen
robcohen requested a review from a team as a code owner September 1, 2026 03:17

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 change is narrowly scoped to the MIN/MAX aggregate path, includes regression tests preventing accidental operator behavior changes, and updates the compatibility corpus to lock in the expected behavior.

Pull request overview

This PR fixes BQL MIN/MAX aggregation over boolean expressions by defining an ordering of booleans as false < true only in the aggregate comparison path, matching bean-query / Python behavior while keeping boolean comparisons via </> rejected.

Changes:

  • Extend the aggregate-only comparison helper (value_less_than) to order Value::Boolean(false) < Value::Boolean(true).
  • Add a focused regression test ensuring MIN/MAX over booleans works while < on booleans still errors.
  • Add an end-to-end compatibility corpus query covering MAX(number > 0), MIN(number > 0).
File summaries
File Description
tests/compatibility/bql-queries.toml Adds a compat corpus query to lock in correct boolean MIN/MAX behavior.
crates/rustledger-query/tests/boolean_minmax_test.rs New regression tests for boolean aggregate ordering and operator rejection.
crates/rustledger-query/src/executor/operators.rs Implements boolean ordering in value_less_than (aggregate-only), leaving compare_values unchanged.
Review details
  • Files reviewed: 3/3 changed files
  • Comments generated: 0
  • Review effort level: Lite

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

@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!

@github-actions

github-actions Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 47.3ms ± 3.7ms 764.4ms ± 7.7ms 16.2x 54.9 MB / 50.1 MB
investment 74.3ms ± 5.0ms 2886.4ms ± 68.4ms 38.8x 59.1 MB / 58.0 MB
fifo 70.4ms ± 3.8ms 17003.3ms ± 145.6ms 241.6x 61.2 MB / 57.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 46.5ms ± 2.2ms 47.3ms ± 3.7ms +1.7% ✅ within noise 55.0 MB → 54.9 MB (-0.2%)
investment 74.2ms ± 5.6ms 74.3ms ± 5.0ms +0.2% ✅ within noise 59.1 MB → 59.1 MB (-0.1%)
fifo 71.2ms ± 3.9ms 70.4ms ± 3.8ms -1.1% ✅ within noise 61.0 MB → 61.2 MB (+0.3%)

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

Review notes on this PR.

Verified the claim I made about scope. All four value_less_than call sites are MIN/MAX — lines 476 and 938 inside "MIN", 502 and 965 inside "MAX" (the grouped and ungrouped paths). Nothing else reaches it, so confining the boolean order to the aggregates is structurally sound rather than a convention.

NULLs are handled before the comparison. Both aggregates skip Value::Null (if matches!(val, Value::Null) { continue; }), so the new arm never sees one.

GROUP BY agrees: SELECT max(number > 0) GROUP BY account gives TRUE,TRUE from both tools.

Two things this turned up that are not in scope here:

  1. ORDER BY number > 0 still fails — that is BQL: ORDER BY on an expression target fails; the header and the lookup spell it differently #2177, the next issue in this cluster, and it reproduces identically on main.

  2. max(payee != '') returns FALSE here and null in bean-query. The divergence is in the comparison, not the aggregate: payee != '' already yields FALSE per row on main, before this PR. All four comparison operators return FALSE where bean-query returns NULL, and it changes an answer — count(payee != '') is 0 there and 4 here. Filed as BQL: comparing NULL yields FALSE instead of NULL, so count() over a comparison is wrong #2213.

Worth stating plainly: this PR makes that pre-existing divergence visible where it previously hit type error: cannot compare values. Trading an error for a wrong value is not obviously an improvement in isolation — but the error was also wrong, since the query is valid and bean-query answers it, and #2213 fixes the actual cause rather than hiding it behind a type error.

Reviewing this PR I went to mutate the boolean arm and my anchor matched
twice: `compare_values_for_sort` already ordered booleans on main. There
are three comparison functions in this file with three different
policies, and nothing said so.

They are not drift. They are bean-query's shape: it answers
`max(number > 0)`, it sorts a boolean column, and it refuses
`(number > 0) < (number > 5)` with `operator "less(bool, bool)" not
supported`. Collapsing them would either accept a query it rejects or
reject two it answers.

The table is in the doc comment now, along with the reason the sort path
is total where the other two are fallible: sorting cannot fail partway
through a result set, so it orders NULL rather than erroring on it.

Also verified the corpus entry is real coverage rather than decoration.
Run against the file list the harness wants, `minmax-over-boolean`
executes and reports `match: True`; reverse the boolean order and the
same run reports `match: False`. The first attempt at that control was
the anchor collision above, so it silently mutated nothing and reported
a match either way.
@robcohen

robcohen commented Sep 1, 2026

Copy link
Copy Markdown
Member Author

Checked the sibling aggregates, since MIN/MAX cannot be the only ones that meet a boolean.

aggregate bean-query rustledger
count(number > 0) 4 4
first / last TRUE TRUE
max / min TRUE / FALSE TRUE / FALSE (this PR)
avg(number > 0) CompilationError: no function matches "avg(bool)" type error — agrees
sum(number > 0) 2, printed as TRUE type error

avg needs nothing: it agrees by refusing. sum is the only gap, and bean-query's own behaviour there is broken — the API returns the integer 2 while the CLI prints TRUE, because the result column is typed from the argument. "Match bean-query" is ambiguous when its value and its output disagree, so I filed it as #2214 rather than widening this PR to guess.

That also settles the scope question for this PR: MIN and MAX were the only two aggregates where bean-query orders booleans and we errored.

One more note for whoever picks up #2177: ORDER BY needs no ordering work. compare_values_for_sort already handles booleans and is total — that is the third path in the table now documented on value_less_than. #2177 is purely the name-lookup mismatch it describes.

@robcohen
robcohen merged commit 47ac5a1 into main Sep 1, 2026
57 of 60 checks passed
@robcohen
robcohen deleted the fix/bql-boolean-minmax branch September 1, 2026 05:16
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: max()/min() over a boolean raise a type error; bean-query orders False < True

2 participants