Skip to content

feat(query): SUM over a boolean counts the matching rows - #2227

Merged
robcohen merged 1 commit into
mainfrom
fix/sum-over-booleans
Sep 1, 2026
Merged

robcohen merged 1 commit into
mainfrom
fix/sum-over-booleans

Conversation

@robcohen

@robcohen robcohen commented Sep 1, 2026

Copy link
Copy Markdown
Member

sum(number > 0) was a type error; it now answers 2 on a ledger with two positive postings. Closes #2214.

The value, not the rendering

Python sums booleans as integers, so bean-query computes the same number. What its CLI prints is TRUE — the result column is typed from the argument, so the integer goes through the boolean formatter. Through its API the number is visible:

conn.execute("SELECT sum(number > 0) FROM #postings").fetchall()   # [(2,)]

So "match bean-query" is ambiguous here, and this takes the value:

bean-query (API) bean-query (CLI) before after
sum(number > 0) 2 TRUE type error 2
grouped by account [('Assets:Cash', 0), ('Expenses:Food', 2)] — type error same
count(number > 0) 4 4 4 4
avg(number > 0) CompilationError — type error type error

Reproducing TRUE would mean reproducing a display bug, and 2 is what a user asking "how many postings are positive" means. Recorded as a deliberate output divergence in docs/reference/compatibility.md, along with a section on #2213's NULL comparisons — that one is agreement, but it's easy to assume otherwise since WHERE filtering is unaffected.

Implementation notes

An all-boolean sum returns an Integer, since it is a count and COUNT answers with one. has_booleans is tracked separately from has_numbers deliberately: widening the numeric arm instead would have folded booleans into the Decimal total, and a mixed sum passing through zero would then render 0 where bean-query renders 0.00. summing_numbers_is_unchanged pins that.

AVG over a boolean still refuses, which is what bean-query does. Agreeing by rejecting is still agreeing, and the test pins that widening SUM did not widen AVG.

On the duplicated accumulator

SUM is implemented twice, and the split is not grouped-vs-ungrouped as it appears: one copy serves queries written without FROM, the other serves every FROM #postings form, grouped or not.

I found this the hard way. The first version of the test file tested the same copy twice while its docstring claimed to cover both — a removal experiment failed both tests instead of one, which is what exposed it. I marked one copy with a sentinel and re-ran the queries to establish the real split. Now, removing either copy's boolean arm fails exactly the tests that name it: site 1 → sum_without_a_from_clause_counts_booleans, site 2 → the other two.

Verification

4693 workspace tests green, clippy clean on 1.97.0, BQL compat harness over 71 files / 1349 runs shows no regression against baseline.

`sum(number > 0)` was a type error; it now answers 2 on a ledger with
two positive postings. Closes #2214.

Python sums booleans as integers, so bean-query computes the same
number. What it PRINTS is `TRUE`: its result column is typed from the
argument, so the integer goes through the boolean formatter. Its API
returns `[(2,)]`.

We match the value, not the rendering. Reproducing `TRUE` would mean
reproducing a display bug, and `2` is what a user asking "how many
postings are positive" means. The outputs therefore differ on purpose,
recorded in `docs/reference/compatibility.md`.

An all-boolean sum returns an Integer rather than a Decimal, since it is
a count and `COUNT` answers with one. `has_booleans` is tracked apart
from `has_numbers` so a mixed sum still comes back as a Number and the
Python scale semantics are untouched -- widening the numeric arm instead
would have made a total passing through zero render `0` where
bean-query renders `0.00`.

`AVG` over a boolean still refuses, which is also what bean-query does
(`no function matches "avg(bool)"`). Agreeing by rejecting is still
agreeing, and the test pins that widening SUM did not widen AVG.

The accumulator is duplicated, and the split is not grouped-vs-ungrouped
as it looks: one copy serves queries written without `FROM`, the other
serves every `FROM #postings` form. Established by marking one copy and
seeing which queries moved -- the first version of the test file
exercised the same copy twice while claiming to cover both. Removing
either copy's arm now fails exactly the tests that name it.
@robcohen
robcohen requested a review from a team as a code owner September 1, 2026 21:19
Copilot AI lite review requested due to automatic review settings September 1, 2026 21:19
@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.

🔵 Needs a closer look

The SUM type error message is now misleading because it does not mention booleans even though booleans are accepted.

Pull request overview

Adds BQL support for SUM over boolean expressions by treating booleans as integer counts (matching bean-query’s computed value rather than its CLI rendering), and records the intentional output divergence in the compatibility reference.

Changes:

  • Extend SUM aggregation to accept Value::Boolean and return an Integer for all-boolean sums.
  • Add regression tests covering boolean sums (grouped, ungrouped, and no-FROM accumulator path) and guarding that numeric scale semantics remain unchanged.
  • Document the bean-query rendering mismatch and the deliberate choice to print the computed integer value.
File summaries
File Description
docs/reference/compatibility.md Documents the deliberate output divergence for SUM(bool) and records related NULL-comparison compatibility notes.
crates/rustledger-query/tests/sum_over_booleans_test.rs Adds regression tests covering boolean SUM behavior across both accumulator implementations and guards numeric scale behavior.
crates/rustledger-query/src/executor/aggregation.rs Implements boolean handling in SUM across both aggregation paths and returns an integer for all-boolean totals.
Review details

Suppressed comments (2)

crates/rustledger-query/src/executor/aggregation.rs:369

  • SUM now accepts booleans, but the type error message still says it "requires numeric or position" values, which is misleading when users pass a boolean expression.

This issue also appears on line 910 of the same file.

                                _ => {
                                    return Err(QueryError::Type(
                                        "SUM requires numeric or position value".to_string(),
                                    ));

crates/rustledger-query/src/executor/aggregation.rs:913

  • This SUM path also now accepts booleans, but the type error message still claims SUM only accepts numeric or position values.
                                _ => {
                                    return Err(QueryError::Type(
                                        "SUM requires numeric or position value".to_string(),
                                    ));
  • 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.

@github-actions

github-actions Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

🔴 Slower than base on: simple

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 51.2ms ± 5.8ms 822.0ms ± 0.7ms 16.1x 55.0 MB / 50.1 MB
investment 75.0ms ± 6.0ms 3048.7ms ± 41.8ms 40.6x 59.1 MB / 58.1 MB
fifo 69.4ms ± 5.1ms 15558.6ms ± 174.4ms 224.3x 61.1 MB / 57.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 47.9ms ± 3.1ms 51.2ms ± 5.8ms +6.9% 🟡 slower 55.0 MB → 55.0 MB (-0.1%)
investment 71.5ms ± 4.9ms 75.0ms ± 6.0ms +5.0% ✅ within noise 59.0 MB → 59.1 MB (+0.2%)
fifo 66.6ms ± 2.4ms 69.4ms ± 5.1ms +4.1% ✅ within noise 61.1 MB → 61.1 MB (-0.1%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 2.9ms, investment 3.5ms, 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 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 merged commit b5e34fa into main Sep 1, 2026
59 of 62 checks passed
@robcohen
robcohen deleted the fix/sum-over-booleans branch September 1, 2026 21:45
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: SUM over a boolean errors here; bean-query computes 2 but prints TRUE

2 participants