diff --git a/CHANGELOG.md b/CHANGELOG.md index f4e6721..2cd00f6 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.11 — 2026-11-19 + +### Actions on the open file no longer wait for the workspace + +(`docs/features/fast-actions`; TODO §71.2. Measured on OpenTitan's `hw` tree +and on generated 20 000- and 40 000-file trees, with the server driven the +way VS Code drives it.) + +- **Same-file answers come from the file.** A hover, a go-to-definition, a + type definition, highlights, a rename's first check or a signature help on + a name the file itself declares — and the outline, folding and selection + ranges — are answered from the open buffer at once, even while the index + is being built or rebuilt. Anything that might live in another file still + waits for the index it needs. + + | hover on a local name (4 000 / 20 000 / 40 000 files) | 0.65.10 | now | + |---|---:|---:| + | during the startup scan | 547 / 665 / 831 ms | 2.4 / 1.5 / 1.9 ms | + | a new file triggers a rescan, request 5 ms later | 1.2 / 6.0 / 12.3 s | 47 / 167 / 321 ms | + | the same, request read together with the event | 1.2 / 6.0 / 12.3 s | 0.3 / 0.1 / 0.1 ms | + | the same, server busy with a previous delete | 1.3 / 7.0 / 14.3 s | 0.17 / 0.99 / 2.2 s | + +- **Every early answer is the settled answer.** A request goes ahead only + when its buffer is open, every older message that could change the buffer + has been applied, its analysis is current, no settings are still on their + way, and the answer is the buffer's alone. 2.9 million early answers were + compared with the answer the finished index gives; none differed. +- **Completion keeps what the file can reach near the top.** Right after the + file's own names it now offers the members of the packages the file + imports, what its class inherits and the macros of the headers it + includes, so a huge workspace no longer pushes them out of the list; such + a name shows the icon and detail of the declaration the file actually + reaches. Completion answers are half the size for VS Code. +- **A new `lucisv.largeFile.threshold` applies to files already open,** the + editor's first settings answer included — not at each file's next edit. +- **Fixed on the way** (present since 0.65.8 and 0.65.10): the editor's + answer to a settings request could be applied ahead of an older settings + change or edit; colours answered while a file-watcher event was waiting + were not refreshed afterwards. +- **What it costs.** Until the editor has answered the server's first + settings request, same-file requests wait (the threshold may change how + the file is read): with an editor that takes 0.5 s to answer, the first + outline arrives after 515 ms — it was 1 043 ms on 0.65.10. +- **Still to come.** Not yet seen in a running editor by a human. + ## 0.65.10 — 2026-11-19 ### Highlighting no longer waits for the index diff --git a/Cargo.lock b/Cargo.lock index 555b99a..211fb91 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -97,7 +97,7 @@ dependencies = [ [[package]] name = "lucisv" -version = "0.65.10" +version = "0.65.11" dependencies = [ "lucisv_core", "rayon", @@ -108,11 +108,11 @@ dependencies = [ [[package]] name = "lucisv_core" -version = "0.65.10" +version = "0.65.11" [[package]] name = "lucisv_mcp" -version = "0.65.10" +version = "0.65.11" dependencies = [ "lucisv_core", "serde", @@ -126,7 +126,7 @@ dependencies = [ [[package]] name = "lucisv_server" -version = "0.65.10" +version = "0.65.11" dependencies = [ "lsp-server", "lsp-types", @@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] name = "vlog_formatter" -version = "0.65.10" +version = "0.65.11" dependencies = [ "vlog_parser", ] [[package]] name = "vlog_linter" -version = "0.65.10" +version = "0.65.11" dependencies = [ "lucisv_core", "vlog_formatter", @@ -279,11 +279,11 @@ dependencies = [ [[package]] name = "vlog_parser" -version = "0.65.10" +version = "0.65.11" [[package]] name = "vlog_refactor" -version = "0.65.10" +version = "0.65.11" dependencies = [ "vlog_formatter", "vlog_parser", @@ -292,7 +292,7 @@ dependencies = [ [[package]] name = "vlog_semantic" -version = "0.65.10" +version = "0.65.11" dependencies = [ "vlog_parser", ] diff --git a/Cargo.toml b/Cargo.toml index 824c76b..641a261 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ members = [ ] [workspace.package] -version = "0.65.10" +version = "0.65.11" authors = ["Guoliang Chen"] edition = "2021" license = "MIT" diff --git a/TODO.md b/TODO.md index 8d4e897..9fe10f3 100644 --- a/TODO.md +++ b/TODO.md @@ -7319,7 +7319,7 @@ subsection, plan and `docs/features//README.md` when its turn comes. Today every file edit re-indexes everything. A change to a `define` may have to; a typical, localized edit must not. -- [ ] **71.2 Actions stay fast on a huge, heavily-dependent tree.** Do the +- [x] **71.2 Actions stay fast on a huge, heavily-dependent tree.** (0.65.11, `docs/features/fast-actions`) Do the work dynamically: answer first from what is already in the same file (hover to a definition in this file), and use the relationship map to load completion candidates on demand. @@ -7482,3 +7482,19 @@ indexing, collide with each other and with §70's test files, and wait for costs one refresh at settle even when nothing changed. - [ ] An edit in one file that changes how another OPEN file colours sends no refresh (as before this lane). + +- Wave 8 (lead, 2026-11-19): 71.2 shipped as 0.65.11 after four dev rounds + and four QA rounds — two QA failures, so the last round ran with Fable 5.2 + as dev and QA (`docs/features/fast-actions`, Review). Left open from it: + - [ ] Inside the startup settings wait, the client's answer to the pull is + applied ahead of an older settings push held with it + (`server/startup.rs`, `take_the_answer_out_of_held`; predates the + lane; needs a client whose push and answer disagree in one burst). + - [ ] `tests/fast_actions_bursts.rs`'s oracle accepts an answer the + reference gives after any later message of the round: 2–9 % of + injected stale answers pass when a later message restores the state. + - [ ] Whether a large open buffer is in the index depends on when it was + opened, saved or scanned (predates the lane; 77–98 answers differ + between a settled session and a fresh server on OpenTitan). + - [ ] The 40 000-file rescan after a delete takes either 12.3 s or + 14.5–15.5 s, on 0.65.10 and on this tree alike; cause not found. diff --git a/crates/lucisv_server/src/candidates.rs b/crates/lucisv_server/src/candidates.rs index ab4071d..eb82eef 100644 --- a/crates/lucisv_server/src/candidates.rs +++ b/crates/lucisv_server/src/candidates.rs @@ -843,7 +843,7 @@ fn macros_of(index: &WorkspaceIndex) -> Vec { } /// One `` `define``'s completion entry. -fn macro_of(define: &vlog_parser::defines::Define) -> Macro { +pub(crate) fn macro_of(define: &vlog_parser::defines::Define) -> Macro { let args = match &define.params { Some(params) => format!("({})", params.join(", ")), None => String::new(), diff --git a/crates/lucisv_server/src/completion/mod.rs b/crates/lucisv_server/src/completion/mod.rs index 86accc2..e77b40b 100644 --- a/crates/lucisv_server/src/completion/mod.rs +++ b/crates/lucisv_server/src/completion/mod.rs @@ -79,6 +79,7 @@ use buffer::{buffer_word_tier, declared_tier}; use connection::Connection; use member::member_answer; use module::module_tier; +use related::{related_macros, related_tier}; use site::{at_module_item, at_statement, enclosing_scopes}; use tiers::{index_tier, keyword_tier, scope_tier, template_tier, word_tier}; use word::typed_word; @@ -90,6 +91,7 @@ pub(crate) use module::{nearest_definition, plan_for}; pub(crate) use module::module_header; pub(crate) use site::at_instantiation_site; pub(crate) use tiers::layout_at; +pub(crate) use wire::{item_defaults_support, with_item_defaults}; mod buffer; mod connection; @@ -97,8 +99,10 @@ mod connection; mod harness; mod member; mod module; +mod related; mod site; mod tiers; +mod wire; mod word; /// How many items one response carries, over every tier. @@ -151,10 +155,14 @@ const TIER_SCOPE: char = '1'; /// (`completion-ux`, TODO §68.1). const TIER_DECLARED: char = '2'; const TIER_BUFFER_WORD: char = '3'; -const TIER_INDEX: char = '4'; -const TIER_TEMPLATE: char = '5'; -const TIER_KEYWORD: char = '6'; -const TIER_WORD: char = '7'; +/// What the file is related to — the packages it imports, the classes its +/// class extends, the headers it includes — below the file itself and above +/// the rest of the workspace (`related.rs`). +const TIER_RELATED: char = '4'; +const TIER_INDEX: char = '5'; +const TIER_TEMPLATE: char = '6'; +const TIER_KEYWORD: char = '7'; +const TIER_WORD: char = '8'; /// What a multi-line item tells the client about its own whitespace. /// @@ -205,6 +213,7 @@ pub fn completions( // The backtick itself is replaced, so the item may carry its own. let replacing = TextRange::new(word.start.saturating_sub(1), offset); let mut items = Items::new(doc, replacing); + related_macros(&mut items, ws, doc, &word.text); for entry in ws.candidates().macros(&word.text) { items.simple( &format!("`{}", entry.name), @@ -243,6 +252,7 @@ pub fn completions( scope_tier(&mut items, doc, &word, fuzzy.as_ref()); declared_tier(&mut items, doc, &word, fuzzy.as_ref()); buffer_word_tier(&mut items, doc, &word, fuzzy.as_ref()); + related_tier(&mut items, ws, doc, &word, fuzzy.as_ref()); index_tier(&mut items, ws, &word, fuzzy.as_ref()); template_tier(&mut items, ws, doc, &word, snippets, at_item, at_statement); keyword_tier(&mut items, &word); @@ -273,6 +283,10 @@ struct Items { items: Vec, seen: HashSet, incomplete: bool, + /// How many of `items` the related tier added — which [`LIMIT`] does not + /// count, so every other tier fills exactly as far as it would without + /// them (`related.rs`). + related: usize, } impl Items { @@ -282,6 +296,7 @@ impl Items { items: Vec::new(), seen: HashSet::new(), incomplete: false, + related: 0, } } @@ -289,7 +304,7 @@ impl Items { /// only sets [`Items::incomplete`] — which is why the tiers ask first /// rather than building items nobody will see. fn full(&mut self) -> bool { - if self.items.len() >= LIMIT { + if self.items.len() - self.related >= LIMIT { self.incomplete = true; return true; } @@ -310,6 +325,14 @@ impl Items { if self.full() || self.seen.contains(name) { return; } + self.unlimited(name, kind, tier, detail); + } + + /// [`Items::simple`] past the cap: the caller has its own. + fn unlimited(&mut self, name: &str, kind: CompletionItemKind, tier: char, detail: String) { + if !self.seen.insert(name.to_string()) { + return; + } let item = CompletionItem { label: name.to_string(), kind: Some(kind), @@ -322,7 +345,7 @@ impl Items { })), ..Default::default() }; - self.push(item); + self.items.push(item); } /// A port or parameter after a connection list's `.`: the bare name, or diff --git a/crates/lucisv_server/src/completion/related.rs b/crates/lucisv_server/src/completion/related.rs new file mode 100644 index 0000000..b9711af --- /dev/null +++ b/crates/lucisv_server/src/completion/related.rs @@ -0,0 +1,341 @@ +//! The **related** tier: what this file is related to through the workspace +//! index, ranked above the rest of the workspace and below the file itself +//! (`docs/features/fast-actions/README.md`, completion through the +//! relationship map). +//! +//! The tier-5 table answers "every package member, typedef, class and module +//! the workspace declares whose name matches", alphabetically, until the +//! response is full — so in a workspace of tens of thousands of files the +//! members of the one package this file actually imports were cut off behind +//! names from files it has nothing to do with (measured: 46 of 47 matching +//! `aes_pkg` names offered at `ae` in 4 000 files, 11 of 47 in 40 000). What a +//! file is related to is known without reading anything: the packages its +//! scope chain imports, the classes its enclosing class extends, the headers +//! its `` `include``s reach. Those names come first. +//! +//! **No item is taken away.** A related item does not count against +//! [`LIMIT`](super::LIMIT): the tiers after it fill exactly as far as they +//! did before, and a name the related tier claimed is skipped by them +//! without being counted, so every label of the old answer is still offered, +//! with the same edit and format (the completion-equivalence test holds the +//! server to that). **What does change** for a name the related tier claims +//! is its icon and its detail: they now describe the declaration the file is +//! related to — the member of the package it imports, the macro of the header +//! it includes, the member of the class it extends — where the workspace tier +//! described the first declaration of that name in the whole workspace +//! (`NumRegs` of whichever register package sorts first; a module of the name +//! where the imported package declares a function). The tier has its own +//! cap, [`RELATED_LIMIT`], past which it says the answer is incomplete. + +use lsp_types::CompletionItemKind; +use vlog_parser::defines::DefineKind; +use vlog_semantic::{Def, ScopeKind, Semantics, SymbolKind}; + +use super::tiers::innermost_scope; +use super::word::Word; +use super::{completion_kind, Items, TIER_RELATED}; +use crate::candidates::{rank_cmp, starts_with_ignore_case, Query, Score}; +use crate::state::{Document, Workspace}; +use crate::symbols::kind_label; + +/// How many related names one response carries at most. +/// +/// A package of a few hundred members is the large case (`aes_pkg` has 259 +/// on its connection surface); at an empty prefix the related tier would +/// otherwise double a response that is already incomplete. +pub(super) const RELATED_LIMIT: usize = 256; + +/// One related name: what to show, and how it ranks. +struct Related { + name: String, + kind: SymbolKind, + detail: String, +} + +impl Items { + /// Add a related item, unless a higher tier already offered that name or + /// the tier is full. Not counted against [`LIMIT`](super::LIMIT). + fn related(&mut self, name: &str, kind: CompletionItemKind, detail: String) { + if self.seen.contains(name) { + return; + } + if self.related >= RELATED_LIMIT { + self.incomplete = true; + return; + } + self.related += 1; + self.unlimited(name, kind, TIER_RELATED, detail); + } +} + +/// The related tier for a name being typed: the members of every package +/// the scope chain at the cursor imports, and of the classes the enclosing +/// class extends. +pub(super) fn related_tier( + items: &mut Items, + ws: &Workspace, + doc: &Document, + word: &Word, + fuzzy: Option<&Query>, +) { + let mut found = imported(ws, &doc.semantics, word.start); + found.extend(inherited(ws, &doc.semantics, word.start)); + let mut matched: Vec<(Related, Option)> = found + .into_iter() + .filter_map(|related| match fuzzy { + None => starts_with_ignore_case(&related.name, &word.text).then_some((related, None)), + Some(query) => query.score(&related.name).map(|score| (related, Some(score))), + }) + .collect(); + matched.sort_by(|(a, sa), (b, sb)| match (sa, sb) { + (Some(sa), Some(sb)) => rank_cmp((&a.name, *sa), (&b.name, *sb)), + _ => a.name.cmp(&b.name), + }); + for (related, _) in matched { + items.related(&related.name, completion_kind(related.kind), related.detail); + } +} + +/// The related tier after a backtick: the macros the headers this buffer +/// reaches through its `` `include``s define, ahead of every other macro in +/// the workspace. +pub(super) fn related_macros(items: &mut Items, ws: &Workspace, doc: &Document, prefix: &str) { + let mut names: Vec<(String, String)> = Vec::new(); + for path in crate::includes::reachable_from(ws, doc) { + let Some(table) = ws.index().file_id(&path).and_then(|file| ws.index().defines(file)) + else { + continue; + }; + let defines = table.entries().iter().filter(|d| d.kind == DefineKind::Define); + for define in defines.filter(|d| starts_with_ignore_case(&d.name, prefix)) { + names.push((define.name.clone(), crate::candidates::macro_of(define).detail)); + } + } + names.sort(); + names.dedup_by(|a, b| a.0 == b.0); + for (name, detail) in names { + items.related(&format!("`{name}"), CompletionItemKind::CONSTANT, detail); + } +} + +/// Every member of every package imported by a scope enclosing `offset`, +/// innermost scope first, a wildcard bringing all of a package's members and +/// an explicit import the one it names. +fn imported(ws: &Workspace, semantics: &Semantics, offset: u32) -> Vec { + let mut out = Vec::new(); + let mut at = innermost_scope(semantics, offset).or(Some(semantics.file_scope())); + while let Some(id) = at { + let Some(scope) = semantics.scope(id) else { break }; + at = scope.parent; + for import in &scope.imports { + for (name, defs) in ws.index().members_of(&import.package) { + if import.item.as_deref().is_some_and(|item| item != name) { + continue; + } + let Some(def) = defs.first() else { continue }; + out.push(Related { + name: name.to_string(), + kind: def.kind, + detail: format!("{} — {}::{name}", kind_label(def.kind), import.package), + }); + } + } + } + out +} + +/// Every member the enclosing class inherits, as the index's member chain for +/// that class lists it — its own members included, which the scope tier has +/// already claimed — each named after the class that **declares** it, the +/// way the workspace tier names a member (`base_c::count`). +fn inherited(ws: &Workspace, semantics: &Semantics, offset: u32) -> Vec { + let mut at = innermost_scope(semantics, offset); + while let Some(id) = at { + let Some(scope) = semantics.scope(id) else { break }; + if scope.kind == ScopeKind::Class { + let Some(key) = semantics.member_key(id) else { return Vec::new() }; + let index = ws.index(); + return index + .members_of_chain(&key) + .into_iter() + .map(|(name, def)| { + let owner = declaring_class(ws, &key, name, def).unwrap_or(&key); + Related { + name: name.to_string(), + kind: def.kind, + detail: format!("{} — {owner}::{name}", kind_label(def.kind)), + } + }) + .collect(); + } + at = scope.parent; + } + Vec::new() +} + +/// Which class of `class`'s `extends` chain declares `def` as `name`: the +/// class itself, then its base, then that base's base — each hop the one +/// `vlog_semantic`'s `base_chain` takes, a recorded base or else the class a +/// typedef aliases (`typedef mid_c alias_t; class leaf_c extends alias_t;`). +/// `None` only for a chain the index cannot follow, and the caller then +/// names the class it started from. +fn declaring_class<'a>( + ws: &'a Workspace, + class: &'a str, + name: &str, + def: &Def, +) -> Option<&'a str> { + let index = ws.index(); + let mut hop = Some(class); + let mut seen: Vec<&str> = Vec::new(); + while let Some(unit) = hop.filter(|unit| !seen.contains(unit)) { + if index.members_of(unit).any(|(member, defs)| member == name && defs.first() == Some(def)) + { + return Some(unit); + } + seen.push(unit); + hop = index.base_of(unit).or_else(|| aliased_class(ws, unit)).map(last_segment); + } + None +} + +/// The class a typedef names, when `unit` is a typedef the index holds once — +/// the alias hop of `vlog_semantic`'s `base_chain` (`aliased_unit`), read +/// through the index's public tables. +fn aliased_class<'a>(ws: &'a Workspace, unit: &str) -> Option<&'a str> { + match ws.index().units(unit) { + [def] if def.kind == SymbolKind::Typedef => def.type_name.as_deref(), + _ => None, + } +} + +/// The last `::` segment of a possibly qualified class path — the name the +/// member and inheritance tables are keyed by. +fn last_segment(path: &str) -> &str { + path.rsplit("::").next().unwrap_or(path) +} + +#[cfg(test)] +mod tests { + use crate::completion::harness::*; + use crate::completion::*; + + /// A package the buffer imports, and one it does not, both holding names + /// that start alike. + fn two_packages(name: &str) -> Tree { + let tree = Tree::new(name); + tree.write( + "near.sv", + "package near_pkg;\n localparam int ZED_NEAR = 1;\n typedef logic zed_t;\nendpackage\n", + ); + tree.write("far.sv", "package far_pkg;\n localparam int ZED_FAR = 2;\nendpackage\n"); + tree + } + + #[test] + fn an_imported_packages_members_rank_above_the_rest_of_the_workspace() { + let top = "module top;\n import near_pkg::*;\n assign x = ze\nendmodule\n"; + let (_tree, ws, uri, position) = opened(two_packages("rel_import"), top, "= ze"); + let items = items(completions(&ws, &uri, position, true)); + let near = find(&items, "ZED_NEAR").expect("the imported member"); + let far = find(&items, "ZED_FAR").expect("the other package's member is still offered"); + assert_eq!(tier(near), TIER_RELATED); + assert_eq!(tier(far), TIER_INDEX); + assert!(near.sort_text < far.sort_text, "related above the workspace"); + assert_eq!(near.detail.as_deref(), Some("localparam — near_pkg::ZED_NEAR")); + assert_eq!(tier(find(&items, "zed_t").expect("the typedef")), TIER_RELATED); + } + + #[test] + fn an_explicit_import_relates_the_one_name_it_imports() { + let top = "module top;\n import near_pkg::zed_t;\n assign x = ze\nendmodule\n"; + let (_tree, ws, uri, position) = opened(two_packages("rel_explicit"), top, "= ze"); + let items = items(completions(&ws, &uri, position, true)); + // The binder makes an explicitly imported name a declaration of this + // scope, so it is offered by the scope tier, above even this one. + assert!(tier(find(&items, "zed_t").expect("imported")) <= TIER_RELATED); + assert_eq!(tier(find(&items, "ZED_NEAR").expect("still offered")), TIER_INDEX); + } + + #[test] + fn related_items_take_nothing_from_the_tiers_after_them() { + // More project names than the cap, and an import whose members all + // match too: the workspace tiers still fill the whole cap. + let tree = two_packages("rel_cap"); + let mut many = String::from("package many_pkg;\n"); + for i in 0..LIMIT + 40 { + many.push_str(&format!(" localparam int ZED_{i:04} = {i};\n")); + } + many.push_str("endpackage\n"); + tree.write("many.sv", &many); + let top = "module top;\n import near_pkg::*;\n assign x = ZE\nendmodule\n"; + let (_tree, ws, uri, position) = opened(tree, top, "= ZE"); + let Some(CompletionResponse::List(list)) = completions(&ws, &uri, position, true) else { + panic!("a list"); + }; + let related = list.items.iter().filter(|i| tier(i) == TIER_RELATED).count(); + assert_eq!(related, 2, "the two near_pkg names"); + assert_eq!(list.items.len() - related, LIMIT, "the cap counts the others only"); + assert!(list.is_incomplete); + } + + #[test] + fn a_class_relates_what_it_inherits() { + let tree = Tree::new("rel_class"); + tree.write( + "base.sv", + "class base_c;\n int zed_count;\n function void zed_reset();\n endfunction\nendclass\n", + ); + let top = "class derived_c extends base_c;\n function void go();\n ze\n endfunction\nendclass\n"; + let (_tree, ws, uri, position) = opened(tree, top, " ze"); + let items = items(completions(&ws, &uri, position, true)); + let count = find(&items, "zed_count").expect("inherited"); + assert_eq!(tier(count), TIER_RELATED); + assert_eq!(tier(find(&items, "zed_reset").expect("inherited")), TIER_RELATED); + // Named after the class that declares it, as the workspace tier + // names a member — not after the class that inherits it. + assert_eq!(count.detail.as_deref(), Some("variable — base_c::zed_count")); + } + + #[test] + fn a_backtick_ranks_what_the_included_headers_define_first() { + let tree = Tree::new("rel_macro"); + tree.write("near.svh", "`define ZED_NEAR 1\n"); + tree.write("far.svh", "`define ZED_FAR 2\n"); + let top = "`include \"near.svh\"\nmodule top;\n assign x = `ZE\nendmodule\n"; + let (_tree, ws, uri, position) = opened(tree, top, "`ZE"); + let items = items(completions(&ws, &uri, position, true)); + let near = find(&items, "`ZED_NEAR").expect("the included header's macro"); + let far = find(&items, "`ZED_FAR").expect("every other macro is still offered"); + assert_eq!(tier(near), TIER_RELATED); + assert!(near.sort_text < far.sort_text); + assert_eq!(near.detail.as_deref(), Some("`define ZED_NEAR"), "the detail tier 5 gives"); + } + + #[test] + fn a_member_two_classes_up_names_the_class_that_declares_it() { + let tree = Tree::new("rel_grand"); + tree.write("base.sv", "class root_c;\n int zed_deep;\nendclass\nclass mid_c extends root_c;\n int zed_mid;\nendclass\n"); + let top = + "class leaf_c extends mid_c;\n function void go();\n ze\n endfunction\nendclass\n"; + let (_tree, ws, uri, position) = opened(tree, top, " ze"); + let items = items(completions(&ws, &uri, position, true)); + let detail = |label: &str| find(&items, label).and_then(|i| i.detail.clone()); + assert_eq!(detail("zed_deep").as_deref(), Some("variable — root_c::zed_deep")); + assert_eq!(detail("zed_mid").as_deref(), Some("variable — mid_c::zed_mid")); + } + + #[test] + fn a_member_reached_through_a_typedef_alias_names_the_class_that_declares_it() { + // QA R2: `leaf_c extends alias_t`, and `alias_t` is a typedef of + // `mid_c` — the member is `mid_c`'s. + let tree = Tree::new("rel_alias"); + tree.write("base.sv", "class mid_c;\n int zed_mid;\nendclass\ntypedef mid_c alias_t;\n"); + let top = "class leaf_c extends alias_t;\n function void go();\n ze\n endfunction\nendclass\n"; + let (_tree, ws, uri, position) = opened(tree, top, " ze"); + let items = items(completions(&ws, &uri, position, true)); + let mid = find(&items, "zed_mid").expect("inherited through the alias"); + assert_eq!(tier(mid), TIER_RELATED); + assert_eq!(mid.detail.as_deref(), Some("variable — mid_c::zed_mid")); + } +} diff --git a/crates/lucisv_server/src/completion/wire.rs b/crates/lucisv_server/src/completion/wire.rs new file mode 100644 index 0000000..7f51f6b --- /dev/null +++ b/crates/lucisv_server/src/completion/wire.rs @@ -0,0 +1,148 @@ +//! What a completion answer costs on the wire, for a client that can take +//! less (`docs/features/fast-actions/README.md`, "payload"). +//! +//! Every item of one answer replaces the same range, and almost every item +//! inserts its own label as plain text — so the `textEdit` each one carries +//! (49 % of a 130 KB answer, measured) and its `insertTextFormat` (8 %) say +//! the same thing five hundred times. LSP 3.17's `CompletionList.itemDefaults` +//! says it once: an item with no `textEdit` replaces `editRange` with its +//! `textEditText`, or with its label when it has none, in +//! `insertTextFormat`. `vscode-languageclient` 9 applies exactly that rule +//! (`protocolConverter.asCompletionInsertText`), and advertises both defaults. +//! +//! **The same edits, fewer bytes.** The rewrite is lossless by construction: +//! an item keeps its own `textEdit` unless its range *is* the default, keeps +//! its own format unless it *is* the default, and moves a `newText` that is +//! not its label into `textEditText`. Done on the serialized answer because +//! `lsp-types` 0.97 has neither field. + +use lsp_types::InitializeParams; +use serde_json::{Map, Value}; + +/// `insertTextFormat: PlainText`, the format nearly every item has. +const PLAIN_TEXT: u64 = 1; + +/// Whether the client applies `itemDefaults.editRange` and +/// `itemDefaults.insertTextFormat` — `textDocument.completion.completionList +/// .itemDefaults` listing both. A client that said nothing gets every item +/// whole, which is what every client got before this was read. +pub(crate) fn item_defaults_support(params: &InitializeParams) -> bool { + let listed = params + .capabilities + .text_document + .as_ref() + .and_then(|text_document| text_document.completion.as_ref()) + .and_then(|completion| completion.completion_list.as_ref()) + .and_then(|list| list.item_defaults.as_ref()); + listed.is_some_and(|names| { + ["editRange", "insertTextFormat"].iter().all(|wanted| names.iter().any(|n| n == wanted)) + }) +} + +/// Rewrite a serialized `CompletionList` so the range and the format every +/// item shares are said once, in `itemDefaults`. Anything that is not a list +/// with items comes back as it was. +pub(crate) fn with_item_defaults(mut answer: Value) -> Value { + let Some(list) = answer.as_object_mut() else { return answer }; + let Some(Value::Array(items)) = list.get_mut("items") else { return answer }; + let Some(range) = items.first().and_then(edit_range).cloned() else { return answer }; + for item in items.iter_mut().filter_map(Value::as_object_mut) { + lift_edit(item, &range); + if item.get("insertTextFormat").and_then(Value::as_u64) == Some(PLAIN_TEXT) { + item.remove("insertTextFormat"); + } + } + let mut defaults = Map::new(); + defaults.insert("editRange".to_string(), range); + defaults.insert("insertTextFormat".to_string(), Value::from(PLAIN_TEXT)); + list.insert("itemDefaults".to_string(), Value::Object(defaults)); + answer +} + +/// The range a plain `textEdit` replaces, if the item has one. +fn edit_range(item: &Value) -> Option<&Value> { + let edit = item.get("textEdit")?; + edit.get("newText")?; + edit.get("range") +} + +/// Drop `item`'s `textEdit` when it replaces `range`, keeping its text in +/// `textEditText` unless that text is the label. +fn lift_edit(item: &mut Map, range: &Value) { + let Some(edit) = item.get("textEdit") else { return }; + if edit.get("range") != Some(range) { + return; + } + let Some(Value::Object(mut edit)) = item.remove("textEdit") else { return }; + let new_text = edit.remove("newText").unwrap_or(Value::Null); + if item.get("label") != Some(&new_text) { + item.insert("textEditText".to_string(), new_text); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn range(line: u32) -> Value { + json!({ "start": { "line": line, "character": 4 }, "end": { "line": line, "character": 6 } }) + } + + /// The edit an item makes under the LSP 3.17 rule, defaults applied. + fn effective(item: &Value, defaults: &Value) -> (Value, Value, Value) { + let format = item.get("insertTextFormat").unwrap_or(&defaults["insertTextFormat"]).clone(); + match item.get("textEdit") { + Some(edit) => (edit["range"].clone(), edit["newText"].clone(), format), + None => ( + defaults["editRange"].clone(), + item.get("textEditText").unwrap_or(&item["label"]).clone(), + format, + ), + } + } + + #[test] + fn every_item_makes_the_same_edit_with_the_defaults_applied() { + let before = json!({ "isIncomplete": true, "items": [ + { "label": "sig", "insertTextFormat": 1, + "textEdit": { "range": range(2), "newText": "sig" } }, + { "label": "if begin/end", "insertTextFormat": 2, + "textEdit": { "range": range(2), "newText": "if (${1:cond}) begin\n$0\nend" } }, + { "label": "`W", "insertTextFormat": 1, + "textEdit": { "range": range(2), "newText": "`W" } }, + { "label": "odd", "insertTextFormat": 1, + "textEdit": { "range": range(7), "newText": "odd" } }, + ]}); + let after = with_item_defaults(before.clone()); + let defaults = &after["itemDefaults"]; + assert_eq!(defaults["editRange"], range(2)); + for (old, new) in + before["items"].as_array().unwrap().iter().zip(after["items"].as_array().unwrap()) + { + let old_effect = ( + old["textEdit"]["range"].clone(), + old["textEdit"]["newText"].clone(), + old["insertTextFormat"].clone(), + ); + assert_eq!(effective(new, defaults), old_effect, "{new}"); + } + assert!(after["items"][0].get("textEdit").is_none(), "the label is the text"); + assert!(after["items"][0].get("textEditText").is_none()); + assert_eq!(after["items"][1]["textEditText"], before["items"][1]["textEdit"]["newText"]); + assert!(after["items"][3].get("textEdit").is_some(), "another range keeps its edit"); + assert!(after.to_string().len() < before.to_string().len()); + } + + #[test] + fn an_answer_that_is_not_a_list_of_edits_is_left_alone() { + for answer in [ + Value::Null, + json!([]), + json!({ "isIncomplete": false, "items": [] }), + json!({ "items": [{ "label": "x", "insertText": "x" }] }), + ] { + assert_eq!(with_item_defaults(answer.clone()), answer); + } + } +} diff --git a/crates/lucisv_server/src/includes.rs b/crates/lucisv_server/src/includes.rs index 29cefc7..c9e3b61 100644 --- a/crates/lucisv_server/src/includes.rs +++ b/crates/lucisv_server/src/includes.rs @@ -578,15 +578,21 @@ pub fn document_links(ws: &Workspace, uri: &Uri) -> Vec { /// The same computation the links use, so F12 and ctrl-click can never /// disagree about where a line goes. pub fn definition(ws: &Workspace, doc: &Document, offset: u32) -> Option { + let include = include_at(doc, offset)?; + let path = ws.includes().resolve(doc.path.as_deref(), &include)?; + Some(Location { uri: path_to_uri(&path)?, range: Range::default() }) +} + +/// The `` `include`` whose directive covers `offset`, read off the buffer's +/// own line — the one question go-to-definition asks before any other, and +/// the one `same_file` asks to know that the answer is a path to resolve. +pub(crate) fn include_at(doc: &Document, offset: u32) -> Option { // Definition is a cursor request, so inspect only its line. `documentLink` // still scans the whole file because it must return every include. let (line, _) = doc.line_index.line_col(offset); let line = doc.line_index.line_range(line)?; let text = doc.text.get(line.as_range())?; - let include = - include_on_line(text, line.start).filter(|include| include.span.contains(offset))?; - let path = ws.includes().resolve(doc.path.as_deref(), &include)?; - Some(Location { uri: path_to_uri(&path)?, range: Range::default() }) + include_on_line(text, line.start).filter(|include| include.span.contains(offset)) } /// Every file this buffer reaches through `` `include``, transitively. diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index 9cb9dae..6a524c7 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -45,6 +45,7 @@ mod perf; mod ports; mod rename; mod rename_trace; +mod same_file; mod scan_order; mod scan_trace; mod selection; @@ -144,6 +145,7 @@ fn main() -> Result<(), Box> { hierarchy_view, code_action_resolve: code_action_resolve_support(¶ms), create_files: create_files_support(¶ms), + completion_item_defaults: completion::item_defaults_support(¶ms), }; connection.initialize_finish(id, initialize_value(ranges_formatting)?)?; diff --git a/crates/lucisv_server/src/same_file.rs b/crates/lucisv_server/src/same_file.rs new file mode 100644 index 0000000..30dd7ae --- /dev/null +++ b/crates/lucisv_server/src/same_file.rs @@ -0,0 +1,195 @@ +//! Same file first: whether a request's **whole** answer comes from its own +//! buffer, so that it need not wait for the workspace index +//! (`docs/features/fast-actions/README.md`). +//! +//! The server answers a request so decided from the buffer while a scan holds +//! everything else (`server/ahead.rs`). The answer is then the one the settled +//! server gives, by construction: this file says yes only where the handler +//! the dispatch runs reads nothing but the buffer's own analysis — its text, +//! tokens, tree, `Semantics` and `` `define`` table, all of which are a +//! function of the text alone (`Document::new`: "the single-file analysis is +//! unaffected by other files"). The two things a buffer holds that are **not** +//! its text's are the workspace overlay (`ExternalResolutions`) and every +//! table behind `Workspace::index`; a yes here is a proof that the handler's +//! path for this position reaches neither. +//! +//! **The locality rule**, the one question under most answers here: is the +//! name under the cursor bound by this file? A *use* is when the single-file +//! binder resolved it (`Reference::resolved`); an unresolved use is the +//! overlay's to answer, and so is not. A cursor on a *declaration* or on no +//! name at all is answered from the buffer alone. Three shapes look local and +//! are not, each answered by waiting: +//! +//! * a use the binder left to the workspace — a name a wildcard `import` +//! brings in, a package-qualified name, an instantiated module, an inherited +//! class member (even one declared in this very file: the class hierarchy +//! that finds it is the index's), a hierarchical path; +//! * a macro use with no `` `define`` in this buffer — the header that defines +//! it is found through the include graph and the index; +//! * an `` `include`` line — its path is resolved against the include +//! directories and the files the scan has found. +//! +//! A local binding that the language would let an import shadow is **not** in +//! that list, deliberately: the dispatch's own answer is the local binding too +//! (`ExternalResolutions::definition_of` asks the binder first), so the early +//! answer is the settled answer — the contract here is "the same answer", +//! which is the only one a differential test can hold the server to. + +use lsp_types::request::{ + DocumentHighlightRequest, DocumentSymbolRequest, FoldingRangeRequest, GotoDefinition, + GotoTypeDefinition, HoverRequest, LinkedEditingRange, PrepareRenameRequest, References, + Request as _, SelectionRangeRequest, SignatureHelpRequest, +}; +use lsp_types::Position; +use serde_json::Value; + +use crate::state::Document; +use crate::{caret, hover, includes, nav, pairs, signature, type_def}; + +#[cfg(test)] +mod tests; + +/// The requests this file can ever say yes to. Everything else — completion, +/// inlay hints, code lenses, document links, the workspace-wide requests — +/// reads the index on every path and always waits. +pub(crate) const METHODS: [&str; 12] = [ + DocumentSymbolRequest::METHOD, + FoldingRangeRequest::METHOD, + SelectionRangeRequest::METHOD, + LinkedEditingRange::METHOD, + pairs::SCOPE_PAIRS_METHOD, + HoverRequest::METHOD, + GotoDefinition::METHOD, + GotoTypeDefinition::METHOD, + DocumentHighlightRequest::METHOD, + References::METHOD, + PrepareRenameRequest::METHOD, + SignatureHelpRequest::METHOD, +]; + +/// Whether the dispatch's answer to `method` with `params` reads nothing but +/// `doc`, the buffer the request names — see the module documentation. +/// +/// A dispatch table over the methods above, each arm the mirror of the path +/// its handler takes; an arm says yes only where every branch that handler +/// can take from this position is a branch over the buffer. +pub(crate) fn answered_by_the_buffer(doc: &Document, method: &str, params: &Value) -> bool { + match method { + // Whole-buffer answers: each handler takes the `Document` and nothing + // else (`symbols::document_symbols`, `folding::folding_ranges`, + // `selection::selection_ranges`, `linked::linked_editing_ranges`, + // `pairs::scope_pairs`). + DocumentSymbolRequest::METHOD + | FoldingRangeRequest::METHOD + | SelectionRangeRequest::METHOD + | LinkedEditingRange::METHOD + | pairs::SCOPE_PAIRS_METHOD => true, + HoverRequest::METHOD => at_name(doc, params).is_some_and(|at| bound_here(doc, at)), + GotoDefinition::METHOD => at_name(doc, params).is_some_and(|at| defined_here(doc, at)), + GotoTypeDefinition::METHOD => at_name(doc, params).is_some_and(|at| { + // The type name is found in the buffer; the jump is then exactly + // a go-to-definition from it (`type_def::type_definition`). + type_def::type_name(doc, at).is_none_or(|span| defined_here(doc, span.start)) + }), + DocumentHighlightRequest::METHOD => { + at_name(doc, params).is_some_and(|at| highlighted_here(doc, at)) + } + References::METHOD => at_name(doc, params).is_some_and(|at| cannot_leave(doc, at)), + PrepareRenameRequest::METHOD => { + at_name(doc, params).is_some_and(|at| renamed_here(doc, at)) + } + // Only outside an instantiation's lists: inside one, the signature is + // the instantiated module's, read from its file. + SignatureHelpRequest::METHOD => at_caret(doc, params) + .is_some_and(|at| signature::enclosing_list(&doc.tokens, at).is_none()), + _ => false, + } +} + +/// The byte offset the request's `position` names, as sent. +fn at_caret(doc: &Document, params: &Value) -> Option { + let position: Position = serde_json::from_value(params.get("position")?.clone()).ok()?; + Some(doc.positions().offset(position)) +} + +/// [`at_caret`] with the caret rule the dispatch applies to a request about +/// the name under the cursor ([`caret::symbol_offset`]). +fn at_name(doc: &Document, params: &Value) -> Option { + at_caret(doc, params).map(|offset| caret::symbol_offset(&doc.text, offset)) +} + +/// The locality rule: whether whatever is at `offset` — a macro use, a use +/// of a name, a declaration, or nothing — is answered from this buffer. +/// +/// Mirrors `hover::hover`: a macro use with a `` `define`` here is answered +/// by it, one without is the workspace's; a use is this file's exactly when +/// the binder resolved it; a declaration, or no name at all, reads nothing +/// else. +fn bound_here(doc: &Document, offset: u32) -> bool { + if let Some(name) = doc.token_at(offset).filter(|t| t.is_macro()).and_then(hover::macro_name) { + return doc.defines.latest(name).is_some(); + } + doc.semantics.reference_at(offset).is_none_or(|use_| use_.resolved().is_some()) +} + +/// [`bound_here`] for `nav::definition`, which asks one question first: an +/// `` `include`` line is a path to resolve, never a name. +fn defined_here(doc: &Document, offset: u32) -> bool { + includes::include_at(doc, offset).is_none() && bound_here(doc, offset) +} + +/// Mirrors the highlight handler: a scope keyword pairs with its closer, a +/// name this file binds lights its own occurrences, a cursor on no use lights +/// nothing — and only an unresolved use asks the overlay +/// (`nav::document_highlights`). +fn highlighted_here(doc: &Document, offset: u32) -> bool { + nav::symbol_at(&doc.semantics, offset).is_some() + || doc.semantics.reference_id_at(offset).is_none() + || pairs::highlights(doc, offset).is_some() +} + +/// Whether find-references here is the in-file answer whatever the index +/// holds — a sufficient condition for `nav::references` never asking it. +/// +/// `leaves_this_file` reads the index, so it cannot be asked early; what can +/// be read off the buffer is that its answer cannot matter. An `untitled:` +/// buffer is never looked up; a cursor on nothing is answered `[]`; and a +/// name this file binds in a scope with no **member key** (an unnamed block, +/// say) and not at file scope is one the index has no record of, so +/// `indexed_def_in_file` finds none and the in-file answer stands. A +/// module-level signal, a port, a function's local — each has a key a +/// hierarchical path or a connection could reach it by, and waits. +fn cannot_leave(doc: &Document, offset: u32) -> bool { + if doc.path.is_none() { + return true; + } + if doc.semantics.reference_at(offset).is_some_and(|use_| use_.resolved().is_none()) { + return false; + } + let Some(symbol) = + nav::symbol_at(&doc.semantics, offset).and_then(|id| doc.semantics.symbol(id)) + else { + return true; + }; + symbol.scope != doc.semantics.file_scope() && doc.semantics.member_key(symbol.scope).is_none() +} + +/// Mirrors `vlog_refactor::prepare_rename_here`: a declaration, or a use the +/// binder resolved, is judged on the buffer — except at file scope, where a +/// second unit of the same name in the index makes it ambiguous. Any use the +/// binder did not resolve waits, which keeps the refusals' wording the +/// settled server's. +fn renamed_here(doc: &Document, offset: u32) -> bool { + if doc.path.is_none() { + return true; + } + let declared = match doc.semantics.reference_at(offset) { + Some(use_) => use_.resolved(), + None => doc.semantics.symbol_at(offset), + }; + let Some(symbol) = declared.and_then(|id| doc.semantics.symbol(id)) else { + // An unresolved use waits; a cursor on nothing is refused alike. + return doc.semantics.reference_at(offset).is_none(); + }; + symbol.scope != doc.semantics.file_scope() +} diff --git a/crates/lucisv_server/src/same_file/tests.rs b/crates/lucisv_server/src/same_file/tests.rs new file mode 100644 index 0000000..c5f942a --- /dev/null +++ b/crates/lucisv_server/src/same_file/tests.rs @@ -0,0 +1,252 @@ +//! The locality rule, shape by shape: each test is one position a user can +//! put the cursor on, and whether the buffer alone answers it. The proof that +//! a yes is the settled answer is the differential test +//! (`server/tests/fast_actions_differential.rs`); these pin the rule. + +use std::str::FromStr; + +use lsp_types::request::{ + Completion, DocumentHighlightRequest, DocumentSymbolRequest, FoldingRangeRequest, + GotoDefinition, GotoTypeDefinition, HoverRequest, InlayHintRequest, PrepareRenameRequest, + References, SignatureHelpRequest, +}; +use lsp_types::Uri; +use serde_json::{json, Value}; + +use super::*; +use crate::state::Workspace; + +/// A workspace holding one buffer and an empty index — the cold start, and +/// the only thing a rule here may read. +fn buffer(text: &str) -> Workspace { + let mut ws = Workspace::default(); + ws.set_document(uri(), text.to_string()); + ws +} + +fn uri() -> Uri { + Uri::from_str("file:///rtl/m.sv").expect("uri") +} + +/// The request params with the cursor at the start of the `nth` occurrence +/// of `needle`, plus `skip` bytes. +fn at(ws: &Workspace, needle: &str, skip: usize) -> Value { + let doc = ws.document(&uri()).expect("open"); + let offset = doc.text.find(needle).expect("needle") + skip; + let position = doc.positions().position(offset as u32); + json!({ "textDocument": { "uri": uri() }, "position": position, + "context": { "includeDeclaration": true } }) +} + +fn local(ws: &Workspace, method: &str, params: &Value) -> bool { + answered_by_the_buffer(ws.document(&uri()).expect("open"), method, params) +} + +const WITH_IMPORT: &str = "module m;\n import p::*;\n logic sig;\n state_t st;\n \ + assign sig = st == IDLE;\n sub u_sub (.a(sig));\n always_comb begin\n \ + logic tmp;\n tmp = sig;\n end\nendmodule\n"; + +#[test] +fn a_use_the_binder_resolved_is_local_for_hover_definition_and_highlight() { + let ws = buffer(WITH_IMPORT); + let params = at(&ws, "sig = st", 0); + for method in [HoverRequest::METHOD, GotoDefinition::METHOD, DocumentHighlightRequest::METHOD] { + assert!(local(&ws, method, ¶ms), "{method}"); + } +} + +#[test] +fn a_name_a_wildcard_import_brings_in_waits() { + let ws = buffer(WITH_IMPORT); + let params = at(&ws, "IDLE", 0); + for method in [HoverRequest::METHOD, GotoDefinition::METHOD, DocumentHighlightRequest::METHOD] { + assert!(!local(&ws, method, ¶ms), "{method}: the import's package answers"); + } +} + +#[test] +fn an_instantiated_module_and_its_port_wait() { + let ws = buffer(WITH_IMPORT); + assert!(!local(&ws, HoverRequest::METHOD, &at(&ws, "sub u_sub", 0))); + assert!(!local(&ws, GotoDefinition::METHOD, &at(&ws, ".a(sig)", 1))); +} + +#[test] +fn a_declaration_and_a_cursor_on_no_name_are_local() { + let ws = buffer(WITH_IMPORT); + assert!(local(&ws, HoverRequest::METHOD, &at(&ws, "sig;", 0)), "a declaration"); + assert!(local(&ws, HoverRequest::METHOD, &at(&ws, "always_comb", 2)), "a keyword"); + assert!(local(&ws, GotoDefinition::METHOD, &at(&ws, " logic sig", 0)), "whitespace"); +} + +#[test] +fn a_type_definition_follows_the_type_the_declaration_writes() { + // `st` is declared with a type the import brings in; `tmp` with a + // built-in one, which has no definition to jump to anywhere. + let ws = buffer(WITH_IMPORT); + assert!(!local(&ws, GotoTypeDefinition::METHOD, &at(&ws, "st;", 0))); + assert!(local(&ws, GotoTypeDefinition::METHOD, &at(&ws, "tmp;", 0))); + let typed = buffer("module m;\n typedef logic [3:0] nib_t;\n nib_t n;\nendmodule\n"); + assert!(local(&typed, GotoTypeDefinition::METHOD, &at(&typed, "n;", 0)), "a local typedef"); +} + +#[test] +fn a_macro_is_local_only_where_this_buffer_defines_it() { + let text = "`define HERE 1\nmodule m;\n logic a = `HERE;\n logic b = `THERE;\nendmodule\n"; + let ws = buffer(text); + for method in [HoverRequest::METHOD, GotoDefinition::METHOD] { + assert!(local(&ws, method, &at(&ws, "`HERE;", 1)), "{method}"); + assert!(!local(&ws, method, &at(&ws, "`THERE", 1)), "{method}: a header defines it"); + } +} + +#[test] +fn an_include_line_is_a_path_for_definition_and_nothing_for_hover() { + let ws = buffer("`include \"defs.svh\"\nmodule m;\nendmodule\n"); + let params = at(&ws, "defs", 0); + assert!(!local(&ws, GotoDefinition::METHOD, ¶ms), "resolved against the scan"); + assert!(local(&ws, HoverRequest::METHOD, ¶ms), "no name, no macro: `null` either way"); +} + +#[test] +fn references_go_ahead_only_where_nothing_can_reach_the_name() { + let ws = buffer(WITH_IMPORT); + // A module-level signal is reachable as `u_m.sig` from anywhere. + assert!(!local(&ws, References::METHOD, &at(&ws, "sig;", 0))); + // A declaration in an unnamed block has no member key at all. + assert!(local(&ws, References::METHOD, &at(&ws, "tmp = sig", 0))); + assert!(!local(&ws, References::METHOD, &at(&ws, "IDLE", 0)), "an unresolved use"); + assert!(local(&ws, References::METHOD, &at(&ws, "assign", 1)), "nothing here"); +} + +#[test] +fn an_untitled_buffer_never_leaves_itself() { + let mut ws = Workspace::default(); + let untitled = Uri::from_str("untitled:Untitled-1").expect("uri"); + ws.set_document(untitled.clone(), "module m;\n logic sig;\nendmodule\n".to_string()); + let doc = ws.document(&untitled).expect("open"); + let position = doc.positions().position(doc.text.find("sig").expect("needle") as u32); + let params = json!({ "textDocument": { "uri": untitled }, "position": position }); + assert!(answered_by_the_buffer(doc, References::METHOD, ¶ms)); + assert!(answered_by_the_buffer(doc, PrepareRenameRequest::METHOD, ¶ms)); +} + +#[test] +fn prepare_rename_waits_at_file_scope_and_on_an_unresolved_use() { + let ws = buffer(WITH_IMPORT); + assert!(!local(&ws, PrepareRenameRequest::METHOD, &at(&ws, "m;", 0)), "a unit name"); + assert!(local(&ws, PrepareRenameRequest::METHOD, &at(&ws, "sig;", 0))); + assert!(local(&ws, PrepareRenameRequest::METHOD, &at(&ws, "sig = st", 0))); + assert!(!local(&ws, PrepareRenameRequest::METHOD, &at(&ws, "IDLE", 0))); +} + +#[test] +fn signature_help_waits_only_inside_an_instantiation() { + let ws = buffer(WITH_IMPORT); + assert!(!local(&ws, SignatureHelpRequest::METHOD, &at(&ws, "sig));", 0))); + assert!(local(&ws, SignatureHelpRequest::METHOD, &at(&ws, "st == IDLE", 0))); +} + +#[test] +fn whole_buffer_requests_always_go_and_index_requests_never_do() { + let ws = buffer(WITH_IMPORT); + let params = at(&ws, "sig", 0); + assert!(local(&ws, DocumentSymbolRequest::METHOD, ¶ms)); + assert!(local(&ws, FoldingRangeRequest::METHOD, ¶ms)); + for method in [Completion::METHOD, InlayHintRequest::METHOD, "textDocument/codeLens"] { + assert!(!local(&ws, method, ¶ms), "{method} reads the index"); + assert!(!METHODS.contains(&method)); + } +} + +#[test] +fn a_position_the_request_does_not_carry_is_not_guessed_at() { + let ws = buffer(WITH_IMPORT); + let params = json!({ "textDocument": { "uri": uri() } }); + assert!(!local(&ws, HoverRequest::METHOD, ¶ms)); +} + +/// The method an arm of the dispatch table answers, by the text of its +/// pattern. A pattern this does not know is a new arm: write its row in the +/// README's per-request table, then add it here. +fn method_of(arm: &str) -> &'static str { + use lsp_types::request::*; + match arm { + "Formatting::METHOD" => Formatting::METHOD, + "RangeFormatting::METHOD" => RangeFormatting::METHOD, + "format::RANGES_FORMATTING" => crate::format::RANGES_FORMATTING, + "OnTypeFormatting::METHOD" => OnTypeFormatting::METHOD, + "WillSaveWaitUntil::METHOD" => WillSaveWaitUntil::METHOD, + "HoverRequest::METHOD" => HoverRequest::METHOD, + "GotoDefinition::METHOD" => GotoDefinition::METHOD, + "GotoTypeDefinition::METHOD" => GotoTypeDefinition::METHOD, + "LinkedEditingRange::METHOD" => LinkedEditingRange::METHOD, + "DocumentLinkRequest::METHOD" => DocumentLinkRequest::METHOD, + "References::METHOD" => References::METHOD, + "DocumentHighlightRequest::METHOD" => DocumentHighlightRequest::METHOD, + "FoldingRangeRequest::METHOD" => FoldingRangeRequest::METHOD, + "InlayHintRequest::METHOD" => InlayHintRequest::METHOD, + "SemanticTokensFullRequest::METHOD" => SemanticTokensFullRequest::METHOD, + "SemanticTokensFullDeltaRequest::METHOD" => SemanticTokensFullDeltaRequest::METHOD, + "SemanticTokensRangeRequest::METHOD" => SemanticTokensRangeRequest::METHOD, + "DocumentSymbolRequest::METHOD" => DocumentSymbolRequest::METHOD, + "CodeActionRequest::METHOD" => CodeActionRequest::METHOD, + "CodeActionResolveRequest::METHOD" => CodeActionResolveRequest::METHOD, + "pairs::SCOPE_PAIRS_METHOD" => pairs::SCOPE_PAIRS_METHOD, + "design_hierarchy::METHOD" => crate::design_hierarchy::METHOD, + "PrepareRenameRequest::METHOD" => PrepareRenameRequest::METHOD, + "Rename::METHOD" => Rename::METHOD, + "CodeLensRequest::METHOD" => CodeLensRequest::METHOD, + "ExecuteCommand::METHOD" => ExecuteCommand::METHOD, + "DocumentDiagnosticRequest::METHOD" => DocumentDiagnosticRequest::METHOD, + "WorkspaceDiagnosticRequest::METHOD" => WorkspaceDiagnosticRequest::METHOD, + "SelectionRangeRequest::METHOD" => SelectionRangeRequest::METHOD, + "Completion::METHOD" => Completion::METHOD, + "InlineCompletionRequest::METHOD" => InlineCompletionRequest::METHOD, + "SignatureHelpRequest::METHOD" => SignatureHelpRequest::METHOD, + "CallHierarchyPrepare::METHOD" => CallHierarchyPrepare::METHOD, + "CallHierarchyIncomingCalls::METHOD" => CallHierarchyIncomingCalls::METHOD, + "CallHierarchyOutgoingCalls::METHOD" => CallHierarchyOutgoingCalls::METHOD, + "TypeHierarchyPrepare::METHOD" => TypeHierarchyPrepare::METHOD, + "TypeHierarchySupertypes::METHOD" => TypeHierarchySupertypes::METHOD, + "TypeHierarchySubtypes::METHOD" => TypeHierarchySubtypes::METHOD, + "WillRenameFiles::METHOD" => WillRenameFiles::METHOD, + "WorkspaceSymbolRequest::METHOD" => WorkspaceSymbolRequest::METHOD, + other => panic!("a new dispatch arm `{other}`: give it a row in the README table"), + } +} + +/// QA Q3 and R3: the README's per-request table names exactly the requests +/// the dispatch answers — no row missing, no row stale. Read off the +/// dispatch's own source and off the table's first column, compared as sets. +#[test] +fn the_readme_table_names_every_request_the_dispatch_answers() { + use std::collections::BTreeSet; + let dispatch = include_str!("../server/dispatch.rs"); + let readme = include_str!("../../../../docs/features/fast-actions/README.md"); + let start = readme.find("## The rule per request").expect("the table's section"); + // Up to the next heading: the sections after it have tables of their own. + let section = &readme[start..start + readme[start..].find("\n## ").expect("end")]; + let answered: BTreeSet<&str> = dispatch + .lines() + .filter_map(|line| { + let (pattern, _) = line.trim().split_once(" =>")?; + (pattern.ends_with("METHOD") || pattern.ends_with("RANGES_FORMATTING")) + .then_some(pattern) + }) + .map(method_of) + .collect(); + // The first cell of every row below the header: each request it names is + // a backticked method, `group/name`. + let tabled: BTreeSet<&str> = section + .lines() + .filter(|line| line.starts_with("| `")) + .filter_map(|line| line.split('|').nth(1)) + .flat_map(|cell| cell.split('`').skip(1).step_by(2)) + .filter(|name| name.contains('/')) + .collect(); + assert_eq!(tabled, answered, "the table and the dispatch disagree"); + for method in METHODS { + assert!(answered.contains(method), "{method} is not a dispatch arm"); + } +} diff --git a/crates/lucisv_server/src/server/ahead.rs b/crates/lucisv_server/src/server/ahead.rs new file mode 100644 index 0000000..723cf8e --- /dev/null +++ b/crates/lucisv_server/src/server/ahead.rs @@ -0,0 +1,440 @@ +//! Answering a request **ahead** of whatever holds the rest, from its buffer +//! alone: the colours (`viewport.rs`) and every request whose whole answer the +//! buffer gives (`crate::same_file`) — where in a burst, a held batch and a +//! widen such a request is taken out, and when its buffer's text is the text +//! the client asked about (`docs/features/fast-actions/README.md`). +//! +//! **What an exempted request reads, and why that is valid mid-scan.** The +//! loop is one thread, so a request is only ever answered "during" a scan by +//! being reached from inside it — the startup's configuration wait, the drain +//! between two of a scan's files (`answer_what_is_waiting`), both through +//! `process_batch`, or a widen's between-files drain — so the scan is between +//! two files and every buffer is whole. The exemption is taken where the +//! request would otherwise be held, and runs the ordinary dispatch arm for the +//! method *without* the all-buffers flush (`answer_flushed`). A colouring arm +//! reads the buffer and its overlay (`viewport.rs` says what and why a guess +//! off the overlay is fine there); every other exempted arm reads only the +//! part of the buffer that is a function of its text, which `same_file` +//! proves position by position — so its answer **is** the settled answer. +//! +//! **When.** The whole precondition — the buffer open, every older message +//! that could change its answer applied, its analysis current under the +//! settings in force, no settings still awaited, the answer the buffer's +//! alone — is stated once, on [`Server::answer_from_the_buffer`], the one +//! function that decides. Everything else in this file is *where* a request +//! is offered to it: at the moment the loop would hold it (`process_batch`), +//! behind a held message of its own burst ([`Server::set_aside`]), behind a +//! notification of its own burst that is about to be applied +//! ([`Server::answer_ahead_of`]), behind a `didOpen` that has been applied +//! and is about to widen ([`Server::open_then_widen`]), between +//! two files of a widen ([`Server::answer_ahead_mid_widen`]) and when the +//! startup's settings land ([`Server::answer_held_ahead`]). +//! +//! **Ahead of an older message only when that message cannot matter.** What +//! is older than a request and still unapplied is in one of four places: +//! `held`; the part of its burst being set aside in front of it (`ahead`); +//! the next notification of its own burst, which the loop is about to apply +//! ([`Server::answer_ahead_of`]); or the tail of a burst a scan is nested in +//! ([`Server::behind`]). Clause (b) is one test for all of them — a request +//! passes a waiting message only if [`REACH`] proves the message cannot +//! change its buffer — where before the escalation round each place had its +//! own, and the third let a request pass a settings push (QA's S1). +//! +//! **A widen** used to drain nothing. Its `didOpen` is applied first; the +//! requests behind it in its burst that can go ahead are answered before the +//! widen runs ([`Server::open_then_widen`]), and the ones that arrive while +//! it runs between two of its files ([`Server::answer_ahead_mid_widen`]), +//! everything else being held in arrival order — so the widen stays the +//! effect of one applied message and no notification overtakes an older one. + +use std::collections::HashSet; +use std::error::Error; + +use lsp_server::{Message, Notification, Request, RequestId, Response}; +use lsp_types::notification::{ + Cancel, DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles, + DidChangeWorkspaceFolders, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument, + DidRenameFiles, DidSaveTextDocument, Notification as _, +}; +use lsp_types::Uri; + +use super::batch::{cancelled_in, cancelled_response}; +use super::dispatch::document_uri; +use super::{Pending, Server}; +use crate::same_file; + +/// What applying a client notification can change of what a request answered +/// ahead reads: its buffer's `Document` (clause (b) of +/// [`Server::answer_from_the_buffer`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Reach { + /// No buffer's `Document`. + Nothing, + /// The `Document` of the one buffer its `textDocument.uri` names. + Named, + /// Any buffer's — or nobody has proved otherwise. + Any, +} + +/// Every notification the server handles — the arms of `handle_notification`, +/// and the cancel the loop consumes — with what applying it can reach. A +/// method that is not here reaches [`Reach::Any`]: the list says what is +/// *proved* harmless, and a test holds it to the handler's arms +/// (`tests/fast_actions_precondition.rs`), so a new arm cannot be let through +/// by forgetting it. +/// +/// What every notification does before its own arm is flush the dirty +/// buffers (`handle_notification`) — the analysis of text already applied, +/// under the settings in force, which is exactly what a request answered +/// ahead does for its own buffer first. Past that: +/// +/// * `didOpen`, `didChange`, `didSave`, `didClose` replace, dirty or drop the +/// `Document` of the buffer they name and no other. What else they start — +/// a widen, a rescan — moves the index and each buffer's overlay of it. +/// * `didChangeWatchedFiles` moves the index, the include graph and the +/// overlays (`reindex`, `reindex_watched`, `refresh_includes_naming`). A +/// buffer's text is the client's whatever the disk says, so the event +/// reaches no `Document` even when it names an open buffer's own file. +/// * `$/cancelRequest` changes nothing the server holds. +/// * `didChangeConfiguration` re-analyzes every open buffer the new +/// `largeFile.threshold` classifies differently +/// (`Server::reclassify_large_buffers`), and which buffers those are is not +/// read off the wire here. +/// * `didChangeWorkspaceFolders`, `didRenameFiles` and `didDeleteFiles` move +/// the index only, like a watcher event. They are a user's occasional +/// gesture, not what a rescan storm is made of, so holding an early answer +/// behind one costs nothing and they are left unproved. +pub(super) const REACH: [(&str, Reach); 10] = [ + (DidOpenTextDocument::METHOD, Reach::Named), + (DidChangeTextDocument::METHOD, Reach::Named), + (DidSaveTextDocument::METHOD, Reach::Named), + (DidCloseTextDocument::METHOD, Reach::Named), + (DidChangeWatchedFiles::METHOD, Reach::Nothing), + (Cancel::METHOD, Reach::Nothing), + (DidChangeConfiguration::METHOD, Reach::Any), + (DidChangeWorkspaceFolders::METHOD, Reach::Any), + (DidRenameFiles::METHOD, Reach::Any), + (DidDeleteFiles::METHOD, Reach::Any), +]; + +impl Server { + /// Answer a request now, ahead of whatever holds the rest — `None` when + /// it must wait like any other request. + /// + /// **The precondition, whole.** For the buffer the request names: + /// + /// * **(a) it is open**; + /// * **(b) every older client message that can change what the handler + /// reads has been applied** ([`Server::nothing_unapplied_for`]); + /// * **(c) its analysis is current** for the text applied, under the + /// settings in force. A dirty buffer is analyzed for a `same_file` + /// request, that buffer alone, exactly as the flush would + /// ([`Server::flush_buffer`]); for a colouring request it waits + /// (`viewport.rs`, "A dirty buffer waits"). A clean one already is: + /// `largeFile.threshold` is the one setting a `Document` reads, and the + /// settings applier re-analyzes whatever a new value re-classifies + /// (`Server::reclassify_large_buffers`); + /// * **(d) no settings are awaited** ([`Server::settings_awaited`]) — + /// they may re-classify any buffer the moment they land. What the + /// startup held for them is offered here again when they do + /// ([`Server::answer_held_ahead`]). The colours are exempt: a guess the + /// refresh replaces, and a buffer that changes mode is refreshed; + /// * **(e) the answer is the buffer's alone** — a colouring request by + /// `viewport.rs`'s rule, any other by + /// [`same_file::answered_by_the_buffer`], position by position. + /// + /// Then the answer is the one a server taking one message at a time gives + /// at this request's place in the client's stream — which is the claim + /// `tests/fast_actions_bursts.rs` holds this function to. + /// + /// `ahead` is what of its own burst is unapplied ahead of it and is not in + /// `held`. A cancel the burst carries for it is honoured here, + /// exactly as the loop would honour it. + pub(super) fn answer_from_the_buffer( + &mut self, + request: &Request, + ahead: &[Message], + cancelled: &mut HashSet, + ) -> Option { + let colours = match self.colours_may_go_ahead(&request.method) { + Some(allowed) => allowed.then_some(true)?, + None => same_file::METHODS.contains(&request.method.as_str()).then_some(false)?, + }; + let uri = document_uri(&request.params)?; + // (a) and (b). + if !self.nothing_unapplied_for(&uri, ahead) { + return None; + } + // (d), then (c), then (e). + if !colours && self.settings_awaited() { + return None; + } + if colours && self.is_dirty(&uri) { + return None; + } + if !colours { + self.flush_buffer(&uri); + let doc = self.workspace.document(&uri)?; + if !same_file::answered_by_the_buffer(doc, &request.method, &request.params) { + return None; + } + } + if cancelled.remove(&request.id) { + return Some(cancelled_response(request.id.clone())); + } + let started = self.timer(); + let unsettled = self.index_unsettled(); + let copy = Request::new(request.id.clone(), request.method.clone(), request.params.clone()); + let response = self.answer_flushed(copy); + if colours { + self.coloured_ahead(uri, &request.method, unsettled, &response); + } + self.timed(started, |took| { + format!( + "{} answered from the buffer ahead of a scan (held={}, settled={}) in {took}", + request.method, + self.held.len(), + !unsettled + ) + }); + Some(response) + } + + /// [`Server::answer_from_the_buffer`] for one message of a burst, the + /// answer sent: whether it was a request the exemption took. + pub(super) fn answered_ahead( + &mut self, + message: &Message, + ahead: &[Message], + cancelled: &mut HashSet, + ) -> Result> { + let Message::Request(request) = message else { return Ok(false) }; + let Some(response) = self.answer_from_the_buffer(request, ahead, cancelled) else { + return Ok(false); + }; + #[cfg(test)] + super::probe::went_ahead(&request.id); + self.connection.sender.send(Message::Response(response))?; + Ok(true) + } + + /// Move the rest of a burst into `rest`, behind a request that must wait + /// — except a request the exemption can answer against everything ahead + /// of it, which is answered now instead of being held. + pub(super) fn set_aside( + &mut self, + rest: &mut Vec, + behind: impl Iterator, + cancelled: &mut HashSet, + ) -> Result<(), Box> { + for later in behind { + if !self.answered_ahead(&later, rest, cancelled)? { + rest.push(later); + } + } + Ok(()) + } + + /// Before `notification` is applied, answer the `same_file` requests + /// behind it in its burst that need not wait for it. Returns the rest of + /// the burst, those answers taken out, in order. + /// + /// The precondition is [`Server::answer_from_the_buffer`]'s, unchanged: + /// `notification` and whatever of the burst lies between it and the + /// request are passed as what is unapplied ahead of the request, so the + /// request goes only when clause (b) proves that none of them can change + /// its buffer — a watcher event, another buffer's edit or save. Behind a + /// settings push, or anything else [`REACH`] has no proof for, it stays + /// where it is and is handled after the notification, in order. + /// + /// What this buys: a request read in one burst with a rescan's trigger + /// — the client wrote them together, or the server was busy when they + /// arrived — is not carried through the whole rescan in the tail of the + /// burst that started it, where no drain can reach it. A `didChange` + /// starts nothing, so nothing is answered ahead of one. + pub(super) fn answer_ahead_of( + &mut self, + notification: &Notification, + rest: std::vec::IntoIter, + cancelled: &mut HashSet, + ) -> Result, Box> { + let local = |m: &Message| matches!(m, Message::Request(r) if same_file::METHODS.contains(&r.method.as_str())); + if notification.method == DidChangeTextDocument::METHOD + || !rest.as_slice().iter().any(local) + { + return Ok(rest); + } + // Everything unapplied in this burst is passed as what is ahead of + // each request, so it is taken out of the count around this one. + let around = self.behind; + let rest: Vec = rest.collect(); + let in_rest = rest.iter().filter(|m| self.owes_a_state_change(m)).count(); + self.behind = around.saturating_sub(in_rest); + let mut kept = vec![Message::Notification(notification.clone())]; + let mut answered = Ok(()); + for later in rest { + match local(&later) { + true => match self.answered_ahead(&later, &kept, cancelled) { + Ok(true) => {} + Ok(false) => kept.push(later), + Err(gone) => { + answered = Err(gone); + kept.push(later); + } + }, + false => kept.push(later), + } + } + self.behind = around; + answered?; + kept.remove(0); + Ok(kept.into_iter()) + } + + /// Apply one notification of a burst whose not-yet-handled tail is + /// `rest`, returning that tail: a `didOpen` goes through + /// [`Server::open_then_widen`], everything else straight to the handler. + pub(super) fn apply_in_burst( + &mut self, + notification: Notification, + rest: std::vec::IntoIter, + cancelled: &mut HashSet, + ) -> Result, Box> { + if notification.method != DidOpenTextDocument::METHOD { + self.notification(notification); + return Ok(rest); + } + Ok(self.open_then_widen(notification, rest.collect(), cancelled)?.into_iter()) + } + + /// Apply a `didOpen`, and when it widens the scope, answer the requests + /// in `rest` — the burst behind it — that can go ahead **before** the + /// widen runs, then run it. Returns what is left of `rest`, in order. + /// + /// The buffer is applied by then and the answers need nothing from the + /// index, so VS Code's `full`, which arrives in the same burst as its + /// `didOpen`, colours at once instead of after the widen. Everything else + /// in `rest` is untouched and runs after the widen exactly as before; the + /// widen is still the effect of the applied `didOpen` and nothing else. + fn open_then_widen( + &mut self, + notification: Notification, + rest: Vec, + cancelled: &mut HashSet, + ) -> Result, Box> { + self.viewport.defer_widen = true; + self.notification(notification); + self.viewport.defer_widen = false; + let Some(added) = self.viewport.owed_widen.take() else { return Ok(rest) }; + // `rest` is passed as what is ahead of each request, so it is taken + // out of the count of unapplied notifications around this one. + let around = self.behind; + let in_rest = rest.iter().filter(|m| self.owes_a_state_change(m)).count(); + self.behind = around.saturating_sub(in_rest); + self.viewport.widening = true; + let mut kept = Vec::new(); + let answered = self.set_aside(&mut kept, rest.into_iter(), cancelled); + self.behind = around; + answered?; + self.reindex_widened(added); + Ok(kept) + } + + /// Once the settings have been applied: answer what staging held that its + /// buffer now answers alone, and keep the rest held, in arrival order. + /// + /// The same exemption the drains take, at the one moment the scan's first + /// drain is not yet reachable: everything older than each held request is + /// either applied or held ahead of it, which is what `set_aside` checks. + pub(super) fn answer_held_ahead(&mut self) -> Result<(), Box> { + let held = std::mem::take(&mut self.held); + let mut cancelled = cancelled_in(&held); + let mut kept = Vec::new(); + let answered = self.set_aside(&mut kept, held.into_iter(), &mut cancelled); + self.held = kept; + answered + } + + /// Between two files of a widen: answer the requests that have arrived + /// and can be answered from their buffers, and hold everything else, in + /// arrival order, behind whatever is already held. + /// + /// Safe for the rest of the burst that carried the `didOpen`: it is older + /// than anything arriving now, and while it holds a notification + /// [`Server::behind`] is non-zero, which makes every buffer not current. + pub(super) fn answer_ahead_mid_widen(&mut self) -> Result<(), Box> { + let arrived: Vec = self.queue.try_iter().collect(); + if arrived.is_empty() { + return Ok(()); + } + let mut cancelled = cancelled_in(&arrived); + let mut kept = Vec::new(); + self.set_aside(&mut kept, arrived.into_iter(), &mut cancelled)?; + self.held.extend(kept); + Ok(()) + } + + /// Clauses (a) and (b) of [`Server::answer_from_the_buffer`]: whether + /// `uri` is open and nothing older than the request being answered that + /// can reach it is still unapplied. + /// + /// Everything older is either applied or in one of three places + /// (`docs/features/scan-ordering/README.md`): `held`; `ahead`, the part + /// of the request's own burst that is unapplied in front of it — set + /// aside, or about to be applied; and the tail of a burst whose message + /// started the scan this request is answered inside. The first two are + /// read message by message + /// ([`Server::can_reach`]); the third is only a count + /// ([`Server::behind`]), so any unapplied message in it is taken as + /// reaching this buffer. + fn nothing_unapplied_for(&self, uri: &Uri, ahead: &[Message]) -> bool { + self.workspace.document(uri).is_some() + && self.behind == 0 + && !self.held.iter().chain(ahead).any(|older| self.can_reach(older, uri)) + } + + /// Whether applying `message` can change the `Document` of the buffer + /// `uri` — the default for anything not proved otherwise. + /// + /// A **request** changes no `Document`: the most one does on the way is + /// the flush, the analysis of text already applied. A **response** does + /// when it is the client's answer to a settings pull, which is applied as + /// a settings push is; the server acts on no other answer in a way that + /// touches a buffer (`Server::response`). A **notification** is read off + /// [`REACH`]; one that should name a buffer and names none that parses is + /// taken as naming this one. + fn can_reach(&self, message: &Message, uri: &Uri) -> bool { + let notification = match message { + Message::Request(_) => return false, + Message::Response(response) => { + return match self.pending.get(&response.id) { + Some(Pending::Configuration(_)) => true, + Some(Pending::ApplyEdit(_)) | None => false, + } + } + Message::Notification(notification) => notification, + }; + match REACH.iter().find(|(method, _)| *method == notification.method) { + Some((_, Reach::Nothing)) => false, + Some((_, Reach::Named)) => { + document_uri(¬ification.params).is_none_or(|named| named == *uri) + } + Some((_, Reach::Any)) | None => true, + } + } + + /// Clause (d): whether settings the client has are still on their way — + /// the startup's pull inside its wait ([`Server::staging`]), or a pull the + /// client itself asked for by pushing nothing + /// ([`Server::settings_announced`]). The startup's pull *after* its wait + /// ran out is not: a client that never answers must not close this path + /// for the session, and its late answer is applied as a push is. + fn settings_awaited(&self) -> bool { + self.staging || self.settings_announced.is_some() + } + + /// Whether `uri` has a change applied to its text and not yet analyzed. + fn is_dirty(&self, uri: &Uri) -> bool { + self.dirty.iter().any(|(pending, _)| pending == uri) + } +} diff --git a/crates/lucisv_server/src/server/client.rs b/crates/lucisv_server/src/server/client.rs index 8a15b4c..3cf44d4 100644 --- a/crates/lucisv_server/src/server/client.rs +++ b/crates/lucisv_server/src/server/client.rs @@ -50,9 +50,9 @@ impl Server { /// before this existed. No `scopeUri`: this server holds one set of /// settings for the whole session, not one per folder, so asking /// per-resource would be asking for answers it has nowhere to put. - pub(super) fn request_configuration(&mut self) { + pub(super) fn request_configuration(&mut self) -> Option { if !self.abilities.configuration { - return; + return None; } let params = ConfigurationParams { items: vec![ConfigurationItem { @@ -61,7 +61,8 @@ impl Server { }], }; let id = self.send_request(WorkspaceConfiguration::METHOD, params); - self.pending.insert(id, Pending::Configuration(std::time::Instant::now())); + self.pending.insert(id.clone(), Pending::Configuration(std::time::Instant::now())); + Some(id) } /// Ask the client to watch the source files and the filelist for us, @@ -172,6 +173,9 @@ impl Server { /// those ids is ever in `pending`, so they all fall out here — in any /// arrival order, since the id is the whole of the lookup. pub(super) fn response(&mut self, response: Response) { + if self.settings_announced.as_ref() == Some(&response.id) { + self.settings_announced = None; + } match self.pending.remove(&response.id) { Some(Pending::ApplyEdit(command)) => self.applied(command, response), Some(Pending::Configuration(asked)) => self.configured(asked, response), diff --git a/crates/lucisv_server/src/server/diagnostics.rs b/crates/lucisv_server/src/server/diagnostics.rs index 661b25e..7e21ab8 100644 --- a/crates/lucisv_server/src/server/diagnostics.rs +++ b/crates/lucisv_server/src/server/diagnostics.rs @@ -52,15 +52,31 @@ impl Server { let started = self.timer(); let buffers = self.dirty.len(); for (uri, text) in std::mem::take(&mut self.dirty) { - self.set_document(uri.clone(), text); - self.workspace.locate_port_entry(&uri); - crate::lint_trace::rebuild(crate::lint_trace::Rebuild::Publish, || self.publish(&uri)); + self.analyze_and_publish(uri, text); } self.timed(started, |took| { format!("flush of {buffers} dirty buffer{} took {took}", plural(buffers)) }); } + /// [`Server::flush_dirty`] for one buffer: analyze and republish `uri` if + /// it is dirty, and leave every other dirty buffer, in its order, to the + /// next flush. What a request answered from its buffer ahead of a scan + /// does instead of flushing them all (`ahead.rs`). + pub(super) fn flush_buffer(&mut self, uri: &Uri) { + let Some(at) = self.dirty.iter().position(|(pending, _)| pending == uri) else { return }; + let (uri, text) = self.dirty.remove(at); + self.analyze_and_publish(uri, text); + } + + /// One dirty buffer's share of a flush: its newest text analyzed, the + /// connection being typed located, its diagnostics republished. + pub(super) fn analyze_and_publish(&mut self, uri: Uri, text: String) { + self.set_document(uri.clone(), text); + self.workspace.locate_port_entry(&uri); + crate::lint_trace::rebuild(crate::lint_trace::Rebuild::Publish, || self.publish(&uri)); + } + /// Say once, in the output channel, that a buffer is on the large-file /// fast path. /// diff --git a/crates/lucisv_server/src/server/dispatch.rs b/crates/lucisv_server/src/server/dispatch.rs index 60dc0c3..b0a2570 100644 --- a/crates/lucisv_server/src/server/dispatch.rs +++ b/crates/lucisv_server/src/server/dispatch.rs @@ -571,8 +571,19 @@ impl Server { Completion::METHOD => decode(request).and_then(|p: CompletionParams| { let at = p.text_document_position; let (uri, position) = (at.text_document.uri, at.position); - completion::completions(&self.workspace, &uri, position, self.abilities.snippets) - .map_or(Ok(Value::Null), to_value) + let answer = completion::completions( + &self.workspace, + &uri, + position, + self.abilities.snippets, + ) + .map_or(Ok(Value::Null), to_value)?; + // The range every item replaces, said once for a client that + // takes defaults — the same edits in half the bytes. + Ok(match self.abilities.completion_item_defaults { + true => completion::with_item_defaults(answer), + false => answer, + }) }), // Ghost text. `null` for every position that is not one of the // two triggers, which is nearly all of them — the request arrives diff --git a/crates/lucisv_server/src/server/index.rs b/crates/lucisv_server/src/server/index.rs index 1eb4890..830ff0a 100644 --- a/crates/lucisv_server/src/server/index.rs +++ b/crates/lucisv_server/src/server/index.rs @@ -217,8 +217,8 @@ impl Server { self.rescan_wanted = true; return; } - // Inside a burst, the widen waits until the colours behind its - // `didOpen` have been answered (`Server::open_then_widen`). + // Inside a burst, the widen waits until what can go ahead behind its + // `didOpen` has been answered (`Server::open_then_widen`). if self.viewport.defers_widen(&added) { return; } @@ -242,8 +242,8 @@ impl Server { self.watching(bar.as_ref(), |ws, watch| ws.begin_widen(&added, watch, verbose)); let total = scan.total(); // A widen is a rescan a message asked for, so every request queued - // behind it waits for it — except colours, which need nothing from the - // index: between two files the queue is drained, colouring requests + // behind it waits for it — except what needs nothing from the index + // (`ahead.rs`): between two files the queue is drained, the requests // that can be are answered from their buffers, and everything else is // held in arrival order exactly as `must_hold` would hold it. loop { @@ -253,7 +253,7 @@ impl Server { if !self.watching(bar.as_ref(), step) { break; } - if self.answer_colours_mid_widen().is_err() { + if self.answer_ahead_mid_widen().is_err() { // The client has gone; nothing after this may speak to it. self.stopped = true; break; diff --git a/crates/lucisv_server/src/server/large_file.rs b/crates/lucisv_server/src/server/large_file.rs index cbc90d2..921e8f0 100644 --- a/crates/lucisv_server/src/server/large_file.rs +++ b/crates/lucisv_server/src/server/large_file.rs @@ -10,7 +10,8 @@ use lsp_types::request::{ CodeActionRequest, DocumentLinkRequest, Formatting, GotoDefinition, HoverRequest, OnTypeFormatting, PrepareRenameRequest, RangeFormatting, References, Rename, Request as _, - SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, WillSaveWaitUntil, + SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, SemanticTokensRefresh, + WillSaveWaitUntil, }; use lsp_types::{GotoDefinitionResponse, Location, Position, Uri}; use serde_json::Value; @@ -156,4 +157,42 @@ impl Server { .collect(), ) } + + /// Re-analyze every open buffer the large-file threshold now classifies + /// differently from when it was analyzed — normal ↔ large — after the + /// settings changed it from `before`; leave every other buffer alone. + /// + /// The threshold is read where a `Document` is built, so without this a + /// new value reached a buffer only at its next edit: one opened before + /// the startup's settings answer kept the default's verdict, and a + /// threshold changed mid-session did not move an open buffer at all + /// (`docs/features/fast-actions/README.md`, R1). A flipped buffer goes + /// through the flush's own path — analyzed, its connection located, its + /// diagnostics republished once — and its colours are re-requested. A + /// dirty buffer is skipped: its flush builds it under the new value + /// anyway. Like an edit, this does not reindex: the index takes the new + /// mode at the buffer's next save or rescan — and before the startup scan + /// there is no index yet, so that scan reads every buffer in its settled + /// mode. An unchanged threshold costs one comparison. + pub(super) fn reclassify_large_buffers(&mut self, before: u64) { + if self.workspace.client_settings().large_file_threshold == before { + return; + } + let flipped: Vec<(Uri, String)> = self + .workspace + .open_documents() + .filter(|(uri, _)| !self.dirty.iter().any(|(pending, _)| pending == *uri)) + .filter(|(_, doc)| self.workspace.is_large(&doc.text) != doc.large) + .map(|(uri, doc)| (uri.clone(), doc.text.clone())) + .collect(); + if flipped.is_empty() { + return; + } + for (uri, text) in flipped { + self.analyze_and_publish(uri, text); + } + if self.abilities.semantic_tokens_refresh { + self.send_request(SemanticTokensRefresh::METHOD, ()); + } + } } diff --git a/crates/lucisv_server/src/server/mod.rs b/crates/lucisv_server/src/server/mod.rs index 80a2daf..e48f238 100644 --- a/crates/lucisv_server/src/server/mod.rs +++ b/crates/lucisv_server/src/server/mod.rs @@ -24,9 +24,11 @@ //! * `formatting` — the five formatting entries and how a refusal is said; //! * `semantic_tokens` — the remembered answer a token delta is computed //! against; -//! * `viewport` — the semantic-token requests answered from the buffer alone -//! while everything else waits for a scan, and the refresh that replaces -//! those answers once the index has settled; +//! * `ahead` — the requests answered from their buffer alone while everything +//! else waits for a scan: where in a burst they are taken out, and when the +//! buffer is current (`crate::same_file` says which positions are local); +//! * `viewport` — which colouring requests may go ahead, and the refresh that +//! replaces those answers once the index has settled; //! * `diagnostics` — when a buffer is analyzed (the change debounce) and how //! what it says reaches the client, pushed or pulled; //! * `notification` — `handle_notification`, the table over notification @@ -52,6 +54,7 @@ use crate::state::Workspace; use batch::{burst, cancelled_id, cancelled_in, cancelled_response, changes_state}; use dispatch::names_nowhere; +mod ahead; mod batch; mod client; mod diagnostics; @@ -137,6 +140,12 @@ pub struct ClientAbilities { /// module it came from /// (`docs/features/extract-inline-module/README.md`). pub create_files: bool, + /// Whether the client applies a completion list's `itemDefaults` — + /// `editRange` and `insertTextFormat` both. Only then is the range every + /// item replaces said once instead of per item; a client that said + /// nothing gets every item whole, as before + /// (`docs/features/fast-actions/README.md`). + pub completion_item_defaults: bool, } /// Everything the server owns. @@ -266,7 +275,16 @@ pub struct Server { /// 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. + /// The client's answer to a settings pull is: it is applied as a push is + /// ([`Server::owes_a_state_change`]). behind: usize, + /// The settings pull an **empty** `didChangeConfiguration` made the + /// server send, until the client answers it. The client has said its + /// settings changed and not yet what they are, so nothing is answered + /// ahead of a scan from buffers those settings may re-classify + /// (`ahead.rs`, clause (d)). Only the newest such pull is kept: its + /// answer is the one that says what the settings are now. + settings_announced: Option, /// Navigation requests a scan answered **empty** while it was still /// growing the index, to be asked again at its next publish. /// @@ -434,7 +452,7 @@ impl Server { // 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 unapplied = batch.iter().filter(|m| self.owes_a_state_change(m)).count(); let mut messages = batch.into_iter(); while let Some(message) = messages.next() { // What is unapplied *older* than this message is only ever in the @@ -445,9 +463,10 @@ impl Server { // `shutdown` included, because a request sent before a shutdown // is a request the client is still owed an answer to. if self.must_hold(&message) { - // The one exemption: a colouring request whose buffer is - // already current is answered from that buffer alone, now - // (`viewport.rs` states what it reads and why that is safe). + // The one exemption: a request whose buffer is current and + // gives the answer alone — the colours, and whatever + // `same_file` proves local — is answered from it now + // (`ahead.rs` states what it reads and why that is safe). if self.answered_ahead(&message, &[], &mut cancelled)? { continue; } @@ -459,7 +478,7 @@ impl Server { self.hold(rest, already_waiting); return Ok(false); } - unapplied -= usize::from(changes_state(&message)); + unapplied = unapplied.saturating_sub(usize::from(self.owes_a_state_change(&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 @@ -487,9 +506,12 @@ impl Server { self.cancel_deferred(&cancel)?; consumed_cancels.push(cancel); } - // An open can widen the scope; the colours behind it in this - // burst are answered before the widen runs (`viewport.rs`). + // What behind it in this burst need not wait for it is + // answered first; and an open can widen the scope, so what can + // go ahead behind it is answered before the widen runs + // (`ahead.rs`). Message::Notification(notification) => { + messages = self.answer_ahead_of(¬ification, messages, &mut cancelled)?; messages = self.apply_in_burst(notification, messages, &mut cancelled)?; } Message::Response(response) => self.response(response), @@ -632,13 +654,37 @@ impl Server { /// **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). + /// argument) — with one exception. The client's **answer to a settings + /// pull** is applied as a push is, so outside the startup's wait it is a + /// state change like any notification + /// ([`Server::owes_a_state_change`]): it waits behind an older + /// unapplied one, and a newer one waits behind it. Before + /// `fast-actions`' escalation round it was applied the moment it was + /// read, ahead of an older push or edit a rescan was holding, and a + /// newer push was applied ahead of one held — either way the server + /// ended, or answered, in a state the client never had. 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, + _ if self.owes_a_state_change(message) => { + self.behind > 0 || self.held.iter().any(|older| self.owes_a_state_change(older)) + } + _ => false, + } + } + + /// Whether `message`, still unapplied, is a state change the messages + /// behind it are owed: any notification but a cancel + /// ([`changes_state`]), and the client's answer to a settings pull — + /// the one response the server applies as it applies a notification + /// (`configured` → `apply_settings`). What [`Server::behind`] counts. + fn owes_a_state_change(&self, message: &Message) -> bool { + match message { + Message::Response(response) => { + matches!(self.pending.get(&response.id), Some(Pending::Configuration(_))) + } + _ => changes_state(message), } } diff --git a/crates/lucisv_server/src/server/notification.rs b/crates/lucisv_server/src/server/notification.rs index 127b0c3..2915d5c 100644 --- a/crates/lucisv_server/src/server/notification.rs +++ b/crates/lucisv_server/src/server/notification.rs @@ -233,7 +233,9 @@ impl Server { DidChangeConfiguration::METHOD => { if let Ok(p) = extract::(notification) { if settings::says_nothing(&p.settings) && self.abilities.configuration { - self.request_configuration(); + // Until that answer lands the settings in force are + // known to be stale (`ahead.rs`, clause (d)). + self.settings_announced = self.request_configuration(); return; } self.apply_settings(settings::from_payload(&p.settings)); @@ -345,7 +347,12 @@ impl Server { // Only `exclude` and `filelist` change which files exist as far as // this server is concerned; the other settings are read afresh by the // next request that wants them and need no invalidation. - if self.workspace.set_client_settings(settings) { + let threshold = self.workspace.client_settings().large_file_threshold; + let rescan = self.workspace.set_client_settings(settings); + // Before the rescan, so the index takes each buffer in the mode the + // new threshold gives it. + self.reclassify_large_buffers(threshold); + if rescan { self.reindex(); } else if self.lint_selection() != linted { // `lucisv.lint.select`/`ignore`, the class switches, the per-rule diff --git a/crates/lucisv_server/src/server/probe.rs b/crates/lucisv_server/src/server/probe.rs index 7ff93c4..56b1939 100644 --- a/crates/lucisv_server/src/server/probe.rs +++ b/crates/lucisv_server/src/server/probe.rs @@ -10,7 +10,7 @@ use std::cell::RefCell; use std::collections::VecDeque; -use lsp_server::Message; +use lsp_server::{Message, RequestId}; #[derive(Default)] struct Probe { @@ -23,6 +23,9 @@ struct Probe { handed_back: usize, /// How many scripted bursts a scan received. delivered: usize, + /// The requests answered ahead of whatever held the rest (`ahead.rs`) + /// since the last [`take_ahead`], in the order they were answered. + ahead: Vec, } /// What [`take_counts`] reports. @@ -77,3 +80,14 @@ pub(super) fn at_interleave_point(handed_back: bool, arrived: &mut Vec) } }); } + +/// Called where a request is answered ahead of what holds the rest. +pub(super) fn went_ahead(id: &RequestId) { + PROBE.with(|probe| probe.borrow_mut().ahead.push(id.clone())); +} + +/// The requests answered ahead since the last call — what a test compares +/// with the answer a server taking one message at a time gives. +pub(super) fn take_ahead() -> Vec { + PROBE.with(|probe| std::mem::take(&mut probe.borrow_mut().ahead)) +} diff --git a/crates/lucisv_server/src/server/startup.rs b/crates/lucisv_server/src/server/startup.rs index 5ad69c4..e21f205 100644 --- a/crates/lucisv_server/src/server/startup.rs +++ b/crates/lucisv_server/src/server/startup.rs @@ -171,6 +171,7 @@ impl Server { stopped: false, held: Vec::new(), behind: 0, + settings_announced: None, deferred: Vec::new(), verbose, born: Instant::now(), @@ -256,7 +257,7 @@ impl Server { return; } self.staging = true; - self.request_configuration(); + let _ = self.request_configuration(); self.await_configuration(wait); // Inside the staging window, because it is the same window: every // request is still held, and the scan has still not begun. @@ -265,6 +266,12 @@ impl Server { } self.staging = false; self.rescan_wanted = false; + // The settings have landed and every buffer is classified by them: + // what its buffer alone answers is answered now, not after the head + // phase of the scan about to run (`ahead.rs`). + if !self.stopped && self.answer_held_ahead().is_err() { + self.stopped = true; + } } /// Wait a bounded moment for the editor's first `didOpen`, when knowing diff --git a/crates/lucisv_server/src/server/tests/fast_actions.rs b/crates/lucisv_server/src/server/tests/fast_actions.rs new file mode 100644 index 0000000..7155b04 --- /dev/null +++ b/crates/lucisv_server/src/server/tests/fast_actions.rs @@ -0,0 +1,209 @@ +//! Same file first, on the wire: each claim of `ahead.rs` about a request +//! `same_file` proves local is one test. It goes ahead of what a scan holds; +//! a cross-file one at the same moment waits, in order; a dirty buffer is +//! analyzed for it — that buffer alone; a cancel is honoured. (When it must +//! wait instead is `fast_actions_precondition.rs`, clause by clause.) + +use lsp_types::notification::Cancel; + +use super::*; + +const PKG: &str = "package p;\n localparam int W = 4;\nendpackage\n"; +const TOP: &str = "module top;\n import p::*;\n logic sig;\n assign sig = W;\nendmodule\n"; + +/// A session over a package and a module that imports it, `top.sv` open. +fn opened(name: &str) -> (Tree, Session, Uri) { + let tree = Tree::new(name); + tree.write("p.sv", PKG); + tree.write("top.sv", TOP); + let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress()); + let uri = session.open(&tree.path.join("top.sv"), TOP); + session.drain(); + (tree, session, uri) +} + +fn ask(id: &str, method: &str, params: Value) -> Message { + Message::Request(lsp_server::Request::new( + RequestId::from(id.to_string()), + method.to_string(), + params, + )) +} + +/// A hover at the first `needle` in `text`, `skip` bytes in. +fn hover_at(id: &str, uri: &Uri, text: &str, needle: &str) -> Message { + let offset = text.find(needle).expect("needle"); + let line = text[..offset].matches('\n').count(); + let column = offset - text[..offset].rfind('\n').map_or(0, |at| at + 1); + ask( + id, + HoverRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": uri }, + "position": { "line": line, "character": column } }), + ) +} + +/// A request about `uri` no buffer answers alone. +fn lens(id: &str, uri: &Uri) -> Message { + ask(id, CodeLensRequest::METHOD, serde_json::json!({ "textDocument": { "uri": uri } })) +} + +fn rid(id: &str) -> RequestId { + RequestId::from(id.to_string()) +} + +/// One burst through the loop body with a rescan pretended to be running. +fn mid_scan(session: &mut Session, burst: Vec) { + session.server.scanning = true; + session.server.answering_a_rescan = true; + session.batch(burst); + session.server.scanning = false; + session.server.answering_a_rescan = false; +} + +fn answered(session: &Session) -> Vec { + session.answers().into_iter().map(|r| r.id).collect() +} + +#[test] +fn a_local_hover_goes_ahead_and_a_cross_file_one_waits_in_order() { + let (_tree, mut session, uri) = opened("fa_ahead"); + mid_scan( + &mut session, + vec![ + lens("l", &uri), + hover_at("cross", &uri, TOP, "W;"), + hover_at("local", &uri, TOP, "sig = W"), + ], + ); + assert_eq!(answered(&session), vec![rid("local")], "the local hover alone goes ahead"); + let held: Vec = session + .server + .held + .iter() + .filter_map(|m| match m { + Message::Request(r) => Some(r.id.clone()), + _ => None, + }) + .collect(); + assert_eq!(held, vec![rid("l"), rid("cross")], "the rest waits, in arrival order"); +} + +#[test] +fn the_early_answer_is_the_answer_given_once_nothing_waits() { + let (_tree, mut session, uri) = opened("fa_same"); + mid_scan(&mut session, vec![lens("l", &uri), hover_at("early", &uri, TOP, "sig = W")]); + let early = session.answers(); + session.server.held.clear(); + let settled = session.batch(vec![hover_at("settled", &uri, TOP, "sig = W")]); + assert!(!settled, "no shutdown"); + let settled = session.answers(); + assert_eq!(early.len(), 1); + assert_eq!( + format!("{:?}", early[0].response_result), + format!("{:?}", settled[0].response_result) + ); + assert!( + early[0].response_result.as_ref().is_ok_and(|r| !r.is_null()), + "a real card: {early:?}" + ); +} + +#[test] +fn a_dirty_buffer_is_analyzed_for_it_and_no_other_dirty_buffer_is() { + let (tree, mut session, uri) = opened("fa_dirty"); + tree.write("other.sv", "module other;\nendmodule\n"); + let other = session.open(&tree.path.join("other.sv"), "module other;\nendmodule\n"); + session.drain(); + let edited = TOP.replace("logic sig;", "logic sig;\n logic fresh;"); + let other_edit = "module other;\n logic o;\nendmodule\n"; + session.batch(vec![changed(&other, 2, other_edit), changed(&uri, 2, &edited)]); + assert_eq!(session.server.dirty.len(), 2, "premise: both buffers are dirty"); + mid_scan(&mut session, vec![lens("l", &uri), hover_at("h", &uri, &edited, "fresh")]); + let answers = session.answers(); + assert_eq!(answers.len(), 1, "the hover on the new declaration goes ahead"); + let card = answers[0].response_result.as_ref().expect("a result").to_string(); + assert!(card.contains("fresh"), "answered from the newest text: {card}"); + let still: Vec<&Uri> = session.server.dirty.iter().map(|(u, _)| u).collect(); + assert_eq!(still, vec![&other], "the other buffer waits for the next flush"); +} + +#[test] +fn a_change_held_ahead_of_it_holds_it_too() { + let (_tree, mut session, uri) = opened("fa_heldchange"); + let edited = TOP.replace("logic sig;", "logic sig2;"); + // The lens is held, and with it the change behind it; the hover is + // behind the change, so its buffer is not current. + mid_scan( + &mut session, + vec![lens("l", &uri), changed(&uri, 2, &edited), hover_at("h", &uri, TOP, "sig = W")], + ); + assert!(answered(&session).is_empty(), "nothing goes ahead of an unapplied change"); +} + +#[test] +fn a_cancel_in_the_same_burst_is_honoured_for_a_request_that_goes_ahead() { + let (_tree, mut session, uri) = opened("fa_cancel"); + let cancel = Message::Notification(lsp_server::Notification::new( + Cancel::METHOD.to_string(), + serde_json::json!({ "id": "h" }), + )); + mid_scan(&mut session, vec![lens("l", &uri), hover_at("h", &uri, TOP, "sig = W"), cancel]); + let answers = session.answers(); + assert_eq!(answers.len(), 1); + assert!(answers[0] + .response_result + .as_ref() + .is_err_and(|e| e.code == lsp_server::ErrorCode::RequestCanceled as i32)); +} + +#[test] +fn whole_buffer_requests_go_ahead_and_completion_waits() { + let (_tree, mut session, uri) = opened("fa_whole"); + let doc = serde_json::json!({ "textDocument": { "uri": uri } }); + let at = serde_json::json!({ "textDocument": { "uri": uri }, + "position": { "line": 3, "character": 15 } }); + mid_scan( + &mut session, + vec![ + lens("l", &uri), + ask("sym", DocumentSymbolRequest::METHOD, doc.clone()), + ask("fold", FoldingRangeRequest::METHOD, doc), + ask("comp", Completion::METHOD, at), + ], + ); + assert_eq!(answered(&session), vec![rid("sym"), rid("fold")]); + assert_eq!(session.server.held.len(), 2, "the lens and the completion"); +} + +#[test] +fn a_client_that_takes_item_defaults_is_sent_the_range_once() { + let tree = Tree::new("fa_defaults"); + tree.write("p.sv", PKG); + let text = "module top;\n import p::*;\n logic sig;\n assign sig = s\nendmodule\n"; + tree.write("top.sv", text); + let position = serde_json::json!({ "line": 3, "character": 16 }); + let mut answers = Vec::new(); + for item_defaults in [false, true] { + let abilities = + ClientAbilities { completion_item_defaults: item_defaults, ..Default::default() }; + let mut session = Session::wide_with(vec![tree.path.clone()], abilities); + let uri = session.open(&tree.path.join("top.sv"), text); + let params = serde_json::json!({ "textDocument": { "uri": uri }, "position": position }); + answers.push(session.result(Completion::METHOD, params)); + } + let (whole, compact) = (&answers[0], &answers[1]); + assert!(whole.get("itemDefaults").is_none(), "a client that said nothing: {whole}"); + let range = &compact["itemDefaults"]["editRange"]; + assert_eq!(range, &whole["items"][0]["textEdit"]["range"]); + let labels = |a: &Value| -> Vec { + a["items"].as_array().expect("items").iter().map(|i| i["label"].to_string()).collect() + }; + assert_eq!(labels(whole), labels(compact), "the same items"); + assert!(compact["items"] + .as_array() + .expect("items") + .iter() + .all(|i| i.get("textEdit").is_none())); + assert!(compact.to_string().len() < whole.to_string().len()); +} diff --git a/crates/lucisv_server/src/server/tests/fast_actions_bursts.rs b/crates/lucisv_server/src/server/tests/fast_actions_bursts.rs new file mode 100644 index 0000000..c3d36e7 --- /dev/null +++ b/crates/lucisv_server/src/server/tests/fast_actions_bursts.rs @@ -0,0 +1,499 @@ +//! **An answer given ahead is the answer a server taking one message at a +//! time gives** — the randomized differential behind the precondition on +//! `Server::answer_from_the_buffer` (`docs/features/fast-actions/README.md`). +//! +//! A seeded client sends rounds of bursts mixing every kind of message that +//! can sit in front of a request: edits, opens, closes and saves of two +//! buffers whose sizes straddle the large-file thresholds in play; settings +//! pushes that move the threshold up or down or move something unrelated; an +//! empty push (the pull model's "ask me") and the client's late answer to a +//! pull; watcher events that cost a whole rescan; folder, rename and delete +//! events; a notification the server does not know. Two servers hear it. The +//! **early** one gets the round as the loop would — a first burst, the rest +//! arriving at the interleave points of the rescan it starts, or held behind +//! it — so the real gate decides what goes ahead. The **reference** gets the +//! same messages one per burst, in the order sent. Then: +//! +//! * every request is answered exactly once by both; +//! * every answer the early server gave *ahead* ([`probe::take_ahead`]) is +//! an answer the reference gives to that request **at its place in the +//! stream or after a later message of the round** — a state the client +//! had, no older than the request. (A request that waited and went ahead +//! later may rightly see what was applied meanwhile, as every request +//! answered late always could; what it may never see is a state before +//! its own, or one that never was.) +//! * once the round has settled, both say the same about every open buffer. +//! +//! The ignored long run takes `LUCISV_FAST_ACTIONS_SEED` and +//! `LUCISV_FAST_ACTIONS_ROUNDS`. + +use std::collections::HashMap; + +use lsp_types::notification::Cancel; + +use super::super::probe; +use super::scan_ordering::{ask, closed, created, note, opened, ordering_tree, settle}; +use super::*; + +/// The `largeFile.threshold` values in play: off, between the buffer sizes, +/// and the default. +const THRESHOLDS: [u64; 4] = [0, 200, 1000, 4 * 1024 * 1024]; + +/// The requests asked at the signal's declaration (line 1) or its use +/// (line 2): each is early-eligible there, and each answer names the signal. +const AT_THE_SIGNAL: [(&str, u32); 4] = [ + (HoverRequest::METHOD, 1), + (GotoDefinition::METHOD, 2), + (DocumentHighlightRequest::METHOD, 2), + (PrepareRenameRequest::METHOD, 1), +]; + +/// A buffer's text: one module, one signal named after `n`, and `padding` +/// comment lines — about 80 bytes, 400 or 1.5 KB for 0, 12 and 55. +fn text(doc: usize, n: u64, padding: usize) -> String { + format!( + "module m{doc};\n logic sig{n};\n assign sig{n} = 1'b0;\nendmodule\n{}", + "// padding padding padding\n".repeat(padding) + ) +} + +/// One message of the client's stream, before it is put on a wire: the +/// settings answer names a request id each server numbered for itself. +#[derive(Clone)] +enum Sent { + Wire(Message), + /// The client's answer to the pull outstanding when the round began. + SettingsAnswer(u64), +} + +struct Rng(u64); + +impl Rng { + 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 + } +} + +struct Client { + rng: Rng, + root: PathBuf, + docs: Vec, + /// Version, by document, of the buffers that are open. + open: HashMap, + asked: Vec, + next_id: i32, + threshold: u64, + /// Whether an empty push has gone unanswered so far. + announced: bool, + folder_added: bool, +} + +impl Client { + fn settings(&self, indent: usize) -> Value { + serde_json::json!({ "index": { "scope": "workspace" }, "indent": indent, + "largeFile": { "threshold": self.threshold } }) + } + + fn new_text(&mut self, doc: usize) -> String { + let padding = [0, 12, 55][self.rng.below(3)]; + text(doc, self.rng.next() % 1000, padding) + } + + /// The answer to whichever pull is outstanding (see [`Heard::wire`]). + fn settings_answer(&mut self) -> Sent { + self.announced = false; + self.threshold = THRESHOLDS[self.rng.below(THRESHOLDS.len())]; + Sent::SettingsAnswer(self.threshold) + } + + /// One message, the client's own view updated as it is sent. + fn message(&mut self) -> Sent { + // A client that said "ask me" answers soon: the early path is shut + // until it does, and a run of rounds with it shut tests little. + if self.announced && self.rng.below(3) == 0 { + return self.settings_answer(); + } + let doc = self.rng.below(self.docs.len()); + let uri = self.docs[doc].clone(); + let roll = self.rng.below(100); + Sent::Wire(match (roll, self.open.contains_key(&doc)) { + (0..=11, true) => { + let version = self.open.get_mut(&doc).map(|v| { + *v += 1; + *v + }); + changed(&uri, version.unwrap_or(2), &self.new_text(doc)) + } + (12..=13, true) => { + self.open.remove(&doc); + closed(&uri) + } + (14..=16, true) => { + let with_text = self.rng.below(2) == 0; + let text = with_text.then(|| self.new_text(doc)); + note( + DidSaveTextDocument::METHOD, + serde_json::json!({ "textDocument": { "uri": uri }, "text": text }), + ) + } + (0..=16, false) => { + self.open.insert(doc, 1); + opened(&uri, &self.new_text(doc)) + } + (17..=22, _) => { + self.threshold = THRESHOLDS[self.rng.below(THRESHOLDS.len())]; + push(self.settings(2)) + } + // Nothing a buffer reads moves: the indent only. + (23..=25, _) => { + let indent = 2 + self.rng.below(3); + push(self.settings(indent)) + } + (26..=27, _) => { + self.announced = true; + note(DidChangeConfiguration::METHOD, serde_json::json!({ "settings": null })) + } + (28..=30, _) => return self.settings_answer(), + (31..=33, _) => self.created_file(), + (34, _) => self.folders(), + (35, _) => self.file_operation(), + (36, _) => note("$/setTrace", serde_json::json!({ "value": "off" })), + (37, _) => note(Cancel::METHOD, serde_json::json!({ "id": 1_000_000 })), + _ => self.request(doc), + }) + } + + /// A new package on disk and the watcher's word for it: a whole rescan. + fn created_file(&mut self) -> Message { + let name = format!("r{}_{}", self.next_id, self.rng.below(100_000)); + 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"); + created(&path) + } + + fn folders(&mut self) -> Message { + let folder = serde_json::json!({ + "uri": path_to_uri(&self.root.join("more")).expect("uri"), "name": "more", + }); + self.folder_added = !self.folder_added; + let (added, removed) = match self.folder_added { + true => (vec![folder], Vec::new()), + false => (Vec::new(), vec![folder]), + }; + note( + DidChangeWorkspaceFolders::METHOD, + serde_json::json!({ "event": { "added": added, "removed": removed } }), + ) + } + + fn file_operation(&mut self) -> Message { + let gone = path_to_uri(&self.root.join("z/gone.sv")).expect("uri"); + match self.rng.below(2) { + 0 => note(DidDeleteFiles::METHOD, serde_json::json!({ "files": [{ "uri": gone }] })), + _ => note( + DidRenameFiles::METHOD, + serde_json::json!({ "files": [{ "oldUri": gone, "newUri": gone }] }), + ), + } + } + + fn request(&mut self, doc: usize) -> Message { + let id = self.next_id; + self.next_id += 1; + self.asked.push(id); + let whole = serde_json::json!({ "textDocument": { "uri": self.docs[doc] } }); + match self.rng.below(8) { + // Never early: it holds the burst behind it. + 0 => ask(id, CodeLensRequest::METHOD, whole), + 1 => ask(id, DocumentSymbolRequest::METHOD, whole), + 2 => ask(id, FoldingRangeRequest::METHOD, whole), + n => { + let (method, line) = AT_THE_SIGNAL[n % AT_THE_SIGNAL.len()]; + let at = serde_json::json!({ "line": line, "character": 10 }); + let params = serde_json::json!({ + "textDocument": { "uri": self.docs[doc] }, "position": at, + }); + ask(id, method, params) + } + } + } + + /// One round: one to four bursts. Four rounds in five have a watcher + /// event in the first, so the rest of the round meets a real rescan — + /// usually as that burst's last message, sometimes with a tail behind it. + fn round(&mut self) -> Vec> { + let bursts = 1 + self.rng.below(4); + let mut round: Vec> = (0..bursts) + .map(|_| (0..1 + self.rng.below(5)).map(|_| self.message()).collect()) + .collect(); + if self.rng.below(5) < 4 { + let end = round[0].len(); + let at = if self.rng.below(4) == 0 { self.rng.below(end + 1) } else { end }; + let event = Sent::Wire(self.created_file()); + round[0].insert(at, event); + } + round + } +} + +fn push(section: Value) -> Message { + note(DidChangeConfiguration::METHOD, serde_json::json!({ "settings": { "lucisv": section } })) +} + +/// One server and what the test knows of it. +struct Heard { + session: Session, + /// The settings pull this server has outstanding, as of the last round. + pull: Option, + /// A newer pull it has made since: the one to answer from the next + /// round on. Kept apart so that both servers start a round answering + /// alike, however far through the round each has been listened to. + newer_pull: Option, + /// Its answers since they were last taken, by request. + answers: HashMap>, +} + +impl Heard { + fn new(tree: &Tree) -> Heard { + let abilities = ClientAbilities { configuration: true, ..watching_progress() }; + let session = Session::wide_with(vec![tree.path.clone()], abilities); + let mut heard = Heard { session, pull: None, newer_pull: None, answers: HashMap::new() }; + let _ = heard.heard(); + heard + } + + /// A burst on this server's wire. A settings answer with no pull to + /// answer is not sent — to either server, since both are asked alike. + fn wire(&mut self, burst: &[Sent]) -> Vec { + burst + .iter() + .filter_map(|sent| match sent { + Sent::Wire(message) => Some(message.clone()), + Sent::SettingsAnswer(threshold) => { + let section = serde_json::json!({ + "index": { "scope": "workspace" }, + "largeFile": { "threshold": threshold }, + }); + let answer = Response::new_ok(self.pull.take()?, serde_json::json!([section])); + Some(Message::Response(answer)) + } + }) + .collect() + } + + /// Take in everything the server sent since the last call: its answers + /// by id, and the newest settings pull among its requests. + fn listen(&mut self) { + for message in self.session.drain() { + match message { + Message::Response(r) => self.answers.entry(r.id.clone()).or_default().push(r), + Message::Request(r) if r.method == WorkspaceConfiguration::METHOD => { + self.newer_pull = Some(r.id); + } + _ => {} + } + } + } + + /// The end of a round: the answers heard since the last one, and the + /// newest pull made in it becomes the one a settings answer answers. + fn heard(&mut self) -> HashMap> { + self.listen(); + if let Some(newer) = self.newer_pull.take() { + self.pull = Some(newer); + } + std::mem::take(&mut self.answers) + } + + /// Ask now, with nothing waiting. + fn says(&mut self, method: &str, params: &Value) -> String { + let response = self.session.request(method, params); + self.listen(); + rendered(&response) + } +} + +/// One line per message of a round, for a failure's message. +fn described(round: &[Vec]) -> String { + let line = |sent: &Sent| match sent { + Sent::SettingsAnswer(threshold) => format!("settings answer, threshold {threshold}"), + Sent::Wire(Message::Request(r)) => format!("{} {} {}", r.id, r.method, r.params), + Sent::Wire(Message::Notification(n)) => { + let mut params = n.params.to_string(); + params.truncate(160); + format!("{} {params}", n.method) + } + Sent::Wire(Message::Response(r)) => format!("response {}", r.id), + }; + let burst = |b: &Vec| b.iter().map(line).collect::>().join("\n "); + round.iter().map(burst).collect::>().join("\n --\n ") +} + +/// What a run compared. +#[derive(Default)] +struct Tally { + asked: usize, + ahead: usize, + /// Answers given ahead that are a later state's, not the request's own. + later: usize, + settled: usize, +} + +fn rendered(response: &Response) -> String { + format!("{:?}", response.response_result.clone().map_err(|e| (e.code, e.message))) +} + +fn run(seed: u64, rounds: usize) -> Tally { + let tree = ordering_tree(&format!("fa_bursts_{seed}_{rounds}")); + let docs: Vec = ["a/a.sv", "b/b.sv"] + .iter() + .map(|rel| path_to_uri(&tree.path.join(rel)).expect("uri")) + .collect(); + let mut client = Client { + rng: Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1), + root: tree.path.clone(), + docs: docs.clone(), + open: HashMap::new(), + asked: Vec::new(), + next_id: 1, + threshold: THRESHOLDS[3], + announced: false, + folder_added: false, + }; + let (mut early, mut reference) = (Heard::new(&tree), Heard::new(&tree)); + for (doc, uri) in docs.iter().enumerate() { + client.open.insert(doc, 1); + for heard in [&mut early, &mut reference] { + heard.session.batch(vec![opened(uri, &text(doc, 0, 12))]); + let _ = heard.heard(); + } + } + let _ = (probe::take_counts(), probe::take_ahead()); + let mut tally = Tally::default(); + for round in 0..rounds { + let said = client.round(); + let asked = std::mem::take(&mut client.asked); + let sent = described(&said); + let context = |what: &str| format!("seed {seed}, round {round}: {what}\n {sent}"); + + // The early server: the first burst to the loop, the rest wherever a + // rescan's interleave points — or the wait after it — puts them. + let mut bursts: Vec> = said.iter().map(|b| early.wire(b)).collect(); + let first = bursts.remove(0); + probe::script(bursts); + assert!(!early.session.batch(first), "no shutdown"); + settle(&mut early.session); + let ahead = probe::take_ahead(); + let early_answers = early.heard(); + + // The reference: the same stream, one message at a time. A request + // the early server answered ahead is asked again after every later + // state change of the round: the states it may rightly have seen. + let mut gone_ahead: Vec<(RequestId, String, Value)> = Vec::new(); + let mut later: HashMap> = HashMap::new(); + for burst in &said { + for message in reference.wire(burst) { + let asked = match &message { + Message::Request(r) if ahead.contains(&r.id) => { + Some((r.id.clone(), r.method.clone(), r.params.clone())) + } + _ => None, + }; + let changes = !matches!(message, Message::Request(_)); + assert!(!reference.session.batch(vec![message]), "no shutdown"); + settle(&mut reference.session); + gone_ahead.extend(asked); + for (id, method, params) in gone_ahead.iter().filter(|_| changes) { + later.entry(id.clone()).or_default().push(reference.says(method, params)); + } + } + } + let _ = probe::take_ahead(); + let reference_answers = reference.heard(); + + for id in asked.iter().map(|id| RequestId::from(*id)) { + let (e, r) = (early_answers.get(&id), reference_answers.get(&id)); + let (Some([e]), Some([r])) = (e.map(Vec::as_slice), r.map(Vec::as_slice)) else { + panic!("{}", context(&format!("{id} answered once by each: {e:?} / {r:?}"))); + }; + tally.asked += 1; + if ahead.contains(&id) { + tally.ahead += 1; + let (e, at_its_place) = (rendered(e), rendered(r)); + let after = later.remove(&id).unwrap_or_default(); + tally.later += usize::from(e != at_its_place); + assert!( + e == at_its_place || after.contains(&e), + "{}", + context(&format!( + "{id} went ahead with an answer the client's stream never gave it\n \ + early: {e}\n at its place: {at_its_place}\n later: {after:?}" + )) + ); + } + } + // Settled, the two servers hold the same buffers in the same mode. + for uri in &docs { + let whole = serde_json::json!({ "textDocument": { "uri": uri } }); + let at = serde_json::json!({ "textDocument": { "uri": uri }, + "position": { "line": 1, "character": 10 } }); + for (method, params) in + [(DocumentSymbolRequest::METHOD, &whole), (HoverRequest::METHOD, &at)] + { + tally.settled += 1; + let (e, r) = (early.says(method, params), reference.says(method, params)); + assert_eq!(e, r, "{}", context(&format!("{method} once settled"))); + } + } + } + tally +} + +#[test] +fn answers_given_ahead_equal_a_one_message_at_a_time_server() { + let mut total = Tally::default(); + for seed in 1..=8 { + let tally = run(seed, 40); + total.asked += tally.asked; + total.ahead += tally.ahead; + total.later += tally.later; + total.settled += tally.settled; + } + eprintln!( + "fast actions, random bursts: {} requests, {} answered ahead ({} from a later state), \ + {} settled comparisons", + total.asked, total.ahead, total.later, total.settled + ); + assert!( + total.ahead > 100, + "the gate lets requests through: {} of {}", + total.ahead, + total.asked + ); + assert!(total.asked > total.ahead * 2, "and holds others: {} of {}", total.ahead, total.asked); +} + +#[test] +#[ignore = "long: LUCISV_FAST_ACTIONS_SEED (default 7), LUCISV_FAST_ACTIONS_ROUNDS (default 3000)"] +fn answers_given_ahead_equal_a_one_message_at_a_time_server_long_run() { + let number = |name: &str, default: u64| { + std::env::var(name).ok().and_then(|s| s.parse().ok()).unwrap_or(default) + }; + let seed = number("LUCISV_FAST_ACTIONS_SEED", 7); + let rounds = number("LUCISV_FAST_ACTIONS_ROUNDS", 3000) as usize; + let tally = run(seed, rounds); + eprintln!( + "fast actions, random bursts, seed {seed}: {} requests, {} answered ahead \ + ({} from a later state), {} settled comparisons, 0 differ", + tally.asked, tally.ahead, tally.later, tally.settled + ); + assert!(tally.ahead > rounds / 4, "{} of {}", tally.ahead, tally.asked); +} diff --git a/crates/lucisv_server/src/server/tests/fast_actions_differential.rs b/crates/lucisv_server/src/server/tests/fast_actions_differential.rs new file mode 100644 index 0000000..1f5ed25 --- /dev/null +++ b/crates/lucisv_server/src/server/tests/fast_actions_differential.rs @@ -0,0 +1,375 @@ +//! **Early answers are settled answers** — the safety net of +//! `docs/features/fast-actions/README.md`. +//! +//! Two servers. The *early* one has an empty index (its root is an empty +//! directory, workspace scope, so opening a buffer widens nothing): the worst +//! case a request answered ahead of a scan can meet. It is asked mid-scan, +//! through the real loop body (`process_batch` with a rescan pretended to be +//! running), so what goes ahead is decided by the real gate. The *settled* one +//! has indexed the whole tree and answers through the ordinary dispatch. At +//! every identifier (and a sample of the other tokens) of every sampled file, +//! for every request kind the gate can let through: whenever the early server +//! answered, its answer must **equal** the settled one, `null` and `[]` +//! included. When it did not answer it held the request, which is always +//! allowed — and is counted, so a gate that lets nothing through cannot pass. +//! +//! The fast subset runs over a fixture written for the shapes the locality +//! rule names; the ignored long run over real trees named by +//! `LUCISV_FAST_ACTIONS_TREES` (`:`-separated roots — scratch **copies**, +//! never a cache), seeded by `LUCISV_FAST_ACTIONS_SEED`: +//! +//! ```text +//! LUCISV_FAST_ACTIONS_TREES=/scratch/corpus:/scratch/ot-hw LUCISV_FAST_ACTIONS_SEED=7 \ +//! tools/guard.sh -- cargo test --release -p lucisv_server early_answers_equal_settled \ +//! -- --ignored --nocapture +//! ``` + +use std::collections::BTreeMap; + +use lsp_server::Response; +use lsp_types::request::{ + DocumentHighlightRequest, DocumentSymbolRequest, FoldingRangeRequest, GotoDefinition, + GotoTypeDefinition, HoverRequest, LinkedEditingRange, PrepareRenameRequest, References, + SelectionRangeRequest, SignatureHelpRequest, +}; +use lsp_types::Position; +use serde_json::json; +use vlog_parser::token::TokenKind; + +use super::*; + +/// The request kinds asked at a position. +const AT_A_POSITION: [&str; 8] = [ + HoverRequest::METHOD, + GotoDefinition::METHOD, + GotoTypeDefinition::METHOD, + DocumentHighlightRequest::METHOD, + References::METHOD, + PrepareRenameRequest::METHOD, + SignatureHelpRequest::METHOD, + LinkedEditingRange::METHOD, +]; + +/// The request kinds asked once per buffer. +const WHOLE_BUFFER: [&str; 3] = + [DocumentSymbolRequest::METHOD, FoldingRangeRequest::METHOD, pairs::SCOPE_PAIRS_METHOD]; + +/// What one comparison run saw, per method: answered early (and equal), +/// waited, and every early answer that differed from the settled one. +#[derive(Default)] +struct Tally { + early: BTreeMap<&'static str, usize>, + waited: BTreeMap<&'static str, usize>, + differed: Vec, +} + +impl Tally { + fn early_total(&self) -> usize { + self.early.values().sum() + } + + fn waited_total(&self) -> usize { + self.waited.values().sum() + } + + fn line(&self) -> String { + let per = |method: &str| { + let (e, w) = (self.early.get(method), self.waited.get(method)); + format!("{method}={}/{}", e.copied().unwrap_or(0), w.copied().unwrap_or(0)) + }; + let all: Vec = AT_A_POSITION + .iter() + .chain(&WHOLE_BUFFER) + .chain([&SelectionRangeRequest::METHOD]) + .map(|m| per(m)) + .collect(); + format!( + "early={} waited={} differed={} (early/waited: {})", + self.early_total(), + self.waited_total(), + self.differed.len(), + all.join(" ") + ) + } +} + +/// The early server: nothing indexed, ever. +fn early_session(empty: &Path) -> Session { + Session::wide(vec![empty.to_path_buf()], false) +} + +/// Ask `early` mid-scan and `settled` settled, and tally the pair. +fn compare( + early: &mut Session, + settled: &mut Session, + method: &'static str, + params: Value, + tally: &mut Tally, +) { + let id = RequestId::from(format!("fa-{method}")); + let asked = Message::Request(lsp_server::Request::new(id, method.to_string(), params.clone())); + early.server.scanning = true; + early.server.answering_a_rescan = true; + early.batch(vec![asked]); + early.server.scanning = false; + early.server.answering_a_rescan = false; + let answers = early.answers(); + if answers.is_empty() { + assert_eq!(early.server.held.len(), 1, "{method}: neither answered nor held"); + early.server.held.clear(); + *tally.waited.entry(method).or_default() += 1; + return; + } + assert_eq!(answers.len(), 1, "{method}: answered once"); + let settled_answer = settled.request(method, ¶ms); + *tally.early.entry(method).or_default() += 1; + if !same(&answers[0], &settled_answer) { + tally.differed.push(format!( + "{method} {params}\n early: {:?}\n settled: {:?}", + answers[0].response_result, settled_answer.response_result + )); + } +} + +/// Two responses say the same thing: the same result, or the same error. +fn same(a: &Response, b: &Response) -> bool { + match (&a.response_result, &b.response_result) { + (Ok(x), Ok(y)) => x == y, + (Err(x), Err(y)) => x.code == y.code && x.message == y.message, + _ => false, + } +} + +/// Every position in `text` worth asking at: the start of each token, the +/// end of each identifier, macro use and keyword, and the middle of each +/// directive and string — of the tokens `pick` keeps. +fn positions(text: &str, mut pick: impl FnMut() -> bool) -> Vec { + let Ok(tokens) = vlog_parser::tokenize(text) else { return Vec::new() }; + let mut out = Vec::new(); + for token in &tokens { + let named = matches!(token.kind, TokenKind::Ident | TokenKind::Keyword); + if !pick() { + continue; + } + out.push(token.span.start); + if named { + out.push(token.span.end); + } + // Inside a directive or a string: an `` `include``'s path is there. + if matches!(token.kind, TokenKind::Directive | TokenKind::String) { + out.push(token.span.start + (token.span.end - token.span.start) / 2); + } + } + out +} + +/// Open `path` in both servers, compare every request kind at `offsets`, and +/// close it again. +fn compare_file( + early: &mut Session, + settled: &mut Session, + path: &Path, + offsets: &[u32], + tally: &mut Tally, +) { + let Ok(text) = std::fs::read_to_string(path) else { return }; + let uri = early.open(path, &text); + settled.open(path, &text); + let doc = early.server.workspace.document(&uri).expect("open"); + let lines = doc.positions(); + let at: Vec = offsets.iter().map(|&o| lines.position(o)).collect(); + for method in WHOLE_BUFFER { + compare(early, settled, method, json!({ "textDocument": { "uri": uri } }), tally); + } + compare( + early, + settled, + SelectionRangeRequest::METHOD, + json!({ "textDocument": { "uri": uri }, "positions": at }), + tally, + ); + for position in &at { + for method in AT_A_POSITION { + let params = json!({ "textDocument": { "uri": uri }, "position": position, + "context": { "includeDeclaration": true } }); + compare(early, settled, method, params, tally); + } + } + for session in [early, settled] { + session.notify( + lsp_types::notification::DidCloseTextDocument::METHOD, + json!({ "textDocument": { "uri": uri } }), + ); + session.drain(); + } +} + +/// The fixture: one file per shape the locality rule names. +fn shapes(tree: &Tree) { + tree.write( + "pkg.sv", + "package p;\n typedef enum logic [1:0] {IDLE, RUN} state_t;\n localparam int W = 4;\n \ + function automatic int twice(int a);\n return a * 2;\n endfunction\nendpackage\n", + ); + tree.write("inc/defs.svh", "`define WIDTH 8\n`define ADD(a, b) ((a) + (b))\n"); + // Found only through an include directory the scan derives. + tree.write("inc/more.svh", "`define MORE 1\n"); + tree.write( + "sub.sv", + "module sub #(parameter int N = 1) (input logic a, output logic b);\n \ + assign b = a;\nendmodule\n", + ); + tree.write( + "top.sv", + "`include \"inc/defs.svh\"\n`include \"more.svh\"\n`define LOCAL 3\nmodule top;\n import p::*;\n \ + state_t st;\n logic [`WIDTH-1:0] w;\n logic [`LOCAL:0] l;\n logic hit;\n \ + sub #(.N(2)) u_sub (.a(st == IDLE), .b(hit));\n \ + always_comb begin : named\n logic t;\n t = w[0];\n end\n \ + always_comb begin\n logic u;\n u = `ADD(1, 2);\n end\n \ + function automatic int g(int x);\n int y;\n y = twice(x) + p::W;\n \ + return y;\n endfunction\n \ + for (genvar i = 0; i < 2; i++) begin : gen_l\n logic q;\n assign q = w[i];\n end\n \ + assign l = p::W;\n wire from_sub = u_sub.b;\n initial $display(\"%0d\", g(1));\nendmodule\n", + ); + tree.write( + "cls.sv", + "class base;\n int m;\n function void hi();\n endfunction\nendclass\n\ + class derived extends base;\n function void go();\n hi();\n m = 1;\n \ + endfunction\nendclass\n", + ); + // One name declared twice: a rename of either is ambiguous, which only + // the index can say. + tree.write("dup_a.sv", "module dup;\nendmodule\n"); + tree.write("dup_b.sv", "module dup;\n logic d;\nendmodule\n"); + tree.write( + "bus.sv", + "interface bus_if;\n logic v;\n modport mp (input v);\nendinterface\n\ + module user (bus_if.mp b, output logic x);\n assign x = b.v;\nendmodule\n", + ); +} + +#[test] +fn early_answers_equal_settled_over_the_locality_shapes() { + let tree = Tree::new("fastactions_shapes"); + shapes(&tree); + let empty = Tree::new("fastactions_shapes_empty"); + // The settled server reads a filelist, whose `+incdir+` is the one way + // `more.svh` resolves — something only a scan learns. + tree.write( + "files.f", + "+incdir+inc\npkg.sv\nsub.sv\ntop.sv\ncls.sv\nbus.sv\ndup_a.sv\ndup_b.sv\n", + ); + let listed = ClientSettings { + index_scope: crate::settings::IndexScope::Workspace, + filelist: Some(tree.path.join("files.f").display().to_string()), + ..Default::default() + }; + let mut settled = Session::started(vec![tree.path.clone()], ClientAbilities::default(), listed); + let mut early = early_session(&empty.path); + let mut tally = Tally::default(); + for file in ["top.sv", "pkg.sv", "sub.sv", "cls.sv", "bus.sv", "dup_a.sv", "inc/defs.svh"] { + let path = tree.path.join(file); + let text = std::fs::read_to_string(&path).expect("fixture"); + compare_file(&mut early, &mut settled, &path, &positions(&text, || true), &mut tally); + } + eprintln!("fast actions over the shapes: {}", tally.line()); + assert!(tally.differed.is_empty(), "{}", tally.differed.join("\n")); + assert!( + tally.early_total() > 500, + "the gate lets the local positions through: {}", + tally.line() + ); + assert!(tally.waited_total() > 50, "and holds the cross-file ones: {}", tally.line()); + for method in [HoverRequest::METHOD, GotoDefinition::METHOD, References::METHOD] { + assert!(tally.early.get(method).is_some_and(|n| *n > 0), "{method} goes ahead somewhere"); + assert!(tally.waited.get(method).is_some_and(|n| *n > 0), "{method} waits somewhere"); + } +} + +/// A seeded generator, so a run can be repeated exactly. +struct Lcg(u64); + +impl Lcg { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + self.0 >> 33 + } + + fn chance(&mut self, per_mille: u64) -> bool { + self.next() % 1000 < per_mille + } +} + +/// Every Verilog source under `root`, sorted, so a seed names the same files. +fn sources(root: &Path) -> Vec { + let mut out = Vec::new(); + let mut stack = vec![root.to_path_buf()]; + while let Some(dir) = stack.pop() { + let Ok(entries) = std::fs::read_dir(&dir) else { continue }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + stack.push(path); + } else if path + .extension() + .is_some_and(|e| ["sv", "svh", "v", "vh"].iter().any(|x| e == *x)) + { + out.push(path); + } + } + } + out.sort(); + out +} + +#[test] +#[ignore = "long: real trees named by LUCISV_FAST_ACTIONS_TREES; run in --release"] +fn early_answers_equal_settled_over_real_trees() { + let Ok(trees) = std::env::var("LUCISV_FAST_ACTIONS_TREES") else { + eprintln!("LUCISV_FAST_ACTIONS_TREES not set — skipping"); + return; + }; + let seed: u64 = + std::env::var("LUCISV_FAST_ACTIONS_SEED").ok().and_then(|s| s.parse().ok()).unwrap_or(7); + let files_per_tree: usize = + std::env::var("LUCISV_FAST_ACTIONS_FILES").ok().and_then(|s| s.parse().ok()).unwrap_or(120); + let mut rng = Lcg(seed); + let empty = Tree::new("fastactions_real_empty"); + let mut total = Tally::default(); + for root in trees.split(':').filter(|r| !r.is_empty()) { + let root = PathBuf::from(root); + let all = sources(&root); + let mut settled = Session::wide(vec![root.clone()], false); + let mut early = early_session(&empty.path); + let mut tally = Tally::default(); + let mut picked = 0; + // Every file has the same chance, until the quota is met. + let per_mille = (files_per_tree * 1000 / all.len().max(1)).clamp(1, 1000) as u64; + for path in &all { + if picked >= files_per_tree || !rng.chance(per_mille) { + continue; + } + picked += 1; + let Ok(text) = std::fs::read_to_string(path) else { continue }; + // A quarter of the tokens of a big file is plenty, every token of + // a small one. + let keep = if text.len() > 40_000 { 250 } else { 1000 }; + let offsets = positions(&text, || rng.chance(keep)); + compare_file(&mut early, &mut settled, path, &offsets, &mut tally); + } + eprintln!( + "fast actions over {} ({picked} files, seed {seed}): {}", + root.display(), + tally.line() + ); + total.differed.extend(tally.differed.iter().take(20).cloned()); + for (m, n) in tally.early { + *total.early.entry(m).or_default() += n; + } + for (m, n) in tally.waited { + *total.waited.entry(m).or_default() += n; + } + } + eprintln!("fast actions, all trees: {}", total.line()); + assert!(total.differed.is_empty(), "{}", total.differed.join("\n")); +} diff --git a/crates/lucisv_server/src/server/tests/fast_actions_precondition.rs b/crates/lucisv_server/src/server/tests/fast_actions_precondition.rs new file mode 100644 index 0000000..aadc2d0 --- /dev/null +++ b/crates/lucisv_server/src/server/tests/fast_actions_precondition.rs @@ -0,0 +1,545 @@ +//! The precondition for answering ahead, one clause at a time +//! (`Server::answer_from_the_buffer`, `docs/features/fast-actions/README.md`, +//! "When a request is answered early"). A request that breaks exactly one +//! clause must **wait**, and is then answered exactly once, with what the +//! settled server says; one that breaks none goes ahead with that same +//! answer. The first tests are QA's S1 in the forms it was found in. + +use lsp_types::notification::Cancel; + +use super::super::ahead::{Reach, REACH}; +use super::super::probe; +use super::scan_ordering::{created, ordering_tree}; +use super::*; + +/// `a.sv` with a signal named `signal`, 1.5 KB: over a 1 000-byte +/// `largeFile.threshold`, under the 4 MiB default. +fn wide(signal: &str) -> String { + let text = format!( + "module qa_a;\n logic {signal};\nendmodule\n{}", + "// padding padding padding\n".repeat(55) + ); + assert!(text.len() > 1000 && text.len() < 2000); + text +} + +fn threshold(bytes: u64) -> Value { + serde_json::json!({ "index": { "scope": "workspace" }, "largeFile": { "threshold": bytes } }) +} + +fn note(method: &str, params: Value) -> Message { + Message::Notification(Notification::new(method.to_string(), params)) +} + +/// A `didChangeConfiguration` carrying `section` as the `lucisv` settings. +fn push(section: Value) -> Message { + note(DidChangeConfiguration::METHOD, serde_json::json!({ "settings": { "lucisv": section } })) +} + +/// The client's answer to the settings pull `id`. +fn settings_answer(id: &RequestId, section: Value) -> Message { + Message::Response(Response::new_ok(id.clone(), serde_json::json!([section]))) +} + +fn ask(id: i32, method: &str, params: Value) -> Message { + Message::Request(Request::new(RequestId::from(id), method.to_string(), params)) +} + +/// A hover on the signal `wide` declares. +fn hover(id: i32, uri: &Uri) -> Message { + let at = serde_json::json!({ "line": 1, "character": 10 }); + ask( + id, + HoverRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": uri }, "position": at }), + ) +} + +/// A request no buffer answers alone: it is held, and the burst behind it. +fn lens(id: i32, uri: &Uri) -> Message { + ask(id, CodeLensRequest::METHOD, serde_json::json!({ "textDocument": { "uri": uri } })) +} + +fn opened(uri: &Uri, text: &str) -> Message { + note( + DidOpenTextDocument::METHOD, + serde_json::json!({ "textDocument": { + "uri": uri, "languageId": "systemverilog", "version": 1, "text": text, + }}), + ) +} + +/// A session with `a.sv` (see [`wide`]) open, against a client that said +/// `abilities`. +fn session_with(name: &str, abilities: ClientAbilities) -> (Tree, Session, Uri) { + let tree = Tree::new(name); + tree.write("a.sv", &wide("sig_a")); + tree.write("b.sv", "module qa_b;\nendmodule\n"); + let mut session = Session::wide_with(vec![tree.path.clone()], abilities); + let uri = session.open(&tree.path.join("a.sv"), &wide("sig_a")); + let _ = probe::take_ahead(); + (tree, session, uri) +} + +fn session(name: &str) -> (Tree, Session, Uri) { + let (tree, session, uri) = session_with(name, ClientAbilities::default()); + session.drain(); + (tree, session, uri) +} + +/// One burst through the loop body with a rescan pretended to be running. +fn mid_rescan(session: &mut Session, burst: Vec) { + session.server.scanning = true; + session.server.answering_a_rescan = true; + session.batch(burst); + session.server.scanning = false; + session.server.answering_a_rescan = false; + session.server.rescan_wanted = false; + session.server.head_owed = false; + session.server.opened_mid_scan = false; +} + +/// What `run` does once the rescan is over: replay what was held. +fn settle(session: &mut Session) { + while !session.server.held.is_empty() { + let held = std::mem::take(&mut session.server.held); + session.batch(held); + } +} + +/// The result sent for request `id`, which must have been answered once. +fn the_answer(sent: &[Message], id: i32) -> Value { + let mine: Vec<&Response> = sent + .iter() + .filter_map(|m| match m { + Message::Response(r) if r.id == RequestId::from(id) => Some(r), + _ => None, + }) + .collect(); + assert_eq!(mine.len(), 1, "request {id} is answered exactly once: {sent:#?}"); + mine[0].response_result.clone().expect("a result") +} + +/// The hover asked again, with nothing waiting. +fn asked_again(session: &mut Session, uri: &Uri) -> Value { + session.batch(vec![hover(99, uri)]); + the_answer(&session.drain(), 99) +} + +/// A rescan holds `[lens, older…, hover]`: whether the hover went ahead, and +/// its one answer — which must be what the settled server then says. +fn behind(session: &mut Session, uri: &Uri, older: Vec) -> (bool, Value) { + let mut burst = vec![lens(1, uri)]; + burst.extend(older); + burst.push(hover(2, uri)); + mid_rescan(session, burst); + let early = probe::take_ahead().contains(&RequestId::from(2)); + settle(session); + let first = the_answer(&session.drain(), 2); + assert_eq!(first, asked_again(session, uri), "the answer the settled server gives"); + (early, first) +} + +fn waits_behind(session: &mut Session, uri: &Uri, older: Vec) -> Value { + let (early, answer) = behind(session, uri, older); + assert!(!early, "answered ahead of an older message that was not applied"); + answer +} + +fn goes_ahead_of(session: &mut Session, uri: &Uri, older: Vec) -> Value { + let (early, answer) = behind(session, uri, older); + assert!(early, "nothing ahead of it can change its buffer: it need not wait"); + answer +} + +// --------------------------------------------------------------------- +// S1: a settings push ahead of the request, in one burst +// --------------------------------------------------------------------- + +#[test] +fn a_hover_behind_an_edit_and_a_threshold_push_in_its_burst_is_answered_after_both() { + // QA's `dirtypush2.py`: the edit used to be analyzed under the old + // threshold for the hover, *before* the push behind it was applied. + let (_tree, mut session, uri) = session("fa_pre_s1_dirty"); + session.batch(vec![changed(&uri, 2, &wide("sig_b")), push(threshold(1000)), hover(1, &uri)]); + assert_eq!(the_answer(&session.drain(), 1), Value::Null, "the buffer is large by then"); + assert_eq!(asked_again(&mut session, &uri), Value::Null); + assert!(probe::take_ahead().is_empty(), "nothing went ahead of an older notification"); +} + +#[test] +fn a_hover_behind_a_threshold_push_in_its_burst_is_answered_after_it() { + // The clean-buffer form. + let (_tree, mut session, uri) = session("fa_pre_s1_clean"); + session.batch(vec![push(threshold(1000)), hover(1, &uri)]); + assert_eq!(the_answer(&session.drain(), 1), Value::Null); + assert_eq!(asked_again(&mut session, &uri), Value::Null); +} + +#[test] +fn a_hover_goes_ahead_of_a_watcher_event_in_its_burst_but_not_of_a_push_beside_it() { + // The same rule at the third place an older message can be unapplied: + // the next notification of the request's own burst. + let (tree, mut session, uri) = session_with("fa_pre_trigger", watching_progress()); + session.drain(); + let order = |session: &Session, id: i32| { + let sent = session.drain(); + let at = |wanted: &dyn Fn(&Message) -> bool| sent.iter().position(wanted).expect("sent"); + let answered = at(&|m| matches!(m, Message::Response(r) if r.id == RequestId::from(id))); + let bar = at(&|m| matches!(m, Message::Notification(n) if n.method == Progress::METHOD)); + (answered < bar, the_answer(&sent, id)) + }; + // A watcher event cannot change the buffer: the hover need not ride the + // rescan it starts. + tree.package("new1.sv", "fresh1"); + session.batch(vec![created(&tree.path.join("new1.sv")), hover(1, &uri)]); + let (before_the_rescan, card) = order(&session, 1); + assert!(before_the_rescan, "answered before the rescan began"); + assert_eq!(probe::take_ahead(), vec![RequestId::from(1)]); + assert_eq!(card, asked_again(&mut session, &uri)); + assert_eq!(indexed(&session, "fresh1"), 1, "premise: the rescan ran"); + // A push between the two can: the hover is answered behind it. + tree.package("new2.sv", "fresh2"); + let burst = vec![created(&tree.path.join("new2.sv")), push(threshold(1000)), hover(2, &uri)]; + session.batch(burst); + let (before_the_rescan, answer) = order(&session, 2); + assert!(!before_the_rescan && probe::take_ahead().is_empty()); + assert_eq!(answer, Value::Null, "large, as the push ahead of it said"); + // A push in front of the event is applied by then, and its effect seen. + tree.package("new3.sv", "fresh3"); + let burst = vec![push(threshold(0)), created(&tree.path.join("new3.sv")), hover(3, &uri)]; + session.batch(burst); + let (before_the_rescan, card) = order(&session, 3); + assert!(before_the_rescan, "ahead of the event, behind the push"); + assert!(card.to_string().contains("sig_a"), "{card}"); + assert_eq!(card, asked_again(&mut session, &uri)); +} + +// --------------------------------------------------------------------- +// (b) every older message that can change the buffer's answer is applied +// --------------------------------------------------------------------- + +#[test] +fn it_waits_behind_a_held_threshold_push() { + // The same hole S1 came through, by the other door: the push is held + // behind a request, the hover behind the push. + let (_tree, mut session, uri) = session("fa_pre_heldpush"); + assert_eq!(waits_behind(&mut session, &uri, vec![push(threshold(1000))]), Value::Null); +} + +#[test] +fn it_waits_behind_a_held_push_that_changes_nothing_it_reads() { + // Which settings a push moves is not read off the wire: every push waits. + let (_tree, mut session, uri) = session("fa_pre_heldsame"); + let card = waits_behind(&mut session, &uri, vec![push(threshold(4 * 1024 * 1024))]); + assert!(card.to_string().contains("sig_a"), "{card}"); +} + +#[test] +fn it_waits_behind_a_held_settings_answer() { + // A client that answers the startup's pull late: the answer is a + // response, never held on its own — but a burst behind a held request + // takes it along. + let pulling = ClientAbilities { configuration: true, ..Default::default() }; + let (_tree, mut session, uri) = session_with("fa_pre_heldanswer", pulling); + let (pull, _) = configuration_request(&session); + let answer = settings_answer(&pull, threshold(1000)); + assert_eq!(waits_behind(&mut session, &uri, vec![answer]), Value::Null); +} + +#[test] +fn it_waits_behind_a_settings_answer_in_the_tail_of_the_burst_that_started_the_rescan() { + // `[created, settings answer]`: the rescan runs with the answer still + // unapplied behind its trigger, and a hover arriving mid-scan is newer + // than both. + let tree = ordering_tree("fa_pre_tailanswer"); + tree.write("a/a.sv", &wide("sig_a")); + let abilities = ClientAbilities { configuration: true, ..watching_progress() }; + let mut session = Session::wide_with(vec![tree.path.clone()], abilities); + let uri = session.open(&tree.path.join("a/a.sv"), &wide("sig_a")); + let (pull, _) = configuration_request(&session); + tree.package("z/new.sv", "new"); + let _ = (probe::take_counts(), probe::take_ahead()); + probe::script([vec![hover(2, &uri)]]); + session + .batch(vec![created(&tree.path.join("z/new.sv")), settings_answer(&pull, threshold(1000))]); + assert!(probe::unarrived().is_empty(), "premise: the hover arrived mid-scan"); + assert!(probe::take_ahead().is_empty(), "not ahead of the unapplied answer"); + settle(&mut session); + assert_eq!(the_answer(&session.drain(), 2), Value::Null); + assert_eq!(asked_again(&mut session, &uri), Value::Null); +} + +#[test] +fn a_push_does_not_overtake_an_older_settings_answer_that_is_held() { + // The answer is a state change like any notification: a newer push must + // not be applied in front of it, or the older settings win. + let pulling = ClientAbilities { configuration: true, ..Default::default() }; + let (_tree, mut session, uri) = session_with("fa_pre_order", pulling); + let (pull, _) = configuration_request(&session); + session.server.scanning = true; + session.server.answering_a_rescan = true; + session.batch(vec![lens(1, &uri), settings_answer(&pull, threshold(1000))]); + session.batch(vec![push(threshold(0))]); + session.server.scanning = false; + session.server.answering_a_rescan = false; + session.server.rescan_wanted = false; + settle(&mut session); + let card = asked_again(&mut session, &uri); + assert!(card.to_string().contains("sig_a"), "the push was the client's last word: {card}"); +} + +#[test] +fn a_settings_answer_does_not_overtake_an_older_push_that_is_held() { + // The mirror image: the answer arrives in a burst of its own while a + // rescan holds an older push. A response is not held as such — but this + // one is a state change, and the push is older. + let pulling = ClientAbilities { configuration: true, ..Default::default() }; + let (_tree, mut session, uri) = session_with("fa_pre_order2", pulling); + let (pull, _) = configuration_request(&session); + session.server.scanning = true; + session.server.answering_a_rescan = true; + session.batch(vec![lens(1, &uri), push(threshold(0))]); + session.batch(vec![settings_answer(&pull, threshold(1000))]); + session.server.scanning = false; + session.server.answering_a_rescan = false; + session.server.rescan_wanted = false; + settle(&mut session); + assert_eq!(asked_again(&mut session, &uri), Value::Null, "the answer was the last word"); +} + +#[test] +fn it_waits_while_the_settings_a_client_announced_have_not_been_answered() { + // The pull model: an empty push says "ask me", and until the answer + // lands the settings in force are known to be stale. + let pulling = ClientAbilities { configuration: true, ..Default::default() }; + let (_tree, mut session, uri) = session_with("fa_pre_announced", pulling); + session.drain(); + // The startup's pull was never answered; that alone holds nothing back. + mid_rescan(&mut session, vec![lens(1, &uri), hover(2, &uri)]); + assert_eq!(probe::take_ahead(), vec![RequestId::from(2)]); + settle(&mut session); + session.drain(); + + session + .batch(vec![note(DidChangeConfiguration::METHOD, serde_json::json!({ "settings": null }))]); + let (pull, _) = configuration_request(&session); + // Only the pull's own answer ends the wait: an answer to anything else + // the server asked says nothing about the settings (QA, escalation round). + let stray = Response::new_ok(RequestId::from(987_654), Value::Null); + session.batch(vec![Message::Response(stray)]); + mid_rescan(&mut session, vec![lens(3, &uri), hover(4, &uri)]); + assert!(probe::take_ahead().is_empty(), "the announced settings are still in flight"); + session.batch(vec![settings_answer(&pull, threshold(1000))]); + settle(&mut session); + assert_eq!(the_answer(&session.drain(), 4), Value::Null); + assert_eq!(asked_again(&mut session, &uri), Value::Null); + // Answered: the path is open again. + mid_rescan(&mut session, vec![lens(5, &uri), hover(6, &uri)]); + assert_eq!(probe::take_ahead(), vec![RequestId::from(6)]); +} + +#[test] +fn it_waits_behind_a_held_change_close_reopen_or_save_of_its_own_buffer() { + let doc = |uri: &Uri| serde_json::json!({ "textDocument": { "uri": uri } }); + let (_tree, mut session, uri) = session("fa_pre_own"); + let card = waits_behind(&mut session, &uri, vec![changed(&uri, 2, &wide("sig_b"))]); + assert!(card.to_string().contains("sig_b"), "{card}"); + let reopened = + vec![note(DidCloseTextDocument::METHOD, doc(&uri)), opened(&uri, &wide("sig_c"))]; + let card = waits_behind(&mut session, &uri, reopened); + assert!(card.to_string().contains("sig_c"), "{card}"); + let saved = serde_json::json!({ "textDocument": { "uri": uri }, "text": wide("sig_d") }); + let card = waits_behind(&mut session, &uri, vec![note(DidSaveTextDocument::METHOD, saved)]); + assert!(card.to_string().contains("sig_d"), "{card}"); + let closed = vec![note(DidCloseTextDocument::METHOD, doc(&uri))]; + assert_eq!(waits_behind(&mut session, &uri, closed), Value::Null, "(a): no longer open"); +} + +#[test] +fn it_waits_behind_every_held_notification_not_proven_to_leave_its_buffer_alone() { + let (tree, mut session, uri) = session("fa_pre_any"); + let elsewhere = path_to_uri(&tree.path.join("gone.sv")).expect("uri"); + let folder = serde_json::json!({ "uri": path_to_uri(&tree.path.join("more")).expect("uri"), + "name": "more" }); + let others = [ + note( + DidChangeWorkspaceFolders::METHOD, + serde_json::json!({ "event": { "added": [folder], "removed": [] } }), + ), + note( + DidRenameFiles::METHOD, + serde_json::json!({ "files": [{ "oldUri": elsewhere, "newUri": elsewhere }] }), + ), + note(DidDeleteFiles::METHOD, serde_json::json!({ "files": [{ "uri": elsewhere }] })), + // A notification the server does not know is not known to be safe. + note("$/setTrace", serde_json::json!({ "value": "off" })), + // Nor is one that should name a buffer and does not. + note(DidChangeTextDocument::METHOD, serde_json::json!({ "contentChanges": [] })), + ]; + for other in others { + let card = waits_behind(&mut session, &uri, vec![other]); + assert!(card.to_string().contains("sig_a"), "{card}"); + } +} + +#[test] +fn it_goes_ahead_of_held_messages_that_cannot_change_its_buffer() { + let (tree, mut session, uri) = session("fa_pre_other"); + let b = session.open(&tree.path.join("b.sv"), "module qa_b;\nendmodule\n"); + session.drain(); + tree.package("new.sv", "fresh_pkg"); + let others = [ + // Another buffer's edit, another buffer opened. + changed(&b, 2, "module qa_b;\n logic x;\nendmodule\n"), + opened(&path_to_uri(&tree.path.join("c.sv")).expect("uri"), "module qa_c;\nendmodule\n"), + // What is on disk moves the index, never a buffer's own analysis — + // not even when it names the buffer's own file. + created(&tree.path.join("new.sv")), + created(&tree.path.join("a.sv")), + // A cancel for something else, and an answer the server acts on + // without touching a buffer. + note(Cancel::METHOD, serde_json::json!({ "id": 12345 })), + Message::Response(Response::new_ok(RequestId::from("nobody".to_string()), Value::Null)), + ]; + for other in others { + let card = goes_ahead_of(&mut session, &uri, vec![other]); + assert!(card.to_string().contains("sig_a"), "{card}"); + } +} + +// --------------------------------------------------------------------- +// (a) open, (c) analyzed under the settings in force, (d) not in staging +// --------------------------------------------------------------------- + +#[test] +fn a_buffer_that_is_not_open_is_not_answered_ahead() { + let (tree, mut session, _) = session("fa_pre_closed"); + let never = path_to_uri(&tree.path.join("b.sv")).expect("uri"); + mid_rescan(&mut session, vec![hover(2, &never)]); + assert!(probe::take_ahead().is_empty()); + settle(&mut session); + assert_eq!(the_answer(&session.drain(), 2), Value::Null); +} + +#[test] +fn a_dirty_buffer_is_analyzed_for_it_under_the_settings_in_force() { + let (_tree, mut session, uri) = session("fa_pre_inforce"); + session.batch(vec![push(threshold(1000))]); + session.batch(vec![changed(&uri, 2, &wide("sig_b"))]); + assert_eq!(session.server.dirty.len(), 1, "premise: the edit is not analyzed yet"); + assert_eq!(goes_ahead_of(&mut session, &uri, Vec::new()), Value::Null, "large, as pushed"); + session.batch(vec![push(threshold(0))]); + session.batch(vec![changed(&uri, 3, &wide("sig_c"))]); + let card = goes_ahead_of(&mut session, &uri, Vec::new()); + assert!(card.to_string().contains("sig_c"), "{card}"); +} + +#[test] +fn what_staging_held_behind_a_push_is_not_released_ahead_of_it() { + // `[open, lens, push, hover]`, then the pull's answer: the settings have + // landed, but the hover is still behind a push nobody has applied. + let tree = Tree::new("fa_pre_staged"); + tree.write("a.sv", &wide("sig_a")); + let uri = path_to_uri(&tree.path.join("a.sv")).expect("uri"); + let pull = RequestId::from("lucisv-0".to_string()); + let queued = vec![ + opened(&uri, &wide("sig_a")), + lens(1, &uri), + push(threshold(1000)), + hover(2, &uri), + settings_answer(&pull, threshold(0)), + ]; + let abilities = ClientAbilities { configuration: true, ..Default::default() }; + let _ = probe::take_ahead(); + let mut session = + Session::staged(vec![tree.path.clone()], abilities, false, CONFIGURATION_WAIT, queued); + assert!(probe::take_ahead().is_empty(), "not ahead of the push it was sent behind"); + settle(&mut session); + assert_eq!(the_answer(&session.drain(), 2), Value::Null); + assert_eq!(asked_again(&mut session, &uri), Value::Null); +} + +// --------------------------------------------------------------------- +// the colours: a guess is always recorded as one +// --------------------------------------------------------------------- + +#[test] +fn colours_answered_ahead_of_a_waiting_index_change_are_checked_once_it_has_landed() { + // No scan is running, but something is held — as when a replayed message + // started a rescan that held newer ones — so the burst waits, and a + // `full` goes ahead of the watcher event that will give `W` a meaning. + let tree = Tree::new("fa_pre_colours"); + let top = "module top;\n import p::*;\n logic [W-1:0] x;\nendmodule\n"; + tree.write("top.sv", top); + let refreshing = ClientAbilities { semantic_tokens_refresh: true, ..Default::default() }; + let mut session = Session::wide_with(vec![tree.path.clone()], refreshing); + let uri = session.open(&tree.path.join("top.sv"), top); + session.server.refresh_tokens_if_stale(); + let full = |id: i32| { + let params = serde_json::json!({ "textDocument": { "uri": uri } }); + ask(id, SemanticTokensFullRequest::METHOD, params) + }; + let _ = (session.drain(), probe::take_ahead()); + tree.write("p.sv", "package p;\n localparam int W = 4;\nendpackage\n"); + session.server.held = vec![lens(7, &uri)]; + session.batch(vec![lens(1, &uri), created(&tree.path.join("p.sv")), full(2)]); + assert_eq!(probe::take_ahead(), vec![RequestId::from(2)], "premise: the colours went ahead"); + let guess = the_answer(&session.drain(), 2); + settle(&mut session); + session.server.refresh_tokens_if_stale(); + let sent = session.drain(); + let refreshes = sent + .iter() + .filter( + |m| matches!(m, Message::Request(r) if r.method == "workspace/semanticTokens/refresh"), + ) + .count(); + session.batch(vec![full(3)]); + let settled = the_answer(&session.drain(), 3); + assert_ne!(guess["data"], settled["data"], "premise: the event changed the colours"); + assert_eq!(refreshes, 1, "so the client is asked to fetch them again"); +} + +// --------------------------------------------------------------------- +// the table the rule is read from +// --------------------------------------------------------------------- + +/// The `X::METHOD =>` arms of `handle_notification`'s table. +fn handled_notifications() -> Vec { + include_str!("../notification.rs") + .lines() + .filter_map(|line| line.trim().split_once("::METHOD =>")) + .map(|(path, _)| path.rsplit("::").next().unwrap_or(path).to_string()) + .collect() +} + +#[test] +fn every_notification_the_server_handles_says_which_buffers_it_can_reach() { + use lsp_types::notification::Notification as _; + let named = |type_name: &str| match type_name { + "DidOpenTextDocument" => DidOpenTextDocument::METHOD, + "DidChangeTextDocument" => DidChangeTextDocument::METHOD, + "DidSaveTextDocument" => DidSaveTextDocument::METHOD, + "DidCloseTextDocument" => DidCloseTextDocument::METHOD, + "DidChangeWatchedFiles" => DidChangeWatchedFiles::METHOD, + "DidRenameFiles" => DidRenameFiles::METHOD, + "DidDeleteFiles" => DidDeleteFiles::METHOD, + "DidChangeConfiguration" => DidChangeConfiguration::METHOD, + "DidChangeWorkspaceFolders" => DidChangeWorkspaceFolders::METHOD, + other => panic!("a new notification arm, {other}: give it a row in `ahead::REACH`"), + }; + let mut handled: Vec<&str> = handled_notifications().iter().map(|n| named(n)).collect(); + // The loop consumes a cancel itself, before the table. + handled.push(Cancel::METHOD); + handled.sort_unstable(); + let mut rows: Vec<&str> = REACH.iter().map(|(method, _)| *method).collect(); + rows.sort_unstable(); + assert_eq!(rows, handled, "one row per notification the server handles, and no other"); + assert!(handled.len() >= 10, "the arms were found: {handled:?}"); + // Only the four that replace one buffer's text may be judged by name. + let by_name: Vec<&str> = + REACH.iter().filter(|(_, reach)| *reach == Reach::Named).map(|(m, _)| *m).collect(); + assert_eq!(by_name.len(), 4, "{by_name:?}"); + assert!(by_name.iter().all(|m| m.starts_with("textDocument/did")), "{by_name:?}"); +} diff --git a/crates/lucisv_server/src/server/tests/fast_actions_staging.rs b/crates/lucisv_server/src/server/tests/fast_actions_staging.rs new file mode 100644 index 0000000..c79a062 --- /dev/null +++ b/crates/lucisv_server/src/server/tests/fast_actions_staging.rs @@ -0,0 +1,233 @@ +//! Same file first **around the settings answer** (QA Q1 and R1 of +//! `docs/features/fast-actions/README.md`): the one setting a buffer's +//! `Document` depends on is `largeFile.threshold`, read where the buffer is +//! analyzed. A buffer analyzed before the startup's settings answer — opened +//! then, or edited and flushed then — is re-analyzed when the answer +//! classifies it differently, and so is every open buffer whenever the +//! threshold changes later; whatever was asked meanwhile is answered as a +//! server given the settings first answers it, and right after the answer. + +use super::*; + +/// The startup pull's answer (`lucisv-0`: the first request a staged session +/// makes), carrying `section` as the `lucisv` settings. +fn settings(section: Value) -> Message { + Message::Response(Response::new_ok( + RequestId::from("lucisv-0".to_string()), + serde_json::json!([section]), + )) +} + +fn threshold(bytes: u64) -> Value { + serde_json::json!({ "index": { "scope": "workspace" }, "largeFile": { "threshold": bytes } }) +} + +fn opened(uri: &Uri, text: &str) -> Message { + Message::Notification(lsp_server::Notification::new( + DidOpenTextDocument::METHOD.to_string(), + serde_json::json!({ "textDocument": { + "uri": uri, "languageId": "systemverilog", "version": 1, "text": text, + }}), + )) +} + +/// A hover on `sig_a`, line 1. +fn hover(id: i32, uri: &Uri) -> Message { + Message::Request(Request::new( + RequestId::from(id), + HoverRequest::METHOD.to_string(), + serde_json::json!({ "textDocument": { "uri": uri }, + "position": { "line": 1, "character": 10 } }), + )) +} + +const SMALL: &str = "module qa_a;\n logic sig_a;\nendmodule\n"; + +/// The result a session sent for request `id`. +fn answer(sent: &[Message], id: i32) -> Value { + sent.iter() + .find_map(|m| match m { + Message::Response(r) if r.id == RequestId::from(id) => { + Some(r.response_result.clone().expect("a result")) + } + _ => None, + }) + .unwrap_or_else(|| panic!("request {id} answered: {sent:#?}")) +} + +/// A staged session that has sent, in one burst before the settings answer: +/// `before`, a hover, then the answer `section`. Returns the hover's answer, +/// whether it was sent before anything the startup held was replayed, and a +/// hover asked again once everything has settled. +fn staged(tree: &Tree, before: Vec, section: Value) -> (Value, bool, Value) { + let uri = path_to_uri(&tree.path.join("a.sv")).expect("uri"); + let mut queued = before; + queued.push(hover(1, &uri)); + queued.push(settings(section)); + let abilities = ClientAbilities { configuration: true, ..Default::default() }; + let mut session = + Session::staged(vec![tree.path.clone()], abilities, false, CONFIGURATION_WAIT, queued); + let mut sent = session.drain(); + let at_once = + sent.iter().any(|m| matches!(m, Message::Response(r) if r.id == RequestId::from(1))); + // What `run` does next: replay whatever the startup held. + let held = std::mem::take(&mut session.server.held); + session.batch(held); + sent.extend(session.drain()); + let first = answer(&sent, 1); + session.batch(vec![hover(2, &uri)]); + let again = answer(&session.drain(), 2); + (first, at_once, again) +} + +/// What a session that had the settings first answers for the same buffer. +fn fresh(tree: &Tree, bytes: u64, text: &str) -> Value { + let settled = ClientSettings { + index_scope: crate::settings::IndexScope::Workspace, + large_file_threshold: bytes, + ..Default::default() + }; + let mut session = + Session::started(vec![tree.path.clone()], ClientAbilities::default(), settled); + let uri = session.open(&tree.path.join("a.sv"), text); + session.batch(vec![hover(3, &uri)]); + answer(&session.drain(), 3) +} + +#[test] +fn a_buffer_edited_before_a_small_threshold_arrives_is_not_analyzed_for_an_early_answer() { + // Default threshold 4 MiB, the user's 300 bytes: the edit makes the + // buffer large under the user's settings and only under them. + let tree = Tree::new("fa_stage_small"); + tree.write("a.sv", SMALL); + let uri = path_to_uri(&tree.path.join("a.sv")).expect("uri"); + let big = format!("{SMALL}{}", "// padding padding padding\n".repeat(30)); + assert!(big.len() > 300 && big.len() < 4 * 1024 * 1024); + let (first, _, again) = + staged(&tree, vec![opened(&uri, SMALL), changed(&uri, 2, &big)], threshold(300)); + assert_eq!(first, Value::Null, "the large-file answer, not a card built under the defaults"); + assert_eq!(again, Value::Null, "and the buffer stays on the fast path"); + assert_eq!(first, fresh(&tree, 300, &big), "what a session given the settings first says"); +} + +#[test] +fn a_buffer_edited_before_a_large_threshold_arrives_is_not_put_on_the_fast_path() { + // The other direction: the default calls a 5 MiB buffer large, the + // user's 8 MiB threshold does not. + let tree = Tree::new("fa_stage_large"); + tree.write("a.sv", SMALL); + let uri = path_to_uri(&tree.path.join("a.sv")).expect("uri"); + let big = format!("{SMALL}/*{}*/\n", "x".repeat(5 * 1024 * 1024)); + let (first, _, again) = staged( + &tree, + vec![opened(&uri, SMALL), changed(&uri, 2, &big)], + threshold(8 * 1024 * 1024), + ); + let card = first.to_string(); + assert!(card.contains("sig_a"), "analyzed under the user's threshold: {card}"); + assert_eq!(first, again); + assert_eq!(first, fresh(&tree, 8 * 1024 * 1024, &big)); +} + +#[test] +fn a_buffer_opened_before_a_small_threshold_arrives_answers_as_a_fresh_server_does() { + // Opened in staging, it is analyzed under the 4 MiB default; the answer + // says 10 bytes, so it is re-analyzed onto the fast path — and the hover + // asked before the answer is answered right after it, from that. + let tree = Tree::new("fa_stage_open"); + tree.write("a.sv", SMALL); + let uri = path_to_uri(&tree.path.join("a.sv")).expect("uri"); + let (first, at_once, again) = staged(&tree, vec![opened(&uri, SMALL)], threshold(10)); + assert_eq!(first, fresh(&tree, 10, SMALL), "what a server given the settings first says"); + assert_eq!(first, Value::Null); + assert_eq!(first, again); + assert!(at_once, "answered when the settings landed, not after the scan's head phase"); +} + +#[test] +fn a_buffer_opened_before_a_large_threshold_arrives_leaves_the_fast_path() { + let tree = Tree::new("fa_stage_open_big"); + let big = format!("{SMALL}/*{}*/\n", "x".repeat(5 * 1024 * 1024)); + tree.write("a.sv", &big); + let uri = path_to_uri(&tree.path.join("a.sv")).expect("uri"); + let (first, _, again) = staged(&tree, vec![opened(&uri, &big)], threshold(8 * 1024 * 1024)); + assert!(first.to_string().contains("sig_a"), "analyzed in full: {first}"); + assert_eq!(first, again); + assert_eq!(first, fresh(&tree, 8 * 1024 * 1024, &big)); +} + +#[test] +fn a_buffer_edited_and_flushed_by_another_open_before_the_settings_is_reclassified() { + // QA's s6: the edit to `a.sv` is flushed — under the default threshold — + // by the `didOpen` of `b.sv` applied during staging. + let tree = Tree::new("fa_stage_flushed"); + tree.write("a.sv", SMALL); + tree.write("b.sv", "module qa_b;\nendmodule\n"); + let uri = path_to_uri(&tree.path.join("a.sv")).expect("uri"); + let b = path_to_uri(&tree.path.join("b.sv")).expect("uri"); + let big = format!("{SMALL}{}", "// padding padding padding\n".repeat(30)); + let before = + vec![opened(&uri, SMALL), changed(&uri, 2, &big), opened(&b, "module qa_b;\nendmodule\n")]; + let (first, _, again) = staged(&tree, before, threshold(300)); + assert_eq!(first, Value::Null); + assert_eq!(again, Value::Null); + assert_eq!(first, fresh(&tree, 300, &big)); +} + +/// A settled session with `a.sv` open, and the hover on it after a +/// `didChangeConfiguration` push of `section`; the parses the push cost. +fn pushed(session: &mut Session, uri: &Uri, section: Value, id: i32) -> (Value, u64) { + let parses = vlog_parser::stats::parses(); + session.notify( + lsp_types::notification::DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": section } }), + ); + let cost = vlog_parser::stats::parses() - parses; + session.drain(); + session.batch(vec![hover(id, uri)]); + (answer(&session.drain(), id), cost) +} + +#[test] +fn a_threshold_changed_mid_session_moves_an_open_buffer_both_ways_and_nothing_else_does() { + let tree = Tree::new("fa_stage_mid"); + tree.write("a.sv", SMALL); + let mut session = Session::wide(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("a.sv"), SMALL); + session.drain(); + let (card, _) = pushed(&mut session, &uri, threshold(4 * 1024 * 1024), 1); + assert!(card.to_string().contains("sig_a"), "{card}"); + let (down, cost) = pushed(&mut session, &uri, threshold(10), 2); + assert_eq!(down, Value::Null, "onto the fast path, as a fresh server says"); + assert_eq!(down, fresh(&tree, 10, SMALL)); + assert_eq!(cost, 1, "the one buffer that changed mode, re-analyzed once"); + let (up, cost) = pushed(&mut session, &uri, threshold(4 * 1024 * 1024), 3); + assert_eq!(up, card, "back off it"); + assert_eq!(cost, 1, "the one buffer that changed mode, parsed once"); + let (same, cost) = pushed(&mut session, &uri, threshold(4 * 1024 * 1024), 4); + assert_eq!(same, card); + assert_eq!(cost, 0, "a push that leaves the threshold alone analyzes nothing"); +} + +#[test] +fn a_buffer_that_changes_mode_has_its_colours_asked_for_again() { + let tree = Tree::new("fa_stage_colours"); + tree.write("a.sv", SMALL); + let refreshing = ClientAbilities { semantic_tokens_refresh: true, ..Default::default() }; + let mut session = Session::wide_with(vec![tree.path.clone()], refreshing); + session.open(&tree.path.join("a.sv"), SMALL); + session.drain(); + let refreshes = |session: &mut Session, section: Value| { + session.notify( + lsp_types::notification::DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": section } }), + ); + let sent = session.drain(); + sent.iter() + .filter(|m| matches!(m, Message::Request(r) if r.method == "workspace/semanticTokens/refresh")) + .count() + }; + assert_eq!(refreshes(&mut session, threshold(4 * 1024 * 1024)), 0, "nothing moved"); + assert_eq!(refreshes(&mut session, threshold(10)), 1, "the buffer went onto the fast path"); + assert_eq!(refreshes(&mut session, threshold(20)), 0, "still large: nothing moved"); +} diff --git a/crates/lucisv_server/src/server/tests/large_file.rs b/crates/lucisv_server/src/server/tests/large_file.rs index 295bb34..728740c 100644 --- a/crates/lucisv_server/src/server/tests/large_file.rs +++ b/crates/lucisv_server/src/server/tests/large_file.rs @@ -341,7 +341,7 @@ fn a_large_buffer_is_present_in_workspace_diagnostics_with_an_empty_full_report( } #[test] -fn the_threshold_arrives_by_push_and_by_pull_and_takes_effect_on_the_next_change() { +fn the_threshold_arrives_by_push_and_by_pull_and_takes_effect_on_open_buffers_at_once() { let tree = Tree::new("largethreshold"); let path = tree.path.join("net.v"); tree.write("net.v", &big_source()); @@ -351,21 +351,22 @@ fn the_threshold_arrives_by_push_and_by_pull_and_takes_effect_on_the_next_change let uri = session.open(&path, &big_source()); assert!(!session.server.workspace.document(&uri).expect("open").large); - // Pushed. The buffer already open does not change mode on the spot — - // the decision is taken where a document is built. + // Pushed. Since fast-actions R1 the buffer already open changes mode on + // the spot, as a server given the setting first would have built it — + // it used to keep its mode until its next change. session.notify( DidChangeConfiguration::METHOD, serde_json::json!({ "settings": { "lucisv": { "largeFile": { "threshold": 100 } } } }), ); assert_eq!(session.server.workspace.client_settings().large_file_threshold, 100); assert!( - !session.server.workspace.document(&uri).expect("open").large, - "the open buffer keeps the mode it was built in" + session.server.workspace.document(&uri).expect("open").large, + "the open buffer takes the fast path when the threshold says so" ); change(&mut session, &uri, 2, serde_json::json!([{ "text": big_source() }])); assert!( session.server.workspace.document(&uri).expect("open").large, - "and takes the fast path at its next change" + "and keeps it through its next change" ); // Pulled: the same value through the other door. diff --git a/crates/lucisv_server/src/server/tests/mod.rs b/crates/lucisv_server/src/server/tests/mod.rs index 87919ba..eb9f10c 100644 --- a/crates/lucisv_server/src/server/tests/mod.rs +++ b/crates/lucisv_server/src/server/tests/mod.rs @@ -49,6 +49,11 @@ mod apply_edit; mod cancel; mod caret_boundary; mod code_action; +mod fast_actions; +mod fast_actions_bursts; +mod fast_actions_differential; +mod fast_actions_precondition; +mod fast_actions_staging; mod file_ops; mod folders; mod formatting; diff --git a/crates/lucisv_server/src/server/tests/scan_ordering.rs b/crates/lucisv_server/src/server/tests/scan_ordering.rs index 698a4e2..7037570 100644 --- a/crates/lucisv_server/src/server/tests/scan_ordering.rs +++ b/crates/lucisv_server/src/server/tests/scan_ordering.rs @@ -67,12 +67,11 @@ fn inserted(uri: &Uri, version: u32, line: u32, text: &str) -> Message { ) } -fn hover(id: i32, uri: &Uri) -> Message { - ask( - id, - HoverRequest::METHOD, - serde_json::json!({ "textDocument": { "uri": uri }, "position": { "line": 0, "character": 0 } }), - ) +/// A request about `uri` that always waits for a scan: a code lens counts +/// instantiations across the workspace, so no buffer answers it alone (a +/// hover on a local name is answered ahead since `fast-actions`). +fn lens(id: i32, uri: &Uri) -> Message { + ask(id, CodeLensRequest::METHOD, serde_json::json!({ "textDocument": { "uri": uri } })) } /// Hand `burst` to the loop as `run` would, with every scripted burst @@ -119,14 +118,14 @@ pub(super) fn with_a_open(tree: &Tree) -> (Session, Uri) { #[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 + // QA F6, held form: the rescan holds `[lens, 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)]]); + probe::script([vec![lens(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"); } @@ -139,10 +138,7 @@ fn incremental_changes_held_mid_rescan_are_applied_in_the_order_they_were_sent() 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)], - ]); + probe::script([vec![lens(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); @@ -176,11 +172,11 @@ fn a_reopen_behind_a_held_close_leaves_the_buffer_open_with_its_new_text() { 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)]]); + probe::script([vec![lens(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"); + assert_eq!(answered, [RequestId::from(1)], "the held lens is answered once"); } #[test] @@ -194,12 +190,12 @@ fn a_change_behind_only_a_held_request_applies_at_once_and_a_late_cancel_waits_w 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]]); + probe::script([vec![lens(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"); + assert_eq!(buffer(&session, &a), v2, "applied mid-scan, ahead of the held lens"); let held: Vec = session.server.held.iter().map(changes_state_of).collect(); - assert_eq!(held, [false, false], "the hover and its cancel, nothing else"); + assert_eq!(held, [false, false], "the lens and its cancel, nothing else"); settle(&mut session); let answers = session.answers(); assert_eq!(answers.len(), 1, "{answers:#?}"); @@ -274,7 +270,7 @@ fn a_request_ahead_of_a_didopen_mid_startup_is_answered_and_the_drain_runs_once( SemanticTokensFullRequest::METHOD, serde_json::json!({ "textDocument": { "uri": b } }), ); - let later = vec![hover(7, &a), opened(&b, "module bmod;\nendmodule\n"), tokens_b]; + let later = vec![lens(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()); diff --git a/crates/lucisv_server/src/server/viewport.rs b/crates/lucisv_server/src/server/viewport.rs index 32860b2..149cccc 100644 --- a/crates/lucisv_server/src/server/viewport.rs +++ b/crates/lucisv_server/src/server/viewport.rs @@ -27,42 +27,19 @@ //! the last publish, so an answer off it is a coherent guess, and the refresh //! below is what replaces the guess. //! -//! **When the buffer's text is current.** The answer is only worth anything if -//! it is for the text the client had when it asked: no `didOpen`, `didChange` -//! or `didClose` for the buffer may still be unapplied ahead of it. This rides -//! on the loop's own bookkeeping (`docs/features/scan-ordering/README.md`): -//! everything older than a request is either applied or sits in one of the -//! places `Server::must_hold` already consults — `held`, and the tail of the -//! burst whose notification started the scan this request is being answered -//! inside, counted by [`Server::behind`] — plus the part of the request's own -//! burst being set aside ahead of it (`ahead`) and `dirty` (a `didChange` -//! applied but not analyzed). A notification naming the buffer in `held` or -//! `ahead`, any unapplied notification counted by `behind` (it names no -//! buffer, so it is taken as naming this one), or the buffer being dirty, and -//! the request waits like any other. -//! -//! **A widen** is the one rescan that used to drain nothing. Its `didOpen` is -//! applied first; the colouring requests behind it in its burst are answered -//! before the widen runs ([`Server::open_then_widen`]), and the ones that -//! arrive while it runs between two of its files -//! ([`Server::answer_colours_mid_widen`]), everything else being held in -//! arrival order — so the widen stays the effect of one applied message and no -//! notification overtakes an older one. +//! Which buffers are current, and how an exempted request is taken out of +//! a burst ahead of what holds the rest, is `ahead.rs`. use std::collections::HashSet; -use std::error::Error; use std::path::PathBuf; -use lsp_server::{Message, Notification, Request, RequestId, Response}; -use lsp_types::notification::{DidOpenTextDocument, Notification as _}; +use lsp_server::Response; use lsp_types::request::{ Request as _, SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, SemanticTokensRangeRequest, SemanticTokensRefresh, }; use lsp_types::Uri; -use super::batch::{cancelled_in, cancelled_response, changes_state}; -use super::dispatch::document_uri; use super::Server; use crate::tokens; @@ -97,9 +74,9 @@ pub(super) struct Viewport { /// Set while `open_then_widen` applies a `didOpen`: a widen that open /// asks for is recorded in `owed_widen` instead of run, so the colours /// behind it in its burst can be answered first. - defer_widen: bool, + pub(super) defer_widen: bool, /// The folders a deferred widen will add. - owed_widen: Option>, + pub(super) owed_widen: Option>, /// Whether a widen is running: the index is unsettled, exactly as during /// a scan, so a range answered now is owed a refresh. pub(super) widening: bool, @@ -128,181 +105,47 @@ impl Viewport { } } -/// The buffer a notification names, if it is a notification and names one. -fn notified_uri(message: &Message) -> Option { - match message { - Message::Notification(notification) => document_uri(¬ification.params), - _ => None, - } -} - impl Server { - /// Answer a semantic-token request now, ahead of whatever holds the rest, - /// when it can be answered from its buffer alone — `None` when it must - /// wait like any other request. + /// Whether a colouring request may go ahead of a scan — `None` when + /// `method` is not one of the three that colour. /// - /// `ahead` is what of its own burst is being held ahead of it and is not - /// in `held` yet. A cancel the burst carries for it is honoured here, - /// exactly as the loop would honour it. - fn answer_from_the_buffer( + /// A whole answer off an unsettled index is only worth giving a client + /// that can be told to ask again; one that cannot keeps it until its next + /// edit, so for it `full` and `full/delta` wait for the index as they + /// always did, and only `range` goes ahead. + pub(super) fn colours_may_go_ahead(&self, method: &str) -> Option { + if !TOKEN_METHODS.contains(&method) { + return None; + } + Some(method == SemanticTokensRangeRequest::METHOD || self.abilities.semantic_tokens_refresh) + } + + /// What answering a colouring request ahead of the index owes: a range + /// answer is not remembered, so one taken off an unsettled index is + /// marked for the refresh; a whole answer is remembered by + /// `remember_tokens` and checked against the settled index anyway. + pub(super) fn coloured_ahead( &mut self, - request: &Request, - ahead: &[Message], - cancelled: &mut HashSet, - ) -> Option { - if !TOKEN_METHODS.contains(&request.method.as_str()) { - return None; - } - // A whole answer off an unsettled index is only worth giving a client - // that can be told to ask again; one that cannot keeps it until its - // next edit, so it waits for the index as it always did. - let range = request.method == SemanticTokensRangeRequest::METHOD; - if !range && !self.abilities.semantic_tokens_refresh { - return None; - } - let uri = document_uri(&request.params)?; - if !self.text_is_current(&uri, ahead) { - return None; - } - if cancelled.remove(&request.id) { - return Some(cancelled_response(request.id.clone())); - } - let started = self.timer(); - let unsettled = self.index_unsettled(); - let copy = Request::new(request.id.clone(), request.method.clone(), request.params.clone()); - let response = self.answer_flushed(copy); - // A remembered answer is checked against the settled index anyway; - // a range answer is not remembered, so it is marked instead. + uri: Uri, + method: &str, + unsettled: bool, + response: &Response, + ) { + let range = method == SemanticTokensRangeRequest::METHOD; if unsettled && range && response.response_result.is_ok() { self.viewport.guessed.insert(uri); } - self.timed(started, |took| { - format!( - "{} answered from the buffer ahead of a scan (held={}, settled={}) in {took}", - request.method, - self.held.len(), - !unsettled - ) - }); - Some(response) - } - - /// [`Server::answer_from_the_buffer`] for one message of a burst, the - /// answer sent: whether it was a request the exemption took. - pub(super) fn answered_ahead( - &mut self, - message: &Message, - ahead: &[Message], - cancelled: &mut HashSet, - ) -> Result> { - let Message::Request(request) = message else { return Ok(false) }; - let Some(response) = self.answer_from_the_buffer(request, ahead, cancelled) else { - return Ok(false); - }; - self.connection.sender.send(Message::Response(response))?; - Ok(true) - } - - /// Move the rest of a burst into `rest`, behind a request that must wait - /// — except a colouring request the exemption can answer against - /// everything ahead of it, which is answered now instead of being held. - pub(super) fn set_aside( - &mut self, - rest: &mut Vec, - behind: impl Iterator, - cancelled: &mut HashSet, - ) -> Result<(), Box> { - for later in behind { - if !self.answered_ahead(&later, rest, cancelled)? { - rest.push(later); - } - } - Ok(()) - } - - /// Apply one notification of a burst whose not-yet-handled tail is - /// `rest`, returning that tail: a `didOpen` goes through - /// [`Server::open_then_widen`], everything else straight to the handler. - pub(super) fn apply_in_burst( - &mut self, - notification: Notification, - rest: std::vec::IntoIter, - cancelled: &mut HashSet, - ) -> Result, Box> { - if notification.method != DidOpenTextDocument::METHOD { - self.notification(notification); - return Ok(rest); - } - Ok(self.open_then_widen(notification, rest.collect(), cancelled)?.into_iter()) - } - - /// Apply a `didOpen`, and when it widens the scope, answer the colouring - /// requests in `rest` — the burst behind it — **before** the widen runs, - /// then run it. Returns what is left of `rest`, in order. - /// - /// The buffer is applied by then and the answers need nothing from the - /// index, so VS Code's `full`, which arrives in the same burst as its - /// `didOpen`, colours at once instead of after the widen. Everything else - /// in `rest` is untouched and runs after the widen exactly as before; the - /// widen is still the effect of the applied `didOpen` and nothing else. - fn open_then_widen( - &mut self, - notification: Notification, - rest: Vec, - cancelled: &mut HashSet, - ) -> Result, Box> { - self.viewport.defer_widen = true; - self.notification(notification); - self.viewport.defer_widen = false; - let Some(added) = self.viewport.owed_widen.take() else { return Ok(rest) }; - // `rest` is passed as what is ahead of each request, so it is taken - // out of the count of unapplied notifications around this one. - let around = self.behind; - self.behind = around.saturating_sub(rest.iter().filter(|m| changes_state(m)).count()); - self.viewport.widening = true; - let mut kept = Vec::new(); - let answered = self.set_aside(&mut kept, rest.into_iter(), cancelled); - self.behind = around; - answered?; - self.reindex_widened(added); - Ok(kept) - } - - /// Between two files of a widen: answer the colouring requests that have - /// arrived and can be answered from their buffers, and hold everything - /// else, in arrival order, behind whatever is already held. - /// - /// Safe for the rest of the burst that carried the `didOpen`: it is older - /// than anything arriving now, and while it holds a notification - /// [`Server::behind`] is non-zero, which makes every buffer not current. - pub(super) fn answer_colours_mid_widen(&mut self) -> Result<(), Box> { - let arrived: Vec = self.queue.try_iter().collect(); - if arrived.is_empty() { - return Ok(()); - } - let mut cancelled = cancelled_in(&arrived); - let mut kept = Vec::new(); - self.set_aside(&mut kept, arrived.into_iter(), &mut cancelled)?; - self.held.extend(kept); - Ok(()) - } - - /// Whether the buffer `uri` holds exactly the text the client had when it - /// sent the request being answered: open, analyzed, and with no change - /// for it still waiting anywhere (see the module documentation). - fn text_is_current(&self, uri: &Uri, ahead: &[Message]) -> bool { - let names = |message: &Message| notified_uri(message).as_ref() == Some(uri); - self.workspace.document(uri).is_some() - && !self.dirty.iter().any(|(pending, _)| pending == uri) - && !self.held.iter().any(names) - && !ahead.iter().any(names) - && self.behind == 0 } /// Whether the index is still being built — a scan running or owed, or a - /// widen running — so that a token answer now may change once it settles. + /// widen running — or about to move: something is held, and whatever it + /// is may ask for a rescan when it is applied (a watcher event a + /// colouring request was answered ahead of, say). A token answer given + /// now may then change once the index settles, and is recorded as a + /// guess. Nothing is ever held while the loop answers in order, so this + /// last clause only ever marks an answer given ahead. pub(super) fn index_unsettled(&self) -> bool { - self.scanning || self.staging || self.viewport.widening + self.scanning || self.staging || self.viewport.widening || !self.held.is_empty() } /// Ask the client to re-request its semantic tokens, once, when the index diff --git a/crates/lucisv_server/src/server/viewport/tests.rs b/crates/lucisv_server/src/server/viewport/tests.rs index 9add0b1..2a20f22 100644 --- a/crates/lucisv_server/src/server/viewport/tests.rs +++ b/crates/lucisv_server/src/server/viewport/tests.rs @@ -18,7 +18,7 @@ use lsp_types::notification::{ Cancel, DidChangeTextDocument, DidOpenTextDocument, Notification as _, }; use lsp_types::request::{ - HoverRequest, Request as _, SemanticTokensFullRequest, SemanticTokensRangeRequest, + CodeLensRequest, Request as _, SemanticTokensFullRequest, SemanticTokensRangeRequest, SemanticTokensRefresh, }; use lsp_types::Uri; @@ -144,12 +144,12 @@ fn range(id: &str, uri: &Uri) -> Message { ) } -fn hover(id: &str, uri: &Uri) -> Message { - request( - id, - HoverRequest::METHOD, - json!({ "textDocument": { "uri": uri }, "position": { "line": 0, "character": 8 } }), - ) +/// A request about `uri` that always waits for a scan: a code lens counts +/// instantiations across the workspace, so no buffer answers it alone. (A +/// hover was the witness until `fast-actions` let a hover on a local name go +/// ahead too.) +fn lens(id: &str, uri: &Uri) -> Message { + request(id, CodeLensRequest::METHOD, json!({ "textDocument": { "uri": uri } })) } fn changed(uri: &Uri, text: &str) -> Message { @@ -188,18 +188,18 @@ fn opened(name: &str, abilities: ClientAbilities) -> (Tree, Lane, Uri) { } #[test] -fn colouring_requests_are_answered_while_a_hover_ahead_of_them_waits() { +fn colouring_requests_are_answered_while_a_lens_ahead_of_them_waits() { let (_tree, mut lane, uri) = opened("ahead", refreshing()); - lane.burst_mid_scan(vec![hover("h", &uri), full("f", &uri), range("r", &uri)]); - assert_eq!(lane.answered(), vec![id("f"), id("r")], "both colour now, the hover waits"); - assert_eq!(lane.server.held.len(), 1, "the hover alone is held"); + lane.burst_mid_scan(vec![lens("h", &uri), full("f", &uri), range("r", &uri)]); + assert_eq!(lane.answered(), vec![id("f"), id("r")], "both colour now, the lens waits"); + assert_eq!(lane.server.held.len(), 1, "the lens alone is held"); assert!(lane.server.viewport.guessed.contains(&uri), "a range off an unsettled index"); } #[test] fn the_exempt_answers_are_the_answers_the_dispatch_gives_once_nothing_waits() { let (_tree, mut lane, uri) = opened("same", refreshing()); - lane.burst_mid_scan(vec![hover("h", &uri), full("f", &uri), range("r", &uri)]); + lane.burst_mid_scan(vec![lens("h", &uri), full("f", &uri), range("r", &uri)]); let early = responses(lane.drain()); lane.server.held.clear(); lane.server.process_batch(vec![full("f2", &uri), range("r2", &uri)]).expect("burst"); @@ -224,7 +224,7 @@ fn a_change_held_ahead_of_the_request_holds_it_too_but_not_another_buffers() { let other = lane.open(&other_path, "module n;\nendmodule\n"); lane.drain(); lane.burst_mid_scan(vec![ - hover("h", &uri), + lens("h", &uri), changed(&uri, "module m3;\nendmodule\n"), range("mine", &uri), range("theirs", &other), @@ -249,7 +249,7 @@ fn a_change_still_behind_the_scans_own_trigger_holds_the_request() { #[test] fn a_cancel_in_the_same_burst_is_honoured_for_an_exempt_request() { let (_tree, mut lane, uri) = opened("cancel", refreshing()); - lane.burst_mid_scan(vec![hover("h", &uri), full("f", &uri), cancel("f")]); + lane.burst_mid_scan(vec![lens("h", &uri), full("f", &uri), cancel("f")]); let answers = responses(lane.drain()); assert_eq!(answers.len(), 1); let error = answers[0].response_result.as_ref().expect_err("cancelled"); @@ -265,7 +265,7 @@ fn a_large_buffer_keeps_its_decline_and_its_lexed_window() { let uri = lane.open(&path, MODULE); assert!(lane.server.workspace.document(&uri).is_some_and(|doc| doc.large)); lane.drain(); - lane.burst_mid_scan(vec![hover("h", &uri), full("f", &uri), range("r", &uri)]); + lane.burst_mid_scan(vec![lens("h", &uri), full("f", &uri), range("r", &uri)]); let answers = responses(lane.drain()); assert_eq!(answers.len(), 2); assert!(answers[0].response_result.is_err(), "full is declined, as always"); @@ -317,7 +317,7 @@ fn a_guessed_range_is_refreshed_and_a_client_that_cannot_be_asked_is_not() { let abilities = ClientAbilities { semantic_tokens_refresh: refresh_support, ..Default::default() }; let (_tree, mut lane, uri) = opened("guessed", abilities); - lane.burst_mid_scan(vec![hover("h", &uri), range("r", &uri)]); + lane.burst_mid_scan(vec![lens("h", &uri), range("r", &uri)]); lane.server.held.clear(); lane.drain(); lane.server.hierarchy_revision += 1; @@ -368,7 +368,7 @@ fn a_cold_start_is_coloured_at_once_and_sharpened_by_one_refresh() { client: ClientSettings::default(), storage: None, verbose: false, - queued: vec![opened, hover("h", &uri), full("f", &uri)], + queued: vec![opened, lens("h", &uri), full("f", &uri)], // The client never answers the pull: everything waits the bound, // and the colours must not. wait: Duration::from_millis(50), @@ -376,7 +376,7 @@ fn a_cold_start_is_coloured_at_once_and_sharpened_by_one_refresh() { let mut lane = Lane { server: Server::started(server_end, vec![tree.0.clone()], startup), client }; let answers = responses(lane.drain()); - assert_eq!(answers[0].id, id("f"), "coloured first, ahead of the held hover: {answers:?}"); + assert_eq!(answers[0].id, id("f"), "coloured first, ahead of the held lens: {answers:?}"); let nib = |answer: &Value| -> u64 { // `p` `::` `nib_t` on line 1: the second identifier token of the line. let data: Vec = @@ -397,11 +397,11 @@ fn a_cold_start_is_coloured_at_once_and_sharpened_by_one_refresh() { crate::tokens::token_types().iter().position(|t| t.as_str() == "variable").expect("legend") as u64 ); - // What `run` does next: answer what the scan held (the hover), then + // What `run` does next: answer what the scan held (the lens), then // take the refresh decision. let held = std::mem::take(&mut lane.server.held); lane.server.process_batch(held).expect("the held burst"); - assert_eq!(responses(lane.drain()).len(), 1, "the hover, answered at last"); + assert_eq!(responses(lane.drain()).len(), 1, "the lens, answered at last"); lane.server.refresh_tokens_if_stale(); assert_eq!(lane.refreshes(), 1, "the index moved what the client was sent"); lane.server.process_batch(vec![full("f2", &uri)]).expect("burst"); @@ -417,9 +417,9 @@ fn a_cold_start_is_coloured_at_once_and_sharpened_by_one_refresh() { #[test] fn a_client_that_cannot_be_refreshed_gets_early_ranges_but_waits_for_whole_answers() { let (_tree, mut lane, uri) = opened("norefresh", ClientAbilities::default()); - lane.burst_mid_scan(vec![hover("h", &uri), full("f", &uri), range("r", &uri)]); + lane.burst_mid_scan(vec![lens("h", &uri), full("f", &uri), range("r", &uri)]); assert_eq!(lane.answered(), vec![id("r")], "only the range colours early"); - assert_eq!(lane.server.held.len(), 2, "the hover and the full wait for the index"); + assert_eq!(lane.server.held.len(), 2, "the lens and the full wait for the index"); } /// Two blocks two folders apart, so that opening the second widens the @@ -466,7 +466,7 @@ fn the_full_in_the_same_burst_as_a_widening_open_colours_before_the_widen() { let indexed = lane.server.workspace.index().files().len(); let uri = path_to_uri(&second).expect("uri"); lane.server - .process_batch(vec![opening(&uri, USES_P), full("f", &uri), hover("h", &uri)]) + .process_batch(vec![opening(&uri, USES_P), full("f", &uri), lens("h", &uri)]) .expect("burst"); assert!(lane.server.workspace.index().files().len() > indexed, "premise: it widened"); let sent = lane.drain(); @@ -492,14 +492,14 @@ fn colours_arriving_during_a_widen_are_answered_and_the_rest_waits_in_order() { let uri = path_to_uri(&second).expect("uri"); // On the wire before the burst is taken: these are what the widen's own // drain finds, newer than the whole burst. - for message in [hover("h2", &first_uri), range("r2", &first_uri)] { + for message in [lens("h2", &first_uri), range("r2", &first_uri)] { lane.client.sender.send(message).expect("the client's traffic"); } std::thread::sleep(Duration::from_millis(100)); lane.server.process_batch(vec![opening(&uri, USES_P)]).expect("burst"); let sent = lane.drain(); let answered: Vec = responses(sent.clone()).into_iter().map(|r| r.id).collect(); - assert_eq!(answered, vec![id("r2")], "the range colours, the hover waits"); + assert_eq!(answered, vec![id("r2")], "the range colours, the lens waits"); let held: Vec<&str> = lane .server .held @@ -509,6 +509,6 @@ fn colours_arriving_during_a_widen_are_answered_and_the_rest_waits_in_order() { _ => None, }) .collect(); - assert_eq!(held, vec![HoverRequest::METHOD]); + assert_eq!(held, vec![CodeLensRequest::METHOD]); assert!(lane.server.viewport.guessed.contains(&first_uri), "a range off a widening index"); } diff --git a/crates/lucisv_server/src/state/buffers.rs b/crates/lucisv_server/src/state/buffers.rs index 61a55eb..a564ac9 100644 --- a/crates/lucisv_server/src/state/buffers.rs +++ b/crates/lucisv_server/src/state/buffers.rs @@ -37,8 +37,11 @@ impl Workspace { /// `lucisv.largeFile.threshold` is line-indexed and nothing more. Because /// the decision lives here it is re-taken on every `didOpen`, `didChange` /// and text-carrying `didSave`, which is what makes a buffer edited past - /// the threshold — or back under it — change mode at that moment and not - /// before (`docs/features/large-file-mode/README.md`). + /// the threshold — or back under it — change mode at that moment. A + /// *changed threshold* reaches the buffers already open through here too: + /// the settings applier re-installs each one the new value classifies + /// differently (`Server::reclassify_large_buffers`; + /// `docs/features/large-file-mode/README.md`). pub fn set_document(&mut self, uri: Uri, text: String) { let path = uri_to_path(&uri); if let Some(dir) = path.as_deref().and_then(Path::parent) { @@ -63,7 +66,7 @@ impl Workspace { /// Whether a buffer of this text takes the fast path. `0` disables it, and /// the comparison is strict, so a buffer of exactly the threshold is still /// analyzed in full. - fn is_large(&self, text: &str) -> bool { + pub fn is_large(&self, text: &str) -> bool { let threshold = self.client.large_file_threshold; threshold != 0 && text.len() as u64 > threshold } diff --git a/crates/lucisv_server/src/state/scope.rs b/crates/lucisv_server/src/state/scope.rs index 16a400a..7f96daf 100644 --- a/crates/lucisv_server/src/state/scope.rs +++ b/crates/lucisv_server/src/state/scope.rs @@ -163,11 +163,11 @@ impl Workspace { /// does `index.logFiles`, which changes only how loudly the *next* rescan /// narrates itself. /// - /// `largeFile.threshold` asks for no rescan either, and deliberately: it - /// is consulted where a `Document` is *built*, so a change to it reaches - /// each open buffer at that buffer's next `didOpen`/`didChange` and not - /// before. A rescan now would index by the mode each buffer is still in, - /// which is the mode the index already reflects + /// `largeFile.threshold` asks for no rescan either: it is consulted where + /// a `Document` is *built*, and the server re-builds exactly the open + /// buffers a new value classifies differently, the way an edit would + /// (`Server::reclassify_large_buffers`, fast-actions R1); the index takes + /// their new mode at their next save or rescan, as it does an edit's /// (`docs/features/large-file-mode/README.md`). pub fn set_client_settings(&mut self, settings: ClientSettings) -> bool { let rescan = self.client.exclude != settings.exclude diff --git a/crates/lucisv_server/src/type_def.rs b/crates/lucisv_server/src/type_def.rs index 11f0468..906776b 100644 --- a/crates/lucisv_server/src/type_def.rs +++ b/crates/lucisv_server/src/type_def.rs @@ -77,7 +77,7 @@ pub fn type_definition(ws: &Workspace, uri: &Uri, offset: u32) -> Vec /// Case 2 is deliberately a use and never a declaration: the cursor on the /// `alias_t` of `typedef state_t alias_t;` is on a declaration whose own type /// is written beside it, and answering "itself" there would waste the hop. -fn type_name(doc: &Document, offset: u32) -> Option { +pub(crate) fn type_name(doc: &Document, offset: u32) -> Option { if let Some(site) = site_at(&doc.tree.items, offset) { if let Some(span) = type_span(&doc.semantics, &site) { if span.contains(offset) { diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index 15b7251..d42467b 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -2490,16 +2490,18 @@ fn keyword_and_project_completion_round_trip_over_the_wire() { assert_eq!(local["kind"], 6, "CompletionItemKind.Variable"); assert!(local["sortText"].as_str().expect("sortText").starts_with('1'), "{local:#?}"); - // `4`, not `2`: `completion-ux` (2026-11-17) put this file's own - // declarations (`2`) and words (`3`) ahead of what other files declare. + // `5`, not `2`: `completion-ux` (2026-11-17) put this file's own + // declarations (`2`) and words (`3`) ahead of what other files declare, + // and `fast-actions` (2026-11-19) what the file is related to (`4`). let macro_name = labelled("WIDGET_MACRO").expect("a `define name"); - assert!(macro_name["sortText"].as_str().expect("sortText").starts_with('4')); + assert!(macro_name["sortText"].as_str().expect("sortText").starts_with('5')); let elsewhere = labelled("widget_elsewhere").expect("a word used in the project"); assert_eq!(elsewhere["kind"], 1, "CompletionItemKind.Text"); - // `7`: M6 inserted the template tier above the keywords, and - // `completion-ux` the two current-file tiers above the index. - assert!(elsewhere["sortText"].as_str().expect("sortText").starts_with('7')); + // `8`: M6 inserted the template tier above the keywords, + // `completion-ux` the two current-file tiers above the index, and + // `fast-actions` the related tier. + assert!(elsewhere["sortText"].as_str().expect("sortText").starts_with('8')); assert!( !items.iter().any(|item| item["sortText"].as_str().is_some_and(|s| s.starts_with('0'))), @@ -2675,12 +2677,12 @@ fn a_template_completion_round_trips_over_the_wire() { assert_eq!(template["textEdit"]["range"]["start"]["line"], 2); assert_eq!(template["textEdit"]["range"]["start"]["character"], 4); assert_eq!(template["textEdit"]["range"]["end"]["character"], 6); - assert!(template["sortText"].as_str().expect("sortText").starts_with('5')); + assert!(template["sortText"].as_str().expect("sortText").starts_with('6')); // The keyword survives beside it, one tier down. let keyword = labelled(items, "if").expect("the keyword"); assert_eq!(keyword["kind"], 14, "CompletionItemKind.Keyword"); - assert!(keyword["sortText"].as_str().expect("sortText").starts_with('6')); + assert!(keyword["sortText"].as_str().expect("sortText").starts_with('7')); // A `.v` buffer is offered Verilog's `always`, never `always_ff`. let verilog = messages.iter().find(|m| m["id"] == 3).expect("completion response"); diff --git a/docs/features/fast-actions/README.md b/docs/features/fast-actions/README.md new file mode 100644 index 0000000..f448f3e --- /dev/null +++ b/docs/features/fast-actions/README.md @@ -0,0 +1,2441 @@ +# fast-actions + +## Goal + +The owner's words: *"When the number of files are really huge and has a lot of +dependencies, every action feels slow. I want to dynamically do those actions +if possible. Like prioritize everything that is already in the same file, like +hover to reveal definition. Use the relationship map to dynamically load the +auto suggest options."* So: (A) a request whose whole answer is in the buffer +it names — the outline, folding, a hover or a jump on a name this file +declares — is answered from that buffer at once, even while a scan holds +everything else, and its answer is **the answer the settled server gives**; +anything that might need another file waits exactly as before. (B) Completion +puts what the file is *related to* — the packages it imports, the classes it +extends, the headers it includes — between the file's own names and the rest +of the workspace, so a huge workspace stops drowning them, and its answer costs +half the bytes on the wire for a client that takes LSP 3.17's defaults. + +## Measured first (2026-11-19, before any code) + +**Harness** (`scratchpad/dev712/drv/`): `lspc.py`, an LSP stdio client that +sends VS Code 1.145's client capabilities (completion `itemDefaults`, +`resolveSupport`, semantic-token refresh, work-done progress, …) and records +each response's arrival time and byte size; `cases.py`, the request catalogue +on `hw/ip/aes/rtl/aes_cipher_core.sv` (932 lines, `import aes_pkg::*` in its +header); `meas.py`, the phases below. The binary is 0.65.10 (`c1c1407`, this +worktree before any edit — the same tree `git archive c1c1407` gives), release +build. Workspace scope, cold store in the scratch dir. + +**Trees.** `ot1` = a copy of OpenTitan `hw/` (4 061 files, 48 MB). `ot5` / +`ot10` = that tree replicated 5 / 10 times under `c0/ … c9/`, every module, +package, interface and program name declared anywhere prefixed `cK_` in copy +K (20 305 / 40 610 files; `gen.py`). `ot10w` = 10 copies with **every** +non-keyword identifier suffixed `_cK` (`genw.py`), so the vocabulary grows +with the tree too — the fairer "really huge" for completion. Settle time +(open → scan done): 3.0 s / 11.1 s / 22.5 s. + +### (a) Settled latency — median / p95 of 20 calls, client-side ms + +| request | 4k | 20k | 40k | bytes 4k → 40k | +|---|---|---|---|---| +| hover / definition / typeDefinition / prepareRename (local, cross, pkg) | 0.02–0.07 / ≤0.14 | ≤0.03 / ≤0.06 | ≤0.04 / ≤0.08 | 37–284, flat | +| references local / cross / pkg | 0.07 / 0.27 / 0.13 | 0.04 / 0.17 / 0.16 | 0.07 / **0.60** / **0.43** | 769–1 524, flat | +| documentHighlight | ≤0.08 | ≤0.05 | ≤0.07 | 127–583 | +| documentSymbol | 0.64 | 0.50 | 0.54 | 45 001 | +| foldingRange / selectionRange / signatureHelp | ≤0.12 | ≤0.09 | ≤0.10 | 200–2 724 | +| inlayHint / codeLens / documentLink | ≤0.11 | ≤0.09 | ≤0.09 | 38–225 | +| completion: statement start, expr prefix 1/2/3, module item (empty, `a`, `ae`) | 1.3–3.9 | 1.4–4.2 | 1.4–4.6 | **129–155 KB, 512 items** | +| completion after `pkg::` | 0.69 | 0.70 | 0.72 | 58 569 (259) | +| completion after `.` (port, parameter) | ≤0.07 | ≤0.07 | ≤0.06 | 301–2 937 | +| completionItem/resolve | MethodNotFound (not advertised) | | | | +| workspace/symbol `aes_ci` / `a` | 1.8 / 7.9 | 6.2 / 57 | **15 / 131** | 80–99 KB | +| `lucisv/moduleHierarchy` (the extension's tree) | 24 | 143 | **300** (p95 2 144) | 2.6 MB → **26 MB** | + +Server-side the per-request handlers do not scale with the workspace except +the two that are workspace-wide by nature (`workspace/symbol`, the hierarchy +snapshot). The p95 spikes on completion (93 ms at 4k, 2.8 s once at 40k) are +not the server: its own `--verbose` lines in the same window say ≤0.7 ms per +answer — a shared machine and a Python client reading 130 KB. + +### (b) Held: latency of a request sent during a scan (median of 3, ms) + +Seven requests on the open buffer — hover / definition / documentHighlight / +references on a local signal, documentSymbol, foldingRange, a port-`.` +completion — in one write. + +| moment | 4k | 20k | 40k | +|---|---|---|---| +| startup scan (sent with `didOpen`, cold) | 658 | 770 | 933 | +| whole rescan (a watched-file *create*, 5 ms before) | 970 | **5 753** | **10 765** | +| widen (folder scope; `didOpen` of a file in a new folder, same write) | 378 | 373 | 376 | + +**Every request waited for the whole scan.** This is "every action feels +slow": a watched-file event that creates one file (a branch switch, a +generator, a new file) takes a whole rescan, by design +(`docs/features/localized-reindex/README.md`), and for its length — 1 s at +4k files, 11 s at 40k — not even the outline of the open file was answered. +Startup held for the head phase; a widen for its folder. + +### (c) Right after a keystroke (`didChange` + the request in one write; median of 10, ms) + +| buffer | documentSymbol | hover | completion | +|---|---|---|---| +| `aes_cipher_core.sv`, 932 lines | 1.9–2.3 | 1.3–1.5 | 1.5–1.8 | +| `ibex_core.sv`, 2 025 lines | 4.5–5.2 | 3.0–3.8 | 3.4–3.9 | +| `rv_plic_reg_top.sv`, 20 021 lines | 28–29 | 21–24 | 21–24 | + +Flat in the workspace size: the cost is the flush — one reparse and analysis +of the edited buffer (`--verbose`: `flush of 1 dirty buffer took 19–33 ms` on +the 20k-line file). + +### (d) Where the time goes over ~20 ms + +* **Held behind a scan**: the order contract (`Server::must_wait`), not work — + the handlers are tens of microseconds. The scan before its first drain point + is the floor: discovery walk 137–161 ms and opening the store 341 ms at 20k + files (`scan 2 stages … discovery=161 … cache_open=341`), during which + nothing is drained (`viewport-highlight` Handshake request 2). +* **workspace/symbol**: `WorkspaceIndex::workspace_symbols` matches the whole + symbol table then sorts it — 126 ms server-side for `a` at 40k. +* **moduleHierarchy**: 144 ms to build the snapshot, 26 MB of JSON, 332 ms to + the client at 40k; re-fetched by the hierarchy view on every index change. +* **Keystroke on a 20k-line buffer**: the reparse (19–33 ms). +* **Completion payload**: 130 KB per keystroke while the typed prefix is + under three characters (always `isIncomplete`, so VS Code re-asks on every + keystroke). Of an item's 258 bytes: `textEdit` 49 % (the same range in + every item), `detail` 21 %, `sortText` 10 %, `label` 9 %, + `insertTextFormat` 8 %. +* **Completion relevance falls with the workspace**: tier 4 ("what the + project declares", alphabetical) fills the 512 cap before the members of + the one package the file imports. At `aes_cipher_core.sv`, the share of the + `aes_pkg` members matching the prefix that were offered at all: + +| prefix | 4k | 40k (`ot10w`) | +|---|---|---| +| `s` | 16 / 28 | 12 / 28 | +| `st` / `sta` | 7 / 7, 7 / 7 | 6 / 7, 6 / 7 | +| `a` (module item) | 8 / 56 | 8 / 56 | +| `ae` (module item) | 34 / 34 | 10 / 34 | + +### What VS Code does — read from source, not memory + +From the VS Code 1.145.2 bundle on this machine +(`/Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/workbench.desktop.main.js`) +and `vscode-languageclient@9.0.1` (`editors/vscode/node_modules`, +`lib/common/completion.js`, `lib/common/protocolConverter.js`): + +1. **Re-ask vs filter** (`SuggestModel._onNewContext`): when the cursor moves + forward in the same word and the current model has a provider whose last + list was `incomplete` (`getIncompleteProvider().size > 0`), VS Code + re-triggers **only those providers** with `triggerKind: 2` + (TriggerForIncompleteCompletions), reusing the others' items; otherwise + it re-filters the items it holds (`completionModel.lineContext = …`) + without asking. So an `isIncomplete: true` answer costs one request **per + keystroke**; a complete one costs none until the word changes. +2. **Filtering cost**: the client scores every item it holds on every + keystroke; over 2 000 items it switches to the cheaper non-graceful scorer + (`r.length > 2e3 ? fuzzyScore : fuzzyScoreGraceful`). +3. **`completionItem/resolve`**: registered only when the server advertises + `resolveProvider` (`completion.js`: `resolveCompletionItem: + options.resolveProvider ? … : undefined`); VS Code resolves the *focused* + item. The client advertises `resolveSupport.properties: ['documentation', + 'detail', 'additionalTextEdits']`. +4. **`itemDefaults`**: the client advertises `completionList.itemDefaults: + ['commitCharacters', 'editRange', 'insertTextFormat', 'insertTextMode', + 'data']`, and `asCompletionInsertText` gives an item with no `textEdit` the + default range and `item.textEditText ?? item.label` as its text, in + `item.insertTextFormat ?? defaultInsertTextFormat`. +5. **Payload**: every list is converted item by item in the extension host + (`asCompletionResult` → `asCompletionItem`) and shipped to the renderer; + bytes are paid twice, once per keystroke while incomplete. + +### Which requests are answerable from what + +| class | requests | +|---|---| +| (1) from the buffer alone, for the symbol under the cursor | documentSymbol, foldingRange, selectionRange, linkedEditingRange, `lucisv/scopePairs`; hover / definition / typeDefinition / documentHighlight / prepareRename on a name this file binds; signatureHelp outside an instantiation | +| (2) the index only for a cross-file target | hover / definition / typeDefinition / documentHighlight on an imported or instantiated name; references (a module-level name is reachable by a hierarchical path); signatureHelp inside an instantiation; inlayHint (the instantiated module's ports); documentLink (include resolution); completion (tiers 0/4/5/8 and member answers read the index) | +| (3) workspace-wide | workspace/symbol, codeLens (instantiation counts), call/type hierarchy, `lucisv/moduleHierarchy`, rename | + +## The rule per request (as built) + +Every request method the dispatch answers (`server/dispatch.rs`), each +spelled in full so `same_file/tests.rs`'s +`the_readme_table_names_every_request_the_dispatch_answers` can hold this +table to the dispatch: a new arm fails it until its row is written here. +This table is clause (e) of the precondition — *which* requests the buffer +answers alone; *when* such a request may go is the next section. + +| request | early from the buffer when | waits when | why | +|---|---|---|---| +| `textDocument/documentSymbol`, `textDocument/foldingRange`, `textDocument/selectionRange`, `textDocument/linkedEditingRange`, `lucisv/scopePairs` | always | never | the handler takes the `Document` and nothing else | +| `textDocument/hover` | the name is bound here: a use the binder resolved, a declaration, no name at all, or a macro this buffer `` `define``s | an unresolved use (imported, package-qualified, instantiated, inherited, hierarchical); a macro defined elsewhere | `ExternalResolutions::definition_of` asks the binder first; only an unresolved use reaches the overlay | +| `textDocument/definition` | as hover, and not on an `` `include`` line | as hover; an include line | an include path resolves against include directories a scan learns | +| `textDocument/typeDefinition` | the type the cursor's declaration writes is bound here (or there is none) | the type is imported / another file's | the jump is `definition` from the type name | +| `textDocument/documentHighlight` | a scope keyword pair; a name bound here; no use at all | an unresolved use | `nav::document_highlights` reads the overlay only for an unresolved use | +| `textDocument/references` | `untitled:` buffer; no name; a name bound here in a scope with no member key (an unnamed block) | a module-level signal, port, function local, unit — anything with a member key or at file scope; an unresolved use | `leaves_this_file` reads the index; this is a sufficient condition for its answer not to matter. **A partial list is never sent** | +| `textDocument/prepareRename` | `untitled:` buffer (refused, in the buffer's own words); a name bound here, not at file scope; no name | file scope (a second unit of that name makes it ambiguous); any unresolved use | `vlog_refactor::prepare_rename_here` | +| `textDocument/signatureHelp` | outside an instantiation's lists | inside one | the signature is the instantiated module's | +| `textDocument/semanticTokens/full`, `textDocument/semanticTokens/full/delta`, `textDocument/semanticTokens/range` | `viewport-highlight`'s rule, unchanged | a dirty buffer | a colour guess, replaced by one refresh | +| `textDocument/completion`, `textDocument/inlineCompletion` | never | always | every path reads the index's tables (or, inline, the instantiated module) | +| `textDocument/inlayHint`, `textDocument/codeLens`, `textDocument/documentLink` | never | always | an instantiated module's ports, instantiation counts, include resolution | +| `workspace/symbol`, `lucisv/moduleHierarchy`, `textDocument/prepareCallHierarchy`, `callHierarchy/incomingCalls`, `callHierarchy/outgoingCalls`, `textDocument/prepareTypeHierarchy`, `typeHierarchy/supertypes`, `typeHierarchy/subtypes` | never | always | workspace-wide | +| `textDocument/rename`, `textDocument/codeAction`, `codeAction/resolve`, `workspace/executeCommand`, `workspace/willRenameFiles` | never | always | the workspace (rename fan-out, refactorings, include rewrites) or the configuration (lint fixes) | +| `textDocument/formatting`, `textDocument/rangeFormatting`, `textDocument/rangesFormatting`, `textDocument/onTypeFormatting`, `textDocument/willSaveWaitUntil` | never | always | the formatter reads the settings and `lucisv.toml` | +| `textDocument/diagnostic`, `workspace/diagnostic` | never | always | the lint pass reads the settings, `lucisv.toml` and the index's census | + +Everything outside `same_file::METHODS` and the three colouring methods +waits by construction (`answer_from_the_buffer` returns at its first line). +The locality rule and its conservative cases are +`crates/lucisv_server/src/same_file.rs`'s module documentation; the per-arm +mirrors are each a short function there. + +## When a request is answered early — the precondition, in one place + +Stated here and as the doc comment of `Server::answer_from_the_buffer` +(`server/ahead.rs`), the one function that decides. Nothing else in this +document or in the code states a part of it on its own (escalation round; +before it the rule was spread over four places and three rounds of QA each +found the part one of them had missed). + +A request the loop would hold — a scan running or owed, something already +held — or that sits behind a notification of its own burst the loop is about +to apply, is answered at once instead when, **for the buffer it names**: + +| | clause | checked by | +|---|---|---| +| (a) | it is open | `nothing_unapplied_for` | +| (b) | every older client message that can change what the handler reads has been **applied** | `nothing_unapplied_for` → `can_reach` over `held` and `ahead`, and `Server::behind` | +| (c) | its analysis is current for the text applied, under the settings in force | `flush_buffer` for a `same_file` request; a colouring request on a dirty buffer waits (`is_dirty`); `reclassify_large_buffers` keeps a clean buffer current | +| (d) | no settings are awaited | `settings_awaited` | +| (e) | the answer is the buffer's alone | `same_file::answered_by_the_buffer` (the table above); `colours_may_go_ahead` | + +Otherwise it waits like any other request and is answered exactly once, in +order, later. When all five hold, the answer is the one a server taking one +message at a time gives at that request's place in the client's stream. + +**What an early handler reads.** A `same_file` handler reads the `Document` +of the buffer it names — text, line index, tokens, tree, `Semantics`, +`` `define`` table and the `large` flag — and nothing else: no setting (each +one and its readers are under Assumptions), no index, no other buffer. +(`Workspace::has_large_documents`, which the large-file gate consults first, +only short-circuits the look at that buffer's own flag, +`server/large_file.rs`.) A `Document` is **built in one place**, +`Workspace::set_document`, from exactly two inputs: the text and +`largeFile.threshold`. It is replaced only there and dropped only in +`close_document`; the only parts changed in place afterwards are the +workspace overlay and the lint snapshot (`Document::refresh_overlay`), which +no `same_file` handler reads. So "what can change the answer" is "what can +call `set_document` or `close_document` for this buffer, or change the +threshold" — a list that can be read off the callers +(`server/notification.rs`, `server/diagnostics.rs`, `server/large_file.rs`). + +**(b), message by message.** What an older message that has not been applied +yet could still do to the buffer, and so whether a request behind it waits: + +| older message, not yet applied | what applying it can do to a `Document` | a request behind it | +|---|---|---| +| `textDocument/didOpen`, `didChange`, `didSave`, `didClose` | replace, dirty or drop the one buffer it names (a `didSave` only when it carries a text that differs; otherwise it re-indexes and re-analyzes nothing) | waits if it names this buffer, or names none that parses; goes otherwise | +| `workspace/didChangeWatchedFiles` | nothing: it moves the index, the include graph and each buffer's overlay; an open buffer's text is the client's whatever the disk says, **also when the event names that buffer's own file** | goes | +| `$/cancelRequest` | nothing | goes | +| `workspace/didChangeConfiguration` | re-analyze **any** open buffer the new `largeFile.threshold` classifies differently (`reclassify_large_buffers`); an empty one makes the server pull, see (d) | waits | +| the client's **answer to a settings pull** (a response, not a notification) | the same, through the same `apply_settings` | waits | +| `workspace/didChangeWorkspaceFolders`, `workspace/didRenameFiles`, `workspace/didDeleteFiles` | the index only, by reading the handlers — deliberately left unproved: rare gestures, nothing to gain | waits | +| any notification the server does not handle | unknown | waits | +| a request; any other response | nothing (a request's flush analyzes applied text under the settings in force; the server acts on an `applyEdit` answer by showing a message) | goes | + +The table is `ahead::REACH` plus `Server::can_reach`. It is a list of what is +**proved harmless**, not of what is known to be dangerous: a method without a +row waits, and `every_notification_the_server_handles_says_which_buffers_it_can_reach` +reads `handle_notification`'s arms out of `notification.rs` and fails for an +arm without a row or a row without an arm. The two response kinds are an +exhaustive `match` over `Pending`, so a third kind of answer the server acts +on does not compile until it is classified. + +An older message can be unapplied in exactly four places, and the one test +above is applied at each: `held`; the part of the request's own burst being +set aside in front of it; **the next notification of its own burst, which +the loop is about to apply** (`answer_ahead_of`, "behaviour 2"); and the tail +of the burst whose message started the scan the request is answered inside, +which is only a count (`Server::behind`) — any message counted there is taken +as reaching the buffer. `behind` counts every notification but a cancel and, +since this round, an unapplied settings answer +(`Server::owes_a_state_change`) — which is also held in order now, like the +notification it is in all but name (Handshakes, "Changed, read this"). + +**Behaviour 2, kept — as the same rule, not as an exception.** Until the +escalation round `answer_ahead_of` had its own reason ("a notification that +does not name the buffer cannot change it"), and `held`/`ahead` shared it: a +notification with no `textDocument.uri` passed for harmless. That is QA's S1 +(a settings push names no buffer and reaches all of them), and it was open at +`held` and `ahead` too, not only where QA found it. All three now ask +`can_reach`. Removing behaviour 2 instead was built and measured first; the +work log has the numbers and why it stayed. + +**Nothing inside the server rebuilds a `Document` behind this path's back.** +Checked against every caller of `set_document`, `close_document` and +`apply_settings`: the quiet-period flush (`run`) and every notification's +flush analyze text already applied, under the settings in force — what (c) +does for one buffer; a scan, a widen, a save's one-file update and the +port-grace release touch the index, the overlays and the diagnostics; a +`workspace/applyEdit` the server sends, a formatting or `willSaveWaitUntil` +answer the client applies, all come back as the client's own `didChange`; +the re-classification runs inside `apply_settings`, i.e. as part of applying +a push or a settings answer, never between two messages. + +**(c).** A `didChange` only marks its buffer dirty; the analysis runs at the +next flush. A `same_file` request analyzes its own dirty buffer first +(`flush_buffer`: the flush's `set_document` + `locate_port_entry` + publish, +for that buffer) — under the settings in force, which (b) and (d) have just +established are the settings the request is owed. A clean buffer is always +current: `apply_settings` re-analyzes whatever a new threshold re-classifies +before it returns, and skips a dirty one, whose flush uses the new value +anyway. + +**(d).** Settings are awaited in two windows, and nothing `same_file` is +answered in either. *Staging*: the startup has asked for the settings and is +inside its wait; whatever a request was answered from could be re-classified +by the answer. The moment the answer is applied `answer_held_ahead` offers +everything staging held to this path again, so the wait is the client's round +trip and not the scan's head phase. *Announced*: a client that pulls says +"my settings changed" with an empty `didChangeConfiguration`; the server asks +(`Server::settings_announced`) and until that answer is applied the settings +in force are known to be stale. Two boundaries, both deliberate: the startup's +pull *after* its bound has run out does not count — a client that never +answers must not close the path for the session, and its late answer is +applied where it arrives in the stream, as a push is; and a request held +during the *announced* window is not released when the answer lands, it is +replayed when the scan ends (there is no scan-free moment to release it in, +as there is at startup). + +**The colours** (`semanticTokens/full`, `/full/delta`, `/range`) take the +same path with the same (a) and (b) — except that they are never offered +ahead of a notification about to be applied (`answer_ahead_of` takes +`same_file` requests only). They differ where the viewport lane made them +differ, because their answer is allowed to be a guess that one refresh +replaces: (c) a dirty buffer waits instead of being analyzed; (d) they go +during staging, and a buffer the settings re-classify is refreshed by +`reclassify_large_buffers` (a client that cannot be refreshed only ever gets +a *range* ahead, and keeps it until it scrolls or edits — the viewport +lane's rule for such a client, unchanged); (e) they read the overlay, which +a scan grows — which is also why a waiting watcher event does not hold +them: it changes only what the guess is a guess of. +What makes a guess safe is that it is **recorded as one** +(`index_unsettled` → `Viewport::early` / `guessed`) and compared with the +settled answer at the next index revision. That record had one gap, closed +this round: a colouring request answered ahead of a waiting watcher event +*while no scan was running* (something held from a rescan a replayed message +started) was recorded as settled, and no refresh followed the event's rescan; +`index_unsettled` now also says yes while anything is held. + +## Assumptions + +- A `Document`'s text, tokens, tree, `Semantics` and `` `define`` table are a + function of its text alone (`Document::new`, `refresh_overlay`'s comment: + "the single-file analysis is unaffected by other files, by construction"). + Only the `ExternalResolutions` overlay and everything behind + `Workspace::index`/`includes`/`candidates` depend on other files. +- **What can replace a buffer's `Document`**: `didOpen`, `didChange`, a + `didSave` carrying a different text and `didClose`, each for the buffer its + `textDocument.uri` names; and a **change of `largeFile.threshold`**, by a + `didChangeConfiguration` or by the client's answer to a settings pull, + for every open buffer the new value classifies differently + (`Server::reclassify_large_buffers`). Nothing else — the complete list, + and what each kind of message can do, is "When a request is answered + early" above. +- **Every setting and what reads it** — why `largeFile.threshold` is the + only one the precondition has to care about (fix round, QA Q1). Read off + `settings.rs` (`ClientSettings`) against every reader: + - `largeFile.threshold` — read by `Workspace::set_document` (`is_large`), + i.e. whenever a `Document` is built. The only setting a `Document` + depends on, which is why clause (d) of the precondition exists. + - `index.scope`, `index.scopeDepth`, `filelist` (and its `+define+` / + `+incdir+`), `exclude`, `maxFileSize`, `index.persist`, `index.cachePath`, + `logFiles` — the index and its store only. The early handlers read no + index; `` `ifdef`` branches are not selected by any setting: + `collect_defines` and `analyze` take the token stream and the tree and + nothing else (QA's filelist run with `+define+` found 0 differences). + The include resolution an `` `include`` line needs (filelist + `+incdir+`) is why definition waits there. + - `lint.*` (select, ignore, options, waivers), `lineLength`, `indent` — + the lint pass and diagnostics only. None of the early handlers lints; + the dirty-buffer flush publishes diagnostics, which is why it, too, is + not run before the settings. + - `style`, `indent`, `lineLength`, `uvmUtilsIndent`, `formatOnSave`, + `autoEnd` — formatting and on-type edits, which always wait. + - `inline.templates`, `inline.instantiation`, `inline.keywords`, `indent` + (templates' layout) — inline and ordinary completion, which always wait. + - Hover, definition, type definition, highlight, references, + prepareRename, signature help, symbols, folding, selection, linked + editing, scope pairs: `grep client_settings` over their modules + (`hover.rs`, `nav.rs`, `type_def.rs`, `symbols.rs`, `folding*`, + `selection.rs`, `linked.rs`, `pairs.rs`, `signature.rs`, `caret.rs`, + `includes::include_at`, `vlog_refactor::prepare_rename_here`) finds no + reader outside tests; their answer formats are fixed. +- `vlog_semantic`'s binder resolves a use (`Resolution::Resolved`) only to a + symbol of the same file, and `resolve_external` gives a target only to an + `ExternalCandidate`/`InheritedCandidate` use. +- The hierarchical-surface member key (`Semantics::member_key`) is `None` + exactly where no index record can name a symbol (scopes with no owner). +- VS Code facts as quoted above; other clients may mix requests any way — + every early answer is the settled answer, so the mix does not matter. + +## Design + +**A. One exemption, generalised — not a second mechanism.** `viewport.rs` +answered the three colouring requests from their buffer at the moment the +loop would hold them (`process_batch` → `answered_ahead`, `set_aside` for the +rest of a held burst, the widen's drains). That machinery moved, as a pure +move, to `server/ahead.rs` ("answering a request ahead of whatever holds the +rest") and now takes a second kind of request: one `same_file` proves local. +`viewport.rs` keeps what is about colours: which colouring requests may go +(`colours_may_go_ahead`), marking a range answer for the refresh +(`coloured_ahead`), the refresh. What differs for the new kind: + +1. **The answer is the settled answer**, so no refresh is owed and + `refreshSupport` is not consulted; it is answered through the same + `answer_flushed` (dispatch without the all-buffers flush). +2. **When it may go** is one rule for both kinds — the precondition + above — with the three differences for colours listed there. A dirty + buffer is analyzed for a `same_file` request (`Server::flush_buffer`: + exactly the flush's `set_document` + `locate_port_entry` + `publish`, + for that one buffer), because a request typed during a rescan otherwise + waited for the whole rescan; its overlay is computed against whatever + the index holds — as a `didOpen` applied mid-scan always was — and only + the text-derived part is read. Every other dirty buffer is left, in + order, for the next flush. +3. **Where it is offered**: at the moment the loop would hold it + (`process_batch` → `answered_ahead`); behind a held message of its own + burst (`set_aside`); behind the next notification of its own burst, + before that notification is applied and starts whatever it starts + (`answer_ahead_of`, `same_file` requests only — "behaviour 2"); behind a + `didOpen` that has been applied and is about to widen + (`open_then_widen`); between two files of a widen + (`answer_ahead_mid_widen`); and when the startup's settings land + (`answer_held_ahead`). The precondition is the same at every one. + +**Why ordering holds** (lane 71.7's invariants). Nothing here applies a +notification early: every notification is still applied by `process_batch` +in arrival order; an early answer only *reads*. A response goes out ahead of +older held requests — allowed by the protocol, and what the colours already +did. `flush_buffer` analyzes text that was applied. Each request is answered +once: `answered_ahead` sends and the request is not kept; a burst's cancel is +honoured where it goes ahead. + +**B. Completion through the relationship map.** + +1. **The related tier** (`completion/related.rs`, sortText `4`, between the + file's own tiers `1`–`3` and the workspace's `5`+): the members of every + package the scope chain at the cursor imports (`WorkspaceIndex::members_of` + — a wildcard all of them, an explicit import the one it names), the + members the enclosing class inherits (`members_of_chain` of its member + key), and after a backtick the `` `define``s of the headers the buffer's + `` `include``s reach (`includes::reachable_from` → `WorkspaceIndex::defines`). + Prefix below three characters, subsequence from three, exactly as the + other tiers. Instantiated modules are not a source: their names are what is + being typed at an item position (tier 0, which the context asks for), and + their ports are the exclusive member answer after `.`. +2. **No item is taken away**: a related item does not count against `LIMIT` + (`Items::related`), and a name it claims is skipped by the later tiers + without being counted — so every label of the 0.65.10 answer is still + offered, at every prefix, with the same edit and format. **What changes + for a name the related tier claims is its icon and detail** (QA Q2: 1 510 + of 1 548 180 items): they describe the declaration the file is related + to, where 0.65.10 showed the first declaration of that name anywhere in + the workspace — `NumRegs` as the imported `sysrst_ctrl_reg_pkg::NumRegs` + rather than `ac_range_check_reg_pkg::NumRegs`, `prim_secded_22_16_dec` as + the imported package's function rather than a module of that name, a + macro with the signature of the included header's `` `define``. Kept: in + each case the new one is what the name means here. An inherited member + names the class that **declares** it (`variable — root_c::zed_deep`), as + the workspace tier did — the first build said `inherited by `, + fixed in the fix round. Its own cap is `RELATED_LIMIT` (256), past + which the answer says `isIncomplete`. Renumbered tiers: index `4→5`, + templates `5→6`, keywords `6→7`, project words `7→8`. +3. **The payload** (`completion/wire.rs`): for a client that lists + `editRange` and `insertTextFormat` in `completionList.itemDefaults`, the + range every item replaces and the plain-text format are said once; an item + whose text is its label carries no edit at all, any other carries + `textEditText`. Lossless by construction (an item keeps its own edit when + its range differs, its own format when it differs) and done on the + serialized answer because `lsp-types` 0.97 has neither field. Read in + `main.rs` as `ClientAbilities::completion_item_defaults`. +4. **`completionItem/resolve` — measured, not built.** After the defaults, + `detail` is about half of what is left. A lazy `detail` must be exact, so + the item must carry an identity to recompute it from; for the bulk (tier 5, + `"enum variant — riscv_instr_pkg::S0"`) that identity is the candidate's + own `pkg::NAME` plus its kind — about 70 % of the bytes the detail itself + costs — because the fuzzy table scan does not keep same-name entries in a + stable order (`keep_best` uses `select_nth_unstable_by`), so a lookup by + label could name a different package. The constant details (`used in this + project`, `keyword`) are a few percent of a typical answer. Not worth a + second round trip per focused item; left documented. +5. **Not early.** Every completion path reads the index's tables; no answer + can be proved equal to the settled one from the buffer, so completion + still waits behind a scan (see "What remains"). + +## Results + +### Correctness + +- **Early == settled** (`server/tests/fast_actions_differential.rs`). Two + servers: the early one has an **empty index** and is asked mid-scan through + the real `process_batch`; the settled one indexed the tree. At every token + (start, identifier end, directive/string middle) of every sampled file, + every early-eligible request kind. Fast subset (fixture of the locality + shapes, with a filelist `+incdir+`): 3 428 early, 456 waited, **0 differ**. + Ignored long run over a scratch copy of the corpus and of OpenTitan `hw/`: + seed 7 — **1 617 255** early answers, 291 129 waited, **0 differ**; seed 11 — + **1 560 031** early, 278 857 waited, **0 differ**. Mutations caught: the + locality rule forced true (98 differ), the references rule forced true (35), + the include-line rule dropped (2, only with the filelist's `+incdir+`), the + prepareRename file-scope rule dropped (3, only with a duplicate unit). + Over LSP (`drv/earlyeq.py`, 20k files, seed 3): 2 400 requests sent into a + whole rescan, 1 677 answered before it ended, **0 differ** from the same + requests after settle; no completion, code lens or inlay hint went early. +- **Ordering / liveness** — see "Checks run" in the work log. +- **Completion superset** (`drv/compeq.py`, old = 0.65.10, new = this lane, + over LSP, each identifier typed one character at a time): seeds 7 and 11 × + OpenTitan and corpus — 1 918 identifiers, 31 304 completion requests per + server: **0** prefixes where the new answer lacks an old (label, range, + text, format); **0** identifiers where a VS Code-shaped client (re-ask while + `isIncomplete`, else filter) ends up without an item the old server offered + at the full identifier; **0** ranking violations (every local item's + sortText below every related one's below every workspace one's, tier 0 + aside). Bytes on the wire: 497.7 MB → 241.7 MB (−51 %). + +### Before / after + +Same harness, both binaries run back to back per tree on the same (shared) +machine; before = 0.65.10 (`c1c1407`), after = this lane. Medians of 3 runs +(held), 20 calls (settled), 10 (keystroke); ms. + +**Held — a request sent while a scan runs** (4k / 20k / 40k files): + +| moment | local hover | local definition, outline, folding, highlight | cross-file hover, module-level references, completion | +|---|---|---|---| +| startup scan (with the `didOpen`) | 637 → **2.3** / 752 → **1.9** / 908 → **2.1** | 637 → **56** / 752 → **172** / 908 → **324** | unchanged (645 / 761 / 918) | +| whole rescan (watched create) | 939 → **195** / 4 712 → **1 110** / 9 781 → **2 435** | the same | unchanged (931 / 4 745 / 10 050) | +| widen (folder scope) | 366 → **0.6** / 369 → **0.6** / 363 → **0.2** | 366 → **21** / 370 → **21** / 364 → **9** | unchanged (~370) | + +What is left of a local request's wait is the scan's prefix that drains +nothing: the discovery walk, and in a rescan the store open — the only +moments a request in the first write can be answered in are before it (the +hover, read with the `didOpen`) or at the first drain point (the rest of the +burst). Handshake request 2. + +**The "whole rescan" row, re-read in the escalation round.** Its 195 / +1 110 / 2 435 ms are not the rescan's undrained prefix. This harness (and +QA's `meas2.py`, same shape) deletes the previous run's file and goes on at +once; the server is then inside that delete's one-file update, which drains +nothing (Handshake request 9), so the next trigger and the requests behind it +are read as **one burst** when it comes back — and are answered by +`answer_ahead_of`, ahead of the trigger. The row measures the delete. With +the server idle when the trigger arrives the same local hover takes +**38 / 168 / 331 ms** (4k / 20k / 40k; that *is* the undrained prefix), and +0.1–0.2 ms when the client writes it together with the trigger. The +before-figures are unaffected (0.65.10 held everything for the whole +rescan). Table in the escalation round's work log. + +**Settled completion** (identical across 4k / 20k / 40k; ms, bytes, items): + +| position | ms | bytes | items | +|---|---|---|---| +| statement start (empty prefix) | 1.46 → 1.19 | 132 261 → **83 848** | 512 → 715 | +| expression, 1 / 2 / 3 letters | 1.40 / 1.39 / 4.16 → 0.90 / 0.85 / 3.67 | 132–136 K → **62–64 K** | 512 → 528 / 513 / 539 | +| after `aes_pkg::` | 0.70 → 0.42 | 58 569 → **22 461** | 259 | +| after a backtick | 0.16 → 0.13 | 18 398 → **10 212** | 54 | +| module item, empty / `a` / `ae` | 1.48 / 1.59 / 1.55 → 1.22 / 1.07 / 1.03 | 129–155 K → **65–84 K** | 512 → 715 / 560 / 533 | +| port `.` / parameter `.` | 0.07 / 0.03 → 0.06 / 0.03 | 2 937 / 301 → 1 486 / 285 | 12 / 1 | + +The extra items are the related tier (the old 512 are all still there). +Relevance — `aes_pkg` members matching the prefix that are offered: + +| prefix | 4k before → after | 40k (`ot10w`) before → after | +|---|---|---| +| `s` | 16 / 28 → **28 / 28** | 12 / 28 → **28 / 28** | +| `st`, `sta` | 7 / 7, 7 / 7 | 6 / 7, 6 / 7 → **7 / 7, 7 / 7** | +| `a` (module item) | 8 / 56 → **56 / 56** | 8 / 56 → **56 / 56** | +| `ae` (module item) | 34 / 34 | 10 / 34 → **34 / 34** | + +**Unchanged, as they should be**: every other settled request (within +±0.1 ms at every size), the keystroke rows (932 / 2 025 / 20 021-line +buffers: ~1.7 / ~3.1 / ~21–27 ms), `workspace/symbol` (`a`: 8 / 55 / 118 ms) +and `moduleHierarchy` (23 / 133 / 274 ms). + +## Handshakes + +**Consumed:** +- `Server::must_hold`/`must_wait`, `held`, `behind`, `dirty`, `staging`, + `scanning` (read-only) — lane 71.7's bookkeeping, through `ahead.rs`; and + `Pending` (which answers from the client the server acts on). +- **Changed, read this (escalation round): the client's answer to a + settings pull is ordered like a notification.** Lane 71.7 ordered "every + notification other than `$/cancelRequest` — the only messages that change + what the server holds" and exempted responses altogether. One response + does change what the server holds: the answer to a `workspace/configuration` + pull, applied by the same `apply_settings` a push is. Since round 3 that + can re-analyze a buffer, so the exemption stopped being harmless, and the + randomized differential found both directions of it (O1, O2 in the work + log). `Server::owes_a_state_change` (any notification but a cancel, **or + an unapplied settings answer**) now replaces `changes_state` in the three + places the order is kept: what `Server::behind` counts (`process_batch`), + and both clauses of `must_hold` — so such an answer waits behind an older + unapplied state change, and a newer one waits behind it. Never one message + fewer held than before; one more in exactly these cases. Unchanged: an + answer with nothing older unapplied is applied where it is read; every + other response is never held; and **staging** still takes the answer out + of `held` ahead of everything (`take_the_answer_out_of_held`, measured in + 2026-09 — the startup depends on it, and nothing `same_file` is answered + before it). `docs/features/scan-ordering/README.md` ("Exempt altogether: + responses") is the lead's to amend if this stands. +- `viewport-highlight`'s exemption, moved as a pure move into `ahead.rs`; + its tests unchanged except their "a request that waits" witness (a hover, + now early on a local name) became a code lens. +- `Document` fields; `Semantics::{reference_at, reference_id_at, symbol_at, + member_key, file_scope, scope}`; `Reference::resolved`; + `WorkspaceIndex::{members_of, members_of_chain, defines, file_id}`; + `includes::reachable_from`. **No `vlog_semantic` change**. + +**Promised:** +- `same_file::answered_by_the_buffer(doc, method, params)` — true only where + the dispatch's answer reads nothing but the buffer's text-derived analysis. + A handler change that makes one of its arms read the index or the overlay + must change the matching arm here; the differential test is the alarm. +- `includes::include_at` (new, `pub(crate)`), `type_def::type_name` + (`pub(crate)`), `candidates::macro_of` (`pub(crate)`) — visibility only. +- `ClientAbilities::completion_item_defaults` (new, read in `main.rs`). +- Completion `sortText` tiers renumbered (`4`→`5`, `5`→`6`, `6`→`7`, `7`→`8`; + `4` is the related tier). `tests/e2e.rs`'s three hard-coded digits updated. +- Responses for the new early kinds can go out ahead of older held requests — + allowed by the spec, as the colours already did. +- `ahead::REACH` — one row per notification `handle_notification` handles, + saying which buffers' `Document`s applying it can change. **A new + notification arm needs a row** (a test fails until it has one), and a + handler that starts changing a buffer it does not name must move its row + to `Reach::Any`. Likewise a new `Pending` kind must be classified in + `Server::can_reach` (it does not compile otherwise). +- `Server::settings_announced` (new): set by an empty + `didChangeConfiguration`, cleared by the answer to the pull it caused. +- `Server::index_unsettled` also says yes while anything is held + (`viewport.rs`): one more case in which a colour answer is recorded as a + guess and compared at the next index revision — never a case fewer. +- `probe::went_ahead` / `take_ahead` (test-only): which requests were + answered ahead, for the differential in `tests/fast_actions_bursts.rs`. + +**Requests (not done here, out of scope):** +6. ~~*A buffer analyzed before the settings answer keeps a default-threshold + analysis*~~ — **resolved in round 3** (with QA's R1, the same bug): the + settings answer, and any later threshold change, re-analyzes the open + buffers whose mode flips. One consequence for another lane's document: + `docs/features/large-file-mode/README.md` (lines 108 and 329) still says + a new threshold "takes effect at each buffer's next change"; its own test + (`server/tests/large_file.rs`, renamed `…_takes_effect_on_open_buffers_at_ + once`) was updated with this lane, the prose is the lead's to amend. +7. *An open buffer in a folder `lucisv.toml` excludes is indexed by the + first rescan or save after it opens* (QA Q4, pre-existing since ≤ 0.65.5; + repro `scratchpad/qa712/drv/excl.py`): a fresh server with the same buffer + open leaves it out; the hierarchy then lists it and completion offers its + words. It is every `rand_run2.py` divergence this lane reported. +8. *Whether a large open buffer is in the index depends on history* (QA + S2, pre-existing on 0.65.10; repros `scratchpad/qa712/drv/openorder.py`, + `largesave.py`). A buffer on the large-file fast path contributes nothing + to the index when it is open at scan or save time, but keeps its disk + record when it was opened *after* the scan. So cross-file definition, + hover, references and prepareRename into such a file depend on when it + was opened, saved or flipped: on base, opened before the scan → + `prepareRename` of a twice-declared unit says renameable, after → + ambiguous; an edit crossing the threshold then a save → another file's + definition into it becomes `[]`. Round 3 added the settings push as one + more way to flip a buffer (it re-analyzes, and like an edit does not + reindex); it did not widen the inconsistency. Not fixed here — the index + lane's: either always keep the disk record of a fast-path buffer or + always drop it, at open, save, flip and scan alike. +9. *A one-file update that drains nothing* (`Server::reindex_one`, measured + this round): the watcher event for a **deleted** file the index holds + takes 0.2 / 1.1 / 2.3 s at 4k / 20k / 40k files in one call, with no + drain point, so every request sent meanwhile waits for it — the early + path included (it is not a scan, and nothing is "held"). It is what the + lane's "whole rescan" row measured as the local request's remaining + wait; see the escalation round's work log. +10. *The pull model outside a scan.* A client that announces a settings + change with an empty push is answered under the old settings by the + ordinary path until its answer to the pull arrives (base behaviour, any + request, no scan needed). The early path now waits in that window; the + ordinary path does not, and making it wait is a settings-lane decision. +1. *A whole rescan for one created file* (`state/`, the re-index lane): 1.0 / + 5.8 / 10.8 s at 4k / 20k / 40k; completion, references on module-level + names, code lenses, inlay hints and everything cross-file wait for it. +2. *Drain during discovery and the store open* (viewport's request 2, + again): the first ~500 ms of a rescan at 20k files drain nothing, which is + now most of what a local request waits during a rescan. +3. *`workspace/symbol`* (`vlog_semantic::WorkspaceIndex::workspace_symbols`): + 126 ms at 40k for a one-letter query — a bounded selection instead of a + whole sort. +4. *`lucisv/moduleHierarchy`*: 26 MB / 144 ms at 40k files, re-fetched on + every index change while the view is open — a paged or incremental + snapshot (`design_hierarchy.rs`, `editors/vscode/hierarchyView.js`). +5. *Keystroke cost of a 20k-line buffer*: the reparse, 19–33 ms. + +## Status / TODO + +- [x] Step 1: measured a/b/c/d at 4k / 20k / 40k over LSP; VS Code facts from + source; the three classes. +- [x] Pure move: the exemption's burst machinery out of `viewport.rs` into + `server/ahead.rs`; suites green with no behaviour change. +- [x] `same_file.rs`: the per-request locality rule, with unit tests + (`same_file/tests.rs`, 13). +- [x] Generalised exemption: `same_file` requests answered ahead of a scan, + a widen, a held batch and a rescan's own trigger; one dirty buffer + analyzed for its own request (`ahead.rs`, `diagnostics.rs`). +- [x] Server tests (`server/tests/fast_actions.rs`, 8; `fast_actions_staging.rs`, 3). +- [x] Differential early == settled: fast subset + ignored long run, two seeds. +- [x] Related completion tier (imports, inherited members, included macros), + outside the cap (`completion/related.rs`, 5 tests). +- [x] `itemDefaults` payload for clients that take it (`completion/wire.rs`). +- [x] Completion superset over LSP, two seeds × two trees. +- [x] Ordering drivers, oracle, ignored release runs, gates — see work log. +- [ ] `completionItem/resolve` — measured, not built (Design B.4). +- [x] Escalation round: S1 and the three holes beside it; one precondition in one place (`answer_from_the_buffer`, "When a request is answered early"); `REACH`; clause tests + the burst differential; stale docs; S2 recorded. +- [x] Round 3: R1 / Handshake 6 (re-classify on threshold change; staging waits, answered when settings land), R2 (alias), R3 (set equality). +- [x] Fix round: Q1 (staging + dirty waits), Q2 (declaring class; doc says what changes), Q3 (complete table + test), Q4/Q6 recorded. + +## Work log + +### 2026-11-19 — dev agent (Opus 5.5) + +**Step 1 first.** Harness and trees above; the tables were written before +any code. The finding that decided the design: nothing a single request does +scales with the workspace — every handler on the list is under a +millisecond at 40k files — except the two workspace-wide ones; what scales is +**the wait** (a whole rescan holds every request: 1 / 5.8 / 10.8 s) and, for +completion, **relevance** (the imported package's members are cut off by +alphabetical workspace names) and a flat **130 KB** per keystroke. + +**Pure move first** (CLAUDE.md's rule for a file that would become "about +more than colours"): `answered_ahead`, `set_aside`, `apply_in_burst`, +`open_then_widen`, `answer_colours_mid_widen`, `text_is_current`, +`notified_uri` and the module-doc paragraphs that describe them moved +verbatim from `viewport.rs` to the new `server/ahead.rs`; the server suite +was green (1 942 + 106 + …) before anything else changed. Then the +generalisation, in place: `answer_from_the_buffer` moved to `ahead.rs` and +takes either kind; `answer_colours_mid_widen` became `answer_ahead_mid_widen`. + +**Deviations from the brief, with reasons.** +- *A dirty buffer is analyzed for a `same_file` request* rather than held. + The viewport lane holds a dirty buffer's colours because an answer off a + cross-file-blind re-analysis flips colours; the `same_file` handlers read + no overlay, so no flip is possible, and holding meant a hover typed during + a rescan waited for the whole rescan. Colours keep their rule. +- *Answering ahead of a burst's own rescan trigger* (`answer_ahead_of`) was + not in the brief; the first measurement showed why it is needed (the + requests the editor writes with a watched-file event rode the whole rescan + in the burst that started it — 4.7 s at 20k files in one of three runs). +- *No staging exclusion.* Built first, measured, removed: it held the + session's first hover for 888 ms (20k) and was not needed for equality. +- *completionItem/resolve not built* — Design B.4 has the measurement. +- *Completion is not answered early.* No completion path can be proved equal + from the buffer alone; the brief's "when the candidates in scope are local" + has no case that a test could hold without reading `member.rs`'s index + lookups, and an early partial list would break safety net 1. + +**Changed outside the obvious handler files** (all inside the stated scope): +`main.rs` (one line, the new ability), `server/index.rs` (the renamed drain +and its comment), `server/diagnostics.rs` (`flush_buffer`, +`analyze_and_publish` — the flush loop body, now shared), `includes.rs` +(`include_at`, split out of `definition`), `type_def.rs` and `candidates.rs` +(visibility only). Tests changed by design: `viewport/tests.rs` and +`tests/scan_ordering.rs` used a hover as "a request that waits" — a hover on +a local name now goes ahead, so the witness is a code lens (helper renamed +`lens`, one test renamed `…_while_a_lens_ahead_of_them_waits`; no assertion +weakened); `tests/e2e.rs`'s three completion sortText digits (`4`→`5`, +`7`→`8`, `5`→`6`, `6`→`7`). + +**Production lines** (non-blank, non-comment, before `mod tests`): new +`server/ahead.rs` 175, `same_file.rs` 97, `completion/related.rs` 113, +`completion/wire.rs` 47; `server/viewport.rs` 208 → 102, +`completion/mod.rs` 286 → 301, `server/mod.rs` 224 → 227, +`server/dispatch.rs` 494 → 503 (the dispatch table), `main.rs` 388 → 390. +Nothing near 600. + +**Checks run** (release binary `server-final`, on scratch copies only): + +| check | result | +|---|---| +| `cargo fmt --all -- --check`, `cargo clippy --all-targets -- -D warnings` | clean | +| guarded suites | lucisv_server 1 971 + 106 + 3 + 1 pass (was 1 942 + 106 + …); vlog_semantic 435; lucisv_mcp 388 | +| `tools/gates.sh` (full, `-c` = scratch corpus copy) | **PASS** — lucisv_server 2 081/0, corpus 814/6 as before, node 37/0, cross pass | +| `node --test editors/vscode/*_test.js` | 37/37 | +| ignored `viewport_sweep` | 1 267 files, 7 602 windows, 541 616 / 559 725 agree, 0 other — identical to 0.65.10 | +| ignored `random_bursts_long_run` (lane 71.7, mixes hover / definition / documentSymbol — now early) | pass | +| ignored `a_seeded_sweep_over_the_corpus_holds` / `…_opentitan_sample_holds` | pass / pass | +| ignored `early_answers_equal_settled_over_real_trees`, seeds 7 and 11 | 0 differ (see Results) | +| `ord3.py` (QA 71.7 ordering attack) corpus seeds 712, 713 workspace, 714 folder; OpenTitan 715 workspace | 0 fails each; fresh oracle 165 / 168 / 102 / 30 answers equal | +| `c717.py` (cold startup, bursts of request + `didOpen`), seeds 1, 2 | all 18 answered by 0.19 s / 0.15 s (scan ends 1.5 s), no duplicates; the 5 answers differing from settled (seed 1) are all `semanticTokens/full` — the colour guess the refresh replaces; no hover / definition / documentSymbol differs | +| `livelock.py`, `livelock2.py hover/delta` | hover 165 ms; `full(B)` 62 ms (viewport README: 658); delta on a dirty buffer held to 628 ms as designed | +| `f6.py tail/held/control` | server holds v3 = client v3, all three | +| `earlyeq.py` (over LSP, 20k files, seed 3) | 1 677 early of 2 400, 0 differ | +| `compeq.py` seeds 7, 11 × OpenTitan, corpus | 0 / 0 / 0 (Results) | +| oracle `small.py` pull | 96 scenarios, only `NEGCTL-silent` diverges (both scopes) — the negative control, as it must | +| oracle `small.py` push | 96 scenarios, only `NEGCTL-silent` diverges (both scopes) | +| oracle `outside.py` pull and push | no divergence | +| oracle `rand_run2.py` corpus 41, 42; OpenTitan 43, 44 | OpenTitan 43: 0 divergent checks. Corpus 41, 42 and OpenTitan 44 hit one divergence class each (corpus 41: a module named `eventually` in the excluded `qa_excl/` files, in the hierarchy and a completion; 42 / 44: a completion one server answers `null`, which crashes the driver's own printer) — **the same classes on 0.65.10 with the same seeds** (base corpus 41 diverges identically, base corpus 42 crashes identically at step 50), so pre-existing and not this lane's; timing moves the step they surface at. Not investigated further | + +### 2026-11-19 — dev agent (Opus 5.5): fix round (QA Q1–Q6) + +- **Q1 (the FAIL), fixed** in `answer_from_the_buffer` (`server/ahead.rs`): + while the startup waits for the settings (`staging`), a `same_file` + request on a **dirty** buffer waits, so no buffer is built under the + default `largeFile.threshold`; a clean buffer still goes ahead. New + `server/tests/fast_actions_staging.rs` (3 tests): an edit before a 300-byte + threshold arrives → the hover answers `null` early-or-not, as a session + given the settings first does; the reverse (an 8 MiB threshold, a 5 MiB + edit) → a full card; a buffer opened in staging answers early exactly what + it answers after the settings. The first two **fail on the unfixed tree** + (run with the condition reverted: both FAILED, the first with the full + card QA saw), the third passes on both. QA's `stg.py` (copied to + `dev712/ext/qa712`): the edited row now matches 0.65.10 — not answered + before the settings, `null`, `null`; the "didOpen big" row answers early + the same card 0.65.10 and the settled session give, where a fresh server + says `null`: 0.65.10's behaviour, recorded as Handshake request 6. + Every setting and its readers are enumerated under Assumptions. +- **Settings arriving later do not re-analyze a buffer** opened in staging + (checked: `set_client_settings` / `apply_settings` rebuild nothing; the + large-file threshold reaches a buffer at its next open or change). So an + early answer on a clean buffer equals the session's answer after the + settings — pinned by the third test — and differs from a fresh server's + only in the pre-existing way (request 6). Fixing that is a settings-lane + change and would make every staging request wait; not done here. +- **Q2**: the inherited-member detail names the declaring class again + (`declaring_class` walks the `extends` chain the index records; + `variable — root_c::zed_deep`), with a two-level test; the README + (Design B.2), `related.rs`'s module doc and the changelog paragraph now + say exactly what changes for a name the related tier claims (icon and + detail, never label, edit or format) and why the new one is kept. +- **Q3**: the per-request table lists every one of the dispatch's 40 arms by + full method name, and `same_file::tests::the_readme_table_names_every_ + request_the_dispatch_answers` reads the arms out of `dispatch.rs` and fails + for any without a row (checked by deleting `codeAction/resolve` from the + table: it failed naming it). +- **Q4**: recorded as Handshake request 7. +- **Q5/Q6**: behaviour 2 (`answer_ahead_of`) kept, with the reason under + Assumptions. QA's `wid.py` rule (hover on a declaration must wait for the + widen) is the driver's to update — that hover is local by design. + +**Checks, fix round** (binary `server-fix`): `cargo fmt --check`, `clippy +--all-targets -D warnings` clean; guarded lucisv_server 1 976 + 106 + 3 + 1; +full `tools/gates.sh` **PASS** (lucisv_server 2 086/0, vlog_semantic 435, +lucisv_mcp 388, corpus 814/6, node 37/0, cross pass); ignored differential +seeds 7 and 11: 1 633 090 / 1 560 031 early, **0 differ**; `ord3.py` 712, +713, 714 (folder), 715 (OpenTitan) and `ord3t.py` 716: 0 fails, fresh +oracles equal; `c717.py` seeds 1, 2: all answered by 0.19 s, no duplicates, +only `semanticTokens/full` differs from settled (colours, as designed); +`livelock` 168 ms, `livelock2` hover 68 ms / delta 616 ms; `f6` tail / +held / control: v3 = v3; `compeq.py` seed 13 on OpenTitan: 480 identifiers, +7 332 requests, 0 / 0 / 0, 159.3 → 79.8 MB. QA's staging differential +(`fadiff.py`, my copy): corpus 48+48 files, OpenTitan 32 files — every early +answer equal to the settled session's and to a fresh server's (**0 +differ_S, 0 differ_F**; 59 294 + 42 139 + 43 571 early answers). Its +"answered in staging, not early" check fires in every group, and its +`overflow` flag with it: a request on an edited buffer now waits for the +settings, and — by lane 71.7's order contract — holds its write's tail, +other buffers' `didOpen`s included, so one write outlives the 2 s +configuration bound and the answers after it come from the ordinary +startup scan, not from this path. The sentinel was moved to an unedited +buffer in my copy; the cascade is the contract, not a defect, and 0.65.10 +held every one of those requests anyway. + +### 2026-11-19 — dev agent (Opus 5.5): round 3 (QA round 2: R1, R2, R3) + +- **R1 + Handshake 6, fixed at the root.** `apply_settings` + (`server/notification.rs`) — the one applier for the startup's answer and + every later push — now calls `Server::reclassify_large_buffers` + (`server/large_file.rs`) with the threshold it had: when it changed, every + open, clean buffer the new value classifies differently (normal ↔ large) + goes through the flush's own path (`analyze_and_publish`: analyzed, + connection located, diagnostics republished once) and a capable client + gets one `workspace/semanticTokens/refresh`; a dirty buffer is left to its + flush, which uses the new value anyway; an unchanged threshold costs one + comparison. Like an edit it does not reindex (next save or rescan; before + the startup scan there is no index yet). `Workspace::is_large` became `pub` + (one word, `state/buffers.rs`), and `scope.rs`'s doc comment says so. +- **The staging rule changes accordingly** (`ahead.rs`): with re-analysis, + a clean buffer's answer before the settings can differ from the answer + after, so no `same_file` request is answered during staging; instead + `answer_held_ahead` (called where `stage_for_configuration` ends) offers + everything staging held to the ahead path the moment the settings are + applied. Measured: startup outline 3.9 ms vs 0.65.10's 537 ms (QA's + `startup.py`, 4k), the meas.py startup row unchanged (local hover + 2.6 / 2.5 / 1.9 ms at 4k / 20k / 40k). +- **Tests** (`fast_actions_staging.rs`, now 7): opened before a 10-byte + threshold → equals a fresh server and is answered right when the settings + land; opened 5 MiB before an 8 MiB threshold → leaves the fast path; QA's + s6 (edited, then flushed by another `didOpen`, in staging); mid-session + both ways with parse counts (onto the fast path: 1 re-analysis; back: 1; + an unchanged push: 0); a mode change sends exactly one token refresh and a + non-change none. With the `reclassify` call removed, 4 of them fail. + `server/tests/large_file.rs`'s test of the old rule ("the open buffer + keeps the mode it was built in") now asserts the new one and is renamed. +- **R2**: `declaring_class` takes `vlog_semantic`'s alias hop too (a + typedef held once naming a class), so `leaf_c extends alias_t` names + `mid_c::zed_mid`; test fails without the hop. +- **R3**: the table test is a set equality between the dispatch's arms and + the backticked methods of the table's first column; a stale + `textDocument/moniker` row fails it, no count. + +**Checks, round 3** (binary `server-r2`): fmt, clippy clean; guarded +lucisv_server 1 981 + 106 + 3 + 1; full `tools/gates.sh` **PASS** +(lucisv_server 2 091/0); differential fast subset (suite) + long seed 7: +1 633 090 early, 0 differ. QA's `stg2.py`: every case equals a fresh +server (s1 `null`, s2 card, s3 `null` / `null` / `null`, s4, s5 `null` +10/10, s6 `null` 10/10). QA's staging differential at threshold 400 (my +copy `fadiff_r3dev.py`, which answers the settings 0.3 s after its writes +instead of waiting for a probe that now waits): adversarial 13 files and +corpus 24, **S ≠ F 0** (was 2 877 on the adversarial files), early 147 + +44 235, 0 differ from S or F, nothing answered during staging. `ord3.py` +712–715 and `ord3t.py` 717: 0 fails; `c717.py` seeds 1, 2: no duplicates, +last answers 0.18 s / 0.64 s (seed 2's requests now wait for its settings +answer; base was 3.3–3.6 s per QA); `livelock` 169 ms, `livelock2` 69 / +620 ms; `f6` v3 = v3 ×3; `compeq.py` seed 17 corpus: 480 identifiers, +7 198 requests, 0 / 0 / 0, 71.5 → 32.8 MB. + +### 2026-11-19 — dev agent (Fable 5.2): escalation round (QA round 3: S1) + +**What was wrong, in one sentence.** "May this request be answered now?" was +decided in one function, but "can this older message change the buffer?" was +answered in two places with two reasons, and both reasons were *"a +notification that names it"* — a deny-list in disguise: anything with no +`textDocument.uri` passed for harmless. Round 3 made a settings push able to +rebuild any buffer, and nothing forced that fact into either place. + +**S1 and what was beside it.** Each is a test that failed on the round-3 +tree (`tests/fast_actions_precondition.rs`: 10 of the 15 tests first +written failed there; C1's, O1's and O2's, added as they were found, each +failed before its fix): + +| # | hole | where the code was looser than the precondition | fixed by | +|---|---|---|---| +| S1 | `[didChange A, push threshold, hover A]` and `[push, hover A]`: the hover answered ahead of the push (QA) | `ahead.rs` `answer_ahead_of`: passed `[notification]` as what is ahead, but `nothing_unapplied_for` only looked for a notification *naming* the buffer | `can_reach` + `REACH` | +| H2 | the same push **held** behind a request (`[lens, push, hover A]` mid-rescan; and staging's `[open, lens, push, hover]` released by `answer_held_ahead`): the hover answered ahead of it — QA's one-line fix would not have closed this | `ahead.rs` `nothing_unapplied_for` (`held`, `ahead`), reached from `set_aside`, `answer_held_ahead`, `answer_ahead_mid_widen` | the same | +| H3 | the client's **answer to a settings pull** held behind a request (`[lens, answer, hover A]`): a response, so it named nothing either | the same function | `can_reach`'s exhaustive `match` over `Pending` | +| H4 | that answer in the **tail of the burst that started the rescan** (`[created, answer]`, hover arriving mid-scan): `behind` counted notifications only, so the tail looked empty | `server/mod.rs` `process_batch` (`unapplied`), `ahead.rs` `open_then_widen` | `Server::owes_a_state_change` | +| H5 | a client that **announces** new settings with an empty push: until its answer to the pull arrived, requests were answered ahead from settings known to be stale | `ahead.rs` (only `staging` was consulted) | `Server::settings_announced`, `settings_awaited` | +| H6 | any notification the server does not know, and a document notification whose params name no buffer, passed for harmless | `nothing_unapplied_for` | default `Reach::Any` | +| O1 | not an early answer, found beside H3: with `[lens, settings answer]` held by a rescan, a newer `didChangeConfiguration` was applied at once, ahead of the answer; the older settings were in force afterwards (0.65.8 on) | `server/mod.rs` `must_hold` (`held.iter().any(changes_state)`) | the same predicate as `behind` | +| O2 | the mirror image, found by the long differential (seed 7, round 139): a settings answer read mid-rescan in a burst of its own was applied at once, **ahead of an older push and edit the rescan was holding**; a request replayed behind them was then answered from a text and a threshold the client never had together | `server/mod.rs` `must_hold` (`Message::Response(_) => false`) | a settings answer waits behind an older unapplied state change | +| C1 | colours answered ahead of a waiting watcher event while no scan was running were recorded as settled; no refresh followed the event's rescan (in 0.65.10 too) | `server/viewport.rs` `index_unsettled` | `\|\| !self.held.is_empty()` | + +Checked and found tight: `hold`, `answered_ahead`, `set_aside`, +`apply_in_burst` (order and exactly-once unchanged); `open_then_widen` +(the `didOpen` is applied before anything is answered); `reindex_widened`'s +drain; `apply_settings` (re-classifies before the rescan it may start, so a +scan's drains never see a buffer in the old mode); +`reclassify_large_buffers`; the staging flush in `handle_notification` +(what it analyzes under the defaults the settings answer re-classifies); +`same_file.rs` (reads nothing but the `Document`; `Document::new` takes the +text, and the index only for the overlay). `didSave` re-analyzes only when it +carries a different text; `didChangeWatchedFiles`, a rename or delete of the +buffer's own file, and a disk change under an open buffer reach no +`Document` (`docs.insert` is in `set_document` only, `docs.remove` in +`close_document` only, `values_mut` in the four overlay refreshes only). + +**The change.** One rule, one place: the doc comment of +`answer_from_the_buffer` and "When a request is answered early" above; the +module documentation of `ahead.rs`, the README's Assumptions and Design now +point there instead of restating parts of it. In code: `ahead::REACH` (a row +per notification the server handles: no buffer / the buffer it names / any +buffer), `Server::can_reach` (a method without a row, and a settings answer, +reach any buffer), `settings_awaited`, `owes_a_state_change`. A test reads +`handle_notification`'s arms out of `notification.rs` and requires set +equality with `REACH`'s rows; a new `Pending` kind does not compile until +`can_reach` classifies it. + +**Behaviour 2: removed, measured, put back as the same rule.** The lead's +default was to remove `answer_ahead_of`. I built that first (binary `rm`) and +measured it against round 3 (`r3`) and the final tree (`esc2`), with a driver +that makes the two cases explicit (`scratchpad/dev712f/drv/b3.py`; a local +hover; ms; medians of 6 / 3 / 2 runs at 4k / 20k / 40k files): + +| the server, when the watcher event arrives | r3 | removed | final | +|---|---|---|---| +| idle; requests 5 ms later | 41 / 163 / 328 | 31 / 168 / 327 | 38 / 168 / 331 | +| idle; requests in the same write | 0.2 / 0.1 / 0.1 | **1 250 / 6 496 / 331–16 178** | 0.2 / 0.1 / 0.1 | +| busy in a handler that drains nothing (a delete's one-file update: 0.2 / 1.1 / 2.3 s) | 180 / 1 032 / 2 257 | **1 398 / 7 567 / 16 495** | 171 / 1 024 / 2 252 | + +(the whole rescan, i.e. what a code lens in the same burst waits: 1.2–1.4 / +6.0–7.6 / 13–18 s). So removing it costs nothing when the trigger is read +alone, and **the whole rescan** — back to 0.65.10's wait — whenever the +trigger and the requests behind it are read as one burst. That is not only +the one-write case QA's Q6 called rare: it is every time the server is busy +outside a scan while they arrive, and it is what the lane's own headline row +and QA's `meas2.py` measured (see Results). With `rm`, QA's loop gives +1 400 / 7 250 / 14 800 ms where round 3 gave 220 / 1 054 / 2 350 +(`drv/b2.py`, 10 / 5 / 3 runs, every run). A user deleting a file and going +on working would notice. + +So it stays — but it no longer has a rule of its own. `answer_ahead_of` +passes the notification, and whatever lies between it and the request, to the +same `can_reach` test as `held` and `ahead`: a request goes ahead of the next +notification of its burst only if `REACH` proves that notification cannot +change its buffer. Behind a settings push it waits (S1's two forms: `null` +in 10/10). The positive invariant the lead asked for in that case is the +`REACH` table; the structural enforcement is the default (`Reach::Any`), the +arms test and the `Pending` match. + +**Tests** (`lucisv_server` unit suite 1 981 → 1 999; one removed, one changed, see below): +- `tests/fast_actions_precondition.rs` (18): S1 dirty and clean; the hover + that goes ahead of a watcher event in its burst but not of a push beside + it; one or more per clause — (a) not open; (b) a held push that moves the + threshold and one that does not, a held settings answer, that answer in a + rescan trigger's tail (real rescan, scripted mid-scan arrival), announced + settings, a push that must not overtake a held settings answer and an + answer that must not overtake a held push (O1, O2), each own-buffer + notification (change, close + reopen, save with + text, close), every notification not proved harmless (folders, rename, + delete, an unknown method, a document notification naming nothing), and + the ones proved harmless (another buffer's edit and open, watcher events + including one naming the buffer's own file, a cancel, an answer the server + ignores); (c) a dirty buffer analyzed under the settings in force, both + ways; (d) what staging held behind a push; the colour record (C1); the + table test. A request that must wait is asserted **not** answered ahead, + answered exactly once, and equal to the same request asked after settling. +- `tests/fast_actions_bursts.rs`: the randomized differential, rebuilt + around the right oracle. A seeded client mixes edits, closes, reopens and + saves of two buffers whose sizes straddle the thresholds; pushes moving + the threshold among 0 / 200 / 1 000 / 4 MiB and pushes moving only the + indent; empty pushes and late settings answers; watcher events that cost a + real rescan, anywhere in the first burst; folder, rename and delete + events; an unknown notification; a stray cancel. The early server gets the + round as the loop would (later bursts scripted at the rescan's interleave + points); a reference server gets the same messages **one per burst**. + Every request answered once by both; every answer given ahead is an + answer the reference gives that request **at its place in the stream or + after a later message of the round** — a state the client had, no older + than the request (a request that waited and went ahead later may see what + was applied meanwhile, as any late answer could; never an earlier state, + never one that did not exist); both servers equal on every buffer once + settled. Fast: 8 seeds × 40 rounds — 1 448 requests, 384 answered ahead, + 1 280 settled comparisons, 0 differ. Ignored long run: see checks. It + earned its keep before it was finished: O2 is its find, and its first + oracle (plain equality with the reference) was wrong in a way worth + knowing — a request that waits and goes ahead later is answered from what + has been applied by then. +- **Mutations** (scratch copy, `scratchpad/dev712f/mutate.sh`, log + `logs/mut2.log`; the unmutated copy passes 34/34): each of twelve + one-line weakenings fails at least one test — + + | weakening | fails | + |---|---| + | a settings push reaches no buffer (`REACH`) | 6 precondition tests and the burst differential | + | a settings answer reaches no buffer (`can_reach`) | the held-answer test | + | a settings answer is not a state change (`owes_a_state_change`) | the tail test, O1's and O2's | + | announced settings are not awaited | its test | + | an unknown notification reaches no buffer | the every-notification test | + | a document notification naming no buffer reaches none | the same | + | `held` does not unsettle the index (`index_unsettled`) | the colour test | + | staging does not hold `same_file` requests | 5 staging tests | + | a buffer's own `didChange` does not hold | 5 tests, the differential and the table test among them | + | folder changes reach no buffer | the every-notification test | + | a settings answer is never held (`must_hold`, O2) | O2's test | + | a notification does not wait behind a held settings answer (O1) | O1's test | + + The differential on its own (long run, seed 7; `logs/mutlong2.log`) + catches the push weakening at round 5 and the settings-answer-ordering one + at round 139, as the fast run catches the push and own-edit ones. It does + not catch the other two it was tried against, and cannot be expected to: + a settings answer held *ahead of* a request needs the one pull that is not + an announced one (the startup's, once per session), and "announced + settings are awaited" is stricter than its oracle — a one-message-at-a-time + server answers under the old settings in that window too. Those two + clauses rest on their directed tests. +- Removed: `fast_actions.rs`'s + `it_goes_ahead_of_a_rescan_trigger_in_its_own_burst_unless_the_trigger_names_its_buffer` + — its claim ("unless the trigger names its buffer") was the wrong rule; + the precondition file's trigger test replaces it with the right one. + Changed: `same_file/tests.rs`'s table test read the README from "The rule + per request" to "## Assumptions"; it now stops at the next heading, + because the section added in between has tables of its own (the parsing + of the per-request table, and what the test demands of it, are + untouched). + +**Docs fixed** (QA's list): `editors/vscode/package.json` (the +`lucisv.largeFile.threshold` description: "A change takes effect at once on +the files already open" — `contributes` text only); +`docs/features/large-file-mode/README.md` (both passages); +`state/buffers.rs` (`set_document`'s doc comment); this README's +Assumptions. S2 recorded as Handshake request 8, the undrained one-file +update as 9, the pull model outside a scan as 10. + +**Unchanged from what QA accepted**: the per-request rule (`same_file.rs` +untouched), the related completion tier and the shared edit range, the +re-classification, `answer_held_ahead`, the staging rule. **Changed, and +why**: (1) the client's answer to a settings pull is ordered like a +notification (`must_hold`, `behind`) — Handshakes, "Changed, read this"; +(2) `index_unsettled` — one more case recorded as a guess (C1); (3) a +request behind a held or pending settings push, a held settings answer, an +unknown notification or a folder / rename / delete event now waits where it +went ahead; (4) nothing `same_file` goes ahead while announced settings are +unanswered. + +**Production lines** (non-blank, non-comment lines of the whole file, round +3 → now): `server/ahead.rs` 186 → 226, `server/mod.rs` 227 → 238, +`server/viewport.rs` 102 → 102, `server/client.rs` 189 → 193, +`server/notification.rs` 251 → 251, `server/startup.rs` 177 → 178, +`server/probe.rs` (test-only) 46 → 53; `same_file.rs` untouched. Longest +function touched: `answer_from_the_buffer`, 49 lines with its comments +(`process_batch` is 83 with its comments, two lines changed). + +**Checks, escalation round.** Final tree; release binary +`scratchpad/dev712f/bin/fin` (the timing rows were also taken on a build one +step earlier, `esc2`, with the same results; `recl.py` was run on that one +only). Every server ran under +`tools/guard.sh`, over scratch copies in `scratchpad/dev712f/trees`, stores in +`scratchpad/dev712f/st`. QA's drivers are copies (`scratchpad/dev712f/drv*`, +`oracle/`) with only their scratch path rewritten. + +| check | result | +|---|---| +| `cargo fmt --all -- --check`; `cargo clippy --all-targets -- -D warnings` | clean | +| guarded suites (`tools/guard.sh -- cargo test -p …`) | lucisv_server 1 999 + 106 + 3 + 1 pass (round 3: 1 981 + 106 + 3 + 1); vlog_semantic 435; lucisv_mcp 388 | +| `node --test editors/vscode/*_test.js` | 37/37 | +| full `tools/gates.sh -c ` (not under `guard.sh`) | **PASS**, every step: fmt, clippy, build, the nine suites (lucisv_server 2 109/0, vlog_semantic 435/0, lucisv_mcp 388/0), docs, corpus 814/6 as before, node 37/0, cross (Windows and Linux) | +| QA's `dirtypush2.py` (S1) | r3: card, then `null`, 3/3 in both forms (reproduced); final: `null` / `null` **10/10** in both — `[change, push, hover]` and `[push, hover]` | +| the lane's differential (`early_answers_equal_settled…`) | fast subset 3 428 early, 456 waited, 0 differ; long, release: seed 7 — 1 499 938 early, 0 differ; seed 13 — 1 432 653 early, 0 differ | +| the burst differential (`fast_actions_bursts.rs`) | fast: 1 448 requests, 384 ahead, 0 differ. Long, release, 3 000 rounds each: seed 7 — 13 534 requests, 3 401 ahead (5 from a later state), 12 000 settled comparisons; seed 11 — 13 643 / 3 099 (3) / 12 000; seed 13 — 13 807 / 3 132 (1) / 12 000; seed 17 — 13 735 / 3 292 (1) / 12 000; **0 differ** in all four | +| QA's staging differential (`fadiff.py`), default threshold: corpus 200 files, OpenTitan `hw/` 220, adversarial 13 with the filelist | 684 067 early, **early ≠ settled 0, early ≠ fresh 0**; settled ≠ fresh 77 — the same 49 references + 6 hover + 6 definition + 16 completion QA attributes to round 1; controls (completion, lens, inlay, link) never early; no duplicates | +| … threshold 400 (adversarial 13, corpus 48) | 115 118 early, 0 / 0; settled ≠ fresh 98 (S2, as in QA's round 3) | +| … settings never answered (adversarial, corpus 48, `hw/` 32) | 136 378 early, 0 / 0; settled ≠ fresh 2 915 (a different configuration by construction) | +| … its rescan phase (edited buffers, mid-rescan) | 99 146 early, 0 differ | +| QA's `stg2.py`, `stg3.py` | every case as in QA's round-3 tables: nothing answered before the settings; s1 `null`, s2 the card, s3 `null` ×3, s4 A `null` / B, C cards, s5 A `null`; stg3 each hover once, in order, `BAD: []` | +| QA's random staging campaign (`strand.py`, 40 runs: corpus and `hw/`, settings after 0 / 0.2 / 0.7 / 1.5 s / never, both scopes, both sync modes) | **0 fails in 40** | +| ordering: `ord3.py` 7121–7126, `ord3t.py` 7131–7134 (their mix already has settings pushes, empty pushes, folders, watcher events) | 0 fails each, every fresh oracle equal (7131 once more after a clash between two of my own parallel campaigns over one source tree) | +| `c717.py` 1–3 | all answered by 0.28 / 0.68 / 0.71 s (scan ends 1.7–2.1 s; base 3.3–3.7 s), 0 duplicates | +| `livelock.py`; `livelock2.py` hover / delta | 167 ms; 109 / 688 ms | +| `f6.py` tail / held / control; `harm2.py`; `wid.py` 1, 2, shutdown | v3 = v3 ×3; H1–H7 as before; 0 fails ×3 | +| ignored release runs | `viewport_sweep`: 1 267 files, 7 602 windows, 541 616 / 559 725 agree, 0 other — identical to 0.65.10; `random_bursts_long_run` pass; `a_seeded_sweep_over_the_corpus_holds` / `…_opentitan_sample_holds` pass | +| re-index oracle (`small.py` pull and push, `outside.py` pull and push, `rand_run2.py` OpenTitan 43) | 96 scenarios each, only `NEGCTL-silent` diverges (both scopes); no divergence; 0 divergent checks | +| QA's `recl.py` (200 buffers, threshold 0 → 1 000 → 1 000 → 0) | 50 publishes, 0 twice, 1 refresh / 0, 0, 0 / 50, 0, 1 — as round 3 | + +**Startup** (QA's `startup.py`, 4k files, medians of 5, ms from the first +write: outline A / hover on an edited A / outline B): + +| settings answered | base | r3 | final | +|---|---|---|---| +| at once | 542 / 544 / 628 | 3.9–4.1 / 544 / 546 | 3.9–4.0 / 549 / 550 | +| after 0.5 s | 1 057 / 1 056 / 1 140 | 507–511 / 1 063 / 1 065 | 515 / 1 073 / 1 075 | +| after 1.9 s | 2 451 / 2 465 / 2 548 | 1 909–1 915 / 2 459 / 2 461 | 1 913–1 914 / 2 475 / 2 477 | + +**The headline, QA's `meas2.py`** (base → final at 4k / 20k / 40k files; ms; +medians of 5 / 3 / 3; its rescan rows measure a busy server — see Results): + +| moment | local hover | outline | cross-file hover | +|---|---|---|---| +| startup (with the `didOpen`) | 543 → **2.3** / 681 → **1.7** / 835 → **1.9** | 544 → 3.4 / 682 → 2.6 / 836 → 3.1 | 544 → 551 / 682 → 678 / 836 → 844 | +| whole rescan, same write as the trigger | 1 419 → **229** / 7 230 → **1 078** / 14 606 → **2 318** | the same + ≤ 8 | 1 420 → 1 496 / 7 230 → 7 058 / 14 622 → 15 733 | +| whole rescan, 5 ms after the trigger | 1 412 → **225** / 7 192 → **1 079** / 14 781 → **2 332** | the same + ≤ 9 | 1 417 → 1 491 / 7 200 → 7 163 / 14 790 → 17 536 | +| widen (folder scope) | 332 → **1.6** / 323 → 0.3–20 / 343 → **1.7** | 333 → 23 / 323 → 23 / 344 → 25 | 333 → 339 / 323 → 344 / 344 → 350 | +| settled | 0.05 → 0.05 / 0.07 → 0.06 / 0.10 → 0.09 | 0.58 → 0.63 / 0.63 → 0.67 / 0.69 → 0.60 | 0.04 → 0.04 / 0.06 → 0.06 / 0.08 → 0.09 | + +Unchanged from round 3 within this machine's noise (the 40k cross-file +rescan figures swing by 2–3 s between runs of the same binary). + +**Not verified**: a real VS Code session (as in every round); how often VS +Code writes a watcher event and a request close enough together to be read +as one burst on an *idle* server (argued from the protocol client's one +write per message, not observed — the busy-server case does not depend on +it); `stg2.py`'s ten-fold repetitions of s5 / s6 (run once each here). + + +## Changelog paragraph (for the lead) + +**Actions on the open file no longer wait for the workspace.** A hover, a +go-to-definition, a type definition, highlights, a rename's first check or a +signature help on a name the file itself declares, and the outline, folding +and selection ranges, are answered from the file at once even while the +index is being built or rebuilt — 2 ms instead of up to a second at startup, +and 0.04–0.3 s instead of 1–10 s while a new file triggers a rescan of a +4 000–40 000-file workspace (sooner still when the request reaches the +server together with the event) — and every such answer is exactly the one +the finished index gives (1.6 million early answers compared, none +differed). +A new `largeFile.threshold` — the editor's first settings answer included — +now takes effect on files already open, not at their next edit. +Anything that might live in another file still waits. Completion now offers +the members of the packages the file imports, what its class inherits and +the macros of the headers it includes right after the file's own names, so a +huge workspace no longer pushes them out of the list (such a name now shows +the icon and detail of the declaration the file actually reaches), and its +answers are half the size for VS Code. + +## QA log + +### 2026-11-19 — QA agent (Opus 5.5) + +**Verdict: FAIL, on one narrow finding (Q1).** Outside Q1 every check passed: no +early answer differed from a settled one, nothing was answered from text that +was not applied, and no completion item became unreachable or had its edit +changed. Q1 is an early answer given before the client's settings arrive that +differs from what a fresh server gives in the same configuration. By the brief's +rule (3) that is a FAIL. The fix is a small one (see Q1). + +Binaries: `new` = this worktree (`cargo build --release`), `base` = `git archive +c1c1407` built into a separate `CARGO_TARGET_DIR`, and `v0655` = `git archive +80017a5` (0.65.5) for item 8. Every tree was a scratch copy under +`scratchpad/qa712/trees`. Every server ran under `tools/guard.sh`, with stores +under `scratchpad/qa712/st`. My drivers are in `scratchpad/qa712/drv` and do +not depend on the dev's harness. `~/.cache/lucisv-opentitan-full` reports +`git status --short` empty at the end. + +**Baseline.** `tools/gates.sh -c `: **PASS**, all steps, +with lucisv_server 2 081/0, vlog_semantic 435/0, lucisv_mcp 388/0, corpus +814/6 (the same as before), node 37/0 and cross passing. Ignored release runs +over scratch copies all passed: +`early_answers_equal_settled_over_real_trees` seed 7 (1 499 938 early / 0 +differed) and seed 13 (1 432 653 / 0), `viewport_sweep` (1 267 files, 7 602 +windows, 541 616 / 559 725 agree, 0 other, identical to the dev's figures), +`random_bursts_long_run`, and `a_seeded_sweep_over_the_corpus_holds` / +`…_opentitan_sample_holds`. The changed pre-existing tests check out. In +`scan_ordering.rs` and `viewport/tests.rs` the hover-to-code-lens swaps keep +each test's purpose: the witness still has to be held, and a local hover no +longer is, so swapping it is right. No assertion was removed or loosened. In +`tests/e2e.rs` only the three sortText digits and their comments changed. The +viewport → ahead move holds for colours: the guard order in +`answer_from_the_buffer`, `set_aside`, `answered_ahead`, `apply_in_burst`, +`open_then_widen` and `answer_ahead_mid_widen` matches 0.65.10, and +`text_is_current` is exactly `nothing_unapplied_for && !is_dirty`. Production +lines: `ahead.rs` 175, `same_file.rs` 95, `related.rs` 113, `wire.rs` 47, +`viewport.rs` 100, `completion/mod.rs` 299, `dispatch.rs` 503. The longest new +function is `answer_from_the_buffer` at 44 lines. Nothing is near 600. + +**The core differential** (`drv/fadiff.py`, over LSP, a real release binary). +For each group of 8 files, one *early* server is started and the +`workspace/configuration` pull is left unanswered, so the server stays in +staging with an **empty index**: no store, and nothing scanned. Each file is +opened (half of them also get a `didChange`, so the dirty-buffer flush runs). +Then every request kind is sent at every sampled position: identifier start, +middle, and the caret just past the name; keyword, number, whitespace, +comment, string, macro, `` `include`` path and non-ASCII lines. During staging +nothing is answered except through the ahead path. Each response is classified +by the `--verbose` "answered from the buffer ahead of a scan" line that comes +immediately before it. The settings are then sent and the same requests asked +again once settled (**S**). The same set is also asked of a **fresh** settled +`new` server (**F**) and a fresh `base` server (**B**), with the same buffers +and edits. + +| request | early | waited | early ≠ S | early ≠ F | +|---|---|---|---|---| +| documentSymbol / foldingRange / scopePairs | 478 each | 118 each¹ | 0 | 0 | +| hover | 72 124 | 58 178 | 0 | 0 | +| definition | 70 948 | 59 354 | 0 | 0 | +| typeDefinition | 94 549 | 35 753 | 0 | 0 | +| documentHighlight | 82 893 | 47 409 | 0 | 0 | +| references | 40 409 | 89 893 | 0 | 0 | +| prepareRename | 80 312 | 49 990 | 0 | 0 | +| signatureHelp | 91 338 | 38 964 | 0 | 0 | +| linkedEditingRange / selectionRange | 103 221 each | 27 081 each¹ | 0 | 0 | +| completion / codeLens / inlayHint / documentLink (controls) | **0** | 3 881 each | — | — | + +In total: 596 files (corpus 350, OpenTitan `hw/` 220, plus 13 hand-written +adversarial files run twice, once in workspace scope and once with a filelist +carrying `+incdir+` and `+define+QA_DEF`). That is **740 449 early answers, 0 +different from S, 0 different from F**. The early answers were also identical +to B wherever B gave one. ¹ The "waited" entries for the always-early kinds +come from my first run, where a `didOpen` arrived in a burst behind a held +request and was held with it (the 71.7 order contract, so expected). After the +harness was fixed every file's whole-buffer requests went early. No request was +answered twice. The adversarial files (`trees/adv`) cover: + +- a local name shadowing a wildcard import, and an explicit `import pkg2::x` + after a local use; +- `$unit` declarations of the same name in two files; +- local names equal to a module, a package and a macro; +- generate-block names, unnamed and named blocks, function and task locals; +- `a.inner.q` where `a` is local and `inner` is in another file; +- `this.`, `super.`, `Cls::`, inherited members from a base in the same file + and from a package class, and `extern` methods; +- modport members, local and package structs, unions and enums; +- `#(.W(4))` overrides, macro arguments and `` `define`` bodies; +- a name used before its declaration, `` `ifdef``'d-out code, and a parse error; +- an `` `include`` of a header that redefines a macro the file also defines; +- `bind`, `extern module`, `config`, ports, and a module declared in two + files. + +The probe in `drv/probe.py` lists each of these; all were the same. For +references, a port, a module-level signal, a generate-block signal, a function +local and a `$unit` name all **wait**; a local in an unnamed block goes early, +and its list equals the settled one. No early list was a strict subset of a +settled list. + +**Behaviour (1): a dirty buffer analysed for the request.** The ordering +drivers from 71.7 and 71.3b were rerun on `new`, with every early kind +(hover, definition, typeDefinition, references, highlight, prepareRename, +signatureHelp, linkedEditingRange, selectionRange, foldingRange, scopePairs, +plus codeLens and completion) added to their random requests. Typing was +mixed with scans: `ord3.py` (corpus 7121–7123 in workspace scope, 7124–7125 +in folder scope, OpenTitan 7126) and `ord3t.py` (7131–7134). All had **0 +fails** and every request was answered exactly once: each documentSymbol came +from the state at or after its send, and every fresh oracle matched. Other +drivers: + +- `f6.py` tail / held / control: the server ends on v3, the same as the client. +- `harm2.py` H1–H7: identical to base. +- `c717.py` seeds 1–3: every startup request answered by 0.15–0.19 s (base + 3.3–3.6 s), with no duplicates. Only `semanticTokens/full` answers differed + from settled, as designed for colours. +- `livelock.py`: hover answered at 168 ms, against 686 ms on base. +- `livelock2` hover: 113 ms (base 662). `livelock2` delta: 719 ms (base 664), + since a dirty buffer's colours still wait. Nothing came near the 300 s case. + +`drv/beh.py` checks, on OpenTitan `hw/`, which text each early hover sees and +what is published. Both binaries end with identical publish sequences for the +buffer. The one difference is that `new` publishes once at the end of the +rescan where `base` publishes twice, because the flush has already happened. +Every hover saw a text the client had sent at or after its request. The scan's +own view did not move: in `drv/flipdiag.py` mid-rescan publishes for +`aes_cipher_core.sv` matched the settled diagnostics in all four rounds. + +**Behaviour (2): requests answered before the trigger in their own burst** +(`beh.py`, one write each): + +| burst | which text the hover saw (new) | early? | which text it saw (base) | +|---|---|---|---| +| `[change v2, created, hover]` | v2 | yes, 1–3 ms | v2 after the rescan (~1.4 s) | +| `[created, change v3, hover]` | v3 | no: `ahead` names the buffer | v3 | +| `[hover, created, change v4]` | v3, answered before the burst | n/a | v3 | +| `[lens, change v5, hover]` mid-rescan | v5 after the rescan | no | v5 | + +No answer came from a state that never existed. Answering before an older +notification is safe only because none of the notifications that can sit +ahead (`didChangeWatchedFiles`, `didSave` of another buffer, +`didChangeConfiguration`, folder, rename and delete events) replaces another +buffer's `Document` (`notification.rs` was read arm by arm). The flush of that +buffer is the only exception, and it is Q1's. + +**Behaviour (3): no exclusion during staging.** See Q1. Everything the early +handlers read is a function of the text, except the large-file decision that +`set_document` takes when the flush runs. The `` `ifdef``/`+define+` case +cannot differ: `collect_defines` and `analyze` take no configuration, and the +filelist run above (with `+define+QA_DEF` against a file declaring the same +name in both branches) had 0 differences. + +**Completion** (`drv/compdiff.py`). Each sample was asked of three settled +servers: base, new with `itemDefaults`, and new from a client that does not +declare `itemDefaults`. Every item's effective edit was rebuilt as LSP 3.17 +specifies: `textEdit`, otherwise `itemDefaults.editRange` + +`textEditText ?? label`, with `insertTextFormat` defaulted. Positions covered +prefixes of length 0–3, mid-word, full word, end of line, after `.`, after +`::`, after a backtick, inside a macro call, and after non-ASCII text on the +same line. + +| tree | samples | base items | missing in new | edit changed | no-defaults client ≠ defaults client | rank violations | bytes base → new | +|---|---|---|---|---|---|---|---| +| corpus | 3 210 | 465 094 | **0** | **0** | 0 | 0 | 129.8 MB → 59.5 MB | +| OpenTitan `hw/` | 3 555 | 657 515 | **0** | **0** | 0 | 0 | 202.8 MB → 102.6 MB | +| 40k (`ot10w`) | 1 985 | 425 571 | **0** | **0** | 0 | 0 | 124.6 MB → 61.1 MB | +| adversarial | 291 | — | 0 | 0 | 0 | 0 | — | + +The client that declares no `itemDefaults` got per-item `textEdit`s, +item-for-item equal to the rebuilt items, and never an `itemDefaults` field. +The related tier's contents were checked by hand (`drv/relcheck2.py`): + +- a wildcard import brings in that package's members only, and a package the + file does not import stays in tier 5; +- an import inside `module top` does not reach a class declared outside it; +- a class gets its whole inherited chain (from the base and from the base's + base); +- after a backtick, only the macros of headers that are actually included are + in tier 4. + +A package of 20 000 members (`drv/big20k.py`): the related tier is capped at +256 items and the response stays under 80 KB. Latency is 3.0–3.8 ms against +1.2–1.5 ms on base, which is bounded. See Q2 for the one kind of difference +found. + +**Headline re-measured** (`drv/meas2.py`; trees regenerated from the dev's +`gen.py` output copies `ot1`/`ot5`/`ot10`; medians of 5 runs; ms from the write +to the response; a shared machine, so treat absolute numbers loosely): + +Each cell reads base → new at 4k / 20k / 40k files. + +| moment | local hover | outline | local definition | cross hover | module-level references | completion | +|---|---|---|---|---|---|---| +| startup (sent with the `didOpen`) | 541 → **2.4** / 656 → **1.4** / 812 → **2.0** | 542 → **3.6** / 657 → **2.3** / 813 → **3.0** | 541 → **2.4** / 656 → **1.4** / 812 → **2.0** | 542 → 560 / 657 → 671 / 813 → 838 | 542 → 560 / 657 → 672 / 813 → 838 | 543 → 562 / 658 → 673 / 814 → 839 | +| whole rescan, same write as the trigger | 1 391 → **227** / 7 047 → **1 085** / 14 538 → **2 362** | 1 392 → 227 / 7 055 → 1 094 / 14 547 → 2 369 | the same as hover | 1 392 → 1 414 / 7 063 → 7 084 / 14 554 → 15 069 | 1 392 → 1 414 / 7 063 → 7 084 / 14 554 → 15 076 | 1 399 → 1 418 / 7 075 → 7 093 / 14 569 → 15 077 | +| whole rescan, 5 ms after the trigger | 1 394 → **220** / 7 066 → **1 082** / 14 593 → **2 294** | 1 395 → 224 / 7 074 → 1 088 / 14 602 → 2 302 | the same as hover | 1 395 → 1 419 / 7 082 → 7 167 / 14 602 → 14 628 | 1 395 → 1 419 / 7 082 → 7 168 / 14 602 → 14 628 | 1 406 → 1 426 / 7 090 → 7 177 / 14 610 → 14 638 | +| widen (folder scope) | 331 → **1.0** / 331 → **1.2** / 329 → **1.1** | 332 → 22 / 332 → 22 / 330 → 21 | 331 → 20 / 331 → 20 / 329 → 20 | 332 → 335 / 332 → 343 / 330 → 334 | 332 → 336 / 332 → 343 / 330 → 334 | 334 → 337 / 333 → 344 / 332 → 336 | +| settled (each request alone, median of 20) | 0.04 → 0.04 / 0.09 → 0.09 / 0.10 → 0.10 | 0.56 → 0.62 / 0.61 → 0.76 / 0.62 → 0.67 | 0.04 → 0.03 / 0.07 → 0.07 / 0.08 → 0.08 | 0.04 → 0.04 / 0.08 → 0.08 / 0.09 → 0.09 | 0.06 → 0.06 / 0.11 → 0.10 / 0.12 → 0.12 | 1.62 → 1.40 / 1.75 → 1.61 / 1.82 → 1.69 | + +The dev's headline shape holds. Local requests no longer scale with the +workspace at startup or during a widen. During a rescan what is left is the +scan's prefix that drains nothing, about 16 % of the old wait. Cross-file +requests and completion still wait the whole scan, as designed, and are within +noise of base: new runs 0–4 % slower, consistently at startup (+3 %), which is +inside this shared machine's variance. Settled latencies are unchanged. The +rescan wait is longer here than in the dev's table (base 14.5 s against 9.8 s +at 40k), because the machine was busier. Completion payload and relevance are +in the completion table above. + +**Re-index oracle (item 8).** `rand_run2.py` was run on corpus seeds 41 and 42 +and OpenTitan seed 44 on `new`, `base` **and 0.65.5**. All three binaries +diverge the same way. Corpus 41 and OpenTitan 44 diverge at the same step with +the same content. Corpus 42 hits the same class of divergence at a different +step on each binary, because the timing differs. All of them reduce to **one +pre-existing bug, at least as old as 0.65.5**, so it is not a regression from +0.65.6–0.65.10 (Q4). The "null completion that crashes the driver" is the same +bug seen from inside the excluded buffer: the fresh server answers `null` +there. The crash is a driver bug, in `rand_run2.py:265`, which does not handle +`null`. + +**Findings** + +- **Q1 (Medium; FAIL under rule 3).** A `didChange` that arrives while the + server is waiting for settings is analysed for an early request under the + *default* `largeFile.threshold` (4 MB), and the buffer keeps that `Document` + until its next edit. + - Where: `crates/lucisv_server/src/server/ahead.rs:100-101` + (`flush_buffer`) together with `state/buffers.rs:56` (`is_large`, read at + `set_document`). + - Repro `drv/stg.py`. Settings `largeFile.threshold = 300`. During staging: + `didOpen` (small text), `didChange` (a ~0.8 KB text), then a hover. + - `new`: answered before settings with a full hover card, and the same card + once settled. + - `base`: held, then `null`, because the flush runs after the settings and + the buffer is on the fast path. + - A fresh server: `null`. + - The opposite direction has the same shape: a user threshold above 4 MB, + with a 10 MB buffer edited during staging, ends up on the fast path. + - Assumption 2 in the README ("none of the early handlers reads a setting") + holds for the handlers but not for the flush in front of them. + - Suggested fix: in `answer_from_the_buffer`, while `self.staging`, a dirty + buffer waits. A clean buffer can still go ahead, since a `didOpen` applied + in staging was already pre-settings in 0.65.10, as `stg.py`'s + "didOpen big" row shows on both binaries. +- **Q2 (Low).** A name the related tier claims keeps its label, edit and + format, but its **kind/detail** come from the relationship instead of + 0.65.10's workspace pick. This affected 1 510 of 1 548 180 base items. The + related view is usually *more* correct: + - `NumRegs`: `ac_range_check_reg_pkg::NumRegs` in 0.65.10, now + `sysrst_ctrl_reg_pkg::NumRegs`, which is the package the file imports; + - `prim_secded_22_16_dec`: offered as a module in 0.65.10, now as a function + of the imported package; + - `` `ASSERT``: now shows the signature of the included header. + + The inherited detail is less informative, though: `variable — inherited by + CD` replaces `variable — CB::zz_cbm`, which named the declaring class. This + contradicts README Design B.2 and the `related.rs:16-20` module doc ("an + answer is always the old answer plus the related names"). The dev's + `compeq.py` compared only (label, range, text, format). Either correct the + doc, or keep the declaring class in the inherited detail + (`related.rs:157`). +- **Q3 (Low, doc).** The per-request table ("The rule per request") does not + list `textDocument/diagnostic`, `workspace/diagnostic`, + `workspace/executeCommand`, `workspace/willRenameFiles`, + `textDocument/inlineCompletion`, `textDocument/willSaveWaitUntil` or + `codeAction/resolve`. The call and type hierarchies appear only as + "hierarchies", and the prepareRename row leaves out the `untitled:` case + (`same_file.rs:183`). The code is right: everything outside + `same_file::METHODS` waits. Every row present matches `same_file.rs` line + by line. +- **Q4 (pre-existing since ≤ 0.65.5; file separately).** An open buffer + inside a folder that `lucisv.toml` excludes is taken into the index by the + first rescan or save after it is opened, while a fresh server with the same + buffer open leaves it out. + - Minimal repro `drv/excl.py`: 70 files and `exclude = ["qa_excl"]`; open + `qa_excl/x.sv`; then any one of a watcher create, a watcher change, a + disk edit of `x.sv` or a `didSave` of it. + - `lucisv/moduleHierarchy` then lists `x.sv` and completion offers its + words. The fresh server does neither, and answers `null` for completion + inside that buffer. + - Open alone, or close-then-rescan: no difference. + - Identical on `new`, `base` and 0.65.5. +- **Q5 (Info).** `wid.py` seed 2 reports two "answered before the widen of its + burst ended" failures, for a hover and a definition on the module-name + declaration at (0, 8). That is this lane's intended change. Both are local, + so the differential above covers them, and the driver's rule needs updating. +- **Q6 (Info).** Answering ahead of a trigger in the same write + (`answer_ahead_of`) only helps when the server's reader has parsed the whole + write before the burst is taken. Over 5 runs at 4k files the median of the + same-write case equalled the 5-ms-later case (≈ 220 ms, which is the first + drain point), although one single run gave 1.4 ms. It is correct either way. +- **Q7 (process, mine).** Once, while restarting my own oracle runs, I ran + `pkill -f "lucisv-server"`. It could have killed `lucisv-server` processes + belonging to other sessions on this machine (about 15:05). My own servers + run as `bin/new` and `bin/base` and were not affected. + +**Fixed myself:** nothing. **Not verified:** a real VS Code session. The +client-side `itemDefaults` handling is checked against the LSP 3.17 rule and +against the dev's reading of `vscode-languageclient`, not by running the +extension host. + +### 2026-11-19 — QA agent (Opus 5.5), round 2 (fix round) + +**Verdict: PASS WITH FINDINGS.** Q1 is fixed. Across the round-2 +differential no early answer differs from a settled one, no message or +diagnostics publish is lost or duplicated, and no completion item has +become unreachable or had its edit changed. + +Three findings remain: + +- **R1 (Low–Medium).** This is a pre-existing staging race that the lane + makes more likely for one write shape. The answer involved is not an + early answer, so it is not a FAIL condition. +- **R2 (Low).** Completion details when a class extends a typedef alias. +- **R3 (Low).** The README-table test does not catch a stale row. + +Binary `r2` is this worktree as it stands, with release build fresh. +`base` is c1c1407. From now on I only ever kill PIDs I started. + +**Baseline** + +- **Gates.** Full `tools/gates.sh -c ` passed. Counts: + - lucisv_server 2 086/0 (round 1: 2 081; the 5 added are the 3 staging + tests, the Q2 test and the Q3 test); + - vlog_semantic 435/0, lucisv_mcp 388/0; + - corpus 814/6; + - node 37/0; + - fmt, clippy and cross all pass. +- **Ignored release runs**, all passing over scratch copies: + - the differential, seed 7 (1 499 938 early, 0 differ) and seed 13 + (1 432 653 early, 0 differ); + - `viewport_sweep`, identical to round 1; + - `random_bursts_long_run`; + - both re-index sweeps. +- **What changed since round 1** (by mtime): `ahead.rs`, `related.rs`, + `same_file/tests.rs`, `server/tests/mod.rs`, the new + `fast_actions_staging.rs`, and this README. No test was removed or + weakened. The one modified test, `a_class_relates_what_it_inherits`, gained + a detail assertion. +- **Sizes** (production lines): `ahead.rs` 175, `related.rs` 135, + `same_file.rs` 95. The longest function, `answer_from_the_buffer`, is + 50 lines. + +**Item 2: the staging tests fail without the fix.** In a scratch copy +(`qa712/mut`, its own target dir) I reverted `ahead.rs:106` to +`self.is_dirty(&uri) && colours`. Result: + +- `…edited_before_a_small_threshold…` **FAILED** at line 104; +- `…edited_before_a_large_threshold…` **FAILED** at line 123; +- `…opened_before_the_settings…` passed. + +With the condition restored, all three pass. + +**Item 5: the table-vs-dispatch test** (`same_file/tests.rs:223`, scratch +copy): + +| mutation | result | +|---|---| +| a row removed (`textDocument/inlineCompletion`) | **fails**, naming it | +| a dispatch arm removed (`WillSaveWaitUntil`) | **fails**, but only through the hard-coded `arms.len() == 40` | +| a stale row added (`textDocument/moniker`, which the dispatch does not answer) | **passes** — see **R3** | + +**Item 3: the staging differential** + +Is the dev's explanation of the round-1 "answered in staging, not early" +alarm right? Mostly, yes: + +- My driver put its per-file probe/sentinel requests on the file it had just + opened, half of which had just been edited. +- With the fix, such a request waits for the settings. The driver *blocked + on it*, so the 2 s configuration bound ran out and the startup scan + answered the rest. +- The cascade the dev describes (a held request holding back the tail of its + own burst) is real, but here it was my blocking wait, not the server, that + outlived the bound. +- With a client that answers the settings pull at once (as VS Code does) + there is no 2 s wait anywhere (startup table below). + +**Driver fix (`drv/fadiff.py`).** + +- Every probe now sits on the group's first file, which is never edited. +- A new check: no request on an edited buffer may be answered early during + staging. +- A new **rescan phase**, so the dirty-buffer flush is still covered outside + staging. After settle, each edited file is edited again while a + watcher-triggered whole rescan runs, its requests are asked, and every + early answer is compared with the same session's answer once settled. + +**Round-2 rerun, on the same files and seeds as round 1:** + +- 446 files: corpus 200, OpenTitan `hw/` 220, and the 13 adversarial files in + both configurations. +- 0 overflows and 0 sanity alarms. +- No request on an edited buffer answered early in staging. + +| request | early | waited | early ≠ same session | early ≠ fresh | +|---|---|---|---|---| +| documentSymbol / foldingRange / scopePairs | 261 each | 185 each | 0 | 0 | +| hover | 39 124 | 57 539 | 0 | 0 | +| definition | 38 485 | 58 178 | 0 | 0 | +| typeDefinition | 51 372 | 45 291 | 0 | 0 | +| documentHighlight | 44 994 | 51 669 | 0 | 0 | +| references | 21 508 | 75 155 | 0 | 0 | +| prepareRename | 43 821 | 52 842 | 0 | 0 | +| signatureHelp | 49 429 | 47 234 | 0 | 0 | +| linkedEditingRange / selectionRange | 55 822 each | 40 841 each | 0 | 0 | +| completion / codeLens / inlayHint / documentLink | 0 | 2 801 each | — | — | +| **rescan phase** (edited buffers, flushed mid-rescan) | **83 793** | 288 915 | **0** | — | + +There are **401 160 staging-early answers**, against about 690 000 for the +same 446 files in round 1. The drop is expected: about 7/16 of the files are +edited, and their requests now wait (690 000 × 9/16 ≈ 390 000). + +**Claim (b): `largeFile.threshold` is the only setting a buffer's analysis or +an early answer reads.** True, checked two ways. + +*By reading.* +- `Document::new`, `collect_defines` and `analyze` take no settings. +- Of the workspace's `self.client` readers, only `state/buffers.rs:67` + (`is_large`) sits on the `set_document` path. `max_file_size` is read only + by the index (`current_text` and discovery). `filelist`, `exclude`, + `scope` and `depth` are read only by discovery and scope. +- `large_file_answer` reads no setting. +- No early handler module reads `client_settings` outside its tests. +- `vlog_parser` and `vlog_semantic` read no environment variables. + +*By experiment.* I ran the staging differential once per setting, over the +adversarial files and 24 corpus files each: + +1. folder scope; +2. scopeDepth 0; +3. scopeDepth 3; +4. `exclude` (including one of the opened files); +5. `maxFileSize` 300; +6. `persist: true`; +7. `largeFile.threshold` 400; +8. a filelist with `+define+`/`+incdir+` plus `lint.select: all`. + +Results: + +- Settings 1–6 and 8: **0 early ≠ same session and 0 early ≠ fresh**, for + both the staging answers and the rescan-phase answers. +- Setting 7: 0 early ≠ same session, but 1 031 (adversarial) and 10 149 + (corpus) early ≠ fresh. All of those are buffers opened in staging under + the 4 MiB default, which is claim (a). + +**Claim (a): a buffer opened before the settings keeps the 4 MiB-default +analysis until its next edit, exactly as 0.65.10 does.** Verified identical, +so the lane neither introduced nor widened it. + +- With threshold 400 and the adversarial files on **base**, same-session ≠ + fresh in **2 877** answers. On `r2` the count is **2 877**, the same + number. +- `drv/stg2.py` s3 (threshold 300; a 0.8 KB file opened in staging; hover; + settings; hover; edit; hover), on both binaries: + - first hover: the full card; + - after the settings: the full card; + - after the edit: `null`; + - a fresh server: `null`. +- `r2` gives the first card *before* the settings and base gives it after. + The content is the same, so the lane only answers sooner; it does not make + the bug more visible. + +As a bug to file: **Low** severity. +- It needs a user `largeFile.threshold` that falls between the size of a + buffer opened or edited in the configuration round trip (milliseconds in VS + Code) and the 4 MiB default. +- It shows as a full analysis where the user asked for the fast path, or the + reverse, until the next keystroke. +- Minimal repro: `stg2.py` s3, or round 1's `stg.py` "didOpen big" row. +- The repro for its sibling, which is R1, is s6. + +**Item 1: Q1 in both directions, plus the variants** (`drv/stg2.py`, on r2 +and base; "early" means answered before the settings): + +| case | r2 | base | fresh | +|---|---|---|---| +| edit during staging, threshold 300 B | waits, `null`, `null` | waits, `null`, `null` | `null` | +| edit to 6 MiB during staging, threshold 8 MiB | waits, card, card | waits, card, card | card | +| open 0.8 KB during staging, threshold 300 (claim a) | early card, card, `null` after edit | card, card, `null` after edit | `null` | +| A edited, B and C clean, separate writes | A waits (`null`); B and C early | all wait | — | +| **one write:** `[edit A, hover A, hover B, open C, hover C]` | A waits; B and C early; **A = card (9/10 runs)** | all wait; **A = `null` (10/10)** | `null` | +| s6: `[open A]` `[edit A]` `[open C]` `[hover A]`, separate writes | card (10/10) | **card (10/10)** | `null` | + +**R1 (Low–Medium; pre-existing, made more likely by the lane).** + +What happens: +- The Q1 fix stops the early path from analysing an edited buffer before the + settings arrive. +- But any *other* notification applied during staging still runs + `flush_dirty` (`server/notification.rs:64-66`) under the 4 MiB default. +- The buffer then keeps that analysis until its next edit. That is s6, and + it is identical on base 10/10. + +What this lane changes: +- In the one-write case, a request answered early (hover B) no longer holds + back the `didOpen C` behind it in its burst. +- So `didOpen C` is applied in staging, its flush analyses A under the + default, and A's later, non-early answer is the card where base and a + fresh server say `null`. +- The verbose trace shows it, in this order: + 1. `hover HELD … staging=true`; + 2. `hover answered from the buffer`; + 3. `flush of 1 dirty buffer`; + 4. `didOpen handled`. + +Why it is not a FAIL condition: +- The divergent answer is not an early one. +- It is reachable on base with a different write order (s6). +- It needs both an edit inside the configuration round trip and a threshold + that the edit straddles. + +Suggested fix: the same place as Handshake request 6. Either don't let +`notification()`'s flush run while `staging`, or re-take `is_large` for the +open buffers when the settings land. That fix would also close (a). + +**Startup cost of making edited-buffer requests wait.** Does it make startup +slower than base, where everything waited anyway? + +- I measured realistic VS Code-like startup sequences (`drv/startup.py`, 4k + tree, medians of 5). The client answers the settings pull at once. +- The opening burst for each file is `didOpen`, semanticTokens/full, + documentSymbol, foldingRange, codeLens and documentLink. +- Timings below are ms from the first write, base → r2. + +| sequence | first answer | outline A | lens A | edited hover A | outline B | lens B | +|---|---|---|---|---|---|---| +| A alone | 2.0 → 2.0 | 574 → **2.2** | 574 → 566 | — | — | — | +| A and B in one write | 2.0 → 2.0 | 558 → **2.2** | 558 → 551 | — | 642 → **553** | 642 → 634 | +| A, an edit of A + hover, and B, in one write | 2.1 → 2.0 | 559 → **2.3** | 559 → 536 | 561 → 537 | 645 → **539** | 645 → 616 | + +The edited buffer's request waits about as long as on base. Nothing is +slower, and nothing waits for the 2 s bound with a client that answers its +settings pull. + +How often VS Code would produce such a write: it needs an edit before the +settings answer arrives (one IPC round trip after `initialized`). That +happens only for a file restored dirty from hot exit, whose text arrives in +its `didOpen` anyway, or for typing within milliseconds of startup. It is +rare, and never worse than base. + +**Item 4: Q2 inherited details**, checked with `drv/inh.py` against the +`trees/adv4` fixture: + +- Each detail names the declaring class: + - multi-level (`zr_root::zz_rf` seen from a grandchild); + - a member overridden in a middle class (`zr_mid::zz_over`); + - a `#(...)`-parameterised base (`zr_param::zz_pt`); + - a package-qualified base (`zr_pkgbase::zz_pkg_m`). +- Interface classes: `implements` brings in nothing (it is not an `extends`). + The implemented method is the class's own and is offered from its own + scope (tier 1). +- **R2 (Low):** when a class `extends` a **typedef alias** (`typedef zr_mid + zr_alias; class zl_alias extends zr_alias`), the chain's members are still + offered (tier 4). Their detail falls back to the *inheriting* class + (`variable — zl_alias::zz_mid_m`, a class that declares nothing). Base + said `zr_mid::zz_mid_m`. + - Code: `completion/related.rs:162` (`unwrap_or(&key)`) and `:195`. The + fallback is documented in the code, but it states a falsehood. + - Better: fall back to the index's own workspace-tier detail, or to no + owner at all. + +**Completion rerun** (`drv/compdiff_r2.py`, OpenTitan `hw/`, seed 21): + +- 3 299 samples and 622 687 base items. +- **0 missing, 0 edits changed.** +- The client without `itemDefaults` got exactly the defaults client's + rebuilt items (0 mismatches) and never an `itemDefaults` field. +- 0 ranking violations. +- 191.3 MB → 97.1 MB on the wire. +- Remaining kind/detail changes: 93, which is Q2 kept as documented. +- I spot-checked the kmac sequence classes against the source; the new + declaring class is the *nearest* declaration in the `extends` chain, for + example `kmac_sideload_vseq::en_sideload_c` where base said + `kmac_sideload_invalid_vseq`, a class that is not in the chain. + +**Item 6: regression sweep on r2, all with every early-eligible kind mixed +in** + +- `ord3.py` 7121–7126 and `ord3t.py` 7131–7134: **0 fails** each, and every + fresh oracle equal. +- `c717.py` 1–3: all answered by 0.18 s (base 3.3–3.7 s), no duplicates. + Only `semanticTokens/full` answers differ from settled, which is the colour + design. +- `harm2.py`: identical to base. +- `f6.py` tail / held / control: v3 = v3. +- `livelock`: 161 ms (base 663). `livelock2` hover: 104 ms (base 662). + `livelock2` delta: 670 ms (base 668). +- `wid.py`, with its rule updated so hover, definition and documentSymbol may + answer before a widen ends (their content is still checked): seeds 1, 2 + and shutdown, **0 fails** on both binaries. +- `beh.py` burst orderings on r2: + - S1 `[change v2, created, hover]`: early, saw v2; + - S2 `[created, change, hover]`: waits, saw v3; + - S3 `[hover, created, change v4]`: answered before the burst, saw v3; + - S4 `[lens, change v5, hover]` mid-rescan: waits, saw v5; + - S5 (a dirty buffer flushed mid-rescan): early, saw v6. +- Publish sequence for the buffer: `[1,2,2,2,3,3,1,1,2,4,4]` on **both** + binaries, with no duplicates. + +**R3 (Low).** `the_readme_table_names_every_request_the_dispatch_answers` +(`same_file/tests.rs:223-243`) checks only the direction "every arm has a +row", plus a hard-coded arm count. +- A row naming a method the dispatch does not answer passes. +- If someone deletes an arm *and* updates the 40, the stale row survives. +- Fix: parse the table's backticked method names and require set equality + with the arms. + +**Fixed myself:** nothing in the worktree. My drivers are updated in +`scratchpad/qa712/drv` (`fadiff.py`) and `drv713` (`wid.py`). + +**Not verified:** +- A real VS Code session. +- How often VS Code actually sends an edit before the settings answer. I + argued this from the protocol and did not observe it. +- `~/.cache/lucisv-opentitan-full`: `git status --short` is empty. + +### 2026-11-19 — QA agent (Opus 5.5), round 3 + +**Verdict: FAIL, on one finding (S1), which needs a one-line fix.** + +S1: an early answer is computed from a state *older* than its request. +A request sent after a `largeFile.threshold` push in the same burst is +answered before that push is applied. The push can now re-analyse the +buffer, so the next identical request answers differently. + +Everything else this round asked about passes: +- `answer_held_ahead`: nothing answered twice, nothing answered from a + closed or never-existing text. +- Reclassification equals a fresh server. +- The staging differential: 0 early answers different from settled. +- Startup is never slower than base. +- R2 and R3 are fixed. + +Binary `r3` is this worktree (release build fresh). `base` is c1c1407 and +`r2` is my round-2 build. I killed only PIDs I started. + +**Process note.** Three of my wait loops waited on `pgrep -f compdiff_r3`. +That pattern matched the loop's own command line, so the loops could never +end, and the lead killed them. No result was lost. From now on I wait on a +PID I recorded or on a done-marker file. + +**S1 (Medium; a FAIL condition: an answer from a state older than the +request's send).** +- **Where:** `answer_ahead_of` (`server/ahead.rs:183-197`, "behaviour 2") + answers a `same_file` request ahead of an older notification in its burst. + Its reason is that only `didOpen`, `didChange` and `didClose` replace a + `Document`. Since round 3, `workspace/didChangeConfiguration` replaces one + too: `apply_settings` → `reclassify_large_buffers` + (`server/notification.rs:352`, `server/large_file.rs:177`). +- **Repro:** `drv/dirtypush2.py`. Open a 1.5 KB buffer with the threshold + off, then send one write: + `[didChange A (same size), didChangeConfiguration largeFile.threshold=1000, hover A]`. + - The hover is answered early with the **full card**: the edit is flushed + under the old threshold, before the push. + - The same hover asked again answers `null`, because A is now large. + - 3/3 runs. + - With a clean buffer, `[push, hover A]` returns the stale card whenever + the server reads the write as one burst (1/3 runs here). + - On base the answer is the card both times. Base never reclassifies, so + it is consistent there. +- **The fix is confirmed:** + - In a scratch copy (`qa712/mut`) I made `answer_ahead_of` return early + for `workspace/didChangeConfiguration` as it already does for + `didChange`. I built `bin/r3fix` from it. + - On `r3fix`, `dirtypush2.py` gives `null` / `null` in 6/6 runs. + - The README's Assumptions bullet "Only `didOpen`, `didChange`, `didSave` + with text and `didClose` replace a buffer's `Document`" also needs + `didChangeConfiguration` (largeFile.threshold) adding. + - The settings *response* at startup is not exposed to this. It is a + `Message::Response`, it never reaches `answer_ahead_of`, and the + requests staging held wait for it. + +**a. `answer_held_ahead` (`server/ahead.rs:280`, called at +`server/startup.rs:271`).** + +How it works: +- It takes `held` and runs it through `set_aside` in arrival order. +- The `ahead` it passes to each request is everything older in `held` that + was not answered, notifications included, so `nothing_unapplied_for` + still sees an older `didOpen`, `didChange` or `didClose` naming the + buffer. +- `self.held` is empty while it runs, and `behind` is 0 outside + `process_batch`. +- An answered request is not put back, so it is never replayed. A cancel + stays in `held` and is dropped at replay when it names nothing. +- It runs after `staging = false`, so a dirty buffer is flushed under the + user's settings. + +Constructed sequences (`drv/stg3.py`): +- Settings were answered 0.3 s after the writes, and in a second run never + (the 2 s timeout). +- Sequences: `[didOpen A v1, hover]`, `[didChange v2, hover]`, + `[didClose, didOpen A' v3, hover]` in separate writes; the same in **one** + write; open/close with no reopen; incremental edits held behind a request. + +| case | r3, answers h1/h2/h3 (settings at 0.3 s) | r3 (settings never) | base (both) | +|---|---|---|---| +| separate writes | v3 / v3 / v3 (early) | v3 / v3 / v3 | v3 / v3 / v3 | +| one write | **v1 / v2 / v3** (h1, h3 early; h2 waits) | v2 / v2 / v3 | v2 / v2 / v3 | +| close, no reopen | `null` / `null` | `null` / `null` | `null` / `null` | +| incremental | v3 / v3 / v3 | v3 / v3 / v3 | v3 / v3 / v3 | + +In every case each hover was answered exactly once, in send order, from a +text at or after its send, and never from a closed document. In the +separate-writes case the notifications are applied during staging, because +only requests are held, so v3 is a later state, which is allowed. + +**Random staging campaign (`drv/strand.py`)** + +- 40 runs per binary: + - trees: corpus and OpenTitan `hw/`; + - settings answered after 0, 0.2, 0.7 or 1.5 s, or never; + - workspace and folder scope; + - incremental and full sync. +- Random bursts of open, edit, close, documentSymbol and every early kind + plus codeLens, completion and tokens, for 3 s from the moment the + settings pull arrives. +- What each run checks: + - every request answered exactly once; + - every documentSymbol answer is a state at or after its send; + - the final server text equals the client's text; + - every buffer equals a fresh server (documentSymbol, hover, references + on every line). + +Results: +- **r3: 0 fails in 40 runs.** +- **base: 0 fails in 40 runs.** +- No hangs and no duplicates. + +I did not attempt an answer-for-answer comparison with base for requests +that were not early. The bursts are timed, so the two binaries cannot +receive identical message sequences. I compared the invariants instead. + +**b. Reclassification** + +*Staging cases* (`drv/stg2.py`, r3): every case equals a fresh server. +- s1: `null`. +- s2 (6 MiB edited, 8 MiB threshold): card. +- s3 (opened 0.8 KB, threshold 300): `null` / `null` / `null`. +- s4: A `null`, B and C card. +- s5 (one mixed write): **10/10** `null`. +- s6: **10/10** `null`. + +*Mid-session* (`drv/recl.py`): 200 open buffers, 50 of them 1.6 KB and 150 +under 200 B. + +| push | blocked (round trip of a request in the same write) | publishes | buffers published twice | token refreshes | session ≠ fresh (hover/def/symbols/folding/tokens) | +|---|---|---|---|---|---| +| threshold 0 → 1000 (50 flip to large) | 0.8 ms | **50** | 0 | **1** | **none** | +| 1000 → 1000 (unchanged) | 0.8 ms | **0** | 0 | 0 | — | +| 1000 → 0 (50 flip back) | 0.9 ms | **50** | 0 | **1** | none in the buffers | + +- **Base:** 0 publishes and 0 refreshes, and it differs from fresh in + hover, symbols, folding and tokens. That is the bug this round fixed. +- **The very first push of the session (`0 → 0`)** republished all 201 + buffers on **both** binaries (about 46 ms). That is the existing lint + republish when a pushed payload differs from the pulled one. It is not a + re-analysis. +- **A dirty buffer during a push:** `notification()` flushes it first, + under the old threshold, then `reclassify` flips it. The hover that + follows is `null` and correct once S1 is fixed; see S1 for today's stale + first answer. + +*The index window.* +- After a buffer flips to large, other files still resolve into it from + the index record until its next save or rescan, and they agree with a + fresh server. +- After a **save** of the large buffer, it contributes nothing: from + `top.sv`, definition, hover and references on `f0` become `[]` / `null`. +- A fresh server that opened `f0` *after* its scan still has `f0` from + disk, so the two differ. +- This is pre-existing: + - `drv/largesave.py`: an *edit* that crosses the threshold, then a save, + gives `[]` on base too; + - `drv/openorder.py`: base already answers differently depending on + whether a large buffer was opened before or after the scan. +- **S2 below.** + +**c. The staging differential, with the driver fixed** + +Driver changes: +- No probes. All opens and edits go in one write, then all requests. +- Settings are answered 0.3 s later, or never. +- Early answers are now classified after the settings land. +- New checks: nothing may be answered during staging at all, and same + session must equal fresh. + +| run | files | early (all of it from `answer_held_ahead`, before the scan starts) | early ≠ S | early ≠ F | S ≠ F | +|---|---|---|---|---|---| +| default threshold (corpus 200, OpenTitan 220, adversarial ×2 configurations) | 446 | **692 520** | 0 | 0 | 77 | +| threshold 400 (adversarial, corpus 48) | 61 | 115 118 | 0 | 0 | 98 | +| settings never answered (adversarial, corpus 48, OpenTitan 32) | 93 | 136 378 | 0 | 0 | 2 913 | +| rescan phase (edited buffers, mid-rescan, all of the above) | — | 106 718 | 0 | — | — | + +Early answers per request kind, default-threshold run: + +| request | early | waited | +|---|---|---| +| documentSymbol / foldingRange / scopePairs | 446 each | 0 | +| hover | 67 261 | 29 402 | +| definition | 66 176 | 30 487 | +| typeDefinition | 88 416 | 8 247 | +| documentHighlight | 77 401 | 19 262 | +| references | 38 095 | 58 568 | +| prepareRename | 74 980 | 21 683 | +| signatureHelp | 85 527 | 11 136 | +| linkedEditingRange / selectionRange | 96 663 each | 0 | +| completion / codeLens / inlayHint / documentLink | 0 | 2 801 each | + +Notes on these numbers: +- **No request was answered during staging.** The one + `edited_buffer_early_in_staging` entry in the results comes from a smoke + run made before I switched that check off for round 3. +- **The edited files' requests are early again.** They are answered after + the settings, with the flush done under the user's settings, so the early + count is back to round 1's order. +- **S ≠ F at the default threshold (77)** splits into: + - 49 references in OpenTitan, the same 49 as round 1, which are + pre-existing; + - 6 hover and 6 definition (adv2's `` `include`` graph), and 16 + completion, all pre-existing from round 1. +- **S ≠ F at threshold 400 went from 2 877 to 98.** The residue is index + history, not analysis. Example: with `misc.sv` opened as large *before* + the scan, it contributes nothing, so `dupm` is unique and `prepareRename` + says renameable. A fresh server that opened it *after* its scan says + ambiguous. `drv/openorder.py` gives exactly the same split on **base** — + this is S2. +- **"Never" runs:** the early server is left on the default settings + (folder scope) while the fresh server gets the workspace scope, so S ≠ F + there is a different configuration, not a defect. + +**d. Startup** (`drv/startup.py`, 4k files, median of 5, ms; outline A / +edited hover A / outline B). + +| settings answered | base | r2 | r3 | +|---|---|---|---| +| at once | 596 / 590 / 683 | 2.4 / 583 / 585 | **2.3–3.7** / 563 / 564 | +| after 0.5 s | 1 043 / 1 057 / 1 148 | 2.5 / 1 090 / 1 091 | **514** / 1 066 / 1 068 | +| after 1.9 s | 2 465 / 2 464 / 2 552 | 2.5 / 2 467 / 2 468 | **1 907** / 2 465 / 2 467 | + +- With a prompt client, r3 equals r2. +- With a slow client, r3 is slower than r2, by design: nothing is answered + before the settings. It is never slower than base, and still roughly + 500 ms ahead of it. +- The first answer of any kind (the colours) arrives at about 2 ms + throughout. + +**e. R2 and R3** + +R2 (`drv/inh5.py` and the `trees/adv5` fixture). The detail now names the +declaring class for: +- an alias of an alias (`zr_mid::zz_mid_m`, `zr_root::zz_root_m`); +- a parameterised alias (`zr_param::zz_pt`). + +Info: a class extending a *package-qualified* alias +(`extends zpkg::zr_pkgalias`) gets no related-tier members at all. The +chain is not walked, and they stay in tier 5 with a correct detail. No +detail is wrong. + +R3, the table test in a scratch copy: + +| mutation | result | +|---|---| +| a stale `textDocument/moniker` row | **fails** | +| a removed `WillSaveWaitUntil` arm | **fails** | +| a removed row | **fails** | +| unmodified | passes | + +**f. The rewritten `large_file.rs` test** (`server/tests/large_file.rs:344`). +The new assertion is right: a push moves an open buffer onto the fast path +at once, and an edit keeps it there. The old rule is still stated in: +1. `editors/vscode/package.json:713`, the user-visible setting description: + "Takes effect the next time the file is opened or edited." +2. `docs/features/large-file-mode/README.md:104-109`: "takes effect at each + buffer's next change, not immediately". +3. `docs/features/large-file-mode/README.md:326-329`: "leaves that buffer in + the mode it was built in until its next change". +4. `crates/lucisv_server/src/state/buffers.rs:36-41` (doc comment): "change + mode at that moment and not before". This one is still true for edits, + but it no longer names the settings path. + +Not stale: `editors/vscode/README.md` (267, 343, 359, 914) and +`docs/site/src/content/docs/start/configuration.md:85`, which state no +timing; and `docs/features/perf5r-lint-snapshot/README.md:109`, since the +mode is still re-taken in `set_document`, the path reclassify goes +through. + +**g. Baseline** + +- **Gates.** Full `tools/gates.sh` **PASS**: lucisv_server 2 091/0 (+5 since + round 2: 4 staging tests and the R2 test), vlog_semantic 435, lucisv_mcp + 388, corpus 814/6, node 37/0; fmt, clippy and cross all pass. +- **Ignored release runs**, all passing: + - differential seed 7: 1 499 938 early, 0 differ; + - differential seed 13: 1 432 653 early, 0 differ; + - `viewport_sweep`, identical; + - `random_bursts_long_run`; + - both re-index sweeps. +- **Changed tests.** Since round 2, besides the declared `large_file.rs` + rewrite, round 2's `a_buffer_opened_before_the_settings_answers_early_what_it_answers_after_them` + was replaced by `a_buffer_opened_before_a_small_threshold_arrives_answers_as_a_fresh_server_does`. + That inverts the old contract, as Handshake request 6 said it would; it is + not a weakening. +- **Ordering drivers on r3, all with early kinds mixed in:** + - `ord3` 7121–7126 and `ord3t` 7131–7134: 0 fails; + - `c717` 1–3: no duplicates, last answers 0.21 / 0.67 / 0.69 s (base + 3.3–3.7 s); only `semanticTokens/full` differs from settled; + - `harm2`: identical to base; + - `f6` ×3: v3 = v3; + - `livelock`: 170 ms; `livelock2`: 102 / 667 ms; + - `wid.py` 1, 2 and shutdown: 0 fails. +- **`beh.py` on r3:** the three burst orderings are unchanged (S1 early v2, + S2 waits v3, S3 v3, S4 v5, S5 early v6), and the publish sequence + `[1,2,2,2,3,3,1,1,2,4,4]` is identical to base. +- **Completion** (corpus, seed 31, 2 702 samples, 402 647 base items): + - 0 missing, 0 edits changed; + - the no-defaults client equals the defaults client; + - 0 ranking violations; + - 112.5 MB → 51.5 MB on the wire; + - 300 detail and 2 kind+detail changes: Q2, kept as documented. + +**S2 (Low; pre-existing on base — file separately).** A large open buffer +is in the index or not depending on history: +- If it is open at scan or save time, it contributes nothing. +- If it is opened after the scan, its disk record stays. + +So cross-file definition, hover, references and prepareRename into it +depend on when it was opened, saved or flipped. Repros: +- `drv/openorder.py`: base, before-scan → renameable; after-scan → + ambiguous; +- `drv/largesave.py`: base, an edit crossing the threshold then a save → + `top`'s definition becomes `[]`. + +Round 3 adds the settings push as one more way to flip a buffer. It does not +widen the inconsistency. + +**Fixed myself:** nothing in the worktree. `bin/r3fix` and the scratch edit +in `qa712/mut` demonstrate the S1 fix only. + +**Not verified:** a real VS Code session. `~/.cache/lucisv-opentitan-full` +`git status --short` is empty. + +### 2026-11-19 — QA agent (Fable 5.2), escalation round + +**Verdict: PASS WITH FINDINGS.** S1, H2–H6, O1, O2 and C1 each reproduce +on the round-3 binary (or on 0.65.10 where they predate the lane) and are +gone on this tree. I found no interleaving in which a request is answered +ahead from a state older than its place in the stream. Five findings, none +of them an early answer: one ordering bug in the startup's settings wait +that predates the lane (F1), three about what the new tests can see (F2 +fixed here, F3, F4), one stale document of another feature (F5). + +Subject: `scratchpad/qa712f/bin/qa`, my own release build of this worktree +— byte-identical to the dev's `fin` (`cmp`). Baselines: `r3` (round 3) and +`base` (0.65.10, `c1c1407`). Everything below is under +`/private/tmp/claude-501/-Users-lucio-repo-lucisv/d043c274-11ff-4de2-ab0f-45daa8a877f0/scratchpad/qa712f/` +(`drv/` my drivers, `odrv*/` the earlier rounds' drivers with only their +scratch path rewritten, `logs/`, `out/`). Every server and every `cargo +test` ran under `tools/guard.sh`; no guard kill. I killed only PIDs I +started. Trees are scratch copies; `~/.cache/lucisv-opentitan-full` and +`~/.cache/lucisv-corpus` are clean (`git status --short` empty, no file +newer than the session). + +**a. The reported holes, re-attacked over LSP** (`drv/atk.py BIN SCENARIO…`, +4 064-file tree, one fresh server per scenario; a 1.5 KB buffer A, a hover +on a signal it declares; "card" = the full hover, `null` = large-file mode). + +| # | scenario (`atk.py` name) | r3 | base | this tree | +|---|---|---|---|---| +| S1 | `[change A, push threshold 1000, hover A]` (`s1a`); `[push, hover A]` (`s1b`) | card, then `null` | — (never re-classifies) | `null` / `null` | +| S1 | `odrv/dirtypush2.py`, both forms | card 3/3; card 2/3 | — | `null` **10/10 and 10/10** | +| H2 | mid-rescan `[lens, push 1000, hover A]` (`h2`) | card, ahead | — | `null`, waited | +| H3 | mid-rescan `[lens, settings answer 1000, hover A]` (`h3`) | card, ahead | — | `null`, waited | +| H4 | `[created, settings answer 1000]`, hover mid-scan (`h4`) | card | — | `null` | +| H5 | empty push, hover mid-rescan, answer withheld (`h5`) | answered before the settings: card | held | held until the answer, then `null` | +| H6 | mid-rescan `[lens, X, hover A]`, X = unknown notification, `didChange` with no / an unparseable URI, folders, `didRenameFiles`, `didDeleteFiles`, `willSave` (`h6…`) | ahead (first three run) | waited | waited, every one | +| O1 | held `[lens, settings answer 1000]`, then push 0 (`o1`) | ends at 1000, 4/4 | ends at 1000, 3 of 4 (once the write was read as two bursts) | ends at 0, 4/4 | +| O2 | held `[lens, push 1000]`, then settings answer 0 (`o2`) | ends at 1000 | ends at 1000 | ends at 0 | +| C1 | colours ahead of a waiting watcher event, no scan running (`c1`; needs the package file to appear after the first walk) | stale colours, **0** refreshes, 3/3 | the same, 3/3 | recorded as a guess, **1** refresh, 3/3 | + +Also closed, and open on r3: the threshold **raised** (`p1`, `p1h`: r3 +answers `null` for a buffer that is no longer large); the **widen** path +(`wburst`, `wmid`: a push behind a widening `didOpen` in its burst, and one +arriving mid-widen — r3 answers the card ahead of both); a held push that +changes `exclude` so the buffer becomes excluded (`p7h`: r3 ahead; the answer +is the same either way). + +**b. The precondition, clause by clause.** Each row is an `atk.py` scenario +on this tree; the hover's answer equals the answer asked again once settled +in every one, and no request was answered twice. + +| clause | attacked with | result | +|---|---|---| +| (a) open | hover on a URI never opened, a request with no `textDocument`, one with a URI that does not parse (`notopen`); close with no reopen (`p3c`) | `null`, `-32602`, `-32602`, each once; `null`, not ahead | +| (b) own-buffer messages | close + reopen with another text, in one burst and held (`p3`, `p3h`); `didSave` carrying another text (`p10`, `p10h`); an edit with an older version number (`lowver`) | the new text every time | +| (b) settings | S1/H2–H5 above; the startup's pull answered late, in a burst and mid-rescan (`p14`, `p14h`); two empty pushes, the first pull answered only (`p13`: no hang, answered at the rescan's end); a push moving only `indent` (`h6indent`: waits behind it when held) | as a one-message-at-a-time server | +| (b) proved harmless | held in front of the hover: a watcher event naming A's own file, changed and deleted on disk (`p8chg`, `p8del`, `gwatch`); another buffer's edit (`gother`); a cancel (`gcancel`); an answer the server never asked for (`gstray`) | goes ahead, same card | +| (b) other spellings of A's URI | an edit and an open under `%61`, `/./`, upper case, `file://localhost/`, a symlink (`p4…`, `p4h…`, `symlink`) | a different buffer on every binary (buffers are keyed by the URI as sent, and no same-file handler looks a buffer up by path); A's answer unchanged | +| (c) current analysis | S1's dirty form; the differential below | — | +| (d) settings awaited | H5; staging (`odrv/stg2.py`: nothing answered before the settings, s5 and s6 `null` **10/10** each; `stg3.py` `BAD: []`) | — | +| (e) | the lane's differential, long run: seed 7 — 1 499 938 early, 0 differ; seed 13 — 1 432 653, 0 differ (default 8 GB guard; no `-m 12` needed) | — | +| colours | behind a held threshold push (`colpush`: r3 ahead with 166 tokens, this tree waits and declines `-32801`); in the announced window (`colann`: ahead by design, 1 refresh when the answer flips the buffer); C1 | — | +| cancel, shutdown, exit | `[hover, cancel, lens, cancel]` and a cancel ahead of its request (`p5`, `p5b`): one answer; `[hover, shutdown]`, `[shutdown, hover]`, `[lens, exit, hover]` (`p6hs`, `p6sh`, `exitburst`) | identical to base (a request behind `shutdown` or `exit` is never answered there either) | + +One run of `h6indent` answered the hover "early": the write was read as two +bursts, the push was applied first and the hover then went ahead of the lens +only — in order. 4/4 repeats waited. + +By reading: `REACH`'s two `Nothing` rows hold — nothing a watcher event +does reaches `set_document`, `close_document` or the threshold +(`lucisv.toml` carries no `largeFile` key; `large_file_threshold` has three +readers, all listed in the README); a `Document` is changed in place only by +`refresh_overlay`. `owes_a_state_change` is evaluated against `pending` +before `response()` removes the entry, so the burst's count stays exact. + +**c. The tests, mutated** (`mutq.sh`, `mut2.sh`: scratch copy, own target, +whole `lucisv_server` suite; the untouched copy passes 1 999 / 106 / 3 / 1). +The dev's twelve (`mutate-dev.sh`): each fails at least one test, as logged. +Mine: + +| mutation | caught by | +|---|---| +| `answer_ahead_of` passes nothing as ahead (S1 back) | 7 precondition tests + the differential | +| `behind` not consulted | 3 (tail test, differential, a viewport test) | +| no flush before the answer (c) | 4 | +| `set_aside` passes nothing as ahead | 9 | +| `didSave` / `didClose` → `Nothing` | 3 each | +| `didOpen` → `Nothing` | the table test only (its count of `Named` rows) | +| a new threshold does not re-classify | 16 | +| colours do not wait on a dirty buffer | 1 (viewport) | +| a cancel for a request answered ahead ignored | 2 | +| a new arm in block form; a row with no arm; a fifth `Named` row; `didDeleteFiles` → `Nothing` | the table test; the held-notification test | +| **any response clears `settings_announced`** | **nothing** → F2 | +| **a new arm written `X::METHOD => expr,`** | **nothing** → F3 | +| `answer_ahead_of` / `open_then_widen` set `behind = 0`; clause (a)'s `document(uri).is_some()` removed | nothing — equivalent: a notification is only applied when `behind` is already 0, and the second lookup (`workspace.document(&uri)?`, or the handler's `null`) gives the same result | + +**d. The differential's oracle** (`fast_actions_bursts.rs:434`). It accepts +an answer given ahead when the reference gives it at the request's place +**or after any later message of the round** — whether or not the early +server had applied that message when it answered. So a stale answer passes +when a later message puts the earlier state back (a threshold moved and +moved back; the same text again). Measured (`mutoracle.sh`: the assert +replaced by a counter, long run, 1 500 rounds, seeds 7 / 11; the unmutated +tree has 4 / 2 legitimate later-state answers): + +| mutation | answers not the one at the request's place | rejected by the oracle | let through beyond the 4 / 2 | +|---|---|---|---| +| S1 back | 220 / 238 | 207 / 216 | 9 / 20 | +| a push reaches no buffer | 94 / 89 | 85 / 79 | 5 / 8 | +| `set_aside` passes nothing | 19 / 12 | 15 / 10 | 0 / 0 | +| own-buffer edits do not hold | 34 / 41 | 29 / 35 | 1 / 4 | +| no flush | 92 / 93 | 87 / 90 | 1 / 1 | + +Tight enough to catch every one of these holes many times over, not tight +per answer: 2–9 % of the stale answers pass. F4. The removed +`fast_actions.rs` test was right to go: its first half is the new trigger +test's first case, its second (`[change, hover]` answered after the change) +is held by five tests (the dev's M9). + +**e. Ordering and liveness.** +- My campaign (`drv/rnd.py`, a causal oracle: a hover's answer must be what + some state gives that lies at or after its place and no later than the + last message written before the answer was read; every request answered + once; the end state equals the client's). Random bursts of edits, opens, + closes, saves, threshold pushes, indent pushes, empty pushes, settings + answers given late or never, watcher events (whole rescans), cancels, an + unknown notification; the startup's pull answered at once / late / never. + **This tree: 42 runs (14 seeds × 3 modes), 5 718 messages, 1 830 hovers, + 942 other requests — 0 violations, 0 duplicates, 0 hangs.** r3 with the + same driver: violations in 10 of 18 runs (the driver sees S1). A first + pass reported one end-state mismatch on this tree; it was the driver (an + indent push built with a stale threshold), fixed, and the 42 runs redone. +- Earlier rounds' drivers on this tree (`camp-old.sh`): `strand.py` 40 runs, + **0 fails**; `ord3.py` 7121–7126 and `ord3t.py` 7131–7134, 0 fails, every + fresh oracle equal; `c717.py` 1–3, 0 duplicates, last answer 0.27 / 0.68 / + 0.70 s; `harm2.py` H1–H7 as before; `livelock` 168 ms, `livelock2` + 101 / 675 ms; `f6.py` ×3 v3 = v3; `wid.py` 1, 2, shutdown 0 fails; + `recl.py` 50 publishes, 0 twice, 1 refresh / 0 / 50, 0, 1; `beh.py` + S1 early v2, S2 waits v3, publishes `[1,2,2,2,3,3,1,1,2,4,4]`. + +**f. Performance** (`camp-perf.sh`, `camp-ab.sh`; idle machine, one run at +a time; ms unless said; 4k / 20k / 40k files). + +| a local hover around a watcher event that costs a whole rescan (`b3.py`, 6 / 3 / 2 runs) | 0.65.10 | this tree | README says | +|---|---|---|---| +| server idle, request 5 ms later | 1 193 / 5 968 / 12 310 | **47 / 167 / 321** | 38 / 168 / 331 | +| server idle, same write | 1 196 / 6 027 / 12 252 | **0.3 / 0.1 / 0.1** | 0.1–0.2 | +| server busy in the previous delete | 1 334 / 6 979 / 14 332 | **171 / 986 / 2 226** | 171 / 1 024 / 2 252 | + +`meas2.py` (5 / 3 / 3 runs), base → this tree: startup local hover 547 → +**2.4** / 665 → **1.5** / 831 → **1.9**; outline 548 → 3.5 / 666 → 2.2 / +831 → 3.2; rescan row (a busy server) 1 398 → 230 / 6 991 → 1 061 / +14 585 → 2 274; widen 345 → 21 / 333 → 1.6 / 356 → 1.6 (outline 23); +settled hover 0.05 → 0.04 / 0.07 → 0.06 / 0.09 → 0.08, completion 1.64 → +1.38 / 1.72 → 1.43 / 1.92 → 1.56. `startup.py` (4k, 5 runs; outline A / +cross-file lens): prompt client 542 / 542 → **4.0** / 548; settings after +0.5 s 1 060 → 513 / 1 069; after 1.9 s 2 467 → 1 911 / 2 470. + +**The README, `docs/perf/README.md` and changelog numbers match what I +measure** (4k idle: 47 where they say 38; everything else within a few +percent). Two things a reader should know, neither wrong as written: the +"same write" 0.1–0.3 ms is the request read in one burst with the event — +in my runs that was the hover (0.1–0.3 ms in all 11); the outline in the +same write took a median 55 / 145 / 300 ms (the first drain point), as in +the dev's own data. +And the "busy" row is the delete's one-file update (Handshake request 9), +which is most of what a user who deletes and goes on will feel. + +**Nothing regressed for what still waits.** Cross-file requests at startup +and in a widen: within 1 % of base (table above, `meas2`). The whole rescan +as the server times it, and what a code lens waits (`drv/ab41.py`, base and +this tree alternated twice, a code-lens barrier so the server really is +idle): + +| | 0.65.10 | this tree | +|---|---|---| +| 4k, idle: lens waits / the rescan itself | 1.24, 1.22 / 1.24, 1.22 s | 1.22, 1.24 / 1.23, 1.25 s | +| 4k, busy | 1.38, 1.37 / 1.19, 1.18 | 1.40, 1.38 / 1.21, 1.20 | +| 20k, idle; busy | 6.18 / 6.19; 7.05 / 6.00 | 6.09 / 6.10; 7.14 / 6.09 | +| 40k, idle | 12.55, 12.48 / 12.56, 12.49 | 12.34, 12.46 / 12.35, 12.47 | +| 40k, busy | 17.40, 16.83 / 15.09, 14.58 | 14.60, 14.60 / 12.31, 12.32 | + +The 40k rescan that follows a delete is bimodal on this machine (about 12.3 +or 14.5–15.5 s): here base took the slow mode both times, in `b3.py` this +tree did (17.7 against 14.3 s) and in the dev's table likewise. I could not +tie it to either binary and did not find its cause. `meas2`'s +5 % for a +cross-file hover in a 4k rescan (1 404 → 1 474) is not in the server's own +timing above; with an early-eligible request as its "idle" barrier a +harness lets this tree start the next step inside the delete (my first A/B +did exactly that: 1.19 → 1.40 s, gone with a code-lens barrier). + +**g. Documents and sizes.** `editors/vscode/package.json` (the threshold +"takes effect at once on the files already open"), both passages of +`docs/features/large-file-mode/README.md`, `state/buffers.rs`'s and +`state/scope.rs`'s comments and this README's Assumptions all match the +behaviour (`recl.py`, `p1`). No other statement of the old rule is left +(`grep` over `*.md`, `*.json`, `*.rs`, `*.ts`, `*.js`). Production lines: `server/ahead.rs` 226, `server/mod.rs` 238, +`notification.rs` 251, `client.rs` 193, `startup.rs` 178, `large_file.rs` +110, `viewport.rs` 102, `dispatch.rs` 503; nothing near 600. Longest +function touched: `process_batch`, 83 lines with its comments (79 on +0.65.10) — over the 80 CLAUDE.md says to look at; most of it is comment. + +**h. Gates** (final tree, with F2's assertion in). + +| gate | result | +|---|---| +| `cargo fmt --all -- --check`; `cargo clippy --all-targets -- -D warnings` | clean | +| `tools/guard.sh -- cargo test -p lucisv_server` | 1 999 + 106 + 3 + 1 pass | +| full `tools/gates.sh -c ` (not under `guard.sh`) | **PASS**, every step: lucisv_server 2 109/0, vlog_semantic 435/0, lucisv_mcp 388/0, vlog_parser 521, vlog_refactor 743, vlog_formatter 376, vlog_linter 672, lucisv_core 119, lucisv 151, docs, corpus 814/6, node 37/0, cross | +| ignored, release: `early_answers_equal_settled…` seeds 7, 13 | 0 differ (numbers in b) | +| … the burst differential, 3 000 rounds, seeds 7, 23, 31 | 13 534 / 14 031 / 13 798 requests, 3 401 / 3 270 / 3 353 ahead (5 / 0 / 1 later state), 12 000 settled each, **0 differ** | +| … `viewport_sweep` | 1 267 files, 7 602 windows, 541 616 / 559 725 agree, 0 other — identical to 0.65.10 | +| … `random_bursts_long_run`, both re-index sweeps | pass | + +**Findings.** + +**F1 (Low; predates the lane — 0.65.10 and r3 alike; in the rule this round +amended).** In the startup's settings wait, the client's answer to the pull +is applied **ahead of an older settings push** held with it, and the server +ends on the older settings. +- Where: `server/startup.rs:357` (`take_the_answer_out_of_held`), which the + Handshakes entry "Changed, read this" keeps on purpose; `must_hold`'s + comment (`server/mod.rs`) says "outside the startup's wait". +- Repro: `python3 qa712f/drv/atk.py qa o3b` (also `base`, `r3`). The + staging loop is made busy by a 40 000-line `didOpen`; then one write + `[didOpen A, hover A, push threshold 1000, settings answer threshold 0]`. +- Observed, 3/3 on each binary: the answer is applied first, the push is + replayed after it, the threshold in force ends at 1 000 — A, 1.5 KB, is + large and a hover after a same-size edit says `null`. Expected: 0 (the + answer is the client's last word) and the card. The hover inside the burst + is answered from a state at or after its place on this tree (card), so + this is not an early-answer defect; every later request is answered under + settings the client replaced. On this tree the wrong mode shows at once + (re-classification); on base at the buffer's next edit. +- Needs a client whose push and pull answer disagree inside one startup + burst behind a request; not seen from VS Code. The O1/O2 fix covers every + other window. Suggest: take the answer out of `held` only when no state + change is held in front of it. + +**F2 (Low; new test gap; fixed here).** Nothing pinned that only the pull's +own answer ends the announced-settings wait: with `client.rs`'s +`if self.settings_announced.as_ref() == Some(&response.id)` made `if true` +the whole suite passed, and then any answer from the client (to a progress +create, a registration, a token refresh) would reopen H5. Added four lines +to `it_waits_while_the_settings_a_client_announced_have_not_been_answered` +(`tests/fast_actions_precondition.rs:327–330`: a stray response before the +held hover); the mutation now fails that test, the unmutated tree passes. + +**F3 (Low; new).** The table test does not see every arm. +`handled_notifications` (`tests/fast_actions_precondition.rs:509–515`) reads +lines ending `::METHOD => {`. Repro: in a copy, add +`lsp_types::notification::DidCreateFiles::METHOD => self.reindex(),` to +`handle_notification` — `cargo test -p lucisv_server` passes (`mutq.sh`, +Q16); the block form of the same arm fails as intended (Q15). An or-pattern +arm is missed the same way. Harmless to answers — a method with no row +reaches `Reach::Any` — but the README (lines 251, 614: "fails for an arm +without a row", "a test fails until it has one") promises more than the +reader delivers. Either read arms as `::METHOD` followed by `=>` or `|`, or +say "an arm in block form". + +**F4 (Low; new).** The burst differential's oracle is loose per answer — +section d: 2–9 % of deliberately stale answers pass it. Suggest recording, +with `probe::went_ahead`, how many of the round's state changes had been +applied when the answer was given, and comparing with exactly that +reference state. + +**F5 (Info; flagged by the dev, the lead's to amend).** +`docs/features/scan-ordering/README.md:54–56` ("Exempt altogether: +**responses**") and `:95` ("A response is never held") are no longer true: +the answer to a settings pull is ordered. The Handshakes entry says so. + +**F6 (Info).** `TODO.md:7322` (§71.2) is still unticked. + +**Fixed myself:** F2's assertion, nothing else in the worktree. + +**Not verified:** a real VS Code session; how often VS Code's writes are +read as one burst with a watcher event on an idle server (in my runs only +the first request behind the event was); the cause of the bimodal 40k rescan +after a delete; Windows and Linux beyond the `cross` check; `fadiff.py` +(the staging differential over LSP) was not re-run this round — `stg2`, +`stg3`, `strand` and the in-tree differential were. + +## Review + +**Lead, 2026-11-19 — accepted for 0.65.11 after the escalation round.** + +History: dev round 1 → QA FAIL (Q1, staging and the large-file threshold) → +fix → QA PASS with findings (R1–R3) → dev round 3 → QA FAIL (S1, a hover +answered ahead of a settings push in its burst). Two failures on one feature, +so the round was redone with Fable 5.2 as dev and as QA, as CLAUDE.md says. + +S1 was partly mine: QA had measured `answer_ahead_of` as buying nothing and I +kept it in round 3 anyway. For the escalation I asked for it to be removed by +default. The dev built the removal, measured it, and kept the behaviour — and +the measurement is why I accept that: without it a same-file request read in +one burst with a rescan's trigger waits the whole rescan (1.2–16 s at +4k–40k files), which is the case this feature exists for whenever the server +is busy. What changed is that it is no longer an exception: it goes through +`can_reach` like every other place, and a settings push blocks it. + +What I checked myself: + +- `server/ahead.rs` whole. The precondition is stated once on + `answer_from_the_buffer` and the function's body is clauses (a)–(e) in the + order the comment gives; `REACH` defaults to `Any` for a method without a + row, and the response kinds are an exhaustive match over `Pending`. Every + entry point (`set_aside`, `answer_ahead_of`, `open_then_widen`, + `answer_held_ahead`, `answer_ahead_mid_widen`) reaches the same function. +- QA's F3 (the set-equality test saw only arms written `X::METHOD => {`): + fixed here — the test now reads any `…::METHOD =>` arm, one-line or + path-qualified. +- QA's F5: `docs/features/scan-ordering/README.md` amended in both places — + the answer to a settings pull is ordered like a notification; every other + response stays exempt. I accept that amendment to scan-ordering's rule: + O1/O2 are real orderings 0.65.8 got wrong. +- The corrected headline. The round-1 "whole rescan" figures measured a file + delete. The numbers in the changelog are QA's own. + +Accepted as they stand, filed in TODO §71: + +- F1 (predates the lane): inside the startup wait the pull's answer is + applied ahead of an older push held with it. +- F4: the burst differential's oracle forgives 2–9 % of stale answers when a + later message restores the old state. Every mutation is still caught many + times over, and the directed tests do not have the weakness. +- S2 (predates the lane): whether a large open buffer is in the index + depends on its history. +- The 40k rescan after a delete is bimodal (12.3 s or 14.5–15.5 s), on base + and lane alike; cause not found. + +Not verified by anyone: a real VS Code session. diff --git a/docs/features/large-file-mode/README.md b/docs/features/large-file-mode/README.md index 2b02a42..f933ff6 100644 --- a/docs/features/large-file-mode/README.md +++ b/docs/features/large-file-mode/README.md @@ -105,8 +105,15 @@ Because the decision lives in `set_document`, it is re-taken on every `didOpen`, every `didChange` and every text-carrying `didSave`. A buffer edited past the threshold switches to the fast path at that moment; one edited back under it is analyzed again in full. **A changed `lucisv.largeFile.threshold` -therefore takes effect at each buffer's next change, not immediately** — the -simplest rule that has no re-analysis storm in it, and the one the tests pin. +takes effect on the open buffers at once** (since `fast-actions`, 2026-11-19; +before it, at each buffer's next change): the settings applier re-analyzes +exactly the open, clean buffers the new value classifies differently +(`Server::reclassify_large_buffers`, called by `apply_settings` for the +startup's settings answer and every later push), republishes each once and asks +a capable client to re-request its colours. An unchanged threshold costs one +comparison, a dirty buffer takes the new value at its flush, and like an edit +this does not reindex — the index takes the buffer's new mode at its next save +or rescan (`docs/features/fast-actions/README.md`, Handshake request 8). ## The dispatch table @@ -324,9 +331,11 @@ rebuilds the buffer (O(file) per batch, and edits in a netlist are rare) and built-in LSP) asks for ranges. - **The buffer's text stays in memory.** 100 MB of `String` is the price of answering anything at all; the editor holds a copy too. -- **The threshold is not consulted anywhere but `set_document`.** A setting - changed while a buffer is open leaves that buffer in the mode it was built - in until its next change. +- **The threshold is consulted in `set_document`, and by the settings applier + for the buffers already open** (`Workspace::is_large`). A setting changed + while a buffer is open moves that buffer to the mode the new value gives it + at once, by re-analyzing it through `set_document` + (`Server::reclassify_large_buffers`). - **VS Code ≥ 1.134 behaves as the bundle read here says.** The two facts relied on — "complete tokens stop the viewport provider" and "an error is not a complete answer" — have been in VS Code for years, and the range provider diff --git a/docs/features/scan-ordering/README.md b/docs/features/scan-ordering/README.md index 368688e..2ed95ae 100644 --- a/docs/features/scan-ordering/README.md +++ b/docs/features/scan-ordering/README.md @@ -53,7 +53,10 @@ fix round for its cost, QA-1). 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 + relies on that) — **amended 2026-11-19 by fast-actions (0.65.11):** the + client's answer to a settings pull is applied as a settings push is, so + outside the startup wait it is ordered like a notification (`must_hold`, + `behind`); every other response stays exempt — 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 @@ -93,7 +96,8 @@ fix round (in particular not `incremental.rs`'s `holds_another_spelling_of`). 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. + held, except the answer to a settings pull (fast-actions, 0.65.11), which + is ordered like a notification. `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), diff --git a/docs/perf/README.md b/docs/perf/README.md index 91da04e..0822a9f 100644 --- a/docs/perf/README.md +++ b/docs/perf/README.md @@ -1498,3 +1498,36 @@ index-changing save (only answers taken off an unsettled index are re-checked; unrestricted it was 1.4–2.3 / 12.7–14.2 ms per save). A 60-line `range` on a buffer of 4 000 modules costs 0.30 ms against 0.28 ms for 500 in a debug build (was 98 ms against 11 ms: the old answer built the whole file). + +### 2026-11-19 — fast actions: same file first, completion through the relationship map (lane 71.2) + +Real binary over LSP stdio with VS Code 1.145's client capabilities, against +copies of OpenTitan `hw/` replicated 1 / 5 / 10 times (4 061 / 20 305 / +40 610 files, unit names prefixed per copy), workspace scope, cold store, +the open buffer `aes_cipher_core.sv`. Before = 0.65.10 (`c1c1407`); both +binaries run back to back per tree on a shared machine. Medians: 3 runs for +held requests, 20 calls settled. Harness and every table in +`docs/features/fast-actions/README.md`. + +| held during … (4k / 20k / 40k files) | before | after, a request the buffer answers | after, a cross-file one | +|---|---|---|---| +| a whole rescan (one watched *create*) | 939 / 4 712 / 9 781 ms | **195 / 1 110 / 2 435 ms** | unchanged | +| the startup scan (local hover with the `didOpen`) | 637 / 752 / 908 ms | **2.3 / 1.9 / 2.1 ms** | unchanged | +| a widen (folder scope) | 366 / 369 / 363 ms | **0.6 / 0.6 / 0.2 ms** | unchanged | + +(Re-measured in the lane's escalation round: the rescan row's "after" is the +harness's own previous step — a delete's one-file update, which drains +nothing — and not the rescan. With the server idle when the watcher event +arrives a buffer-local request sent 5 ms later takes **38 / 168 / 331 ms**, +and 0.1–0.2 ms when it is written together with the event.) + +Settled, nothing the buffer-local requests do scales with the workspace +(every one under 1 ms at 40k files, unchanged by this lane). Completion, +per answer, at every size: 129–155 KB → **62–84 KB** for a client that takes +`itemDefaults` (the range and format said once), server time 1.4–1.6 → +0.9–1.2 ms, and the members of the imported package all offered (at +`ae`, 40k files: 10 of 34 → 34 of 34). What remains slow and is not this +lane's: the rescan itself (whole, for one created file), its first ~0.5–2 s +before any drain point, `workspace/symbol` (118 ms for one letter at 40k), +the hierarchy snapshot (26 MB, 274 ms at 40k), and a 20k-line buffer's +reparse per keystroke (~20–27 ms). diff --git a/editors/vscode/CHANGELOG.md b/editors/vscode/CHANGELOG.md index 982fe76..a7e5d44 100644 --- a/editors/vscode/CHANGELOG.md +++ b/editors/vscode/CHANGELOG.md @@ -5,6 +5,18 @@ 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.11 — 2026-11-19 + +- **Hover, go-to-definition, the outline and folding answer immediately for + names declared in the file you are in,** even while a large project is + being indexed or re-scanned: milliseconds instead of up to a second at + startup, and a fraction of a second instead of 1–12 s during a re-scan. +- **Completion lists what the file can actually reach first** — imported + package members, inherited class members and macros from included + headers — instead of losing them among a huge workspace's names. +- **Changing `lucisv.largeFile.threshold` takes effect on open files at + once.** + ## 0.65.10 — 2026-11-19 - **Syntax colours appear immediately,** without waiting for the workspace to diff --git a/editors/vscode/README.md b/editors/vscode/README.md index 02be578..405cc11 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.10**. Its platform packages include +The current release is **0.65.11**. Its platform packages include `lucisv-server`, the `lucisv` command-line tool and `lucisv-mcp` (see [Agents (MCP)](#agents-mcp)): @@ -440,6 +440,12 @@ default): } ``` +## Release 0.65.11 highlights + +Version 0.65.11 answers hover, go-to-definition, the outline and folding for +names declared in the current file without waiting for the workspace index, +and puts the names a file can reach at the top of completion. + ## Release 0.65.10 highlights Version 0.65.10 colours a file the moment it opens instead of after the diff --git a/editors/vscode/package-lock.json b/editors/vscode/package-lock.json index e211a81..c85b8c8 100644 --- a/editors/vscode/package-lock.json +++ b/editors/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "lucisv", - "version": "0.65.10", + "version": "0.65.11", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "lucisv", - "version": "0.65.10", + "version": "0.65.11", "license": "MIT", "dependencies": { "vscode-languageclient": "9.0.1" diff --git a/editors/vscode/package.json b/editors/vscode/package.json index beba937..2398db3 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.10", + "version": "0.65.11", "publisher": "guoliangchen", "author": "Guoliang Chen", "license": "MIT", @@ -710,7 +710,7 @@ "type": "number", "default": 4194304, "minimum": 0, - "markdownDescription": "Size in bytes above which an **opened file** is put on the fast path: it is line-counted and nothing else — never parsed, never analyzed, never indexed — so a 100 MB netlist opens instantly instead of hanging the editor. What you still get is **syntax colouring of what is on screen**, painted a screenful at a time, plus go-to-definition and find-references within that file by text search. Everything else — diagnostics, formatting, symbols, folding, rename, hover, completion — answers nothing at all for such a file, and formatting says so rather than doing nothing quietly. A file on the fast path is left out of the workspace index entirely, so its symbols do not exist for the rest of the project. Set to `0` to analyze every file you open however big it is. Takes effect the next time the file is opened or edited. Not to be confused with `#lucisv.index.maxFileSize#`, which is about files nobody opened." + "markdownDescription": "Size in bytes above which an **opened file** is put on the fast path: it is line-counted and nothing else — never parsed, never analyzed, never indexed — so a 100 MB netlist opens instantly instead of hanging the editor. What you still get is **syntax colouring of what is on screen**, painted a screenful at a time, plus go-to-definition and find-references within that file by text search. Everything else — diagnostics, formatting, symbols, folding, rename, hover, completion — answers nothing at all for such a file, and formatting says so rather than doing nothing quietly. A file on the fast path is left out of the workspace index entirely, so its symbols do not exist for the rest of the project. Set to `0` to analyze every file you open however big it is. A change takes effect at once on the files already open. Not to be confused with `#lucisv.index.maxFileSize#`, which is about files nobody opened." }, "lucisv.lint.select": { "type": "array",