Skip to content

fix(query): cost(position) reads the posting's booked cost - #2428

Merged
robcohen merged 7 commits into
mainfrom
fix/bql-cost-exact-total-2425
Sep 26, 2026
Merged

robcohen merged 7 commits into
mainfrom
fix/bql-cost-exact-total-2425

Conversation

@robcohen

@robcohen robcohen commented Sep 25, 2026 •

Copy link
Copy Markdown
Member

The rest of #2425. #2427 made lots keep their exact totals; this makes BQL's cost() agree with them.

Problem

cost(position) read a Value::Position, which holds only the resolved per-unit cost. A lot bought as 3 X {{500 USD}} has a per-unit cost of 500/3, rounded, so:

this PR main
cost(position) of the buy 500 500.00000000000000000000000001
cost(position) of a sale that takes 1 of those 3 -166.6666666666666666666666667 -166.66666666666666666666666667
weight of either same as cost(position) 500 / -166.66…67
sum(cost(position)) of an AVERAGE pool (1 at 100 and 2 at 200) sold whole 0 -0 USD (-1E-26)

Fix

  • COST(position) over the position column now takes the posting's booked cost through the canonical rustledger_booking::cost_number_weight. It's the same route WEIGHT(position) has taken since WEIGHT() ignores the price annotation, returning units in the wrong currency #1966, via is_position_column.

    • It's exact for a total-carrying cost (PerUnitFromTotal: a {{T}} buy, or the sale that empties such a lot).
    • It's identical to before for every per-unit cost (units × per-unit).
    • A posting without a booked number and currency falls back to the value path, as before.
  • The posting table's cost column did the same multiplication, with an unchecked * that panicked on overflow. It uses the same rule now, unsigned as before.

  • BALANCES AT COST (Inventory::at_cost) now reads a lot's exact total where the inventory keeps one. The balances come from the booking engine's replay, which keeps those totals, so a held {{500 USD}} lot shows 500 there, not 500.00…01.

  • JOURNAL … AT COST:

  • Still per-unit (the same limit WEIGHT accepts, documented in docs/reference/bql.md):

  • Scale of the raw value. cost(position), the cost column and JOURNAL … AT cost now carry the booked total's scale, the weight column's, instead of the re-multiplied product's:

    • {{300.00 USD}} gives 300.00, where it gave 300.00000000000000000000000000.
    • 2 HOOL {150 # 5 USD} gives 305, where 152.50 × 2 gave 305.00.

    Text output rounds for display and is unchanged. JSON and embedders see the new scale. Across the compat corpus's 29 total- and compound-cost ledgers, all 551 (file, query) pairs keep their bean-query status and the rendered text is byte-identical, while the raw JSON differs on 19 pairs.

  • A deliberate divergence from bean-query, which gives the rounded product. It's recorded in bql.md and the CHANGELOG.

Tests

  • crates/rustledger-query/tests/cost_function_matches_weight.rs books a ledger the way the loader does, then checks every cost-bearing posting: a {{T}} lot sold whole, a {{T}} lot sold down, a per-unit lot and an AVERAGE pool.
    • cost(position) equals weight on every row.
    • The cost column is |weight|.
    • Every emptied account's sum(cost(position)) is exactly zero.
    • cost(sum(position)) still gives the per-unit product.
    • JOURNAL … AT COST shows 500 / -500 with balances 500 / 0. The test fails on main's execution.rs.
    • BALANCES AT COST of a held {{500 USD}} lot is exactly 500. The test fails with the old at_cost.
    • cost(units(position)) per row is the units, not the posting's cost, which pins the route's guard.
    • With the routing disabled, the first two tests fail.
  • Mutation testing on the query diff: the first run left the guard unpinned (2 survivors). The per-row test above kills both, confirmed by hand.
  • Workspace: 176 test binaries, 0 failures. cargo clippy --workspace --all-features --all-targets -D warnings is clean.

Closes #2425

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

`cost(position)` multiplied the Position value's per-unit cost back out,
and a lot bought as `3 X {{500 USD}}` has a per-unit cost of 500/3,
rounded: it gave 500.0000000000000000000000001 where `weight` gives 500,
and so did the sale that empties such a lot, so an emptied account's
`sum(cost(position))` printed `-0 USD`.

Over the position column it now takes the posting's booked cost through
the canonical `cost_number_weight`, the route `weight(position)` already
takes (#1966): exact for a total-carrying cost, and the same
`units x per-unit` for every per-unit one. The posting table's `cost`
column did the same multiplication with an unchecked `*`; it uses the
same rule now, unsigned as before. `cost()` of any other argument still
works from the per-unit cost.

Closes #2425

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen requested a review from a team as a code owner September 25, 2026 19:18
@codecov

codecov Bot commented Sep 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.17647% with 6 lines in your changes missing coverage. Please review.

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

📢 Thoughts on this report? Let us know!

Mutation testing left the route's guard unpinned: forcing it true, or
`&&` to `||`, sent every `COST(x)` to the posting's cost, and the only
non-column case tested was `cost(sum(position))`, which is aggregated
elsewhere. `cost(units(position))` per row is the units themselves.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@github-actions

github-actions Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 34.4ms ± 1.9ms 563.4ms ± 5.3ms 16.4x 51.2 MB / 50.1 MB
investment 53.4ms ± 1.0ms 2150.7ms ± 6.9ms 40.3x 55.3 MB / 58.2 MB
fifo 51.2ms ± 0.3ms 12093.2ms ± 146.8ms 236.1x 55.3 MB / 57.8 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 33.9ms ± 0.2ms 34.4ms ± 1.9ms +1.5% ✅ within noise 51.0 MB → 51.2 MB (+0.3%)
investment 52.9ms ± 0.3ms 53.4ms ± 1.0ms +1.0% ✅ within noise 55.3 MB → 55.3 MB (+0.0%)
fifo 51.1ms ± 0.4ms 51.2ms ± 0.3ms +0.2% ✅ within noise 59.1 MB → 55.3 MB (-6.5%)

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

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 178 masked)
Full AST Match 100%
Total Files 813
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 and others added 2 commits September 25, 2026 19:36
VitePress parses `{{ ... }}` as a Vue expression even inside inline code,
so the docs build failed on `3 X {{500 USD}}`. No other docs page writes
the syntax; say it in words instead.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
`Inventory::at_cost` multiplied each lot's per-unit cost back out, so a
held `{{500 USD}}` lot of 3 showed 500.0000000000000000000000001 under
`BALANCES AT COST`. It now reads the lot's total where the inventory
keeps one (#2427). BQL's balances come from the booking engine's
replay, whose inventories keep those totals; an inventory built without
them values its lots as before.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen

robcohen commented Sep 25, 2026 •

Copy link
Copy Markdown
Member Author

Deep review (three passes)

Fixed in 3823b70: BALANCES AT COST was still inexact. For a held 3 X {{500 USD}} lot it showed 500.0000000000000000000000001. Inventory::at_cost multiplied each lot's per-unit cost back out. It now reads the lot's total where the inventory keeps one. BQL's balances come from the booking engine's replay, whose inventories keep those totals since #2427. There's a core test and a query test; the query test fails with the old at_cost.

Fixed in 8aaeed0: JOURNAL … AT COST was still inexact. An earlier version of this comment claimed the at_cost fix covered it. It didn't, and I checked after posting.

Pass 3: compat corpus and raw scale (docs only, 3d427c5). I fetched the BQL compat corpus and ran all 19 queries on its 29 ledgers with a total or compound cost, against bean-query 0.2.0, on this branch and on main.

  • Compat suite: all 551 (file, query) pairs keep their status (393 match, 158 mismatch, both builds). The rendered text of JOURNAL 'Assets' AT cost is byte-identical on all 29, so no KNOWN_*_DIVERGENCES entry is needed.

  • Raw values: these differ on 19 pairs, because cost(position) now carries the booked total's scale, the weight column's:

    posting main this PR
    {{300.00 USD}} 300.00000000000000000000000000 300.00
    2 HOOL {150 # 5 USD} 305.00 (152.50 × 2) 305 (2 × 150 + 5)
    10.00 HOOL {100.00 # 9.95 USD} 1009.95000 1009.9500

    That's the intended equality with weight, and the old trailing zeros were artifacts of dividing and multiplying back. Only JSON and embedders see it, so the CHANGELOG now says so.

Pass 2, 80e3d8e (no behavior change):

  • COST(position) computed the posting's cost twice per row: once in the arm's guard and once in its body. It's now one call, with the value-path fallback moved into evaluate_on_argument_values, which the default arm shares.
  • JOURNAL … AT COST built a running balance it no longer reads. It now skips it in that mode.
  • Loop check: cost_balance and the row it feeds are updated inside the same if matches block as before, with no continue between them, so the running sum covers exactly the rows shown.
  • Mutation testing on the whole diff (query + core): 14 mutants, 6 caught, 8 didn't compile, none survived.

Probed, correct on this PR:

  • cost(position) in ORDER BY and inside sum() goes through the same per-row evaluator, so it's exact there too.

Found, not fixed here (pre-existing, same class), filed as #2429 and #2430:

  • FROM #postings: cost(position) still gives 500.00000000000000000000000001. The system table materializes its rows as Values, and its evaluator has no posting to route to. WEIGHT(position) has the same gap there: 10 EUR @ 1.10 USD gives 10 EUR over FROM #postings, on main too, where the weight column gives 11.00 USD, so WEIGHT() ignores the price annotation, returning units in the wrong currency #1966's fix never covered the table path. Fixing both means the table path learning the route. It could read the row's own weight column for a cost-bearing posting, but that has to be restricted to the real #postings table, since a subquery can alias anything as weight.
  • cost(sum(position)): sum() builds its inventory from bare Position values, which carry no totals.

Both are documented in bql.md and the CHANGELOG as still per-unit.

Each row's position AT COST was `units x per-unit` (with a bare `*`),
and its balance was `at_cost` of the running balance, which multiplies
the rounded per-unit cost back out: a `{{500 USD}}` lot showed
500.0000000000000000000000001 on its row and in the balance. The
running balance uses the shared backing (#1086), which keeps no lot
totals, so `at_cost` cannot be made exact there.

The row now shows the posting's booked cost (`compute_posting_cost`, as
`cost(position)` gives it), and the balance is the running sum of those
row costs, which is what `at_cost` of the cumulative balance is: a
sale's cost nets its buy's, and cost-less amounts pass as units.
Unchanged for per-unit lots, including a sale that spans lots.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
robcohen and others added 2 commits September 26, 2026 01:31
The arm's guard called `compute_posting_cost` and the body called it
again, so every `cost(position)` row paid for the canonical weight
twice. The arm now matches on one call and falls back to the value
path, which moves into `evaluate_on_argument_values` so the default arm
and the fallback share it. JOURNAL AT COST also stops building the
running balance it no longer reads; its balance is `cost_balance`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
…scale

Running the BQL compat corpus's 29 total/compound-cost ledgers through
both builds: all 551 (file, query) pairs keep their status, and the
rendered text of `JOURNAL ... AT cost` is identical, but the raw JSON
changes on 19 pairs. `cost(position)` now carries the booked total's
scale, the weight column's: 300.00 where it was
300.00000000000000000000000000, and 305 for `2 HOOL {150 # 5 USD}`
where the re-multiplied per-unit gave 305.00. Say so for JSON and
embedder consumers.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen merged commit 5aa8ec2 into main Sep 26, 2026
70 of 71 checks passed
@robcohen
robcohen deleted the fix/bql-cost-exact-total-2425 branch September 26, 2026 02:14
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.

Selling a whole {{T}} lot whose total doesn't divide evenly fails to balance: a lot keeps only its rounded per-unit cost

1 participant