Files
lucisv/crates/lucisv_server/src/watch.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

303 lines
12 KiB
Rust

//! `workspace/didChangeWatchedFiles`: the index's answer to changes lucisv never
//! saw an editor make.
//!
//! Until this, the index was rebuilt on save and (with no workspace root) on
//! open — so a `git pull`, a branch checkout, a generated file, or an edit to
//! the `.f` filelist itself stayed invisible until the user happened to save
//! something. The client already watches the disk for its own reasons; this
//! module asks it to say what it sees. See
//! `docs/features/file-watching/README.md`.
use std::path::{Path, PathBuf};
use lsp_types::notification::{DidChangeWatchedFiles, Notification as _};
use lsp_types::{
DidChangeWatchedFilesRegistrationOptions, FileEvent, FileSystemWatcher, GlobPattern,
InitializeParams, Registration, Unregistration,
};
use lucisv_core::walk::EXTENSIONS;
use crate::uri::uri_to_path;
/// Every source file the workspace walk would take, in one glob.
///
/// Deliberately the same four extensions as `lucisv_core::walk::EXTENSIONS` and
/// nothing else: a watcher wide enough to cover a build directory or a
/// `target/` tree would hand us thousands of events that cannot change the
/// index. `pinned_to_the_extensions_the_walk_takes` asserts the two agree.
pub const SOURCE_GLOB: &str = "**/*.{v,vh,sv,svh}";
/// Whether the client can be asked to watch files at all.
///
/// The protocol has no static form of this capability — a server that wants
/// file events must register for them, and a client that did not advertise
/// dynamic registration cannot be asked. Such a client simply keeps the
/// save-only staleness model it had before this feature.
pub fn dynamic_registration(params: &InitializeParams) -> bool {
params
.capabilities
.workspace
.as_ref()
.and_then(|workspace| workspace.did_change_watched_files.as_ref())
.and_then(|watched| watched.dynamic_registration)
.unwrap_or(false)
}
/// The registration to send as `client/registerCapability`: the source glob,
/// plus the configured filelist's own path when there is one.
///
/// `serial` numbers the registration so a later one can unregister it by name;
/// a re-registration is what a change of `lucisv.filelist` needs, because the
/// path being watched is part of the registration itself.
///
/// No `kind` is set on either watcher, which the protocol defines as
/// create|change|delete — all three matter here, since a file appearing and a
/// file vanishing move the index exactly as much as one being rewritten.
pub fn registration(serial: u32, filelist: Option<&Path>) -> Registration {
let options = DidChangeWatchedFilesRegistrationOptions { watchers: watchers(filelist) };
Registration {
id: registration_id(serial),
method: DidChangeWatchedFiles::METHOD.to_string(),
// Cannot fail for this shape (no non-string map keys, no floats), and
// a `None` here would register a watcher for nothing rather than
// corrupt anything — so there is nothing to report and nobody to
// report it to.
register_options: serde_json::to_value(options).ok(),
}
}
/// Undo a previous `registration`, by the id it carried.
pub fn unregistration(id: String) -> Unregistration {
Unregistration { id, method: DidChangeWatchedFiles::METHOD.to_string() }
}
/// The watchers a registration carries: sources always, the filelist when the
/// project has one.
///
/// The filelist is watched by its own absolute path rather than by a `*.f`
/// glob: a filelist can be called anything (`files.list`, `srcs.txt`), and a
/// glob wide enough for every name would also fire on every unrelated `.f` in
/// the tree. A path that is not valid UTF-8 cannot be written as a glob and is
/// simply not watched — the same restriction `uri.rs` already lives under.
fn watchers(filelist: Option<&Path>) -> Vec<FileSystemWatcher> {
let mut watchers = vec![watcher(SOURCE_GLOB.to_string())];
if let Some(pattern) = filelist.and_then(|path| path.to_str()) {
watchers.push(watcher(pattern.to_string()));
}
watchers
}
fn watcher(pattern: String) -> FileSystemWatcher {
FileSystemWatcher { glob_pattern: GlobPattern::String(pattern), kind: None }
}
fn registration_id(serial: u32) -> String {
format!("lucisv-watched-files-{serial}")
}
/// Whether a notification's events touch anything the index reads.
///
/// Asked **once per notification**, not once per file: a branch checkout
/// arrives as one notification carrying hundreds of events, and rebuilding per
/// event would re-scan the workspace hundreds of times for one answer.
///
/// The client's globs already filter, but a client is free to send more than
/// it was asked for (some watch a whole workspace and forward everything), and
/// a stray `.txt` must not cost a workspace re-scan.
pub fn touches_scope(changes: &[FileEvent], filelist: Option<&Path>) -> bool {
changes
.iter()
.filter_map(|change| uri_to_path(&change.uri))
.any(|path| watched(&path, filelist))
}
/// Every path an event named that the index reads, each once and in order —
/// or `None` when one of them is the filelist, whose change moves the whole
/// scope and is a rebuild by definition. A client is free to send `Changed`
/// and `Created` for one file, and that is still one file.
///
/// What `server/index.rs`'s `reindex_watched` sorts into held, outside and
/// unknown files (`docs/features/localized-reindex/README.md`); until
/// 2026-11-19 this was `one_scope_file`, which gave up on any list longer
/// than one.
pub fn scope_files(changes: &[FileEvent], filelist: Option<&Path>) -> Option<Vec<PathBuf>> {
let mut named: Vec<PathBuf> = changes
.iter()
.filter_map(|change| uri_to_path(&change.uri))
.filter(|path| watched(path, filelist))
.collect();
named.sort();
named.dedup();
(!named.iter().any(|path| Some(path.as_path()) == filelist)).then_some(named)
}
/// Whether an event names a `lucisv.toml` (either spelling) — a change to
/// which moves the scope's excludes and filelist and the lint configuration
/// together. The names are `lucisv_core::config::NAMES`, the CLI's own.
pub fn names_a_config(changes: &[FileEvent]) -> bool {
changes.iter().filter_map(|change| uri_to_path(&change.uri)).any(|path| {
let name = path.file_name().and_then(|n| n.to_str());
name.is_some_and(|n| lucisv_core::config::NAMES.contains(&n))
})
}
/// Whether one path is something the index reads: a source file, or the
/// filelist that decides which source files there are.
///
/// Public since 2026-08-27 for `file_ops.rs`: `didRenameFiles`/`didDeleteFiles`
/// nudge the index for exactly the paths a watcher event would, and two copies
/// of that test would drift.
pub fn watched(path: &Path, filelist: Option<&Path>) -> bool {
if filelist == Some(path) {
return true;
}
let extension = path.extension().and_then(|e| e.to_str()).unwrap_or_default();
EXTENSIONS.contains(&extension)
}
#[cfg(test)]
mod tests {
use super::*;
use lsp_types::{
ClientCapabilities, DidChangeWatchedFilesClientCapabilities, FileChangeType, Uri,
WorkspaceClientCapabilities,
};
use std::path::PathBuf;
use std::str::FromStr;
fn saying(dynamic_registration: Option<bool>) -> InitializeParams {
InitializeParams {
capabilities: ClientCapabilities {
workspace: Some(WorkspaceClientCapabilities {
did_change_watched_files: Some(DidChangeWatchedFilesClientCapabilities {
dynamic_registration,
relative_pattern_support: None,
}),
..Default::default()
}),
..Default::default()
},
..Default::default()
}
}
#[test]
fn only_a_client_that_says_so_is_asked_to_watch() {
assert!(!dynamic_registration(&InitializeParams::default()), "silence means no");
assert!(!dynamic_registration(&saying(None)), "an empty capability means no");
assert!(!dynamic_registration(&saying(Some(false))));
assert!(dynamic_registration(&saying(Some(true))));
}
#[test]
fn the_registration_is_the_shape_the_protocol_asks_for() {
// Pinned as JSON, because this is what goes on the wire and a client
// that cannot read it watches nothing at all — silently.
let value = serde_json::to_value(registration(0, None)).expect("json");
assert_eq!(
value,
serde_json::json!({
"id": "lucisv-watched-files-0",
"method": "workspace/didChangeWatchedFiles",
"registerOptions": { "watchers": [{ "globPattern": "**/*.{v,vh,sv,svh}" }] },
})
);
}
#[test]
fn a_configured_filelist_is_watched_by_its_own_path() {
let value =
serde_json::to_value(registration(2, Some(Path::new("/p/files.f")))).expect("json");
assert_eq!(
value,
serde_json::json!({
"id": "lucisv-watched-files-2",
"method": "workspace/didChangeWatchedFiles",
"registerOptions": { "watchers": [
{ "globPattern": "**/*.{v,vh,sv,svh}" },
{ "globPattern": "/p/files.f" },
] },
})
);
}
#[test]
fn no_filelist_means_no_second_watcher() {
assert_eq!(watchers(None).len(), 1, "sources only");
assert_eq!(watchers(Some(Path::new("/p/files.f"))).len(), 2, "and the filelist");
}
#[test]
fn an_unregistration_names_the_same_id_and_method() {
let registration = registration(7, None);
let undo = unregistration(registration.id.clone());
assert_eq!(undo.id, "lucisv-watched-files-7");
assert_eq!(undo.method, registration.method);
}
#[test]
fn the_glob_is_pinned_to_the_extensions_the_walk_takes() {
// A file the walk indexes but the glob does not name is a file whose
// external changes are invisible; the reverse is wasted rebuilds.
for extension in EXTENSIONS {
assert!(
SOURCE_GLOB.contains(&format!("{extension},"))
|| SOURCE_GLOB.contains(&format!("{extension}}}")),
"{extension} is not in {SOURCE_GLOB}"
);
}
assert_eq!(EXTENSIONS.len(), 4, "a fifth extension needs a wider glob");
}
fn event(path: &str) -> FileEvent {
FileEvent {
uri: Uri::from_str(&format!("file://{path}")).expect("uri"),
typ: FileChangeType::CHANGED,
}
}
#[test]
fn a_source_file_event_asks_for_a_rebuild() {
for name in ["/p/a.sv", "/p/a.v", "/p/a.svh", "/p/a.vh"] {
assert!(touches_scope(&[event(name)], None), "{name}");
}
}
#[test]
fn an_unrelated_extension_does_not() {
// The stray-event case: a client that forwards more than it was asked
// for must not cost a workspace re-scan per keystroke in a README.
assert!(!touches_scope(&[event("/p/notes.txt")], None));
assert!(!touches_scope(&[event("/p/target/build.log")], None));
assert!(!touches_scope(&[event("/p/files.f")], None), "an unconfigured filelist");
assert!(!touches_scope(&[], None), "and an empty notification");
}
#[test]
fn the_configured_filelist_asks_for_a_rebuild() {
let filelist = PathBuf::from("/p/files.f");
assert!(touches_scope(&[event("/p/files.f")], Some(&filelist)));
assert!(!touches_scope(&[event("/p/other.f")], Some(&filelist)), "not another one");
}
#[test]
fn one_relevant_event_among_many_is_enough() {
// The `git checkout` shape: one notification, a long list, one answer.
let mut changes: Vec<FileEvent> =
(0..200).map(|i| event(&format!("/p/n{i}.txt"))).collect();
assert!(!touches_scope(&changes, None));
changes.push(event("/p/rtl/top.sv"));
assert!(touches_scope(&changes, None));
}
#[test]
fn a_non_file_uri_is_ignored_rather_than_guessed_at() {
let event = FileEvent {
uri: Uri::from_str("untitled:Untitled-1").expect("uri"),
typ: FileChangeType::CREATED,
};
assert!(!touches_scope(&[event], None));
}
}