Repository navigation
fix(lsp): use posting.span in formatters, preserving metadata (closes #1142) - #1156
Merged
Merged
Conversation
…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]>
Contributor
There was a problem hiding this comment.
Pull request overview
This PR fixes a destructive LSP formatting bug where posting TextEdits could be applied to the wrong lines when posting-level metadata is interleaved between postings (e.g., effective_date:), by using each posting’s own source span instead of txn_start_line + 1 + posting_idx.
Changes:
- Update document-formatting and range-formatting handlers to derive
posting_linefromSpanned<Posting>.span.startand skip synthesized postings (SYNTHESIZED_FILE_ID). - Add regression tests ensuring no formatter edit targets metadata lines for the canonical interleaved-metadata scenario from #1142.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| crates/rustledger-lsp/src/handlers/formatting.rs | Use per-posting spans for edit positioning; add #1142 regression test for document formatting. |
| crates/rustledger-lsp/src/handlers/range_formatting.rs | Use per-posting spans for edit positioning; add #1142 regression test for range formatting. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Contributor
📊 Benchmark Results
vs main branch (2026-05-19)
What do these numbers mean?
|
Contributor
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
…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]>
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]>
robcohen
enabled auto-merge (squash)
May 19, 2026 21:44
5 tasks done
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]>
This was referenced May 20, 2026
This was referenced Jun 3, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Closes #1142.
The LSP's document-formatting and range-formatting handlers computed each posting's source line as
txn_start_line + 1 + posting_idx. That works only when postings sit on consecutive lines — and breaks the moment a transaction has posting-level metadata interleaved between postings, as theeffective_date:plugin convention does:The second posting is on line 3, not line 2. The handlers emitted a posting-shaped
TextEdittargeting line 2, overwriting the metadata line with formatted posting content. The reporter saw the file silently mangled every time their editor (nvim, VS Code, etc.) ran format-on-save.The fix uses the per-posting source span landed by #1151 (
Vec<Spanned<Posting>>): look up each posting's line directly fromspanned.span.start. The line-arithmetic assumption is gone.What changed
handlers/formatting.rsandhandlers/range_formatting.rsnow iteratetxn.postingsas&[Spanned<Posting>], derive each posting's line viabyte_offset_to_position(source, p.span.start), and skip plugin-synthesized postings (file_id == SYNTHESIZED_FILE_ID) which have no source location.Regression tests pin the contract
test_*_preserves_interleaved_metadata_1142test that builds the canonicaleffective_date:source, runs the handler, and asserts no emitted edit targets a metadata line.Out of scope (audit-identified follow-ups)
The same
start_line + 1 + ianti-pattern lives in 11 other LSP handlers:call_hierarchy.rs,document_highlight.rs,selection_range.rs,linked_editing.rs,code_actions.rs,inlay_hints.rs,document_color.rs,execute_command.rs,references.rs,on_type_formatting.rs,symbols.rs.These handlers are read-only — they produce wrong highlights / hovers / navigation targets in the same scenarios but cannot corrupt files. Each warrants its own audit + tests + PR rather than a blind sweep here.
Test plan
cargo check --workspace --all-features --all-targetscargo clippy --workspace --all-features --all-targets -- -D warningsRUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-depscargo test -p rustledger-lsp --all-features— 130 tests, 0 failures (incl. 2 new regression tests)cargo fmt --all -- --check🤖 Generated with Claude Code