Skip to content

refactor(core): Tag domain newtype (refs #1163) - #1172

Merged
robcohen merged 1 commit into
mainfrom
feat/tag-newtype
May 21, 2026
Merged

robcohen merged 1 commit into
mainfrom
feat/tag-newtype

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

Third slice of #1163. After #1169 (Currency) and #1171 (Account), this wraps the `tags: Vec` fields on `Transaction` and `Document` behind the existing `Tag` newtype.

What changed

AST fields:

  • `Transaction.tags: Veccrate::Tag` (was `Vec`)
  • `Document.tags: Veccrate::Tag`
  • `Document::with_tag` and `Transaction::with_tag` take `impl Into`

Parser:

  • `parse_tag` returns `Tag` instead of `InternedStr`
  • `ParsedItem::Pushtag` / `Poptag` and the pushtag stack thread `Tag` through end-to-end
  • `apply_pushed_tags` walks `&[(Tag, Span)]`

Loader dedup:

  • `intern_typed_vec(&mut txn.tags, ..., Tag::as_interned_mut)` for both Transaction and Document tag slices
  • Reuses the existing helper from the Currency/Open.currencies migration — no new infrastructure

Newtype macro (`identifiers.rs`):

  • Added `ptr_eq(&self, other: &Self)` to the `domain_newtype!` macro so cross-file dedup tests can assert `Arc` identity directly on the newtype. Closes the awkwardness called out in the refactor(core): Account domain newtype (refs #1163) #1171 self-review where the loader test had to do `txns[0].tags[0].as_interned().ptr_eq(...)`.

Why this one is small

No HashMap/BTreeMap keys to migrate in tandem — tags only flow through:

  1. parse → `ParsedItem::Pushtag(Tag, _)` → directive
  2. directive → `Vec` on Transaction/Document
  3. loader dedup pass

No state machinery in booking/validate/query cares about tag identity beyond byte equality, so this PR is contained.

Performance

  • `Tag` is `#[repr(transparent)]` over `InternedStr`; `Hash` / `Eq` delegate
  • Loader dedup still hits the `Arc::ptr_eq` fast path via `as_interned_mut()`
  • No new allocations

What's left for #1163

  • Link migration (`Transaction.links`, `Document.links`) — same shape as Tag
  • `MetaValue::{Account, Currency, Tag, Link}` — still `String`, design decision deferred

Test plan

  • `cargo check --workspace --all-features --all-targets` — clean
  • `cargo clippy --workspace --all-features --all-targets -- -D warnings` — clean
  • `cargo test -p rustledger-core -p rustledger-parser -p rustledger-loader -p rustledger-query -p rustledger-validate --all-features` — 1800+ pass
  • Cross-file tag-dedup test in `rustledger-loader` still asserts `Arc` identity (now via `Tag::ptr_eq`)
  • CI full workspace + compat suite

🤖 Generated with Claude Code

Third slice of #1163. Wraps Transaction.tags and Document.tags
behind the Tag newtype. Smaller than Currency/Account because tags
only flow through the parser dedup + pushtag/poptag stack — no
hot-loop HashMap keys to migrate in tandem.

Changes:
- AST: Transaction.tags and Document.tags switch to Vec<Tag>
- with_tag constructors take impl Into<Tag>
- Parser parse_tag returns Tag; ParsedItem::Pushtag/Poptag and
  the pushtag stack thread Tag through
- Loader dedup pass uses intern_typed_vec(Tag::as_interned_mut)
  for tag slices
- Added ptr_eq method to the domain_newtype! macro so cross-file
  dedup tests can assert Arc<str> identity directly on the newtype
  instead of routing through .as_interned()

Deferred:
- Link migration (Transaction.links, Document.links) — same shape
- MetaValue::{Account,Currency,Tag,Link} — design decision deferred

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 02:20
Copilot AI review requested due to automatic review settings May 21, 2026 02:20
@codecov

codecov Bot commented May 21, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@github-actions

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 35.2ms ± 1.5ms 25.1 MB
beancount 889.6ms ± 4ms 50.6 MB
Comparison 25.3x faster 2.0x less

vs main branch (2026-05-20)

Metric main this PR Change
Time 40.2ms 35.2ms -12.4% 🟢
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

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

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 continues the domain-newtype migration (#1163) by plumbing the existing Tag newtype end-to-end through the AST, parser, and loader dedup pass, so tags are no longer represented as raw InternedStr in Transaction and Document.

Changes:

  • Migrates Transaction.tags and Document.tags from Vec<InternedStr> to Vec<Tag>, and updates with_tag APIs to accept impl Into<Tag>.
  • Updates the parser to produce and thread Tag through parse_tag, pushtag/poptag, and the pushed-tag stack application.
  • Updates loader cross-file dedup to re-intern Vec<Tag> via intern_typed_vec(..., Tag::as_interned_mut) and adds Tag::ptr_eq via the domain_newtype! macro for identity assertions in tests.

Reviewed changes

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

File Description
crates/rustledger-parser/src/parser.rs Parses tags as Tag and threads Tag through pushtag/poptag + tag stack.
crates/rustledger-loader/src/dedup.rs Re-interns Transaction.tags / Document.tags as typed identifiers during cross-file dedup.
crates/rustledger-core/src/identifiers.rs Updates docs and adds ptr_eq to domain_newtype! for pointer-identity checks.
crates/rustledger-core/src/directive.rs Switches AST tag fields and builder methods to use Tag newtype.
Comments suppressed due to low confidence (1)

crates/rustledger-parser/src/parser.rs:1767

  • apply_pushed_tags only applies the current pushtag stack to Directive::Transaction, so pushtag/poptag will never affect document directives even though Document now has a tags: Vec<Tag> field. Extend this function to also merge the stack into Directive::Document (and any other directive types that carry tags, if applicable) so pushtags behave consistently across tagged directives.
fn apply_pushed_tags(directive: &mut Directive, tag_stack: &[(rustledger_core::Tag, Span)]) {
    if tag_stack.is_empty() {
        return;
    }

    if let Directive::Transaction(txn) = directive {
        for (tag, _) in tag_stack {
            if !txn.tags.contains(tag) {
                txn.tags.push(tag.clone());
            }
        }
    }

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

@robcohen
robcohen merged commit 6cf4df1 into main May 21, 2026
41 checks passed
@robcohen
robcohen deleted the feat/tag-newtype branch May 21, 2026 02:29
robcohen added a commit that referenced this pull request May 21, 2026
)

Fourth and final newtype slice. Wraps Transaction.links and
Document.links behind the Link newtype — same shape as the Tag
migration in #1172.

Changes:
- AST: Transaction.links and Document.links switch to Vec<Link>
- with_link constructors take impl Into<Link>
- Parser parse_link returns Link
- Loader dedup pass uses intern_typed_vec(Link::as_interned_mut)
- Dropped the now-unused intern_vec helper (all four Vec<InternedStr>
  fields are typed); intern_typed_vec docs updated to cover all four
  newtypes
- Dropped the now-unused AsVecInternedStr import

Issue #1163 AST coverage is now complete (Currency/Account/Tag/Link).
MetaValue::{Account,Currency,Tag,Link} variants still carry String —
that crossing-the-typed-boundary question is a separate decision and
remains deferred.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 21, 2026
…1163) (#1174)

* refactor(core): MetaValue::{Account,Currency,Tag,Link} typed (closes #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]>

* fix(loader): extend dedup pass to canonicalize MetaValue payloads + correct 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]>

* chore: address #1174 self-review followups

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]>

---------

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.

2 participants