Skip to content

refactor(core): factor PriceAnnotation orthogonal axes (closes #1167) - #1176

Merged
robcohen merged 2 commits into
mainfrom
feat/price-annotation-axes
May 21, 2026
Merged

robcohen merged 2 commits into
mainfrom
feat/price-annotation-axes

Conversation

@robcohen

@robcohen robcohen commented May 21, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #1167. PriceAnnotation was a 6-variant enum flattening two orthogonal axes:

  • kind: per-unit (@) vs total (@@)
  • completeness: Complete amount / IncompleteAmount / no amount

This made every consumer write 6 match arms even when only one axis mattered.

New shape

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).

Construction sites preserved

New constructors keep the variant-style readability:

Old New
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::UnitEmpty PriceAnnotation::unit_empty()
PriceAnnotation::TotalEmpty PriceAnnotation::total_empty()

Only match arms had to change shape.

Wins

  • 20+ consumers shed 6-arm boilerplate. The two big residual blocks in rustledger-booking (the Decimal and BigDecimal calculators) lose ~30 lines each.
  • Shared helper: price_residual_contribution(price, units) lives in rustledger-booking and 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() and amount() helpers become trivial: matches!(self.kind, PriceKind::Unit) and self.amount.as_ref().and_then(IncompleteAmount::as_amount).

Breaking changes

The serde JSON shape changes (caught in Copilot review).

  • Old (enum-tagged):
    {"Unit": {"number": "150", "currency": "USD"}}
    {"UnitEmpty": null}
  • New (struct):
    {"kind": "Unit", "amount": {"Complete": {"number": "150", "currency": "USD"}}}
    {"kind": "Unit", "amount": null}

This is intentional. No in-tree consumer reads PriceAnnotation via derived serde — the ffi-wasi crate, the plugin convert layer, and the wasm crate all use their own DTOs. The plugin wire format (PriceAnnotationData in rustledger-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_VERSION bump 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

  • Parser input syntax (unchanged — beancount source format).
  • Display (unchanged — @ 150 USD / @@).
  • Plugin wire (MetaValueData / PriceAnnotationData) — independent of PriceAnnotation.
  • BQL semantics: Value::Amount at the SQL boundary for price accessor — matches bean-query.

Test plan

  • cargo check --workspace --all-features --all-targets — clean
  • cargo clippy --workspace --all-features --all-targets -- -D warnings — clean
  • cargo test across 9 affected crates (core, parser, booking, validate, query, loader, plugin, lsp, cli) — all pass
  • CI full workspace + compat suite

🤖 Generated with Claude Code

@robcohen
robcohen requested a review from a team as a code owner May 21, 2026 13:27
Copilot AI review requested due to automatic review settings May 21, 2026 13:27

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 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 PriceKind and reshape PriceAnnotation into { kind, amount }, with constructor helpers mirroring the old variants.
  • Update parser/formatter/visitors and all consumers to use kind + amount access patterns; booking residual logic is partially consolidated into a shared helper.
  • Bump CACHE_VERSION to 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_annotation currently returns Err(()) when the input is just a bare @/@@ with no amount. That causes parse_posting to drop the sigil entirely (.ok()), changing semantics vs the previous UnitEmpty/TotalEmpty behavior and breaking round-tripping. Consider returning PriceAnnotation::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.

Comment thread crates/rustledger-core/src/directive.rs Resolved
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]>
@robcohen
robcohen force-pushed the feat/price-annotation-axes branch from e801a28 to fc6b9f8 Compare May 21, 2026 13:49
@robcohen robcohen self-assigned this May 21, 2026
@robcohen
robcohen enabled auto-merge (squash) May 21, 2026 13:52
@github-actions

github-actions Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 36ms ± 1.1ms 25.2 MB
beancount 888.4ms ± 7.1ms 50.7 MB
Comparison 24.7x faster 2.0x less

vs main branch (2026-05-21)

Metric main this PR Change
Time 35.8ms 36ms +0.6% ✅
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

@robcohen
robcohen merged commit f6d7b5e into main May 21, 2026
41 checks passed
@robcohen
robcohen deleted the feat/price-annotation-axes branch May 21, 2026 14:02
@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 786
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

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.

Type-driven: factor PriceAnnotation orthogonal axes

2 participants