Repository navigation
fix(query): stop WEIGHT() inventing precision the weight column does not - #1965
Conversation
Found by the canonical-function drift sweep (#1902 Phase 2). CLAUDE.md names this pair specifically: a consumer surfacing a per-posting weight must call `rustledger_booking::posting_weight` rather than re-derive it. The `weight` COLUMN does. The `WEIGHT()` FUNCTION re-derived `units * cost.number`. 3 HOOL {{100.00 USD}} weight column 100.00 WEIGHT(position) 100.00000000000000000000000000 Same value, 26 digits of scale invented by the multiplication. `{{100.00}}` resolves to a per-unit of 33.333..., and multiplying back reintroduces exactly the division-then-multiplication the canonical exists to avoid (#1106/#1113). The compat suite compares RENDERED output, so scale is not cosmetic. WHY THIS IS A MITIGATION AND NOT A CORRECTION `WEIGHT()` cannot call the canonical. It receives a `Value::Position`, whose cost is already resolved to a per-unit `Decimal` - the preserved total that makes `posting_weight` exact is gone by then - and `evaluate_function_on_values` gets only `Value`s, with no posting to recover it from. So the function still yields `100` where the column yields `100.00`. Closing that needs `Position` to retain the cost spec, which is a wider change than the symptom warrants; it is recorded on #1963. THE OBVIOUS FIX WAS WORSE, AND IS NOW PINNED AGAINST Normalizing unconditionally was the first attempt. It fixes the case above and REGRESSES the common one: `2 HOOL {5.25 USD}` went from `10.50` to `10.5`, because normalize strips meaningful trailing zeros too. Trading a rare cosmetic problem for a frequent one is not a fix. So the strip applies only when the scale is already past anything a real cost carries (>12). Such a scale can only come from a division; `rust_decimal` tops out at 28, and no written cost has 12 decimal places. Both tests verified to fail on their own sabotage: raw product -> "WEIGHT() invented precision: column=100.00 ..." unconditional normalize -> "on a plain per-unit cost the function and the column must match exactly" The second is the one worth having: it is the guard against re-attempting the fix I nearly shipped. Closes #1963.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
📊 Benchmark Results
vs main branch (2026-08-04)
What do these numbers mean?
|
There was a problem hiding this comment.
Pull request overview
Mitigates a precision/scale drift in the BQL WEIGHT() function so it no longer invents excessive decimal scale compared to the weight column, aligning query output stability with the canonical posting-weight behavior surfaced elsewhere in rustledger-query.
Changes:
- Adds scale-artifact stripping to
WEIGHT(position)whenunits × per-unitmultiplication produces division-derived trailing-zero precision. - Adds an integration test covering both the “total cost that doesn’t divide evenly” repro and a guard for preserving meaningful trailing zeros on ordinary per-unit costs.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| crates/rustledger-query/src/executor/mod.rs | Updates WEIGHT() evaluation logic to mitigate scale artifacts when recomputing totals from per-unit costs. |
| crates/rustledger-query/tests/weight_function_scale.rs | Adds regression tests pinning the scale behavior for WEIGHT(position) vs the weight column. |
Suppressed comments (1)
crates/rustledger-query/src/executor/mod.rs:1568
- The new scale-artifact mitigation is applied only for
WEIGHT(position). TheWEIGHT(inventory)path (used forWEIGHT(sum(position))) still multiplies and returns the rawDecimal, so the same invented-scale issue can still surface when the function is used over inventories/aggregates.
} else {
raw
};
Ok(Value::Amount(Amount::new(total, cost.currency.clone())))
} else {
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
| 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
- WEIGHT() multiplied with the bare operator while the adjacent COST() arm uses checked_mul + overflow_err. Same product, same operands, two different overflow behaviors; now both fail loudly. A saturating product would certify a weight that never existed, which is the unsoundness #1863 removed from the residual path. - The comment claimed a scale past 12 could only have come from a division, never from a written number. rust_decimal accepts literals out to 28 places, so a user could author a 13-place cost and see its weight normalized. Stated as the heuristic it is, with why the alternative (normalizing every weight) is worse. - The regression guard compared Debug-string lengths as a proxy for precision. A formatting tweak could move it with no scale changing, and it never named the invariant. Compares Decimal::scale() now. Both sabotages still fail the test: dropping the normalize (function scale 26 vs column 2) and applying it unconditionally (10.50 -> 10.5).
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.
Suppressed comments (1)
crates/rustledger-query/tests/weight_function_scale.rs:20
- The tests currently depend on
Value’sDebugformatting (stringifying cells with{:?}and then parsing outnumber: ...). That’s brittle: changing derived Debug output (field order/names) would break the test without any semantic regression. Since the query engine already returnsValue/Amount, prefer extractingAmount.numberdirectly and asserting onDecimal::scale()/to_string()instead of parsing Debug strings.
/// The `number:` field out of a `Value`'s debug rendering, as a `Decimal`.
fn number_of(rendered: &str) -> rust_decimal::Decimal {
let after = rendered.split("number: ").nth(1).expect("a number field");
let text: String = after
.chars()
Deep review of this PR found the fix was half a fix. WEIGHT() reaches the same units x cost arithmetic two ways - a bare Position, and every position inside an Inventory - and the first commit patched only the first. The Inventory arm 30 lines below kept #1963 verbatim, so on the same 3 HOOL {{100.00 USD}} lot: weight column 100.00 WEIGHT(position) 100 WEIGHT(SUM(position)) 100.00000000000000000000000000 The two WEIGHT() spellings disagreed with each other as well as with the column. Which is the drift this sweep exists to find: the same quantity derived twice in one function, fixed once. Both arms now call position_cost_total(). That also consolidates the overflow message - the Inventory arm had its own wording rather than overflow_err() - and nothing asserts on the old text. New test pins the two paths together; verified it reports dirty by reverting only the Inventory arm to a bare multiply (inventory scale 26, position scale 0). Also fixed a comment referring to a length check that the previous commit replaced with a scale assertion.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.
Suppressed comments (1)
crates/rustledger-query/tests/weight_function_scale.rs:24
- The tests extract decimals by parsing
Value’s Debug output (splitting on"number: "and scanning characters). That’s unnecessarily brittle:Executor::executereturnsTable { rows: Vec<Vec<Value>> }andValueis publicly re-exported (rustledger_query::Value), so the test can keepValueinstances and pattern-matchValue::Amount(a)to accessa.numberdirectly. This avoids coupling the test to Debug formatting details and makes the scale/value assertions more robust.
/// The `number:` field out of a `Value`'s debug rendering, as a `Decimal`.
fn number_of(rendered: &str) -> rust_decimal::Decimal {
let after = rendered.split("number: ").nth(1).expect("a number field");
let text: String = after
.chars()
.take_while(|c| c.is_ascii_digit() || *c == '.' || *c == '-')
.collect();
text.parse().expect("a parsable decimal")
}
) * fix(query): route WEIGHT(position) to the canonical weight ladder 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. * test(query): render via Display, and select the row by account 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".
Found by the canonical-function drift sweep (#1902 Phase 2). CLAUDE.md names this pair specifically: a consumer surfacing a per-posting weight must call
rustledger_booking::posting_weightrather than re-derive it. The column does. The function re-derivedunits * cost.number.Same value, 26 digits of scale invented by the multiplication.
{{100.00}}resolves to a per-unit of33.333…, and multiplying back reintroduces exactly the division-then-multiplication the canonical exists to avoid (#1106/#1113). The compat suite compares rendered output, so scale isn't cosmetic.Why this is a mitigation, not a correction
WEIGHT()cannot call the canonical. It receives aValue::Position, whose cost is already resolved to a per-unitDecimal— the preserved total that makesposting_weightexact is gone by then — andevaluate_function_on_valuesgets onlyValues, with no posting to recover it from.So the function still yields
100where the column yields100.00. Closing that needsPositionto retain the cost spec, which is a wider change than the symptom warrants. Recorded on #1963.The obvious fix was worse, and is now pinned against
Normalizing unconditionally was my first attempt. It fixes the case above and regresses the common one:
2 HOOL {5.25 USD}went from10.50to10.5, becausenormalizestrips meaningful trailing zeros too. Trading a rare cosmetic problem for a frequent one is not a fix.So the strip applies only when the scale is already past anything a real cost carries (
>12). Such a scale can only come from a division —rust_decimaltops out at 28, and no written cost has 12 decimal places.Both tests verified to fail on their own sabotage
The second is the one worth having: it's the guard against re-attempting the fix I nearly shipped.
Verification
rustledger-query: 0 failurescargo fmt --checkclean,RUSTDOCFLAGS=-D warnings cargo doccleanCloses #1963.