Files
lucisv/crates/lucisv_server/src/server/tests/mod.rs
T
Guoliang ChenandClaude Mythos 5.2 58d3db3e3c
ci / checks (push) Successful in 59s
ci / corpus (push) Successful in 16s
release / build-and-publish (push) Failing after 4m55s
Release 0.65.6: saving a file no longer re-indexes the workspace
TODO §71.1. On OpenTitan hw (4 058 files) every save cost ~160 ms of
whole-index work, twice (the save and VS Code's watcher echo), and watcher
events for files the index could not hold started whole rescans.

- vlog_semantic: resolution records every table lookup per reading file,
  misses included (workspace/dependents.rs, references.rs, replace.rs); an
  update re-resolves the edited file and the readers of keys whose values
  changed in what resolution reads. An unchanged record merges nothing. When
  the readers hold more than an eighth of all references, old results are
  removed in one pass over the postings.
- lucisv_server: watcher events are classified per file (state/watched.rs);
  the include graph keeps every include line as written and re-resolves the
  lines a named path could satisfy, in one pass per event; an event naming
  more paths than half the index takes the single rescan; an open buffer the
  index does not hold joins on its first save; completion tables are rebuilt
  only for the names a file declares. Every save still republishes every open
  buffer. The line-length lint follows the formatting style's width.
- Fixed on the way: removing an included header left other files' include
  edges pointing at it.

Typical saves: comment or watcher echo <0.3 ms, local signal 4 ms, package
member 12 ms; warm startup +40..120 ms for the readers table.

QA failed the first cut on four stale answers found with an independent
fresh-server oracle; all four are fixed and are differential tests. Dev
(three rounds), QA (two rounds) and lead review:
docs/features/localized-reindex/README.md. TODO.md files lane 71.7 from
what the QA rounds and an investigation found in earlier releases too.

Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.65.6) and
editors/vscode/CHANGELOG.md.

Gates: tools/gates.sh PASS on this tree; vlog_semantic 435/0,
lucisv_server 2011/0, lucisv_mcp 384/0.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 08:52:01 -08:00

655 lines
24 KiB
Rust

//! The `Server` tests: one file per feature, every one driven through the
//! real `process_batch` against a scratch workspace on disk.
//!
//! This file is the harness — `Tree`, a workspace root removed on drop, and
//! `Session`, a server on an in-memory connection whose every outgoing
//! message can be read back — followed by the helpers more than one file
//! uses. The sibling files are the sections the one big test module used to
//! have, under the names they had; a helper used by one section only stayed
//! with it.
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::time::Duration;
use lsp_server::{Notification, Request, Response};
use lsp_types::notification::{
DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles,
DidChangeWorkspaceFolders, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument,
DidRenameFiles, DidSaveTextDocument, LogMessage, Progress, PublishDiagnostics, ShowMessage,
};
use lsp_types::request::{
ApplyWorkspaceEdit, CallHierarchyPrepare, CodeActionRequest, CodeActionResolveRequest,
CodeLensRefresh, CodeLensRequest, Completion, DocumentDiagnosticRequest,
DocumentHighlightRequest, DocumentLinkRequest, DocumentSymbolRequest, ExecuteCommand,
FoldingRangeRequest, Formatting, GotoDefinition, GotoTypeDefinition, HoverRequest,
InlayHintRequest, InlineCompletionRequest, LinkedEditingRange, OnTypeFormatting,
PrepareRenameRequest, RangeFormatting, References, RegisterCapability, Rename, Request as _,
SelectionRangeRequest, SemanticTokensFullDeltaRequest, SemanticTokensFullRequest,
SemanticTokensRangeRequest, ShowDocument, Shutdown, SignatureHelpRequest, TypeHierarchyPrepare,
UnregisterCapability, WillRenameFiles, WillSaveWaitUntil, WorkDoneProgressCreate,
WorkspaceConfiguration, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
};
use lsp_types::{
DidChangeWatchedFilesParams, FileChangeType, FileEvent, LogMessageParams, MessageType,
ProgressParams, ProgressParamsValue, ProgressToken, PublishDiagnosticsParams,
ShowMessageParams, WorkDoneProgress, WorkDoneProgressCreateParams,
};
use serde_json::Value;
use super::batch::{is_shutdown, widen_of, Widen};
use super::progress::{reports, MAX_REPORTS};
use super::startup::{Startup, CONFIGURATION_WAIT};
use super::*;
use crate::settings::ClientSettings;
use crate::uri::path_to_uri;
use crate::{design_hierarchy, diagnostics, format, lens, pairs, ports};
mod apply_edit;
mod cancel;
mod code_action;
mod file_ops;
mod folders;
mod formatting;
mod hierarchy_everywhere;
mod hierarchy_reach;
mod index;
mod large_file;
mod lint_snapshot;
mod localized_reindex;
mod progress;
mod pull_diagnostics;
mod qa_generate_label;
mod qa_rename_implicit;
mod references_scope;
mod references_top_rooted;
mod rename_generate_label;
mod rename_implicit;
mod rename_top_rooted_scope;
mod requests;
mod scan;
mod scan_trace;
mod settings;
mod startup;
mod sync;
mod tokens;
mod watchers;
/// A scratch workspace root, removed on drop.
struct Tree {
path: PathBuf,
}
impl Tree {
fn new(name: &str) -> Tree {
let path =
std::env::temp_dir().join(format!("lucisv_server_watch_{}_{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("temp dir");
Tree { path }
}
/// A package declaring one localparam, so the index can be asked
/// whether this file was scanned at all.
fn package(&self, rel: &str, name: &str) {
let path = self.path.join(rel);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).expect("parent");
}
std::fs::write(&path, format!("package {name};\n localparam K = 1;\nendpackage\n"))
.expect("write");
}
fn write(&self, rel: &str, text: &str) {
let path = self.path.join(rel);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).expect("parent");
}
std::fs::write(&path, text).expect("write");
}
#[cfg(unix)]
fn link(&self, rel: &str, target: &str) {
let path = self.path.join(rel);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).expect("parent");
}
std::os::unix::fs::symlink(target, &path).expect("symlink");
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
/// A real `Server` on an in-memory connection, plus the client end of it —
/// so a test can drive a notification and read every message it produced.
struct Session {
server: Server,
client: Connection,
}
impl Session {
fn new(roots: Vec<PathBuf>, file_watching: bool) -> Session {
Session::with(roots, ClientAbilities { file_watching, ..Default::default() })
}
/// A session against a client that said exactly `abilities`.
fn with(roots: Vec<PathBuf>, abilities: ClientAbilities) -> Session {
Session::started(roots, abilities, ClientSettings::default())
}
/// A session whose client had already asked for
/// `lucisv.index.scope: "workspace"` when the startup scan ran — the
/// scope every session had before 2026-08-27.
///
/// Used by every test in this module whose subject is not the scope:
/// they want their whole fixture tree indexed from the first bar, and
/// saying so here keeps the folder scope from being a hidden variable
/// in a test about a progress report or a rename. The folder scope's
/// own behaviour is tested by the tests named in
/// `docs/features/index-scope/README.md`.
fn wide(roots: Vec<PathBuf>, file_watching: bool) -> Session {
Session::wide_with(roots, ClientAbilities { file_watching, ..Default::default() })
}
/// [`Session::wide`] against a client that said exactly `abilities`.
fn wide_with(roots: Vec<PathBuf>, abilities: ClientAbilities) -> Session {
let wide = ClientSettings {
index_scope: crate::settings::IndexScope::Workspace,
..Default::default()
};
Session::started(roots, abilities, wide)
}
fn started(
roots: Vec<PathBuf>,
abilities: ClientAbilities,
settings: ClientSettings,
) -> Session {
Session::started_in(roots, abilities, settings, None)
}
/// [`Session::started`] against a client that offered a storage
/// folder — `initializationOptions.storagePath`, which is where the
/// persistent index cache goes.
fn started_in(
roots: Vec<PathBuf>,
abilities: ClientAbilities,
settings: ClientSettings,
storage: Option<PathBuf>,
) -> Session {
let (server_end, client) = Connection::memory();
// Verbose off, which is how the server ships: every assertion in
// this module counts the messages a session produces, and the
// timing lines are tested where they are observable as protocol
// traffic — `tests/e2e.rs`, against the real binary and its flag.
//
// `wait: ZERO` is the client that never answers the settings pull:
// the request goes out and the startup scan runs at what this
// harness already put in `settings`, which is what every session in
// this module was before the startup was staged. The staging itself
// is tested in `startup.rs`, where the answer is queued.
let startup = Startup {
abilities,
client: settings,
storage,
verbose: false,
queued: Vec::new(),
wait: Duration::ZERO,
};
let server = Server::started(server_end, roots, startup);
Session { server, client }
}
/// [`Session::started`] against a client that had **already sent**
/// `queued` when the server was built.
///
/// The opening burst of a real editor: `initialized` is answered by
/// `initialize_finish`, and everything the client sent behind it is
/// sitting on the transport before the startup scan takes its first
/// file. That is the case
/// `docs/features/scan-interleave/README.md` is about, and the only
/// way to reach it is to put the messages there first.
fn started_behind(
roots: Vec<PathBuf>,
abilities: ClientAbilities,
settings: ClientSettings,
on_the_wire: Vec<Message>,
queued: Vec<Message>,
) -> Session {
let (server_end, client) = Connection::memory();
// Anything that has to reach the *connection* rather than the
// queue — an `exit`, which `handle_shutdown` reads for itself —
// goes here, ahead of the forwarder ever starting.
for message in on_the_wire {
client.sender.send(message).expect("the client's wire traffic");
}
let startup = Startup {
abilities,
client: settings,
storage: None,
verbose: false,
queued,
wait: Duration::ZERO,
};
let server = Server::started(server_end, roots, startup);
Session { server, client }
}
/// A session whose startup is **staged**: the settings pull goes out
/// first and the startup scan waits `wait` for the answer
/// (`server/startup.rs`). `queued` is what the client had already sent
/// when the server was built — the answer among it, for a client that
/// answers.
///
/// The settings start at the defaults, which is the whole point: what a
/// staged session indexes is what the *answer* said, not what a test put
/// in ahead of it.
fn staged(
roots: Vec<PathBuf>,
abilities: ClientAbilities,
verbose: bool,
wait: Duration,
queued: Vec<Message>,
) -> Session {
let (server_end, client) = Connection::memory();
let startup = Startup {
abilities,
client: ClientSettings::default(),
storage: None,
verbose,
queued,
wait,
};
Session { server: Server::started(server_end, roots, startup), client }
}
/// [`Session::wide`] against a client that spawned the server with
/// `--verbose` — the only sessions that are ever told what a scan spent
/// its time on (`docs/features/perf5-p4/README.md`).
fn verbose_wide(roots: Vec<PathBuf>, storage: Option<PathBuf>) -> Session {
let wide = ClientSettings {
index_scope: crate::settings::IndexScope::Workspace,
..Default::default()
};
let (server_end, client) = Connection::memory();
let startup = Startup {
abilities: ClientAbilities::default(),
client: wide,
storage,
verbose: true,
queued: Vec::new(),
wait: Duration::ZERO,
};
let server = Server::started(server_end, roots, startup);
Session { server, client }
}
fn notify(&mut self, method: &str, params: impl serde::Serialize) {
self.server.notification(Notification::new(method.to_string(), params));
}
/// Drive one request through the real dispatch, as the loop would.
fn request(&mut self, method: &str, params: impl serde::Serialize) -> Response {
let id = RequestId::from(format!("test-{method}"));
self.server.request(Request::new(id, method.to_string(), params))
}
/// A request's result, or the reason it was refused.
fn result(&mut self, method: &str, params: impl serde::Serialize) -> Value {
match self.request(method, params).response_result {
Ok(value) => value,
Err(error) => panic!("{method} failed: {error:?}"),
}
}
/// Answer the last request the server made of us.
fn answer(&mut self, id: RequestId, result: impl serde::Serialize) {
self.server.response(Response::new_ok(id, result));
}
/// Everything the server has said since the last drain.
fn drain(&self) -> Vec<Message> {
self.client.receiver.try_iter().collect()
}
/// The requests the server has made of the client, as (method, params).
fn requests(&self) -> Vec<(String, Value)> {
self.sent().into_iter().map(|request| (request.method, request.params)).collect()
}
/// The requests the server has made of the client, ids included.
fn sent(&self) -> Vec<Request> {
self.drain()
.into_iter()
.filter_map(|message| match message {
Message::Request(request) => Some(request),
_ => None,
})
.collect()
}
/// Every progress message since the last drain, in order, as
/// (step, token) — one `create` per request, one `begin`/`report`/`end`
/// per `$/progress`. Order and token are the whole protocol here.
fn progress(&self) -> Vec<(&'static str, String)> {
self.drain().into_iter().filter_map(progress_step).collect()
}
/// The `message` on every `$/progress` end since the last drain.
fn ended(&self) -> Vec<Option<String>> {
self.drain()
.into_iter()
.filter_map(|message| match message {
Message::Notification(n) if n.method == Progress::METHOD => {
let params: ProgressParams =
serde_json::from_value(n.params).expect("progress params");
let ProgressParamsValue::WorkDone(work) = params.value;
match work {
WorkDoneProgress::End(end) => Some(end.message),
_ => None,
}
}
_ => None,
})
.collect()
}
/// Every `$/progress` report since the last drain, as
/// (message, percentage) — what the bar was told to say and where to
/// stand.
fn reported(&self) -> Vec<(Option<String>, Option<u32>)> {
self.drain()
.into_iter()
.filter_map(|message| match message {
Message::Notification(n) if n.method == Progress::METHOD => {
let params: ProgressParams =
serde_json::from_value(n.params).expect("progress params");
let ProgressParamsValue::WorkDone(work) = params.value;
match work {
WorkDoneProgress::Report(report) => {
Some((report.message, report.percentage))
}
_ => None,
}
}
_ => None,
})
.collect()
}
/// Everything the server logged since the last drain, as
/// (type, message) — the client's output channel, in order.
fn logged(&self) -> Vec<(MessageType, String)> {
self.drain()
.into_iter()
.filter_map(|message| match message {
Message::Notification(n) if n.method == LogMessage::METHOD => {
let params: LogMessageParams =
serde_json::from_value(n.params).expect("log message params");
Some((params.typ, params.message))
}
_ => None,
})
.collect()
}
/// What the server showed the user since the last drain, as
/// (type, message).
fn shown(&self) -> Vec<(MessageType, String)> {
self.drain()
.into_iter()
.filter_map(|message| match message {
Message::Notification(n) if n.method == ShowMessage::METHOD => {
let params: ShowMessageParams =
serde_json::from_value(n.params).expect("show message params");
Some((params.typ, params.message))
}
_ => None,
})
.collect()
}
/// How many diagnostics publishes the server pushed since the last
/// drain. With exactly one open buffer this counts index rebuilds:
/// `reindex` republishes every open document, once.
fn publishes(&self) -> usize {
self.drain()
.iter()
.filter(|message| match message {
Message::Notification(n) => n.method == PublishDiagnostics::METHOD,
_ => false,
})
.count()
}
/// The diagnostics the server pushed since the last drain.
fn published(&self) -> Vec<PublishDiagnosticsParams> {
self.drain()
.into_iter()
.filter_map(|message| match message {
Message::Notification(n) if n.method == PublishDiagnostics::METHOD => {
Some(serde_json::from_value(n.params).expect("publish params"))
}
_ => None,
})
.collect()
}
fn open(&mut self, path: &Path, text: &str) -> Uri {
let uri = path_to_uri(path).expect("uri");
self.notify(
DidOpenTextDocument::METHOD,
serde_json::json!({
"textDocument": {
"uri": uri, "languageId": "systemverilog",
"version": 1, "text": text,
}
}),
);
uri
}
/// Drive one burst through the real loop body — the whole of `run`
/// except the receiving — reporting whether the client shut us down.
fn batch(&mut self, messages: Vec<Message>) -> bool {
self.server.process_batch(messages).expect("the burst is handled")
}
/// The responses the server sent since the last drain, in order.
fn answers(&self) -> Vec<Response> {
self.drain()
.into_iter()
.filter_map(|message| match message {
Message::Response(response) => Some(response),
_ => None,
})
.collect()
}
fn watched(&mut self, paths: &[PathBuf]) {
let changes: Vec<FileEvent> = paths
.iter()
.map(|path| FileEvent {
uri: path_to_uri(path).expect("uri"),
typ: FileChangeType::CHANGED,
})
.collect();
self.notify(DidChangeWatchedFiles::METHOD, DidChangeWatchedFilesParams { changes });
}
}
/// One message's place in the progress protocol, or `None` when it is not
/// progress at all.
fn progress_step(message: Message) -> Option<(&'static str, String)> {
match message {
Message::Request(request) if request.method == WorkDoneProgressCreate::METHOD => {
let params: WorkDoneProgressCreateParams =
serde_json::from_value(request.params).expect("create params");
Some(("create", token_text(&params.token)))
}
Message::Notification(n) if n.method == Progress::METHOD => {
let params: ProgressParams = serde_json::from_value(n.params).expect("progress params");
let ProgressParamsValue::WorkDone(work) = params.value;
let step = match work {
WorkDoneProgress::Begin(_) => "begin",
WorkDoneProgress::Report(_) => "report",
WorkDoneProgress::End(_) => "end",
};
Some((step, token_text(&params.token)))
}
_ => None,
}
}
fn token_text(token: &ProgressToken) -> String {
match token {
ProgressToken::String(text) => text.clone(),
ProgressToken::Number(number) => number.to_string(),
}
}
/// A client that shows a progress bar and nothing else.
fn watching_progress() -> ClientAbilities {
ClientAbilities { work_done_progress: true, ..Default::default() }
}
// ----------------------------------------------------------------------
// helpers more than one file uses
// ----------------------------------------------------------------------
const SUB: &str = "module sub (\n input logic clk,\n input logic rst\n);\nendmodule\n";
const TOP: &str = "module top;\n logic clk, rst;\n sub u_sub (.clk(clk));\nendmodule\n";
/// One `didChange`, carrying whatever changes were given. The flush at the
/// end is the quiet-period timer firing: a test drives notifications one
/// at a time, so the burst the loop would have coalesced never forms, and
/// without this the buffer would sit dirty forever.
fn change(session: &mut Session, uri: &Uri, version: u32, changes: Value) {
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": version },
"contentChanges": changes,
}),
);
session.server.flush_dirty();
}
/// The text the server currently holds for a buffer — the newest applied
/// text, which while a change sits dirty is the pending one.
fn buffer(session: &Session, uri: &Uri) -> String {
if let Some((_, text)) = session.server.dirty.iter().find(|(pending, _)| pending == uri) {
return text.clone();
}
session.server.workspace.document(uri).expect("an open buffer").text.clone()
}
/// A whole-buffer `didChange`, queued.
fn changed(uri: &Uri, version: u32, text: &str) -> Message {
Message::Notification(Notification::new(
DidChangeTextDocument::METHOD.to_string(),
serde_json::json!({
"textDocument": { "uri": uri, "version": version },
"contentChanges": [{ "text": text }],
}),
))
}
/// The `didChangeConfiguration` push that sets the index size cap.
///
/// It carries `scope: "workspace"` because a push replaces *every*
/// setting: a cap pushed on its own would take the index back to the
/// folder scope in the same breath, which is not what a test about the cap
/// is asking. Same reason `state.rs`'s `wide()` exists.
fn capping(bytes: u64) -> serde_json::Value {
serde_json::json!({
"settings": {
"lucisv": { "index": { "maxFileSize": bytes, "scope": "workspace" } }
}
})
}
/// A client that pulls diagnostics rather than being pushed them.
fn pulling() -> ClientAbilities {
ClientAbilities { pull_diagnostics: true, ..Default::default() }
}
fn document_pull(session: &mut Session, uri: &Uri, previous: Option<&str>) -> Value {
session.result(
DocumentDiagnosticRequest::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"identifier": diagnostics::SOURCE,
"previousResultId": previous,
}),
)
}
/// How many times the index holds a package of this name.
fn indexed(session: &Session, name: &str) -> usize {
session.server.workspace.index().member(name, "K").len()
}
/// A `lucisv.filelist` push, in the shape a client sends it.
fn filelist_push(path: &str) -> Value {
serde_json::json!({ "settings": { "lucisv": { "filelist": path } } })
}
/// Settings a test uses when its subject is not the scope, spelled once.
fn wide_ish() -> ClientSettings {
ClientSettings { index_scope: crate::settings::IndexScope::Workspace, ..Default::default() }
}
/// A workspace holding `sub` and two instantiations of it, with `sub.sv`
/// open — the shape every lens test below asks about.
fn lens_tree(name: &str) -> Tree {
let tree = Tree::new(name);
tree.write("sub.sv", "module sub;\nendmodule\n");
tree.write("top.sv", "module top;\n sub u_a ();\n sub u_b ();\nendmodule\n");
tree
}
/// A two-module workspace with `top.sv` open, and the arguments that ask
/// for the one port its instantiation is missing.
fn propagating(name: &str, abilities: ClientAbilities) -> (Tree, Session, Value) {
let tree = Tree::new(name);
tree.write("sub.sv", SUB);
tree.write("top.sv", TOP);
let mut session = Session::with(vec![tree.path.clone()], abilities);
let uri = session.open(&tree.path.join("top.sv"), TOP);
let _ = session.drain();
let params = serde_json::json!({
"command": ports::PROPAGATE_PORTS,
"arguments": [uri, { "line": 2, "character": 6 }],
});
(tree, session, params)
}
/// What `textDocument/formatting` answers for the same buffer, asking for
/// the 2-space tab an editor defaults to — which is also the built-in
/// indent, so the two paths resolve to the same settings.
fn formatting_result(session: &mut Session, uri: &Uri) -> Value {
session.result(
Formatting::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"options": { "tabSize": 2, "insertSpaces": true },
}),
)
}
/// The id of the one outstanding `workspace/configuration`, and the params
/// it went out with.
fn configuration_request(session: &Session) -> (RequestId, Value) {
let sent = session.sent();
let asked: Vec<&Request> =
sent.iter().filter(|r| r.method == WorkspaceConfiguration::METHOD).collect();
assert_eq!(asked.len(), 1, "exactly one pull is outstanding: {sent:#?}");
(asked[0].id.clone(), asked[0].params.clone())
}