Skip to content

fix(query): route WEIGHT(position) to the canonical weight ladder - #1969

Merged
robcohen merged 2 commits into
mainfrom
fix/weight-price-rung
Aug 5, 2026
Merged

robcohen merged 2 commits into
mainfrom
fix/weight-price-rung

Conversation

@robcohen

@robcohen robcohen commented Aug 5, 2026

Copy link
Copy Markdown
Member

Closes #1966.

The canonical rustledger_booking::posting_weight is a three-rung ladder:
cost, then price, then units. WEIGHT() implemented two of them.

It was dispatched through the shared value registry, and by the time the
registry sees a Value::Position the posting is gone — a Position carries
units and cost and no price at all. So a priced posting fell straight
through to the units rung:

$ rledger query p.beancount "SELECT account, weight, WEIGHT(position)"
account      weight      WEIGHT
-----------  ----------  ----------
Assets:Bank  11.00 USD   10 EUR      <- 10 EUR @ 1.10 USD

A different number in a different currency. Any SUM(WEIGHT(position)) over a
ledger with priced postings produced a silently currency-mixed total — worse
than #1963, which was the same value carrying invented scale.

The fix

Dispatch WEIGHT(position) on the lazy path, where the Posting is still
in hand, straight to compute_posting_weight — the same helper the weight
COLUMN uses. The two spellings become one computation instead of two
implementations that agree by inspection.

This follows the precedent already in that match: the META family stays on
the lazy path because it reads the row context. Same reason here. The arm is
deliberately narrow — WEIGHT of anything but the bare position column still
goes to the shared registry, so this reintroduces exactly one lazy arm rather
than un-collapsing the dual dispatch.

Side effect: it also closes the residual scale gap #1963 recorded as
unfixed. With no re-derivation left there is nothing to lose scale in, so
WEIGHT(position) now returns the column's exact 100.00 rather than 100.

Tests

Five new cases pin every rung against the column — @, @@, per-unit cost,
total cost, plain units, and cost-outranking-price. 3 of 5 fail without the
fix.

The cost-outranks-price case asserts the value, not agreement. Agreement
alone cannot see the ladder order: both sides route through the same canonical
now, so swapping cost and price inside posting_weight moves them together and
every agreement assertion stays green. Verified by doing exactly that, which is
how I found the first version of that test was vacuous.

Two existing-test consequences, both correct

  • The fix(query): stop WEIGHT() inventing precision the weight column does not #1965 inventory-vs-position guard asserted equality. The position path
    is now better than the inventory path, not equal to it — SUM(position) has
    already collapsed the postings, so it has no posting to route with. Relaxed to
    inv_scale <= pos_scale, which still catches the original defect: verified it
    reports scale 26 against 2.
  • The eager arm's comment described the scale gap as needing a wider change.
    Updated — that arm is now reached only by an Inventory or a constructed
    Position, neither of which carries a price, so cost-or-units genuinely is
    the best answer available there.

Verification

cargo test -p rustledger-query -p rustledger-booking (23 suites), -p rustledger (27 suites), the dual_eval_parity harness, cargo +1.97.0 clippy --workspace --all-targets, and cargo doc all clean.

Closes #1966.

The canonical rustledger_booking::posting_weight is a three-rung
ladder: cost, then PRICE, then units. WEIGHT() implemented two of them.

It was dispatched through the shared value registry, and by the time
the registry sees a Value::Position the posting is gone - a Position
carries units and cost and no price at all. So a priced posting fell
through to the units rung:

  10 EUR @ 1.10 USD    weight column: 11.00 USD
                       WEIGHT(position): 10 EUR

A different number in a different currency, which made any SUM of
WEIGHT() over a ledger with priced postings a currency-mixed total.

Fixed by dispatching WEIGHT(position) on the LAZY path, where the
Posting is still in hand, straight to compute_posting_weight - the same
helper the weight COLUMN uses. The two spellings are now one
computation rather than two implementations that agree by inspection.

This follows the existing precedent in that match: the META family
already stays on the lazy path because it reads the row context. Same
reason here. The arm is deliberately narrow - WEIGHT of anything other
than the bare position column still goes to the shared registry, so
this reintroduces exactly one lazy arm rather than un-collapsing the
dual dispatch.

Side effect: it also closes the residual scale gap #1963 documented as
unfixed. There is no longer a re-derivation to lose scale in, so
WEIGHT(position) returns the column exact 100.00 rather than 100.

Two consequences for existing tests, both correct:

- the #1965 inventory-vs-position guard asserted EQUALITY. The position
  path is now better than the inventory path, not equal to it
  (SUM(position) has already collapsed the postings, so it has nothing
  to route with). Relaxed to inv_scale <= pos_scale, which still
  catches the original defect - verified, it reports 26 against 2.
- the eager arm comment described the scale gap as needing a wider
  change. Updated: that arm is now reached only by an Inventory or a
  constructed Position, neither of which carries a price, so
  cost-or-units really is the best answer available there.

New tests pin all four rungs against the column; 3 of 5 fail without
the fix. The cost-outranks-price case asserts the VALUE rather than
agreement, because agreement alone cannot see the ladder order - both
sides route through the same canonical now, so swapping cost and price
inside posting_weight moves them together and every agreement
assertion stays green. Verified by doing exactly that.
@robcohen
robcohen requested a review from a team as a code owner August 5, 2026 05:27
Copilot AI review requested due to automatic review settings August 5, 2026 05:27
@github-actions

github-actions Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 35.6ms ± 1.1ms 23.9 MB
beancount 901ms ± 5.1ms 50.6 MB
Comparison 25.3x faster 2.1x less

vs main branch (2026-08-05)

Metric main this PR Change
Time 36.6ms 35.6ms -2.7% ✅
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

@codecov

codecov Bot commented Aug 5, 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.

Pull request overview

This PR fixes BQL WEIGHT(position) so it uses the canonical posting-weight ladder (cost → price → units) by dispatching that specific call on the lazy path while the Posting (and its price annotation) is still available. This aligns WEIGHT(position) with the existing weight column computation and prevents silently wrong-currency results when price annotations are present.

Changes:

  • Add a narrow lazy-path dispatch for WEIGHT(position) to reuse compute_posting_weight (and thus rustledger_booking::posting_weight).
  • Add a new test suite pinning WEIGHT(position) to the weight column across all ladder rungs and key shapes (@, @@, costs, plain units, cost-vs-price precedence).
  • Update the existing scale-focused tests to reflect the now-intentional scale difference between per-posting and inventory-aggregated paths while preserving numeric agreement.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.

File Description
crates/rustledger-query/src/executor/mod.rs Routes WEIGHT(position) through the lazy path to the canonical posting-weight helper; updates eager-path commentary accordingly.
crates/rustledger-query/tests/weight_function_matches_column.rs New tests ensuring WEIGHT(position) and the weight column are the same computation across cost/price/units ladder cases.
crates/rustledger-query/tests/weight_function_scale.rs Adjusts the inventory-vs-position scale invariant and clarifies rationale now that WEIGHT(position) uses the canonical path.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@github-actions

github-actions Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 95% (raw 89%, 162 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 enabled auto-merge (squash) August 5, 2026 12:31
Both from Copilot review, both right.

Comparing format!("{:?}") tied the test to Value/Amount debug
formatting - a derive change would move it with no behavior changing,
and the failure output was a wall of struct syntax. Renders through
Amount Display now, which is {number} {currency} straight off Decimal
and so PRESERVES scale. That property is load-bearing: this file exists
to compare scale, and rendering through DisplayContext the way the CSV
writer does would round both sides to the same thing and make every
assertion vacuous. Said so in the helper.

The cost-outranks-price case indexed rows[0] for the broker posting.
Row order is an engine implementation detail unless the query
constrains it, so that was asserting on whichever posting came first.
Selects by account now, and the added account column lets a
disagreement name the posting instead of dumping two Debug strings.

Assertion also tightened from a contains("10.50") substring to
assert_eq!(broker, "10.50 USD") - Display makes the whole value
comparable, so there is no reason to match a fragment.

Re-ran both sabotages after the rewrite: removing the lazy arm fails 3
of 5, swapping the ladder inside posting_weight fails the value
assertion with left "12.00 USD".
Copilot AI review requested due to automatic review settings August 5, 2026 12:37

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.

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated no new comments.

Suppressed comments (1)

crates/rustledger-query/src/executor/mod.rs:736

  • The new lazy-path special-case fixes WEIGHT(position) only when the argument is the posting column in the default posting scan. Queries that evaluate expressions on materialized table rows (e.g. FROM #postings or subquery results) still route WEIGHT() through evaluate_function_on_values, where Value::Position has no price and the no-cost branch returns units (Ok(Value::Amount(p.units.clone()))), so a priced posting like 10 EUR @ 1.10 USD can still yield 10 EUR instead of 11.00 USD. If this PR is intended to fully close #1966, consider also intercepting WEIGHT(position) in the table/subquery evaluator (e.g., if the row has a weight column, return that canonical value), or change the Value/Position contract to retain price; add a regression test for SELECT weight, WEIGHT(position) FROM #postings on a price-only posting to prevent reintroducing the wrong-currency result.
            "WEIGHT" if Self::is_position_column(func) => Ok(compute_posting_weight(
                &ctx.transaction.postings[ctx.posting_index],
            )),

@robcohen
robcohen merged commit 058293c into main Aug 5, 2026
69 of 70 checks passed
@robcohen
robcohen deleted the fix/weight-price-rung branch August 5, 2026 13:01
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.

WEIGHT() ignores the price annotation, returning units in the wrong currency

2 participants