Skip to content

fix(query): NULL in NULL out for BQL functions, NULL number/currency of an empty inventory, NULL #entries tags, and str() of positions - #2867

Merged
robcohen merged 4 commits into
mainfrom
fix/bql-null-and-value-semantics
Nov 5, 2026
Merged

robcohen merged 4 commits into
mainfrom
fix/bql-null-and-value-semantics

Conversation

@robcohen

@robcohen robcohen commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

What

Three BQL value-semantics fixes reported against @rustledger/wasm 0.24.0, each checked against beanquery 0.2.0 / beancount 3.2.3 (the rustledger-compat container).

#2820, NULL in, NULL out. bean-query's @function wrapper returns None as soon as any argument is None (beanquery/query_env.py). A single guard at the top of evaluate_function_on_values (is_null_in_null_out) now does the same for the functions that raised a type error on NULL. Both evaluation paths go through it:

  • substr/substring, maxwidth, date, parse_date
  • weekday, ymonth, date_add, date_diff, date_part, date_trunc, date_bin, interval
  • splitcomp, round, root, grepn, possign (already NULL-safe, now through the guard), startswith, endswith, account_depth
  • two-argument getitem/get, and one-argument joinstr (it gave an empty string)

Also: meta / entry_meta / any_meta of a NULL key are NULL (the lazy-path arm was a type error), and three-argument getitem with a NULL key gives its default, as bean-query does.

The list was found by probing every function with NULL argument combinations. Only valid arities are listed, so substr(payee) is still an arity error. Deliberately kept, where bean-query gives NULL: convert and value refuse a NULL target currency (#902); convert(NULL, 'USD') is 0 USD (#586); and a NULL date in convert or getprice means the latest price. The guard's rustdoc, the CONVERT date arm, docs/reference/bql.md and the CHANGELOG all list these.

#2821, number() / currency() of an inventory that holds nothing. Both now read only the held (non-empty) positions, the same set Inventory::is_empty counts. An empty inventory, or one whose only position is the zero a balance back at zero keeps, is NULL, as get and only read it. Before, they gave 0 and USD.

#2822, #entries tags/links and str().

  • #entries tags and links are NULL for an entry kind that has none, i.e. anything but a transaction, note or document. This matches bean-query's getattr(entry, 'tags', None). Before, they were empty sets.
    Embedders see this too: JSON CLI output, the WASM CellValue and the FFI QueryValue give null where they gave [], and the FFI column datatype, inferred from the first non-NULL cell, can read null instead of set for a tags/links column. The CHANGELOG says so.
  • str() of a position or inventory is Python's str(), as bean-query prints it. The renderer is the one the C conversions narration already used, moved out of OrderedBalance::render into the shared python_inventory_str / python_position_str, so the two cannot drift.
  • str() of a set, metadata, an entry or an interval renders as its cell does (sort.rs::value_to_string). It no longer errors.

bean-query comparison, per row

Query bean-query main this PR
SELECT substr(payee, 0, 2) (NULL payee) blank type error: SUBSTR ... NULL
SELECT maxwidth(payee, 5) blank type error NULL
SELECT subst('a', 'b', payee) blank NULL NULL (already fixed on main)
SELECT date(payee) blank type error NULL
SELECT weekday(close_date(account)) blank type error NULL
startswith(NULL, ...) (rledger-only) n/a type error NULL
WHERE payee IS NOT NULL AND substr(payee, 0, 2) = 'Ac' 2 rows 2 rows (already fixed on main: AND short-circuits) 2 rows
date_add / date_diff / date_part / date_trunc of a NULL date, date_trunc(payee, date), interval(payee), getitem(meta, payee) blank type error NULL
number(balance) / currency(balance) on a balance back at zero (rledger-only overloads) n/a 0, USD NULL, NULL
SELECT count(*) FROM #entries WHERE tags IS NULL 2 0 2
SELECT tags IS NULL, links IS NULL FROM #entries LIMIT 1 TRUE, TRUE FALSE, FALSE TRUE, TRUE
SELECT length(tags) FROM #entries LIMIT 1 blank 0 NULL
SELECT str(tags) FROM #entries LIMIT 1 (an open) blank type error NULL
meta(payee) on a NULL payee blank type error NULL
getitem(meta, payee, 'd') d type error d
joinstr(tags) on an open (#entries) blank '' NULL
SELECT str(position) 10 USD type error 10 USD
SELECT str(balance) (10 USD), () type error (10 USD), ()
str() of a lot 2 HOOL {100 USD, 2024-01-05, "lot"} type error same
str(entry), str(meta), str(tags) of a transaction Python repr (Transaction(...), {'filename': ...}, frozenset({'t1'})) type error rledger's cell text ({date: ..., ...}, {filename: ..., lineno: 4}, t1), deliberate deviation

Deliberate deviations:

  • str() of a set, metadata or entry does not copy Python's repr. A repr names Python types (frozenset, datetime.date), not ledger values. The inline comment in value_to_str, docs/reference/bql.md and the CHANGELOG say so, and test_entries_tags_and_links_are_null_where_the_directive_has_none pins str(tags) = t1, and test_str_of_meta_and_entry_is_the_cell_text pins the exact str(meta) and str(entry) text. No compat-suite query uses str(), number(inventory) or #entries tags, so nothing goes in KNOWN_RUST_DIVERGENCES.
  • convert(x, NULL) still raises the [Bug]: Some queries are broken #902 diagnostic, and so does value(x, NULL) for any NULL second argument (a currency or a date, e.g. value(position, close_date(account))), where bean-query gives NULL. This PR does not change either.

Remaining differences, pre-existing, not in scope:

  • str() of a running balance whose currency went through zero keeps the summed scale (-200.00 USD where Python, which drops the zero position, prints -200 USD). This is the Inventory::add scale note already in the NUMBER arm.
  • round(number(only(payee, balance))) is NULL where bean-query gives 0.
  • str() of an inventory orders two positions that tie on beancount's sortkey by the inventory's own order. When one of them went through zero, Python drops the emptied key and re-appends it, and the core inventory keeps it in place: +5 ZWL, +5 XYZ, -5 ZWL, +5 ZWL gives bean-query (5 XYZ, 5 ZWL) and this PR (5 ZWL, 5 XYZ). The root is the core inventory, like the -200.00 item.

Review round 2

Merged origin/main (#2862, #2864, #2869); the CHANGELOG conflict kept both sides. This PR bumps no parse-cache version.

  1. A NULL getitem container wins over the default. The (_, Null) if len == 3 arm came before (Null, _), so getitem(currency_meta(payee), payee, 'd') on a NULL-payee row and getitem(NULL, NULL, 'd') gave 'd'. bean-query's GetItem3 returns None for a None container; it prints a blank for the first query on every row (checked against beanquery 0.2.0). The NULL-container arm is now first. test_getitem_null_container_wins_over_the_default pins both. bean-query refuses the literal getitem(NULL, NULL, 'd') at compile time (getitem(nonetype, nonetype, str)); here it is NULL, as main gave it. bql.md and the CHANGELOG now say the default applies for a non-NULL container.
  2. value and a NULL second argument. bql.md and the CHANGELOG said value refuses a NULL target currency; it refuses any NULL second argument, a date too (VALUE: second argument evaluated to NULL). Reworded; behavior unchanged.
  3. JOURNAL ... AT str now runs, as in bean-query. check_at_function accepts str for JOURNAL, whose cells are shown without being summed. bean-query 0.2.0 output on the test ledger, matched cell for cell by test_journal_at_str_shows_the_position_and_balance_as_text:
    2024-01-02  *  buy   Assets:Stock  4 VHT {100 USD, 2024-01-02}   (4 VHT {100 USD, 2024-01-02})
    2024-01-05  *  sell  Assets:Stock  -1 VHT {100 USD, 2024-01-02}  (3 VHT {100 USD, 2024-01-02})
    
    Only str is taken: currency(position) also answers text here, but bean-query refuses AT currency (and AT upper), so a text result alone does not qualify. BALANCES AT str is still refused, as bean-query refuses it, but now with bean-query's reason, no function matches "sum(str)", instead of the false str(position) (test_balances_at_str_refuses_summing_text). The BQL: BALANCES / JOURNAL ... AT value ignore the clause and return units #2826 CHANGELOG entry no longer lists JOURNAL ... AT str as a remaining difference. The JOURNAL column headers stay position / balance, as they are for every AT, where bean-query writes str(position) / str(balance).

How to test

cargo test -p rustledger-query --test bql_null_and_str_test
cargo test -p rustledger-query -p rustledger --all-features

The new bql_null_and_str_test.rs has 9 tests. On main, 6 of the first 8 fail (the 9th, the NULL-container getitem case, passes on main and pins the round-2 fix). The two that pass on main pin the WHERE guard (already fixed) and the wrong-arity error. A main-vs-branch run of all 68 docs/ queries on example.beancount shows no difference.

Closes #2820
Closes #2821
Closes #2822

🤖 Generated with Claude Code

…ncy for an empty inventory, NULL #entries tags where none, and str() of positions

bean-query returns NULL from a function as soon as any argument is NULL;
substr, maxwidth, date, weekday, startswith and others raised a type
error instead, so one NULL payee failed the query. number() and
currency() of an inventory holding nothing are NULL, as get/only read
it. #entries tags/links are NULL on entries that have none, as
getattr(entry, "tags", None). str() renders a position or inventory as
Python does, through the renderer the conversions narration uses, and
sets, metadata and entries as their cells.

Closes #2820
Closes #2821
Closes #2822

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner November 5, 2026 06:01
robcohen and others added 3 commits November 5, 2026 02:06
… fix the bql.md rows

Review follow-up. meta, entry_meta and any_meta of a NULL key are NULL,
one-argument joinstr of NULL is NULL, and three-argument getitem with a
NULL key gives its default, as in bean-query. The number/currency rows
land in the function table instead of above the front matter, and the
NULL paragraph lists the deliberate convert/value/getprice exceptions.
The CHANGELOG notes the tags/links change for JSON, WASM and FFI.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…T str runs

getitem(NULL-container, NULL, default) answered the default because the
NULL-key arm came first. bean-query GetItem3 returns None for a None
container, so a NULL container now gives NULL whatever the key.

JOURNAL ... AT str now prints str(position) and str(balance) as
bean-query does. BALANCES AT str is still refused, now with bean-query
reason, no function matches "sum(str)", instead of naming str(position),
which str() takes since this PR.

Docs and CHANGELOG: the getitem default applies for a non-NULL container,
and value refuses any NULL second argument (currency or date).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@codecov

codecov Bot commented Nov 5, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.86364% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-query/src/executor/mod.rs 96.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 52.0ms ± 3.1ms 859.5ms ± 4.5ms 16.5x 34.8 MB / 51.0 MB
investment 80.8ms ± 1.1ms 3128.5ms ± 21.8ms 38.7x 44.8 MB / 59.2 MB
fifo 76.4ms ± 1.0ms 15859.2ms ± 523.9ms 207.7x 41.0 MB / 58.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 52.0ms ± 0.9ms 52.0ms ± 3.1ms -0.0% ✅ within noise 34.9 MB → 34.8 MB (-0.3%)
investment 79.2ms ± 0.7ms 80.8ms ± 1.1ms +2.0% ✅ within noise 44.9 MB → 44.8 MB (-0.2%)
fifo 75.9ms ± 1.0ms 76.4ms ± 1.0ms +0.6% ✅ within noise 40.8 MB → 41.0 MB (+0.7%)

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

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 179 masked)
Full AST Match 100%
Total Files 826
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 e3e082a into main Nov 5, 2026
59 of 60 checks passed
@robcohen
robcohen deleted the fix/bql-null-and-value-semantics branch November 5, 2026 11:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant