Skip to content

fix(query): a comparison with a NULL operand yields NULL - #2225

Merged
robcohen merged 2 commits into
mainfrom
fix/null-comparison-yields-null
Sep 1, 2026
Merged

robcohen merged 2 commits into
mainfrom
fix/null-comparison-yields-null

Conversation

@robcohen

@robcohen robcohen commented Sep 1, 2026

Copy link
Copy Markdown
Member

payee != '' answered FALSE on a payee-less posting where bean-query answers NULL. Closes #2213.

FALSE and NULL are not interchangeable downstream. COUNT(expr) skips NULLs but counts every FALSE, so count(payee != '') over payee-less rows answered 4 where it should answer 0. COUNT excluding NULLs was already correct and tested — it was the comparison feeding it that manufactured a non-NULL.

All six comparison operators shared one guard, so all six were wrong. The fix is that guard returning Value::Null.

Target semantics

Python's rule, which is what beanquery implements — not strict SQL three-valued logic. NOT (NULL) is TRUE there (Python's not None) where SQL would say NULL. That behavior stays and is now pinned by a test, so a later "make it proper 3VL" change meets the decision rather than assuming the current answer is an oversight.

Filtering is unaffected: to_bool(NULL) is false, so WHERE still drops the row. That is why this survived — filtering looked right, and only projecting or counting a comparison exposed it.

Verification

Against beanquery 0.2.0 / beancount 3.2.3, all seven expressions from the issue now agree:

expression bean-query before after
payee != '' (null) FALSE (null)
payee = '' (null) FALSE (null)
payee > 'a' (null) FALSE (null)
payee < 'a' (null) FALSE (null)
payee IS NULL TRUE TRUE TRUE
NOT (payee = '') TRUE TRUE TRUE
count(payee != '') 0 4 0

Also checked on a mixed ledger that ordinary comparisons are untouched ('Cafe' = 'Cafe' → TRUE, WHERE payee != '' → 2 rows), agreeing with bean-query on each.

BQL compat harness over 71 corpus files / 1349 runs: no regression against the pre-change baseline, no new stale masks, counts unchanged. The corpus barely exercises NULL comparisons, which is part of why this survived.

On the coverage gap

The full workspace suite (4686 tests) passed unchanged after the semantic fix, before any test was added — nothing covered this at all. Two of the five new tests fail against the old behavior; the other three deliberately pass both ways because they pin invariants that must not move (WHERE filtering, NOT coercion, and ordinary two-operand comparisons still being boolean). Without that third group, returning NULL unconditionally would satisfy the rest of the file.

Not addressed here: the issue's secondary note that SELECT count(*) ... WHERE <no matches> returns no row from bean-query where we return 0. That is an aggregate-over-empty-input difference, already recorded as a deliberate divergence in aggregate_count_null_test.rs.

`payee != ''` answered FALSE on a payee-less posting where bean-query
answers NULL. Closes #2213.

FALSE and NULL are not interchangeable downstream: `COUNT(expr)` skips
NULLs but counts every FALSE, so `count(payee != '')` over payee-less
rows answered 4 where it should answer 0. `COUNT` excluding NULLs was
already correct and tested -- it was the comparison feeding it that
manufactured a non-NULL.

All six comparison operators shared one guard, so all six were wrong,
and the fix is that guard returning `Value::Null`.

The target is Python's rule, which is what beanquery implements, not
strict SQL three-valued logic: `NOT (NULL)` is TRUE there (Python's
`not None`), where SQL would say NULL. That stays as it is and is now
pinned, so a later "make it proper 3VL" change meets the decision
instead of assuming the current answer is an oversight.

Filtering is unaffected: `to_bool(NULL)` is false, so `WHERE` still
drops the row. That is why the bug survived -- filtering looked right,
and only projecting or counting a comparison exposed it.

Verified against beanquery 0.2.0 / beancount 3.2.3: all seven
expressions in the issue now agree. The workspace suite passed
unchanged before these tests were added, which is the coverage gap that
let this land; two of the five new tests fail against the old behavior,
and the other three pin invariants that must NOT move (`WHERE`
filtering, `NOT` coercion, and ordinary two-operand comparisons still
being boolean).
@robcohen
robcohen requested a review from a team as a code owner September 1, 2026 19:58
Copilot AI lite review requested due to automatic review settings September 1, 2026 19:58

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 semantic change is small, targeted, and backed by focused regression tests that cover both the bug and the key invariants that must not change.

Pull request overview

Fixes BQL comparison semantics in rustledger-query so that =, !=, <, <=, >, >= with a NULL operand yield NULL (matching beanquery / Python-beancount behavior), preventing downstream aggregates like COUNT(expr) from incorrectly counting FALSE values.

Changes:

  • Updated the executor’s comparison short-circuit so NULL comparisons return Value::Null instead of Value::Boolean(false).
  • Added regression tests covering all six comparison operators, COUNT behavior over NULL comparisons, WHERE filtering behavior, and NOT (NULL) coercion behavior.
File summaries
File Description
crates/rustledger-query/src/executor/operators.rs Changes comparison short-circuit to return NULL when either operand is NULL for the six core comparison operators.
crates/rustledger-query/tests/null_comparison_test.rs Adds regression tests to pin NULL-comparison semantics and the downstream effects on COUNT, WHERE, and NOT.
Review details

Suppressed comments (1)

crates/rustledger-query/src/executor/operators.rs:265

  • This block comment states “A comparison with a NULL operand is NULL”, but the guard only applies when is_comparison(op) is true (the six equality/ordering operators). Tightening the wording prevents readers from assuming IN/NOT IN/regex operators also return NULL on NULL operands.
        // A comparison with a NULL operand is NULL, not FALSE (#2213). The two
        // are not interchangeable: `COUNT` skips NULLs but counts every FALSE,
        // so `count(payee != '')` over payee-less rows answered 4 where it
        // should answer 0. Filtering is unaffected -- `to_bool(NULL)` is false,
        // so `WHERE` still drops the row.
  • 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.

@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

🔴 Slower than base on: simple

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 51.9ms ± 6.4ms 764.2ms ± 23.4ms 14.7x 55.0 MB / 50.2 MB
investment 69.7ms ± 3.2ms 2806.5ms ± 11.7ms 40.2x 59.0 MB / 58.0 MB
fifo 67.7ms ± 4.0ms 15795.7ms ± 85.3ms 233.3x 61.0 MB / 58.0 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 45.9ms ± 1.4ms 51.9ms ± 6.4ms +12.9% 🔴 regression 55.2 MB → 55.0 MB (-0.4%)
investment 69.7ms ± 3.8ms 69.7ms ± 3.2ms +0.0% ✅ within noise 59.0 MB → 59.0 MB (+0.0%)
fifo 66.6ms ± 0.8ms 67.7ms ± 4.0ms +1.7% ✅ within noise 60.9 MB → 61.0 MB (+0.1%)

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

Extends the previous commit. Review asked whether the NULL rule really
covered every comparison, since `~`, `!~`, `IN` and `NOT IN` were left
out of the guard. Checking against beanquery 0.2.0 rather than assuming:
on a payee-less posting bean-query answers NULL for all four, where we
answered FALSE, TRUE, FALSE, TRUE.

Both regex arms carried a comment stating the old answer "matches Python
beancount behavior". It does not, and the oracle says so directly. Those
arms are now unreachable and the claim is gone.

An empty collection is NOT null and must keep its boolean answer:
`'food' IN tags` on an untagged posting is FALSE, agreeing with
bean-query, because `tags` there is an empty SET rather than a missing
value. Pinned by `membership_in_an_empty_set_is_false_not_null` -- the
mistake would look like a fix, since an untagged posting reads as
"missing", and it would break a common query shape.

`is_comparison` is renamed `propagates_null`, which is what the
predicate now decides; it documents why `IS NULL`, `AND` and `OR` stay
out.
@robcohen

robcohen commented Sep 1, 2026

Copy link
Copy Markdown
Member Author

Good catch, and it was more than a wording problem — the fix was incomplete.

The comment was imprecise because the guard covered only the six equality/ordering operators. Rather than just narrow the wording, I checked what ~, !~, IN and NOT IN actually do against beanquery 0.2.0 on a payee-less posting:

expression bean-query before after
payee ~ 'x' (null) FALSE (null)
payee !~ 'x' (null) TRUE (null)
payee IN ('a') (null) FALSE (null)
payee NOT IN ('a') (null) TRUE (null)

All four were the same #2213 bug. Both regex arms carried a comment asserting the old answer "matches Python beancount behavior" — it does not, and the oracle says so directly. Those arms are now unreachable and the false claim is gone.

is_comparison is renamed propagates_null, which is what it now decides, and it documents why IS NULL/IS NOT NULL (null tests) and AND/OR (coercing, like NOT) stay out.

The risk this opened. An untagged posting reads as "missing", so it would be easy to propagate NULL from tags as well — and that would look like a fix while breaking 'food' IN tags, a common query shape. It is an empty set, not NULL (tags IS NULL is FALSE in both tools), so the guard doesn't fire and the answer stays FALSE, matching bean-query. membership_in_an_empty_set_is_false_not_null pins it, and mutating the guard to treat an empty set as NULL makes it fail.

Re-verified: 4688 workspace tests green, clippy clean on 1.97.0, and the BQL compat harness over 71 files / 1349 runs shows no regression against baseline.

@robcohen
robcohen merged commit 8ff8a1c into main Sep 1, 2026
57 of 60 checks passed
@robcohen
robcohen deleted the fix/null-comparison-yields-null branch September 1, 2026 20:58
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: comparing NULL yields FALSE instead of NULL, so count() over a comparison is wrong

2 participants