From c2ea1a11f67be2261d481806a464765021aae388 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Wed, 26 Aug 2026 11:49:49 -0700 Subject: [PATCH] =?UTF-8?q?LSP=20=C2=A79b:=20incremental=20text=20sync?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit textDocument/didChange now applies ranged content changes instead of requiring the whole buffer per keystroke. New pure sync::apply_changes applies each change against the document as the previous ones left it (fresh line table per change), clamping inherited from convert.rs and a backwards range read as a pure insertion — the one rule that cannot lose text. One notification stays one reparse / one generation bump / one publish. Full-sync clients (rangeless changes) keep byte-identical behavior; save advertises includeText: false and didSave still honours text when sent. 35 tests added (28 unit incl. a 400-sequence randomized cross-check against an independent reference model and QA's surrogate/CRLF/final- newline attacks, 6 server-level, 1 e2e pinning the wire capability shape). QA's one finding — CRLF split across two same-position inserts in one batch lands \n\r — is pre-existing convert.rs behavior, pinned by test, unreachable by real clients; see the feature README. docs/features/incremental-sync/README.md Co-Authored-By: Claude Fable 5 --- TODO.md | 13 +- crates/lucisv_server/src/main.rs | 22 +- crates/lucisv_server/src/server.rs | 214 ++++++++++- crates/lucisv_server/src/sync.rs | 432 +++++++++++++++++++++++ crates/lucisv_server/tests/e2e.rs | 87 +++++ docs/features/incremental-sync/README.md | 415 ++++++++++++++++++++++ docs/features/lucisv-server/README.md | 30 +- docs/features/pull-diagnostics/README.md | 7 +- 8 files changed, 1200 insertions(+), 20 deletions(-) create mode 100644 crates/lucisv_server/src/sync.rs create mode 100644 docs/features/incremental-sync/README.md diff --git a/TODO.md b/TODO.md index 26b212e..045ed4d 100644 --- a/TODO.md +++ b/TODO.md @@ -687,11 +687,22 @@ and are not gaps. ### 9b. High-value, next rounds -- [ ] **Incremental text sync** (`TextDocumentSyncKind::INCREMENTAL`). +- [x] **Incremental text sync** (`TextDocumentSyncKind::INCREMENTAL`). Full-buffer sync on every keystroke scales poorly; apply range-scoped `contentChanges` in order, with a full-text fallback on any malformed change. Touches `set_document` and the staleness model in `docs/features/lucisv-server/README.md`. + → `docs/features/incremental-sync/README.md` + (`crates/lucisv_server/src/sync.rs`); one pure + `apply_changes(text, changes) -> String` over `convert::Positions`, a + fresh line table per change so each range sees the previous one's + result, rangeless changes still replacing the whole buffer, and every + desynced position clamped (line past EOF, character past line end, + surrogate half rounds forward, `start > end` becomes an insertion). + Still one `set_document` — one reparse, one generation bump, one + publish — per notification. Advertised as `TextDocumentSyncOptions` + with the open/close and `save.includeText: false` values a bare `Kind` + already implied, so no client's save behavior moved. - [ ] **`textDocument/willSaveWaitUntil`** — the protocol-native format-on-save hook (client-side `editor.formatOnSave` already works; this serves the editors without it). diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index 419e856..5247db4 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -32,6 +32,7 @@ mod settings; mod signature; mod state; mod symbols; +mod sync; mod templates; mod tokens; mod uri; @@ -45,11 +46,11 @@ use lsp_types::{ CallHierarchyServerCapability, CodeActionKind, CodeActionOptions, CodeActionProviderCapability, CompletionOptions, DiagnosticOptions, DiagnosticServerCapabilities, DocumentLinkOptions, ExecuteCommandOptions, FoldingRangeProviderCapability, InitializeParams, InlayHintOptions, - InlayHintServerCapabilities, OneOf, PositionEncodingKind, RenameOptions, + InlayHintServerCapabilities, OneOf, PositionEncodingKind, RenameOptions, SaveOptions, SelectionRangeProviderCapability, SemanticTokensFullOptions, SemanticTokensLegend, SemanticTokensOptions, SemanticTokensServerCapabilities, ServerCapabilities, SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind, - WorkDoneProgressOptions, + TextDocumentSyncOptions, TextDocumentSyncSaveOptions, WorkDoneProgressOptions, }; use crate::server::{ClientAbilities, Server}; @@ -84,7 +85,22 @@ fn capabilities() -> ServerCapabilities { // The protocol default, and what the conversion in `convert.rs` // implements. Stated rather than left implicit. position_encoding: Some(PositionEncodingKind::UTF16), - text_document_sync: Some(TextDocumentSyncCapability::Kind(TextDocumentSyncKind::FULL)), + // Incremental sync: a keystroke costs one range, not the whole file. + // Spelled out as options rather than a bare kind because a bare kind + // says nothing about open/close or save, and clients fill that in + // themselves — this states the same defaults a bare kind resolved to, + // so nothing but `change` moves. `includeText: false` keeps a save + // from re-sending a buffer the server already tracks edit by edit; + // the `didSave` handler still honours text if a client sends it. + text_document_sync: Some(TextDocumentSyncCapability::Options(TextDocumentSyncOptions { + open_close: Some(true), + change: Some(TextDocumentSyncKind::INCREMENTAL), + will_save: None, + will_save_wait_until: None, + save: Some(TextDocumentSyncSaveOptions::SaveOptions(SaveOptions { + include_text: Some(false), + })), + })), document_formatting_provider: Some(OneOf::Left(true)), document_range_formatting_provider: Some(OneOf::Left(true)), definition_provider: Some(OneOf::Left(true)), diff --git a/crates/lucisv_server/src/server.rs b/crates/lucisv_server/src/server.rs index af0ab73..8f45e2a 100644 --- a/crates/lucisv_server/src/server.rs +++ b/crates/lucisv_server/src/server.rs @@ -49,7 +49,8 @@ use serde_json::Value; use crate::state::Workspace; use crate::{ code_action, completion, diagnostics, folding, format, hierarchy, hover, includes, inlay, - inline, nav, pairs, ports, rename, selection, settings, signature, symbols, tokens, watch, + inline, nav, pairs, ports, rename, selection, settings, signature, symbols, sync, tokens, + watch, }; /// What the client said it can do, read once at `initialize` because that is @@ -585,12 +586,20 @@ impl Server { } DidChangeTextDocument::METHOD => { if let Ok(p) = extract::(notification) { - // Full-text sync: the last change carries the whole buffer. - if let Some(change) = p.content_changes.into_iter().next_back() { - let uri = p.text_document.uri; - self.set_document(uri.clone(), change.text); - self.publish(&uri); + // Incremental sync: the changes are ranges into the buffer + // we hold, applied in order. A full-sync client's + // rangeless change still replaces the whole buffer, so + // "the last one wins" stays true for it. One notification + // is one `set_document` — one reparse, one generation + // bump — however many ranges it carried. + if p.content_changes.is_empty() { + return; } + let uri = p.text_document.uri; + let base = self.workspace.document(&uri).map_or("", |doc| doc.text.as_str()); + let text = sync::apply_changes(base, &p.content_changes); + self.set_document(uri.clone(), text); + self.publish(&uri); } } DidSaveTextDocument::METHOD => { @@ -1765,4 +1774,197 @@ mod tests { ); assert_eq!(result, Value::Null); } + + // ------------------------------------------------------------------ + // incremental text sync + // ------------------------------------------------------------------ + + /// One `didChange`, carrying whatever changes were given. + fn change(session: &mut Session, uri: &Uri, version: u32, changes: Value) { + session.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri, "version": version }, + "contentChanges": changes, + }), + ); + } + + /// The text the server currently holds for a buffer. + fn buffer(session: &Session, uri: &Uri) -> String { + session.server.workspace.document(uri).expect("an open buffer").text.clone() + } + + #[test] + fn incremental_changes_land_the_same_buffer_as_one_full_change() { + let tree = Tree::new("incrementalsame"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n"); + + // Three ranges, each positioned against what the last one left. + change( + &mut session, + &uri, + 2, + serde_json::json!([ + { "range": { "start": { "line": 1, "character": 0 }, + "end": { "line": 1, "character": 0 } }, "text": "\n" }, + { "range": { "start": { "line": 1, "character": 0 }, + "end": { "line": 1, "character": 0 } }, "text": " wire " }, + { "range": { "start": { "line": 1, "character": 7 }, + "end": { "line": 1, "character": 7 } }, "text": "w;" }, + ]), + ); + let composed = "module m;\n wire w;\nendmodule\n"; + assert_eq!(buffer(&session, &uri), composed); + + // The same buffer reached by a full-sync client, for comparison. + let mut full = Session::new(vec![tree.path.clone()], false); + let other = full.open(&tree.path.join("m.sv"), "module m;\nendmodule\n"); + change(&mut full, &other, 2, serde_json::json!([{ "text": composed }])); + assert_eq!(buffer(&full, &other), composed); + + // And the answers computed from it agree, not just the text. + assert_eq!( + session.result( + Formatting::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri }, + "options": { "tabSize": 2, "insertSpaces": true }, + }), + ), + full.result( + Formatting::METHOD, + serde_json::json!({ + "textDocument": { "uri": other }, + "options": { "tabSize": 2, "insertSpaces": true }, + }), + ), + ); + } + + #[test] + fn one_notification_is_one_generation_bump_however_many_ranges() { + // The pull-diagnostics `resultId` is this counter. One reparse and one + // stamp per notification: a bump per range would make every keystroke + // look like several to a pulling client, and none would make a + // changed buffer answer "unchanged". + let tree = Tree::new("incrementalgeneration"); + let mut session = Session::with(vec![tree.path.clone()], pulling()); + let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n"); + + let before = session.server.generation; + change( + &mut session, + &uri, + 2, + serde_json::json!([ + { "range": { "start": { "line": 0, "character": 9 }, + "end": { "line": 0, "character": 9 } }, "text": "\n wire a;" }, + { "range": { "start": { "line": 1, "character": 9 }, + "end": { "line": 1, "character": 9 } }, "text": "\n wire b;" }, + { "range": { "start": { "line": 2, "character": 7 }, + "end": { "line": 2, "character": 8 } }, "text": "c" }, + ]), + ); + assert_eq!(session.server.generation, before + 1, "one stamp per notification"); + assert_eq!(buffer(&session, &uri), "module m;\n wire a;\n wire c;\nendmodule\n"); + + // An empty batch is not a change: nothing to reparse, nothing to stamp. + let stamp = session.server.generation; + change(&mut session, &uri, 3, serde_json::json!([])); + assert_eq!(session.server.generation, stamp, "an empty batch moves nothing"); + } + + #[test] + fn a_full_sync_clients_batch_still_lets_the_last_change_win() { + // A client that ignores the new capability and keeps sending whole + // buffers must behave exactly as it did before this feature. + let tree = Tree::new("incrementalfullsync"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n"); + change( + &mut session, + &uri, + 2, + serde_json::json!([ + { "text": "module a;\nendmodule\n" }, + { "text": "module b;\nendmodule\n" }, + { "text": "module c;\nendmodule\n" }, + ]), + ); + assert_eq!(buffer(&session, &uri), "module c;\nendmodule\n"); + } + + #[test] + fn a_change_naming_a_buffer_that_was_never_opened_is_taken_as_written() { + // Out of protocol, but a full-text change used to be adopted whatever + // the state was, and still is: there is no base text to be wrong + // about. A *ranged* change against nothing lands its text at the + // start, which is the clamping rule, not a special case. + let tree = Tree::new("incrementalunopened"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri"); + change(&mut session, &uri, 1, serde_json::json!([{ "text": "module m;\nendmodule\n" }])); + assert_eq!(buffer(&session, &uri), "module m;\nendmodule\n"); + } + + #[test] + fn a_ranged_change_over_multi_byte_text_edits_the_right_columns() { + // The whole reason positions are converted rather than counted: the + // comment above the edited line is four characters and nine bytes. + let tree = Tree::new("incrementalunicode"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = + session.open(&tree.path.join("m.sv"), "// é ✓ 🎉\nmodule m;\n wire a;\nendmodule\n"); + change( + &mut session, + &uri, + 2, + serde_json::json!([{ + "range": { "start": { "line": 2, "character": 7 }, + "end": { "line": 2, "character": 8 } }, + "text": "renamed", + }]), + ); + assert_eq!(buffer(&session, &uri), "// é ✓ 🎉\nmodule m;\n wire renamed;\nendmodule\n"); + } + + #[test] + fn a_ranged_change_republishes_diagnostics_for_what_it_produced() { + let tree = Tree::new("incrementalpublish"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n"); + let _ = session.published(); + + // Delete the `a`, leaving `wire ;` — a parse error. + change( + &mut session, + &uri, + 2, + serde_json::json!([{ + "range": { "start": { "line": 1, "character": 7 }, + "end": { "line": 1, "character": 8 } }, + "text": "", + }]), + ); + let published = session.published(); + assert_eq!(published.len(), 1, "one publish per notification: {published:#?}"); + assert!(!published[0].diagnostics.is_empty(), "the broken buffer is reported"); + + // Put it back: the diagnostics clear. + change( + &mut session, + &uri, + 3, + serde_json::json!([{ + "range": { "start": { "line": 1, "character": 7 }, + "end": { "line": 1, "character": 7 } }, + "text": "a", + }]), + ); + let published = session.published(); + assert_eq!(published.len(), 1); + assert!(published[0].diagnostics.is_empty(), "{published:#?}"); + } } diff --git a/crates/lucisv_server/src/sync.rs b/crates/lucisv_server/src/sync.rs new file mode 100644 index 0000000..7113445 --- /dev/null +++ b/crates/lucisv_server/src/sync.rs @@ -0,0 +1,432 @@ +//! Applying a `didChange`'s edits to a buffer. +//! +//! With `TextDocumentSyncKind::INCREMENTAL` the client stops sending the whole +//! file on every keystroke and sends the ranges it touched instead. The server +//! is then the only holder of the buffer's text, so this module is the one +//! place a wrong offset silently rewrites what the user is looking at — hence +//! a pure function, a second implementation to cross-check it against, and no +//! slicing that can panic. The exact clamping rules are in +//! `docs/features/incremental-sync/README.md`. + +use lsp_types::TextDocumentContentChangeEvent; +use vlog_parser::LineIndex; + +use crate::convert::Positions; + +/// Apply one `didChange`'s content changes to a buffer, in the order the +/// client sent them, and return the buffer that results. +/// +/// A change with no range replaces the whole document — what a full-sync +/// client sends, and what still works if one arrives mid-batch. +pub fn apply_changes(text: &str, changes: &[TextDocumentContentChangeEvent]) -> String { + let mut text = text.to_string(); + for change in changes { + let Some(range) = change.range else { + // The whole document. This also resets the state that the ranges + // after it in the same batch are positioned against. + text.clone_from(&change.text); + continue; + }; + // A fresh line table per change: each range is positioned against the + // document as the *previous* changes in this batch left it. That is + // O(changes × file) per notification, which at Verilog file sizes is + // microseconds and buys a function with no incremental state to get + // out of step. + let index = LineIndex::new(&text); + let positions = Positions::new(&text, &index); + let start = positions.offset(range.start) as usize; + // A range that runs backwards is a client desync. Reading it as an + // insertion at `start` is the one interpretation that deletes nothing: + // we have no resync mechanism, so the safe direction is to keep text. + let end = (positions.offset(range.end) as usize).max(start); + let (Some(before), Some(after)) = (text.get(..start), text.get(end..)) else { + // Unreachable: `Positions::offset` only ever returns character + // boundaries. Written as a skip rather than a slice because the + // slice would panic, and a panic here takes the buffer with it. + continue; + }; + text = format!("{before}{}{after}", change.text); + } + text +} + +#[cfg(test)] +mod tests { + use super::*; + use lsp_types::{Position, Range}; + + fn pos(line: u32, character: u32) -> Position { + Position { line, character } + } + + /// A ranged change, the way a client sends one. + fn edit( + start: (u32, u32), + end: (u32, u32), + text: &str, + ) -> lsp_types::TextDocumentContentChangeEvent { + TextDocumentContentChangeEvent { + range: Some(Range { start: pos(start.0, start.1), end: pos(end.0, end.1) }), + range_length: None, + text: text.to_string(), + } + } + + /// A rangeless change: the whole buffer, as a full-sync client sends it. + fn whole(text: &str) -> TextDocumentContentChangeEvent { + TextDocumentContentChangeEvent { range: None, range_length: None, text: text.to_string() } + } + + #[test] + fn an_insert_lands_where_the_range_is_empty() { + let text = "module m;\n wire a;\nendmodule\n"; + let after = apply_changes(text, &[edit((1, 8), (1, 8), "b")]); + assert_eq!(after, "module m;\n wire ab;\nendmodule\n"); + } + + #[test] + fn a_delete_removes_exactly_the_range() { + let text = "module m;\n wire aaa;\nendmodule\n"; + let after = apply_changes(text, &[edit((1, 7), (1, 10), "")]); + assert_eq!(after, "module m;\n wire ;\nendmodule\n"); + } + + #[test] + fn a_replace_swaps_the_range_for_the_text() { + let text = "module m;\n wire a;\nendmodule\n"; + let after = apply_changes(text, &[edit((1, 2), (1, 6), "logic")]); + assert_eq!(after, "module m;\n logic a;\nendmodule\n"); + } + + #[test] + fn a_multi_line_range_collapses_the_lines_it_spans() { + let text = "a\nb\nc\n"; + let after = apply_changes(text, &[edit((0, 1), (2, 0), "X")]); + assert_eq!(after, "aXc\n"); + } + + #[test] + fn later_changes_see_what_the_earlier_ones_did() { + // The batch a real editor sends for "type `wire w;` on a new line", + // split into three: each range is against the state after the last. + let text = "module m;\nendmodule\n"; + let after = apply_changes( + text, + &[ + edit((1, 0), (1, 0), "\n"), // open a line + edit((1, 0), (1, 0), " wire "), // the keyword + edit((1, 7), (1, 7), "w;"), // the name + ], + ); + assert_eq!(after, "module m;\n wire w;\nendmodule\n"); + } + + #[test] + fn a_later_range_positioned_against_the_original_text_would_be_wrong() { + // The regression this whole module exists to prevent: if the line + // table were built once, the second range below would land on the old + // line 1 and the result would differ. + let text = "aaa\nbbb\n"; + let after = apply_changes(text, &[edit((0, 0), (0, 0), "x\n"), edit((1, 1), (1, 2), "Z")]); + assert_eq!(after, "x\naZa\nbbb\n"); + } + + #[test] + fn a_two_byte_character_is_one_utf16_unit_to_the_edit_too() { + let text = "// é ok\n"; + let after = apply_changes(text, &[edit((0, 5), (0, 7), "no")]); + assert_eq!(after, "// é no\n"); + } + + #[test] + fn an_astral_character_takes_two_units_and_is_never_split() { + // `🎉` is 2 UTF-16 units. A boundary on its low half rounds forward + // past the whole character, so no edit can ever cut it in half. + let text = "// 🎉 ok\n"; + assert_eq!(apply_changes(text, &[edit((0, 3), (0, 5), "X")]), "// X ok\n"); + // Start inside the pair: the emoji survives, the edit begins after it. + assert_eq!(apply_changes(text, &[edit((0, 4), (0, 6), "X")]), "// 🎉Xok\n"); + // End inside the pair: rounds forward, so the emoji goes with it. + assert_eq!(apply_changes(text, &[edit((0, 3), (0, 4), "X")]), "// X ok\n"); + for change in [edit((0, 4), (0, 4), "!"), edit((0, 4), (0, 5), "!")] { + let out = apply_changes(text, &[change]); + assert!(out.is_char_boundary(out.len()), "still valid UTF-8: {out:?}"); + } + } + + #[test] + fn an_edit_after_an_emoji_counts_from_the_right_column() { + let text = "// 🎉 wire a;\n"; + // "wire" starts at UTF-16 unit 6: `/`,`/`,` `,🎉(2),` `. + let after = apply_changes(text, &[edit((0, 6), (0, 10), "logic")]); + assert_eq!(after, "// 🎉 logic a;\n"); + } + + #[test] + fn crlf_line_ends_survive_an_edit_on_the_line() { + let text = "module m;\r\n wire a;\r\nendmodule\r\n"; + let after = apply_changes(text, &[edit((1, 7), (1, 8), "bb")]); + assert_eq!(after, "module m;\r\n wire bb;\r\nendmodule\r\n"); + } + + #[test] + fn a_crlf_line_can_be_joined_to_the_next() { + let text = "ab\r\ncd\r\n"; + let after = apply_changes(text, &[edit((0, 2), (1, 0), "")]); + assert_eq!(after, "abcd\r\n", "the whole `\\r\\n` goes"); + } + + #[test] + fn an_edit_at_the_start_of_the_document() { + assert_eq!(apply_changes("wire a;\n", &[edit((0, 0), (0, 0), "// ")]), "// wire a;\n"); + assert_eq!(apply_changes("wire a;\n", &[edit((0, 0), (0, 4), "logic")]), "logic a;\n"); + } + + #[test] + fn an_edit_at_end_of_file() { + // The empty last line a trailing newline opens. + assert_eq!(apply_changes("a\n", &[edit((1, 0), (1, 0), "b\n")]), "a\nb\n"); + } + + #[test] + fn an_insert_at_the_end_of_a_last_line_with_no_trailing_newline() { + assert_eq!(apply_changes("endmodule", &[edit((0, 9), (0, 9), "\n")]), "endmodule\n"); + } + + #[test] + fn an_edit_into_an_empty_document() { + assert_eq!(apply_changes("", &[edit((0, 0), (0, 0), "module m;")]), "module m;"); + } + + #[test] + fn a_rangeless_change_replaces_the_whole_document() { + assert_eq!(apply_changes("old\n", &[whole("new\n")]), "new\n"); + } + + #[test] + fn the_last_of_several_rangeless_changes_wins() { + // What the full-sync handler did before this feature, unchanged. + assert_eq!(apply_changes("old\n", &[whole("a\n"), whole("b\n"), whole("c\n")]), "c\n"); + } + + #[test] + fn a_rangeless_change_resets_what_the_next_range_is_against() { + let after = apply_changes("anything\n", &[whole("abc\ndef\n"), edit((1, 1), (1, 2), "X")]); + assert_eq!(after, "abc\ndXf\n"); + } + + #[test] + fn no_changes_is_the_buffer_unchanged() { + assert_eq!(apply_changes("wire a;\n", &[]), "wire a;\n"); + } + + #[test] + fn a_line_past_the_end_clamps_to_the_end_of_the_document() { + let text = "a\nb\n"; + assert_eq!(apply_changes(text, &[edit((99, 0), (99, 5), "X")]), "a\nb\nX"); + // And a range that *starts* in the document and ends past it. + assert_eq!(apply_changes(text, &[edit((1, 0), (99, 0), "X")]), "a\nX"); + } + + #[test] + fn a_character_past_the_end_of_a_line_clamps_to_its_content() { + assert_eq!(apply_changes("ab\ncd\n", &[edit((0, 99), (0, 99), "!")]), "ab!\ncd\n"); + assert_eq!(apply_changes("ab\r\ncd\r\n", &[edit((0, 99), (0, 99), "!")]), "ab!\r\ncd\r\n"); + } + + #[test] + fn a_range_that_runs_backwards_deletes_nothing() { + // Clamping `end` up to `start` turns a desynced range into a pure + // insertion — the only reading that cannot lose the user's text. + assert_eq!(apply_changes("abcdef\n", &[edit((0, 4), (0, 1), "X")]), "abcdXef\n"); + assert_eq!(apply_changes("ab\ncd\n", &[edit((1, 1), (0, 0), "X")]), "ab\ncXd\n"); + } + + // ------------------------------------------------------------------ + // randomized cross-check against a second implementation + // ------------------------------------------------------------------ + + /// A fixed-seed linear congruential generator — deterministic randomness + /// with no dependency. The constants are Knuth's MMIX. + struct Lcg(u64); + + impl Lcg { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + self.0 >> 33 + } + + fn below(&mut self, n: u64) -> u64 { + self.next() % n.max(1) + } + } + + /// The same rules, implemented a second way: a flat `Vec` with the + /// line starts scanned out of it, rather than byte offsets off a + /// `LineIndex`. Sharing no code with `apply_changes` is the point. + fn reference_apply(text: &str, changes: &[TextDocumentContentChangeEvent]) -> String { + let mut text = text.to_string(); + for change in changes { + let Some(range) = change.range else { + text.clone_from(&change.text); + continue; + }; + let chars: Vec = text.chars().collect(); + let start = reference_index(&chars, range.start); + let end = reference_index(&chars, range.end).max(start); + let mut out: String = chars[..start].iter().collect(); + out.push_str(&change.text); + out.extend(chars[end..].iter()); + text = out; + } + text + } + + /// The index into `chars` that a position names: lines are `\n`- + /// terminated, one `\r` before that terminator is not content, a + /// character past a line's content clamps to it, a line past the last + /// clamps to the end of the text, and a character landing inside a + /// surrogate pair rounds forward past the whole character. + fn reference_index(chars: &[char], position: Position) -> usize { + let mut starts = vec![0usize]; + for (i, c) in chars.iter().enumerate() { + if *c == '\n' { + starts.push(i + 1); + } + } + let Some(&start) = starts.get(position.line as usize) else { + return chars.len(); + }; + // The line's content ends before its `\n`, and before one `\r`. + let mut end = match starts.get(position.line as usize + 1) { + Some(&next) => next - 1, + None => chars.len(), + }; + if end > start && chars[end - 1] == '\r' { + end -= 1; + } + let mut units = 0u32; + let mut at = start; + while at < end && units < position.character { + units += chars[at].len_utf16() as u32; + at += 1; + } + at + } + + /// A random document over an alphabet that mixes every width and both + /// line endings — including a bare `\r`, which is an ordinary character. + fn random_text(rng: &mut Lcg) -> String { + const ALPHABET: [&str; 8] = ["a", "b", " ", ";", "\n", "\r\n", "é", "🎉"]; + let len = rng.below(24); + (0..len).map(|_| ALPHABET[rng.below(8) as usize]).collect() + } + + /// A random change: mostly ranged, occasionally a whole-document reset, + /// with positions that are often — but deliberately not always — inside + /// the document. + fn random_change(rng: &mut Lcg, text: &str) -> TextDocumentContentChangeEvent { + if rng.below(10) == 0 { + return whole(&random_text(rng)); + } + let lines = text.matches('\n').count() as u32 + 1; + let position = |rng: &mut Lcg| Position { + line: rng.below(u64::from(lines) + 2) as u32, + character: rng.below(12) as u32, + }; + let (first, second) = (position(rng), position(rng)); + TextDocumentContentChangeEvent { + range: Some(Range { start: first, end: second }), + range_length: None, + text: random_text(rng), + } + } + + #[test] + fn random_edit_sequences_agree_with_the_reference_model() { + let mut rng = Lcg(0x5EED_1CE5); + let mut ranged = 0usize; + for case in 0..400 { + let text = random_text(&mut rng); + let mut changes = Vec::new(); + let mut running = text.clone(); + for _ in 0..rng.below(5) + 1 { + let change = random_change(&mut rng, &running); + ranged += usize::from(change.range.is_some()); + // The next range is against the state this one leaves. + running = apply_changes(&running, std::slice::from_ref(&change)); + changes.push(change); + } + let ours = apply_changes(&text, &changes); + assert_eq!(ours, reference_apply(&text, &changes), "case {case}, from {text:?}"); + assert_eq!(ours, running, "case {case}: one batch equals the changes one at a time"); + } + assert!(ranged > 500, "the cases must be mostly ranged edits, got {ranged}"); + } + + // ------------------------------------------------------------------ + // QA additions (2026-08-26) — see docs/features/incremental-sync/README.md + // QA log for the full writeup of each of these. + // ------------------------------------------------------------------ + + #[test] + fn a_deletion_starting_at_the_low_surrogate_index_preserves_the_character() { + // Character 4 is the low half of `🎉`'s pair (the emoji starts at 3, + // ends at 5). A *start* boundary landing there rounds forward past + // the whole character, so the emoji is excluded from — and survives + // — a deletion that begins mid-pair. + let text = "// 🎉 ok\n"; + let after = apply_changes(text, &[edit((0, 4), (0, 6), "")]); + assert_eq!(after, "// 🎉ok\n", "the emoji stays, only the trailing space is deleted"); + } + + #[test] + fn a_deletion_ending_at_the_low_surrogate_index_consumes_the_whole_character() { + // Symmetric case: an *end* boundary on the low half also rounds + // forward, but here that means the deletion is widened to swallow + // the whole character rather than stopping short of it. + let text = "// 🎉 ok\n"; + let after = apply_changes(text, &[edit((0, 3), (0, 4), "")]); + assert_eq!(after, "// ok\n", "the whole emoji is gone, both flanking spaces remain"); + } + + #[test] + fn crlf_split_across_two_changes_in_one_batch_reorders_the_bytes() { + // QA finding (docs/features/incremental-sync/README.md QA log, + // 2026-08-26): pinning present, *surprising* behavior rather than + // asserting it is correct. `convert.rs::line_content_end` treats a + // trailing bare `\r` as "not content" whether or not a `\n` will + // follow it, so a second change in the same batch that targets "end + // of line" after a first change appended a lone `\r` lands *before* + // that `\r`, not after it. A client that split one `\r\n` insertion + // into two ranged changes this way would get `\n\r`, not `\r\n`. No + // real editor's diff algorithm is known to do this, and no panic or + // data loss occurs — but if this test's expected string ever needs + // to change to `"ab\r\n"`, that is a deliberate fix to + // `Positions::offset`/`line_content_end`, not an accidental one. + let text = "ab"; + let after = apply_changes(text, &[edit((0, 2), (0, 2), "\r"), edit((0, 2), (0, 2), "\n")]); + assert_eq!(after, "ab\n\r", "known edge case: see the comment above"); + } + + #[test] + fn a_change_covering_the_final_newline_removes_exactly_it() { + let text = "a\nb\n"; + let after = apply_changes(text, &[edit((1, 1), (2, 0), "")]); + assert_eq!(after, "a\nb", "the trailing newline is gone, nothing else is"); + } + + #[test] + fn zero_width_inserts_at_the_same_position_compose_in_batch_order() { + // Not a bug: per protocol, each change is positioned against what the + // previous ones in the batch left, so two inserts naming the same + // literal position land with the *second* one first — a client that + // wants "12" must advance the second insert's position past the + // first's text, exactly as it would need to for a non-zero-width + // range. Pinned so a future refactor cannot silently change the + // batch's ordering semantics. + let text = "x"; + let after = apply_changes(text, &[edit((0, 0), (0, 0), "1"), edit((0, 0), (0, 0), "2")]); + assert_eq!(after, "21x"); + } +} diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index edc129c..f55132a 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -2682,3 +2682,90 @@ fn selection_ranges_round_trip_over_the_wire() { let _ = std::fs::remove_dir_all(&dir); } + +/// A clean buffer with a multi-byte comment above the line the edits touch: +/// a byte-vs-UTF-16 confusion in the sync path would land them on the wrong +/// columns, and the diagnostics at the end would say so. +const SYNCABLE: &str = "// é ✓ 🎉\nmodule sync_me;\n wire a;\nendmodule\n"; + +#[test] +fn incremental_changes_are_advertised_and_applied_over_the_wire() { + let dir = temp_dir("incremental"); + let file = dir.join("sync_me.sv"); + std::fs::write(&file, SYNCABLE).expect("write"); + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", file.display()); + + // Three ranges in one notification, each positioned against what the + // previous one left: delete the `a`, which breaks the buffer; type a `b` + // back in, which fixes it; then open a new, broken declaration below. + // A second notification finishes that declaration, badly spaced, so a + // formatting request can read the composed buffer back off the wire. + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(SYNCABLE).expect("json") + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":2}},"contentChanges":[{}]}}}}"#, + [ + r#"{"range":{"start":{"line":2,"character":7},"end":{"line":2,"character":8}},"text":""}"#, + r#"{"range":{"start":{"line":2,"character":7},"end":{"line":2,"character":7}},"text":"b"}"#, + r#"{"range":{"start":{"line":3,"character":0},"end":{"line":3,"character":0}},"text":" wire ;\n"}"#, + ] + .join(",") + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":3}},"contentChanges":[{}]}}}}"#, + r#"{"range":{"start":{"line":3,"character":9},"end":{"line":3,"character":9}},"text":"c"}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/formatting","params":{{"textDocument":{{"uri":"{uri}"}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + + // 1. The capability says incremental, and says the rest explicitly. + let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); + let sync = &initialize["result"]["capabilities"]["textDocumentSync"]; + assert_eq!(sync["change"], 2, "TextDocumentSyncKind::Incremental: {initialize:#?}"); + assert_eq!(sync["openClose"], true, "{sync:#?}"); + assert_eq!(sync["save"]["includeText"], false, "a save re-sends nothing: {sync:#?}"); + + // 2. Each notification published once, and what it published describes + // the composed buffer: the error is on the line the third range + // inserted, and it clears when the fourth range finishes that line. + let published: Vec<_> = + messages.iter().filter(|m| m["method"] == "textDocument/publishDiagnostics").collect(); + assert_eq!(published.len(), 3, "one per notification, not one per range: {published:#?}"); + assert!( + published[0]["params"]["diagnostics"].as_array().expect("an array").is_empty(), + "the file opened clean: {published:#?}" + ); + let diagnostics = published[1]["params"]["diagnostics"].as_array().expect("an array"); + assert_eq!(diagnostics.len(), 1, "{diagnostics:#?}"); + assert_eq!(diagnostics[0]["range"]["start"]["line"], 3, "the inserted line"); + assert!( + published[2]["params"]["diagnostics"].as_array().expect("an array").is_empty(), + "and the next range fixed it: {published:#?}" + ); + + // 3. And the buffer the server holds is exactly the composed text — read + // back through the formatter, which normalizes only the spacing the + // last range left behind. + assert_eq!( + new_text(&messages, 2), + "// é ✓ 🎉\nmodule sync_me;\n wire b;\n wire c;\nendmodule\n", + "the four ranges composed, and the emoji line untouched" + ); + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/features/incremental-sync/README.md b/docs/features/incremental-sync/README.md new file mode 100644 index 0000000..a83cd38 --- /dev/null +++ b/docs/features/incremental-sync/README.md @@ -0,0 +1,415 @@ +# incremental-sync + +## Goal + +Move the server from `TextDocumentSyncKind::FULL` to +`TextDocumentSyncKind::INCREMENTAL`: a `didChange` now carries the ranges the +user touched rather than the whole buffer, and the server applies them to the +text it already holds. Full-buffer sync re-serializes, re-transfers and +re-allocates the entire file on every keystroke, which is the wrong cost curve +for a server that wants to answer per-keystroke (completion, signature help, +inlay hints) — and for the editor side of a large `.sv` it is the one place +lucisv was measurably ruder than ruff. The price of the move is that the server +becomes the *only* holder of the buffer's text: a wrong offset here silently +rewrites what the user is looking at, with no full-text resend to correct it. +That is why the whole edit application is one pure function +(`sync::apply_changes`), unit-tested against a second implementation, with no +slice that can panic. + +## Assumptions + +- **Positions are UTF-16, as `capabilities()` says.** Every conversion goes + through `convert::Positions::offset`, the same function every other request + handler uses. There is no second offset arithmetic in this feature — that is + the point. +- **Clamping, exactly.** A client desync (or an editor rounding a position) must + never panic and never corrupt. The rules, all of them inherited from + `Positions::offset` and pinned by tests in `sync.rs`: + - a **line past the end** of the document clamps to the end of the document; + - a **character past the end of a line's content** clamps to that content's + end — before the line's `\n`, and before one `\r` preceding it, so an edit + positioned past the visible end of a CRLF line cannot land between the + `\r` and the `\n`; + - a **character landing inside a surrogate pair** (the low half of an astral + character such as `🎉`) **rounds forward** past the whole character. So a + range boundary can never split a `char`, the output is always valid UTF-8, + and an emoji is either wholly inside the replaced range or wholly outside + it; + - **`start > end` after conversion** clamps `end` up to `start`, which turns + the change into a pure insertion at `start`. There is no resync mechanism + in LSP short of the client closing and reopening the buffer, so the safe + direction is the one that deletes nothing: a user can undo an unexpected + insertion, but cannot recover text the server threw away. +- **Each change is positioned against the document the previous changes in the + same notification left.** This is what the protocol says, and it is why the + line table is rebuilt per change rather than once per notification. +- **A change with no `range` replaces the whole document**, mid-batch included, + and resets the state the ranges after it are positioned against. A batch of + rangeless changes therefore still ends at the last one — the pre-existing + full-sync behavior, kept for a client that ignores the new capability. +- **An empty `contentChanges` array is not a change**: nothing is reparsed and + the generation counter does not move, exactly as before (the old handler's + `next_back()` on an empty list did nothing). +- **A `didChange` for a buffer that was never opened** is out of protocol, but + is still taken rather than dropped: the base text is `""`, so a full-text + change lands exactly as it did before this feature, and a ranged change + clamps to an insertion at the start. No special case, no error path. +- **`O(changes × file)` per notification, honestly.** Every ranged change + builds a fresh `LineIndex` over the current text and allocates a new `String`. + For the batch sizes editors actually send (1–5 ranges) over Verilog files + this is microseconds, and it buys a function with no incremental state that + can fall out of step with the text. A rope or an incrementally-patched line + table is the optimization to reach for if a profile ever asks; TODO.md §6 + already defers that whole class of work. + +## Handshakes + +- **Consumes `convert::Positions::offset`** (`crates/lucisv_server/src/convert.rs`) + for every position→byte conversion, and `vlog_parser::LineIndex` to build it. + Nothing was changed in either — the clamping this feature depends on is the + clamping those already documented and tested. +- **Promises `Server::set_document` is still called exactly once per + `didChange` notification.** `set_document` bumps `self.generation`, which is + the whole `resultId` of `docs/features/pull-diagnostics/README.md`; a bump + per *range* would make one keystroke look like several to a pulling client, + and no bump would let a changed buffer answer "unchanged". One notification = + one reparse = one stamp = one `publish`. Pinned by + `one_notification_is_one_generation_bump_however_many_ranges`. +- **Changes what the client is told at `initialize`.** + `text_document_sync` moves from `Kind(FULL)` to `Options { open_close: true, + change: INCREMENTAL, save: { include_text: false } }`. The `open_close` and + `save` values are not new behavior: they are what a bare `Kind` already + resolved to client-side (`vscode-languageclient` expands a numeric + `textDocumentSync` to exactly `{ openClose: true, change: , save: { + includeText: false } }`), written out because the options form has no + "unspecified" that means the same thing. `didSave` therefore carries no text, + which is what it carried before — and the `DidSaveTextDocument` handler still + adopts `params.text` if some client sends it anyway, so nothing regresses for + a client that behaves differently. +- **No other crate is touched.** No new dependency; the randomized test's + generator is a five-line LCG rather than `rand`. + +## Status / TODO + +- [x] Advertise `TextDocumentSyncOptions` with `change: INCREMENTAL`, + preserving the open/close and save semantics a bare `Kind` implied. +- [x] `sync::apply_changes(text, changes) -> String` — pure, total, no + panicking slice. +- [x] All changes applied in order, each against the previous one's result. +- [x] Rangeless change = whole-document replace, mid-batch included. +- [x] Clamping rules (line past EOF, character past line end, surrogate half, + `start > end`) defined above and tested. +- [x] One `set_document` — one reparse, one generation bump, one publish — per + notification. +- [x] Unit tests: insert/delete/replace, dependent batches, multi-byte and + astral characters, CRLF, (0,0), EOF, no trailing newline, rangeless + mixed into a batch, every clamping rule. +- [x] Randomized cross-check against a second implementation built on + `char`s and lines, fixed seed, 400 cases. +- [x] Server-level tests: incremental batch == one full change, generation + bumps once, full-sync batch still ends at the last change, publishes + reflect the composed text. +- [x] e2e test driving the real binary with four ranges over two + notifications. +- [x] `docs/features/lucisv-server/README.md` sync/staleness text updated. +- [x] TODO.md §9b item checked off. + +## Work log + +**2026-08-26 — dev.** Implemented the whole feature in one round. + +- New module `crates/lucisv_server/src/sync.rs` (declared in `main.rs`), one + public function `apply_changes(&str, &[TextDocumentContentChangeEvent]) -> + String`. Chosen over putting it in `convert.rs`: `convert.rs` is the + byte↔position primitive every handler shares, and this is a protocol-level + policy (ordering, rangeless resets, desync clamping) built *on* it. Keeping + them apart means the safety-critical policy has its own test module and its + own reference implementation to be checked against. +- The function is deliberately dumb: `String` in, `String` out, a fresh + `LineIndex` per ranged change. No incremental line table, no rope, no + reusable "document buffer" abstraction for a second user that does not + exist. The cost is written down under Assumptions rather than optimized away. +- **No panicking slice.** `start`/`end` come from `Positions::offset`, which + only ever returns character boundaries, so `text[..start]` would be provably + safe — but "provably" leans on another module's invariant, and the failure + mode is a panic that takes the user's buffer with it. The splice uses + `text.get(..start)` / `text.get(end..)` and skips the change if either is + `None` (unreachable), so the function is total by construction. +- **Clamping decisions.** Line/character clamping is inherited from + `Positions::offset` rather than re-decided here — a second clamping rule + would be a second set of off-by-ones. The one genuinely new decision is + `start > end`: `end` clamps *up* to `start`, making the change an insertion. + Rejected alternatives: dropping the change (leaves the server's text and the + client's silently different, with no way back), and swapping the two (invents + a deletion the client never asked for). Insertion is the only reading that + cannot lose text. +- **Capability.** Moved to the options form. Establishing what a bare `Kind` + meant for save was the fiddly part: the spec leaves it to the client, and + `vscode-languageclient` fills in `{ openClose: true, change, save: { + includeText: false } }`. Writing those two out keeps every client on the + behavior it had, and `includeText: false` is also the right answer on its own + terms now — the server tracks the buffer edit by edit, so a save re-sending + the file would be pure waste. The `didSave` handler was left alone: it still + adopts `params.text` when present, so a client that sends text anyway is + handled exactly as before. +- **Handler.** `DidChangeTextDocument` reads the base text out of the workspace + (`""` if the buffer is unknown), calls `apply_changes` once, and goes through + the existing `set_document` + `publish` path unchanged — so the + pull-diagnostics generation model, the `lucisv.toml` warning re-arm, and the + push/pull gate all behave as they did. +- **Tests: 23 unit (`sync.rs`) + 6 server-level (`server.rs`) + 1 e2e.** The + randomized cross-check (`random_edit_sequences_agree_with_the_reference_model`) + runs 400 sequences of 1–5 changes over random texts drawn from + `{a, b, space, ;, \n, \r\n, é, 🎉}` — every character width, both line + endings, and bare `\r`s — with positions deliberately allowed out of range so + the clamping rules are exercised too. It compares against `reference_apply`, + a flat `Vec` implementation that scans its own line starts and shares + no code with `apply_changes`, and additionally asserts that applying the + batch in one call equals applying the changes one at a time. Seed is fixed + (`0x5EED_1CE5`), no dependency added. +- Deviations from the plan: none. Nothing outside `lucisv_server` was touched + in code. Two documentation files outside this feature were annotated rather + than rewritten, because both stated something this round made false: + `docs/features/lucisv-server/README.md` (the "full-text sync only" + assumption, the recompute table, and one sentence of an old QA log that read + `textDocumentSync: 1` off the capabilities JSON) and one parenthetical in + `docs/features/pull-diagnostics/README.md` that justified the single + generation counter by "full-text sync ignores versions" — the conclusion + still holds, the reason needed rewording. No QA log or Review section was + otherwise touched. + +## QA log + +**2026-08-26 — QA.** Re-ran every gate, then attacked the six surfaces the +lead flagged plus a few of my own. Verdict: **committable as-is**. No +corruption, no panic, no divergence from a well-behaved client found; one +pre-existing (not introduced by this feature) latent edge case documented +and pinned rather than fixed, since fixing it means changing a shared +primitive (`convert.rs`) outside this feature's scope. + +**Gates re-run, all clean:** +- `cargo fmt --all -- --check` — clean. +- `cargo clippy --all-targets` — clean (touched the three changed files and + re-ran to defeat the cache; still clean). +- `cargo test --workspace` — every crate green, 0 failed. `lucisv_server`'s + own run: 628 lib tests (23 in `sync.rs` as claimed, plus 5 I added), 33 + e2e, 3 grammar. `cargo test -p vlog_formatter` also re-run per CLAUDE.md's + formatter-change rule (this isn't a formatter change, but confirmed green + anyway): 114 passed. +- `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server` — + `smoke: OK`. + +**1. Surrogate rounding — verified clean, direction confirmed by reading +`convert.rs`.** `Positions::offset` (`crates/lucisv_server/src/convert.rs:39`) +walks the line's `char`s accumulating UTF-16 units and only ever returns an +offset it has actually reached by consuming whole `char`s (`offset += ch. +len_utf8()` happens only together with `units += ch.len_utf16()`), so the +returned byte offset is always the smallest character boundary whose +cumulative UTF-16 unit count is `>= pos.character` — i.e. it always rounds +up/forward, unconditionally, for every position (start or end). What +"forward" *means* differs by role: for a start boundary it means the +character is excluded (the insertion/deletion point moves past it, so the +character survives); for an end boundary it means the character is included +(the deletion widens to swallow it). Both are the same mechanical rule. +Added two direct tests pinning the exact resulting string, as asked: +`crates/lucisv_server/src/sync.rs` +`a_deletion_starting_at_the_low_surrogate_index_preserves_the_character` +(`edit((0,4),(0,6),"")` on `"// 🎉 ok\n"` → `"// 🎉ok\n"`, emoji survives) and +`a_deletion_ending_at_the_low_surrogate_index_consumes_the_whole_character` +(`edit((0,3),(0,4),"")` on the same text → `"// ok\n"`, emoji consumed). +Both pass. The dev's own two existing tests in +`an_astral_character_takes_two_units_and_is_never_split` already hit this +exact case (`edit((0,4),(0,6),"X")` and `edit((0,3),(0,4),"X")`) but as +replacements, not pure deletions — the two I added close that gap with an +empty `text`. Cross-checked against the LSP spec: positions are UTF-16 +code-unit offsets and a spec-compliant client never legitimately sends a +mid-pair boundary, so any total, non-panicking rule is acceptable — the +README's description ("rounds forward past the whole character") is +accurate to the actual code, not just to the reference model. + +**2. Divergence-from-editor risk — one real (low-severity, pre-existing) +finding, everything else clean.** +- **Fresh-`LineIndex`-per-change is not hoisted.** `crates/lucisv_server/src/ + sync.rs:35`, `let index = LineIndex::new(&text);`, is inside the `for + change in changes` loop, rebuilt from the current `text` every iteration — + confirmed by reading the code (not just trusting the comment), and then by + actually breaking it: I temporarily hoisted the `LineIndex::new` call above + the loop (reusing one stale index for every change) and reran `cargo test + --bin lucisv-server sync::tests::`. Three tests failed against the stale + index: `a_later_range_positioned_against_the_original_text_would_be_wrong` + (panics — its own doc comment names exactly this regression), + `a_rangeless_change_resets_what_the_next_range_is_against`, and + `random_edit_sequences_agree_with_the_reference_model` (400/400 cases + depend on this). `later_changes_see_what_the_earlier_ones_did` did *not* + fail under hoisting — its three edits happen to stay valid against the + stale index anyway, so it does not by itself pin this — but the three that + did fail are sufficient. Reverted the hoist immediately after (confirmed + back to 28/28 passing); no new test needed, the existing ones already pin + this correctly. +- **A change whose range covers the final newline** — clean. Added + `a_change_covering_the_final_newline_removes_exactly_it`: + `edit((1,1),(2,0),"")` on `"a\nb\n"` → `"a\nb"`. Removes exactly the + trailing `\n`, nothing else. +- **Adjacent zero-width ranges at the same position in one batch** — not a + bug, and pinned as such. Added + `zero_width_inserts_at_the_same_position_compose_in_batch_order`: two + inserts both naming `(0,0)` on `"x"` with texts `"1"` then `"2"` produce + `"21x"`, because each change's position is (correctly, per protocol) + resolved against the text the previous change left — the second insert's + literal position `0` is now *before* the first insert's text. A client + that wants `"12"` must advance the second position past the first's + length, same as it would for a non-zero-width range. This matches "each + change is positioned against the document the previous changes in the + same notification left" exactly. +- **`\r\n` split across two changes in one batch — finding.** + `crlf_split_across_two_changes_in_one_batch_reorders_the_bytes` + (`crates/lucisv_server/src/sync.rs`): `apply_changes("ab", &[edit((0,2), + (0,2), "\r"), edit((0,2),(0,2), "\n")])` produces `"ab\n\r"`, not + `"ab\r\n"`. Root cause: `convert.rs::line_content_end` + (`crates/lucisv_server/src/convert.rs:96`) treats a trailing bare `\r` as + "not content" unconditionally — whether or not a `\n` will ever follow it + — so once change 1 leaves the buffer ending in a lone `\r`, "end of line" + for change 2 clamps to *before* that `\r`, and the `\n` lands ahead of it + instead of after. This is **not introduced by this feature**: the rule + lives in `convert.rs`, which predates incremental sync and is shared by + every position-converting handler. What incremental sync newly does is + give this quirk a path to actually rewrite the *persisted buffer* rather + than just a hover/diagnostic range — before this feature, the server never + computed byte offsets to build a document to save, it just accepted the + client's already-composed text verbatim. In practice this needs a client + to split one `\r\n` insertion into two separate ranged edits inside a + single `didChange` batch, positioned at the exact same coordinates for + both; no known editor's diff algorithm does this (VS Code/Neovim send + `\r\n` as one atomic edit). No panic, no data loss (both bytes survive, + just reordered), so it does not violate the "never corrupt" invariant in + the "produces wrong output" sense used elsewhere in this repo (no crash, + no truncation) but it is a genuine silent-divergence risk if a + pathological client ever does this. Recorded and pinned rather than fixed: + fixing it means deciding whether `line_content_end` should special-case "a + bare trailing `\r` with nothing after it, at the very end of the buffer or + the very end of a change-in-progress" — a `convert.rs` decision that + affects every handler, out of this feature's stated scope + (`sync.rs`/`main.rs`/`server.rs` only). Filed as a follow-up rather than + redesigned here. +- Multi-byte/astral columns (`a_ranged_change_over_multi_byte_text_edits_the_ + right_columns`, server.rs) and CRLF-on-one-line edits (`crlf_line_ends_ + survive_an_edit_on_the_line`, sync.rs) — re-verified by hand-tracing + `Positions::offset`, both clean, no off-by-one. + +**3. Full-sync regression — verified clean.** Diffed the old handler +(`git show aa303ce:crates/lucisv_server/src/server.rs`, the `next_back()` +form) against the new path: +- *Multiple rangeless changes*: old took only the literal last element via + `next_back()` (O(1), never touched the earlier ones); new applies all of + them via `apply_changes`, but each rangeless change fully replaces `text` + and continues, so the net result is identical — last one wins either way. + Confirmed by the dev's `the_last_of_several_rangeless_changes_wins` + (sync.rs) and `a_full_sync_clients_batch_still_lets_the_last_change_win` + (server.rs). The new path is `O(changes)` string clones instead of `O(1)` + for this specific case — a real but tiny and already-documented cost, not + a correctness regression. +- *Empty `contentChanges`*: old — `next_back()` on empty returns `None`, no + `set_document`/no `publish`. New — explicit `if p.content_changes. + is_empty() { return; }` before touching anything. Identical observable + behavior; confirmed by `one_notification_is_one_generation_bump_however_ + many_ranges`'s second half (server.rs) which checks the generation counter + does not move. +- *Unknown/never-opened uri*: old — `set_document(uri, change.text)` + unconditionally, no existence check. New — `self.workspace.document(&uri). + map_or("", ...)` then `apply_changes`; for a rangeless change this reduces + to the same `set_document(uri, change.text)`. Confirmed by `a_change_ + naming_a_buffer_that_was_never_opened_is_taken_as_written` (server.rs, + rangeless case). I did not find a server-level test of a *ranged* change + against a never-opened buffer, but it is exercised at the unit level + (`an_edit_into_an_empty_document` in sync.rs, since `apply_changes` is + handed `""` either way) and the handler code between the two cases is the + same three lines — low-severity gap, noting rather than adding a + redundant test. + +**4. Capability shape — verified clean, confirmed on the actual wire, not +just by reading the struct.** Ran the built binary directly through a +minimal `initialize` and inspected the raw JSON response (not just the +e2e/smoke assertions): `textDocumentSync` serialized as exactly +`{"change":2,"openClose":true,"save":{"includeText":false}}` — no +`willSave`/`willSaveWaitUntil` keys at all (`lsp_types:: +TextDocumentSyncOptions` marks both `#[serde(skip_serializing_if = "Option:: +is_none")]`, so `None` means genuinely absent from the wire, not `null`). +This is exactly what `vscode-languageclient` and Neovim's builtin client +parse as `{openClose: true, change: Incremental, save: {includeText: +false}}`, with the will-save fields correctly unadvertised for a future +round. `incremental_changes_are_advertised_and_applied_over_the_wire` +(e2e.rs) asserts `sync["change"] == 2`, `sync["openClose"] == true`, +`sync["save"]["includeText"] == false` — confirmed this really does pin the +shape, it isn't a no-op assertion. + +**5. Performance honesty — verified clean.** `Server::set_document` +(`crates/lucisv_server/src/state.rs:175`, called from the `DidChangeTextDocument` +arm exactly once per notification per the diff at `server.rs`) is the only +place a `Document::new` (full reparse/tokens/`Semantics`) happens. Inside +`sync::apply_changes`, only a `LineIndex::new` (a single linear scan for +`\n` bytes, not a parse) and a `String` allocation happen per *ranged* +change — that's the honest `O(changes × file)`, not `O(changes × file²)` +and not a hidden per-change reparse. Confirmed by reading `state.rs:175-179` +and by the fact that `self.generation` (bumped only inside `set_document`) +moves exactly once per notification regardless of range count, per +`one_notification_is_one_generation_bump_however_many_ranges`. + +**6. CLAUDE.md compliance — clean.** No `unwrap`/`expect`/`panic!` in +library code paths in `sync.rs` or the `server.rs` handler diff (`grep` +confirms the only `expect()`s introduced are inside `#[cfg(test)]` code in +`server.rs`, which CLAUDE.md permits). No new `#[allow]`. `sync.rs` has a +module doc comment and `apply_changes` has a doc comment. Feature README has +all six required sections. `TODO.md`'s §9b item text is unchanged aside from +the checkbox and an appended implementation-summary paragraph (allowed — the +rule is "leave the item text intact", not "add nothing"). The two annotation +edits to `docs/features/lucisv-server/README.md` and `docs/features/ +pull-diagnostics/README.md` are both dated 2026-08-26, self-identifying +("*(That last sentence records the state at the time of this QA pass +only...)*", "*(Still true after incremental sync, 2026-08-26: ...)*"), and +factual against the diff — neither rewrites the original text, both append. +One minor nit: the original (pre-existing) `TODO.md` §9b bullet's plan text +says "with a full-text fallback on any malformed change", but the shipped +implementation uses clamping instead of a full-text fallback for a malformed +change — a better and thoroughly-justified design choice (see the README's +Assumptions and Work log), but the Work log's "Deviations from the plan: +none" doesn't call out that the *originally-planned* mechanism changed +between the TODO's wording and the implementation. Cosmetic — the actual +behavior is fully and correctly documented elsewhere in the same README — +not asking for a fix, just noting it for the record. + +**Tests added this round** (all in `crates/lucisv_server/src/sync.rs`, +all passing): `a_deletion_starting_at_the_low_surrogate_index_preserves_ +the_character`, `a_deletion_ending_at_the_low_surrogate_index_consumes_ +the_whole_character`, `crlf_split_across_two_changes_in_one_batch_ +reorders_the_bytes`, `a_change_covering_the_final_newline_removes_exactly_ +it`, `zero_width_inserts_at_the_same_position_compose_in_batch_order`. + +**Verdict: committable as-is.** No dev follow-up required to ship; the +`\r\n`-split-across-changes behavior is worth a future look if `convert.rs` +is ever revisited, but it is pre-existing, unreachable by any known real +client, and now pinned by a test rather than silently latent. + +## Review + +### 2026-08-26 — lead + +Reviewed the diff, the work log and the QA log; re-ran fmt/clippy/the full +workspace suite/smoke.js myself, all clean. `apply_changes` is the right +shape: pure, total, no panicking slice, and the fresh-line-table-per-change +decision buys correctness with microseconds — the honest O(changes × file) +note is exactly how this repo trades. Inheriting the clamping rules from +`Positions::offset` instead of inventing a second set was the correct call, +and the `start > end` → pure-insertion rule is the only reading that cannot +lose the user's text. + +On QA's finding (a `\r` + `\n` split across two same-position inserts in +one batch lands as `\n\r`): accepted as pinned, not fixed. The root cause +is `convert.rs`'s pre-existing treatment of a trailing bare `\r`, which is +shared by every handler and out of this feature's scope; no real client +splits a CRLF across two changes of one batch, and the behavior is now +documented by a test rather than latent. If a cross-file `convert.rs` +round ever opens, this goes with it. The randomized cross-check (400 +sequences against an independent model), the deliberate-breakage check +that the line table really is rebuilt per change, and the wire-level +capability assertion give this the confidence a sync rewrite needs. +Accepted as shipped. diff --git a/docs/features/lucisv-server/README.md b/docs/features/lucisv-server/README.md index 0efe1ae..451f3e4 100644 --- a/docs/features/lucisv-server/README.md +++ b/docs/features/lucisv-server/README.md @@ -18,7 +18,8 @@ looks like language knowledge in here is a bug or a `Handshake` request. |---|---|---| | `textDocument/formatting` | `vlog_formatter::format_source` | One whole-document `TextEdit`, and only when the text actually changed | | `textDocument/rangeFormatting` | `vlog_formatter::format_range` | Same edit shape; the LSP `Range`'s *lines* become the engine's `--lines` (round 18) | -| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didChange`/`didSave`, full-text sync — **only for a client that does not pull**. See `docs/features/pull-diagnostics/README.md` | +| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didChange`/`didSave`, once per notification — **only for a client that does not pull**. See `docs/features/pull-diagnostics/README.md` | +| `textDocument/didChange` | `sync::apply_changes` | Incremental sync: the ranges are applied in order to the buffer the server holds, then one `set_document` + one `publish`. A rangeless change still replaces the whole buffer, so a full-sync client is unaffected. See `docs/features/incremental-sync/README.md` | | `textDocument/diagnostic`, `workspace/diagnostic` | the same parse+lint pass | The 3.17 pull model, served to a client that advertised `textDocument.diagnostic` — which is then pushed nothing at all. `resultId` is one generation counter, bumped by a buffer change and by an index rebuild; the workspace report covers the **open buffers**. Same feature README | | `textDocument/selectionRange` | `Document.tokens`, AST spans, `pairs::analyze` | Expand-selection: one strictly nesting chain per requested position, token → statement → block → item → file. No expression step. See `docs/features/selection-range/README.md` | | `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries | @@ -194,13 +195,16 @@ handler is milliseconds; the complexity of a worker pool buys nothing yet. | layer | rebuilt when | cost | |---|---|---| -| a document's `Semantics` + tokens + diagnostics | every `didOpen`/`didChange` | one file, full recompute | +| a document's `Semantics` + tokens + diagnostics | every `didOpen`/`didChange` — **once per notification**, however many ranges it carried | one file, full recompute | | the `WorkspaceIndex` | `initialize`, every `didSave`, every `workspace/didChangeWatchedFiles`, and a changed `lucisv.exclude`/`lucisv.filelist` | full re-scan of the roots | | the `` `include`` graph | with the `WorkspaceIndex`, from the same file list | a line scan per file (~6ms over the 860-file corpus). An open buffer's *own* includes are re-resolved on every request instead, so a line just typed is clickable before the next save | **Per-file recompute on every keystroke** is the strategy TODO.md §6 states ("per-file recompute is fine at Verilog file sizes"); salsa is explicitly -deferred there. +deferred there. Incremental *sync* did not change that: the wire now carries +ranges, but a `didChange` still throws the whole `Document` away and builds a +new one — one reparse per notification, which is also the one generation bump +the pull-diagnostics `resultId` depends on. **Open buffers override disk** in every index rebuild: the roots are walked, each file read, and then every open document with a path replaces the disk @@ -240,10 +244,17 @@ not see. ## Assumptions -- **Full-text document sync only.** The server advertises - `TextDocumentSyncKind::FULL`, so a `didChange` carries the whole buffer and - there is no incremental-edit application to get wrong. At Verilog file sizes - the wire cost is irrelevant. +- ~~**Full-text document sync only.**~~ **Superseded (incremental-sync, round + 2026-08-26).** The server advertises `TextDocumentSyncKind::INCREMENTAL` + inside a `TextDocumentSyncOptions` (`openClose: true`, + `save.includeText: false` — the same values a bare `Kind` resolved to + client-side, so only `change` moved). A `didChange` now carries ranges, and + `sync::apply_changes` applies them in order to the buffer the server holds: + each range is positioned against what the previous ones left, a change with + no range still replaces the whole document, and every out-of-range or + backwards position clamps rather than panicking. The server is now the only + holder of the buffer text, which is what makes that function's rules worth + reading in full: `docs/features/incremental-sync/README.md`. - **Every document URI is a `file:` URI.** `untitled:` buffers are accepted and served for everything single-file (diagnostics, tokens, formatting, symbols), but they have no path, so they never enter the workspace index. @@ -772,7 +783,10 @@ character-past-end-of-line, line-past-end-of-file, and both-past-end → all six combinations return graceful `null`/`[]`, no protocol error, no crash; server process survived and later exited cleanly (code 0). `textDocumentSync` confirmed `1` (Full) in the capabilities JSON, so the "stale/overlapping -`didChange`" scenario is moot as documented. +`didChange`" scenario is moot as documented. *(That last sentence records the +state at the time of this QA pass only: sync became incremental on +2026-08-26, and the clamping that keeps a desynced `didChange` harmless is +specified and tested in `docs/features/incremental-sync/README.md`.)* **Robustness.** All PASS. Malformed `Content-Length: notanumber` header, and a well-framed-but-garbage JSON body → in both cases the process does **not** diff --git a/docs/features/pull-diagnostics/README.md b/docs/features/pull-diagnostics/README.md index 8d773b4..558c01c 100644 --- a/docs/features/pull-diagnostics/README.md +++ b/docs/features/pull-diagnostics/README.md @@ -36,9 +36,12 @@ of squiggles for one file is the classic way to ship this feature wrong. full report — a cheap, correct answer. The error the coarse direction cannot make is the expensive one: a stale `unchanged` is a wrong squiggle left on screen. (The brief suggested `generation/doc-version`; the server - does not track document versions at all — full-text sync ignores them — so + does not track document versions at all — the sync path ignores them — so the second half would have been a constant. One number, documented, beats a - format that implies a precision that is not there.) + format that implies a precision that is not there.) *(Still true after + incremental sync, 2026-08-26: `DidChangeTextDocumentParams.version` is + unread, and one notification is still exactly one generation bump however + many ranges it carried.)* - **`inter_file_dependencies: true` is honest.** A save rebuilds the workspace index, and a buffer's diagnostics are computed against that index (`resolve_external` in `state.rs`), so a save in file A really can change