Skip to content

fix!: round-18/19/20 deep-review hardening (LSP encoding, ShiftSpans trait, FFI v2) - #1247

Merged
robcohen merged 1 commit into
mainfrom
wip/round-18-19-20-deep-review-hardening
Jun 2, 2026
Merged

robcohen merged 1 commit into
mainfrom
wip/round-18-19-20-deep-review-hardening

Conversation

@robcohen

@robcohen robcohen commented Jun 2, 2026 •

Copy link
Copy Markdown
Member

Summary

Follow-up to #1244. The original PR was a one-shot fix for rledger format vs bean-format byte divergence (issue #1242) but accumulated 20 rounds of iterative deep review. The first 17 rounds landed in #1244. Rounds 18, 19, and 20 were in the working tree at merge time but uncommitted, so they did not make the squash. This PR lands them.

All findings here originated from deep-review passes that exercised the same areas #1244 touched (LSP, parser, FFI, core span machinery). They are the architectural hardening that the format-compat work surfaced.

Changes by area

rustledger-core: ShiftSpans trait with compile-time discipline

Replaces the prior open-coded shift_metadata free function plus wildcard Self::X(_) | Self::Y(_) => {} no-op arms with a ShiftSpans trait, per-variant binding patterns (Self::Variant(v) => v.shift_spans(shift)), and a HashMap<K, V, S> blanket impl. A new Spanned<T> field on any variant now compiles only after its impl shifts the span. The discipline is enforced at the type level.

rustledger-lsp: encoding-correct positions across every handler

  • LineIndex with negotiated PositionEncoding. Every handler that emits a Position or Range now threads UTF-8 / UTF-16 negotiation through a single encoding-aware index (offset_to_position, position_to_offset, byte_in_line_to_position). Lazy ropey::Rope for UTF-16 (never built under UTF-8 negotiation).
  • byte_in_line_to_position helper. Collapses the recurring line.find(needle) then emit Position pattern that previously emitted raw byte offsets as columns (wrong under UTF-16 on non-ASCII). Strictly rejects byte offsets that overshoot the addressed line, instead of silently routing to the next line via the source-len clamp.
  • 30+ handlers migrated: call_hierarchy, references, document_highlight, linked_editing, rename, type_hierarchy, selection_range, code_actions, document_color, on_type_formatting, semantic_tokens, and others.
  • Typed DispatchError enum. Request dispatch now routes via MethodNotFound / DuplicateInitialize / Handler variants instead of msg.starts_with(...) prefix-string matching.
  • Duplicate initialize rejection. Per LSP 3.17 §Lifecycle, a second initialize is a protocol violation; previously the server silently rebuilt a stripped ServerCapabilities (downgrading the session). Now returns InvalidRequest.
  • BOM CodeAction dedup. Multiple BomInDirectiveBody errors at the same offset collapse into one quick-fix via BTreeSet<usize>.
  • Currency and account collectors walk the parser's currency_occurrences index. Replaces bespoke string-search that mutated currency-substrings inside payee strings and account names (linked-edit, rename, and highlight were corrupting unrelated text as the user typed).

rustledger-parser: BOM handling and exhaustiveness

  • Mid-file BOM tolerated as lexer error. Preserves following-line indentation when a Windows-encoded include is concatenated.
  • ParseError::every_kind_sample exhaustive. Gated by a compile-time-exhaustive variant_index match so new variants can't silently slip out of the sample list.
  • Format module. Companion pretty-printer kept in sync with the new formatter.

rustledger-ffi-wasi: API v2.0 (breaking)

API_VERSION bumped from 1.0 to 2.0 to mark the ParseErrorEntry.error.data.errors wire-shape break. CHANGELOG, README, OpenRPC schema, and tests updated.

Breaking change

FFI-WASI API_VERSION bumped to 2.0. ParseErrorEntry.error.data.errors is now an object array; consumers pinned to the 1.x string-array shape must update.

How to test

  • cargo test --all-features: full workspace, 2925 tests, zero failures
  • cargo test -p rustledger-lsp --all-features: 192 LSP tests including test_byte_in_line_to_position_strict_overshoot, dispatch_error_codes, dispatch_error_display, and the round-trip encoding coverage suite under both UTF-8 and UTF-16
  • cargo test -p rustledger-core --all-features: pins metadata_shift_spans_dispatches_via_value_impl for the trait wiring

Test plan

  • cargo test --all-features: workspace-wide, 2925 passed / 0 failed
  • cargo clippy --all-features --all-targets -- -D warnings: clean
  • cargo fmt --all -- --check: clean
  • RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps --all-features: clean

Follow-up to #1244.

🤖 Generated with Claude Code

@robcohen
robcohen requested a review from a team as a code owner June 2, 2026 09:05
Copilot AI review requested due to automatic review settings June 2, 2026 09:05

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

Lands rounds 18–20 of deep-review hardening from #1244 that were in the working tree but missed the squash: a ShiftSpans trait that enforces span-shifting discipline at the type level in rustledger-core, encoding-correct Position/Range emission across all LSP handlers via threaded PositionEncoding, BOM tolerance and exhaustive ParseError sampling in the parser, and a breaking FFI bump to API v2.0 for the ParseErrorEntry wire shape.

Changes:

  • Core: ShiftSpans trait + impl_shift_spans_noop! macro with per-variant binding patterns, making any new Spanned<T> field a compile-time error until its shift impl is added.
  • LSP: LineIndex::new(source, encoding) and byte_in_line_to_position threaded through ~30 handlers; typed DispatchError; duplicate-initialize rejection; BOM CodeAction dedup; ranges_overlap semantics aligned to LSP half-open.
  • FFI: API_VERSION 1.0 → 2.0 with ParseErrorEntry[] structured error.data.errors; path_security opt-out on ledger.loadFile; format_source_to_response shared by format.source/format.file; documented -32000 vs -32700 separation.

Reviewed changes

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

Show a summary per file
File Description
supply-chain/{imports.lock,config.toml} Promote either from exemption to audited via Google/Mozilla deltas.
Cargo.toml, Cargo.lock Pin ropey to cr_lines-only (match similar line semantics); add similar workspace dep; tempfile dev-dep for ffi-wasi tests.
crates/rustledger/src/cmd/{format,extract_cmd,add_cmd}/*.rs Use new Alignment/format_directives/format_source path; -c becomes optional with auto-default.
crates/rustledger/tests/format_compat.rs + fixtures Golden + idempotence + live bean-format parity tests for #1242.
crates/rustledger-core/src/lib.rs Re-export Alignment, FormatLine, format_directives, ShiftSpans, etc.
crates/rustledger-core/src/span.rs New ShiftSpans trait, blanket impls, impl_shift_spans_noop! macro, and rationale for not marking Span/Spanned non_exhaustive.
crates/rustledger-core/src/format/{transaction,directives}.rs Two-phase formatter: *_lines render phase + render_lines align phase.
crates/rustledger-core/src/synthetic/edge_cases.rs, tests/synthetic_generation.rs Update synthetic generation/tests to new format API.
crates/rustledger-loader/src/phase.rs Replace clippy #[allow] with explanatory comment for non-const into_inner.
crates/rustledger-parser/src/{lib,error,bom}.rs, CHANGELOG.md New bom module, has_leading_bom, BomInDirectiveBody variant, exhaustive every_kind_sample, #[non_exhaustive] on result/error types.
crates/rustledger-parser/tests/parser_integration_test.rs Use format_directives in round-trip test.
crates/rustledger-lsp/Cargo.toml Add similar dep for formatting line-diff.
crates/rustledger-lsp/src/server.rs Thread PositionEncoding from negotiation into main loop.
crates/rustledger-lsp/src/handlers/*.rs Thread encoding into ~30 handlers; replace raw byte-col emission with byte_in_line_to_position; share ranges_overlap via utils.
crates/rustledger-lsp/tests/encoding_coverage.rs New end-to-end round-trip test exercising handlers under both UTF-8 and UTF-16.
crates/rustledger-wasm/src/{api,parsed_ledger,types}.rs Use format_source for whole-file formatting; doc fix for TypedValueJson.
crates/rustledger-wasm/bindings/{types.py,index.schema.json} Sync regenerated bindings doc-string.
crates/rustledger-ffi-wasi/src/lib.rs, CHANGELOG.md, README.md, openrpc.json API_VERSION 1.0 → 2.0; document ParseErrorEntry shape; path_security schema.
crates/rustledger-ffi-wasi/src/jsonrpc/{router,response,request,error,mod}.rs Shared format_source_to_response; beancount_parse_error (-32000) vs parse_error (-32700) split; stdin IO failure now internal_error; path_security param plumbed to Loader::with_path_security.
crates/rustledger-ffi-wasi/Cargo.toml + tests/{openrpc_kind_code_sync,load_file_path_security}.rs New tests pin openrpc.json ↔ ParseErrorKind sync and path_security opt-in/opt-out behavior.

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

…rge)

Captures the round-18/19/20 deep-review work that was in the working
tree of the #1244 PR branch but never committed, so it did not land
in the squash-merge. Preserved on its own branch as a starting point
for a follow-up PR.

Scope (~47 files, +4382/-1084):

rustledger-core:
- ShiftSpans trait with per-variant binding discipline
- HashMap<K, V, S> blanket impl, replacing open-coded shift_metadata

rustledger-lsp:
- LineIndex with negotiated PositionEncoding (UTF-8/UTF-16) and lazy
  ropey::Rope (OnceCell, never built under UTF-8)
- byte_in_line_to_position helper with strict overshoot rejection
- 30+ handlers migrated for encoding-aware positions
- DispatchError typed enum replacing prefix-string routing
- Duplicate initialize rejection per LSP 3.17 §Lifecycle
- BOM CodeAction dedup via BTreeSet<usize>
- Currency/account collectors walk parser currency_occurrences index

rustledger-parser:
- Mid-file BOM tolerated as lexer error preserving following indent
- ParseError::every_kind_sample exhaustive via variant_index match

rustledger-ffi-wasi:
- API_VERSION 1.0 -> 2.0 wire-shape bump (breaking)

Verified pre-stash: cargo test --all-features (workspace, zero failures),
clippy -D warnings clean, fmt clean, rustdoc clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen force-pushed the wip/round-18-19-20-deep-review-hardening branch from b336388 to cb3fb73 Compare June 2, 2026 09:09
@robcohen
robcohen merged commit db104e5 into main Jun 2, 2026
40 of 41 checks passed
@robcohen
robcohen deleted the wip/round-18-19-20-deep-review-hardening branch June 2, 2026 09:15
@github-actions

github-actions Bot commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 31.6ms ± 0.6ms 25 MB
beancount 863.7ms ± 7.8ms 50.7 MB
Comparison 27.3x faster 2.0x less

vs main branch (2026-06-02)

Metric main this PR Change
Time 33.9ms 31.6ms -6.8% 🟢
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 Jun 2, 2026

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 791
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.

2 participants