diff --git a/CHANGELOG.md b/CHANGELOG.md index 394b18c..6fc103b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,51 @@ All notable changes to lucisv are recorded here. Versions follow [semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes (see `README.md`) are the only frozen contract. +## 0.65.8 — 2026-11-19 + +### Find References next to a name, edits kept in order, and a startup that could take minutes + +(`docs/features/scan-ordering`; TODO §71.7. Three bugs, all older than this +series of releases.) + +- **Find All References, Go to Definition, hover, highlight and rename work + with the cursor just after a name.** A double-click, a click on the right + half of a name's last letter, or a click on a row of lucisv's References + view leaves the cursor there, and the server used to look at the character + *after* the name — so VS Code said "No references found" until you clicked + away and back. Nine requests now resolve the name the cursor touches + (hover, definition, type definition, references, document highlight, + prepare-rename, rename, and the call- and type-hierarchy prepares); the + ones with boundary rules of their own (completion, signature help, linked + editing, selection range) are unchanged. The References view now opens a + row with the cursor at the start of the name. Checked on every identifier + of 350 files: the answer at the end of a name equals the answer at its + start, and a rename there never touches the neighbouring token. +- **Edits made while the workspace is re-indexing are applied in order.** + The server held requests during a scan but applied notifications at once, + so a newer edit could overtake an older one still queued — and since the + editor sends edits as differences, the server's copy of the file then + differed from the editor's until the file was closed and reopened: wrong + symbols, wrong diagnostics, wrong references. Edits, opens, closes, saves + and the other notifications the editor sends are now applied in the order + sent. QA's independent driver: 9 118 bursts, 87 % of them sent mid-scan, + no wrong text, no lost or duplicated answer; the same check fails on + 0.65.7 at once. +- **Opening a file while the first index is built no longer makes that index + take minutes.** A request followed by a file open in the same batch was + handed back and re-held at every file of the startup scan: about 300–400 s + on OpenTitan instead of 2 s. Now a held batch is handed back at most once + per file actually opened; the same sequence takes 2.6–3.3 s. +- **Known and left for later**, all present before: a request held during a + scan is answered against the newest text, so a position-based request can + land on a different symbol if an edit moved the text under it (and rename + edits carry no document version for the client to reject a stale one by); + deleting a directory is not seen by the server (VS Code reports the folder, + which the client's source-file filter drops); an excluded file stays in the + index after it is closed; symlinked files can be held under two spellings; + renaming a port of a module defined twice gives an edit or a refusal at + random. + ## 0.65.7 — 2026-11-19 ### 0.65.6, built for every platform diff --git a/Cargo.lock b/Cargo.lock index 54934a0..cecd717 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -97,7 +97,7 @@ dependencies = [ [[package]] name = "lucisv" -version = "0.65.7" +version = "0.65.8" dependencies = [ "lucisv_core", "rayon", @@ -108,11 +108,11 @@ dependencies = [ [[package]] name = "lucisv_core" -version = "0.65.7" +version = "0.65.8" [[package]] name = "lucisv_mcp" -version = "0.65.7" +version = "0.65.8" dependencies = [ "lucisv_core", "serde", @@ -126,7 +126,7 @@ dependencies = [ [[package]] name = "lucisv_server" -version = "0.65.7" +version = "0.65.8" dependencies = [ "lsp-server", "lsp-types", @@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] name = "vlog_formatter" -version = "0.65.7" +version = "0.65.8" dependencies = [ "vlog_parser", ] [[package]] name = "vlog_linter" -version = "0.65.7" +version = "0.65.8" dependencies = [ "lucisv_core", "vlog_formatter", @@ -279,11 +279,11 @@ dependencies = [ [[package]] name = "vlog_parser" -version = "0.65.7" +version = "0.65.8" [[package]] name = "vlog_refactor" -version = "0.65.7" +version = "0.65.8" dependencies = [ "vlog_formatter", "vlog_parser", @@ -292,7 +292,7 @@ dependencies = [ [[package]] name = "vlog_semantic" -version = "0.65.7" +version = "0.65.8" dependencies = [ "vlog_parser", ] diff --git a/Cargo.toml b/Cargo.toml index 170a5aa..6225ba9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ members = [ ] [workspace.package] -version = "0.65.7" +version = "0.65.8" authors = ["Guoliang Chen"] edition = "2021" license = "MIT" diff --git a/TODO.md b/TODO.md index 56fd348..74ce050 100644 --- a/TODO.md +++ b/TODO.md @@ -7340,7 +7340,8 @@ subsection, plan and `docs/features//README.md` when its turn comes. file's instance and its parents in different shades — bright light orange for the instance, dimmer the further up — or anything in that spirit that makes the hierarchy easy to read. -- [ ] **71.7 Find References sometimes answers "not found"** on a +- [x] **71.7 Find References sometimes answers "not found"** (0.65.8, `docs/features/scan-ordering`: a server bug — the caret just past a name) + on a port/signal, then works after clicking elsewhere and back. VS Code or the server? Investigate, then fix what is ours. - [x] **71.8 Comments: no code colours inside them** (0.65.3, `docs/features/comment-highlighting`; the bracket colour is VS Code's, explained not changed) @@ -7410,14 +7411,14 @@ indexing, collide with each other and with §70's test files, and wait for stale answers), a fix round, a QA pass and a last small round. What the QA rounds and a read-only investigation turned up, all present before this wave, becomes lane **71.7** (the owner's Find References item, widened): - - [ ] A caret just past an identifier's last letter asks about the next + - [x] A caret just past an identifier's last letter asks about the next character: references, definition, hover and highlight come back empty (`server/dispatch.rs` `Server::offset`). This is the owner's "not found, then works after clicking back". - - [ ] A `didChange` arriving during a whole rescan can overtake an older + - [x] A `didChange` arriving during a whole rescan can overtake an older one still queued (`server/mod.rs` `process_batch`): with incremental sync the server's buffer is corrupted until the file is reopened. - - [ ] A burst `[request, didOpen]` during the startup scan is re-held at + - [x] A burst `[request, didOpen]` during the startup scan is re-held at every file (`server/index.rs` `answer_what_is_waiting`): the scan takes ~300 s on OpenTitan instead of ~1.7 s. - [ ] A watcher event naming only a directory leaves stale state; an @@ -7435,3 +7436,18 @@ indexing, collide with each other and with §70's test files, and wait for line) and shipped as 0.65.7 with 0.65.6's notes; `tools/gates.sh` gains a `cross` step so the next one is caught before the tag. Seven of the eight §71 items therefore have releases 0.65.2–0.65.5 and 0.65.7. + +- Wave 6 (lead, 2026-11-19): 71.7 shipped as 0.65.8. Left open from it and + from its QA, all older than this series: + - [ ] A request held during a scan is answered against the newest text; a + position-based one can resolve a different symbol when an edit moved + the text under it, and rename edits carry no document version. + - [ ] An unheld buffer opened while a scan runs is never taken in + afterwards; closing an unsaved in-scope buffer a rescan had indexed + leaves its text in the index. + - [ ] Renaming a port of a module defined twice gives an edit or a refusal + at random (`qa717/drv/dup.py`). + - [ ] Directory-only watcher events (needs a broader watcher + registration — the owner's call), excluded buffers after close (a + cheap fix belongs in the index layer: adding a file is a wide + change), symlink spellings. diff --git a/crates/lucisv_server/src/caret.rs b/crates/lucisv_server/src/caret.rs new file mode 100644 index 0000000..3f45b48 --- /dev/null +++ b/crates/lucisv_server/src/caret.rs @@ -0,0 +1,127 @@ +//! Which byte a "symbol under the cursor" request is about. +//! +//! An LSP position is a caret *between* two characters, and a span here is +//! end-exclusive, so a caret just past an identifier's last letter names the +//! character **after** the name. VS Code calls that caret "on the word" — a +//! double-click, a click on the right half of the last letter, or a jump that +//! selects the name all leave it there, and its own word highlight and the +//! title of a references search both use the word before it. Asking about the +//! next character instead answered `[]`, and VS Code said "No references +//! found" for a name it was showing as selected +//! (`docs/features/scan-ordering/README.md`, A1). +//! +//! The rule is VS Code's: a caret touching a name on its right edge is on +//! that name — unless a name also starts at the caret, which then wins +//! (`a|b` cannot happen; `a|.b` is on `a`, `a.|b` is on `b`). + +/// The byte offset a request about the name under the cursor should resolve, +/// given the caret's byte offset in `text`. +/// +/// Moves one byte left when the caret is just past a name and not at the +/// start of another; every other caret is returned unchanged. A name is an +/// identifier, keyword, system task, macro or number written with +/// [`is_name_byte`] — or an escaped identifier, `\` up to the whitespace that +/// ends it, whose own characters can be anything. +pub fn symbol_offset(text: &str, caret: u32) -> u32 { + let bytes = text.as_bytes(); + let at = caret as usize; + if at == 0 || at > bytes.len() || bytes.get(at).copied().is_some_and(is_name_byte) { + return caret; + } + let before = bytes[at - 1]; + if is_name_byte(before) || ends_an_escaped_identifier(bytes, at) { + return caret - 1; + } + caret +} + +/// Whether `byte` can be part of a simple identifier (IEEE 1800-2017 §5.6): +/// a letter, a digit, `_` or `$`. A system task's leading `$` and a macro +/// name after its backtick are covered by the same set. +fn is_name_byte(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$' +} + +/// Whether the caret at `at` sits on the whitespace (or the end of the text) +/// that terminates an escaped identifier — a `\` followed by at least one +/// non-whitespace byte, all of it before the caret. +fn ends_an_escaped_identifier(bytes: &[u8], at: usize) -> bool { + if bytes.get(at).is_some_and(|b| !b.is_ascii_whitespace()) { + return false; + } + let start = bytes[..at].iter().rposition(u8::is_ascii_whitespace).map_or(0, |ws| ws + 1); + at - start >= 2 && bytes[start] == b'\\' +} + +#[cfg(test)] +mod tests { + use super::symbol_offset; + + /// The offset `symbol_offset` picks for the caret written as `|` in + /// `marked`, as the character it lands on (`None` past the end). + fn lands_on(marked: &str) -> Option { + let caret = marked.find('|').expect("a caret") as u32; + let text = marked.replacen('|', "", 1); + let at = symbol_offset(&text, caret) as usize; + text[at..].chars().next() + } + + #[test] + fn a_caret_just_past_a_name_is_on_its_last_letter() { + assert_eq!(lands_on("logic tx|,"), Some('x')); + assert_eq!(lands_on("assign y = tx|;"), Some('x')); + assert_eq!(lands_on("tx|"), Some('x'), "at the end of the text"); + assert_eq!(lands_on("logic tx|\nwire w;"), Some('x'), "at the end of a line"); + assert_eq!(lands_on("logic tx|\r\nwire w;"), Some('x'), "before a CRLF"); + } + + #[test] + fn a_caret_on_or_inside_a_name_is_left_alone() { + assert_eq!(lands_on("logic |tx;"), Some('t'), "at the start"); + assert_eq!(lands_on("logic t|x;"), Some('x'), "in the middle"); + } + + #[test] + fn a_caret_touching_two_names_takes_the_one_that_starts_there() { + // VS Code's word at `a|.b` is `a`; at `a.|b` it is `b`. + assert_eq!(lands_on("u_a|.sig"), Some('a'), "before the dot: the instance"); + assert_eq!(lands_on("u_a.|sig"), Some('s'), "after the dot: the member"); + assert_eq!(lands_on(".clk|(clk_i)"), Some('k'), "a port name before its paren"); + assert_eq!(lands_on(".clk(|clk_i)"), Some('c'), "the signal after the paren"); + assert_eq!(lands_on("mem|[3]"), Some('m'), "a name before an index"); + } + + #[test] + fn a_caret_after_anything_but_a_name_is_left_alone() { + assert_eq!(lands_on("a = b;|"), None, "past a semicolon at the end"); + assert_eq!(lands_on("a = b; |"), None, "past whitespace"); + assert_eq!(lands_on("f(x)|;"), Some(';'), "past a paren"); + assert_eq!(lands_on("|"), None, "an empty text"); + assert_eq!(lands_on("|tx"), Some('t'), "the very start"); + } + + #[test] + fn system_tasks_macros_and_keywords_are_names_too() { + assert_eq!(lands_on("$display|("), Some('y')); + assert_eq!(lands_on("`WIDTH|-1"), Some('H')); + assert_eq!(lands_on("begin|\n"), Some('n'), "so a keyword pair highlights"); + } + + #[test] + fn an_escaped_identifier_ends_at_its_whitespace() { + // `\a+b ` is one name whose last byte is not an identifier byte. + assert_eq!(lands_on(r"assign \a+b+ |= 1;"), Some('='), "past the space: not on it"); + assert_eq!(lands_on(r"assign \a+b+| = 1;"), Some('+'), "on the space that ends it"); + assert_eq!(lands_on(r"\bus[0]|"), Some(']'), "at the end of the text"); + assert_eq!(lands_on(r"x = a \| b;"), Some(' '), "a lone backslash is not a name"); + } + + #[test] + fn non_ascii_text_before_the_name_does_not_move_the_byte() { + // The caret arrives as a byte offset already converted from UTF-16; + // the rule reads bytes, and a multi-byte character is never a name. + assert_eq!(lands_on("// é\nlogic tx|;"), Some('x')); + assert_eq!(lands_on("é|tx"), Some('t'), "a name starting after a non-ASCII letter"); + assert_eq!(lands_on("é|;"), Some(';'), "a non-ASCII letter is not a name"); + } +} diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index b10a158..44d95b0 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -8,6 +8,7 @@ mod auto_style; mod candidates; +mod caret; mod code_action; mod completion; mod convert; diff --git a/crates/lucisv_server/src/server/batch.rs b/crates/lucisv_server/src/server/batch.rs index be855e6..24fdb34 100644 --- a/crates/lucisv_server/src/server/batch.rs +++ b/crates/lucisv_server/src/server/batch.rs @@ -4,20 +4,20 @@ //! forwarder here moves them onto a queue of our own so that "everything the //! client has already sent" is a question with an answer. The rest of the //! file reads a burst without handling anything in it: which requests it -//! cancels, which files it opens, and — for a `didOpen` — whether the index -//! scope grew, stayed, or has to be rebuilt. The loop in `mod.rs` and the +//! cancels and — for a `didOpen` — whether the index scope grew, stayed, or +//! has to be rebuilt. (Which files a burst *opens* is not read here any more: +//! a `didOpen` changes a scan's order when it is applied, never because a +//! batch carries it — `docs/features/scan-ordering/README.md`.) The loop in `mod.rs` and the //! mid-scan drain in `index.rs` both read bursts through here, which is why //! this is its own file rather than part of either. use std::collections::HashSet; use lsp_server::{Connection, Message, RequestId, Response}; -use lsp_types::notification::{Cancel, DidOpenTextDocument, Notification as _}; +use lsp_types::notification::{Cancel, Notification as _}; use lsp_types::request::{Request as _, Shutdown}; use lsp_types::{CancelParams, NumberOrString}; -use super::dispatch::document_uri; - /// Whether this message is the `shutdown` request. `lsp-server` keeps its own /// answer to that question private, so it is asked here by method name — the /// same name `handle_shutdown` matches on. @@ -167,22 +167,9 @@ pub(super) fn widen_of(before: &[std::path::PathBuf], after: &[std::path::PathBu Widen::Added(after.iter().filter(|dir| !before.contains(dir)).cloned().collect()) } -/// The files a burst opened, in the order the client opened them. -/// -/// Read off the raw messages rather than off the workspace afterwards, -/// because the workspace holds its buffers in a `HashMap` and "which file did -/// the user just open" is a question about order. -pub(super) fn opened_in(batch: &[Message]) -> Vec { - batch - .iter() - .filter_map(|message| match message { - Message::Notification(notification) - if notification.method == DidOpenTextDocument::METHOD => - { - document_uri(¬ification.params) - } - _ => None, - }) - .filter_map(|uri| crate::uri::uri_to_path(&uri)) - .collect() +/// Whether a message changes what the server holds — any notification but a +/// `$/cancelRequest`. These are the messages whose order is the order the +/// client sent them in (`Server::must_hold`). +pub(super) fn changes_state(message: &Message) -> bool { + matches!(message, Message::Notification(n) if n.method != Cancel::METHOD) } diff --git a/crates/lucisv_server/src/server/dispatch.rs b/crates/lucisv_server/src/server/dispatch.rs index 49891ab..d6e625b 100644 --- a/crates/lucisv_server/src/server/dispatch.rs +++ b/crates/lucisv_server/src/server/dispatch.rs @@ -44,9 +44,10 @@ use serde_json::Value; use super::client::ms; use super::Server; use crate::{ - code_action, completion, design_hierarchy, extract, file_ops, folding, format, hierarchy, - hover, imports, includes, inlay, inline, inline_module, lens, linked, lint, lint_trace, nav, - pairs, ports, rename, selection, signature, symbols, tokens, type_def, type_hierarchy, + caret, code_action, completion, design_hierarchy, extract, file_ops, folding, format, + hierarchy, hover, imports, includes, inlay, inline, inline_module, lens, linked, lint, + lint_trace, nav, pairs, ports, rename, selection, signature, symbols, tokens, type_def, + type_hierarchy, }; /// The requests whose empty answer may mean "this scan has not reached the @@ -197,7 +198,7 @@ impl Server { HoverRequest::METHOD => decode(request).and_then(|p: HoverParams| { let at = p.text_document_position_params; let (uri, position) = (at.text_document.uri, at.position); - self.offset(&uri, position) + self.symbol_offset(&uri, position) .map(|offset| hover::hover(&self.workspace, &uri, offset)) .map_or(Ok(Value::Null), to_value) }), @@ -205,7 +206,7 @@ impl Server { let at = p.text_document_position_params; let (uri, position) = (at.text_document.uri, at.position); let locations = self - .offset(&uri, position) + .symbol_offset(&uri, position) .map(|offset| nav::definition(&self.workspace, &uri, offset)) .unwrap_or_default(); to_value(GotoDefinitionResponse::Array(locations)) @@ -221,7 +222,7 @@ impl Server { let at = p.text_document_position_params; let (uri, position) = (at.text_document.uri, at.position); let locations = self - .offset(&uri, position) + .symbol_offset(&uri, position) .map(|offset| type_def::type_definition(&self.workspace, &uri, offset)) .unwrap_or_default(); to_value(GotoTypeDefinitionResponse::Array(locations)) @@ -255,7 +256,7 @@ impl Server { let at = p.text_document_position; let (uri, position) = (at.text_document.uri, at.position); let locations = self - .offset(&uri, position) + .symbol_offset(&uri, position) .map(|offset| nav::references(&self.workspace, &uri, offset, include)) .unwrap_or_default(); to_value(locations) @@ -271,7 +272,7 @@ impl Server { decode(request).and_then(|p: DocumentHighlightParams| { let at = p.text_document_position_params; let (uri, position) = (at.text_document.uri, at.position); - let found = self.offset(&uri, position).and_then(|offset| { + let found = self.symbol_offset(&uri, position).and_then(|offset| { let doc = self.workspace.document(&uri)?; pairs::highlights(doc, offset) .or_else(|| nav::document_highlights(doc, offset)) @@ -444,7 +445,7 @@ impl Server { PrepareRenameRequest::METHOD => { decode(request).and_then(|at: TextDocumentPositionParams| { let (uri, position) = (at.text_document.uri, at.position); - let Some(offset) = self.offset(&uri, position) else { + let Some(offset) = self.symbol_offset(&uri, position) else { return Ok(Value::Null); }; match rename::prepare(&self.workspace, &uri, offset) { @@ -457,7 +458,7 @@ impl Server { let new_name = p.new_name; let at = p.text_document_position; let (uri, position) = (at.text_document.uri, at.position); - let Some(offset) = self.offset(&uri, position) else { + let Some(offset) = self.symbol_offset(&uri, position) else { return Ok(Value::Null); }; // One `timing: rename trace …` line behind `--verbose`, and @@ -588,7 +589,7 @@ impl Server { decode(request).and_then(|p: CallHierarchyPrepareParams| { let at = p.text_document_position_params; let (uri, position) = (at.text_document.uri, at.position); - self.offset(&uri, position) + self.symbol_offset(&uri, position) .and_then(|offset| hierarchy::prepare(&self.workspace, &uri, offset)) .map_or(Ok(Value::Null), to_value) }) @@ -611,7 +612,7 @@ impl Server { decode(request).and_then(|p: TypeHierarchyPrepareParams| { let at = p.text_document_position_params; let (uri, position) = (at.text_document.uri, at.position); - self.offset(&uri, position) + self.symbol_offset(&uri, position) .and_then(|offset| type_hierarchy::prepare(&self.workspace, &uri, offset)) .map_or(Ok(Value::Null), to_value) }) @@ -660,6 +661,17 @@ impl Server { fn offset(&self, uri: &Uri, position: Position) -> Option { self.workspace.document(uri).map(|doc| doc.positions().offset(position)) } + + /// [`Server::offset`] for a request about the name under the cursor: a + /// caret just past a name is on that name, as VS Code's own word rule + /// says ([`caret::symbol_offset`]). Requests with a boundary rule of + /// their own — completion, signature help, linked editing, on-type + /// formatting — keep the caret as sent; the table is in + /// `docs/features/scan-ordering/README.md`. + fn symbol_offset(&self, uri: &Uri, position: Position) -> Option { + let doc = self.workspace.document(uri)?; + Some(caret::symbol_offset(&doc.text, doc.positions().offset(position))) + } } /// Why a request could not be answered, in the protocol's own terms. diff --git a/crates/lucisv_server/src/server/index.rs b/crates/lucisv_server/src/server/index.rs index c628020..8b65f99 100644 --- a/crates/lucisv_server/src/server/index.rs +++ b/crates/lucisv_server/src/server/index.rs @@ -14,7 +14,6 @@ use std::path::Path; use lsp_types::ProgressToken; -use super::batch::opened_in; use super::client::{notify_on, plural}; use super::progress::IndexWatch; use super::{Server, INTERLEAVE_ABOVE}; @@ -305,6 +304,7 @@ impl Server { self.scanning = false; // A neighbourhood can only be owed by a scan, and there is none now. self.head_owed = false; + self.opened_mid_scan = false; self.answer_what_was_deferred(); warnings } @@ -477,6 +477,8 @@ impl Server { while let Ok(message) = self.queue.try_recv() { arrived.push(message); } + #[cfg(test)] + super::probe::at_interleave_point(owed, &mut arrived); // A quiet scan pays nothing at all, and that is a promise: the cadence // is asked only when there is something for a publish to be *for*. if !owed && arrived.is_empty() && self.deferred.is_empty() { @@ -493,15 +495,22 @@ impl Server { if batch.is_empty() { return false; } - // A `didOpen` in this burst names a folder the work list has not been - // ordered around yet, so the requests behind it in the burst are owed - // that ordering before they are answered — which is exactly what the - // widen this `didOpen` used to trigger made them wait for. The flag is - // set *before* the batch is applied, so `must_wait` holds them; it is - // recomputed below once the new head segment is known. - let opened = !opened_in(&batch).is_empty(); - self.head_owed |= opened; + // A `didOpen` this burst *applies* names a folder the work list has + // not been ordered around yet, so the requests behind it are owed that + // ordering before they are answered — which is exactly what the widen + // this `didOpen` used to trigger made them wait for. The `didOpen` arm + // sets `head_owed` as it applies one, so `must_wait` holds what is + // behind it; it is recomputed below once the new head is known. + // + // **Applied, not merely present.** Before 2026-11-19 the flag was read + // off the batch before it was handled, so a `didOpen` the batch held + // unapplied behind a request re-held that request, and the same batch + // came back at every file — a five-minute startup scan on OpenTitan + // (`docs/features/scan-ordering/README.md`, C). Only a message that + // has been applied changes the scan's state, and each is applied once. + self.opened_mid_scan = false; self.stopped = !matches!(self.process_batch(batch), Ok(false)); + let opened = std::mem::take(&mut self.opened_mid_scan); // The files the user has just opened, and the folders around them, are // what they are looking at, so they are indexed next rather than when // the alphabet reaches them — the open-first rule, for buffers opened diff --git a/crates/lucisv_server/src/server/mod.rs b/crates/lucisv_server/src/server/mod.rs index 94778bd..678908c 100644 --- a/crates/lucisv_server/src/server/mod.rs +++ b/crates/lucisv_server/src/server/mod.rs @@ -46,7 +46,7 @@ use lsp_types::{SemanticToken, Uri}; use crate::state::Workspace; -use batch::{burst, cancelled_id, cancelled_in, cancelled_response}; +use batch::{burst, cancelled_id, cancelled_in, cancelled_response, changes_state}; use dispatch::names_nowhere; mod batch; @@ -57,6 +57,8 @@ mod formatting; mod index; mod large_file; mod notification; +#[cfg(test)] +mod probe; mod progress; mod semantic_tokens; mod startup; @@ -222,6 +224,12 @@ pub struct Server { /// (`docs/features/perf5-p4/README.md`). False whenever no scan is /// running, and false during a scan with no neighbourhood to wait for. head_owed: bool, + /// Whether a `didOpen` was **applied** while the scan now running had + /// messages to answer — set where the `didOpen` is applied, and read by + /// that scan's drain once the batch carrying it has been handled. Never + /// read off a batch, which may hold the `didOpen` unapplied behind a + /// request (`docs/features/scan-ordering/README.md`, C). + opened_mid_scan: bool, /// A rescan asked for while a scan was running. Coalesced: any number of /// requests is one more scan when this one ends, whatever asked for them. rescan_wanted: bool, @@ -239,6 +247,12 @@ pub struct Server { /// [`Server::must_wait`] — this is the order contract, not a queue of its /// own. held: Vec, + /// How many notifications older than the message being handled are still + /// unapplied in the bursts it is nested inside — the tail of a burst + /// whose message started a scan, while that scan answers newer ones. One + /// of the two places an older notification can wait; `held` is the other + /// ([`Server::must_hold`]). Cancels are not counted: they change nothing. + behind: usize, /// Navigation requests a scan answered **empty** while it was still /// growing the index, to be asked again at its next publish. /// @@ -398,52 +412,42 @@ impl Server { // The `$/cancelRequest`s this burst has already carried, kept only // long enough to put them back if a request behind them has to wait. let mut consumed_cancels: Vec = Vec::new(); + // The bursts this one is nested inside, and the notifications of them + // still unapplied; restored on the way out (an `Err` is a client that + // has gone, and nothing reads this after it). + let outer = self.behind; + let mut unapplied = batch.iter().filter(|m| changes_state(m)).count(); let mut messages = batch.into_iter(); while let Some(message) = messages.next() { - // A request that must wait takes everything behind it with it, or + // What is unapplied *older* than this message is only ever in the + // bursts around this one — the rest of this burst is newer. + self.behind = outer; + // A message that must wait takes everything behind it with it, or // the burst's arrival order would not survive the wait — // `shutdown` included, because a request sent before a shutdown // is a request the client is still owed an answer to. - if self.must_wait() && matches!(message, Message::Request(_)) { + if self.must_hold(&message) { + self.cancel_deferred(&message)?; self.say_held(&message); - // The cancels this burst carried were consumed on the way - // here, and `cancelled_in` runs again over the held batch — so - // they go back in front of what they cancel rather than being - // lost. A cancel naming nothing in the held batch is dropped - // there exactly as it was dropped here. let mut rest: Vec = std::mem::take(&mut consumed_cancels); rest.push(message); rest.extend(messages); - rest.extend(self.held.split_off(already_waiting)); - self.held.extend(rest); + self.hold(rest, already_waiting); return Ok(false); } + unapplied -= usize::from(changes_state(&message)); + // Whatever this message starts — a scan, whose drain answers the + // client's newer messages — runs with the rest of this burst's + // notifications still unapplied, and newer ones must not overtake + // them. + self.behind = outer + unapplied; match message { Message::Request(request) => { if self.connection.handle_shutdown(&request)? { + self.behind = outer; return Ok(true); } - // Removed as it is used: a second cancel for the same id - // then finds nothing, and the set cannot outlive the burst. - let response = if cancelled.remove(&request.id) { - cancelled_response(request.id) - } else { - // A navigation request whose answer would be `[]` only - // because the scan has not reached its target yet is - // asked again at the next publish rather than answered - // with nowhere ([`Server::deferred`]). - let again = self.ask_again_if_empty(&request); - let response = self.request(request); - match again.filter(|_| names_nowhere(&response)) { - Some(request) => { - self.say_deferred(&request); - self.deferred.push(Message::Request(request)); - continue; - } - None => response, - } - }; - self.connection.sender.send(Message::Response(response))?; + self.answer_from_batch(request, &mut cancelled)?; } // The cancels themselves are consumed here — `notification` // has nothing to do with one, and everything it could do has @@ -463,9 +467,53 @@ impl Server { Message::Response(response) => self.response(response), } } + self.behind = outer; Ok(false) } + /// Answer one request a burst carried: `RequestCancelled` when the burst + /// also carried its cancel, set aside for the next publish when it is a + /// navigation request the scan has not reached the answer to yet, and + /// computed otherwise. + fn answer_from_batch( + &mut self, + request: lsp_server::Request, + cancelled: &mut HashSet, + ) -> Result<(), Box> { + // Removed as it is used: a second cancel for the same id then finds + // nothing, and the set cannot outlive the burst. + let response = if cancelled.remove(&request.id) { + cancelled_response(request.id) + } else { + // A navigation request whose answer would be `[]` only because + // the scan has not reached its target yet is asked again at the + // next publish rather than answered with nowhere + // ([`Server::deferred`]). + let again = self.ask_again_if_empty(&request); + let response = self.request(request); + if let Some(request) = again.filter(|_| names_nowhere(&response)) { + self.say_deferred(&request); + self.deferred.push(Message::Request(request)); + return Ok(()); + } + response + }; + self.connection.sender.send(Message::Response(response))?; + Ok(()) + } + + /// Put `rest` — the cancels the burst already carried, the message that + /// must wait, and the rest of its burst, in that order — into `held`: in + /// front of whatever a scan this burst started has held since + /// `already_waiting`, behind everything older. The cancels go back in + /// front of what they cancel because `cancelled_in` runs again over the + /// held batch; one naming nothing in it is dropped there, as it would + /// have been here. + fn hold(&mut self, mut rest: Vec, already_waiting: usize) { + rest.extend(self.held.split_off(already_waiting)); + self.held.extend(rest); + } + /// Honour a `$/cancelRequest` naming a request in [`Server::deferred`]: /// take it out and answer it cancelled. A cancel naming anything else is /// left to the batch's own rule. @@ -528,6 +576,44 @@ impl Server { || self.head_owed } + /// Whether `message`, reaching `process_batch` right now, must be held + /// instead of handled. + /// + /// **No notification overtakes an older notification.** Only a + /// notification changes what the server holds — a buffer's text, which + /// buffers are open, the settings, the folders, what is on disk — so the + /// order those are applied in is the order they were sent in, and nothing + /// a request is later answered against can be a state the client never + /// had. A notification waits while an older one is unapplied: in `held`, + /// or in the tail of a burst whose message started the scan now draining + /// ([`Server::behind`]). Before 2026-11-19 a `didChange` drained mid-scan + /// was applied ahead of an older `didChange` still waiting, and an + /// incremental edit landed on the wrong text + /// (`docs/features/scan-ordering/README.md`, B). + /// + /// **Not "no notification overtakes a request".** A request held by the + /// contract above is answered against whatever was applied by the time + /// it is replayed — as every request answered late always was — and a + /// notification behind it with nothing older unapplied is applied at + /// once. Holding it too would cost the startup its first `didOpen` + /// (QA-3) and buy no state the client could see. + /// + /// A **cancel** changes nothing the server holds, so it never makes a + /// notification wait; it waits itself whenever anything is held, so that + /// one naming a held request is replayed beside it and honoured. A + /// **response** is never held: it answers a request the server made, and + /// no ordering promise ties it to the editor's stream + /// (`take_the_answer_out_of_held` in `startup.rs` makes the same + /// argument). + fn must_hold(&self, message: &Message) -> bool { + match message { + Message::Request(_) => self.must_wait(), + Message::Notification(_) if !changes_state(message) => !self.held.is_empty(), + Message::Notification(_) => self.behind > 0 || self.held.iter().any(changes_state), + Message::Response(_) => false, + } + } + /// Whether a scan is running or already owed — the two states in which a /// rescan trigger records that one more scan is wanted instead of running /// one itself. diff --git a/crates/lucisv_server/src/server/notification.rs b/crates/lucisv_server/src/server/notification.rs index 5b73a02..127b0c3 100644 --- a/crates/lucisv_server/src/server/notification.rs +++ b/crates/lucisv_server/src/server/notification.rs @@ -96,6 +96,14 @@ impl Server { // rungs, which an open buffer cannot widen. let before = self.workspace.scope_dirs(); self.set_document(uri.clone(), p.text_document.text); + // Mid-scan, the work list is re-ordered round this buffer + // once the batch carrying it is handled, and what is behind + // it in that batch waits for the new order + // (`Server::answer_what_is_waiting`). + if self.scanning { + self.head_owed = true; + self.opened_mid_scan = true; + } match widen_of(&before, &self.workspace.scope_dirs()) { Widen::Nothing => self.publish(&uri), Widen::Added(dirs) => self.reindex_widened(dirs), diff --git a/crates/lucisv_server/src/server/probe.rs b/crates/lucisv_server/src/server/probe.rs new file mode 100644 index 0000000..7ff93c4 --- /dev/null +++ b/crates/lucisv_server/src/server/probe.rs @@ -0,0 +1,79 @@ +//! A test's hand on the mid-scan drain: what the client "sends" at each +//! interleave point, and how often a scan handed back what it was holding. +//! +//! Test-only. The real transport cannot be timed against a scan's files — +//! the forwarder thread delivers whenever it likes — so a test that needs a +//! burst to land *at the third file* scripts it here, and the drain appends it +//! to what `try_recv` found, exactly where a real arrival would be. Thread +//! local because every test drives its server on its own thread. + +use std::cell::RefCell; +use std::collections::VecDeque; + +use lsp_server::Message; + +#[derive(Default)] +struct Probe { + /// Bursts to deliver, one per interleave point, oldest first. + arrivals: VecDeque>, + /// Interleave points reached since the last [`take_counts`]. + points: usize, + /// How many of those handed messages the scan had been holding back to + /// `process_batch` — what loops when a held batch is re-held at every file. + handed_back: usize, + /// How many scripted bursts a scan received. + delivered: usize, +} + +/// What [`take_counts`] reports. +#[derive(Debug, Clone, Copy)] +pub(super) struct Counts { + /// Interleave points reached. + pub(super) points: usize, + /// Held batches handed back to `process_batch`. + pub(super) handed_back: usize, + /// Scripted bursts delivered mid-scan. + pub(super) delivered: usize, +} + +thread_local! { + static PROBE: RefCell = RefCell::default(); +} + +/// Script `bursts` to arrive at the next interleave points, one each, behind +/// anything already scripted. +pub(super) fn script(bursts: impl IntoIterator>) { + PROBE.with(|probe| probe.borrow_mut().arrivals.extend(bursts)); +} + +/// What is still scripted and has not arrived — the bursts a scan ended +/// before reaching, which the test then delivers as `run` would. +pub(super) fn unarrived() -> Vec> { + PROBE.with(|probe| probe.borrow_mut().arrivals.drain(..).collect()) +} + +/// What the scans did since the last call. +pub(super) fn take_counts() -> Counts { + PROBE.with(|probe| { + let mut probe = probe.borrow_mut(); + Counts { + points: std::mem::take(&mut probe.points), + handed_back: std::mem::take(&mut probe.handed_back), + delivered: std::mem::take(&mut probe.delivered), + } + }) +} + +/// Called by the drain at every interleave point: count it, and deliver the +/// next scripted burst behind whatever the transport delivered. +pub(super) fn at_interleave_point(handed_back: bool, arrived: &mut Vec) { + PROBE.with(|probe| { + let mut probe = probe.borrow_mut(); + probe.points += 1; + probe.handed_back += usize::from(handed_back); + if let Some(burst) = probe.arrivals.pop_front() { + probe.delivered += 1; + arrived.extend(burst); + } + }); +} diff --git a/crates/lucisv_server/src/server/startup.rs b/crates/lucisv_server/src/server/startup.rs index 86a9761..13518fa 100644 --- a/crates/lucisv_server/src/server/startup.rs +++ b/crates/lucisv_server/src/server/startup.rs @@ -163,11 +163,13 @@ impl Server { queue, scanning: false, head_owed: false, + opened_mid_scan: false, staging: false, rescan_wanted: false, answering_a_rescan: false, stopped: false, held: Vec::new(), + behind: 0, deferred: Vec::new(), verbose, born: Instant::now(), diff --git a/crates/lucisv_server/src/server/tests/caret_boundary.rs b/crates/lucisv_server/src/server/tests/caret_boundary.rs new file mode 100644 index 0000000..8763923 --- /dev/null +++ b/crates/lucisv_server/src/server/tests/caret_boundary.rs @@ -0,0 +1,153 @@ +//! A caret just past a name is on that name, for every request about the +//! symbol under the cursor (`docs/features/scan-ordering/README.md`, A1). +//! +//! The owner's report: Find All References said "No references found" for a +//! port, and worked again after clicking away and back. A double-click, a +//! click on the right half of the last letter, or a row of lucisv's own +//! References view leaves the caret *after* the name; spans are +//! end-exclusive, so the request used to ask about the next character. + +use super::*; + +const SOURCE: &str = "\ +module sub (input logic clk); +endmodule +module top; + logic clk; + sub u_sub (.clk(clk)); + typedef logic [3:0] nib_t; + nib_t n; + assign n = 4'd1; +endmodule +class base; +endclass +class child extends base; +endclass +"; + +/// A session with [`SOURCE`] open, and its uri. +fn opened(tag: &str) -> (Tree, Session, Uri) { + let tree = Tree::new(tag); + tree.write("top.sv", SOURCE); + let mut session = Session::wide(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("top.sv"), SOURCE); + let _ = session.drain(); + (tree, session, uri) +} + +/// The params every position request below sends, plus what `method` adds. +fn at(method: &str, uri: &Uri, line: u32, character: u32) -> Value { + let mut params = serde_json::json!({ + "textDocument": { "uri": uri }, + "position": { "line": line, "character": character }, + }); + if method == References::METHOD { + params["context"] = serde_json::json!({ "includeDeclaration": true }); + } + if method == Rename::METHOD { + params["newName"] = serde_json::json!("renamed"); + } + params +} + +/// The answer, or the error's message — a declined rename is an answer too. +fn answer(session: &mut Session, method: &str, params: Value) -> Value { + match session.request(method, params).response_result { + Ok(value) => value, + Err(error) => Value::String(error.message), + } +} + +/// Whether an answer says nothing: `null`, `[]`, or a refusal. +fn says_nothing(value: &Value) -> bool { + value.is_null() || value.as_array().is_some_and(Vec::is_empty) || value.is_string() +} + +/// For `name` on `line`, the answer at the name's first column, just past +/// its last character, and one column further right. +fn around(session: &mut Session, uri: &Uri, method: &str, line: u32, name: &str) -> [Value; 3] { + let text = SOURCE.lines().nth(line as usize).expect("the line"); + let start = find_word(text, name) as u32; + let end = start + name.len() as u32; + [start, end, end + 1].map(|column| answer(session, method, at(method, uri, line, column))) +} + +/// The byte column of `name` as a whole word on `text`. +fn find_word(text: &str, name: &str) -> usize { + let is_name = |c: char| c.is_ascii_alphanumeric() || c == '_'; + text.match_indices(name) + .find(|(at, _)| { + let before = text[..*at].chars().next_back().is_none_or(|c| !is_name(c)); + let after = text[at + name.len()..].chars().next().is_none_or(|c| !is_name(c)); + before && after + }) + .map(|(at, _)| at) + .expect("the name on its line") +} + +#[test] +fn every_symbol_request_answers_the_same_just_past_a_name_as_at_its_start() { + let (_tree, mut session, uri) = opened("caretend"); + // (method, line, name) — each followed by a character that is not part + // of a name, so one column further right answers nothing. The two + // hierarchy prepares are the exception: they answer for the whole + // instantiation or declaration, so one further right is still the name. + let cases = [ + (References::METHOD, 3, "clk"), + (GotoDefinition::METHOD, 7, "n"), + (HoverRequest::METHOD, 3, "clk"), + (DocumentHighlightRequest::METHOD, 3, "clk"), + (PrepareRenameRequest::METHOD, 3, "clk"), + (Rename::METHOD, 3, "clk"), + (GotoTypeDefinition::METHOD, 7, "n"), + (CallHierarchyPrepare::METHOD, 4, "sub"), + (TypeHierarchyPrepare::METHOD, 9, "base"), + ]; + for (method, line, name) in cases { + let [start, end, beyond] = around(&mut session, &uri, method, line, name); + assert!(!says_nothing(&start), "{method} at the start of {name} answers: {start}"); + assert_eq!(end, start, "{method} just past {name} answers as at its start"); + if ![CallHierarchyPrepare::METHOD, TypeHierarchyPrepare::METHOD].contains(&method) { + assert!(says_nothing(&beyond), "{method} one further right: nothing, got {beyond}"); + } + } +} + +#[test] +fn a_caret_after_a_dot_is_on_the_member_and_before_it_on_the_instance() { + // `u_sub.clk` is not in the fixture, but `.clk(` is: the caret between + // `.` and `clk` is on `clk`, and just past `clk` (before `(`) too. + let (_tree, mut session, uri) = opened("caretdot"); + let text = SOURCE.lines().nth(4).expect("line 4"); + let port = find_word(text, "clk") as u32; + let refs = |s: &mut Session, column| { + answer(s, References::METHOD, at(References::METHOD, &uri, 4, column)) + }; + let on_port = refs(&mut session, port); + assert!(!says_nothing(&on_port)); + assert_eq!(refs(&mut session, port + 3), on_port, "before the paren: the port"); + let signal = refs(&mut session, port + 4); + assert!(!says_nothing(&signal), "after the paren: the signal"); + assert_ne!(signal, on_port, "the signal's references are not the port's"); + assert_eq!(refs(&mut session, port + 7), signal, "before the closing paren: the signal"); +} + +#[test] +fn the_column_past_a_name_is_counted_in_utf16_after_non_ascii_text() { + // `é` is two bytes and one UTF-16 unit: the caret arrives in units, is + // converted to a byte offset, and only then moved back one byte. + let text = "module m;\n /* é ü */ logic tx;\n assign tx = 1'b0;\nendmodule\n"; + let tree = Tree::new("caretutf16"); + tree.write("m.sv", text); + let mut session = Session::wide(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), text); + let line = text.lines().nth(1).expect("line 1"); + let start = line[..line.find("tx").expect("tx")].encode_utf16().count() as u32; + let refs = |s: &mut Session, column| { + answer(s, References::METHOD, at(References::METHOD, &uri, 1, column)) + }; + let at_start = refs(&mut session, start); + assert_eq!(at_start.as_array().map(Vec::len), Some(2), "the declaration and the use"); + assert_eq!(refs(&mut session, start + 2), at_start, "just past `tx`, in UTF-16 units"); + assert!(says_nothing(&refs(&mut session, start + 3)), "past the `;`"); +} diff --git a/crates/lucisv_server/src/server/tests/mod.rs b/crates/lucisv_server/src/server/tests/mod.rs index 52aab2f..87919ba 100644 --- a/crates/lucisv_server/src/server/tests/mod.rs +++ b/crates/lucisv_server/src/server/tests/mod.rs @@ -47,6 +47,7 @@ use crate::{design_hierarchy, diagnostics, format, lens, pairs, ports}; mod apply_edit; mod cancel; +mod caret_boundary; mod code_action; mod file_ops; mod folders; @@ -57,6 +58,7 @@ mod index; mod large_file; mod lint_snapshot; mod localized_reindex; +mod ordering_random; mod progress; mod pull_diagnostics; mod qa_generate_label; @@ -68,6 +70,7 @@ mod rename_implicit; mod rename_top_rooted_scope; mod requests; mod scan; +mod scan_ordering; mod scan_trace; mod settings; mod startup; diff --git a/crates/lucisv_server/src/server/tests/ordering_random.rs b/crates/lucisv_server/src/server/tests/ordering_random.rs new file mode 100644 index 0000000..d4e123d --- /dev/null +++ b/crates/lucisv_server/src/server/tests/ordering_random.rs @@ -0,0 +1,341 @@ +//! Random interleavings of the client's bursts against the real loop, mid-scan +//! and between scans (`docs/features/scan-ordering/README.md`, B and C). +//! +//! A seeded client sends bursts of requests, full and incremental +//! `didChange`s for three documents, opens, closes, cancels and watcher +//! events that cost a whole rescan; some bursts land at a scan's interleave +//! points ([`probe::script`]), the rest between scans. After every round the +//! server must hold exactly the buffers the client holds, with exactly the +//! client's text; every request must be answered exactly once; no scan may +//! hand its held batch back more often than the `didOpen`s and scans it saw +//! can explain; and at the end, the server must answer what a fresh server +//! on the same files and buffers answers. + +use std::collections::HashMap; + +use super::super::probe; +use super::scan_ordering::{ask, closed, created, note, opened, ordering_tree, settle, A_TEXT}; +use super::*; + +/// A small deterministic generator — xorshift64, no dependency. +struct Rng(u64); + +impl Rng { + fn new(seed: u64) -> Rng { + Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1) + } + + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn below(&mut self, n: usize) -> usize { + (self.next() % n.max(1) as u64) as usize + } + + fn percent(&mut self, p: u64) -> bool { + self.next() % 100 < p + } +} + +/// The client: what it has open, with what text, and what it has asked. +struct Client { + rng: Rng, + docs: Vec<(Uri, String)>, + open: HashMap, + asked: Vec, + next_id: i32, + created: Vec, + root: PathBuf, + /// `didOpen`s sent this round — what may re-order a scan. + opens: usize, +} + +impl Client { + fn new(seed: u64, tree: &Tree) -> Client { + let docs = ["a/a.sv", "b/b.sv", "c/c.sv"] + .iter() + .map(|rel| { + let path = tree.path.join(rel); + let text = std::fs::read_to_string(&path).expect("a document"); + (path_to_uri(&path).expect("uri"), text) + }) + .collect(); + Client { + rng: Rng::new(seed), + docs, + open: HashMap::new(), + asked: Vec::new(), + next_id: 1, + created: Vec::new(), + root: tree.path.clone(), + opens: 0, + } + } + + fn doc(&mut self) -> Uri { + let n = self.rng.below(self.docs.len()); + self.docs[n].0.clone() + } + + fn burst(&mut self) -> Vec { + (0..1 + self.rng.below(4)).map(|_| self.message()).collect() + } + + /// One message, applied to the client's own view as it is sent. + fn message(&mut self) -> Message { + let uri = self.doc(); + let roll = self.rng.below(100); + match (roll, self.open.contains_key(&uri)) { + (0..=29, true) => self.change(&uri), + (30..=39, true) => { + self.open.remove(&uri); + closed(&uri) + } + (0..=39, false) => self.reopen(&uri), + (40..=49, _) => self.watcher_event(), + (50..=57, _) if !self.asked.is_empty() => { + let id = self.asked[self.rng.below(self.asked.len())]; + note(Cancel::METHOD, serde_json::json!({ "id": id })) + } + _ => self.request(&uri), + } + } + + fn reopen(&mut self, uri: &Uri) -> Message { + let disk = self.docs.iter().find(|(u, _)| u == uri).map(|(_, t)| t.clone()); + let text = disk.unwrap_or_default() + &format!("// opened {}\n", self.rng.below(1000)); + self.open.insert(uri.clone(), (1, text.clone())); + self.opens += 1; + opened(uri, &text) + } + + /// A full or an incremental `didChange`, ranges in the text the client + /// holds right now — which is what makes a reordering visible. + fn change(&mut self, uri: &Uri) -> Message { + let n = self.rng.below(1000); + let full = self.rng.percent(30); + let lines = self.open[uri].1.split_inclusive('\n').count() as u32; + let line = self.rng.below(lines as usize + 1) as u32; + let (version, text) = self.open.get_mut(uri).expect("open"); + *version += 1; + let mut kept: Vec = text.split_inclusive('\n').map(str::to_string).collect(); + let change = if full { + kept.push(format!("module m{n};\nendmodule\n")); + serde_json::json!({ "text": kept.concat() }) + } else if lines > 3 && n.is_multiple_of(3) { + kept.remove(line.min(lines - 1) as usize); + let at = line.min(lines - 1); + serde_json::json!({ + "range": { "start": { "line": at, "character": 0 }, + "end": { "line": at + 1, "character": 0 } }, + "text": "", + }) + } else { + kept.insert(line as usize, format!("// e{n}\n")); + let at = serde_json::json!({ "line": line, "character": 0 }); + serde_json::json!({ "range": { "start": at, "end": at }, "text": format!("// e{n}\n") }) + }; + *text = kept.concat(); + note( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri, "version": *version }, + "contentChanges": [change], + }), + ) + } + + /// A file created on disk, or one created earlier deleted, and the + /// watcher's word for it. A creation costs a whole rescan. + fn watcher_event(&mut self) -> Message { + if !self.created.is_empty() && self.rng.percent(30) { + let path = self.created.swap_remove(self.rng.below(self.created.len())); + let _ = std::fs::remove_file(&path); + let uri = path_to_uri(&path).expect("uri"); + return note( + DidChangeWatchedFiles::METHOD, + serde_json::json!({ "changes": [{ "uri": uri, "type": 3 }] }), + ); + } + self.created_file() + } + + /// A new package file on disk, and the watcher's word for it. + fn created_file(&mut self) -> Message { + let name = format!("r{}", self.next_id * 1000 + self.rng.below(1000) as i32); + let path = self.root.join("z").join(format!("{name}.sv")); + std::fs::write(&path, format!("package {name};\n localparam K = 1;\nendpackage\n")) + .expect("write"); + self.created.push(path.clone()); + created(&path) + } + + fn request(&mut self, uri: &Uri) -> Message { + let id = self.next_id; + self.next_id += 1; + self.asked.push(id); + let at = serde_json::json!({ + "textDocument": { "uri": uri }, + "position": { "line": self.rng.below(4), "character": self.rng.below(12) }, + }); + match self.rng.below(4) { + 0 => ask(id, HoverRequest::METHOD, at), + 1 => ask(id, GotoDefinition::METHOD, at), + 2 => ask(id, WorkspaceSymbolRequest::METHOD, serde_json::json!({ "query": "p00" })), + _ => ask( + id, + DocumentSymbolRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": uri } }), + ), + } + } +} + +/// What one round's messages from the server came to. +#[derive(Default)] +struct Heard { + answers: HashMap, + scans: usize, +} + +fn hear(session: &Session, heard: &mut Heard) { + for message in session.drain() { + match message { + Message::Response(response) => *heard.answers.entry(response.id).or_default() += 1, + Message::Notification(n) + if n.method == Progress::METHOD && n.params["value"]["kind"] == "begin" => + { + heard.scans += 1; + } + _ => {} + } + } +} + +/// The server holds exactly the client's buffers, with the client's text. +fn same_buffers(session: &Session, client: &Client, at: &str) { + let mut held: Vec = session.server.workspace.open_uris(); + held.sort_by_key(|uri| uri.to_string()); + let mut wanted: Vec = client.open.keys().cloned().collect(); + wanted.sort_by_key(|uri| uri.to_string()); + assert_eq!(held, wanted, "{at}: the open buffers"); + for (uri, (_, text)) in &client.open { + assert_eq!(&buffer(session, uri), text, "{at}: the text of {uri:?}"); + } +} + +/// The answers a fresh server is compared on: every open buffer's symbols, +/// and the packages the watcher events created and deleted. +/// +/// Not the modules a buffer's edits added: a whole rescan indexes an open +/// buffer's text and a fresh server opened after its scan has not, which is +/// the documented staleness of an unsaved buffer, not an ordering. +fn battery(session: &mut Session, client: &Client) -> Vec { + let mut uris: Vec<&Uri> = client.open.keys().collect(); + uris.sort_by_key(|uri| uri.to_string()); + let mut out: Vec = uris + .into_iter() + .map(|uri| { + session.result( + DocumentSymbolRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": uri } }), + ) + }) + .collect(); + let mut names: Vec = session + .result(WorkspaceSymbolRequest::METHOD, serde_json::json!({ "query": "r" })) + .as_array() + .cloned() + .unwrap_or_default() + .iter() + .filter_map(|s| s["name"].as_str().map(str::to_string)) + .collect(); + names.sort(); + out.push(serde_json::json!(names)); + out +} + +/// One seeded run: a startup scan with bursts landing in it, then `rounds` +/// rounds of bursts landing between and inside rescans. Reports how many +/// bursts landed mid-scan, so a run cannot pass by never interleaving. +fn run_seed(seed: u64, rounds: usize) -> usize { + let tree = ordering_tree(&format!("orderrand{seed}")); + tree.write("c/c.sv", "module cmod;\n logic c;\nendmodule\n"); + let mut client = Client::new(seed, &tree); + let a = client.docs[0].0.clone(); + client.open.insert(a.clone(), (1, A_TEXT.to_string())); + let _ = probe::take_counts(); + let startup: Vec> = (0..1 + client.rng.below(5)).map(|_| client.burst()).collect(); + probe::script(startup); + let mut session = Session::started_behind( + vec![tree.path.clone()], + watching_progress(), + wide_ish(), + Vec::new(), + vec![opened(&a, A_TEXT)], + ); + let mut heard = Heard::default(); + let mut mid_scan = 0; + let mut opens = std::mem::take(&mut client.opens) + 1; + for round in 0..=rounds { + settle(&mut session); + hear(&session, &mut heard); + let counts = probe::take_counts(); + let handed_back = counts.handed_back; + mid_scan += counts.delivered; + let at = format!("seed {seed} round {round}"); + assert!( + handed_back <= opens + heard.scans + 1, + "{at}: a scan handed its held batch back {handed_back} times \ + for {opens} didOpens and {} scans", + heard.scans + ); + same_buffers(&session, &client, &at); + if round == rounds { + break; + } + heard.scans = 0; + // Most rounds start a rescan, from anywhere in the burst — so the + // burst's own tail is often still unapplied while the scan runs. + let mut top = client.burst(); + if client.rng.percent(70) { + let at = client.rng.below(top.len() + 1); + let trigger = client.created_file(); + top.insert(at, trigger); + } + let inside: Vec> = (0..client.rng.below(7)).map(|_| client.burst()).collect(); + opens = std::mem::take(&mut client.opens); + probe::script(inside); + assert!(!session.batch(top), "no shutdown"); + } + for id in &client.asked { + let times = heard.answers.get(&RequestId::from(*id)).copied().unwrap_or(0); + assert_eq!(times, 1, "seed {seed}: request {id} answered {times} times"); + } + let mine = battery(&mut session, &client); + let mut fresh = Session::wide(vec![tree.path.clone()], false); + for (uri, (_, text)) in &client.open { + let path = crate::uri::uri_to_path(uri).expect("a path"); + fresh.open(&path, text); + } + assert_eq!(mine, battery(&mut fresh, &client), "seed {seed}: a fresh server's answers"); + mid_scan +} + +#[test] +fn random_bursts_keep_every_buffer_and_answer_every_request_once() { + let mid_scan: usize = (1..=12).map(|seed| run_seed(seed, 10)).sum(); + assert!(mid_scan >= 200, "only {mid_scan} bursts landed mid-scan"); +} + +/// The long run: `cargo test -p lucisv_server -- --ignored ordering_random`. +#[test] +#[ignore = "a few minutes; the normal suite runs the twelve seeds above"] +fn random_bursts_long_run() { + let mid_scan: usize = (100..400).map(|seed| run_seed(seed, 40)).sum(); + assert!(mid_scan >= 10_000, "only {mid_scan} bursts landed mid-scan"); +} diff --git a/crates/lucisv_server/src/server/tests/scan_ordering.rs b/crates/lucisv_server/src/server/tests/scan_ordering.rs new file mode 100644 index 0000000..698a4e2 --- /dev/null +++ b/crates/lucisv_server/src/server/tests/scan_ordering.rs @@ -0,0 +1,312 @@ +//! No client message overtakes an older one while a scan answers messages +//! (`docs/features/scan-ordering/README.md`, B and C). +//! +//! Every test here scripts what the client sends *at* a given interleave +//! point ([`probe::script`]) — the transport cannot be timed against a scan's +//! files — and then lets the loop finish the way `run` does: the held batch +//! first, then whatever the scan ended before receiving. + +use super::super::probe; +use super::*; + +/// A tree with enough files that every whole scan interleaves, plus one +/// file `a/a.sv` (and `b/b.sv`) that a test opens. +pub(super) fn ordering_tree(tag: &str) -> Tree { + let tree = Tree::new(tag); + for n in 0..INTERLEAVE_ABOVE + 6 { + tree.package(&format!("z/p{n:03}.sv"), &format!("p{n:03}")); + } + tree.write("a/a.sv", A_TEXT); + tree.write("b/b.sv", "module bmod;\nendmodule\n"); + tree +} + +pub(super) const A_TEXT: &str = "module amod;\n logic s;\nendmodule\n"; + +/// A notification on the wire. +pub(super) fn note(method: &str, params: Value) -> Message { + Message::Notification(Notification::new(method.to_string(), params)) +} + +/// A request on the wire. +pub(super) fn ask(id: i32, method: &str, params: Value) -> Message { + Message::Request(Request::new(RequestId::from(id), method.to_string(), params)) +} + +/// A watcher event saying `path` was created — a file the index does not +/// hold, which costs a whole rescan. +pub(super) fn created(path: &Path) -> Message { + note( + DidChangeWatchedFiles::METHOD, + serde_json::json!({ "changes": [{ "uri": path_to_uri(path).expect("uri"), "type": 1 }] }), + ) +} + +pub(super) fn opened(uri: &Uri, text: &str) -> Message { + note( + DidOpenTextDocument::METHOD, + serde_json::json!({ "textDocument": { + "uri": uri, "languageId": "systemverilog", "version": 1, "text": text, + } }), + ) +} + +pub(super) fn closed(uri: &Uri) -> Message { + note(DidCloseTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } })) +} + +/// An incremental `didChange` inserting `text` at the start of `line`. +fn inserted(uri: &Uri, version: u32, line: u32, text: &str) -> Message { + let at = serde_json::json!({ "line": line, "character": 0 }); + note( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri, "version": version }, + "contentChanges": [{ "range": { "start": at, "end": at }, "text": text }], + }), + ) +} + +fn hover(id: i32, uri: &Uri) -> Message { + ask( + id, + HoverRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": uri }, "position": { "line": 0, "character": 0 } }), + ) +} + +/// Hand `burst` to the loop as `run` would, with every scripted burst +/// arriving mid-scan, then everything the loop owes afterwards. +fn deliver(session: &mut Session, burst: Vec) { + assert!(!session.batch(burst), "no shutdown"); + let late = probe::unarrived(); + assert!(late.is_empty(), "the rescan ended before the script did: {late:#?}"); + settle(session); +} + +/// What `run` does between bursts: answer the held batch until none is +/// left, then take the scripted bursts that arrived after every scan ended. +pub(super) fn settle(session: &mut Session) { + loop { + while !session.server.held.is_empty() { + let held = std::mem::take(&mut session.server.held); + assert!(!session.batch(held), "no shutdown"); + } + let late = probe::unarrived(); + if late.is_empty() { + return; + } + for burst in late { + assert!(!session.batch(burst), "no shutdown"); + } + } +} + +/// A workspace-scoped session showing a progress bar, with `a/a.sv` open, +/// and that buffer's uri. +pub(super) fn with_a_open(tree: &Tree) -> (Session, Uri) { + let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress()); + let a = session.open(&tree.path.join("a/a.sv"), A_TEXT); + // What the watcher events in these tests say was created: on disk, and + // not in the index the startup scan built, so each costs a whole rescan. + for new in ["new", "x1", "x2"] { + tree.package(&format!("z/{new}.sv"), new); + } + let _ = probe::take_counts(); + let _ = session.drain(); + (session, a) +} + +#[test] +fn a_change_drained_mid_rescan_waits_behind_an_older_change_held_with_a_request() { + // QA F6, held form: the rescan holds `[hover, v2]`; `v3` arrives at the + // next file and used to be applied at once — ahead of `v2`, which then + // replaced it. + let tree = ordering_tree("orderheldfull"); + let (mut session, a) = with_a_open(&tree); + let v2 = format!("{A_TEXT}module v2;\nendmodule\n"); + let v3 = format!("{A_TEXT}module v3;\nendmodule\n"); + probe::script([vec![hover(1, &a), changed(&a, 2, &v2)], vec![changed(&a, 3, &v3)]]); + deliver(&mut session, vec![created(&tree.path.join("z/new.sv"))]); + assert_eq!(buffer(&session, &a), v3, "the client's last text is the server's"); +} + +#[test] +fn incremental_changes_held_mid_rescan_are_applied_in_the_order_they_were_sent() { + // The same race under incremental sync is corruption, not staleness: each + // edit is a range into the text the one before it produced. + let tree = ordering_tree("orderheldincr"); + let (mut session, a) = with_a_open(&tree); + let first = "// first\n"; + let second = " // second, inside the module\n"; + probe::script([ + vec![hover(1, &a), inserted(&a, 2, 1, first)], + vec![inserted(&a, 3, 2, second)], + ]); + deliver(&mut session, vec![created(&tree.path.join("z/new.sv"))]); + let mut client: Vec<&str> = A_TEXT.split_inclusive('\n').collect(); + client.insert(1, first); + client.insert(2, second); + assert_eq!(buffer(&session, &a), client.concat()); +} + +#[test] +fn a_change_drained_mid_rescan_waits_behind_the_rest_of_the_burst_that_started_it() { + // QA F6, tail form: the burst that asks for the rescan still carries + // `v2` behind the watcher event while the scan answers `v3`. + let tree = ordering_tree("ordertail"); + let (mut session, a) = with_a_open(&tree); + let v2 = format!("{A_TEXT}module v2;\nendmodule\n"); + let v3 = format!("{A_TEXT}module v3;\nendmodule\n"); + probe::script([vec![changed(&a, 3, &v3)]]); + let burst = vec![ + ask(1, WorkspaceSymbolRequest::METHOD, serde_json::json!({ "query": "p" })), + created(&tree.path.join("z/new.sv")), + changed(&a, 2, &v2), + ]; + deliver(&mut session, burst); + assert_eq!(buffer(&session, &a), v3); +} + +#[test] +fn a_reopen_behind_a_held_close_leaves_the_buffer_open_with_its_new_text() { + // Nothing is lost either way round: a close held behind a request and a + // reopen drained after it are applied close-then-open, so the buffer the + // editor is showing is the one the server holds. + let tree = ordering_tree("orderreopen"); + let (mut session, a) = with_a_open(&tree); + let reopened = format!("{A_TEXT}// reopened\n"); + probe::script([vec![hover(1, &a), closed(&a)], vec![opened(&a, &reopened)]]); + deliver(&mut session, vec![created(&tree.path.join("z/new.sv"))]); + assert_eq!(buffer(&session, &a), reopened, "open, with the text it was reopened with"); + let answered: Vec = session.answers().into_iter().map(|r| r.id).collect(); + assert_eq!(answered, [RequestId::from(1)], "the held hover is answered once"); +} + +#[test] +fn a_change_behind_only_a_held_request_applies_at_once_and_a_late_cancel_waits_with_it() { + // The rule is about notifications overtaking notifications. A change + // with nothing older unapplied but a held *request* is applied where it + // lands — the request is answered later against it, as every late + // request always was — while a cancel for that request waits beside it + // and is honoured when the held batch is replayed. + let tree = ordering_tree("ordernarrow"); + let (mut session, a) = with_a_open(&tree); + let v2 = format!("{A_TEXT}// v2\n"); + let cancel = note(Cancel::METHOD, serde_json::json!({ "id": 1 })); + probe::script([vec![hover(1, &a)], vec![changed(&a, 2, &v2)], vec![cancel]]); + assert!(!session.batch(vec![created(&tree.path.join("z/new.sv"))]), "no shutdown"); + assert!(probe::unarrived().is_empty(), "all three landed mid-scan"); + assert_eq!(buffer(&session, &a), v2, "applied mid-scan, ahead of the held hover"); + let held: Vec = session.server.held.iter().map(changes_state_of).collect(); + assert_eq!(held, [false, false], "the hover and its cancel, nothing else"); + settle(&mut session); + let answers = session.answers(); + assert_eq!(answers.len(), 1, "{answers:#?}"); + assert!( + answers[0] + .response_result + .as_ref() + .is_err_and(|e| e.code == lsp_server::ErrorCode::RequestCanceled as i32), + "the late cancel was honoured: {answers:#?}" + ); +} + +fn changes_state_of(message: &Message) -> bool { + super::super::batch::changes_state(message) +} + +#[test] +fn a_rescans_trigger_alone_in_its_burst_still_lets_newer_changes_apply_at_once() { + // The rule holds a notification only when something *older* is waiting. + // With nothing behind the watcher event and nothing held, a change + // drained mid-rescan is applied where it lands — so a burst of watcher + // events during a rescan is still coalesced into exactly one more scan. + let tree = ordering_tree("ordercoalesce"); + let (mut session, a) = with_a_open(&tree); + let v2 = format!("{A_TEXT}// v2\n"); + probe::script([ + vec![changed(&a, 2, &v2)], + vec![created(&tree.path.join("z/x1.sv"))], + vec![created(&tree.path.join("z/x2.sv"))], + ]); + deliver(&mut session, vec![created(&tree.path.join("z/new.sv"))]); + assert_eq!(buffer(&session, &a), v2); + let ends = session.drain().into_iter().filter_map(progress_step).filter(|(s, _)| *s == "end"); + assert_eq!(ends.count(), 2, "the rescan, and one more for both watcher events"); +} + +/// The session the startup-scan tests below start: `a/a.sv` opened in the +/// client's opening burst, so the scan leads with folder `a`, and `later` +/// scripted to arrive once that folder is in. +fn startup_with(tree: &Tree, later: Vec) -> Session { + let a = path_to_uri(&tree.path.join("a/a.sv")).expect("uri"); + let _ = probe::take_counts(); + // The head is `a/a.sv` alone; three interleave points is well past it. + probe::script([Vec::new(), Vec::new(), later]); + Session::started_behind( + vec![tree.path.clone()], + watching_progress(), + wide_ish(), + Vec::new(), + vec![opened(&a, A_TEXT)], + ) +} + +/// Where the response to `id` sits among `said`, and where the bar's end. +fn answered_before_the_end(said: &[Message], id: i32) -> bool { + let (ended, answered) = super::scan::positions(said, id); + matches!((answered, ended), (Some(answered), Some(ended)) if answered < ended) +} + +#[test] +fn a_request_ahead_of_a_didopen_mid_startup_is_answered_and_the_drain_runs_once() { + // QA Q1: `[request, didOpen(B)]` during the startup scan. The `didOpen` + // used to be read off the batch *before* it was applied, which held the + // request with the `didOpen` unapplied behind it — and the next file + // handed the same batch back, forced a publish, and held it again, at + // every file to the end of the scan (~300 s on OpenTitan). + let tree = ordering_tree("orderq1"); + let a = path_to_uri(&tree.path.join("a/a.sv")).expect("uri"); + let b = path_to_uri(&tree.path.join("b/b.sv")).expect("uri"); + let tokens_b = ask( + 8, + SemanticTokensFullRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": b } }), + ); + let later = vec![hover(7, &a), opened(&b, "module bmod;\nendmodule\n"), tokens_b]; + let session = startup_with(&tree, later); + let probe::Counts { points, handed_back, .. } = probe::take_counts(); + let _control = startup_with(&tree, Vec::new()); + let unloaded = probe::take_counts().points; + let said = session.drain(); + assert!(answered_before_the_end(&said, 7), "the request ahead of the didOpen: {said:#?}"); + assert!(answered_before_the_end(&said, 8), "and the one behind it, mid-scan"); + assert!(session.server.held.is_empty(), "nothing is left held"); + assert!(handed_back <= 1, "one hand-back for one didOpen, not one per file: {handed_back}"); + assert_eq!(points, unloaded, "as many interleave points as the scan with nothing sent"); +} + +#[test] +fn a_request_behind_a_didopen_mid_startup_still_waits_for_the_buffer_it_names() { + // The ordering the old flag existed for is kept: a request *behind* the + // `didOpen` sees the buffer, and the work list ordered round it. + let tree = ordering_tree("orderq1behind"); + let b = path_to_uri(&tree.path.join("b/b.sv")).expect("uri"); + let symbols_b = + ask(9, DocumentSymbolRequest::METHOD, serde_json::json!({ "textDocument": { "uri": b } })); + let session = startup_with(&tree, vec![opened(&b, "module bmod;\nendmodule\n"), symbols_b]); + let said = session.drain(); + assert!(answered_before_the_end(&said, 9), "answered mid-scan: {said:#?}"); + let answer = said.iter().find_map(|m| match m { + Message::Response(r) if r.id == RequestId::from(9) => r.response_result.clone().ok(), + _ => None, + }); + let names: Vec = answer + .and_then(|v| v.as_array().cloned()) + .unwrap_or_default() + .iter() + .filter_map(|s| s["name"].as_str().map(str::to_string)) + .collect(); + assert_eq!(names, ["bmod"], "answered off the buffer the didOpen installed"); +} diff --git a/docs/features/scan-ordering/README.md b/docs/features/scan-ordering/README.md new file mode 100644 index 0000000..368688e --- /dev/null +++ b/docs/features/scan-ordering/README.md @@ -0,0 +1,890 @@ +# scan-ordering + +## Goal + +The owner's report: *"Sometimes when I find references on a port/signal, it +shows not found. But if I click somewhere else and then click back to the same +word, the find reference suddenly works again."* The investigation (TODO §71.7) +found the cause and two worse bugs beside it. **A1:** a caret just past a +name's last letter — where a double-click, a click on the right half of the +last letter, or a row of lucisv's own References view leaves it — asked the +server about the *next* character, and every "symbol under the cursor" request +answered nothing there. **B:** while a whole rescan answered messages, a +`didChange` drained mid-scan was applied ahead of an older `didChange` still +waiting, so under incremental sync the server's copy of a buffer silently +diverged from the editor's until the file was reopened. **C:** a burst +`[request, didOpen]` during the startup scan re-held the request at every +file, and the scan took ~300 s instead of ~1.7 s on OpenTitan. This round makes +a caret touching a name's right edge mean that name, establishes "no +notification overtakes an older notification" as the loop's rule, and makes +"only applied messages change a scan's state" true. P1, P2 and P3 are +documented, not changed (P2 was fixed in the first round and reverted in the +fix round for its cost, QA-1). + +## Assumptions + +- **VS Code's word rule is the one to match.** `getWordAtText` + (`src/vs/editor/common/core/wordHelper.ts`) accepts a word whose end equals + the caret, so VS Code titles a references search, highlights the word and + shows "No references found" for the name *before* a caret that touches it + on the right. Its default word pattern splits on `.`, `(`, `[`, `` ` `` and + `$`, so in `u_a|.sig` the word is `u_a` and in `u_a.|sig` it is `sig`; the + rule here agrees ([`caret::symbol_offset`]). +- **A name byte** is ASCII alphanumeric, `_` or `$` (IEEE 1800-2017 §5.6). A + macro after its backtick and a system task are covered by the same set; an + escaped identifier (`\a+b `) is handled by its terminating whitespace. A + number or keyword just before the caret is a "name" too: harmless for the + requests that resolve nothing there, and right for `documentHighlight`'s + keyword pairs (`begin|` now highlights its `end`, as VS Code's own word + highlight already did). +- **`vscode.open` puts the caret at a range's end.** Verified in VS Code's + source (`extHostTypeConverters.ts` converts `selection` with `Range.from`, + losing a `Selection`'s direction; `codeEditorWidget.ts`'s `setSelection(IRange)` + makes the range's end the position). VS Code's own references view passes + `range.with({ end: range.start })` and go to definition + `Range.collapseToStart(range)`; lucisv's view now does the same. +- **What is ordered (fix round, narrowed from "every client message"):** + every notification other than `$/cancelRequest` — the only messages that + change what the server holds — is applied in the order sent, across + documents (a `didClose` of one file and a `didOpen` of another stay in + order). A request is answered after every notification sent before it + (`must_wait`, unchanged), but **may** be answered after a newer + notification has been applied, when it was held and nothing older than + that notification was: it is then answered against newer state, exactly as + every request answered late on base was. Exempt altogether: **responses** + (they answer a request the server made; `take_the_answer_out_of_held` + relies on that) and the navigation requests the empty-answer rule set aside + (`deferred`, re-asked at a later publish). A **cancel** waits whenever + anything is held, so one naming a held request is honoured at replay; one + naming a request in the unapplied tail of the burst a scan is nested in is + dropped and the request computed, as on base. +- **Why narrowing is sound.** Buffer text, open/closed state, settings, + folders and watcher effects are changed only by non-cancel notifications. + Such a notification is applied only when no older one is unapplied in + `held` or in an enclosing burst's tail ([`Server::behind`]), `held` is + replayed in order, and nothing else defers a notification — so the + sequence of state changes is the client's. The broad rule's only extra + effect was to keep a notification from overtaking a held *request*, which + changes no state and cost the startup its first `didOpen` (QA-3). Checked + by the randomized test, f6.py, QA's seeds and hand scenarios (Work log). +- **Memory while holding is bounded by the scan's length times the client's + rate.** Requests were already held this way; a `didChange` under incremental + sync (what lucisv advertises) is a few hundred bytes. A full-sync client + flooding whole-buffer changes during a long rescan holds one copy per change + until the scan ends — the same order as the `dirty` text it would otherwise + have kept, times the number of changes. Not coalesced: coalescing two held + changes is only sound when nothing between them reads the buffer, which is + the analysis this round avoids. +- **P1 (directory-only watcher events) is a registration question, not a + handler one** — see Handshakes; nothing arrives today for the case that + matters. + +## Handshakes + +**Consumed:** `Scan::neighbourhood_indexed` and `open_next` (unchanged), +`sync::apply_changes_at` (unchanged). No `state/` file is touched after the +fix round (in particular not `incremental.rs`'s `holds_another_spelling_of`). + +**Promised to the rest of the server (changed, read this):** + +1. **`process_batch` holds notifications too** (`Server::must_hold`, mod.rs). + A non-cancel notification is held when an older one is still unapplied: + in `held`, or in the tail of a burst whose message started the scan now + draining (`Server::behind`, a count of those tails' non-cancel + notifications, kept by `process_batch`). A cancel is held when anything + is held. A request's rule is `must_wait`, unchanged. A response is never + held. `batch::changes_state` names the messages that are ordered. + Anything that adds a new caller of `process_batch` inherits the rule for + free; anything that applies a client message *without* going through + `process_batch` breaks it. **For lane 71.3 (viewport highlighting), + rebasing onto this:** the `process_batch` diff is the `behind` + bookkeeping (an `unapplied` counter), the `must_hold` call in place of + `must_wait() && Request`, a `cancel_deferred` before holding, and the + splice moved into `Server::hold` (which keeps `process_batch` under 80 + lines). Nothing else in the loop moved. +2. **A `didOpen` changes a scan's order where it is applied.** The `didOpen` + arm sets `head_owed` and `opened_mid_scan` when `scanning`; + `answer_what_is_waiting` reads `opened_mid_scan` after the batch. `batch.rs`'s + `opened_in` is gone — nothing may read a batch's `didOpen`s again. +3. **Position → symbol requests resolve through `Server::symbol_offset`** + (dispatch.rs), which is `Server::offset` plus [`caret::symbol_offset`]. A + new request about the name under the cursor should use it; one with a + boundary rule of its own keeps `offset`. The table is below. +4. **Test-only:** `server/probe.rs` scripts bursts into a scan's interleave + points and counts hand-backs; it is `#[cfg(test)]` and thread-local, and + the one production line is `#[cfg(test)]` too. + +**Requests to other modules / the lead (not done here):** + +- **P1 needs a second watcher registration.** VS Code coalesces the deletes + under a deleted folder into one event for the folder + (`src/vs/platform/files/common/watcher.ts`, `EventCoalescer`: "remove all + DELETE events up to the root folder that got deleted"; `vscode.d.ts`: "file + events from deleting a folder may not include events for the contained + files"), and `extHostFileSystemEventService.ts` then drops the folder event + because its path does not match `**/*.{v,vh,sv,svh}`. So after `rm -rf dir` + or a `git checkout` that removes a directory, **the server receives + nothing** — no handler change can fix it. Created files are not coalesced: + `mkdir d && cp x.svh d/` or a checkout that adds a directory arrives as + per-file creates, which the server already handles; a directory *moved in* + arrives as one folder event, dropped the same way. The fix is a second + watcher, `**/*` with `kind: Create | Delete`, plus a handler that expands a + folder path to the held files under it (delete) or a rescan (create). That + changes the registration every client receives and the traffic it sends + (every create/delete outside `files.watcherExclude`), which is a decision + for the lead, so it is filed rather than done. QA's synthetic + `r2attack.py dir-create` / `held-dir-delete` still diverge (unchanged). +- **P3 (symlinked files held under one spelling or both)** is unchanged: the + rule "one file, one spelling, whatever is open" needs the walk + (`discover.rs`'s `Aliased`), the overlay and the one-file path changed + together. Not small; filed. +- **P2 (reverted, known, pre-existing — 0.65.6 behaviour).** An excluded or + unlisted buffer the index took in (a whole scan takes every open buffer; + the one-file path of a save or watcher event takes it too, QA F4 of + `localized-reindex`) **stays in the index after `didClose`**, where a fresh + server would not hold it: `oracle/r2attack.py excluded-close`, "closed" and + "saved then closed", 20 answers differ. The first round fixed it by taking + an unheld buffer in on `didOpen` and forgetting it on `didClose`; each is a + one-file add/remove, which shifts file ids and rebuilds the completion + tables and include naming — ~190 ms per open and ~225 ms per close on full + OpenTitan, 2 000 outside files opened and closed 806 s vs 0.7 s + (`qa717/drv/lat717.py`, `p2perf.py`, QA-1). Reverted. A fix must make the + removal cheap (a tombstone the next scan or publish folds in, say) — it is + an index-layer change, filed. +- **QA-2 (known, pre-existing): an unheld buffer opened while a scan runs is + not taken in by that scan**, and nothing takes it in when the scan ends; + opened before the scan it is held. `qa717/drv/race717.py BIN 0.5`: an excluded file opened 0.5 s into the startup scan is still + unheld after settle, base and new alike. The same final state answers + differently depending on when the buffer was opened; QA's `QA_FRESH_SAVE` + exists to hide exactly this on the fresh side. +- **QA-7a (known, pre-existing): closing an unsaved in-scope buffer whose + text a rescan took into the index leaves that text in the index** after + the close; a fresh server holds the disk text. `qa717/drv/closeidx.py BIN + rescan`: `qd_buf` survives the close, the fresh server holds `qd_disk`. + Identical on base. Same root as P2: a close does not touch the index. +- **Notes for the lead's backlog (QA, not this lane):** QA-6 — the + `lucisv_mcp` test `qa_m3::qa_lucisv_check_over_the_same_tree_while_the_server_formats` + (`crates/lucisv_mcp/tests/qa_m3.rs:687`) hung to the guard's 600 s limit + once in QA's gate run (passed on the retry), also seen in the 0.65.5 + release gate log. QA-7b — `rand_run.py` full OpenTitan seed 301 ×100 + diverges at step 100 (13 answers, `top_earlgrey/ip/ast/rtl/usb_osc.sv`) + identically on base. QA-7c — renaming a port of a module defined twice + (`top_englishbreakfast/ip/ast/rtl/adc.sv:81` `rst_adc_ni`) gives an edit + or a refusal at random across fresh servers, base too (`qa717/drv/dup.py`). +- **lucisv_mcp** answers by name, not by caret position, so A1 does not + apply to it. + +### Every position-taking request and its boundary rule (A1) + +| request | what the position names | rule now | +|---|---|---| +| `textDocument/hover` | the name under the cursor | **shifted** (`symbol_offset`) | +| `textDocument/definition` | the name | **shifted** | +| `textDocument/typeDefinition` | the name whose type is wanted | **shifted** | +| `textDocument/references` | the name | **shifted** — the owner's bug | +| `textDocument/documentHighlight` | the name, or a scope keyword of a pair | **shifted** | +| `textDocument/prepareRename`, `textDocument/rename` | the name | **shifted** | +| `textDocument/prepareCallHierarchy` | the module under the cursor | **shifted** (already answered for the whole instantiation, so it changes nothing there) | +| `textDocument/prepareTypeHierarchy` | the class | **shifted** (already answered for the whole declaration) | +| `textDocument/linkedEditingRange` | a closing label being typed | as sent — `linked.rs`'s `covers` is already end-inclusive (`offset <= span.end`), which typing at a label's end needs | +| `textDocument/signatureHelp` | the call the caret is *in* | as sent — before `(` and after it are different answers on purpose | +| `textDocument/completion`, `textDocument/inlineCompletion` | the insertion point | as sent — "just past a name" is where the text goes | +| `textDocument/onTypeFormatting` | the character just typed | as sent | +| `textDocument/selectionRange` | where expansion starts | as sent — VS Code merges its own word ranges in | +| `textDocument/codeAction` (port refactorings, organize imports) | `range.start` as the cursor, resolved to the *instantiation* or *import* around it | as sent — the item's span contains a name's end | +| `textDocument/codeAction` (extract, inline module) | a range | as sent | +| `workspace/executeCommand` (port commands, lens) | positions the server itself issued | as sent | +| `inlayHint`, `semanticTokens/range`, `foldingRange`, `documentLink`, `documentSymbol`, `lucisv/scopePairs`, the hierarchy snapshot | a range or the whole document | no caret | + +## Status / TODO + +- [x] Reproduce A1, B, C on 58d3db3 with the investigation's drivers; record +- [x] A1: `caret::symbol_offset`, `Server::symbol_offset`, nine requests +- [x] A1: the References view puts the caret at the identifier's start +- [x] B: `Server::must_hold` + `Server::behind` +- [x] C: `opened_mid_scan`, set where a `didOpen` is applied; `opened_in` gone +- [x] P2: fixed in round 1, **reverted** in the fix round (QA-1); documented +- [x] Fix round: rule narrowed to notification-over-notification (QA-3); + `process_batch` split (`Server::hold`); QA-4 measured; QA-5 wording +- [ ] P1: filed (Handshakes) — needs a registration decision +- [ ] P3: filed (Handshakes) +- [x] Regression tests (fail on 58d3db3 + the probe, pass now) +- [x] Randomized ordering test, fast and `#[ignore]`d long +- [x] QA's seeds and hand scenarios against the binary +- [x] Timings +- [x] fmt, clippy `--all-targets -D warnings`, guarded `lucisv_server` + (fix round: 1 920 unit + 106 integration, 44 + 3 ignored), + `vlog_semantic` 435, `lucisv_mcp` 384, `node --test + editors/vscode/*_test.js` 37; ignored release runs (both re-index + sweeps, the 300-seed ordering run) pass +- [x] full `tools/gates.sh`: PASS, every step (corpus 814/6, the same six + known failures; `lucisv_server` 2 032/0) + +**Not verified here (no VS Code on this machine):** double-click a port name +and run Find All References — results, not "No references found"; F12 and +hover with the caret just after a name; a row of lucisv's References view +opens with the caret at the name's start, and Shift+F12 from there finds the +same list; F2 with the caret just after a name opens the rename box. + +## Work log + +### 2026-11-19 — dev agent + +Base is 58d3db3 (release 0.65.6). Drivers are the investigation's +(`scratchpad/inv717/drv`), QA's oracle (`scratchpad/qa711/oracle`) and the Q1 +driver (`scratchpad/qa713/drv/livelock2.py`), copied to `scratchpad/dev717/` +with the guard pointed at this worktree; every tree they touch is a scratch +copy, every index store is under `dev717/st`. + +**Reproduced on base, then fixed (same drivers, release binaries):** + +| | 58d3db3 | now | +|---|---|---| +| A1 `refpos.py` uart_core.sv `tx`, caret just past the name (col 27) | refs 0, def 0, highlight null, hover null | refs 3, def 1, highlight 2, hover yes (= col 25) | +| A1 one column further right (col 28) | 0 / 0 / null / null | 0 / 0 / null / null (unchanged) | +| B `f6.py held`, full sync | server holds v2, client v3 | v3 | +| B `f6.py tail`, full / incremental | v2 / v3 lost (`{qa_v2_mod}` only) | v3 / both, in place | +| B `f6.py held`, incremental | right by luck (the two inserts commute) | right | +| C `livelock2.py hover`, cold full OpenTitan | hover and tokens answered at 318.6 s, scan ended 318.6 s | hover 0.68 s, tokens(B) 0.76 s, scan ends 1.70 s (median of 3; 4th run, `delta` variant: 0.67 / 0.76 / 1.70 s) | + +**A1.** `caret.rs` is the rule (23 production lines): one byte left when the +caret's byte is not a name byte and the byte before is, or when the caret sits +on the whitespace that ends an escaped identifier. Applied after the UTF-16 → +byte conversion, so a multi-byte character before the name changes nothing. +`Server::symbol_offset` in dispatch.rs uses it for the nine requests in the +table. Decided against shifting *inside* the feature modules (`nav.rs` etc.): +one place, one rule, and the requests with their own boundary rule are visibly +the ones still calling `offset`. The References view's rows now open with a +collapsed selection at the identifier's start — `vscode.open` cannot carry a +backwards `Selection`, so "select the name, caret at its start" is not +expressible through it, and the start is where VS Code's own view and go to +definition put the caret. + +**B.** `Server::must_hold` is the rule, `Server::behind` the bookkeeping. The +prototype held every notification while a rescan a message asked for was +running (`answering_a_rescan`). That is a superset of what is needed and it +cost something real: a watcher event arriving during a rescan was then +applied *after* it, one scan each, instead of coalescing into one more scan. +`behind` is exact: `process_batch` sets it, for the message it is handling, to +"how many older messages are unapplied in the bursts around me", so a scan's +drain holds a notification only if something older really is waiting. Pinned +by `a_rescans_trigger_alone_in_its_burst_still_lets_newer_changes_apply_at_once` +(two bars: the rescan, and one more for both watcher events). Cancels follow +the same rule, so a cancel arriving after its held request now waits *with* it +and is honoured when the batch is replayed (before, it was dropped and the +request computed); a cancel naming a deferred request is still honoured where +it lands. + +Answers to the brief's questions: + +- *Must didClose/didSave/watched/config keep order?* Yes, all of them: the + rule is about the stream, not the method. A `didSave` held behind a held + request is applied after it — as the cheap one-file update, where before it + was folded into a whole rescan. +- *Other documents?* Same stream, same rule — `didClose(a)` then `didOpen(b)` + (a rename) cannot cross. `a_reopen_behind_a_held_close…` pins the one- + document form, the randomized test the cross-document one. +- *Starvation?* The scan drains exactly as before (the drain still reads, it + only holds). Progress is the scan's and unaffected. `shutdown` was already + held behind a rescan a message asked for and still is: measured with + `dev717/drv/exitmid.py` (see Timings). `exit` is read by `handle_shutdown` + off the connection, never queued. +- *Memory?* Under Assumptions. +- **One exemption, kept:** a navigation request the empty-answer rule + deferred (`Server::deferred`, startup scan only) is re-asked at the next + publish, and a `didChange` applied in between moves the text under its + position. That is the perf5r-publication design, not a reordering of + applied messages; the worst it gives is a stale or empty navigation answer, + never a buffer change. Not changed. + +**C.** As the prototype: the `didOpen` arm sets `head_owed` and +`opened_mid_scan` when a scan is running; `answer_what_is_waiting` clears the +flag before the batch and takes it after. **Bound:** a held batch is handed +back only when `!answering && !rescan_wanted && !head_owed`; handling it +re-holds something only behind a `didOpen` it *applied* (each message is +applied once) or a rescan it asked for (one per scan), so hand-backs ≤ +applied `didOpen`s + scans + 1 — the randomized test asserts exactly that +inequality every round, and base breaks it at seed 1, round 0 (37 hand-backs +for 2 `didOpen`s and 1 scan). + +**P2.** The index now holds every open buffer (a `didOpen` that moves no scope +takes an unheld buffer in through `update_one_file`, the path F4 already +used) and forgets a closed one that `scope_could_take` says no scan would +hold. Both halves were needed: closing alone fixed `r2attack.py +excluded-close` "closed" and "saved then closed" and broke "reopened". Mid-scan +the open half does nothing (as before) and the close half asks for one more +scan. One existing test changed fixture, not assertion: +`sync::closing_a_dirty_buffer…` opened two files that were not on disk, which +now costs an index change on close; the files are written to disk so the test +asks what it always asked. + +**P1, P3:** not changed — see Handshakes for what VS Code actually sends and +why the fix is a registration decision. + +**Tests** (new files; each failing test was run against 58d3db3 plus only the +`probe` hook, in `scratchpad/dev717/basecopy`): + +| test | 58d3db3 | +|---|---| +| `scan_ordering::a_change_drained_mid_rescan_waits_behind_an_older_change_held_with_a_request` | FAIL (holds v2) | +| `scan_ordering::incremental_changes_held_mid_rescan_are_applied_in_the_order_they_were_sent` | FAIL (second insert one line off) | +| `scan_ordering::a_change_drained_mid_rescan_waits_behind_the_rest_of_the_burst_that_started_it` | FAIL (holds v2) | +| `scan_ordering::a_reopen_behind_a_held_close_leaves_the_buffer_open_with_its_new_text` | FAIL (buffer closed) | +| `scan_ordering::a_request_ahead_of_a_didopen_mid_startup_is_answered_and_the_drain_runs_once` | FAIL (answered after the bar) | +| `scan_ordering::a_request_behind_a_didopen_mid_startup_still_waits_for_the_buffer_it_names` | pass (kept behaviour) | +| `scan_ordering::a_rescans_trigger_alone_in_its_burst_still_lets_newer_changes_apply_at_once` | pass (kept behaviour) | +| `caret_boundary::every_symbol_request_answers_the_same_just_past_a_name_as_at_its_start` | FAIL (references `[]`) | +| `caret_boundary::a_caret_after_a_dot_is_on_the_member_and_before_it_on_the_instance` | FAIL | +| `caret_boundary::the_column_past_a_name_is_counted_in_utf16_after_non_ascii_text` | FAIL | +| `outside_buffers::an_excluded_buffer_is_held_while_open_and_forgotten_when_closed` | FAIL | +| `outside_buffers::a_buffer_not_on_disk_is_held_while_open_and_forgotten_when_closed` | FAIL | +| `outside_buffers::closing_a_buffer_the_scope_takes_leaves_the_index_alone` | pass (kept behaviour) | +| `ordering_random::random_bursts_keep_every_buffer_and_answer_every_request_once` | FAIL (C bound, seed 1 round 0; with that check disabled, B: seed 1 round 5, `a.sv` lost an edit) | +| `caret::tests` (7, the rule itself) | — (new module) | + +**Randomized test** (`ordering_random.rs`): a seeded xorshift client with three +documents sends bursts of 1–4 messages — full and incremental `didChange`s +(insert or delete a line, ranges in the client's own current text), +`didOpen`/`didClose`, `$/cancelRequest` for a random earlier id, hover / +definition / documentSymbol / workspace/symbol, and watcher create/delete +events; 70 % of rounds put a rescan trigger at a random place in the round's +first burst, and 0–6 more bursts land at the scan's interleave points through +the probe. The startup scan gets 1–5 scripted bursts too (that is where C +lives). After every round: the server's open buffers are the client's and +their text is byte-equal; hand-backs ≤ `didOpen`s + scans + 1. At the end: +every request answered exactly once, and documentSymbol of every open buffer +plus the created packages equal a fresh server's on the same disk and +buffers. Normal suite: seeds 1–12 × 10 rounds, ≥ 200 bursts must land +mid-scan (300 do), 0.8 s debug. `#[ignore]`d long run: seeds 100–399 × 40 +rounds, ≥ 10 000 mid-scan bursts, 32 s in release — passes. + +**QA's oracle against this binary** (logs `scratchpad/dev717/logs/`), none +with `QA_REPAIR` (the "re-send buffers before each check" workaround): + +| run | 58d3db3 / QA | now | +|---|---|---| +| `rand_run.py` corpus, push, seed 7 × 200 (every 25) | divergent at step 200 (F6) | 8 checks, 0 divergent | +| `rand_run2.py` OpenTitan sample, seed 42 × 500 (every 25), `QA_FRESH_SAVE=1` as in QA's run | step 350 divergent (F6) | 20 checks, 0 divergent | +| `rand_run.py` full OpenTitan `hw`, seed 21 × 50 (every 50) | 309 answers differ | 0 differ | +| `small.py`, workspace + folder scope, pull and push | — | 94 + 94 ok; only `NEGCTL-silent` diverges (both scopes), as it must | +| `outside.py`, pull and push | — | 14/14 and 14/14 ok (re-run on the final binary too) | +| `r2attack.py` (all cases) | `directory-create`, `held-directory-deleted` (P1), `excluded-open-close` closed / saved-then-closed (P2) diverge | only the two P1 cases diverge | + +Seed 42 run *without* `QA_FRESH_SAVE` diverged at step 50 on an excluded +buffer (`qa_excl/qa_x0.sv`) the incremental server now holds while it is open +and the fresh side does not — the fresh server's documented startup race (a +buffer opened while its startup scan takes its work list is not taken in), +which is what `QA_FRESH_SAVE` exists to remove; with it, 0 divergent over 500 +steps. + +**Re-index lane sweeps** (release, `--ignored a_seeded_sweep`): corpus 3 +seeds and OpenTitan sample 2 seeds, both pass. + +**Timings** (release, full OpenTitan `hw` 4 061 files, workspace scope; the +machine is shared with another lane): + +| | 58d3db3 | now | +|---|---:|---:| +| startup scan, cold (median of 3) | 2 104 ms | 2 077 ms | +| startup scan, warm (median of 3) | 1 124 ms | 1 124 ms | +| `perf.py`, median of 5, save → `reindex_one` line: uart_tx comment / uart_tx signal / prim_flop signal / prim_flop top / uart_reg_pkg member / prim_assert / prim_mubi member / prim_mubi top / tlul_pkg top / new `uvm_object` / new `` `define`` / clk_rst_if top | 0.04 / 8.2 / 8.1 / 67.3 / 22.8 / 3.5 / 97.9 / 98.8 / 85.4 / 13.4 / 9.5 / 28.6 | 0.04 / 8.6 / 8.4 / 67.1 / 23.5 / 3.4 / 106.5 / 103.2 / 84.3 / 10.5 / 14.6 / 30.0 | +| watcher echo, every row | 0.03–0.35 ms | 0.02–0.33 ms | +| C: `[hover, didOpen(B), tokens(B)]` in a cold startup (`livelock2.py`) | 318.6 s | 1.70 s scan, hover 0.68 s | +| `didClose` of a held file (P2's scope check), median of 3: prim_assert (174-file dir) / top_earlgrey / uart_core / dv_base_env | 0.02 / 0.16 / 0.13 / 0.02 ms | 1.22 / 0.41 / 0.27 / 0.22 ms | +| `didOpen` of the same four | 0.21 / 1.64 / 1.28 / 0.31 ms | 0.20 / 1.57 / 1.15 / 0.28 ms | +| shutdown sent mid-rescan, behind a held hover and change (`exitmid.py`) | answered 0.75 s, exit 0.92 s later | answered 0.76 s, exit 0.87 s later | + +The save rows move by noise either way except `prim_mubi_pkg` (+5–9 ms of +~100) and the new `` `define`` (+5 ms), both single-digit and in rows whose +work this round does not touch (nothing here runs on a save); a `didClose` +now pays the scope walk of its directory, about a millisecond at worst. + +**Test hook:** `server/probe.rs` (`#[cfg(test)]`, thread-local) — the +transport cannot be timed against a scan's files, so a test scripts what +arrives at each interleave point. One `#[cfg(test)]` line in +`answer_what_is_waiting`. + +**Files** (production lines, non-blank non-comment, before `mod tests`; base +in parentheses): `server/mod.rs` 203 (186), `server/dispatch.rs` 491 (486), +`server/index.rs` 292 (265), `server/notification.rs` 252 (244), +`server/batch.rs` 74 (`opened_in` removed), `server/startup.rs` 173 (+2), +`state/watched.rs` 95 (+3), `state/incremental.rs` 145 (+4), new +`caret.rs` 23, new `server/probe.rs` 46 (test-only); `main.rs` +1; +`editors/vscode/referencesView.js` +5. Tests: `server/tests/{scan_ordering, +caret_boundary,ordering_random,outside_buffers}.rs` new, `tests/mod.rs` ++4 module lines, `tests/sync.rs` fixture, `referencesView_test.js` one +assertion. + +### 2026-11-19 — dev agent: fix round (QA-1 … QA-5, the size note) + +**QA-1 — P2 reverted.** `take_in_if_unheld`, `forget_if_outside`, +`Workspace::holds_outside_the_scope` and `Workspace::forget_file` are gone; +`state/watched.rs`, `state/incremental.rs` and `server/tests/sync.rs` are +byte-identical to 58d3db3 again (the `sync` fixture change is undone — +without P2 it is not needed), `server/tests/outside_buffers.rs` is deleted. +Making open/close of an unheld file cost < 1 ms is not reachable at the +server layer: adding or removing one file shifts ids and rebuilds the +completion tables and the include naming (QA's `sample`), so it is filed as +an index-layer change (Handshakes, with QA-2 and QA-7a). QA's drivers, +full OpenTitan, before the other lane's load test started: + +| `lat717.py` (median of 5), didOpen / didClose | 58d3db3 | round 1 (QA) | now | +|---|---|---|---| +| held files | 0.83–2.72 / 0.11–0.27 ms | 0.47–1.74 / 0.39–1.02 ms | 0.80–3.43 / 0.11–0.29 ms | +| outside the root | 0.57–0.59 / 0.08–0.10 ms | 185–189 / 222–230 ms | 0.54–0.56 / 0.06–0.08 ms | +| excluded | 0.55–0.59 / 0.07 ms | 188–190 / 222–225 ms | 0.44–0.81 / 0.07–0.08 ms | +| outside / excluded, 200 buffers open | 0.47–0.60 / 0.07–0.08 ms | 201–228 / 258–279 ms | 0.52–0.58 / 0.06–0.08 ms | +| `p2perf.py`: 2 000 outside files opened and closed | 0.7 s | 806 s | 0.7 s | +| `p2perf.py`: didClose with ~200 open, in-scope / outside (median) | 0.13 / 0.09 ms | — | 0.11 / 0.09 ms | + +**QA-3 — the rule narrowed** to "no notification overtakes an older +notification" (`must_hold`; the soundness argument is under Assumptions). +Chosen over a staging-only patch because it is the rule B actually needs and +the broad rule bought no state the client could see; the staging case then +needs nothing special. `live717.py staging`, first hover with a request ahead +of the first `didOpen`: 58d3db3 0.111–0.133 s, round 1 0.151–0.160 s, now +0.116–0.125 s (3 × 3 runs). Cancels: one waits whenever anything is held +(so a late cancel of a held request is still honoured); `changes_state` +excludes them from what makes a notification wait. New test +`a_change_behind_only_a_held_request_applies_at_once_and_a_late_cancel_waits_with_it` +pins both halves. Every earlier test, the randomized one (fast and the +`#[ignore]`d 300-seed run) and f6.py's six variants pass unchanged. + +**QA-4 — documented, not changed.** QA's `c717.py` (cold full OpenTitan, 16–18 +bursts `[request, didOpen×1–3]` in the first 0.2 s) on the narrowed rule: +scan ends 3.74–4.17 s (5 seeds), answers 0.02–4.17 s, median 1.40–1.68 s; QA +measured 2.8–4.2 s on round 1, the same 26 opens without requests 1.66–1.89 s. +Each request behind an applied `didOpen` is held until the work list +re-ordered round that buffer has indexed its neighbourhood, and the hand-back +then forces a publish (a merge over the index so far) so the answer can see +it — one per burst here. Coalescing hand-backs would mean answering a later +burst's requests before *its* neighbourhood is in, which is the §P4b `[]` +the head rule exists to prevent; cheaper publishes are the index layer's. +So the cost stays: bounded (≤ one forced publish per applied `didOpen`), +seconds, against ~400 s on base. + +**QA-5 — the changelog** now names what is ordered: edits, opens, closes, +saves and the other notifications (not responses, not deferred navigation +requests). + +**Size.** `process_batch` 95 → 69 lines: the splice into `held` is +`Server::hold`, and answering one request (cancelled / deferred / computed) +is `Server::answer_from_batch`. No behaviour moved. + +**Fix-round checks against this binary** (`dev717/logs3`, none with +`QA_REPAIR`). Another lane ran an 18-busy-loop load test on this machine from +about 11:00 into the oracle runs, so the latency numbers below that window are +not comparable and were re-taken after it eased. + +| run | result | +|---|---| +| `refpos.py` (A1) | col 27 = col 25 (refs 3, def 1, highlight 2, hover), col 28 nothing — unchanged | +| `f6.py` held / tail / control, full and incremental | all six: server holds v3, incremental inserts in place | +| `livelock2.py hover` (C), after the load eased | hover 0.66–0.90 s, tokens(B) 0.74–0.99 s, scan ends 1.67–2.15 s (3 runs) | +| `q1min.py` | answered 0.96 s, one progress cycle | +| corpus push 7 × 200 | 8 checks, 0 divergent | +| OpenTitan sample 42 × 500 (`QA_FRESH_SAVE=1`) | 20 checks, 0 divergent | +| full OpenTitan 21 × 50 | 0 divergent | +| new: corpus push 111 × 300 (`rand_run2.py`) | 12 checks, 0 divergent | +| new: OpenTitan sample 211 × 300 (`QA_FRESH_SAVE=1`) | 12 checks, 0 divergent | +| `small.py` pull and push, both scopes | 94 + 94 ok; only `NEGCTL-silent` diverges, as it must | +| `outside.py` pull and push | 14/14 and 14/14 | +| `r2attack.py` | P1's two cases and P2's two (excluded-open-close closed / saved then closed) diverge — 58d3db3's set, as the revert intends | +| full `tools/gates.sh` | PASS every step; `lucisv_server` 2 030/0, corpus 814/6 | + +**Production lines now** (as before, base in brackets): `server/mod.rs` 215 +(186), `server/index.rs` 267 (265), `server/notification.rs` 248 (244), +`server/batch.rs` 77 (`opened_in` removed, `changes_state` added), +`server/dispatch.rs` 491 (486), `server/startup.rs` +2, `caret.rs` 23, +`server/probe.rs` 46 (test-only); `state/` untouched. + +## Changelog paragraph (for the lead) + +**Find All References, Go to Definition, hover, highlight and rename now work +with the cursor just after a name.** A double-click, a click on the right half +of the last letter, or a click on a row of lucisv's References view leaves the +cursor there, and the server used to look at the character after the name — +so VS Code said "No references found" until you clicked away and back. The +References view now also puts the cursor at the start of the name it opens. +**An edit typed while the workspace was re-indexing could be applied out of +order**, leaving the server's copy of the file different from the editor's +until it was closed and reopened; edits, opens, closes, saves and the other +notifications the editor sends are now applied in the order it sent them. **A +file opened while the first index of a session was being built could make +that index take minutes instead of seconds** on a large workspace (about +300 s instead of 2 s on OpenTitan); fixed. + +## QA log + +### 2026-11-19 — QA agent (Opus 5.5) + +**Verdict: PASS WITH FINDINGS.** No lost, duplicated or reordered message, no +deadlock, no wrong buffer text and no wrong rename found in anything below. One +**High** finding (QA-1, a P2 cost: opening or closing a file the index does not +hold now blocks the loop ~0.2 s on OpenTitan) should be fixed before release; +the rest are Low/Info or pre-existing. Everything ran against release binaries +built here (`qa717/bin/new` from this worktree, `qa717/bin/base` from +`git archive 58d3db3`, own `CARGO_TARGET_DIR`s). All drivers and logs are in +`scratchpad/qa717/{drv,oracle,logs}`; every tree was a scratch copy, every +index store under `qa717/st`; `~/.cache/lucisv-opentitan-full` `git status +--short` empty and nothing under either cache newer than this QA's start. + +**Baseline.** `tools/gates.sh` (full, logs `qa717/gates/`): PASS — fmt, +clippy `-D warnings`, build, every suite (`lucisv_server` 2 032/0, +`vlog_semantic` 435/0, `lucisv_mcp` 384/0), docs, corpus 814/6, node 37/0. +One guard kill — see QA-6. Ignored release runs (`--ignored ordering_random +sweep_over_the_corpus sweep_over_an_opentitan`, guarded, trees from scratch +copies): 3/3 pass. Counts vs 58d3db3: `lucisv_server` unit 1 901 + 43 ignored → +1 922 + 44 (+14 server tests, +1 ignored long run, +7 `caret` unit); integration +106/3 unchanged; no pre-existing test removed or edited except `sync.rs`. +**The changed fixture:** with the base fixture on the new code the test fails +`generation 6 != 5` — P2's take-in/forget of two not-on-disk buffers is an extra +index change and republish. Writing the files to disk keeps the test's subject +(the closed buffer's dirty text is never analyzed, the other one flushes) and +every assertion's meaning; accepted. **New tests on base:** grafted +`probe.rs` + its one `#[cfg(test)]` call + the four test files onto the +58d3db3 archive: exactly the 11 the README lists fail, the 3 "kept behaviour" +tests pass. `probe` is `#[cfg(test)]` at `server/mod.rs:60` and +`server/index.rs:522`, no other reference. Sizes: every touched file under 600; +`process_batch` is 95 lines (78 on base), mostly comment — over the 80 line +"investigate" mark (Info). + +**B/C code read.** `must_hold`, `behind`, `process_batch`, +`answer_what_is_waiting`, `waiting_for_this_scan`, `run`'s replay, +`take_the_answer_out_of_held` and the staging loops: every message put in +`held` is taken out by `run` (loop top) or by the startup scan's drain; `held` +non-empty never outlives a scan, and nothing waits on a client response except +staging's bounded waits (the only `recv_timeout`s). `behind` is restored on +every exit of `process_batch` that the caller reads. No path found where a +message is applied twice or dropped. + +**B — ordering, own stdio driver** (`drv/ord717.py`, independent of the probe): +4 synthetic documents in 4 folders, seeded bursts of 1–5 messages written in +one `write()` — incremental single- and multi-change and full `didChange`s, +`didOpen` (disk or new text), save-then-`didClose`, `didSave` (±text), +documentSymbol / hover / definition / references / semanticTokens / highlight / +workspace/symbol, `$/cancelRequest` of a recent id, watcher create/delete of +package files, an unknown notification, a malformed `didChange` — while scans +run: the startup scan, workspace-folder add/remove, a pushed and an *empty* +(`workspace/configuration` pull) config change, a save of an unheld file, +watcher creates. Checked: **every documentSymbol answer equals the client's +text at the moment the request was sent** (the order contract, exact +names/lines/columns); after each settle every buffer's text, open/closed state +and the watcher/save effects; every id answered exactly once; a final battery +(documentSymbol, semantic tokens, hover/references/definition at both ends of +every name, workspace/symbol, push diagnostics) equal to a fresh server's. +Runs: corpus seeds 1–3 ×30 and 10–17 ×60 (workspace), 20–23 ×60 (folder); full +OpenTitan seeds 30–32 ×40 (workspace), 40–41 ×40 (folder): **≈ 8 700 bursts, +≈ 27 000 messages, 85 % of bursts sent while a scan was running, ≈ 4 500 +at-send-time checks — 0 ordering/text/state failures, 0 duplicate or missing +responses.** Fresh oracle: equal in every run once the driver saved dirty +buffers before comparing (the 6 seeds that had differed, re-run, and the 5 that +never had); the 12 runs that differed before that correction differed *only* in +`workspace/symbol` for module names typed but not yet saved — the documented +index staleness of unsaved text, not this lane. The same driver on **base fails at once** (seed 1: 22 failures, +both scopes — stale documentSymbol answers, a buffer one edit behind). +(Two driver corrections were needed, both *my* model: duplicate wire names +collapse in documentSymbol; and unsaved buffer text reaches the index only at a +scan or save, so the final oracle saves dirty buffers first. A third thing the +driver found is pre-existing — QA-7.) + +**Liveness / latency** (`drv/live717.py`, full OpenTitan, whole rescans of +~0.6–1.8 s; base vs new): + +| case | 58d3db3 | now | +|---|---|---| +| hover held mid-rescan, then its cancel: cancel → answer | 0.55–0.59 s, honoured 4/5 (once computed) | 0.58–0.62 s, honoured 5/5 | +| shutdown behind a held hover + change mid-rescan: answer / exit | 0.65 s / 0.86 s; hover answered first | 0.66 s / 0.94 s; hover answered first | +| `exit` alone mid-rescan with a held queue | exits 0.8–1.6 s | exits 1.0–1.6 s | +| server's `workspace/configuration` (+ progress create, lens refresh) held by the client, answered mid-burst while notifications are held | no deadlock, final text right | no deadlock, final text right | +| 20 000 incremental `didChange`s flooded behind a held request across rescans | settle 23 s, RSS peak 686 MB, **text wrong** | settle 27 s, RSS peak 679 MB, text right | +| VS Code-like typing (change + tokens + highlight per key, 30 ms) through 5 rescans | scans 1.5–1.85 s, **text wrong at the end** | scans 1.6–1.86 s, text right | +| request before the first `didOpen` during staging: first hover | 0.11–0.13 s | 0.15–0.18 s (QA-3) | + +(The shutdown case exits with rc 1 in 2 of 3 runs on *both* binaries — pre-existing, Info.) + +**C bound** (`drv/c717.py`: cold startup on full OpenTitan, 26 `didOpen`s in +13–14 bursts `[request, didOpen×1–3]` every 2–10 ms): base — every answer at +406.9 s, scan ends 406.9 s. Now — scan ends 2.8–4.2 s (5 seeds), answers +0.03–4.15 s, no duplicate. Same 26 opens with no requests between them: scan +1.66–1.89 s; plain cold startup 1.65 s. So C is fixed and bounded, but see QA-4. + +**A1 sweep** (`drv/a1sweep.py`): 200 corpus files × 25 tokens and 150 OpenTitan +files × 20 tokens (identifiers, keywords, macros, system tasks, numbers), all +nine requests: **69 030 token×request pairs; end == start == middle on the new +server in every one**; new == base at the start in all but 6 (all in +OpenTitan's duplicated `top_*/ip/ast` modules — `rename` there is +nondeterministic on base too: 4 edit / 4 refused in 8 fresh base servers; QA-7); +**one column right of the name (40 158 cases) new == base in every one.** +Edges (`drv/a1edge.py`, `drv/a1rename.py`): `\foo `/`\a+b ` (on the ending +space: the name; after it: nothing), `$bits(a|)`, `` `FOO| ``, `` `BAR|(b) ``, +`8'hFF|` / `8'hF|F` / `12|` (nothing — no `hFF`/`FF` signal resolved), +`begin|`/`end|`, `u_a|.b`/`u_a.|b`/`u_a.b|`, `pkg|::x`/`pkg:|:x`/`pkg::|x`/`pkg::x|`, +`a|+b`, `x|[i]`, `x[i|]`, `f|(a)`, `f(a|)`, end of line, `endmodule : d|` at EOF +with and without newline, empty file, column 0, CRLF, tabs, non-ASCII and an +astral character before the name, `ifdef`-out region: end-of-name == start +everywhere. Comments, strings and a `` `define`` body: nothing at start and end. +Rename/prepareRename at the end-of-name caret: placeholder and range are the +whole name and the applied edit is byte-identical to the one from the start in +all nine shapes — never the neighbour. A position past the end of a line now +resolves the line's last name (VS Code never sends one; Info). **Request table:** +every arm in `dispatch.rs` that reads a position is either one of the nine or in +the "as sent" rows (linked editing, signature help, completion, inline +completion, on-type, selection range, the two code-action uses of +`range.start`, executeCommand); declaration/implementation/moniker are not +served; nothing missed. + +**P2** (`drv/p2.py`: excluded / outside-the-root / not-on-disk buffer × +open-close, open, close-reopen, save-close, change-close, open-mid-scan-close, +close-mid-scan, open+close in one burst; fresh server with the same buffers +opened before its scan): workspace scope **24/24 equal (base 12/24)**. Folder +scope: the outside-the-root file stays held after close — the opened file's +folder widened the scope, which never shrinks; base does the same in an +isolated tree, by design. 2 000 distinct outside files opened and closed: RSS +695 → 718 MB, none left in the index — but see QA-1 for the time it took. +`QA_FRESH_SAVE` — see QA-2. + +**Re-index oracle on this binary** (QA 71.1's scripts, no `QA_REPAIR`): +`small.py` pull and push, both scopes: only `NEGCTL-silent` diverges, as it must; +`outside.py` 14/14 both. Previously failing seeds: corpus push 7 ×200 — 8 checks, +0 divergent; full OpenTitan 21 ×50 — 0 differ; OpenTitan sample 42 ×500 with +`QA_FRESH_SAVE` — 20 checks, 0 divergent (without it: divergent at step 50, the +QA-2 race). New seeds: corpus 101–103 ×500 and push/folder 104 ×500 — 0 divergent; +OpenTitan sample 201–203 ×500 — 0 divergent with `QA_FRESH_SAVE`, divergent at +step 150–200 without (every diff an excluded `qa_excl` buffer, QA-2); full +OpenTitan 301 ×100 — 13 answers differ at step 100, **identically on base** +(QA-7). + +**References view.** VS Code's `TextEditorOpenOptions.from` converts +`selection` with `Range.from` and `codeEditorWidget.setSelection(IRange)` makes +the range's *end* the position — so base put the caret just past the name, the +A1 spot; a collapsed range at `range.start` puts it at the name's start, where +Shift+F12 works on a base server as well as this one (VS Code's own references +view uses `range.with({ end: range.start })`). Cost: the row no longer +*selects* the identifier. The test asserts the new collapsed range. The P1 +analysis checks out against `watcher.ts` (`coalesce`: deletes under a deleted +parent dropped) and `extHostFileSystemEventService.ts` (each event filtered by +the registered glob). The extension sets no `wordPattern`, so VS Code's default +word rule is the one in play. + +**Timings** (release, full OpenTitan, workspace scope, medians of 5, machine +shared with this QA's own runs): cold startup 1 667 → 1 681 ms, warm 747 → 747 +ms. Open/close (`drv/lat717.py`, didOpen → its publish, didClose → its clearing +publish): + +| file | 58d3db3 open / close | now open / close | +|---|---|---| +| held (prim_assert, top_earlgrey, uart_core, dv_base_env) | 0.46–1.83 / 0.07–0.18 ms | 0.47–1.74 / 0.39–1.02 ms | +| outside the root, 0 other buffers | 0.33–0.36 / 0.06–0.07 ms | **185–189 / 222–230 ms** | +| excluded, 0 other buffers | 0.34–0.37 / 0.06–0.07 ms | **188–190 / 222–225 ms** | +| outside / excluded, 200 buffers open | 0.31–0.38 / 0.05–0.07 ms | **201–228 / 258–279 ms** | + +Saves (QA 71.1's `perf.py`, 5 reps, save → `reindex_one` line, base / now): +uart_tx comment 0.05 / 0.04, uart_tx signal 5.4 / 4.2, prim_flop signal 4.4 / +4.3, prim_flop top 49.6 / 48.8, uart_reg_pkg member 12.9 / 12.1, prim_assert +1.4 / 1.5, prim_mubi member 93.5 / 91.2, prim_mubi top 90.3 / 85.1, tlul_pkg top +69.9 / 67.1, new `uvm_object` 4.8 / 4.1, new `` `define`` 6.9 / 6.2, clk_rst_if +top 16.6 / 26.2 ms; echoes 0.03–0.28 ms both. Unchanged within noise except +clk_rst_if, the one row that moved (the dev measured it 28.6 / 30.0, so most +likely noise; nothing in this lane runs on a save). + +**Findings** + +- **QA-1 (High, performance, P2).** `server/index.rs:212-224` + (`take_in_if_unheld`) and `:189-202` (`forget_if_outside`), called from + `notification.rs:109` and `:285`. Taking an unheld buffer in on `didOpen` + and forgetting it on `didClose` each run a one-file index update plus lens + refresh, hierarchy bump and `republish_all`, synchronously on the message + loop. On full OpenTitan that is ~190 ms per open and ~225 ms per close (table + above; ×500–3 000 vs base), with nothing else open; 2 000 outside files opened + and closed took **806 s vs 0.7 s** (`drv/p2perf.py`). A `sample` of the server + meanwhile sits in `Candidates::unit_tables`/`merge_words`/`take_index_tables`, + `IncludeGraph::refresh_naming_all`, `dependents::note`, + `WorkspaceIndex::push_records`. Every keystroke, hover and completion queued + behind such an open/close waits for it. Repro: + `python3 -I drv/lat717.py BIN 5`. The README's timing rows + measured only *held* files. Correctness of P2 is fine; its cost is not. +- **QA-2 (Low, P2 gap; on the `QA_FRESH_SAVE` question).** A buffer the index + does not hold that is opened while a scan is running is not taken in, and + nothing takes it in when that scan ends (`take_in_if_unheld` returns at + `scan_owed()`): `drv/race717.py BIN 0.5` — an excluded file + opened 0.5 s into the startup scan is still unheld after settle, base and new + alike; opened before the scan it is held. So "the index holds every open + buffer" (Handshakes 4) is true only for buffers opened outside a scan, and the + same final state answers differently depending on when the buffer was opened. + The dev's argument is sound as far as it goes — the divergence `QA_FRESH_SAVE` + removes is the *fresh* server losing this race, not the incremental one + getting anything wrong — but it is a real, user-visible nondeterminism of the + server (pre-existing in kind), and `QA_FRESH_SAVE` hides it. Suggest taking in + open unheld buffers when a scan finishes, or documenting the limit in + Handshakes 4 rather than only in the code comment. +- **QA-3 (Low, startup).** `startup.rs:283-296` (`await_opening_file`): a + request that arrives before the first `didOpen` during staging is held + (`staging`), and the `didOpen` behind it is now held too (`must_hold`: + `held` non-empty), so the "wait for the first buffer" loop never sees it, + waits its full 25 ms bound, and the startup scan does not lead with the user's + folder. Measured first hover 0.15–0.18 s vs 0.11–0.13 s (`live717.py staging`). + Harmless to correctness; not mentioned in the README. +- **QA-4 (Low, C cost).** The C bound holds (≤ one hand-back per applied + `didOpen` + 1), but each hand-back forces a `publish_scan`: 26 opens + interleaved with requests stretch the cold OpenTitan startup scan from + 1.65–1.9 s to 2.8–4.2 s, and in 2 of 5 seeds a request is answered only at + the scan's end (3.7–4.2 s). Five minutes → four seconds, so this is a note, + not a blocker; the README's 1.70 s figure is for the 3-message `livelock2` + burst. +- **QA-5 (Info, docs).** The changelog's "every message is now handled in the + order it was sent" overstates it: responses and deferred navigation requests + are exempt (both explained in the Work log). Suggest "every edit". +- **QA-6 (Info, pre-existing, outside this lane).** `tools/gates.sh`: + `suite:lucisv_mcp` was KILLED by the guard at 600 s and passed on the retry; + the hung test was `qa_m3::qa_lucisv_check_over_the_same_tree_while_the_server_formats` + (`crates/lucisv_mcp/tests/qa_m3.rs:687`). `lucisv_mcp` does not depend on + `lucisv_server`, and the 0.65.5 release gates log shows the same KILLED → + retried. Not filed anywhere in `TODO.md`; reporting as CLAUDE.md asks. +- **QA-7 (pre-existing, outside this lane — file for the backlog).** (a) + Closing an **unsaved in-scope** buffer whose text a rescan took into the + index leaves that text in the index after the close (`drv/closeidx.py BIN + rescan`: `qd_buf` survives the close, a fresh server holds `qd_disk`) — + identical on base; P2 covers excluded/unlisted files only. (b) `rand_run.py` + full OpenTitan seed 301 ×100: 13 answers differ at step 100 (pull diagnostics, + references, incoming calls in `top_earlgrey/ip/ast/rtl/usb_osc.sv`) — + byte-identical divergence on base. (c) Rename of a port of a module defined + twice in OpenTitan (`top_englishbreakfast/ip/ast/rtl/adc.sv:81` + `rst_adc_ni`) is edit-or-refuse at random across fresh servers, base and new + (`drv/dup.py`). All three involve state this lane did not touch. + +**Fixed myself:** nothing. **Not verified (no VS Code here):** the four items +under Status; that VS Code itself never sends a request ahead of its first +`didOpen` during staging (QA-3's trigger). + +### 2026-11-19 — QA agent (Opus 5.5), round 2 (f1d4492 on dbb2349) + +**Verdict: PASS WITH FINDINGS** (one Info-level note on the narrowed rule, +pre-existing in kind; nothing new). Binaries: `qa717/bin2/new` (this tree), +`qa717/bin2/base` (`git archive dbb2349`), `qa717/bin2/r1` (round 1's binary, +for comparison). Caches untouched as in round 1. + +**Baseline.** Full `tools/gates.sh` (logs `qa717/gates2/`): PASS every step +including `cross`; `lucisv_server` 2 030/0 (dbb2349: 1 901 + 106 + 4 = 2 011 → +1 920 + 106 + 4, +19 and +1 ignored), `vlog_semantic` 435, `lucisv_mcp` 384 (no +guard kill this time), corpus 814/6, node 37. Ignored release runs 3/3 pass. +P2's revert is a clean one: no `state/` file and no `sync.rs` in +`git diff dbb2349`. `caret.rs`, `dispatch.rs`, `referencesView.js` and +`caret_boundary.rs` are byte-identical to round 1. + +**What the narrowed rule promises, stated as checked** (`must_hold`, +`server/mod.rs`): (i) after settle every open buffer's text, and which buffers +are open, equal the client's; (ii) non-cancel notifications are applied in the +order sent, across documents — a notification is applied only when no older one +is in `held` or in an enclosing burst's unapplied tail; (iii) every request is +answered exactly once; (iv) a request is answered against the state after every +notification sent before it, and possibly after some sent after it — so its +answer reflects *some* client state between sending and answering, never one the +client did not have (each `didChange` is applied whole, in one handler call). + +**Ordering driver** (`drv/ord3.py`: round 1's driver with check (iv) — every +documentSymbol answer must equal the expected symbols of the client's state at +send or of some later state the client had sent before the answer arrived, each +state recorded per message): corpus seeds 510–519 ×60 (workspace), 520–523 ×60 +(folder); full OpenTitan 530–533 ×40 (workspace), 540–541 ×40 (folder); +incremental single/multi-change and full-sync changes, scans in flight as in +round 1. **20 runs, 9 118 bursts (≈ 87 % mid-scan), 28 663 messages, 4 693 +state checks: 0 failures, 0 duplicate or missing responses, every fresh oracle +equal; 13 answers reflected a later state than at send, each one a state the +client had.** The same check fails at once on dbb2349 (seed 501: answers +matching no client state, a buffer an edit behind). An earlier run of my +coarser `ord2.py` (states recorded per burst, not per message) flagged one +answer (seed 514) that matched no burst-final state; with per-message states the +same seed ran clean three times — a driver limitation, recorded. + +**Harm hunt** (`drv/harm2.py`, `GAP=0.2`, full OpenTitan, index not persisted so +the rescan really interleaves; a request sent against v1 is held, then a +`didChange` to v2 that inserts a line above it is applied mid-scan): + +| request held, then v2 applied | dbb2349 | round 1 | now | +|---|---|---|---| +| rename of `beta` at its v1 position | answered on v2: renames **`alpha`** (the name now at that position); edit consistent with v2 | answered on v1; applied to the client's v2 it **corrupts** (`logic qqa;`, `alpqq`) | **as dbb2349** | +| hover / definition / references | about `alpha`, v2 ranges | about `beta`, v1 ranges | as dbb2349 | +| formatting | edits for v2, applied to v2 = v2's own formatting | same | same | +| hover held, then `didClose` applied | `null` | answered from the open buffer | `null` | +| documentSymbol(A) held, then `didClose A` + `didOpen A2` | `null` | from A | `null` | +| documentSymbol(B) sent before `didOpen B` | B's buffer | `null` | B's buffer | +| `[documentSymbol, change v2]` in one burst, then v3 | answered on **v3** (B) | v1 | v1 | + +So the narrowing restores dbb2349's late-request behaviour exactly — no harm +that base did not already have — and keeps B fixed (last row). Rename edits are +unversioned (`changes` map; `extract.rs:185` sends `version: None`), so a client +cannot reject a stale one by version; VS Code drops a rename or format result +when the buffer changed while it waited (its editor-state cancellation), so the +practical exposure is a client without that guard. **QA-8 (Info, pre-existing):** +a held position-taking request can resolve a *different* symbol when a newer +edit moved the text under its position — identical on dbb2349. Round 1's +strict rule had the opposite trade (right symbol, ranges for text the client no +longer had). + +**Liveness** (`live717.py`, dbb2349 / now): cancel of a held request mid-rescan +answered 0.58–0.62 / 0.55–0.60 s, honoured 5/5 / 5/5; shutdown behind a held +hover + change answered 0.70 / 0.70 s, hover first, exit < 1 s (rc 1 in 2 of 3 +on both, as round 1); `exit` alone 0.8–1.6 s on both; server→client requests +held by the client and answered mid-burst: no deadlock, final text right on +both; 20 000-change flood (now): settle 27.7 s, RSS peak 680 MB, text right; +typing through 5 rescans: scans 1.67–1.90 / 1.69–1.93 s, **text wrong on +dbb2349, right now**; staging (QA-3): first hover 0.13–0.15 / 0.13–0.14 s — +fixed (round 1 was 0.15–0.18 s). + +**C** (`c717.py`, 26 opens in 13–14 `[request, didOpen×1–3]` bursts, cold full +OpenTitan): scan ends 2.59–3.32 s, answers 0.02–3.32 s (5 seeds), 0 duplicates; +round 1 2.8–4.2 s; dbb2349-class base 407 s; plain cold startup 1.51 s +(dbb2349 1.51 s, now 1.53 s; warm 0.71 / 0.70 s). QA-4 as documented. + +**P2 revert confirmed.** `lat717.py`: outside/excluded didOpen 0.41–0.72 ms, +didClose 0.07–0.12 ms (dbb2349 0.37–0.79 / 0.06–0.13 ms); held files as base. +`p2perf.py`: 2 000 outside open+close 0.6 s (dbb2349 0.7 s), RSS flat. +`r2attack.py`: the same four divergent cases on both binaries +(directory-create, held-directory-deleted, excluded-open-close closed and +saved-then-closed); `outside.py` 14/14 equal on both, push and pull. + +**A1** (code byte-identical): sample sweep 60 corpus files × 15 tokens, 7 830 +token×request pairs — end = start = middle everywhere, start and end+1 = base +everywhere; `a1edge.py` all end = start; `a1rename.py` 9/9 identical. + +**Oracle (no repair workaround):** `small.py` push and pull — only +`NEGCTL-silent` diverges (both scopes); corpus push seed 7 ×200 — 0 divergent; +full OpenTitan 21 ×50 — 0; OpenTitan sample 42 ×500 (`QA_FRESH_SAVE`) — 0. +New: corpus seed 601 ×500 — 10 checks, 0 divergent; OpenTitan sample 602 ×500 +(`QA_FRESH_SAVE`, for QA-2's race) — 10 checks, 0 divergent. + +**Findings this round:** QA-8 above (Info, pre-existing). Round 1's QA-1 and +QA-3 are fixed, QA-4 documented, QA-5 reworded; QA-2, QA-6, QA-7 stand as +written (pre-existing, outside this lane). **Fixed myself:** nothing. **Not +verified:** a real VS Code (the Status items, and whether VS Code's editor-state +cancellation really sends `$/cancelRequest` for a held rename). + +## Review + +**Lead, 2026-11-19.** Accepted for 0.65.8, after two QA rounds. + +- The owner asked whether it was VS Code or the server. It was the server, + and it was not a race: an end-exclusive span met a caret VS Code considers + to be on the word. The investigation's deterministic reproduction + (`refpos.py`, column 27) settled that before any code was written, and + ruled out the things I would have guessed first — cancellation, deferred + answers, caching. +- B and C were found by other lanes' QA and are worse than the reported bug: + one corrupts the server's copy of a buffer, the other turns a 2 s startup + into minutes. Both come from treating queued messages as applied. I kept + them in this lane because they live in the same loop. +- I asked for P2 "only if small"; the dev's attempt cost 190 ms per open of + an outside file and QA caught it (806 s for 2 000 files). Reverted. The + right fix is in the index layer and is filed. +- The ordering rule was narrowed in the fix round from "no message overtakes + an older message" to "no notification overtakes an older notification". + That changes the invariant, so I sent it back to QA instead of accepting + the dev's own run. QA's harm table is what decides it: under the narrow + rule a held request behaves exactly as on 0.65.7; under the broad rule a + held rename was answered on the old text and would have corrupted the + client's newer one. Narrow is both faster and safer. +- Not verified: a real VS Code, in particular whether it drops a rename or + format result when the buffer changed while the request was held (QA-8 + rests on that for its "Info" grade). diff --git a/editors/vscode/CHANGELOG.md b/editors/vscode/CHANGELOG.md index 0b3ba13..d1440a5 100644 --- a/editors/vscode/CHANGELOG.md +++ b/editors/vscode/CHANGELOG.md @@ -5,6 +5,19 @@ for you. The extension and its bundled language server share one version number; the full engineering notes live in the [project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md). +## 0.65.8 — 2026-11-19 + +- **Find All References works with the cursor just after a name** — after a + double-click, or a click on the last letter. So do Go to Definition, hover, + highlight and rename. (It used to say "No references found" until you + clicked away and back.) Rows in the References view now open with the + cursor at the start of the name. +- **Typing while the workspace is indexing can no longer scramble the + server's view of your file** (wrong symbols and diagnostics until the file + was reopened). +- **Opening files during startup no longer stalls indexing** for minutes on + a large workspace. + ## 0.65.7 — 2026-11-19 - **0.65.6, now for every platform.** 0.65.6 was never published — it did not diff --git a/editors/vscode/README.md b/editors/vscode/README.md index d773cf4..4b5a1b6 100644 --- a/editors/vscode/README.md +++ b/editors/vscode/README.md @@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view, then open a Verilog or SystemVerilog file. There is no separate server or CLI setup. -The current release is **0.65.7**. Its platform packages include +The current release is **0.65.8**. Its platform packages include `lucisv-server`, the `lucisv` command-line tool and `lucisv-mcp` (see [Agents (MCP)](#agents-mcp)): @@ -440,6 +440,13 @@ default): } ``` +## Release 0.65.8 highlights + +Version 0.65.8 fixes Find All References (and definition, hover, rename) +answering "not found" when the cursor sits just after a name, keeps edits +typed during indexing in order, and removes a startup stall that could last +minutes on a large workspace. + ## Release 0.65.7 highlights Version 0.65.7 is 0.65.6 built for every platform (0.65.6 was never published: diff --git a/editors/vscode/package-lock.json b/editors/vscode/package-lock.json index 348644a..8929f91 100644 --- a/editors/vscode/package-lock.json +++ b/editors/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "lucisv", - "version": "0.65.7", + "version": "0.65.8", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "lucisv", - "version": "0.65.7", + "version": "0.65.8", "license": "MIT", "dependencies": { "vscode-languageclient": "9.0.1" diff --git a/editors/vscode/package.json b/editors/vscode/package.json index 843bee8..7ee8a5b 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -2,7 +2,7 @@ "name": "lucisv", "displayName": "lucisv — Verilog/SystemVerilog", "description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.", - "version": "0.65.7", + "version": "0.65.8", "publisher": "guoliangchen", "author": "Guoliang Chen", "license": "MIT", diff --git a/editors/vscode/referencesView.js b/editors/vscode/referencesView.js index 10b90c1..2a2c221 100644 --- a/editors/vscode/referencesView.js +++ b/editors/vscode/referencesView.js @@ -95,7 +95,7 @@ function fileItem(group) { return item; } -/** A reference's row: the whole line, the identifier highlighted; a click selects it in its file. */ +/** A reference's row: the whole line, the identifier highlighted; a click puts the caret on it in its file. */ function referenceItem(reference) { const label = reference.text === '' ? { label: `line ${reference.line}` } @@ -105,10 +105,15 @@ function referenceItem(reference) { item.description = reference.declaration ? `declaration · line ${reference.line}` : `line ${reference.line}`; if (reference.declaration) item.iconPath = new vscode.ThemeIcon('symbol-key'); item.tooltip = `${vscode.workspace.asRelativePath(uri)}:${reference.line}:${reference.character}`; + // The caret goes to the identifier's start, as VS Code's own references + // view and go to definition put it. `vscode.open` makes a range's *end* the + // caret (a selection's direction does not survive it), and a Find All + // References from just past a name used to ask about the next character. + const { line, character } = range.start; item.command = { command: 'vscode.open', title: 'Open Reference', - arguments: [uri, { selection: range, preserveFocus: false, preview: true }], + arguments: [uri, { selection: new vscode.Range(line, character, line, character), preserveFocus: false, preview: true }], }; return item; } diff --git a/editors/vscode/referencesView_test.js b/editors/vscode/referencesView_test.js index da40390..a72a5c0 100644 --- a/editors/vscode/referencesView_test.js +++ b/editors/vscode/referencesView_test.js @@ -181,7 +181,10 @@ async function theCommandFillsGroupsAndRevealsTheView() { assert.equal(topRows[0].command.command, 'vscode.open'); const [target, options] = topRows[0].command.arguments; assert.equal(target.toString(), 'file:///ws/top.sv'); - assert.deepEqual(options.selection, new Range(1, 27, 1, 28), 'a click selects exactly the identifier'); + // At the identifier's start, as VS Code's own references view and go to + // definition put it: `vscode.open` makes a range's *end* the caret, and a + // search started from there used to ask about the character after the name. + assert.deepEqual(options.selection, new Range(1, 27, 1, 27), 'a click puts the caret on the identifier'); const crlfRow = labels(view.getChildren(groups[2]))[0]; assert.deepEqual(crlfRow.label, { label: 'assign y = top.r;', highlights: [[15, 16]] }, 'tab and CRLF handled');