Skip to content

feat(core,parser,plugin): wrap inner postings in Spanned<Posting> - #1151

Merged
robcohen merged 6 commits into
mainfrom
feat/posting-span
May 19, 2026
Merged

robcohen merged 6 commits into
mainfrom
feat/posting-span

Conversation

@robcohen

@robcohen robcohen commented May 19, 2026 •

Copy link
Copy Markdown
Member

Why this PR was rewritten

The first draft of #1151 added an inline Option<Span> field to Posting. Review feedback flagged two architectural concerns:

  1. Inconsistent representation — top-level directives already use Vec<Spanned<Directive>>; tacking inline source-location fields onto inner nodes set a precedent for ad-hoc per-field metadata instead of a uniform pattern.
  2. Plugin Modify silently strips inner spans — apply_plugin_ops rebuilt postings via data_to_posting, which had no way to preserve location. Any transaction touched by a Modify plugin lost the LSP fix.

This PR reshapes the foundation to address both, with no legacy half-measures.

Design

  • Move Span / Spanned / SYNTHESIZED_FILE_ID into rustledger-core. core owns Posting; the move makes Spanned available where it is structurally needed without a layering inversion. rustledger-parser no longer owns location types.
  • Transaction.postings: Vec<Posting> → Vec<Spanned<Posting>>. Source location lives in one consistent place across the AST, matching the existing top-level Vec<Spanned<Directive>> pattern.
  • Spanned<T> gains:
    • Span::ZERO + Spanned::synthesized(value) — explicit constructors for programmatically-built postings so synthesis is always intentional.
    • Deref<Target = T> / DerefMut — Spanned<T> is a transparent wrapper (the standard library uses the same convention for Box<T>, Rc<T>, Cow<'_, T>, MutexGuard<T>). Field reads and method calls on &Spanned<Posting> work without .value boilerplate; callers reach for .span / .file_id / .value only when location is the point.
    • Value-only equality: PartialEq / Eq / Hash delegate to the inner value, so two equal Ts from different source locations compare equal. Location-sensitive equality is opt-in via .span / .file_id field comparisons.
  • Plugin wire format thread-through. PostingData gains span: Option<SourceSpan> (u64 byte offsets + u16 file_id, stable across WASM and host). posting_to_data / data_to_spanned_posting preserve location across the round-trip. Plugin Modify now retains inner posting spans automatically; only postings the plugin synthesizes get span = None on the wire.
  • File-id inheritance. The loader sets file_id on the outer Spanned<Directive> and walks the inner Spanned<Posting> entries in each transaction so each posting knows its source file without parent traversal. Hard-errors on file_id > u16::MAX so silent overflow can't masquerade as synthesis.
  • Cache version bumped 4 → 5 so existing rkyv caches (which encode the old Vec<Posting> shape) get rejected at the header instead of deserialized as junk.
  • Host-side span sanitization. apply_plugin_ops calls sanitize_inner_posting_spans on every Modify/Insert directive — any inner span whose file_id doesn't resolve in the host's SourceMap, or whose byte range exceeds the file's length, collapses to Spanned::synthesized. A misbehaving plugin cannot smuggle out-of-bounds spans into the LSP edit path. Pinned by 7 unit tests against SourceMap.

Span semantics

The posting's Spanned<Posting>.span covers the posting line itself — leading indent, optional flag, account, amount, cost, price, and same-line trailing comment. It excludes any following posting-level metadata lines so an LSP edit can replace the posting without disturbing its metadata. This is exactly the boundary the line-arithmetic anti-pattern gets wrong in #1142.

Scope discipline

Only Posting gets wrapped this round. Amount / CostSpec / MetaValue keep their current inline representation. Wrapping those is a separate refactor that should land alongside a concrete LSP feature that needs them, not preemptively.

⚠️ Breaking changes (external API)

This PR makes several intentional breaking changes; the project's policy permits them, but here is the explicit list so external users of rustledger-core / rustledger-plugin-types can migrate cleanly:

Most likely migration for downstream code: rename .with_posting(p) to .with_synthesized_posting(p) everywhere — it's a mechanical sed. The new short name with_posting(Spanned<Posting>) is reserved for callers that actually have a real source span (parsers, plugin round-trips). The compiler points you at the rename if you miss any.

What Old New Fix
Transaction::with_posting(p) (builder method, most common touchpoint) took Posting, silently wrapped with Spanned::synthesized takes Spanned<Posting>; silent synthesis got its own method sed .with_posting( → .with_synthesized_posting( in your code
Transaction.postings field type Vec<Posting> Vec<Spanned<Posting>> Direct-field callers wrap with Spanned::synthesized(p) (parser-derived postings are already wrapped)
PostingData.span (plugin wire format) did not exist Option<SourceSpan> field WASM plugins recompile against the new schema; older on-the-wire payloads decode with span = None via #[serde(default)]
SourceSpan (new type) – { start: u64, end: u64, file_id: u16 } in rustledger-plugin-types Plugins synthesizing new postings leave span = None; existing postings round-trip automatically
Spanned<T>: PartialEq / Eq / Hash derived (location-sensitive) manual impl (value-only) If you relied on location-sensitive equality, compare .span / .file_id explicitly
CACHE_VERSION 4 5 Existing .cache files are rejected at the header and rebuilt on next load

Follow-up PRs (now unblocked)

  • PR #B — sweep ~13 LSP handlers (formatting.rs, range_formatting.rs, inlay_hints.rs, call_hierarchy.rs, document_highlight.rs, selection_range.rs, etc.) to use posting.span instead of start_line + 1 + i arithmetic. Closes [Bug]: Destructive formatting on repeated metadata, LSP-only #1142.
  • PR #C — delegate inlay_hints interpolation to rustledger-booking.
  • PR #D — route execute_command::align_amounts through format_directive.
  • PR #E — currency rename via AST visitor.

Test plan

  • cargo check --workspace --all-features --all-targets
  • cargo clippy --workspace --all-features --all-targets -- -D warnings
  • cargo test --workspace --all-features — 56 test suites, 0 failures
  • cargo fmt --all -- --check
  • 5 new parser tests pin the line-span contract (line-only, metadata-excluded, trailing-comment-included, unicode account, synthesized marker).
  • 7 new loader tests pin sanitize_inner_posting_spans against the full SourceMap surface.
  • New test_load_cache_rejects_older_version pins the v4→v5 cache safety net.
  • New test_spanned_eq_ignores_location pins value-only equality + HashSet behavior.

Refs #1142

🤖 Generated with Claude Code

Copilot AI review requested due to automatic review settings May 19, 2026 00:28
@robcohen
robcohen requested a review from a team as a code owner May 19, 2026 00:28

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

Adds source-range tracking for transaction postings to enable precise, source-mapped LSP edits without relying on fragile line/offset arithmetic (foundation for fixing #1142).

Changes:

  • Introduces Posting::span: Option<Span> in rustledger-core and populates it in the parser so each parsed posting can be mapped back to its byte range.
  • Moves Span / Spanned / SYNTHESIZED_FILE_ID into rustledger-core::span (with rustledger-parser re-exporting to preserve rustledger_parser::Span call sites).
  • Updates tests and conversion layers across crates to initialize Posting { span: None } for synthesized/programmatic postings, plus adds parser tests pinning span semantics.

Reviewed changes

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

Show a summary per file
File Description
crates/rustledger-validate/tests/tla_proptest.rs Updates property-test fixtures to include Posting.span = None.
crates/rustledger-validate/src/lib.rs Updates validator unit tests to include Posting.span = None.
crates/rustledger-query/src/executor/mod.rs Updates query executor tests to include Posting.span = None.
crates/rustledger-plugin/src/convert/mod.rs Updates plugin conversion tests to include Posting.span = None.
crates/rustledger-plugin/src/convert/from_wrapper.rs Ensures wrapper→core posting conversion sets span: None.
crates/rustledger-parser/src/parser.rs Captures and assigns posting-line-only spans during parsing; adds span contract tests.
crates/rustledger-parser/src/lib.rs Removes local span module; re-exports span types/constants from rustledger-core.
crates/rustledger-ffi-wasi/src/types/input.rs Ensures FFI input conversion sets Posting.span = None.
crates/rustledger-core/src/span.rs Adds new core::span module defining Span, Spanned, and SYNTHESIZED_FILE_ID.
crates/rustledger-core/src/lib.rs Exposes pub mod span and re-exports span types/constants at crate root.
crates/rustledger-core/src/format/mod.rs Updates formatter tests to include Posting.span = None.
crates/rustledger-core/src/extract.rs Updates extraction tests to include Posting.span = None.
crates/rustledger-core/src/directive.rs Adds Posting::span field and initializes it to None in constructors/tests.

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

@github-actions

github-actions Bot commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 37.2ms ± 1.3ms 25.2 MB
beancount 773.1ms ± 29.2ms 50.7 MB
Comparison 20.8x faster 2.0x less

vs main branch (2026-05-19)

Metric main this PR Change
Time 35.4ms 37.2ms +5.1% 🟡
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 19, 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

@codecov

codecov Bot commented May 19, 2026 •

Copy link
Copy Markdown

Replaces the inline Option<Span> on Posting from the earlier draft of
this PR with a structural Vec<Spanned<Posting>>. Postings now carry
their source location with the same wrapper used for top-level
directives, threading naturally through the parser, plugin protocol,
and loader. This is the foundation for fixing issue #1142 (LSP
formatter destroys posting-level metadata) and removing the
"start_line + 1 + posting_index" anti-pattern from 13 LSP handlers.

Design

- Move Span / Spanned / SYNTHESIZED_FILE_ID from rustledger-parser
  into rustledger-core. Core owns Posting; the move makes Spanned
  available where it is structurally needed without a layering
  inversion.
- Change Transaction.postings from Vec<Posting> to
  Vec<Spanned<Posting>>. Mirrors the established Vec<Spanned<Directive>>
  pattern at the top level so source location lives in one consistent
  place, not in ad-hoc inline fields.
- Spanned<T> gains:
    * Span::ZERO and Spanned::synthesized(value) — explicit
      constructors for programmatically-built postings so synthesis is
      always intentional, never inferred from a None.
    * Deref<Target = T> / DerefMut — Spanned<T> is a transparent
      wrapper (Box<T>, Rc<T>, Cow<'_, T>, MutexGuard<T> all follow
      this convention). Field reads / method calls on
      &Spanned<Posting> just work; consumers reach for .span /
      .file_id / .value only when location is the point.

Plugin protocol

- PostingData gains span: Option<SourceSpan> on the wire. SourceSpan
  is u32 byte offsets + u16 file_id, so the encoding is stable across
  WASM (32-bit) and host (64-bit) targets.
- posting_to_data / spanned_posting_to_data preserve the span on the
  way out; data_to_spanned_posting reconstructs it on the way in.
- The loader's apply_plugin_ops Modify path now propagates inner
  posting spans through the wrapper round-trip: a plugin that edits
  one field of an existing posting keeps its source location instead
  of resetting to synthesized. Plugin-authored brand-new postings
  carry span = None on the wire and become Spanned::synthesized in
  the host.

File-id inheritance

- The loader sets file_id on the outer Spanned<Directive> via
  with_file_id and walks inner Spanned<Posting> entries in each
  transaction to set the same file_id. Postings know which file they
  came from without traversing parent pointers.

Parser

- parse_posting captures the byte range from the leading indent
  through the optional flag, account, amount, cost, price, and same-
  line trailing comment. It deliberately excludes any following
  posting-level metadata lines so an LSP edit can replace a posting
  without disturbing its metadata. This is exactly the boundary that
  the line-arithmetic approach gets wrong in issue #1142.
- parse_transaction_directive assigns parser-derived Vec<Spanned<Posting>>
  directly into txn.postings (bypassing Transaction::with_posting,
  which wraps with synthesized for programmatic callers).

Breaking change

- Public surface: Posting struct unchanged; Transaction.postings
  field changed to Vec<Spanned<Posting>>. External callers that built
  Posting directly and pushed into postings need to wrap with
  Spanned::synthesized.
- PostingData (plugin wire format) gained the span field. Existing
  WASM plugins recompile against the new schema; on-the-wire decoding
  works for old payloads via #[serde(default)].

Tests pin the contract

- test_posting_span_covers_line_only — span round-trips the posting
  line bytes, does not bleed into the next posting.
- test_posting_span_excludes_following_metadata — the #1142 scenario:
  postings with effective_date metadata interleaved, span never leaks
  into metadata bytes.
- test_posting_span_includes_trailing_comment — same-line ; comment is
  inside the span so an LSP edit replaces it atomically.
- test_posting_span_handles_unicode_account — multi-byte UTF-8 in the
  account name stays inside the span.
- test_synthesized_posting_carries_zero_span_and_synth_file_id —
  Spanned::synthesized writes Span::ZERO + SYNTHESIZED_FILE_ID so
  consumers can distinguish programmatic from parsed at the
  per-posting level.

Verified

- cargo check --workspace --all-features --all-targets
- cargo clippy --workspace --all-features --all-targets -- -D warnings
- cargo test --workspace --all-features (56 test suites, 0 failures)
- cargo fmt --all -- --check

Refs #1142

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen force-pushed the feat/posting-span branch from e1b0762 to d68b759 Compare May 19, 2026 04:11
@robcohen robcohen changed the title feat(core,parser): add Posting::span for source-mapped LSP edits feat(core,parser,plugin): wrap inner postings in Spanned<Posting> May 19, 2026
robcohen and others added 5 commits May 19, 2026 00:10
Addresses all eight findings from the deep PR review of #1151. No new
feature; just sharpening the rough edges in the foundation before
downstream PRs land on it.

Must-fix

- Bump cache header from v4 to v5. The on-disk rkyv encoding of
  Transaction.postings changed shape; without the bump, stale caches
  would deserialize as junk. The header check short-circuits and
  forces a rebuild.
- Loader propagation now hard-errors on file_id > u16::MAX instead of
  silently mapping the 65,536th file onto SYNTHESIZED_FILE_ID. Matches
  the existing debug_assert in Spanned::with_file_id.
- Sweep all literal Span::new(0, 0) callsites to Span::ZERO so the
  named constant is the single canonical way to spell the synthesis
  sentinel.

Spanned<T> semantics

- PartialEq / Eq / Hash on Spanned<T> now delegate to the inner value
  only. Two values with the same content but different source
  locations are equal. Consumers that need location-sensitive
  equality compare .span / .file_id explicitly. Pinned with
  test_spanned_eq_ignores_location plus HashSet round-trip coverage.

Wire format

- SourceSpan offsets widened from u32 to u64. The previous u32
  silently clamped at u32::MAX for files >4 GiB; u64 is
  target-portable and defensive at trivial cost.
- data_to_spanned_posting now surfaces an explicit SpanOverflow
  ConversionError on the (hypothetical) 32-bit-host overflow path
  instead of casting u64 to usize blindly.

API

- Renamed Transaction::with_posting(Posting) to
  with_synthesized_posting(Posting) and added a new
  with_posting(Spanned<Posting>) that pushes a real wrapper directly.
  Silent synthesis is now visible at every call site. All ~800
  in-tree call sites updated.
- Posting::with_cost / with_price / with_flag rustdoc cross-link
  Spanned::map for the wrapper-preserving pattern.

Plugin trust

- apply_plugin_ops now calls sanitize_inner_posting_spans on the
  inner postings of every Modify / Insert directive. Any inner span
  whose file_id doesn't resolve in SourceMap, or whose byte range
  exceeds the file's length, collapses to Spanned::synthesized. A
  misbehaving plugin can no longer smuggle out-of-bounds spans into
  the LSP edit path.

Docs

- rustledger-wasm: TS interface comment notes the deliberate
  flattening of Spanned<Posting> to plain Posting at the JS boundary.

Verified: cargo check --workspace --all-features --all-targets,
cargo clippy --workspace --all-features --all-targets -- -D warnings,
cargo test --workspace --all-features (56 suites, 0 failures),
cargo fmt --all -- --check.

Refs #1142

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Addresses the final six findings from the second review pass of #1151.

- Add 7 unit tests for sanitize_inner_posting_spans: span within file,
  span past EOF, unknown file_id, inverted start/end, synthesized
  file_id (span normalized to ZERO), boundary span == source.len(),
  and non-Transaction directives passed through unchanged. The
  function is now exercised against the full SourceMap surface
  instead of relying on integration coverage from downstream code.
- Sanitizer also normalizes any non-zero span on a synthesized
  file_id to Span::ZERO so the in-memory state matches the
  Spanned::synthesized contract instead of carrying junk in
  unconsulted fields.
- Add test_load_cache_rejects_older_version: writes a valid magic +
  CACHE_VERSION-1 header and asserts load_cache_entry returns None.
  Pins the safety net that prevents v4 caches from being fed to v5
  decoding after the Vec<Posting> -> Vec<Spanned<Posting>> shape
  change.
- Fix stale doc comment at process.rs:962: literal zero-span spelling
  switched to Span::ZERO to match the actual code path. The whole
  point of the named constant is canonicalization.
- Document on Spanned<T> that the rkyv-archived form does not
  automatically receive PartialEq/Eq either; consumers that need it
  must opt in via the rkyv compare attribute or hand-roll.
- Span::ZERO gains a doctest so the common idiom is visible at the
  constant's definition.
- SpanOverflow ConversionError doc now says "file a bug if you see
  it" instead of the vague "should only ever surface on 32-bit hosts"
  framing — the path is effectively unreachable and the error message
  should signal that to operators.

Verified: cargo check --workspace --all-features --all-targets,
cargo clippy --workspace --all-features --all-targets -- -D warnings,
cargo test --workspace --all-features (56 suites, 0 failures — incl.
7 new sanitize tests, the cache-version-mismatch test, and 2 new
Span/Spanned tests), cargo fmt --all -- --check.

Refs #1142

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Apply the three remaining nits from the latest review pass:

- start_after_end_is_reset_to_synthesized now also asserts the span
  collapses to Span::ZERO, matching the assertion pattern of its
  sibling tests (span_past_eof, unknown_file_id). The implementation
  already produced this state via Spanned::synthesized; the test
  just now pins it.
- Drop the pub(crate) on sanitize_inner_posting_spans in favor of
  plain private fn. The same-module test submodule can access parent
  items without an explicit visibility bump; the pub(crate) was a
  misconception on my part and signaled wider visibility than the
  function actually has.
- Tighten the function's rustdoc backtick coverage to satisfy
  clippy::doc-markdown (the wider clippy lint set that CI runs).

Verified: cargo check --workspace --all-features --all-targets,
cargo clippy --workspace --all-features --all-targets -- -D warnings,
cargo test -p rustledger-loader --all-features (all 7 sanitize
tests still green), cargo fmt --all -- --check.

Refs #1142

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
CI's Documentation job runs with `RUSTDOCFLAGS=-Dwarnings`, which
promotes broken intra-doc links to errors. The rustdoc I added on
the `Transaction.postings` field referenced `Spanned::synthesized`,
`Span::ZERO`, and `SYNTHESIZED_FILE_ID` as bare names, but those
items live in `crate::span` and are not in scope at the `directive`
module level. Pre-push `cargo check` doesn't trip the rustdoc link
checker, so the break only showed up in CI.

Refs #1142

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen merged commit 8c74bf7 into main May 19, 2026
41 checks passed
@robcohen
robcohen deleted the feat/posting-span branch May 19, 2026 20:55
robcohen added a commit that referenced this pull request May 19, 2026
…1142) (#1156)

* fix(lsp): use posting.span in formatters, preserving metadata (closes #1142)

The document-formatting and range-formatting handlers computed each
posting's line as `txn_start_line + 1 + posting_idx`. That assumption
breaks the moment a transaction has posting-level metadata interleaved
between postings — e.g., the `effective_date:` plugin convention:

```
2024-01-15 * "Test"
  Assets:Bank  -50.00 USD
    effective_date: 2024-01-20
  Expenses:Food  50.00 USD
    effective_date: 2024-01-21
```

The second posting is on line 3, not line 2 (line 2 is the metadata
line). The handlers emitted a posting-shaped `TextEdit` targeting
line 2, overwriting the metadata. The reporter saw the file silently
mangled every time their editor (e.g., nvim) ran format-on-save.

The fix uses the per-posting source span landed by PR #1151
(`Vec<Spanned<Posting>>`): convert `spanned_posting.span.start` to a
line number directly. The assumption that postings sit on consecutive
lines is gone.

What changed:

- `handlers/formatting.rs` and `handlers/range_formatting.rs` now
  iterate `txn.postings` as `&[Spanned<Posting>]`, look up each
  posting's line via `byte_offset_to_position(source, p.span.start)`,
  and skip plugin-synthesized postings (`file_id ==
  SYNTHESIZED_FILE_ID`) which have no source location to format.

Regression tests pin the contract:

- Both handlers get a `test_*_preserves_interleaved_metadata_1142`
  test that builds the canonical `effective_date:` source, runs the
  handler, and asserts no emitted edit targets a metadata line.
- I verified the test fails against the pre-fix code by applying
  the test alone against the buggy implementation: it caught the bug
  exactly where reported.

Out of scope for this PR (audit-identified follow-ups):

The same `start_line + 1 + i` anti-pattern lives in 11 other LSP
handlers (`call_hierarchy`, `document_highlight`, `selection_range`,
`linked_editing`, `code_actions`, `code_lens`, `inlay_hints`,
`document_color`, `execute_command`, `references`, `on_type_formatting`,
`symbols`). Those handlers are read-only — they produce wrong
highlights, hovers, etc. but cannot corrupt files. They warrant their
own audit + tests + PR rather than a blind sweep here.

Closes #1142

Verified: cargo check --workspace --all-features --all-targets,
cargo clippy --workspace --all-features --all-targets -- -D warnings,
RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps,
cargo test -p rustledger-lsp --all-features (130 tests, 0 failures),
cargo fmt --all -- --check.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(lsp): strengthen #1142 regression coverage + clarify synth-skip comment

Apply review nits on PR #1156.

Tests

- formatting.rs's `test_*_preserves_interleaved_metadata_1142` gains a
  positive assertion: at least one edit must target a real posting
  line. The previous negative-only assertion would pass for a
  degenerate formatter that emits zero edits, so the regression net
  didn't catch a future short-circuit. The negative assertion (no
  metadata line touched) stays for the #1142 contract itself.

- range_formatting.rs gets a new companion test
  `test_range_formatting_fixes_misindented_posting_without_touching_metadata`
  that feeds a misindented posting interleaved with metadata. The
  fixer should emit an edit at the misindented posting line and
  leave the metadata alone — together with the existing all-correct
  regression test, the pair pin both "don't break #1142" and "still
  do useful work."

- range_formatting.rs's all-correct regression test now explicitly
  documents why it has no positive assertion (the source is already
  well-formatted; an empty edit set is the correct outcome).

Comments

- Both handlers' `SYNTHESIZED_FILE_ID` skip got a more accurate
  comment. The branch is dead code in today's LSP path
  (parse-driven, single-file), but documents the defensive intent
  for future code that might feed loader/plugin output through these
  handlers.

Refs #1142

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* perf(lsp): use LineIndex in formatters; address Copilot review

Copilot review on PR #1156 flagged that the new per-posting span
lookups in the two formatting handlers were calling the naive O(n)
`byte_offset_to_position` scanner on every iteration, which can
become quadratic on large files (file_len × postings).

Fix: build a single `LineIndex` at the top of each handler. The
index is O(n) to construct once, then each `offset_to_position`
lookup is O(log lines). Same approach other handlers already use.

Also addressed:

- Doc-comment nit in the regression test: said metadata lines were
  matched "after four-space indent" but the check actually uses
  `trim_start()` which accepts any indent. Comment updated to
  describe the actual behavior and note the canonical form.

Verified: cargo check --workspace --all-features --all-targets,
cargo clippy --workspace --all-features --all-targets -- -D warnings,
RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps,
cargo test -p rustledger-lsp --all-features (130 tests, 0 failures,
including all 4 #1142 regression tests still green),
cargo fmt --all -- --check.

Refs #1142

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

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

* fix(lsp): use posting.span in formatters, preserving metadata (closes #1142)

The document-formatting and range-formatting handlers computed each
posting's line as `txn_start_line + 1 + posting_idx`. That assumption
breaks the moment a transaction has posting-level metadata interleaved
between postings — e.g., the `effective_date:` plugin convention:

```
2024-01-15 * "Test"
  Assets:Bank  -50.00 USD
    effective_date: 2024-01-20
  Expenses:Food  50.00 USD
    effective_date: 2024-01-21
```

The second posting is on line 3, not line 2 (line 2 is the metadata
line). The handlers emitted a posting-shaped `TextEdit` targeting
line 2, overwriting the metadata. The reporter saw the file silently
mangled every time their editor (e.g., nvim) ran format-on-save.

The fix uses the per-posting source span landed by PR #1151
(`Vec<Spanned<Posting>>`): convert `spanned_posting.span.start` to a
line number directly. The assumption that postings sit on consecutive
lines is gone.

What changed:

- `handlers/formatting.rs` and `handlers/range_formatting.rs` now
  iterate `txn.postings` as `&[Spanned<Posting>]`, look up each
  posting's line via `byte_offset_to_position(source, p.span.start)`,
  and skip plugin-synthesized postings (`file_id ==
  SYNTHESIZED_FILE_ID`) which have no source location to format.

Regression tests pin the contract:

- Both handlers get a `test_*_preserves_interleaved_metadata_1142`
  test that builds the canonical `effective_date:` source, runs the
  handler, and asserts no emitted edit targets a metadata line.
- I verified the test fails against the pre-fix code by applying
  the test alone against the buggy implementation: it caught the bug
  exactly where reported.

Out of scope for this PR (audit-identified follow-ups):

The same `start_line + 1 + i` anti-pattern lives in 11 other LSP
handlers (`call_hierarchy`, `document_highlight`, `selection_range`,
`linked_editing`, `code_actions`, `code_lens`, `inlay_hints`,
`document_color`, `execute_command`, `references`, `on_type_formatting`,
`symbols`). Those handlers are read-only — they produce wrong
highlights, hovers, etc. but cannot corrupt files. They warrant their
own audit + tests + PR rather than a blind sweep here.

Closes #1142

Verified: cargo check --workspace --all-features --all-targets,
cargo clippy --workspace --all-features --all-targets -- -D warnings,
RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps,
cargo test -p rustledger-lsp --all-features (130 tests, 0 failures),
cargo fmt --all -- --check.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(lsp): strengthen #1142 regression coverage + clarify synth-skip comment

Apply review nits on PR #1156.

Tests

- formatting.rs's `test_*_preserves_interleaved_metadata_1142` gains a
  positive assertion: at least one edit must target a real posting
  line. The previous negative-only assertion would pass for a
  degenerate formatter that emits zero edits, so the regression net
  didn't catch a future short-circuit. The negative assertion (no
  metadata line touched) stays for the #1142 contract itself.

- range_formatting.rs gets a new companion test
  `test_range_formatting_fixes_misindented_posting_without_touching_metadata`
  that feeds a misindented posting interleaved with metadata. The
  fixer should emit an edit at the misindented posting line and
  leave the metadata alone — together with the existing all-correct
  regression test, the pair pin both "don't break #1142" and "still
  do useful work."

- range_formatting.rs's all-correct regression test now explicitly
  documents why it has no positive assertion (the source is already
  well-formatted; an empty edit set is the correct outcome).

Comments

- Both handlers' `SYNTHESIZED_FILE_ID` skip got a more accurate
  comment. The branch is dead code in today's LSP path
  (parse-driven, single-file), but documents the defensive intent
  for future code that might feed loader/plugin output through these
  handlers.

Refs #1142

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* perf(lsp): use LineIndex in formatters; address Copilot review

Copilot review on PR #1156 flagged that the new per-posting span
lookups in the two formatting handlers were calling the naive O(n)
`byte_offset_to_position` scanner on every iteration, which can
become quadratic on large files (file_len × postings).

Fix: build a single `LineIndex` at the top of each handler. The
index is O(n) to construct once, then each `offset_to_position`
lookup is O(log lines). Same approach other handlers already use.

Also addressed:

- Doc-comment nit in the regression test: said metadata lines were
  matched "after four-space indent" but the check actually uses
  `trim_start()` which accepts any indent. Comment updated to
  describe the actual behavior and note the canonical form.

Verified: cargo check --workspace --all-features --all-targets,
cargo clippy --workspace --all-features --all-targets -- -D warnings,
RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps,
cargo test -p rustledger-lsp --all-features (130 tests, 0 failures,
including all 4 #1142 regression tests still green),
cargo fmt --all -- --check.

Refs #1142

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(lsp): sweep read-only handlers to use posting.span (refs #1142)

Follow-up to #1156: extends the per-posting-span lookup pattern from
the formatting handlers to seven read-only handlers that had the same
`txn_start_line + 1 + posting_idx` anti-pattern. These handlers
produced wrong line numbers — but not file corruption — whenever a
transaction had posting-level metadata interleaved between postings
(e.g., the `effective_date:` plugin convention).

Symptom per handler before this PR:

- document_highlight: account highlights for the second posting
  landed on its metadata line instead of the posting line.
- references / find-references: range pointed at the metadata line,
  so jumping to a reference scrolled the editor to the wrong row.
- inlay_hints: inferred-amount overlay sat one row too high.
- selection_range: cursor-expand selected the metadata line as the
  posting body.
- symbols: outline-view ranges for postings pointed at metadata.
- call_hierarchy: incoming/outgoing call ranges pointed at metadata,
  and the transaction's outer range under-counted lines because the
  `txn_line + postings.len() + 1` heuristic ignored metadata rows.
- document_color: amount color decorations rendered on the wrong row.
- linked_editing: rename-linked ranges pointed at metadata lines.

What changed:

- Each handler now iterates `&[Spanned<Posting>]` and looks up the
  posting's line from `byte_offset_to_position(source, p.span.start)`
  or via the pre-built `LineIndex` where one already exists.
- Plugin-synthesized postings (file_id == SYNTHESIZED_FILE_ID) are
  skipped explicitly (defensive — the LSP parses single files in
  practice, but consistent with the formatters).
- call_hierarchy's transaction-range also uses `spanned.span.end`
  instead of the `txn_line + postings.len() + 1` heuristic.

Regression tests pin the contract for the three highest-impact
handlers — `document_highlight`, `references`, `inlay_hints`. Each
runs the canonical `effective_date:` source and asserts no result
lands on a metadata line, plus a positive assertion that the real
posting lines are surfaced. The remaining handlers ride on the same
mechanical pattern; their tests can be added incrementally if a
specific handler regresses.

Out of scope for this PR (genuine false positives in earlier audit):

- `code_actions.rs` — the only matching grep hit was a window-search
  heuristic (`range.start.line + 10`), not posting arithmetic.
- `on_type_formatting.rs` / `execute_command.rs` — matches were for
  `is_posting_line()` content classifiers, not line indexing.

Verified: cargo check --workspace --all-features --all-targets,
cargo clippy --workspace --all-features --all-targets -- -D warnings,
RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps,
cargo test -p rustledger-lsp --all-features (134 tests, 0 failures —
including 3 new #1142 regression tests, plus the existing 2 from
#1156), cargo fmt --all -- --check.

Refs #1142

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(lsp): drop unused start_line binding in references handler

CI's `Check` and `Doctests` jobs run with `RUSTFLAGS=-Dwarnings`,
which promotes `unused_variables` to an error. After PR #1157's
switch from `txn_start_line + 1 + i` arithmetic to per-posting span
lookup, the `start_line` binding in `collect_account_references` was
no longer read — every Transaction case derives its line from the
posting's own span, and the non-Transaction cases use
`spanned.span.start` directly via `find_in_directive`.

Local cargo check passes because the workspace's `.envrc` doesn't
set `RUSTFLAGS=-Dwarnings`; this is the same gap memorialized in
`feedback_check_cargo_doc_locally.md`. The two-file form of pre-push
verification I should be running for these LSP sweeps is:

    cd worktree
    RUSTFLAGS=-Dwarnings cargo build -p rustledger-lsp --all-features
    RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps

Refs #1142

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* perf(lsp): LineIndex in 4 handlers + fix call_hierarchy off-by-one

Apply Copilot review on PR #1157.

Performance (4 handlers): each posting/directive lookup previously
called `byte_offset_to_position` which is an O(n) scan; on a large
file with many transactions this scaled quadratically. Builds a
single `LineIndex` per request and threads it into the collect
helpers so every offset→line conversion is O(log lines):

- `inlay_hints.rs`
- `document_highlight.rs` (account / currency / payee collectors)
- `linked_editing.rs` (account / currency collectors)
- `references.rs` (account / currency / payee collectors + the
  `find_in_directive` helper that was called per-directive)

Correctness:

- `call_hierarchy.rs` transaction range was off-by-one. The previous
  fix used `spanned.span.end → (line, _).saturating_add(1)`, but
  `span.end` is *exclusive* and for newline-terminated transactions
  the resulting line is already the next line. Now: use the end
  line directly when `end_col == 0`, only round up when the span
  ends mid-line. Otherwise the call-hierarchy item range extended
  into the following directive.

Dead-code cleanup:

- Removed `let _ = line;` in `call_hierarchy::handle_outgoing_calls`
  — `line` is used at the enclosing scope's `if line != txn_line`
  check, so the suppression was a misread of the closure's capture
  rules.
- Removed `let _ = dir_range;` in `selection_range` — `dir_range` is
  the match binding and was destined to be used later in the
  hierarchy builder; the suppression hid an inert binding rather
  than silencing a real warning.

Verified: cargo check --workspace --all-features --all-targets,
RUSTFLAGS=-Dwarnings cargo build --workspace --all-features --all-targets,
cargo clippy --workspace --all-features --all-targets -- -D warnings,
RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps,
cargo test -p rustledger-lsp --all-features (134 tests, 0 failures),
cargo fmt --all -- --check.

Refs #1142

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

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

* refactor(lsp): align_amounts command delegates to formatting handler

`execute_command::rledger.alignAmounts` had its own bespoke posting-
alignment pipeline: a regex-style line scanner, an "Assets/Liabilities/
Equity/Income/Expenses" prefix check to identify posting lines, and a
"max-existing-column" alignment heuristic. It produced visibly
different output than the canonical paths:

- `rledger format` (CLI, uses `rustledger_core::format::format_directive`).
- `textDocument/formatting` (LSP, uses `handlers::formatting::handle_formatting`).

It also pre-dates #1142 and #1151 — so it didn't benefit from any of:

- Per-posting source spans (the bespoke line scanner can't see
  posting-level metadata interleaved between postings, just like the
  pre-#1142 formatting handlers).
- The shared `LineIndex` (#1157 perf fix) — every alignment computed
  its own line positions from scratch.

This commit deletes the bespoke pipeline and delegates to
`handle_formatting`. The command now inherits every formatter fix
automatically:

- Per-posting span lookup preserves interleaved metadata (#1142).
- Single `LineIndex` per request → O(log lines) offset lookups.
- Posting-line detection comes from the parsed AST, not a
  hard-coded account-prefix list (custom account roots from
  `option "name_assets" ...` now work).
- Plugin-synthesized postings (`file_id == SYNTHESIZED_FILE_ID`)
  are skipped consistently.

Removed code:

- `handle_align_amounts`'s 80-line scanner.
- `is_posting_line` / `find_amount_position` helpers (dead after
  the scanner was removed; the on_type_formatting handler has its
  own `is_posting_line` copy and is unaffected).
- Their two unit tests, replaced by one delegation smoke test that
  verifies both the misaligned-source and already-aligned shapes.

Verified: cargo check --workspace --all-features --all-targets,
RUSTFLAGS=-Dwarnings cargo build --workspace --all-features --all-targets,
cargo clippy --workspace --all-features --all-targets -- -D warnings,
RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps,
cargo test -p rustledger-lsp --all-features (133 tests, 0 failures),
cargo fmt --all -- --check.

Refs #1142

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* refactor(lsp,core): unify LSP and CLI formatters via core::format_posting

Closes the deeper duplication this PR's first round only partially
removed. The LSP's `handle_formatting` had its own bespoke
`format_posting_line` with two latent problems:

1. **Column mismatch.** Hardcoded `AMOUNT_COLUMN = 50` constant in
   the LSP vs `FormatConfig::default().amount_column = 60` in core.
   `rledger format` (CLI, via `format_directive` → `format_posting`)
   wrote amounts to column 60 on disk; the editor's
   `textDocument/formatting` and `rledger.alignAmounts` produced
   column 50. The two never agreed.

2. **Silent data-shape loss.** The LSP's hand-rolled formatter
   handled only the account + units. It did NOT format cost specs
   (`{...}`) or price annotations (`@`/`@@`). For postings that
   carried them, the resulting "formatted" string was a strict
   subset of the source, the surrounding `needs_alignment` heuristic
   correctly refused to emit an edit (the tokenization didn't
   match), and the upshot was that **the LSP formatter silently
   never realigned cost-bearing or priced postings**.

This commit:

- Exports `rustledger_core::format::format_posting` (was
  module-private). It's the same function that `format_directive`
  already uses internally for posting rendering.
- Rewrites the LSP's `format_posting_line` to a thin wrapper around
  `format_posting`: format the posting via the core formatter using
  `FormatConfig::default()`, compare to the source line trimmed of
  trailing whitespace (which a separate pass strips), emit a
  TextEdit if they differ. The bespoke alignment math, the
  `needs_alignment` helper, and the `AMOUNT_COLUMN` constant are
  gone.
- Updates the `rledger.alignAmounts` command's docstring to reflect
  that all three formatting paths (CLI, LSP format, LSP align)
  share one source of truth.

Test:

- `test_align_amounts_produces_canonical_alignment` (replaces the
  earlier shape-only smoke test) applies the emitted edits to the
  source and asserts the amount column matches
  `FormatConfig::default().amount_column`. Pins the contract that
  the three paths agree on alignment.

Verified: cargo check --workspace --all-features --all-targets,
RUSTFLAGS=-Dwarnings cargo build --workspace --all-features --all-targets,
cargo clippy --workspace --all-features --all-targets -- -D warnings,
RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps,
cargo test -p rustledger-lsp --all-features (133 tests, 0 failures),
cargo fmt --all -- --check.

Refs #1142

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs(lsp): clarify executeCommand can't carry client formatting options

Address Copilot review on PR #1158.

The previous comment claimed the synthesized `DocumentFormattingParams`
would let "future option-driven behavior land automatically", which
isn't true: `workspace/executeCommand` doesn't carry the client's
formatting preferences — those only travel with
`textDocument/formatting`. If `handle_formatting` ever honors
`params.options`, this command will keep using server defaults and
silently diverge.

The honest fix is documenting that, plus a forward-looking note that
the right solution (when this matters) is plumbing a server-wide
`FormatConfig` through both handlers, not mirroring a client value
this command can't actually see.

Refs #1142

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(lsp,core): preserve trailing comments via shared format_posting_line

The previous commit on this PR unified the LSP formatter with the
core formatter by routing through `format_posting`. That fixed the
column-mismatch and cost/price-drop bugs but introduced a new
data-loss regression: `format_posting` returns just account + amount
+ cost + price, omitting trailing comments. Any posting like

    Assets:Bank  -50.00 USD  ; my comment

now had its source line replaced with a `format_posting` output that
silently dropped `; my comment`. The previous bespoke LSP formatter
accidentally avoided this via its `needs_alignment` heuristic
(whitespace-token compare); my unification removed the heuristic
without restoring an equivalent guard.

Fix: extract `format_posting_line` in core that wraps
`format_posting` and appends the first same-line trailing comment
(matching what `format_transaction` already does inline). Both the
on-disk path (`format_transaction`) and the LSP edit path now call
the same helper. One source of truth for "what does a posting line
look like as one line".

Changes:

- `rustledger_core::format::format_posting_line` (new public fn) —
  wraps `format_posting` + appends `posting.trailing_comments[0]`.
- `format_transaction` in core uses it instead of the inline
  `if let Some(trailing) = ... writeln!(...)` block.
- LSP's `posting_text_edit` (renamed from the colliding
  `format_posting_line`) now calls
  `rustledger_core::format_posting_line`.

Test:

- `test_formatting_preserves_trailing_comment_on_posting` — feeds a
  misindented posting with a same-line `; comment`, asserts the
  resulting `TextEdit`'s `new_text` still contains the comment.
  Verified to FAIL against the bad version (calling `format_posting`
  directly).

Verified: cargo test -p rustledger-lsp -p rustledger-core
--all-features (134 LSP + 305 core, 0 failures);
cargo clippy --workspace --all-features --all-targets -- -D warnings;
RUSTFLAGS=-Dwarnings cargo build --workspace --all-features --all-targets;
RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps;
cargo fmt --all -- --check.

Refs #1142

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* refactor(lsp): extract format_document with shared FormatConfig helper

Address review item 2 (options divergence between handlers).

The previous shape had `handle_align_amounts` synthesizing a
`DocumentFormattingParams` with `options: Default::default()` and
passing it to `handle_formatting`. That hid the fact that the
executeCommand path has NO client formatting options to honor — it
just inherited whatever interpretation `handle_formatting` placed on
the synthetic default. The moment `handle_formatting` learned to
read `params.options`, the two paths would diverge silently.

Fix:

- Split `handle_formatting` into two functions:
  * `handle_formatting(params, source, parse_result)` — the LSP
    protocol wrapper, takes the client's `DocumentFormattingParams`,
    resolves a `FormatConfig` from `params.options` via
    `document_format_config(Some(...))`.
  * `format_document(source, parse_result, &FormatConfig)` — the
    pure formatting body, takes an already-resolved config.

- New `handlers::utils::document_format_config(opts: Option<&FormattingOptions>) -> FormatConfig`
  is the single place that maps LSP options → `FormatConfig`. Today
  it ignores `opts` and returns `FormatConfig::default()`; when
  server-config plumbing lands, that one function changes. The
  `Some` / `None` distinction is preserved so the helper can fall
  back to server defaults when the executeCommand path provides no
  client value.

- `handle_align_amounts` now calls
  `format_document(source, parse_result, &document_format_config(None))`
  directly — no more fake `DocumentFormattingParams`. The `None`
  literally encodes "no client options here," and the comment
  documents why.

This contains the divergence risk to a single function (the helper)
and a single boolean (`Some`/`None`). When the LSP server gains real
config, both paths benefit automatically.

Verified: cargo test -p rustledger-lsp --all-features (134 tests, 0
failures); cargo clippy --workspace --all-features --all-targets --
-D warnings; RUSTFLAGS=-Dwarnings cargo build --workspace
--all-features --all-targets; RUSTDOCFLAGS=-Dwarnings cargo doc
--workspace --no-deps; cargo fmt --all -- --check.

Refs #1142

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 21, 2026
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 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]>
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.

[Bug]: Destructive formatting on repeated metadata, LSP-only

2 participants