Skip to content

refactor(core): MetaValue::{Account,Currency,Tag,Link} typed (closes #1163) - #1174

Merged
robcohen merged 3 commits into
mainfrom
feat/metavalue-typed
May 21, 2026
Merged

robcohen merged 3 commits into
mainfrom
feat/metavalue-typed

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

Final slice of #1163. Migrates the four typed `MetaValue` variants from `String` to the corresponding domain newtypes, matching the typing already in place on the rest of the AST.

This closes #1163 for the AST layer. Every identifier kind in the AST — including inside metadata — now has a compiler-enforced type.

What changed

Core enum (`rustledger-core/src/directive.rs`):

  • `MetaValue::Account(String)` → `MetaValue::Account(Account)`
  • `MetaValue::Currency(String)` → `MetaValue::Currency(Currency)`
  • `MetaValue::Tag(String)` → `MetaValue::Tag(Tag)`
  • `MetaValue::Link(String)` → `MetaValue::Link(Link)`

Parser (`rustledger-parser/src/parser.rs`):

  • Drop `.to_string()` at MetaValue construction sites
  • Align `parse_currency` and `parse_link` to return their newtypes (`parse_account` and `parse_tag` already did)
  • Delete now-redundant `.into()` bridges at downstream construction sites (7 sites)

Core constructors:

Plugin convert layer:

  • `from_wrapper` re-interns from String into the workspace interner via the newtype `From<&str>` impl
  • `to_wrapper` lowers via `Display`
  • `MetaValueData` itself stays String-typed — `plugin-types` is intentionally minimal and does not depend on `rustledger-core`, and plugins run without access to the workspace interner. The host re-interns at the convert boundary. This is the architecturally-correct layering.

FFI / Query / CLI:

  • `ffi-wasi`: typed variants lowered via `Display` at the JSON boundary
  • `query/executor/functions/util.rs`: typed variants lowered to `BQL Value::String` at the SQL boundary — matches `bean-query` semantics (no first-class typed values in the SQL surface)
  • `cmd/price/discovery.rs`: or-pattern split — `MetaValue::String(s) | Currency(s)` bound `s` to two different types; now separate arms

Wire-format compatibility

#1163 status after this PR

Component Status
AST directive fields (Currency) ✅ #1169
AST directive fields (Account) ✅ #1171
AST directive fields (Tag) ✅ #1172
AST directive fields (Link) ✅ #1173
`MetaValue::*` variants ✅ this PR

The architectural goal of #1163 — compiler distinguishes the four identifier kinds at every AST position, including metadata — is now fully met.

Test plan

  • `cargo check --workspace --all-features --all-targets` — clean
  • `cargo clippy --workspace --all-features --all-targets -- -D warnings` — clean (removed 7 useless conversions in parser as bonus)
  • `cargo test` across 8 affected crates — pass
  • CI full workspace + compat suite

🤖 Generated with Claude Code

…1163)

Final slice of #1163. Migrates the four typed MetaValue variants
from String to the corresponding domain newtypes, matching the
typing already in place on the rest of the AST.

Changes:
- core: MetaValue::{Account,Currency,Tag,Link} carry their
  respective newtypes
- parser: drop .to_string() at MetaValue construction sites; also
  align parse_currency and parse_link to return their newtypes
  (parse_account and parse_tag already returned newtypes), then
  delete the no-longer-needed .into() bridges at downstream
  construction sites
- with_link constructors take impl Into<Link> (already done for
  with_tag in #1172; this catches the missed half)
- plugin convert layer: from_wrapper re-interns from String into
  the workspace interner via the newtype From<&str> impl; to_wrapper
  lowers via Display. MetaValueData itself stays String-typed —
  plugin-types is intentionally minimal and does not depend on
  rustledger-core (the host re-interns at the convert boundary).
- ffi-wasi: typed variants lowered via Display at the JSON boundary
- query: typed variants lowered to BQL Value::String at the SQL
  boundary (matches bean-query semantics; no first-class typed values
  in the SQL surface)
- discovery: or-pattern split — MetaValue::String(s) | Currency(s)
  bound s to two different types; now separate arms

#1163 is fully closed for the AST layer. The MetaValue typing was
the last asymmetry: every identifier kind in the AST (including
inside metadata) now has a compiler-enforced type.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner May 21, 2026 04:13
Copilot AI review requested due to automatic review settings May 21, 2026 04:13
@codecov

codecov Bot commented May 21, 2026 •

Copy link
Copy Markdown

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 completes the #1163 AST typing effort by migrating the remaining MetaValue::{Account,Currency,Tag,Link} variants from String payloads to the corresponding domain newtypes, and updates parser + boundary layers (query, plugin convert, FFI, CLI) to construct/lower these typed variants appropriately.

Changes:

  • Refactors rustledger-core::MetaValue::{Account,Currency,Tag,Link} to carry domain newtypes instead of String.
  • Updates the parser to return/propagate typed Currency/Link (and to stop redundant .to_string()/.into() conversions at construction sites).
  • Updates plugin/query/FFI/CLI lowering paths to convert typed meta values back to String at their respective boundaries.

Reviewed changes

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

Show a summary per file
File Description
crates/rustledger-core/src/directive.rs Changes MetaValue typed variants to store Account/Currency/Tag/Link newtypes.
crates/rustledger-parser/src/parser.rs Makes parse_currency return Currency and updates meta/custom/open construction sites accordingly.
crates/rustledger-core/src/identifiers.rs Updates docs to reflect typed MetaValue coverage and plugin boundary story.
crates/rustledger-plugin/src/convert/from_wrapper.rs Converts string-typed plugin wire values into typed MetaValue variants.
crates/rustledger-plugin/src/convert/to_wrapper.rs Lowers typed MetaValue variants back to string-typed MetaValueData.
crates/rustledger-query/src/executor/functions/util.rs Lowers typed MetaValue variants to BQL Value::String at query boundary.
crates/rustledger-ffi-wasi/src/types/output.rs Lowers typed MetaValue variants to JSON strings at FFI boundary.
crates/rustledger/src/cmd/price/discovery.rs Fixes matching/lowering of MetaValue::Currency in metadata parsing helpers.
crates/rustledger-core/src/format/helpers.rs Updates formatting helpers to render typed Account/Currency via Display.
crates/rustledger-core/src/format/mod.rs Updates format tests to construct typed MetaValue variants via .into().
crates/rustledger-core/src/extract.rs Updates extract tests to construct typed MetaValue::Currency via .into().

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

@github-actions

github-actions Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 33.7ms ± 1.4ms 25.2 MB
beancount 898.9ms ± 12.3ms 50.8 MB
Comparison 26.7x faster 2.0x less

vs main branch (2026-05-21)

Metric main this PR Change
Time 35.8ms 33.7ms -5.9% 🟢
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

@github-actions

github-actions Bot commented May 21, 2026 •

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

robcohen and others added 2 commits May 20, 2026 23:25
…orrect docs

Addresses Copilot review on #1174.

Two related findings:

1. The convert-boundary docstring claimed `From<&str>` re-interns
   into the workspace interner. That was wrong: `InternedStr::from(&str)`
   just wraps the string in a fresh `Arc<str>`. The actual dedup
   happens later via `StringInterner::intern` in the loader pass.

2. The dedup pass (`reintern_directives`) walked every AST identifier
   field but never touched `Metadata` maps — so cross-file (and
   plugin-emitted) MetaValue::{Account, Currency, Tag, Link, Amount}
   payloads silently retained distinct `Arc<str>` allocations even
   when they referenced identical strings.

Changes:

- Add `intern_meta` helper in `rustledger-loader::dedup` that walks
  every `MetaValue` payload type containing an interned string
  (Account, Currency, Tag, Link, and the currency on Amount) and
  re-interns through the shared workspace interner.

- Call `intern_meta` for the `meta` field on every directive variant
  (Transaction, Balance, Open, Close, Commodity, Pad, Note, Document,
  Price, Event, Query, Custom) AND on every posting (transactions
  carry posting-level meta separately).

- Rewrite the docstrings on both `from_wrapper.rs` and
  `identifiers.rs` to accurately describe where dedup happens: at
  the loader pass, not at the convert boundary or the From impl.

- Add `test_fresh_parse_deduplicates_metavalue_across_files`
  regression test pinning that two cross-file Transactions with
  identical `counterparty: Assets:Bank` meta land on a single shared
  `Arc<str>`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Three of four review-followup items addressed:

1. **CACHE_VERSION bump 5 → 6**: the #1163 newtype slices (Currency/
   Account/Tag/Link/MetaValue) changed rkyv archive wrappers for the
   typed variants. Bumping the version short-circuits old cache files
   at the header check instead of risking rkyv reading old bytes into
   a structurally-different ArchivedMetaValue. Same pattern as the v5
   bump for the Spanned<Posting> change in #1151.

2. **Regression test variant coverage**: the original Copilot-driven
   regression test only exercised MetaValue::Account. Expanded to
   cover all five interned-payload variants (Account, Currency, Tag,
   Link, Amount.currency) in a single multi-file fixture.

3. **Posting-level meta dedup test**: added a per-posting
   MetaValue::Account assertion to verify the per-posting intern_meta
   call (not just the directive-level one). Catches silent regressions
   if someone removes the per-posting call later.

The fourth item (recovering ) is not
achievable: Arc::deref is not const in stable Rust, so neither
InternedStr::as_str nor by extension Currency::as_str can be const.
Added an inline comment explaining the constraint.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen enabled auto-merge (squash) May 21, 2026 04:41
@robcohen
robcohen merged commit 16bd0dc into main May 21, 2026
40 checks passed
@robcohen
robcohen deleted the feat/metavalue-typed branch May 21, 2026 04:45
robcohen added a commit that referenced this pull request May 21, 2026
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 added a commit that referenced this pull request May 21, 2026
…#1176)

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]>
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: newtype InternedStr by domain (Account / Currency / Tag / Link)

2 participants