From c1c140749863152d9ca1aaf7299b072f8ecc5338 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Thu, 19 Nov 2026 13:04:41 -0800 Subject: [PATCH] Release 0.65.10: highlighting no longer waits for the index MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TODO §71.3. On OpenTitan the first colours of a newly opened file waited 600-700 ms for the index (building them takes 0.3-6.5 ms), a rescan held them for most of a second, and the first answer, built from a half-finished index, was never corrected. - server/viewport.rs: semanticTokens range, full and full/delta for a buffer whose text is current are answered from that buffer alone before the request would be held — when no change for it is queued anywhere (held, 71.7's behind count, set aside ahead of it in its burst) and it is not dirty. The handler reads only that document and the remembered token answer. Built on 0.65.8's must_hold; the lane's own queue tracking is gone. - server/index.rs: open_then_widen applies the didOpen, answers the burst's colour requests, then widens; reindex_widened answers colour requests between its files. - One workspace/semanticTokens/refresh once the index settles, when an early answer differed or was a guess; only for clients with refreshSupport, which are also the only ones given early full answers. - tokens.rs: range classifies only the window's tokens (+1 each side) and skips AST items outside it; large.rs's line window is shared. First colour 2-39 ms (was 600-700); folder-scope late open 611-641 -> 2-32 ms; rescan hold 325-791 -> 70-159 ms. 96.8 % of early tokens already match the settled answer; the rest resolve through the index. Dev (two rounds), QA (two rounds: ~10 000 token answers against an exact oracle, 978 non-colour answers identical to base) and lead review: docs/features/viewport-highlight/README.md. Not seen in a running editor. Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both package-lock.json spots); notes in CHANGELOG.md (## 0.65.10) and editors/vscode/CHANGELOG.md. Gates: tools/gates.sh PASS on this tree including cross; lucisv_server 2052/0. Co-Authored-By: Claude Mythos 5.2 --- CHANGELOG.md | 46 + Cargo.lock | 18 +- Cargo.toml | 2 +- TODO.md | 15 +- crates/lucisv_server/src/large.rs | 20 +- crates/lucisv_server/src/main.rs | 16 + crates/lucisv_server/src/server/dispatch.rs | 12 + crates/lucisv_server/src/server/index.rs | 21 +- crates/lucisv_server/src/server/mod.rs | 32 +- .../src/server/semantic_tokens.rs | 4 + crates/lucisv_server/src/server/startup.rs | 1 + crates/lucisv_server/src/server/viewport.rs | 366 ++++++++ .../src/server/viewport/tests.rs | 514 +++++++++++ crates/lucisv_server/src/tokens.rs | 41 +- .../lucisv_server/src/tokens/instantiation.rs | 25 +- .../src/tokens/viewport_sweep.rs | 256 ++++++ .../lucisv_server/src/tokens/window_tests.rs | 120 +++ docs/features/viewport-highlight/README.md | 827 ++++++++++++++++++ docs/perf/README.md | 30 + editors/vscode/CHANGELOG.md | 10 + editors/vscode/README.md | 8 +- editors/vscode/package-lock.json | 4 +- editors/vscode/package.json | 2 +- 23 files changed, 2361 insertions(+), 29 deletions(-) create mode 100644 crates/lucisv_server/src/server/viewport.rs create mode 100644 crates/lucisv_server/src/server/viewport/tests.rs create mode 100644 crates/lucisv_server/src/tokens/viewport_sweep.rs create mode 100644 crates/lucisv_server/src/tokens/window_tests.rs create mode 100644 docs/features/viewport-highlight/README.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 61d43fd..f4e6721 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,52 @@ 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.10 — 2026-11-19 + +### Highlighting no longer waits for the index + +(`docs/features/viewport-highlight`; TODO §71.3. Measured on OpenTitan's `hw` +tree with the server driven the way VS Code drives it.) + +- **Colours arrive at once.** Building a file's colours takes 0.3–6.5 ms; + nearly all of the wait before first colour was the server holding every + request until the index was ready. A colouring request for a buffer whose + text is current is now answered from that buffer alone, even while a scan + or a widening of the index holds everything else. + + | first colour after opening a file | before | now | + |---|---:|---:| + | cold start, whole-workspace scope | 660–685 ms | 3.5–39 ms | + | cold start, folder scope (the default) | 38–74 ms | 3–32 ms | + | a file opened after startup settled, folder scope | 611–641 ms | 2–32 ms | + | a file in a folder not indexed yet, mid-session | 375 ms | 6 ms | + | while a rescan runs | 325–791 ms | 70–159 ms | + + The larger figure in each range is a 545 KB file, whose own parse is most + of what remains. +- **Imperfect first, then corrected — once.** Before the index settles, + names that resolve through it (a module or package in another file, an + inherited method) are coloured as local guesses: 96.8 % of tokens already + match the final answer, and nothing is ever coloured as code inside a + comment or a string. When the index settles the server sends one + `workspace/semanticTokens/refresh` and the editor's next answer is the + accurate one. This also fixes colours that used to stay wrong until the + next edit: the first answer was built from a half-finished index and never + revisited (2 745 tokens in one OpenTitan file). +- **The viewport request costs the viewport.** `semanticTokens/range` built + the whole file's tokens and filtered them; it now classifies only the + visible lines (0.3 ms for 60 lines of a 4 000-module buffer, against 98 ms). +- **What it will not do.** A buffer with edits the server has not applied + yet still waits — its existing colours stay on screen. An editor that + cannot be asked to refresh gets early viewport colours only, and its + whole-file answer waits as before. Hover, go-to-definition and every other + request still wait for the index they need; QA compared 978 such answers + with 0.65.8's and they are identical. +- **Still to come.** The file-discovery walk at the start of every scan + answers nothing while it runs, which is what is left of the wait in + whole-workspace scope (62–86 ms for a late open) and during rescans. Not + yet seen in a running editor by a human. + ## 0.65.9 — 2026-11-19 ### `lucisv-mcp` no longer serves stale contents; the suite runs on Linux diff --git a/Cargo.lock b/Cargo.lock index b1580d1..555b99a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -97,7 +97,7 @@ dependencies = [ [[package]] name = "lucisv" -version = "0.65.9" +version = "0.65.10" dependencies = [ "lucisv_core", "rayon", @@ -108,11 +108,11 @@ dependencies = [ [[package]] name = "lucisv_core" -version = "0.65.9" +version = "0.65.10" [[package]] name = "lucisv_mcp" -version = "0.65.9" +version = "0.65.10" dependencies = [ "lucisv_core", "serde", @@ -126,7 +126,7 @@ dependencies = [ [[package]] name = "lucisv_server" -version = "0.65.9" +version = "0.65.10" dependencies = [ "lsp-server", "lsp-types", @@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] name = "vlog_formatter" -version = "0.65.9" +version = "0.65.10" dependencies = [ "vlog_parser", ] [[package]] name = "vlog_linter" -version = "0.65.9" +version = "0.65.10" dependencies = [ "lucisv_core", "vlog_formatter", @@ -279,11 +279,11 @@ dependencies = [ [[package]] name = "vlog_parser" -version = "0.65.9" +version = "0.65.10" [[package]] name = "vlog_refactor" -version = "0.65.9" +version = "0.65.10" dependencies = [ "vlog_formatter", "vlog_parser", @@ -292,7 +292,7 @@ dependencies = [ [[package]] name = "vlog_semantic" -version = "0.65.9" +version = "0.65.10" dependencies = [ "vlog_parser", ] diff --git a/Cargo.toml b/Cargo.toml index 7816c2c..824c76b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ members = [ ] [workspace.package] -version = "0.65.9" +version = "0.65.10" authors = ["Guoliang Chen"] edition = "2021" license = "MIT" diff --git a/TODO.md b/TODO.md index cd7c85f..8d4e897 100644 --- a/TODO.md +++ b/TODO.md @@ -7323,7 +7323,8 @@ subsection, plan and `docs/features//README.md` when its turn comes. 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. -- [ ] **71.3 Highlighting does not wait for the index.** Always run a +- [x] **71.3 Highlighting does not wait for the index.** (0.65.10, `docs/features/viewport-highlight`) + Always run a localized, viewport-only highlight; it may be imperfect and be corrected later, but basic colours must not wait for the whole database. @@ -7469,3 +7470,15 @@ indexing, collide with each other and with §70's test files, and wait for `cargo check --all-targets` for Windows fails there (tests only). - [ ] The release is still gated on macOS alone; Windows is compile-checked (`cross`), never executed. + +- Wave 7 (lead, 2026-11-19): 71.3 shipped as 0.65.10, re-applied onto + 0.65.8's message loop by hand and re-validated by a second QA round. Left + open from it: + - [ ] The discovery walk at the start of every scan answers nothing while + it runs: a late open in workspace scope still waits 62–86 ms for + colour and a rescan holds colours 70–159 ms. Making the walk + resumable needs its own identical-result proof (`state/discover.rs`). + - [ ] A `range` answered during a rescan always counts as a guess and + 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). diff --git a/crates/lucisv_server/src/large.rs b/crates/lucisv_server/src/large.rs index e2d7e37..7497b17 100644 --- a/crates/lucisv_server/src/large.rs +++ b/crates/lucisv_server/src/large.rs @@ -121,11 +121,7 @@ pub fn window(doc: &Document, range: lsp_types::Range) -> Window { /// Both ends land on a character boundary: a line start and a line end always /// do, and the cap is floored onto one. fn bounds(index: &LineIndex, len: u32, range: lsp_types::Range) -> (u32, u32) { - let last = index.line_count(); - let first_line = (range.start.line + 1).min(last); - let last_line = (range.end.line + 1).clamp(first_line, last); - let start = index.line_range(first_line).map_or(0, |line| line.start); - let mut end = index.line_range(last_line).map_or(len, |line| line.end); + let (start, mut end) = line_window(index, len, range); if end.saturating_sub(start) > MAX_WINDOW { // Snapped to the line the cap lands in where that helps, and cut // mid-line where it does not: a single line longer than the cap is @@ -140,6 +136,20 @@ fn bounds(index: &LineIndex, len: u32, range: lsp_types::Range) -> (u32, u32) { (start, end.max(start)) } +/// The byte range one `Range` asks about, snapped out to the whole lines it +/// touches and **not** capped — the window an analyzed buffer's range answer +/// selects its tokens from (`tokens::semantic_tokens_in_range`), and the first +/// half of [`bounds`]. Both ends are line boundaries, so both are character +/// boundaries; a range past the end of the file is the empty window there. +pub fn line_window(index: &LineIndex, len: u32, range: lsp_types::Range) -> (u32, u32) { + let last = index.line_count(); + let first_line = (range.start.line.saturating_add(1)).min(last); + let last_line = (range.end.line.saturating_add(1)).clamp(first_line, last); + let start = index.line_range(first_line).map_or(0, |line| line.start); + let end = index.line_range(last_line).map_or(len, |line| line.end); + (start, end.max(start)) +} + /// Whether the byte at `at` is inside a `/* ... */` comment, as far as a /// backwards scan of at most [`BACKSCAN`] bytes can tell. /// diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index 44d95b0..9cb9dae 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -140,6 +140,7 @@ fn main() -> Result<(), Box> { show_document: show_document_support(¶ms), configuration: configuration_support(¶ms), token_server_cancel: token_server_cancel_support(¶ms), + semantic_tokens_refresh: semantic_tokens_refresh_support(¶ms), hierarchy_view, code_action_resolve: code_action_resolve_support(¶ms), create_files: create_files_support(¶ms), @@ -605,6 +606,21 @@ fn token_server_cancel_support(params: &InitializeParams) -> bool { }) } +/// Whether the client can be asked to re-request its semantic tokens +/// (`workspace/semanticTokens/refresh`), which is what replaces colours taken +/// off a half-built index once it has settled +/// (`docs/features/viewport-highlight/README.md`). Server-initiated, so the +/// capability is the gate; silence means no. +fn semantic_tokens_refresh_support(params: &InitializeParams) -> bool { + params + .capabilities + .workspace + .as_ref() + .and_then(|workspace| workspace.semantic_tokens.as_ref()) + .and_then(|tokens| tokens.refresh_support) + .unwrap_or(false) +} + /// Whether the client pulls diagnostics (LSP 3.17). /// /// Sending the capability at all is what says so; its two fields are about diff --git a/crates/lucisv_server/src/server/dispatch.rs b/crates/lucisv_server/src/server/dispatch.rs index d6e625b..60dc0c3 100644 --- a/crates/lucisv_server/src/server/dispatch.rs +++ b/crates/lucisv_server/src/server/dispatch.rs @@ -167,6 +167,18 @@ impl Server { // burst is coalesced: the changes before this request all become one // `set_document` in `flush_dirty`. self.flush_dirty_traced(); + self.answer_flushed(request) + } + + /// [`Server::answer_request`] after the flush: the large-file gate, then + /// the table. + /// + /// Its own function for the one caller that must **not** flush — the + /// viewport exemption, which answers a semantic-token request for a + /// buffer that is not dirty while a scan holds everything else, and which + /// must not analyze or publish any *other* buffer on the way + /// (`viewport.rs`). Every other request goes through `answer_request`. + pub(super) fn answer_flushed(&mut self, request: Request) -> Response { let id = request.id.clone(); let method = request.method.clone(); // The large-file fast path answers first, and for most methods it diff --git a/crates/lucisv_server/src/server/index.rs b/crates/lucisv_server/src/server/index.rs index 8b65f99..1eb4890 100644 --- a/crates/lucisv_server/src/server/index.rs +++ b/crates/lucisv_server/src/server/index.rs @@ -217,6 +217,12 @@ 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`). + if self.viewport.defers_widen(&added) { + return; + } + self.viewport.widening = true; let started = self.timer(); let since_start = self.since_start(); if started.is_some() { @@ -235,10 +241,11 @@ impl Server { let mut scan = self.watching(bar.as_ref(), |ws, watch| ws.begin_widen(&added, watch, verbose)); let total = scan.total(); - // No drain between the files: a widen is a rescan a message asked for, - // and `must_wait` would hold every request queued behind it anyway. It - // is also the point of the round that there is no longer a wait worth - // interleaving — a widen indexes one folder, not the whole scope. + // 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 + // that can be are answered from their buffers, and everything else is + // held in arrival order exactly as `must_hold` would hold it. loop { let step = |workspace: &mut Workspace, watch: &mut dyn FnMut(IndexEvent)| { workspace.scan_step(&mut scan, watch) @@ -246,6 +253,11 @@ impl Server { if !self.watching(bar.as_ref(), step) { break; } + if self.answer_colours_mid_widen().is_err() { + // The client has gone; nothing after this may speak to it. + self.stopped = true; + break; + } } let (skipped, cached) = (scan.skipped(), scan.cached()); let warnings = self.workspace.finish_scan(scan); @@ -257,6 +269,7 @@ impl Server { ) }); self.say_scan_trace(since_start); + self.viewport.widening = false; self.refresh_code_lenses(); self.hierarchy_index_changed(); self.generation += 1; diff --git a/crates/lucisv_server/src/server/mod.rs b/crates/lucisv_server/src/server/mod.rs index 678908c..80a2daf 100644 --- a/crates/lucisv_server/src/server/mod.rs +++ b/crates/lucisv_server/src/server/mod.rs @@ -24,6 +24,9 @@ //! * `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; //! * `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 @@ -64,6 +67,7 @@ mod semantic_tokens; mod startup; #[cfg(test)] mod tests; +mod viewport; /// What the client said it can do, read once at `initialize` because that is /// the only time those capabilities are sent. @@ -110,6 +114,12 @@ pub struct ClientAbilities { /// which error code declines `semanticTokens/full` on a large buffer — /// see `docs/features/large-file-mode/README.md`. pub token_server_cancel: bool, + /// Whether the client accepts a `workspace/semanticTokens/refresh` + /// (`workspace.semanticTokens.refreshSupport`). The refresh is what + /// replaces the colours answered while the index was still being built + /// (`docs/features/viewport-highlight/README.md`); a client that said + /// nothing keeps them until its next edit asks again. + pub semantic_tokens_refresh: bool, /// Whether the client hosts the custom lucisv hierarchy sidebar and wants /// a notification whenever the installed workspace index changes. pub hierarchy_view: bool, @@ -186,6 +196,10 @@ pub struct Server { /// client's `previousResultId` has to name the exact data it holds, and /// two buffers' answers are never comparable. token_results: u64, + /// What the viewport exemption owes the client once the index settles: + /// which buffers were coloured off an unsettled index, and which index + /// revision the last refresh decision was taken at (`viewport.rs`). + viewport: viewport::Viewport, /// Numbers the progress tokens the index rescans run under. One rescan is /// one token, and a token is never reused: a client keys the bar it is /// showing off it. @@ -369,6 +383,10 @@ impl Server { // arriving is released here, not only when the wait below times // out (`docs/features/port-entry-grace/README.md`). self.release_port_entries(); + // The index has settled and everything held behind it has been + // answered: whatever was coloured off a half-built index is + // re-requested now, at most once per index revision. + self.refresh_tokens_if_stale(); let message = match self.quiet_wait() { None => match self.queue.recv() { Ok(message) => message, @@ -427,11 +445,17 @@ 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). + if self.answered_ahead(&message, &[], &mut cancelled)? { + continue; + } self.cancel_deferred(&message)?; self.say_held(&message); let mut rest: Vec = std::mem::take(&mut consumed_cancels); rest.push(message); - rest.extend(messages); + self.set_aside(&mut rest, messages, &mut cancelled)?; self.hold(rest, already_waiting); return Ok(false); } @@ -463,7 +487,11 @@ impl Server { self.cancel_deferred(&cancel)?; consumed_cancels.push(cancel); } - Message::Notification(notification) => self.notification(notification), + // An open can widen the scope; the colours behind it in this + // burst are answered before the widen runs (`viewport.rs`). + Message::Notification(notification) => { + messages = self.apply_in_burst(notification, messages, &mut cancelled)?; + } Message::Response(response) => self.response(response), } } diff --git a/crates/lucisv_server/src/server/semantic_tokens.rs b/crates/lucisv_server/src/server/semantic_tokens.rs index 01dac85..79ffe79 100644 --- a/crates/lucisv_server/src/server/semantic_tokens.rs +++ b/crates/lucisv_server/src/server/semantic_tokens.rs @@ -52,6 +52,10 @@ impl Server { /// is computed against. One buffer holds one answer: a client that asks /// again has moved on from the previous one. fn remember_tokens(&mut self, uri: &Uri, data: Vec) -> String { + // A whole answer supersedes any viewport the client was painted with, + // and it is remembered, so the refresh check compares *it* instead. + let unsettled = self.index_unsettled(); + self.viewport.answered_whole(uri, unsettled); self.token_results += 1; let result_id = self.token_results.to_string(); self.tokens.insert(uri.clone(), TokenAnswer { result_id: result_id.clone(), data }); diff --git a/crates/lucisv_server/src/server/startup.rs b/crates/lucisv_server/src/server/startup.rs index 13518fa..5ad69c4 100644 --- a/crates/lucisv_server/src/server/startup.rs +++ b/crates/lucisv_server/src/server/startup.rs @@ -158,6 +158,7 @@ impl Server { hierarchy_revision: 0, tokens: HashMap::new(), token_results: 0, + viewport: Default::default(), indexings: 0, dirty: Vec::new(), queue, diff --git a/crates/lucisv_server/src/server/viewport.rs b/crates/lucisv_server/src/server/viewport.rs new file mode 100644 index 0000000..32860b2 --- /dev/null +++ b/crates/lucisv_server/src/server/viewport.rs @@ -0,0 +1,366 @@ +//! Colours that never wait for the index: the semantic-token requests +//! answered from the buffer alone while a scan holds everything else, and the +//! one `workspace/semanticTokens/refresh` that replaces them once the index +//! has settled (`docs/features/viewport-highlight/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, or the +//! drain between two of a scan's files (`answer_what_is_waiting`), both of +//! which go through `process_batch`. The exemption is taken there, before the +//! request would be held, and runs the ordinary dispatch arm for the method +//! *without* the dirty-buffer flush (`answer_flushed`). Those three arms and +//! the large-file gate in front of them read exactly: +//! +//! * the one `Document` the request names — its text, line index, tokens, +//! tree, `Semantics` and `ExternalResolutions` overlay, all of which are +//! replaced wholesale (`set_document`) or refreshed in place by a publish +//! (`refresh_overlay`) and are never half-written when control is back in +//! the loop; +//! * `Workspace::has_large_documents` and `ClientAbilities::token_server_cancel` +//! (the large-file decline); +//! * `Server::tokens` / `token_results`, the remembered answer the next delta +//! is computed against — the server's own record of what it sent. +//! +//! Never the workspace index, never another buffer, never a flush or a +//! publish. The overlay is the buffer's own copy of the index's answers as of +//! 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. + +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_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; + +#[cfg(test)] +mod tests; + +/// The requests that may be answered ahead of a scan: the three that colour. +const TOKEN_METHODS: [&str; 3] = [ + SemanticTokensRangeRequest::METHOD, + SemanticTokensFullRequest::METHOD, + SemanticTokensFullDeltaRequest::METHOD, +]; + +/// What the exemption owes the client once the index settles. +#[derive(Default)] +pub(super) struct Viewport { + /// Buffers whose last answer was a **range** taken off an unsettled + /// index. A range answer is not remembered, so it cannot be compared with + /// what the settled index says; it is simply owed a refresh. A whole + /// answer for the buffer takes it out again ([`Viewport::answered_whole`]). + guessed: HashSet, + /// Buffers whose last **whole** answer (full or delta) was computed off an + /// unsettled index. Only these, and `guessed`, are re-classified at the + /// next refresh decision: an answer given once the index had settled is + /// what the index said, and re-checking every open buffer on every index + /// change cost 13 ms per save with 200 buffers open (QA Q6). + early: HashSet, + /// The index revision (`Server::hierarchy_revision`) the last refresh + /// decision was taken at. One decision per revision is the coalescing + /// rule: however many publishes a scan made, its settling is one check. + checked_at: u64, + /// 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, + /// The folders a deferred widen will add. + 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, +} + +impl Viewport { + /// Record a widen instead of running it, when an open inside a burst asked + /// for it — reporting whether it was recorded. + pub(super) fn defers_widen(&mut self, added: &[PathBuf]) -> bool { + if !self.defer_widen { + return false; + } + self.owed_widen.get_or_insert_with(Vec::new).extend_from_slice(added); + true + } + + /// A full or delta answer was sent for `uri`, off an index that was or + /// was not `unsettled`: it is remembered, so the refresh check compares + /// it — when it may be stale — instead of assuming it stale. + pub(super) fn answered_whole(&mut self, uri: &Uri, unsettled: bool) { + self.guessed.remove(uri); + match unsettled { + true => self.early.insert(uri.clone()), + false => self.early.remove(uri), + }; + } +} + +/// 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. + /// + /// `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( + &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. + 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. + pub(super) fn index_unsettled(&self) -> bool { + self.scanning || self.staging || self.viewport.widening + } + + /// Ask the client to re-request its semantic tokens, once, when the index + /// has moved since the last decision and some buffer's colours were taken + /// off an index that has since changed. + /// + /// **Never when nothing a token reads has changed.** Each open buffer + /// whose remembered answer was computed off an unsettled index is + /// re-classified and compared with what was sent; a buffer coloured only + /// by a range answer off an unsettled index counts as changed. A buffer + /// answered after the index settled is not re-checked: what it was sent + /// is what the index said, and this check is not a second change-tracker + /// for later edits elsewhere (which never refreshed before this lane). A dirty buffer is skipped — the client asks again + /// after its own edit, and comparing against text it has moved past would + /// say nothing. Silent for a client without `refreshSupport`. + /// + /// **What one refresh costs.** `vscode-languageclient` fires every + /// document-tokens provider's change event, and VS Code re-fetches tokens + /// for every model attached to an editor — a `full/delta` each, which the + /// prefix/suffix trim makes a few edits apiece. + pub(super) fn refresh_tokens_if_stale(&mut self) { + if self.viewport.checked_at == self.hierarchy_revision || self.must_wait() { + return; + } + self.viewport.checked_at = self.hierarchy_revision; + if !self.abilities.semantic_tokens_refresh { + self.viewport.guessed.clear(); + self.viewport.early.clear(); + return; + } + let started = self.timer(); + let stale = self.stale_token_buffers(); + self.viewport.guessed.clear(); + self.viewport.early.clear(); + self.timed(started, |took| { + format!("semantic tokens: {stale} stale buffer(s), checked in {took}") + }); + if stale > 0 { + self.send_request(SemanticTokensRefresh::METHOD, ()); + } + } + + /// How many open buffers the client is showing colours for that the + /// buffer's current analysis would not give. + fn stale_token_buffers(&self) -> usize { + self.workspace + .open_documents() + .filter(|(uri, doc)| { + !doc.large && !self.dirty.iter().any(|(pending, _)| pending == *uri) + }) + .filter(|(uri, doc)| { + self.viewport.guessed.contains(*uri) + || self.viewport.early.contains(*uri) + && self + .tokens + .get(*uri) + .is_some_and(|sent| sent.data != tokens::semantic_tokens(doc)) + }) + .count() + } +} diff --git a/crates/lucisv_server/src/server/viewport/tests.rs b/crates/lucisv_server/src/server/viewport/tests.rs new file mode 100644 index 0000000..9add0b1 --- /dev/null +++ b/crates/lucisv_server/src/server/viewport/tests.rs @@ -0,0 +1,514 @@ +//! The viewport exemption and the refresh behind it, on the wire. +//! +//! Each claim of `viewport.rs` is one test: a colouring request is answered +//! while a scan holds everything else, a request that is not colouring still +//! waits, a buffer whose text is not current waits (dirty, a change held +//! ahead of it, a change still behind the scan's own trigger), a cancel is +//! honoured, a large buffer keeps its decline; and the refresh goes out once +//! per index revision, only when something a token reads has changed, and +//! only to a client that asked for it. The last test is the whole story: a +//! staged cold start coloured at once, then sharpened by the refresh. + +use std::collections::HashSet; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use lsp_server::{Connection, Message, Notification, Request, RequestId, Response}; +use lsp_types::notification::{ + Cancel, DidChangeTextDocument, DidOpenTextDocument, Notification as _, +}; +use lsp_types::request::{ + HoverRequest, Request as _, SemanticTokensFullRequest, SemanticTokensRangeRequest, + SemanticTokensRefresh, +}; +use lsp_types::Uri; +use serde_json::{json, Value}; + +use super::super::startup::Startup; +use super::super::{ClientAbilities, Server}; +use crate::settings::ClientSettings; +use crate::uri::path_to_uri; + +/// A directory of its own, removed when dropped. +struct Tree(PathBuf); + +impl Tree { + fn new(name: &str) -> Tree { + let path = + std::env::temp_dir().join(format!("lucisv_viewport_{}_{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).expect("temp dir"); + Tree(path) + } + + fn write(&self, rel: &str, text: &str) -> PathBuf { + let path = self.0.join(rel); + std::fs::write(&path, text).expect("write"); + path + } +} + +impl Drop for Tree { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A server and the client end of its connection. +struct Lane { + server: Server, + client: Connection, +} + +/// A started session whose startup scan has run, against `abilities`. +fn lane(root: &Path, abilities: ClientAbilities) -> Lane { + let (server_end, client) = Connection::memory(); + let startup = Startup { + abilities, + client: ClientSettings::default(), + storage: None, + verbose: false, + queued: Vec::new(), + wait: Duration::ZERO, + }; + Lane { server: Server::started(server_end, vec![root.to_path_buf()], startup), client } +} + +impl Lane { + /// Everything the server has sent since the last drain. + fn drain(&self) -> Vec { + self.client.receiver.try_iter().collect() + } + + /// The ids of the responses sent since the last drain, in order. + fn answered(&self) -> Vec { + responses(self.drain()).into_iter().map(|r| r.id).collect() + } + + fn open(&mut self, path: &Path, text: &str) -> Uri { + let uri = path_to_uri(path).expect("uri"); + self.server.notification(Notification::new( + DidOpenTextDocument::METHOD.to_string(), + json!({ "textDocument": { + "uri": uri, "languageId": "systemverilog", "version": 1, "text": text, + }}), + )); + uri + } + + /// One burst through the loop body, with a scan pretended to be running + /// — the state every mid-scan drain is in — and nothing settled. + fn burst_mid_scan(&mut self, batch: Vec) { + self.server.scanning = true; + self.server.answering_a_rescan = true; + self.server.process_batch(batch).expect("the burst is handled"); + self.server.scanning = false; + self.server.answering_a_rescan = false; + } + + fn refreshes(&self) -> usize { + self.drain() + .iter() + .filter( + |m| matches!(m, Message::Request(r) if r.method == SemanticTokensRefresh::METHOD), + ) + .count() + } +} + +fn responses(messages: Vec) -> Vec { + messages + .into_iter() + .filter_map(|m| match m { + Message::Response(response) => Some(response), + _ => None, + }) + .collect() +} + +fn request(id: &str, method: &str, params: Value) -> Message { + Message::Request(Request::new(RequestId::from(id.to_string()), method.to_string(), params)) +} + +fn full(id: &str, uri: &Uri) -> Message { + request(id, SemanticTokensFullRequest::METHOD, json!({ "textDocument": { "uri": uri } })) +} + +fn range(id: &str, uri: &Uri) -> Message { + request( + id, + SemanticTokensRangeRequest::METHOD, + json!({ "textDocument": { "uri": uri }, "range": { + "start": { "line": 0, "character": 0 }, "end": { "line": 60, "character": 0 }, + }}), + ) +} + +fn hover(id: &str, uri: &Uri) -> Message { + request( + id, + HoverRequest::METHOD, + json!({ "textDocument": { "uri": uri }, "position": { "line": 0, "character": 8 } }), + ) +} + +fn changed(uri: &Uri, text: &str) -> Message { + Message::Notification(Notification::new( + DidChangeTextDocument::METHOD.to_string(), + json!({ "textDocument": { "uri": uri, "version": 2 }, "contentChanges": [{ "text": text }] }), + )) +} + +fn cancel(id: &str) -> Message { + Message::Notification(Notification::new(Cancel::METHOD.to_string(), json!({ "id": id }))) +} + +fn id(text: &str) -> RequestId { + RequestId::from(text.to_string()) +} + +/// A client that accepts `workspace/semanticTokens/refresh`, as VS Code does. +fn refreshing() -> ClientAbilities { + ClientAbilities { semantic_tokens_refresh: true, ..Default::default() } +} + +const MODULE: &str = "module m;\n localparam W = 8;\n wire [W-1:0] a;\nendmodule\n"; + +/// A lane with `m.sv` open and the client end drained. +fn opened(name: &str, abilities: ClientAbilities) -> (Tree, Lane, Uri) { + let tree = Tree::new(name); + let path = tree.write("m.sv", MODULE); + let mut lane = lane(&tree.0, abilities); + let uri = lane.open(&path, MODULE); + // What `run` does before it takes its first message: the refresh decision + // for the index the startup built. + lane.server.refresh_tokens_if_stale(); + lane.drain(); + (tree, lane, uri) +} + +#[test] +fn colouring_requests_are_answered_while_a_hover_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"); + 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)]); + let early = responses(lane.drain()); + lane.server.held.clear(); + lane.server.process_batch(vec![full("f2", &uri), range("r2", &uri)]).expect("burst"); + let late = responses(lane.drain()); + let data = |r: &Response| r.response_result.as_ref().expect("ok")["data"].clone(); + assert_eq!(data(&early[0]), data(&late[0]), "full"); + assert_eq!(data(&early[1]), data(&late[1]), "range"); +} + +#[test] +fn a_dirty_buffer_is_not_answered_from_text_the_client_has_moved_past() { + let (_tree, mut lane, uri) = opened("dirty", ClientAbilities::default()); + lane.burst_mid_scan(vec![changed(&uri, "module m2;\nendmodule\n"), range("r", &uri)]); + assert!(lane.answered().is_empty(), "held until the change is analyzed"); + assert_eq!(lane.server.held.len(), 1); +} + +#[test] +fn a_change_held_ahead_of_the_request_holds_it_too_but_not_another_buffers() { + let (tree, mut lane, uri) = opened("held", ClientAbilities::default()); + let other_path = tree.write("n.sv", "module n;\nendmodule\n"); + let other = lane.open(&other_path, "module n;\nendmodule\n"); + lane.drain(); + lane.burst_mid_scan(vec![ + hover("h", &uri), + changed(&uri, "module m3;\nendmodule\n"), + range("mine", &uri), + range("theirs", &other), + ]); + assert_eq!(lane.answered(), vec![id("theirs")], "only the untouched buffer colours"); +} + +#[test] +fn a_change_still_behind_the_scans_own_trigger_holds_the_request() { + let (_tree, mut lane, uri) = opened("behind", ClientAbilities::default()); + lane.server.staging = true; + // A scan started by a notification whose burst still has one + // unapplied notification behind it (`Server::behind`). + lane.server.behind = 1; + let Message::Request(r) = range("r", &uri) else { unreachable!() }; + let mut none = HashSet::new(); + assert!(lane.server.answer_from_the_buffer(&r, &[], &mut none).is_none(), "owed the change"); + lane.server.behind = 0; + assert!(lane.server.answer_from_the_buffer(&r, &[], &mut none).is_some(), "nothing owed"); +} + +#[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")]); + let answers = responses(lane.drain()); + assert_eq!(answers.len(), 1); + let error = answers[0].response_result.as_ref().expect_err("cancelled"); + assert_eq!(error.code, lsp_server::ErrorCode::RequestCanceled as i32); +} + +#[test] +fn a_large_buffer_keeps_its_decline_and_its_lexed_window() { + let (tree, mut lane, _) = opened("large", refreshing()); + let settings = ClientSettings { large_file_threshold: 16, ..Default::default() }; + let _ = lane.server.workspace.set_client_settings(settings); + let path = tree.0.join("big.sv"); + 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)]); + let answers = responses(lane.drain()); + assert_eq!(answers.len(), 2); + assert!(answers[0].response_result.is_err(), "full is declined, as always"); + let data = &answers[1].response_result.as_ref().expect("a window")["data"]; + assert!(!data.as_array().expect("data").is_empty()); +} + +#[test] +fn no_refresh_when_nothing_a_token_reads_has_changed() { + let abilities = ClientAbilities { semantic_tokens_refresh: true, ..Default::default() }; + let (_tree, mut lane, uri) = opened("quiet", abilities); + lane.burst_mid_scan(vec![full("f", &uri)]); + lane.drain(); + lane.server.hierarchy_revision += 1; + lane.server.refresh_tokens_if_stale(); + assert_eq!(lane.refreshes(), 0, "what was sent is what the index says"); +} + +#[test] +fn one_refresh_per_index_revision_when_what_was_sent_is_stale() { + let abilities = ClientAbilities { semantic_tokens_refresh: true, ..Default::default() }; + let (_tree, mut lane, uri) = opened("stale", abilities); + lane.burst_mid_scan(vec![full("f", &uri)]); + lane.drain(); + // What the client holds, made different from what the buffer says. + lane.server.tokens.get_mut(&uri).expect("remembered").data.pop(); + lane.server.refresh_tokens_if_stale(); + assert_eq!(lane.refreshes(), 0, "the index has not moved since the last decision"); + lane.server.hierarchy_revision += 1; + lane.server.refresh_tokens_if_stale(); + lane.server.refresh_tokens_if_stale(); + assert_eq!(lane.refreshes(), 1, "coalesced to one"); +} + +#[test] +fn an_answer_given_once_the_index_had_settled_is_not_checked_again() { + let (_tree, mut lane, uri) = opened("settled", refreshing()); + lane.server.process_batch(vec![full("f", &uri)]).expect("burst"); + lane.drain(); + lane.server.tokens.get_mut(&uri).expect("remembered").data.pop(); + lane.server.hierarchy_revision += 1; + lane.server.refresh_tokens_if_stale(); + assert_eq!(lane.refreshes(), 0, "only answers taken off an unsettled index are owed one"); +} + +#[test] +fn a_guessed_range_is_refreshed_and_a_client_that_cannot_be_asked_is_not() { + for (refresh_support, expected) in [(true, 1), (false, 0)] { + 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.server.held.clear(); + lane.drain(); + lane.server.hierarchy_revision += 1; + lane.server.refresh_tokens_if_stale(); + assert_eq!(lane.refreshes(), expected, "refreshSupport={refresh_support}"); + assert!(lane.server.viewport.guessed.is_empty(), "the debt is paid either way"); + } +} + +#[test] +fn a_dirty_buffer_is_left_to_the_clients_own_next_request() { + let abilities = ClientAbilities { semantic_tokens_refresh: true, ..Default::default() }; + let (_tree, mut lane, uri) = opened("dirtyrefresh", abilities); + lane.burst_mid_scan(vec![full("f", &uri)]); + lane.server.tokens.get_mut(&uri).expect("remembered").data.pop(); + lane.server.mark_dirty(uri.clone(), "module z;\nendmodule\n".to_string()); + lane.drain(); + lane.server.hierarchy_revision += 1; + lane.server.refresh_tokens_if_stale(); + assert_eq!(lane.refreshes(), 0); +} + +/// The whole story, through a real staged startup: the buffer is opened and +/// coloured before the settings answer lands — so before anything is +/// indexed — with the package's type name a plain `variable`; once the scan +/// has run, one refresh goes out and the next answer says `type`. +#[test] +fn a_cold_start_is_coloured_at_once_and_sharpened_by_one_refresh() { + let tree = Tree::new("story"); + tree.write("p.sv", "package p;\n typedef logic [3:0] nib_t;\nendpackage\n"); + let text = "module m;\n p::nib_t a;\nendmodule\n"; + let path = tree.write("m.sv", text); + let uri = path_to_uri(&path).expect("uri"); + let opened = Message::Notification(Notification::new( + DidOpenTextDocument::METHOD.to_string(), + json!({ "textDocument": { + "uri": uri, "languageId": "systemverilog", "version": 1, "text": text, + }}), + )); + let (server_end, client) = Connection::memory(); + let abilities = ClientAbilities { + configuration: true, + semantic_tokens_refresh: true, + ..Default::default() + }; + let startup = Startup { + abilities, + client: ClientSettings::default(), + storage: None, + verbose: false, + queued: vec![opened, hover("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), + }; + 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:?}"); + let nib = |answer: &Value| -> u64 { + // `p` `::` `nib_t` on line 1: the second identifier token of the line. + let data: Vec = + answer["data"].as_array().expect("data").iter().filter_map(Value::as_u64).collect(); + let (mut line, mut col) = (0, 0); + for t in data.chunks(5) { + line += t[0]; + col = if t[0] == 0 { col + t[1] } else { t[1] }; + if line == 1 && col == 5 { + return t[3]; + } + } + panic!("no token at 1:5 in {data:?}"); + }; + let before = nib(answers[0].response_result.as_ref().expect("ok")); + assert_eq!( + before, + 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 + // 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"); + 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"); + let after = responses(lane.drain()); + let sharpened = nib(after[0].response_result.as_ref().expect("ok")); + assert_eq!( + sharpened, + crate::tokens::token_types().iter().position(|t| t.as_str() == "type").expect("legend") + as u64 + ); +} + +#[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)]); + 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"); +} + +/// Two blocks two folders apart, so that opening the second widens the +/// default folder scope; the second uses a package only its own block holds. +fn two_blocks(name: &str) -> (Tree, PathBuf, PathBuf) { + let tree = Tree::new(name); + for dir in ["a/b/c", "x/y/z", "x/y/pk"] { + std::fs::create_dir_all(tree.0.join(dir)).expect("dirs"); + } + let first = tree.write("a/b/c/m.sv", MODULE); + tree.write("x/y/pk/p.sv", "package p;\n typedef logic [3:0] nib_t;\nendpackage\n"); + let second = tree.write("x/y/z/n.sv", USES_P); + (tree, first, second) +} + +const USES_P: &str = "module n;\n p::nib_t a;\nendmodule\n"; + +fn opening(uri: &Uri, text: &str) -> Message { + Message::Notification(Notification::new( + DidOpenTextDocument::METHOD.to_string(), + json!({ "textDocument": { + "uri": uri, "languageId": "systemverilog", "version": 1, "text": text, + }}), + )) +} + +/// Where in what the server sent the first diagnostics publish for `uri` is. +fn first_publish(sent: &[Message], uri: &Uri) -> usize { + sent.iter() + .position(|m| { + matches!(m, Message::Notification(n) + if n.method == "textDocument/publishDiagnostics" && n.params["uri"] == json!(uri)) + }) + .expect("the widen publishes the new buffer") +} + +#[test] +fn the_full_in_the_same_burst_as_a_widening_open_colours_before_the_widen() { + let (_tree, first, second) = two_blocks("widen"); + let mut lane = lane(&_tree.0, refreshing()); + lane.open(&first, MODULE); + lane.server.refresh_tokens_if_stale(); + lane.drain(); + 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)]) + .expect("burst"); + assert!(lane.server.workspace.index().files().len() > indexed, "premise: it widened"); + let sent = lane.drain(); + let order: Vec = responses(sent.clone()).into_iter().map(|r| r.id).collect(); + assert_eq!(order, vec![id("f"), id("h")]); + let coloured = sent + .iter() + .position(|m| matches!(m, Message::Response(r) if r.id == id("f"))) + .expect("the full"); + assert!(coloured < first_publish(&sent, &uri), "coloured before the widen finished"); + // The early answer could not see the package; the widen could, so the + // index revision it made is owed exactly one refresh. + lane.server.refresh_tokens_if_stale(); + assert_eq!(lane.refreshes(), 1); +} + +#[test] +fn colours_arriving_during_a_widen_are_answered_and_the_rest_waits_in_order() { + let (_tree, first, second) = two_blocks("midwiden"); + let mut lane = lane(&_tree.0, refreshing()); + let first_uri = lane.open(&first, MODULE); + lane.drain(); + 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)] { + 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"); + let held: Vec<&str> = lane + .server + .held + .iter() + .filter_map(|m| match m { + Message::Request(r) => Some(r.method.as_str()), + _ => None, + }) + .collect(); + assert_eq!(held, vec![HoverRequest::METHOD]); + assert!(lane.server.viewport.guessed.contains(&first_uri), "a range off a widening index"); +} diff --git a/crates/lucisv_server/src/tokens.rs b/crates/lucisv_server/src/tokens.rs index 70c5912..db1cd8c 100644 --- a/crates/lucisv_server/src/tokens.rs +++ b/crates/lucisv_server/src/tokens.rs @@ -21,9 +21,13 @@ use vlog_parser::token::{Token, TokenKind}; use vlog_parser::TextRange; use vlog_semantic::{Definition, ExternalResolutions, Semantics, SymbolKind}; -use crate::state::Document; +use crate::state::{first_token_from, first_token_reaching, Document}; mod instantiation; +#[cfg(test)] +mod viewport_sweep; +#[cfg(test)] +mod window_tests; /// The legend the server advertises. The index into this array is what the /// wire format carries, so the order is part of the protocol contract and @@ -123,8 +127,41 @@ pub fn semantic_tokens(doc: &Document) -> Vec { /// exactly as a full answer's does, and only the tokens outside the range are /// missing. A token that merely overlaps the range is kept whole — the client /// asked which tokens to draw, not where to cut them. +/// +/// **Costs the window, not the file** (`docs/features/viewport-highlight`): +/// only the tokens on the lines the range touches are classified, and only the +/// items overlapping those lines are walked for instantiation overrides. The +/// answer is still exactly the full answer filtered to the range — the same +/// pieces from the same tokens through the same `within` — which the tests +/// below hold it to over the corpus. pub fn semantic_tokens_in_range(doc: &Document, range: Range) -> Vec { - encode(&within(absolute(doc), range)) + if range.start >= range.end { + return Vec::new(); + } + let (start, end) = crate::large::line_window(&doc.line_index, doc.text.len() as u32, range); + let tokens = window_tokens(&doc.tokens, start, end); + let Some((first, last)) = tokens.first().zip(tokens.last()) else { return Vec::new() }; + let reach = TextRange::new(start.min(first.span.start), end.max(last.span.end)); + let overrides = instantiation::overrides_within(doc, Some(reach)); + let mut pieces = Vec::new(); + for token in tokens { + collect(token, doc, &overrides, &mut pieces); + } + encode(&within(flatten(pieces, doc), range)) +} + +/// The tokens whose pieces can reach the bytes `start..end`: every token +/// touching the window, plus one on either side of it. +/// +/// The neighbours are for their comments. A comment is trivia on the token +/// after it (or, trailing, on the token before it), so the block comment that +/// opens the window may hang off a token above it and the one that closes it +/// off a token below — the EOF token included. One each is enough: trivia +/// only ever sits between a token and its immediate neighbour. +fn window_tokens(tokens: &[Token], start: u32, end: u32) -> &[Token] { + let from = first_token_reaching(tokens, start).saturating_sub(1); + let to = (first_token_from(tokens, end) + 1).min(tokens.len()); + tokens.get(from..to.max(from)).unwrap_or(&[]) } /// The tokens a range covers of a buffer nothing has lexed — the large-file diff --git a/crates/lucisv_server/src/tokens/instantiation.rs b/crates/lucisv_server/src/tokens/instantiation.rs index 42572ce..edd1616 100644 --- a/crates/lucisv_server/src/tokens/instantiation.rs +++ b/crates/lucisv_server/src/tokens/instantiation.rs @@ -24,6 +24,22 @@ use crate::state::{first_token_from, Document}; /// Token-start byte offset -> highlight overrides derived from `doc.tree`. pub(super) fn overrides(doc: &Document) -> HashMap { + overrides_within(doc, None) +} + +/// [`overrides`] for the items that overlap `window` only, or for every item +/// when there is none — what a viewport's range answer walks, so its cost is +/// the items on screen and not the file's. +/// +/// Exact for every token inside the window: each override this walk makes +/// lands inside the span of the item that makes it, so an item that does not +/// overlap the window has nothing to say about a token in it. The items that +/// enclose the window (a module, a package, a generate region) are still +/// entered, and only their children are filtered. +pub(super) fn overrides_within( + doc: &Document, + window: Option, +) -> HashMap { let mut out = HashMap::new(); if doc.tokens.is_empty() { return out; @@ -32,6 +48,7 @@ pub(super) fn overrides(doc: &Document) -> HashMap { tokens: &doc.tokens, semantics: &doc.semantics, external: &doc.external, + window, out: &mut out, }; ctx.items(&doc.tree.items); @@ -42,13 +59,19 @@ struct Ctx<'a> { tokens: &'a [Token], semantics: &'a Semantics, external: &'a ExternalResolutions, + /// The byte range whose tokens are wanted, or `None` for all of them. + window: Option, out: &'a mut HashMap, } impl<'a> Ctx<'a> { fn items(&mut self, items: &[Item]) { for item in items { - self.item(item); + let wanted = + self.window.is_none_or(|w| item.span.start < w.end && w.start < item.span.end); + if wanted { + self.item(item); + } } } diff --git a/crates/lucisv_server/src/tokens/viewport_sweep.rs b/crates/lucisv_server/src/tokens/viewport_sweep.rs new file mode 100644 index 0000000..3b4b527 --- /dev/null +++ b/crates/lucisv_server/src/tokens/viewport_sweep.rs @@ -0,0 +1,256 @@ +//! The real-code proof for the viewport answer +//! (`docs/features/viewport-highlight/README.md`): over every corpus file and +//! a sample of OpenTitan, several windows per file, the **local** range answer +//! — a buffer analyzed against an *empty* index, which is what a cold start +//! colours off — is checked for validity and compared with the **accurate** +//! full answer — the same text analyzed against the index of its whole tree — +//! restricted to the window. +//! +//! `#[ignore]`: it indexes two trees and parses several thousand files. Run +//! with `tools/guard.sh -- cargo test --release -p lucisv_server +//! viewport_sweep -- --ignored --nocapture`. The trees are +//! `LUCISV_CORPUS` (default `~/.cache/lucisv-corpus`) and `LUCISV_OPENTITAN_HW` +//! (default `~/.cache/lucisv-opentitan-full/hw`); a missing one is skipped +//! with a line on stderr. + +use std::path::{Path, PathBuf}; + +use lsp_types::{Position, Range, SemanticToken}; +use vlog_parser::token::TokenKind; +use vlog_parser::TextRange; +use vlog_semantic::{Definition, WorkspaceIndex}; + +use super::{semantic_tokens, semantic_tokens_in_range, semantic_tokens_in_window, within}; +use super::{Absolute, Highlight}; +use crate::state::{Document, Workspace}; + +/// A tree from `var`, else `default` under `$HOME`, when it is there. +fn tree(var: &str, default: &str) -> Option { + let root = std::env::var_os(var) + .map(PathBuf::from) + .or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(default)))?; + if !root.is_dir() { + eprintln!("{} not there — skipping", root.display()); + } + root.is_dir().then_some(root) +} + +/// Every Verilog source under `dir`, sorted so a run is reproducible. +fn sources(dir: &Path, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + let mut entries: Vec = entries.flatten().map(|e| e.path()).collect(); + entries.sort(); + for path in entries { + if path.is_dir() { + sources(&path, out); + } else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "svh" | "v")) { + out.push(path); + } + } +} + +/// Decoded tokens, absolute: (line, start, length, type, modifiers). +fn decode(data: &[SemanticToken]) -> Vec { + let (mut line, mut start) = (0u32, 0u32); + data.iter() + .map(|t| { + line += t.delta_line; + start = if t.delta_line == 0 { start + t.delta_start } else { t.delta_start }; + Absolute { + line, + start, + length: t.length, + ty: t.token_type, + modifiers: t.token_modifiers_bitset, + } + }) + .collect() +} + +/// The comment and string spans of the whole file, from its own lex — the +/// truth a window answer must never colour across. +fn trivia(doc: &Document) -> (Vec, Vec) { + let mut comments = Vec::new(); + let mut strings = Vec::new(); + for token in &doc.tokens { + comments.extend(token.leading.iter().map(|c| c.span)); + comments.extend(token.trailing.iter().map(|c| c.span)); + if token.kind == TokenKind::String { + strings.push(token.span); + } + } + comments.sort_by_key(|s| s.start); + (comments, strings) +} + +/// Whether `span` lies inside one of `spans` (sorted by start). +fn inside(spans: &[TextRange], span: TextRange) -> bool { + let at = spans.partition_point(|s| s.start <= span.start); + at > 0 && spans[at - 1].end >= span.end && spans[at - 1].end > span.start +} + +/// Every validity rule of a range answer; returns a description of the first +/// one broken. +fn invalid(doc: &Document, data: &[SemanticToken], range: Range) -> Option { + let tokens = decode(data); + let positions = doc.positions(); + let (comments, strings) = trivia(doc); + for pair in tokens.windows(2) { + let (a, b) = (pair[0], pair[1]); + if (a.line, a.start + a.length) > (b.line, b.start) { + return Some(format!("out of order or overlapping: {a:?} then {b:?}")); + } + } + for t in &tokens { + if t.length == 0 || !(t.from() < range.end && range.start < t.to()) { + return Some(format!("empty or outside the range: {t:?}")); + } + let start = positions.offset(t.from()); + let end = positions.offset(t.to()); + if positions.position(end) != t.to() + || doc.text[start as usize..end as usize].contains('\n') + { + return Some(format!("past the end of its line: {t:?}")); + } + let span = TextRange::new(start, end); + if t.ty != Highlight::Comment as u32 && inside(&comments, span) { + return Some(format!("code colour inside a comment: {t:?}")); + } + if t.ty != Highlight::String as u32 + && strings.iter().any(|s| s.start <= start && end <= s.end) + { + return Some(format!("non-string colour inside a string: {t:?}")); + } + } + None +} + +/// How the local answer and the accurate one compare on one window. +#[derive(Default)] +struct Tally { + files: usize, + windows: usize, + agree: usize, + index_resolved: usize, + other: usize, + examples: Vec, +} + +impl Tally { + /// Compare token by token, keyed by position. A token both answers carry + /// with the same class agrees; a disagreement is **index-resolved** when + /// the accurate buffer resolves that name through the index — almost + /// always to another file, though an inherited method can resolve to + /// this one — and "other" otherwise, the class that must stay empty. + fn compare(&mut self, accurate: &Document, local: &[Absolute], truth: &[Absolute]) { + let positions = accurate.positions(); + let mut local = local.iter().peekable(); + for t in truth { + while local.next_if(|l| (l.line, l.start) < (t.line, t.start)).is_some() { + self.other += 1; + } + let found = local.next_if(|l| (l.line, l.start) == (t.line, t.start)); + if found.is_some_and(|l| l == t) { + self.agree += 1; + continue; + } + let offset = positions.offset(t.from()); + let external = matches!( + accurate.external.definition_of(&accurate.semantics, offset), + Some(Definition::External(_)) + ); + match external { + true => self.index_resolved += 1, + false => { + self.other += 1; + if self.examples.len() < 12 { + let text = &accurate.text[offset as usize..]; + let word: String = text.chars().take(24).collect(); + self.examples.push(format!("{t:?} local={found:?} at {word:?}")); + } + } + } + } + self.other += local.count(); + } +} + +/// Windows over a file of `lines` lines: whole-line viewports of 60 lines at +/// a few deterministic starts, plus one that starts and ends mid-line. +fn windows(lines: u32, seed: u64) -> Vec { + let at = |line: u32, character: u32| Position { line, character }; + let mut out = vec![Range { start: at(0, 0), end: at(60, 0) }]; + let mut x = seed | 1; + for _ in 0..4 { + x = x.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + let from = ((x >> 33) % u64::from(lines.max(1))) as u32; + out.push(Range { start: at(from, 0), end: at(from + 60, 0) }); + } + out.push(Range { start: at(lines / 2, 7), end: at(lines / 2 + 20, 3) }); + out +} + +/// One tree: index it whole, then sweep `files` of it. +fn sweep(root: &Path, every: usize, tally: &mut Tally) { + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![root.to_path_buf()]); + let mut files = Vec::new(); + sources(root, &mut files); + let empty = WorkspaceIndex::default(); + for (n, path) in files.iter().enumerate().filter(|(n, _)| n % every == 0) { + let Ok(text) = std::fs::read_to_string(path) else { continue }; + let local = Document::new(Some(path.clone()), text.clone(), &empty); + let accurate = Document::new(Some(path.clone()), text.clone(), ws.index()); + let fast = Document::large(Some(path.clone()), text); + let local_full = super::absolute(&local); + let truth_full = decode(&semantic_tokens(&accurate)); + tally.files += 1; + for range in windows(local.line_index.line_count(), n as u64) { + let answer = semantic_tokens_in_range(&local, range); + if let Some(problem) = invalid(&local, &answer, range) { + panic!("{}: {range:?}: {problem}", path.display()); + } + let lexed = semantic_tokens_in_window(&fast, range); + if let Some(problem) = invalid(&local, &lexed, range) { + panic!("{}: fast path {range:?}: {problem}", path.display()); + } + // The window is exact: it is the full answer filtered, always. + let local_window = decode(&answer); + assert_eq!( + local_window, + within(local_full.clone(), range), + "{}: {range:?}: the window disagrees with the full answer filtered", + path.display() + ); + let truth = within(truth_full.clone(), range); + tally.compare(&accurate, &local_window, &truth); + tally.windows += 1; + } + } +} + +#[test] +#[ignore = "indexes the corpus and OpenTitan; run with --release --ignored --nocapture"] +fn viewport_sweep_local_answers_are_valid_and_agree_with_the_accurate_ones() { + let mut tally = Tally::default(); + if let Some(corpus) = tree("LUCISV_CORPUS", ".cache/lucisv-corpus") { + sweep(&corpus, 1, &mut tally); + } + if let Some(hw) = tree("LUCISV_OPENTITAN_HW", ".cache/lucisv-opentitan-full/hw") { + sweep(&hw, 10, &mut tally); + } + let compared = tally.agree + tally.index_resolved + tally.other; + eprintln!( + "viewport sweep: {} files, {} windows, {compared} accurate tokens: {} agree ({:.3}%), \ + {} index-resolved, {} other", + tally.files, + tally.windows, + tally.agree, + 100.0 * tally.agree as f64 / compared.max(1) as f64, + tally.index_resolved, + tally.other + ); + for example in &tally.examples { + eprintln!(" other: {example}"); + } +} diff --git a/crates/lucisv_server/src/tokens/window_tests.rs b/crates/lucisv_server/src/tokens/window_tests.rs new file mode 100644 index 0000000..6c3e38e --- /dev/null +++ b/crates/lucisv_server/src/tokens/window_tests.rs @@ -0,0 +1,120 @@ +//! The range answer's window (`semantic_tokens_in_range`): the shapes where +//! selecting a window's tokens could lose a piece the full answer has — a +//! comment hanging off a token outside the window — and the claim that its +//! cost is the window's and not the file's. + +use std::time::{Duration, Instant}; + +use lsp_types::{Position, Range}; +use vlog_semantic::WorkspaceIndex; + +use super::{absolute, semantic_tokens_in_range, within, Absolute}; +use crate::state::Document; + +fn doc(text: &str) -> Document { + Document::new(None, text.to_string(), &WorkspaceIndex::default()) +} + +fn range(from: (u32, u32), to: (u32, u32)) -> Range { + Range { + start: Position { line: from.0, character: from.1 }, + end: Position { line: to.0, character: to.1 }, + } +} + +/// Decoded, for comparing with `within(absolute(..))`. +fn decoded(doc: &Document, range: Range) -> Vec { + let (mut line, mut start) = (0u32, 0u32); + semantic_tokens_in_range(doc, range) + .iter() + .map(|t| { + line += t.delta_line; + start = if t.delta_line == 0 { start + t.delta_start } else { t.delta_start }; + Absolute { + line, + start, + length: t.length, + ty: t.token_type, + modifiers: t.token_modifiers_bitset, + } + }) + .collect() +} + +/// The window's answer is the full answer filtered, at every whole-line +/// window and a few mid-line ones. +#[track_caller] +fn exact_everywhere(text: &str) { + let doc = doc(text); + let lines = doc.line_index.line_count(); + let full = absolute(&doc); + for from in 0..=lines { + for to in from..=lines + 1 { + for r in [range((from, 0), (to, 0)), range((from, 3), (to, 2))] { + assert_eq!(decoded(&doc, r), within(full.clone(), r), "{r:?} of {text:?}"); + } + } + } +} + +#[test] +fn a_block_comment_trailing_a_token_above_the_window_is_still_coloured() { + exact_everywhere("wire a; /* opens here\n still a comment\n */ wire b;\nwire c;\n"); +} + +#[test] +fn a_comment_leading_a_token_below_the_window_is_still_coloured() { + exact_everywhere("wire a;\n// a line comment\n/* a block\n comment */\nwire b;\n"); +} + +#[test] +fn a_comment_riding_the_end_of_file_token_is_still_coloured() { + exact_everywhere("module m;\nendmodule\n// the last word\n/* and a\n block */\n"); +} + +#[test] +fn instantiations_continued_defines_and_wide_characters_window_exactly() { + exact_everywhere( + "`define FF(q, d) \\\n always_ff @(posedge clk) q <= d;\nmodule top;\n \ + sub #(.W(8)) u0 (\n .a(x), // é 🎉\n .*\n );\nendmodule\n", + ); +} + +#[test] +fn a_buffer_that_does_not_lex_and_an_empty_one_answer_nothing_without_panicking() { + for text in ["module m; /* unterminated\n wire a;\n", "", "\n\n\n"] { + let doc = doc(text); + for r in [range((0, 0), (99, 0)), range((5, 0), (2, 0)), range((1, 1), (1, 1))] { + assert!(semantic_tokens_in_range(&doc, r).is_empty(), "{r:?} of {text:?}"); + } + } +} + +/// **The cost claim.** The same 60-line viewport of buffers 8x apart in size: +/// a window that classified the file would cost ~8x at the largest, a window +/// that classifies the window costs about the same at every size. Asserted +/// on the shape, fastest of five, with a slack of 3x — the same shape check +/// `large.rs`'s linear-time gates use, for the same reason (a shared machine +/// and a debug build move the absolute numbers, not the ratio). +#[test] +fn a_viewport_costs_the_window_not_the_file() { + let block = "module m;\n localparam W = 8;\n logic [W-1:0] q;\n \ + sub #(.W(W)) u (.clk_i(clk), .q_o(q)); // tail\nendmodule\n"; + let sizes = [500usize, 4000]; + let docs: Vec = sizes.iter().map(|&n| doc(&block.repeat(n))).collect(); + let viewport = range((1000, 0), (1060, 0)); + let mut fastest = [Duration::MAX; 2]; + for _ in 0..5 { + for (best, doc) in fastest.iter_mut().zip(&docs) { + let clock = Instant::now(); + assert!(!semantic_tokens_in_range(doc, viewport).is_empty()); + *best = (*best).min(clock.elapsed()); + } + } + let growth = fastest[1].as_secs_f64() / fastest[0].as_secs_f64().max(f64::MIN_POSITIVE); + eprintln!( + "60-line viewport: {:?} (500 modules) vs {:?} (4000 modules)", + fastest[0], fastest[1] + ); + assert!(growth < 3.0, "8x the file cost {growth:.1}x the viewport: {fastest:?}"); +} diff --git a/docs/features/viewport-highlight/README.md b/docs/features/viewport-highlight/README.md new file mode 100644 index 0000000..d7f0c06 --- /dev/null +++ b/docs/features/viewport-highlight/README.md @@ -0,0 +1,827 @@ +# viewport-highlight + +## Goal + +Semantic highlighting must never wait for the workspace index. The owner's +words: *"Syntax highlight should always be running a localized-only version on +the viewport if possible. This highlight might not be 100% correct, but can be +later fixed. I don't want to wait for the whole database to be indexed before +the basic syntax highlight works."* So: a semantic-token request (`range`, +`full`, `full/delta`) for a buffer whose text is current is answered **from +that buffer alone, immediately**, even while a scan holds every other request; +a range answer costs the window, not the file; and when the index settles in a +way that changes what a buffer's colours would be, the server sends **one** +`workspace/semanticTokens/refresh` so the client re-requests and gets the +accurate answer. + +## Measured first (2026-11-19, before any code) + +Real binary (`target/release/lucisv-server --stdio --verbose`, 0.65.5 at +`80017a5`) over LSP stdio against the full OpenTitan checkout +(`~/.cache/lucisv-opentitan-full`, 4 058 indexable files under `hw/`), replaying +what VS Code does on open: `initialize` (VS Code's capabilities: configuration, +work-done progress, `semanticTokens` range + full/delta, `refreshSupport`), +`initialized`, the settings answer, `didOpen`, then at once +`semanticTokens/full`, `documentSymbol`, `foldingRange`, `codeLens`, and +100 ms later (the viewport contribution's debounce) `semanticTokens/range` for +lines 0–120 and `inlayHint`. Cold = empty `storagePath`, warm = the same store +reused. Medians of 5 runs; the machine is shared with other lanes. Time from +`didOpen`; "first colour" is the earlier of the full and range answers. + +| scope | file | cold first colour | warm first colour | mid-session rescan: tokens held | +|---|---|---|---|---| +| workspace | `spi_device_reg_top.sv` (545 KB) | **679 ms** | 400 ms | 650 ms | +| workspace | `aes_cipher_core.sv` (small) | **677 ms** | 365 ms | 646 ms | +| folder (default) | `spi_device_reg_top.sv` | 55 ms | 84 ms | 263 ms | +| folder (default) | `aes_cipher_core.sv` | 24 ms | 50 ms | 245 ms | + +**Where the time goes** (verbose trace of a cold workspace run): configuration +round trip 1 ms; `didOpen` 1–16 ms (the buffer's own parse); discovery walk +78 ms; then **every request is HELD** (`head_owed`) until the user's +neighbourhood is indexed at ~650 ms, while the scan runs on to 1.6 s. Building +the tokens themselves costs **0.3 ms** (small file) and **6.5 ms** (545 KB) — +the token build was never the problem; waiting was. The range request was a +whole-file build plus a filter (5.7 ms for 545 KB). The mid-session rescan (a +watched-file *create* for a file the index does not hold, so a whole rescan) +holds `full/delta` and `range` for its whole length. + +**Stale forever.** The held `full` was answered off the head prefix and never +refreshed: in folder scope **2 745 tokens** of `spi_device_reg_top.sv` +(26 in workspace scope) stayed different from what the settled index says +until the user edited the file. + +**A `didOpen` that widens the scope** (folder scope, `aes_cipher_core.sv` +open, then `hw/top_earlgrey/rtl/autogen/top_earlgrey.sv`): the new file's +`full` waits for the whole widen, **336 ms** — `reindex_widened` drains +nothing. + +### 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/.../workbench.desktop.main.js`) and +`vscode-languageclient@9.0.1` (`lib/common/semanticTokens.js`, unpkg): + +1. **The range provider is asked only while the document has no complete + tokens.** `ViewportSemanticTokensContribution._tokenizeViewportNow` returns + at once on `model.tokenization.hasCompleteSemanticTokens()`; any answer of + the full provider (data, null, an empty delta) marks the model complete + (`setSemanticTokens(…, true)`); an error does not. So range is only the + *first paint*, until the first full answer lands. +2. **Both are asked at open.** The document feature schedules its first + fetch at `0` ms; the viewport contribution debounces 100–500 ms + (adaptive) and asks for `getVisibleRangesPlusViewportAboveBelow()`. It + re-asks on scroll, content change and on a range provider's `onDidChange`. +3. **Only one full request in flight per model**; edits made while it is + pending are applied to its result when it lands, and then it re-fetches. + The result is therefore assumed to be for the text at *request* time. The + range result is dropped outright if the model's version moved. +4. **Debounce adapts to response time** (300 ms min, 2 s max for the full + provider): a request held for seconds slows every later re-fetch of that + model. +5. **Refresh** (`workspace/semanticTokens/refresh`): the language client + fires the shared `onDidChangeSemanticTokens` emitter of the **document** + provider; the range provider gets no `onDidChange`. VS Code then re-fetches + full/delta for every model attached to an editor (`handleProviderDidChange` + → `schedule(0)`, or after the in-flight request if one is pending). +6. **Capabilities** `vscode-languageclient` advertises: `requests: { range: + true, full: { delta: true } }`, `multilineTokenSupport: false`, + `overlappingTokenSupport: false`, `serverCancelSupport: true`, + `augmentsSyntaxTokens: true`, and `workspace.semanticTokens.refreshSupport: + true`. It registers both providers whenever the server advertises both. **No + extension configuration is needed** — `editors/vscode/extension.js` is + unchanged. + +**What this decides.** VS Code does *not* use range only for "large" +documents — it uses it for every document, but only until the full answer +lands. So answering only `range` early would still leave the first full +answer — the one that makes the model complete and stops all range requests — +held behind the scan, and a held full also raises the adaptive debounce. The +full request has to be answered early too, and the refresh is what reaches the +full provider afterwards (it never reaches the range provider). + +## Assumptions + +- A buffer's `Document` (text, line index, tokens, tree, `Semantics`, overlay) + is only ever replaced wholesale or refreshed in place between two messages, + never left half-written when control returns to the loop. True today: the + loop is one thread and the scan publishes (`publish_scan`, `finish_scan`) + only between files. +- The index's overlay on a buffer (`ExternalResolutions`) only ever grows more + right during a scan: `publish_scan` absorbs records, it never takes the old + index away mid-rescan (`state/rescan.rs`), so an answer off it is a coherent + guess, never a regression to "nothing resolves". +- `Server::hierarchy_revision` is bumped by every index mutation + (`hierarchy_index_changed` in `reindex`, `reindex_one`, `reindex_widened` and + the startup). The refresh decision keys off it. +- A text-changing notification about a buffer carries that buffer in + `textDocument.uri` (`didOpen`, `didChange`, `didClose`, `didSave`). +- VS Code facts as quoted above; other clients may ask for range and full in + any mix — every answer is valid on its own whatever the mix. + +## Design + +**One exemption from the order contract, taken where requests are held.** +`process_batch` holds a message when `must_hold` says so (for a request: +`must_wait`); just before that, a semantic-token request is offered to +`answer_from_the_buffer` (`server/viewport.rs`). It is answered there and +then — and so is any colouring request behind a held one in the same burst +(`set_aside`) — when its buffer's text is **current**: the text the server +holds is exactly what the client had sent for that document when it asked, +i.e. no `didOpen`/`didChange`/`didClose` for it is queued unapplied. + +**Rebuilt on the loop's own bookkeeping (2026-11-19, on 0.65.8).** Lane 71.7 +(`docs/features/scan-ordering/README.md`) made the loop keep exactly the +fact this needs: a message older than the one being handled is either +applied or (a) in `held`, or (b) in the tail of the burst whose message +started the scan now draining, counted by `Server::behind` — the clause +`must_hold` uses so that no notification overtakes an older one. The +exemption reads the same two places, plus the two that are its own: + +1. `held` — a notification naming the buffer there means its text is behind; +2. `Server::behind > 0` — an unapplied older notification exists; it is a + count and names no buffer, so it is taken to name this one (conservative: + the request is then held exactly as before); +3. `ahead` — the part of the request's own burst being set aside in front of + it, not yet in `held`; +4. `dirty` — a `didChange` applied to the text but not analyzed. + +The first version kept its own stack of "buffers still behind this message" +lists (`Viewport::behind`, `enter`/`leave`, `handle_before`); it overlapped +`behind`/`must_hold` and is deleted. What that costs: a colouring request +inside a scan that a notification started, while that notification's burst +still has *any* unapplied notification, now waits — the old stack let it +through when none of them named its buffer. That shape is a mid-session +rescan with a second notification in the same write; it was not in any +measured scenario. + +**Clients without `refreshSupport` get early `range` only** (QA Q3). An early +whole answer is cross-file-blind and only the refresh corrects it; a client +that cannot be refreshed would keep it until its next edit, which is worse +than waiting. So for such a client `full`/`full/delta` wait as they always +did, and early `range` answers (painted over by the first `full`) still go. + +**A widen drains** (QA Q2). In folder scope — the default — a `didOpen` after +the settings answer, or any open in a folder not yet indexed, widens the +scope, and `reindex_widened` used to drain nothing: ~650 ms with no colour. +Now: + +- `process_batch` hands a `didOpen` to `open_then_widen` with the rest of its + burst. The `didOpen` is applied as always; a widen it asks for is recorded + (`Viewport::defers_widen`) instead of run. Then the colouring requests in + the rest of the burst are answered from their buffers — the just-opened one + is applied, so VS Code's `full` in the same write colours at once — and the + widen runs; the rest of the burst then proceeds exactly as before. +- Between two of the widen's files, `answer_colours_mid_widen` drains the + queue: colouring requests that can be are answered, everything else goes to + `held` in arrival order (and `hold` splices the burst's own tail in front of + it, as for a scan that holds). +- `Viewport::widening` is set for the widen's length, so a range answered + then is owed the refresh, and the widen's revision bump triggers it. + +Within 71.7's invariants: the widen is still the effect of the one applied +`didOpen` (only applied messages change scan state); nothing drained during a +widen is applied during it (it is held), so no notification overtakes an +older one; and while the burst's tail holds a notification, `behind > 0` +makes every drained colouring request wait. + +**What the exempted handler reads** — the ordinary dispatch arm for the +method, run through `answer_flushed` (the dispatch *without* +`flush_dirty`): + +- the one `Document` the request names (text, line index, tokens, tree, + `Semantics`, the `ExternalResolutions` overlay); +- `Workspace::has_large_documents`, `Document::large`, + `ClientAbilities::token_server_cancel` (the large-file decline); +- `Server::tokens`/`token_results` (the remembered answer and its id). + +Never the workspace index, never another buffer, never a flush or a publish. +**Why that is valid mid-scan:** a request is only ever answered "during" a +scan by being reached from inside it — the startup's configuration wait +(`await_configuration`/`await_opening_file`), a scan's between-files drain +(`answer_what_is_waiting`), both through `process_batch`, or a widen's +between-files drain (`answer_colours_mid_widen`) — so the scan is between two +files, the buffer's state is whole, and its overlay is the index's answer as +of the last publish. + +**A dirty buffer waits.** Answering it would need its analysis, i.e. a parse +of the newest text — and either the index (forbidden) or a cross-file-blind +re-analysis, which would flip every package type, imported enum and +parameter to `variable` on each keystroke during a rescan and back at the end +(right → wrong → right). Holding is the honest choice: VS Code keeps the +colours it has (it shifts them through the edit), only text typed during the +rescan waits for colour, and the rescan hold is now 70–156 ms (below; QA +round 2's figure on the final binary). + +**`full`/`full/delta` before the index is ready: answered locally, now** — for a client with `refreshSupport` (see above for one without). +From the VS Code facts: the first full answer is the one that completes the +model and ends range requests, so holding it holds the colours that matter; +answering it early gives the whole file colour (scrolling needs no range +round trips), keeps the adaptive debounce short, and costs one refresh later. +The sequence the user sees is **local → accurate**, once: the overlay only +grows during a scan, and the refresh decision is taken once, at settle — never +at intermediate publishes, so there is no wrong → right → wrong. Once the +index is ready, nothing is exempt (`must_wait` is false) and full/delta are +exactly what they were. + +**Delta consistency.** Every full/delta answer, local or accurate, goes +through `remember_tokens`, which stamps a fresh `resultId` and keeps *that* +data as the delta base. A client's `previousResultId` therefore always names +the exact data it holds, whichever kind of answer that was; a mismatched id is +answered with a full set, as before. + +**The range answer costs the window** (`tokens::semantic_tokens_in_range`). +The range is snapped to whole lines (`large::line_window`, the uncapped half of +the large-file window's `bounds`), the tokens touching those lines plus one +neighbour each side (for the comments that hang off them, the EOF token's +included) are classified, and the instantiation-override AST walk visits only +items overlapping the window (`instantiation::overrides_within`). The answer is +still exactly the full answer filtered to the range. A buffer over the +large-file threshold keeps its lexer-only window (`large::window`, with its +block-comment back-scan) and its `full` decline, unchanged; the large window +was generalised (`line_window`) rather than duplicated. What "local" uses: the +lexer always (a large buffer's window lexes on demand); the buffer's own +parse/semantics, which every non-large buffer already has for its current +version (`didOpen` parses; the 4 MiB large-file threshold is the measured line +above which nothing parses — `docs/features/large-file-mode`); the overlay as +of the last publish; never the index. + +**Refresh** (`refresh_tokens_if_stale`, called by `run` once `held` is empty, +before it blocks for the next message). At most once per index revision: if +`hierarchy_revision` moved since the last decision and nothing must wait, the +open, non-large, non-dirty buffers whose last answer was taken off an +**unsettled** index (a scan running or owed, or a widen running — +`Server::index_unsettled`) are checked: a remembered whole answer +(`Viewport::early`) is compared with a fresh classification, and a buffer last +painted by a range answer (`Viewport::guessed`) counts as stale. Any stale +buffer → one `workspace/semanticTokens/refresh`, gated on +`workspace.semanticTokens.refreshSupport`; both sets are then cleared. An +answer given once the index had settled is not checked again (QA Q6: checking +every open buffer on every index change cost 13 ms per save with 200 open). +**Cost:** one token build per buffer answered while unsettled, once (0.3–7 ms +each on OpenTitan; 12.9 ms for 200 buffers opened at startup); on the client +side, one `full/delta` per editor-attached model, which the prefix/suffix +trim keeps to the tokens that changed. This also fixes the old "stale +forever": a full answered off the head prefix mid-scan is unsettled, and so +compared at settle like any early answer. What it does not do: a later edit +in one file that changes another open file's colours (a package type +renamed) refreshes nothing — exactly as before this lane. + +## Results + +### Fix round, on 0.65.8 (2026-11-19, QA's harness, medians of 5) + +QA's driver (`qa713/drv/meas.py`, copied with its tree to the dev scratch +dir), on a **copy** of OpenTitan `hw/` with every store under the scratch +dir. "before" is master 0.65.8 (`934d472`, built from `git archive` with its +own target dir); "after" is this lane. ms from `didOpen`; *late open* = the +`didOpen` arrives 30 ms after `initialized`, i.e. after the settings answer — +the ordering QA's Q2 is about. Rescan hold = a watcher *create* (whole +rescan) with a `full/delta` and a `range` sent 5 ms after it. + +| scope / file | cold first colour | warm | **late open, cold** | rescan hold | refresh lands (cold / warm) | +|---|---|---|---|---|---| +| workspace / aes_cipher_core | 700 → **3.5** | 384 → **3.5** | 631 → **64** | 778 → **120** | 1 614 / 827 | +| workspace / spi_device_reg_top | 680 → **39** | 401 → **39** | 668 → **89** | 758 → **156** | 1 647 / 877 | +| folder / aes_cipher_core | 39 → **3.3** | 66 → **3.3** | 614 → **2.4** | 325 → **70** | 638 / 352 | +| folder / spi_device_reg_top | 71 → **38** | 100 → **38** | 643 → **32** | 341 → **87** | 680 / 352 | + +Exactly one refresh in every "after" run (5/5 in every row), none in any +"before" run. **Opening a file in a folder not yet indexed, mid-session** +(folder scope, `aes_cipher_core.sv` settled, then `top_earlgrey.sv`): the new +buffer's `full` **350 → 3 ms** (5 runs each: 357/350/350/351/351 → +2.9/2.7/3.2/3.2/3.1). + +**What remains, and why.** The 32–39 ms on `spi_device_reg_top.sv` is that +buffer's own parse at `didOpen` (16 ms) plus the token build (6.5 ms) — the +floor for a 545 KB file. The 64–89 ms of a late open in **workspace** scope is +the startup scan's discovery walk (~80 ms on OpenTitan), which drains nothing +(Handshake request 2, left documented). The rescan hold is the same walk at +the front of the rescan. A second file opened in the same write as a +request that is held during the startup's head phase colours at the head +(~650 ms): the tail of a burst behind a held request is held whole by +`process_batch` (71.7's rule), so its `didOpen` is not applied yet and its +buffer has no text to colour from — the exemption correctly refuses it +(QA's `livelock2.py hover`: `full(B)` at 658 ms, answered "from the buffer" +the moment the `didOpen` is applied). + +**Refresh check cost (QA Q6)**, verbose timing line, OpenTitan, buffers +opened at startup and each sent a `full`, then five saves that each change +the index (a module appended): before restricting, every index change +re-tokenized every open buffer — **1.4–2.3 ms with 50 buffers (227 KiB), +12.7–14.2 ms with 200 (2 MiB), per save**. Restricted to buffers whose last +answer was taken off an unsettled index (`Viewport::early`/`guessed`): the +one post-startup check is unchanged (1.4 ms / 12.9 ms — those buffers were +answered mid-scan and are genuinely owed it), every later save **0.00 ms**. + +### First round, on 0.65.5 (dev harness; superseded by the table above) + +| scope | file | first colour cold: before → after | warm: before → after | rescan hold: before → after | refresh lands (cold / warm) | tokens recoloured by it | +|---|---|---|---|---|---|---| +| workspace | `spi_device_reg_top.sv` | 679 → **111 ms** | 400 → **174 ms** | 650 → **112 ms** | 1 594 / 779 ms | 2 771 | +| workspace | `aes_cipher_core.sv` | 677 → **1.8 ms** | 365 → **1.8 ms** | 646 → **99 ms** | 1 568 / 729 ms | 114 | +| folder | `spi_device_reg_top.sv` | 55 → 54 ms | 84 → 80 ms | 263 → **39 ms** | 648 / 307 ms | 2 745 | +| folder | `aes_cipher_core.sv` | 24 → 26 ms | 50 → **2.0 ms** | 245 → **20 ms** | 611 / 309 ms | 114 | + +In every run the refreshed answer was **identical** to a `full` asked after +the scan had settled. (These runs passed a relative store path to a server +whose cwd was the OpenTitan checkout, and so wrote forty stores into it — +QA Q5; the fix round's numbers do not.) + +## Correctness on real code + +`tokens::viewport_sweep` (ignored; `tools/guard.sh -- cargo test --release -p +lucisv_server viewport_sweep -- --ignored --nocapture`): all 860 corpus files +and every 10th OpenTitan `hw` file (407), six windows each (five 60-line +viewports, one mid-line), **7 602 windows**. The local answer is the buffer +analyzed against an **empty** index (the cold start); the accurate one is the +same text analyzed against its whole tree's index. + +- **Valid, every window:** sorted, non-overlapping, non-empty, inside the + range, never past its line's end, never a non-comment token inside a + comment, never a non-string token inside a string — for the analyzed path + and for the large-file lexer window on the same windows. +- **Exact:** the window answer equals the full answer filtered to the range on + every window (the windowing loses nothing). +- **Agreement with the accurate answer:** 559 725 accurate tokens, **541 616 + agree (96.77 %)**, **18 109 disagree, and 0 "other"** — every disagreement + is a name the accurate buffer resolves *through the index*: almost all to + another file (package types, imported parameters and enum members, + cross-file modules), but not all. QA's own checker (Q4) found 7 of 1 501 + that resolve to the **same** file — inherited class methods + (`core_ibex_test_lib.sv:1101`, `stress_debug()` through `extends`), whose + resolution goes through the index's class hierarchy even though the + declaration is local. My sweep classifies by "the resolution is + `Definition::External`", which those are, so it counted them as + "cross-file"; the accurate word is *index-resolved*. All of them are + exactly the colours the refresh replaces. + +Mutation checks: dropping the "one token after the window" neighbour fails the +sweep's exactness assertion; restoring the whole-file build fails +`a_viewport_costs_the_window_not_the_file` (8.6× for 8× the file). Dropping the +"one token before" neighbour is caught by no real file (no trailing multi-line +comment reaches across a viewport edge in the corpus); it is kept because the +trivia model allows the shape, and `window_tests` pin the comment shapes. + +## Handshakes + +**Consumed:** +- `Server::must_hold`/`must_wait`, `held`, `behind` (lane 71.7's count of + unapplied notifications around a scan's trigger), `dirty`, `scanning`, + `staging` (read-only) and `hierarchy_revision` (read-only, as "the index + moved"). +- `reindex_widened` (`server/index.rs`, now this lane's to touch): it defers + itself inside `open_then_widen`, drains colours between files, and sets + `Viewport::widening`. +- `Workspace::document`, `open_documents`; `Document` fields; `large::window`. +- The dispatch arms for the three token methods, via `answer_flushed` + (`answer_request` minus `flush_dirty`, a pure split). + +**Promised:** +- `ClientAbilities::semantic_tokens_refresh` (new field, read in `main.rs`). +- `tokens::semantic_tokens_in_range` answers exactly what it did, at window + cost; `large::line_window` is new and public to the crate. +- A request answered ahead of held ones is a response sent out of arrival + order — allowed by the spec, and only ever for the three colouring methods. + +**Touched outside the first round's scope:** `server/startup.rs`, one line — +`viewport: Default::default()` in `Server::empty`, because a `Server` field +cannot exist without its initializer; `server/index.rs` (fix round, by the +lead's ruling once the re-index lane had merged) for the widen. + +**Requests.** + +1. *Colours during a widen* — **done in this lane** (2026-11-19, after the + re-index lane merged and `server/index.rs` became this lane's): the drain + and the before-the-widen answers above. The original request missed the + same-burst `full`; `open_then_widen` is what reaches it. +2. *Drain during discovery* — **left documented.** The startup scan and every + whole rescan begin with a discovery walk (25–80 ms on OpenTitan) that + drains nothing; it is now the largest share of the cold first colour in + workspace scope and of the rescan hold. It is not small: the walk runs in + `state/discover.rs` with the `Workspace` borrowed mutably throughout + (`first_scope` inside `begin_scan`), and answering a request needs the + `Server` and a shared borrow of that same `Workspace`. A drain point means + splitting the walk into resumable steps the way `scan_step` splits the + indexing — a change to the scan's structure whose identical-result proof + is a lane of its own, not a hook. + +## Status / TODO + +- [x] Step 1: measure cold/warm/rescan/widen on OpenTitan over LSP; VS Code + client facts from source. +- [x] Range answer at window cost, exactly the full answer filtered + (`tokens.rs`, `tokens/instantiation.rs`, `large.rs`). +- [x] Exemption from `must_wait` for the three colouring methods on a + text-current buffer, without `flush_dirty` (`server/viewport.rs`, + `server/mod.rs`, `server/dispatch.rs`). +- [x] `workspace/semanticTokens/refresh`, coalesced per index revision, only + when a token would change, gated on `refreshSupport` (`main.rs`, + `server/viewport.rs`, hook in `run`). +- [x] Tests: `server/viewport/tests.rs` (16 tests, incl. a staged cold + start coloured at once and sharpened by one refresh, the widen's + same-burst and mid-widen answers, and a client without + `refreshSupport`), + `tokens/window_tests.rs`, `tokens/viewport_sweep.rs` (ignored sweep). +- [x] Before/after numbers (this README, `docs/perf/README.md`). +- [x] Widen drain and before-the-widen answers (QA Q2). +- [x] No early whole answers for a client without `refreshSupport` (QA Q3). +- [ ] Discovery drain — Handshake request 2, documented, not done. +- [ ] A dirty buffer during a rescan still waits (deliberate; see Design). +- [ ] Not verifiable here: a running VS Code. What a human should watch: open + a big file (`spi_device_reg_top.sv`) on a cold start with + `lucisv.index.scope: workspace` — module names, parameters, ports and + instance names colour at once; package types / imported names sharpen + once when the indexing bar ends; no flicker back to plain. Type during a + rescan (save a file in another folder): existing colours stay, new text + takes colour when the bar ends. + +## Work log + +- **2026-11-19 (dev).** Measured first (above). Design decided from the VS + Code source: answer full early as well as range, refresh once at settle. + `semantic_tokens_in_range` re-implemented at window cost (token slice + one + neighbour each side; item-filtered override walk; `large::line_window` split + out of `bounds`). `answer_request` split into flush + `answer_flushed`. + `server/viewport.rs`: the exemption (`answer_from_the_buffer`, + `answered_ahead`, `set_aside`, `handle_before` with the `behind` frames), + and `refresh_tokens_if_stale`. First cut only looked at the request at the + head of a held burst; the server tests showed a colouring request *behind* a + held hover in the same burst was still held — fixed with `set_aside`, which + also needed the `ahead` slice in the currency check. `process_batch` grew + 77 → 86 lines (most of the growth is comments; the logic moved into + `viewport.rs` helpers). Production lines: `tokens.rs` 267 → 288, + `tokens/instantiation.rs` 278 → 290, `large.rs` 195 → 199, + `server/viewport.rs` 0 → 169, `server/mod.rs` 186 → 216, + `server/dispatch.rs` 486 → 489, `server/semantic_tokens.rs` 34 → 35, + `server/startup.rs` 171 → 172, `main.rs` 377 → 387. + +- **2026-11-19 (dev, fix round on 0.65.8).** Re-applied onto master 0.65.8 + (lead). Resolved the two `process_batch` conflict hunks by keeping 71.7's + `must_hold`/`hold` structure and putting the exemption in front of the + hold (`answered_ahead`, then `set_aside` for the rest of the burst, then + `hold`). Deleted as redundant with `Server::behind`/`must_hold`: + `Viewport::behind`, `enter`, `leave`, `owes` and `Server::handle_before` + (master's plain notification/response arms are back); the currency check + now reads `self.behind == 0` instead of its own per-buffer frames (the + trade is in Design). QA Q2: `open_then_widen` (a `didOpen` arm in + `process_batch`, 5 lines; the function is 74 lines) answers the burst's + colouring requests before the widen, `reindex_widened` records a deferred + widen (`Viewport::defers_widen`), drains between files + (`answer_colours_mid_widen`) and sets `Viewport::widening`. QA Q3: early + `full`/`full/delta` only for a client with `refreshSupport`. QA Q4: README + corrected (index-resolved, not "cross-file"; the test count stated as it is). + QA Q5: my harness passed a *relative* store path to a server whose cwd was + the OpenTitan checkout, which is how forty stores landed there; this + round measures on a copy under the scratch dir with absolute store paths. + Handshake 2 (discovery drain) assessed and left documented (reason under + Handshakes). QA Q6: measured 1.4–2.3 ms (50 buffers) and 12.7–14.2 ms + (200) per index-changing save; restricted the check to answers taken off + an unsettled index (`Viewport::early`), after which a later save costs + 0.00 ms. To keep `process_batch` under 80 lines (78) the notification arm + calls `apply_in_burst`, which routes a `didOpen` to `open_then_widen`. Q1 + re-checked with QA's and 71.7's drivers: the startup scan settles in + 1.6–2.6 s with one progress cycle. Production lines (vs 0.65.8): + `tokens.rs` 267 → 288, `tokens/instantiation.rs` 278 → 290, `large.rs` + 195 → 199, `server/viewport.rs` 0 → 208, `server/mod.rs` 215 → 224, + `server/dispatch.rs` 491 → 494, `server/semantic_tokens.rs` 34 → 36, + `server/startup.rs` 173 → 174, `server/index.rs` 267 → 276, `main.rs` + 378 → 388. Tests: `server/viewport/tests.rs` 16, `tokens/window_tests.rs` + 6, `tokens/viewport_sweep.rs` 1 (ignored). + +## Changelog paragraph (for the lead) + +Semantic highlighting no longer waits for indexing. A colouring request for a +buffer whose text is current is answered from that buffer alone even while a +scan or a widen holds every other request: on OpenTitan the first colours of +a newly opened file arrive in 2–39 ms instead of 600–700 ms (cold start in +either scope, opening a file in a folder not indexed yet), and a mid-session +rescan holds them 70–156 ms instead of 325–778 ms. Names resolved through the +index are coloured as local guesses until it settles; then the server sends +one `workspace/semanticTokens/refresh` and the client's next answer is the +accurate one (this also fixes colours that used to stay stale until the next +edit). A client that cannot be refreshed gets early viewport colours only. +Viewport (`range`) answers now cost the visible lines, not the file. + +## QA log + +- **2026-11-19 (QA, Opus 5.5).** Verdict **PASS WITH FINDINGS**. No corrupted + or stale-unrecoverable token state, no duplicated response, no invalid + encoding and no read of unsafe state found. The findings are one + pre-existing scan livelock (Q1), a widen gap that leaves the default scope's + common ordering where it was (Q2), and some smaller ones. The harness + (Python LSP driver against the real release binaries, its own delta + reconstruction and validity checker, nothing shared with the dev's sweep) + is in the QA scratchpad (`qa713/drv/`). + + **Baseline.** `tools/gates.sh`: all steps pass (fmt, clippy, build, every + suite with lucisv_server at 2014/0, docs, corpus 814/6 as usual, node + 37/0). Ignored `viewport_sweep` in release: 1267 files, 7 602 windows, 96.765 % + agree, 18 109 index-resolved, 0 other, which reproduces the dev's numbers. The + `#[test]` count went from 5 433 to 5 452 (+19, the new files only). No + existing test or assertion was removed or edited. None of the off-limits + files differ from `80017a5`. `process_batch` is 86 lines, in the + "investigate" band. It has no reason comment, but it reads top to bottom + and the new logic lives in `viewport.rs` helpers. Acceptable. + + **Safety review** (`viewport.rs`, `process_batch`, `answer_flushed`, + `large_file_answer`, the three dispatch arms, `semantic_tokens.rs`, + `tokens.rs` window code). The exempt path reads only these: the named + `Document` (via `workspace.document`), `has_large_documents` and `doc.large`, + `abilities.token_server_cancel`, `self.tokens` and `token_results`, `held`, + `dirty`, `viewport.behind`, `scanning` and `staging`. It writes only + `self.tokens`, `token_results` and `viewport.guessed`. None of that is + half-written between two scan files. Scans start only from notification + and response handlers (every `reindex*` caller is in `notification.rs` or + the settings response), so the `behind` frames cover every outer burst. The + `didChange`/cancel skip is sound. Documents are keyed by exact `Uri`, so a + different spelling is a different document before and after the change; + the exemption adds no new hole. Mid-scan `didClose`+`didOpen` in one + burst answers from the new text. A never-opened document waits and gets + `null` at settle. + + **Scenarios on a full OpenTitan `hw/` copy** (workspace scope unless + noted). Every answer was validated: 5-tuples, sorted, non-overlapping, + UTF-16 widths, inside the legend, inside the range. The client array was + rebuilt by applying deltas per spec and compared with a `full` from the + same server and from a fresh server. + + | scenario | result | + |---|---| + | cold start; open small, then big, then a third file mid-scan; type plus delta mid-scan | valid; 1 refresh; client equals the same server's full and a fresh server's full for all 3 | + | warm start, same flow | same; 1 refresh | + | folder scope, same flow | same; 0 or 1 refresh depending on ordering (Q2) | + | client without refreshSupport | 0 refreshes ever; client keeps early colours (Q3) | + | after settle: 20 keystrokes each followed by a delta; save after edits; no-op save; unrelated file and a dependency changed on disk | **0 refreshes** each (no storm) | + | watcher *create* (whole rescan); range plus delta at once; hover; `full(B)` then `didClose(B)`; typing during the rescan | range/delta answered at 133 ms, hover held to 772 ms, typed delta held (dirty, by design), closed file's full answered once; 0 extra refreshes; client equals full | + | `didChangeConfiguration` mid-scan | valid; client equals full | + | cancel of a held token request, cancel in the same burst as an exempt request, delta against unknown id `999999`, `didClose`+`didOpen`+`full` in one burst, `full` for a never-opened document | -32800, -32800, full set, data for the new text, `null` at settle: one answer each | + | two documents with interleaved edits and deltas while unsettled | client equals full for both | + | 4.5 MiB generated buffer | full and delta declined -32802, range is the lexer window (640 ints, valid) | + | alternative URI spelling (`%5F`) `didChange` | answers for the real URI unchanged (pre-existing phantom document for the other spelling) | + + **Accuracy, own checker** (settings answer withheld so the index is + *empty*; my own comment/string scanner; disagreements classified with a + real `textDocument/definition` after settle). 1 678 windows: 992 corpus + windows over 80 files and 686 OpenTitan windows over 60 files. Edge + windows included: inside a block comment, macro continuation, + `` `ifdef``, `(* *)`, instantiation edge, file start, past EOF, mid-line + columns, empty, reversed, beyond EOF, one line with column 9999. + Results: + - early and settled answers: **0 invalid**; + - settled window equals the full filtered to the range: **1 678/1 678**; + - early vs settled: 43 070 agree, 1 501 disagree; + - 1 494 of the disagreements resolve cross-file; + - **7 resolve to the same file** (Q4). + + The checker flagged 10 comment and 428 string hits. All are tokens of a + `` `define``/`` `include``/macro-call directive whose text contains `//` + or a string (for example `kmac_test_vectors_kmac_vseq.sv:31`, + `dma_longer_transfer_vseq.sv:43`). The settled and base answers say the + same, so this is a pre-existing directive classification, not an early-answer + issue. + + **Measured** (medians of 5, ms from `didOpen`, machine shared, load + around 20). 80017a5 is built from `git archive` with its own target dir. + "late open" means the `didOpen` arrives 30 ms after `initialized`, i.e. + after the settings answer. + + | scope / file | cold first colour before → after | warm before → after | late-open cold before → after | rescan hold before → after | refresh lands cold / warm | + |---|---|---|---|---|---| + | ws / aes_cipher_core | 716 → **2.2** | 384 → **2.2** | 669 → 68 | 769 → **127** | 1 706 / 865 | + | ws / spi_device_reg_top | 736 → **39** | 433 → **36** | 687 → 99 | 781 → **163** | 1 673 / 945 | + | folder / aes_cipher_core | 35 → **2.1** | 62 → **3.3** | 650 → **627** | 327 → **70** | 659 / 310 | + | folder / spi_device_reg_top | 75 → **38** | 101 → **38** | 645 → **650** | 340 → **86** | 683 / 349 | + + Exactly one refresh in every run that answered early; none in the + late-open folder runs, which never answered early. + + **Findings.** + - **Q1 (HIGH, pre-existing in `80017a5`, `server/index.rs` + `answer_what_is_waiting` — not this lane's file).** A `didOpen` set + aside behind a held request makes `opened` true at every later + interleave. So `head_owed` is set again, the whole held burst is held + again, and each interleave publishes. The startup scan then takes + **287–304 s instead of 1.7 s**, and every held request waits it out. + *Repro:* cold workspace start on OpenTitan, open `aes_cipher_core.sv` + plus `documentSymbol`; at 150 ms, in one write, send `didChange(A)`, + `full/delta(A)`, `didOpen(uart_core.sv)` and `full(uart_core)`. + Result: `documentSymbol` answered at 304 s on base and 287 s on this + branch. This lane makes the trigger *more reachable*, because A now + colours at 2 ms and a user can type and open a second file inside the + head phase. My first VS Code-like replay hit it without being + constructed to. + - **Q2 (MEDIUM, goal gap and README accuracy).** In folder scope, the + default, when the first `didOpen` arrives after the settings answer + (VS Code with `onView:lucisv.hierarchy` activation, or any race), the + startup scans 0 files and the `didOpen` then *widens*. + `reindex_widened` drains nothing, so first colour is still **~630–650 ms**, + unchanged from base. Opening any file in an un-indexed folder later + behaves the same way. The README's results table shows only the + race-won ordering. Handshake request 1 as written does **not** fix this: + as the dev notes, it cannot reach the `full` in the same burst as the + `didOpen`, which is exactly VS Code's case. The request should ask for + the widen to run after the burst's exempt colour requests are answered, + or for the exemption to run before `reindex_widened`. + - **Q3 (LOW/MEDIUM, design trade-off).** A client without + `refreshSupport` keeps the cross-file-blind colours of an early full + until its next edit. `spi_device_reg_top.sv` and `uart_core.sv` stayed + different from the settled full in the norefresh run. Before this + change, workspace scope left ~26 stale tokens; now it can leave + thousands. VS Code is not affected. The lead should decide whether + non-refresh clients get the early `range` only. + - **Q4 (LOW, doc).** "Every disagreement is a name resolved to another + file" is not exact. 7 of 1 501 disagreements are inherited class + methods resolved through the index to the *same* file, for example + `ibex/dv/uvm/core_ibex/tests/core_ibex_test_lib.sv:1101` `stress_debug()` + in `core_ibex_directed_test extends core_ibex_debug_intr_basic_test`. + The refresh fixes them all the same. Also, Status says "13 claims on the + wire", but `server/viewport/tests.rs` has 12 tests. + - **Q5 (LOW, process).** Forty `st-before-*`/`st-after-*` index-store + directories (1.3 GB) were written into the off-limits + `~/.cache/lucisv-opentitan-full/` at 07:13–07:28. Their names match this + lane's measurement harness. QA did not remove them; that is for the lead. + - **Q6 (INFO).** `refresh_tokens_if_stale` re-tokenizes every open + non-large buffer once per index revision, and every save is a revision. + That is 0.3–7 ms per buffer on the `run` thread. It is not measured with + many open buffers. + + VS Code facts 1, 2, 3 (range dropped on version change) and 5 (refresh + calls `schedule(0)` or waits for the in-flight request) check out against + the 1.145.2 bundle (`_tokenizeViewportNow`, `_requestRange`, + `handleProviderDidChange`). The `vscode-languageclient@9.0.1` claims + (fact 6) are unverified: no local copy, not fetched. A real VS Code was + not observed. Nothing fixed by QA. + +- **2026-11-19 (QA round 2, Opus 5.5; worktree 71.3b on `934d472`).** + Verdict **PASS WITH FINDINGS** (minor findings only). Base `934d472` was + built from `git archive` with its own target dir. Every store and tree + lived under the QA scratch dir (`qa713b/`). + `git -C ~/.cache/lucisv-opentitan-full status --short` is empty, the forty + `st-*` stores are gone, and nothing in `~/.cache/lucisv-corpus` is newer + than this round. + + **Baseline.** + - `tools/gates.sh`: every step passes, including `cross`. lucisv_server is + 2052/0 and corpus 814/6. + - Ignored release runs, with the corpus and OpenTitan paths pointed at + scratch copies, all pass: + - `viewport_sweep`: 7 602 windows, 0 other; + - `ordering_random` long run; + - both `localized_reindex` sweeps. + - `#[test]` count went from 5 491 to 5 514. Nothing was removed or edited. + No file under `server/tests/`, `tests/`, `state/` or `vlog_semantic` + differs from `934d472`, so 71.7's scan_ordering, caret_boundary and + ordering_random tests and the re-index differential tests are untouched + and pass. + - `process_batch` is 79 lines and `open_then_widen` is 22. + + **Safety on the new loop** (`process_batch`/`must_hold`/`hold`, + `answered_ahead`, `set_aside`, `apply_in_burst`, `open_then_widen`, + `answer_colours_mid_widen`, `reindex_widened`). Every place an unapplied + older message can sit is covered by `text_is_current`: + - this burst's older messages are applied, otherwise `process_batch` has + already returned holding them; + - `held` (a notification naming the buffer); + - `behind`, set to `outer` at the head and to `around` while the widen + runs, so the burst's unapplied tail makes every mid-widen colour request + wait; + - `ahead` (the set-aside part of its own burst); + - `dirty`. + + The four 71.7 invariants hold: + - (i) No notification overtakes another. Messages drained mid-widen go to + `held` unapplied, and `hold` splices the burst tail in front of them. + - (ii) Scan state changes only through applied messages. The recorded + widen is the applied `didOpen`'s, and between recording it and running + it only colouring requests are answered; notifications are kept. + - (iii) Held messages are handed back a bounded number of times. Q1 does + not come back: on `livelock2.py` delta and hover the held requests are + answered at 741 and 665 ms, against 667 ms on base. On `c717.py`, seeds + 1 and 2, the startup scan ends at 3.33 and 3.60 s, against 4.19 and + 3.70 s on base (machine loaded). + - (iv) Exactly once: no request was lost or duplicated in any run. + + One semantic note: a held settings notification does not stop an early + colour answer, because it names no buffer. The answer can therefore use the + previous settings' analysis. Colours only, and the early-answer refresh + corrects it at settle. + + **Attack campaigns** (exact text oracle: the generated documents' tokens + are computed from the client's own text; deltas rebuilt as the LSP spec + says; every answer has to match a state the client had sent at or after + the request): + + | campaign | runs | token answers checked | result | + |---|---|---|---| + | 71.7's `ord3.py` with range/full/delta mixed in, plus didOpen+full, didOpen+change+range/full, didOpen+didClose, change+delta (`ord3t.py`) | corpus 6 workspace + 4 folder, OT 2+2, corpus 2 without refresh: 16 runs, 26 refreshes | 6 918 (range 4 562, full 863, delta 1 493, 1 050 of them as edits) | **0 fails**; fresh-server oracle equal in every run; 0 stale at settle; 153 early answers | + | `wid.py`: folder scope on a full OT copy, 24 docs in 12 disjoint scope folders, 12 widens per run, 1–3 widening didOpens per burst each with its `full`, settings change between the recorded widen and its run, didOpen+didClose before the widen, watcher creates (rescans) mixed in | 8 seeds × (new, base) + 3 shutdown+exit mid-widen + 2 without refresh | 3 047 on new | **0 fails** | + + In `wid.py`: + - **non-colouring requests in a widening burst were answered only after + the widen ended (63/63);** + - **all 978 non-colouring answers are identical to base, answer for + answer**; + - shutdown+exit mid-widen: the server exited in 0.1–0.9 s with `full` and + `shutdown` both answered. + + Other comparisons with base: + - `f6.py` tail, held and control all report "server holds v3", the same + as base. + - `harm2.py` matches base. Base's first run gave one different + `definition`, which did not reproduce in two reruns of either binary, so + it is a pre-existing timing race. + + **Re-index oracle** (qa711 `small.py`, `outside.py`): + - `small.py` and `outside.py` (push and pull): only the negative controls + diverge, as in 71.1. + - `rand_run2.py`, two seeds per tree × 300 steps (`QA_FRESH_SAVE=1` as + before): corpus 71/72 and otsample 73/74 all end with 0 divergent checks. + + **Accuracy** (own checker, index empty): 726 windows (498 corpus, 228 OT). + - 0 invalid answers; + - windowed answer equals the full answer filtered to the range in 726/726; + - all 437 disagreements resolve through the index (go-to-definition lands + in another file); + - the directive and attribute string/comment hits are pre-existing, as in + round 1. + + **Q3.** A client without refreshSupport gets `full` at 655 ms (held, as on + base at 672 ms), `range` early at 107 ms, and no refresh. With + refreshSupport: `full` at 2 ms and one refresh. + + **Q6.** + - Trade-off (`q6.py trade`): an edit plus save in package A that changes + how open B colours sends no refresh, on base and on new, so "same as + before" holds. + - Check cost: with 50 or 200 buffers answered during the startup scan, + the one settle check takes 5.2 and 32 ms (machine loaded; the dev + measured 1.4/12.9 ms). Later saves run no check. + + **Measured on the final binary** (medians of 5, ms from didOpen, OT copy; + before = 934d472): + + | scope / file | cold | warm | late open, cold | rescan hold | refresh lands cold / warm | + |---|---|---|---|---|---| + | ws / aes_cipher_core | 660 → **3.5** | 374 → **3.5** | 626 → **62** | 756 → **141** | 1 616 / 839 | + | ws / spi_device_reg_top | 685 → **39** | 400 → **37** | 674 → **86** | 791 → **159** | 1 635 / 868 | + | folder / aes_cipher_core | 38 → **3.2** | 66 → **3.2** | 611 → **2.3** | 325 → **70** | 636 / 348 | + | folder / spi_device_reg_top | 74 → **32** | 98 → **31** | 641 → **32** | 344 → **70** | 699 / 372 | + + Opening `top_earlgrey.sv` mid-session in folder scope: its `full` takes + **375 → 5.6 ms**. Refresh counts per run, 5/5 runs each: + - cold and late open: 1; + - warm with the rescan, and mid-session open: 2, i.e. one more at the + rescan's or widen's settle; + - base: 0. + + No storm, and no early answer that was left without a refresh when + stale. The dev's table reproduces within noise. + + **Findings.** + - **R2-1 (LOW/INFO, `server/viewport.rs` `answer_from_the_buffer` + `guessed.insert`).** A `range` answered during a rescan is always + counted stale, so it buys one refresh at settle even when nothing + changed. On `flick.py`, a `full` asked during the same rescan was + identical to the settled answer and drew 0 refreshes. With the measured + `range`, every warm run got a second refresh. VS Code asks for `range` + only until the first `full`, so this rarely fires there. + - **R2-2 (LOW, docs).** + - Design ("A dirty buffer waits") still says "rescan hold is now + 20–112 ms"; it is 70–156 ms. + - The work log says `open_then_widen` "is 74 lines"; it is 22. + - The changelog says first colours arrive in "2–39 ms … cold start in + either scope". Late open in workspace scope is still 62–86 ms + (discovery walk), and the paragraph should say so. + - Handshake 2 (discovery drain) is still open and correctly described. + + Unverified: a real VS Code, and the vscode-languageclient facts. Nothing + fixed by QA. + +## Review + +**Lead, 2026-11-19.** Accepted for 0.65.10, after two QA rounds and a re-application onto a changed loop. + +- The owner asked for a viewport-only highlight. The dev's Step 1 found that + VS Code asks for the viewport only until its first whole-file answer, so + answering `range` early would not have been enough; `full` is answered + early too and corrected by a refresh. Reading the client before designing + is what made this work. +- Round 1 passed QA but left the default scope's common ordering untouched + (a file opened after settings arrive still waited ~630 ms) and I did not + ship it. It also could not be finished then: the fix sits in + `server/index.rs`, which the re-index lane held. +- Lanes 71.1 and 71.7 then changed the loop underneath it. I re-applied the + lane onto 0.65.8 by hand and had the dev rebuild the exemption on 71.7's + `must_hold`/`behind` instead of beside it; its own per-buffer lists were + deleted. One mechanism for "is anything for this buffer still queued", + at the price of one narrow shape where a colour request now waits. +- QA round 2 re-measured the whole table on the final binary (the dev had + measured before its last refactor), rebuilt client token state from deltas + for ~10 000 answers with no failure, and compared 978 non-colour answers + with base, identical. That, and 71.7's invariants holding under `wid.py`, + is what I accept this on. +- QA's two README corrections: I fixed the rescan-hold figure in Design; the + work log's "74 lines" is history and stays. The release notes state the + workspace-scope late-open figure the dev's paragraph left out. +- Not verified: a running VS Code; the `vscode-languageclient` facts (read + from a fetched copy, not the pinned one). diff --git a/docs/perf/README.md b/docs/perf/README.md index f3e9f5f..91da04e 100644 --- a/docs/perf/README.md +++ b/docs/perf/README.md @@ -1468,3 +1468,33 @@ Details and the method: `docs/features/localized-reindex/README.md`. | mention census, one lint pass (average / worst file) | 51 µs / 2.8 ms | unchanged | Probes: `tools/guard.sh -- cargo test --release -p lucisv_server reindex_perf -- --ignored --nocapture --test-threads=1`. + +### 2026-11-19 — viewport highlight: colours that do not wait for the index (TODO §71.3) + +Time from `didOpen` to the first semantic-token answer, real binary over LSP +stdio, a copy of OpenTitan `hw/` (4 058 files), a VS Code-shaped opening +burst (`full` at once, `range` for lines 0–120 after the viewport's 100 ms +debounce). Medians of 5 runs, shared machine; before = 0.65.8 (`934d472`). +*Late open* = the `didOpen` arrives after the settings answer (in folder +scope the startup then scans nothing and the open widens). Harness and +traces in `docs/features/viewport-highlight/README.md`. + +| scope / file | cold | warm | late open (cold) | tokens held by a mid-session rescan | +|---|---|---|---|---| +| workspace / `aes_cipher_core.sv` | 700 → **3.5 ms** | 384 → **3.5 ms** | 631 → **64 ms** | 778 → **120 ms** | +| workspace / `spi_device_reg_top.sv` (545 KB) | 680 → **39 ms** | 401 → **39 ms** | 668 → **89 ms** | 758 → **156 ms** | +| folder / `aes_cipher_core.sv` | 39 → **3.3 ms** | 66 → **3.3 ms** | 614 → **2.4 ms** | 325 → **70 ms** | +| folder / `spi_device_reg_top.sv` | 71 → **38 ms** | 100 → **38 ms** | 643 → **32 ms** | 341 → **87 ms** | + +Opening a file in a folder not yet indexed, mid-session: the new buffer's +first colour 350 → **3 ms** (the widen now answers colours before it runs and +between its files). The token build itself was never the cost (0.3 ms small, +6.5 ms for 545 KB); the wait was the order contract. What is left is the +buffer's own parse at `didOpen` and the discovery walk at the front of every +scan (~80 ms), which drains nothing. One `workspace/semanticTokens/refresh` +lands when the scan settles; the check behind it costs 1.4 ms (50 open +buffers) / 12.9 ms (200) once after startup and 0.00 ms per later +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). diff --git a/editors/vscode/CHANGELOG.md b/editors/vscode/CHANGELOG.md index fb313d5..982fe76 100644 --- a/editors/vscode/CHANGELOG.md +++ b/editors/vscode/CHANGELOG.md @@ -5,6 +5,16 @@ 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.10 — 2026-11-19 + +- **Syntax colours appear immediately,** without waiting for the workspace to + be indexed: 2–39 ms after opening a file on a large project instead of + 600–700 ms, and they no longer freeze for most of a second while the + project is re-scanned. +- **They sharpen once when indexing finishes.** Names defined in other files + start as a best guess and are corrected by one refresh — including colours + that previously stayed wrong until you edited the file. + ## 0.65.9 — 2026-11-19 - **The bundled MCP server (`lucisv-mcp`) no longer answers from a file's old diff --git a/editors/vscode/README.md b/editors/vscode/README.md index 1480eef..02be578 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.9**. Its platform packages include +The current release is **0.65.10**. 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.10 highlights + +Version 0.65.10 colours a file the moment it opens instead of after the +workspace is indexed, then corrects cross-file names once when indexing +finishes. + ## Release 0.65.9 highlights Version 0.65.9 fixes the bundled MCP server answering from a file's old diff --git a/editors/vscode/package-lock.json b/editors/vscode/package-lock.json index 8d9006b..e211a81 100644 --- a/editors/vscode/package-lock.json +++ b/editors/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "lucisv", - "version": "0.65.9", + "version": "0.65.10", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "lucisv", - "version": "0.65.9", + "version": "0.65.10", "license": "MIT", "dependencies": { "vscode-languageclient": "9.0.1" diff --git a/editors/vscode/package.json b/editors/vscode/package.json index bb89bd8..beba937 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.9", + "version": "0.65.10", "publisher": "guoliangchen", "author": "Guoliang Chen", "license": "MIT",