Repository navigation
refactor(core): factor PriceAnnotation orthogonal axes (closes #1167) - #1176
Conversation
There was a problem hiding this comment.
Pull request overview
This PR refactors rustledger-core::PriceAnnotation from a 6-variant enum into a (kind, amount) struct (PriceKind + Option<IncompleteAmount>) to eliminate boilerplate matches across the workspace, and updates all downstream consumers accordingly (booking math, query accessors, loader dedup, plugin conversions, formatting, and tests). It also bumps the loader cache version due to the rkyv layout change.
Changes:
- Introduce
PriceKindand reshapePriceAnnotationinto{ kind, amount }, with constructor helpers mirroring the old variants. - Update parser/formatter/visitors and all consumers to use
kind+amountaccess patterns; booking residual logic is partially consolidated into a shared helper. - Bump
CACHE_VERSIONto invalidate old rkyv caches affected by the new archive layout.
Reviewed changes
Copilot reviewed 22 out of 22 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| crates/rustledger-wasm/src/convert.rs | Adjust JSON conversion to read complete amounts from the new amount field. |
| crates/rustledger-validate/tests/validation_integration_test.rs | Update test construction sites to use new PriceAnnotation::* constructors. |
| crates/rustledger-validate/src/validators/transaction.rs | Simplify tolerance computation by extracting only complete price amounts from amount. |
| crates/rustledger-query/tests/bql_integration_test.rs | Update query integration tests to use new constructors. |
| crates/rustledger-query/src/price.rs | Update price DB tests/construction sites to use new constructors. |
| crates/rustledger-query/src/executor/evaluation.rs | Simplify BQL price accessor to return only complete amounts via IncompleteAmount::as_amount. |
| crates/rustledger-plugin/src/convert/to_wrapper.rs | Convert PriceAnnotation to plugin wire format using kind + amount. |
| crates/rustledger-plugin/src/convert/from_wrapper.rs | Convert plugin wire data back into the new PriceAnnotation representation. |
| crates/rustledger-parser/src/parser.rs | Update parser construction to new constructors (but currently lacks bare-sigil handling). |
| crates/rustledger-lsp/src/ledger_state.rs | Simplify currency extraction from price annotations by walking the underlying IncompleteAmount. |
| crates/rustledger-loader/src/dedup.rs | Re-intern strings inside price annotations by matching on amount. |
| crates/rustledger-loader/src/cache.rs | Bump CACHE_VERSION to 6 for the new rkyv layout. |
| crates/rustledger-ffi-wasi/src/types/input.rs | Update FFI input conversion to use PriceAnnotation::unit(...). |
| crates/rustledger-core/src/visit.rs | Update currency visitor logic/tests to inspect amount rather than matching old variants. |
| crates/rustledger-core/src/lib.rs | Re-export PriceKind from rustledger-core. |
| crates/rustledger-core/src/format/mod.rs | Update formatting tests to use new constructors. |
| crates/rustledger-core/src/format/amount.rs | Format price annotations using kind + amount. |
| crates/rustledger-core/src/extract.rs | Update extract tests to use new constructors. |
| crates/rustledger-core/src/directive.rs | Define PriceKind and refactor PriceAnnotation into a struct with constructors/helpers. |
| crates/rustledger-booking/src/lib.rs | Add shared residual helper and migrate residual/currency logic to kind + amount. |
| crates/rustledger-booking/src/interpolate.rs | Update interpolation residual/scale tracking logic to kind + amount. |
| crates/rustledger-booking/src/book.rs | Update booking/cost inference paths to use kind + amount accessors. |
Comments suppressed due to low confidence (1)
crates/rustledger-parser/src/parser.rs:829
parse_price_annotationcurrently returnsErr(())when the input is just a bare@/@@with no amount. That causesparse_postingto drop the sigil entirely (.ok()), changing semantics vs the previousUnitEmpty/TotalEmptybehavior and breaking round-tripping. Consider returningPriceAnnotation::unit_empty()/total_empty()in this fallback case (and ideally add a parser regression test for bare-sigil prices).
});
}
stream.pos = save_pos;
Err(())
}
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
PriceAnnotation was a 6-variant enum flattening two orthogonal axes:
- kind (Unit `@` vs Total `@@`)
- completeness (Complete amount / IncompleteAmount / no amount)
Refactor into:
pub enum PriceKind { Unit, Total }
pub struct PriceAnnotation {
pub kind: PriceKind,
pub amount: Option<IncompleteAmount>,
}
The five non-empty old variants collapse to (kind, Some(amount));
the two empty variants collapse to (kind, None).
Wins:
- 6-arm match boilerplate at 20+ consumers collapses to one match
on `amount` and/or one check on `kind`. Most sites lose 15-30
lines each (booking residual logic, validator tolerances, LSP
currency extraction, query BQL price accessor, plugin convert,
wasm convert, loader dedup).
- The orthogonal axes become orthogonal in the code.
- `is_unit()` / `amount()` helpers become trivial field accesses.
New constructors (`PriceAnnotation::unit`/`total` for complete,
`unit_incomplete`/`total_incomplete`, `unit_empty`/`total_empty`)
preserve the readability of the old variant names at construction
sites — only match arms had to change shape.
New shared helper in booking: `price_residual_contribution` factors
the (kind=Unit vs kind=Total) signed-amount math so it lives in
one place instead of duplicated across the precise and non-precise
residual calculators.
CACHE_VERSION bumps 5 to 6: the PriceAnnotation archive layout
changed (enum discriminants vs struct fields), so old caches would
rkyv-deserialize as nonsense. Same precedent as #1151 / #1174.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
e801a28 to
fc6b9f8
Compare
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
📊 Benchmark Results
vs main branch (2026-05-21)
What do these numbers mean?
|
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
Summary
Closes #1167.
PriceAnnotationwas a 6-variant enum flattening two orthogonal axes:@) vs total (@@)This made every consumer write 6 match arms even when only one axis mattered.
New shape
The five non-empty old variants collapse to
(kind, Some(amount)); the two empty variants collapse to(kind, None).Construction sites preserved
New constructors keep the variant-style readability:
PriceAnnotation::Unit(amt)PriceAnnotation::unit(amt)PriceAnnotation::Total(amt)PriceAnnotation::total(amt)PriceAnnotation::UnitIncomplete(inc)PriceAnnotation::unit_incomplete(inc)PriceAnnotation::TotalIncomplete(inc)PriceAnnotation::total_incomplete(inc)PriceAnnotation::UnitEmptyPriceAnnotation::unit_empty()PriceAnnotation::TotalEmptyPriceAnnotation::total_empty()Only match arms had to change shape.
Wins
rustledger-booking(theDecimalandBigDecimalcalculators) lose ~30 lines each.price_residual_contribution(price, units)lives inrustledger-bookingand factors the Unit-vs-Total signed-amount math so it lives in one place instead of being duplicated across the precise and non-precise residual calculators.is_unit()andamount()helpers become trivial:matches!(self.kind, PriceKind::Unit)andself.amount.as_ref().and_then(IncompleteAmount::as_amount).Breaking changes
The serde JSON shape changes (caught in Copilot review).
{"Unit": {"number": "150", "currency": "USD"}} {"UnitEmpty": null}{"kind": "Unit", "amount": {"Complete": {"number": "150", "currency": "USD"}}} {"kind": "Unit", "amount": null}This is intentional. No in-tree consumer reads
PriceAnnotationvia derived serde — the ffi-wasi crate, the plugin convert layer, and the wasm crate all use their own DTOs. The plugin wire format (PriceAnnotationDatainrustledger-plugin-types) is unaffected.External consumers of the derived serde on the core AST would need to update. Given the project's stance on correctness over wire compat (see the #1163 / #1174 cadence), this is the right tradeoff.
The rkyv archive shape also changes, handled by the
CACHE_VERSIONbump 5 → 6. Same precedent as #1151 (Spanned<Posting>) and #1174 (newtype payloads). Note: PR #1174 also bumps to 6 — whichever lands first will need the second to rebase to 7.What didn't change
Display(unchanged —@ 150 USD/@@).MetaValueData/PriceAnnotationData) — independent ofPriceAnnotation.Value::Amountat the SQL boundary forpriceaccessor — matchesbean-query.Test plan
cargo check --workspace --all-features --all-targets— cleancargo clippy --workspace --all-features --all-targets -- -D warnings— cleancargo testacross 9 affected crates (core, parser, booking, validate, query, loader, plugin, lsp, cli) — all pass🤖 Generated with Claude Code