diff --git a/TODO.md b/TODO.md index 6ac3001..fc29a9e 100644 --- a/TODO.md +++ b/TODO.md @@ -750,6 +750,16 @@ and are not gaps. — the rescan is one opaque call — and the `end` names the indexed file count, read off the index's own file list. The bar covers the scan, ending before the scope warnings and the republishes. + → **Superseded in part, 2026-08-27**: the rescan is no longer opaque. + `docs/features/indexing-ux/README.md` adds + `vlog_semantic::IndexBuilder`/`index_order`, so the bar now carries + `n/total file.sv` and a counted percentage (throttled to at most + 1000 reports per rescan), a per-file `window/logMessage` under + `lucisv.index.logFiles`, and a 1 MiB default walk-file size cap under + `lucisv.index.maxFileSize` whose skips the `end` message counts. + Everything else above — the capability gate, the token scheme, the + create's ignored answer, the ordering against the republish — is + unchanged. - [x] **`$/cancelRequest`** — the loop handles requests sequentially and ignores cancellation; at minimum answer already-cancelled queued requests with `RequestCancelled`. diff --git a/crates/lucisv_server/src/server.rs b/crates/lucisv_server/src/server.rs index 35160f9..12e2e58 100644 --- a/crates/lucisv_server/src/server.rs +++ b/crates/lucisv_server/src/server.rs @@ -11,6 +11,7 @@ use std::collections::{HashMap, HashSet}; use std::error::Error; +use std::path::Path; use lsp_server::{Connection, ExtractError, Message, Notification, Request, RequestId, Response}; use lsp_types::notification::{ @@ -55,15 +56,17 @@ use lsp_types::{ ShowMessageParams, SignatureHelpParams, TextDocumentPositionParams, TypeHierarchyPrepareParams, TypeHierarchySubtypesParams, TypeHierarchySupertypesParams, UnchangedDocumentDiagnosticReport, UnregistrationParams, Uri, WillSaveTextDocumentParams, WorkDoneProgress, WorkDoneProgressBegin, - WorkDoneProgressCreateParams, WorkDoneProgressEnd, WorkspaceDiagnosticParams, - WorkspaceDiagnosticReport, WorkspaceDiagnosticReportResult, WorkspaceDocumentDiagnosticReport, - WorkspaceEdit, WorkspaceFolder, WorkspaceFullDocumentDiagnosticReport, WorkspaceSymbolParams, - WorkspaceSymbolResponse, WorkspaceUnchangedDocumentDiagnosticReport, + WorkDoneProgressCreateParams, WorkDoneProgressEnd, WorkDoneProgressReport, + WorkspaceDiagnosticParams, WorkspaceDiagnosticReport, WorkspaceDiagnosticReportResult, + WorkspaceDocumentDiagnosticReport, WorkspaceEdit, WorkspaceFolder, + WorkspaceFullDocumentDiagnosticReport, WorkspaceSymbolParams, WorkspaceSymbolResponse, + WorkspaceUnchangedDocumentDiagnosticReport, }; use serde::de::DeserializeOwned; use serde_json::Value; -use crate::state::Workspace; +use crate::settings::ClientSettings; +use crate::state::{IndexEvent, Workspace}; use crate::{ code_action, completion, diagnostics, file_ops, folding, format, hierarchy, hover, includes, inlay, inline, lens, linked, nav, on_type, pairs, ports, rename, selection, settings, @@ -201,8 +204,15 @@ impl Server { // first index build is the slowest one of the session, so it gets the // same bar every later rescan gets. let bar = server.begin_indexing(); - let warnings = server.workspace.open_roots(roots); - server.end_indexing(bar); + // The fields are split apart because the watcher writes to the + // connection while the workspace is borrowed mutably for the rebuild + // it is watching. The same two operations on the same value, in the + // same order, as the one-line call they replace. + let Server { connection, workspace, .. } = &mut server; + let mut watch = IndexWatch::new(connection, bar.as_ref(), workspace.client_settings()); + let warnings = workspace.open_roots_with(roots, &mut |event| watch.see(event)); + let skipped = watch.skipped; + server.end_indexing(bar, skipped); server.report_scope(warnings); server.register_watchers(); // The pull half of the settings model. Asked here because this is the @@ -1298,8 +1308,14 @@ impl Server { /// or a file the client renamed or deleted. fn reindex(&mut self) { let bar = self.begin_indexing(); - let warnings = self.workspace.rebuild_index(); - self.end_indexing(bar); + // Split apart for the same reason `Server::new` splits them: the + // watcher writes to the connection throughout a rebuild that holds the + // workspace mutably. + let Server { connection, workspace, .. } = self; + let mut watch = IndexWatch::new(connection, bar.as_ref(), workspace.client_settings()); + let warnings = workspace.rebuild_index_with(&mut |event| watch.see(event)); + let skipped = watch.skipped; + self.end_indexing(bar, skipped); // A rescan can change any module's instantiation count, so every lens // a client is holding may now read wrong. Sent after the bar comes // down, for the same reason the bar comes down before the republishes: @@ -1325,8 +1341,10 @@ impl Server { /// is over. The spec allows it, and a client that errors the `create` /// ignores the `$/progress` that follows. /// - /// No percentage and no intermediate report: the rescan is one opaque call - /// into `Workspace`, and an invented percentage is worse than none. + /// The `begin` carries no percentage: the first one that means anything + /// is the first file's, and it is `IndexWatch` that sends it. Every + /// percentage from there on is measured — `n` files of a work list whose + /// length was known before the first parse — never invented. fn begin_indexing(&mut self) -> Option { if !self.abilities.work_done_progress { return None; @@ -1356,11 +1374,19 @@ impl Server { /// know. Called the moment the rescan returns, before the scope warnings /// and the republishes — the bar names the scan, and what follows it is /// per-open-buffer work the user already pays on every keystroke. - fn end_indexing(&self, token: Option) { + /// + /// `skipped` is how many files the size cap kept out, and it is named here + /// whether or not the per-file log is on: the log is the *detail*, and a + /// user who turned it off should still learn that part of their workspace + /// is not in the index. + fn end_indexing(&self, token: Option, skipped: usize) { let Some(token) = token else { return }; let files = self.workspace.index().files().len(); let plural = if files == 1 { "" } else { "s" }; - let message = Some(format!("{files} file{plural} indexed")); + let message = Some(match skipped { + 0 => format!("{files} file{plural} indexed"), + _ => format!("{files} file{plural} indexed, {skipped} skipped"), + }); self.progress(token, WorkDoneProgress::End(WorkDoneProgressEnd { message })); } @@ -1382,8 +1408,7 @@ impl Server { /// One `$/progress` notification for a token the client already knows. fn progress(&self, token: ProgressToken, value: WorkDoneProgress) { - let params = ProgressParams { token, value: ProgressParamsValue::WorkDone(value) }; - self.notify(Progress::METHOD, params); + progress_on(&self.connection, &token, value); } /// Say what went wrong while working out which files to index — a @@ -1460,10 +1485,7 @@ impl Server { } fn notify(&self, method: &str, params: impl serde::Serialize) { - let notification = Notification::new(method.to_string(), params); - // A closed channel means the client is gone; there is nobody left to - // report the failure to. - let _ = self.connection.sender.send(Message::Notification(notification)); + notify_on(&self.connection, method, params); } /// The byte offset an LSP position names in an open document. @@ -1472,6 +1494,174 @@ impl Server { } } +// ---------------------------------------------------------------------- +// watching an index rebuild +// ---------------------------------------------------------------------- + +/// How many `$/progress` reports one rescan may send. +/// +/// One per file is right for the workspaces people actually have — the 860-file +/// corpus is 860 small notifications across two thirds of a second — but a +/// 40,000-file filelist would be 40,000 of them on every save. Past this many +/// files the reports thin out to every ⌈total/1000⌉-th, which still moves the +/// bar by a tenth of a percent at a time: under a pixel. +const MAX_REPORTS: usize = 1000; + +/// Whether the file numbered `done` (from 0) of `total` gets a `report`. +/// +/// The last file always reports, so a rescan's final bar position is always +/// `total/total` at 100%. Without that, a 10,000-file scan would stop +/// reporting at 10,000 exactly — but a 10,001-file one would stop at 10,000 +/// and leave the bar a file short of the work it had finished. +fn reports(done: usize, total: usize) -> bool { + let step = total.div_ceil(MAX_REPORTS).max(1); + (done + 1).is_multiple_of(step) || done + 1 == total +} + +/// Watches one index rebuild: a `$/progress` report and a log line per file, +/// and a count of the files the size cap skipped. +/// +/// Holds the connection rather than the `Server`, because the workspace is +/// borrowed mutably for the whole of the rebuild being watched. Everything it +/// sends is a notification, so nothing here can fail in a way a caller could +/// act on. +struct IndexWatch<'a> { + connection: &'a Connection, + /// The bar to report against — `None` for a client that cannot show one, + /// which is the same gate `begin_indexing` applied. + bar: Option<&'a ProgressToken>, + /// `lucisv.index.logFiles`: whether the per-file lines are sent at all. + log_files: bool, + /// How many files the size cap kept out of this rebuild. Counted whether + /// or not the log is on, because the end message names it either way. + skipped: usize, +} + +impl<'a> IndexWatch<'a> { + fn new( + connection: &'a Connection, + bar: Option<&'a ProgressToken>, + settings: &ClientSettings, + ) -> IndexWatch<'a> { + IndexWatch { connection, bar, log_files: settings.log_files, skipped: 0 } + } + + /// Report one thing the rebuild just did. + fn see(&mut self, event: IndexEvent) { + match event { + IndexEvent::Parsing { done, total, path } => { + self.say(format!("indexing: {}", path.display())); + self.tick(done, total, path); + } + IndexEvent::Skipped { path, size, cap } => { + self.skipped += 1; + self.say(format!( + "skipped ({} > {} cap): {}", + human_size(size), + human_size(cap), + path.display() + )); + } + } + } + + /// Move the bar to `done + 1` of `total`, if this file is one of the ones + /// that reports. + /// + /// The message names the file rather than its path: the bar is a strip of + /// status bar a few dozen characters wide, and the path is in the log for + /// anyone who wants it. The percentage is `(done + 1) / total`, which + /// only ever counts up. + fn tick(&self, done: usize, total: usize, path: &Path) { + let Some(token) = self.bar else { return }; + if !reports(done, total) { + return; + } + let name = path.file_name().unwrap_or(path.as_os_str()).to_string_lossy(); + let report = WorkDoneProgressReport { + cancellable: Some(false), + message: Some(format!("{}/{total} {name}", done + 1)), + // `total` cannot be 0 here — this is called from inside the loop + // over the files — but a percentage is not worth a division that + // has to be argued about. + percentage: Some(((done + 1) * 100 / total.max(1)) as u32), + }; + progress_on(self.connection, token, WorkDoneProgress::Report(report)); + } + + /// One line in the client's output channel, if the user left the file log + /// on. + /// + /// `MessageType::LOG`, unprefixed: these are hundreds of lines per rescan + /// in a channel that is already this server's, and "lucisv: " on every one + /// of them would be noise plus traffic. The scope warnings, which are + /// rare and also shown in a popup, keep their prefix. + fn say(&self, message: String) { + if !self.log_files { + return; + } + let params = LogMessageParams { typ: MessageType::LOG, message }; + notify_on(self.connection, LogMessage::METHOD, params); + } +} + +/// A byte count in the largest unit that keeps it readable. +/// +/// The cap is written in bytes and can be set to anything, so a fixed unit is +/// wrong at one end or the other: "0.0 MiB > 0.0 MiB cap" says nothing about a +/// 4 KiB file under a 1 KiB cap, and "4194304 B" says nothing quickly about a +/// netlist. +fn human_size(bytes: u64) -> String { + const KIB: f64 = 1024.0; + const MIB: f64 = KIB * 1024.0; + // The unit is chosen by what the ROUNDED number reads as, not the raw + // size: 1 048 575 bytes is "1.0 MiB", never "1024.0 KiB" (QA log, + // 2026-08-27 — the same class of bug the e2e's "0.0 MiB > 0.0 MiB" + // caught at the opposite edge). + let size = bytes as f64; + if size < KIB { + format!("{bytes} B") + } else if (size / KIB).round() < KIB { + format!("{:.1} KiB", size / KIB) + } else { + format!("{:.1} MiB", size / MIB) + } +} + +#[cfg(test)] +mod human_size_tests { + use super::human_size; + + #[test] + fn the_unit_is_chosen_by_what_the_rounded_number_reads_as() { + // QA finding, 2026-08-27: a byte short of a MiB must not print as + // "1024.0 KiB". The unit flips when the smaller unit's rounded + // number would read as the next unit. + assert_eq!(human_size(1_048_575), "1.0 MiB"); + assert_eq!(human_size(1_048_576), "1.0 MiB"); + assert_eq!(human_size(1023), "1023 B"); + assert_eq!(human_size(1024), "1.0 KiB"); + assert_eq!(human_size(4_096), "4.0 KiB"); + assert_eq!(human_size(2_411_724), "2.3 MiB"); + } +} + +/// One `$/progress` notification, on a connection rather than through a +/// `Server` — what the index watcher has while the workspace is borrowed. +fn progress_on(connection: &Connection, token: &ProgressToken, value: WorkDoneProgress) { + let params = + ProgressParams { token: token.clone(), value: ProgressParamsValue::WorkDone(value) }; + notify_on(connection, Progress::METHOD, params); +} + +/// One notification, on a connection rather than through a `Server`. +fn notify_on(connection: &Connection, method: &str, params: impl serde::Serialize) { + let notification = Notification::new(method.to_string(), params); + // A closed channel means the client is gone; there is nobody left to + // report the failure to. + let _ = connection.sender.send(Message::Notification(notification)); +} + // ---------------------------------------------------------------------- // cancellation // ---------------------------------------------------------------------- @@ -1733,6 +1923,45 @@ mod tests { .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, Option)> { + 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)> { @@ -1861,11 +2090,14 @@ mod tests { let tree = Tree::new("progressstartup"); tree.package("rtl/a.sv", "a"); let session = Session::with(vec![tree.path.clone()], watching_progress()); + // One `report` because the tree holds one file: the counting reports + // this round added ride the same path the begin/end pair does. assert_eq!( session.progress(), vec![ ("create", "lucisv-index-0".to_string()), ("begin", "lucisv-index-0".to_string()), + ("report", "lucisv-index-0".to_string()), ("end", "lucisv-index-0".to_string()), ] ); @@ -1883,13 +2115,14 @@ mod tests { DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }), ); - // One create, one begin, one end — the save's own token, not the - // startup one. + // One create, one begin, one report per file, one end — the save's own + // token, not the startup one. assert_eq!( session.progress(), vec![ ("create", "lucisv-index-1".to_string()), ("begin", "lucisv-index-1".to_string()), + ("report", "lucisv-index-1".to_string()), ("end", "lucisv-index-1".to_string()), ] ); @@ -1912,6 +2145,69 @@ mod tests { assert_eq!(session.ended(), vec![Some("1 file indexed".to_string())], "not `1 files`"); } + #[test] + fn the_bar_counts_the_files_as_it_goes() { + // The whole of feature 2: how many of how many, which file, and a + // percentage that was measured rather than guessed. + let tree = Tree::new("progressreports"); + tree.package("rtl/a.sv", "a"); + tree.package("rtl/b.sv", "b"); + let session = Session::with(vec![tree.path.clone()], watching_progress()); + assert_eq!( + session.reported(), + vec![ + (Some("1/2 a.sv".to_string()), Some(50)), + (Some("2/2 b.sv".to_string()), Some(100)), + ], + "counts ascending, the file named, the percentage monotonic and ending at 100" + ); + } + + #[test] + fn the_reports_thin_out_when_the_workspace_is_huge() { + // A report per file is right for hundreds and wrong for tens of + // thousands. Past `MAX_REPORTS` files they thin out — but the last + // file always reports, so the bar always finishes where the work did. + let tree = Tree::new("progressflood"); + let files = MAX_REPORTS + 100; + for i in 0..files { + tree.package(&format!("f{i:05}.sv",), &format!("p{i}")); + } + let session = Session::with(vec![tree.path.clone()], watching_progress()); + let reports = session.reported(); + assert!(reports.len() <= MAX_REPORTS, "{} reports for {files} files", reports.len()); + assert!(reports.len() > MAX_REPORTS / 2, "but not silence: {}", reports.len()); + + let percentages: Vec = reports.iter().filter_map(|(_, p)| *p).collect(); + assert_eq!(percentages.len(), reports.len(), "every report carries one"); + assert!(percentages.windows(2).all(|w| w[0] <= w[1]), "monotonic: {percentages:?}"); + assert_eq!(percentages.last(), Some(&100), "and it ends at 100"); + let last = reports.last().expect("a report").0.clone().expect("a message"); + assert!(last.starts_with(&format!("{files}/{files} ")), "the last file reports: {last}"); + } + + #[test] + fn the_report_schedule_never_floods_and_never_stops_short() { + // The rule itself, across both regimes and their boundary — cheaper to + // check exhaustively here than to build 40,000 files. + for total in [1, 2, 999, 1000, 1001, 1999, 2000, 12_345, 40_000] { + let reporting: Vec = (0..total).filter(|d| reports(*d, total)).collect(); + assert!(!reporting.is_empty(), "{total} files must report something"); + assert!(reporting.len() <= MAX_REPORTS, "{total} files: {} reports", reporting.len()); + assert_eq!( + reporting.last(), + Some(&(total - 1)), + "{total} files: the last file must report" + ); + assert!(reporting.windows(2).all(|w| w[0] < w[1]), "{total}: strictly ascending"); + // The percentage a client sees only ever counts up, and lands on + // 100 exactly once, at the end. + let percentages: Vec = reporting.iter().map(|d| (d + 1) * 100 / total).collect(); + assert!(percentages.windows(2).all(|w| w[0] <= w[1]), "{total}: monotonic"); + assert_eq!(percentages.last(), Some(&100), "{total}: ends at 100"); + } + } + #[test] fn the_bar_is_down_before_the_republish() { // Pinned because either order is defensible and a reader would @@ -1938,7 +2234,170 @@ mod tests { _ => progress_step(message).map(|(step, _)| step.to_string()), }) .collect(); - assert_eq!(order, vec!["create", "begin", "end", "publish"]); + assert_eq!(order, vec!["create", "begin", "report", "end", "publish"]); + } + + /// A tree with one file the default cap would keep and one it would not. + /// The big one is padded with a trailing comment, so what makes it big is + /// not what makes it a package. + fn oversized_tree(name: &str) -> Tree { + let tree = Tree::new(name); + tree.package("rtl/keep.sv", "keep_pkg"); + let head = "package netlist_pkg;\n localparam K = 1;\nendpackage\n// "; + let mut text = String::from(head); + while text.len() < 4096 { + text.push('x'); + } + text.push('\n'); + tree.write("rtl/netlist.sv", &text); + tree + } + + /// The `didChangeConfiguration` push that sets the index size cap. + fn capping(bytes: u64) -> serde_json::Value { + serde_json::json!({ "settings": { "lucisv": { "index": { "maxFileSize": bytes } } } }) + } + + #[test] + fn the_end_message_names_what_the_cap_skipped() { + // The count survives even when the per-file log is off, because it is + // the only place a user who turned the log off would hear that part of + // their workspace is not indexed. + let tree = oversized_tree("capend"); + let mut session = Session::with(vec![tree.path.clone()], watching_progress()); + assert_eq!(session.ended(), vec![Some("2 files indexed".to_string())], "premise: no cap"); + + session.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ + "settings": { "lucisv": { "index": { "maxFileSize": 1024, "logFiles": false } } } + }), + ); + assert_eq!( + session.ended(), + vec![Some("1 file indexed, 1 skipped".to_string())], + "the cap change rescanned, and the end message counts the skip" + ); + } + + #[test] + fn a_capped_file_is_out_of_the_index_and_an_open_buffer_is_not() { + let tree = oversized_tree("capserver"); + let mut session = Session::with(vec![tree.path.clone()], watching_progress()); + session.notify(DidChangeConfiguration::METHOD, capping(1024)); + assert_eq!(indexed(&session, "netlist_pkg"), 0, "the big file is not indexed"); + assert_eq!(indexed(&session, "keep_pkg"), 1, "and the small one still is"); + + // Opening it is the user saying they want it: the buffer is indexed + // whatever the cap says. + let text = std::fs::read_to_string(tree.path.join("rtl/netlist.sv")).expect("read"); + session.open(&tree.path.join("rtl/netlist.sv"), &text); + session.notify( + DidSaveTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": path_to_uri(&tree.path.join("rtl/netlist.sv")).expect("uri") } + }), + ); + assert_eq!(indexed(&session, "netlist_pkg"), 1, "an open buffer is exempt"); + } + + #[test] + fn every_indexed_file_is_named_in_the_log_and_so_is_every_skip() { + let tree = oversized_tree("caplog"); + let mut session = Session::with(vec![tree.path.clone()], watching_progress()); + let _ = session.drain(); + session.notify(DidChangeConfiguration::METHOD, capping(1024)); + + let logged = session.logged(); + assert!( + logged.iter().all(|(typ, _)| *typ == MessageType::LOG), + "the file log is LOG, never a popup-worthy level: {logged:?}" + ); + let lines: Vec<&String> = logged.iter().map(|(_, line)| line).collect(); + assert_eq!( + lines.iter().filter(|l| l.starts_with("indexing: ")).count(), + 1, + "one line per file parsed: {lines:?}" + ); + assert!( + lines.iter().any(|l| l.ends_with("rtl/keep.sv") && l.starts_with("indexing: ")), + "named by full path: {lines:?}" + ); + let skip = lines + .iter() + .find(|l| l.starts_with("skipped (")) + .unwrap_or_else(|| panic!("a skip line: {lines:?}")); + assert!(skip.contains("1.0 KiB cap"), "the cap it was measured against: {skip}"); + assert!(skip.contains("4.0 KiB >"), "and the size that broke it: {skip}"); + assert!(skip.ends_with("rtl/netlist.sv"), "and the file it kept out: {skip}"); + } + + #[test] + fn the_file_log_goes_quiet_when_the_setting_is_off() { + let tree = oversized_tree("caplogoff"); + let mut session = Session::with(vec![tree.path.clone()], watching_progress()); + let _ = session.drain(); + session.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ + "settings": { "lucisv": { "index": { "maxFileSize": 1024, "logFiles": false } } } + }), + ); + let logged = session.logged(); + assert!(logged.is_empty(), "not one line, skips included: {logged:?}"); + } + + #[test] + fn the_file_log_does_not_wait_for_a_progress_bar() { + // The two features are independent: the log is a `window/logMessage`, + // which every client gets, and the bar is gated on a capability. + let tree = Tree::new("caplognobar"); + tree.package("rtl/a.sv", "a"); + let session = Session::new(vec![tree.path.clone()], false); + // One drain, both questions: `Session::drain` consumes. + let messages = session.drain(); + assert!( + messages.iter().cloned().filter_map(progress_step).next().is_none(), + "premise: no bar for this client" + ); + let logged: Vec = messages + .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.message) + } + _ => None, + }) + .collect(); + assert_eq!(logged.len(), 1, "{logged:?}"); + assert!(logged[0].starts_with("indexing: "), "{logged:?}"); + } + + #[test] + fn a_new_cap_rescans_and_a_new_log_setting_does_not() { + // `lucisv.index.maxFileSize` changes which files exist, so it costs a + // rescan exactly as `exclude` does; `logFiles` changes nothing but the + // narration of the next one. + let tree = Tree::new("caprescan"); + tree.package("rtl/a.sv", "a"); + let mut session = Session::with(vec![tree.path.clone()], watching_progress()); + let _ = session.drain(); + + session.notify(DidChangeConfiguration::METHOD, capping(4096)); + assert_eq!(session.progress().len(), 4, "create, begin, one report, end"); + + session.notify(DidChangeConfiguration::METHOD, capping(4096)); + assert!(session.progress().is_empty(), "the same cap again buys nothing"); + + session.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ + "settings": { "lucisv": { "index": { "maxFileSize": 4096, "logFiles": false } } } + }), + ); + assert!(session.progress().is_empty(), "and neither does turning the log off"); } #[test] @@ -1994,7 +2453,20 @@ mod tests { "{steps:#?}" ); assert_eq!(ends, begins, "every bar that went up came down"); - assert!(steps.iter().all(|(step, _)| *step != "report"), "no invented percentages"); + // Superseded this round: there *are* reports now, and every one of + // them belongs to a bar that is up. What must never happen is a + // report on a token whose `end` has already gone out. + let mut open: Option<&String> = None; + for (step, token) in &steps { + match *step { + "begin" => open = Some(token), + "report" => { + assert_eq!(open, Some(token), "a report outside its own bar: {steps:#?}") + } + "end" => open = None, + _ => {} + } + } } #[test] @@ -2097,7 +2569,7 @@ mod tests { _ => progress_step(message).map(|(step, _)| step.to_string()), }) .collect(); - assert_eq!(order, vec!["create", "begin", "end", "register"], "{order:?}"); + assert_eq!(order, vec!["create", "begin", "report", "end", "register"], "{order:?}"); } #[test] @@ -3092,7 +3564,9 @@ mod tests { other => progress_step(other).map(|(step, _)| step.to_string()), }) .collect(); - assert_eq!(order, ["create", "begin", "end", "refresh"]); + // Two files in `lens_tree`, so two reports between the begin and the + // end; the refresh is still after all of them. + assert_eq!(order, ["create", "begin", "report", "report", "end", "refresh"]); } #[test] @@ -5093,7 +5567,9 @@ mod tests { let messages = session.drain(); let steps: Vec<&'static str> = messages.iter().cloned().filter_map(progress_step).map(|(step, _)| step).collect(); - assert_eq!(steps, vec!["create", "begin", "end"], "one bar, up and down"); + // One bar, up and down — with a report for each of the two files the + // new root set holds (`a.sv` and `c.sv`). + assert_eq!(steps, vec!["create", "begin", "report", "report", "end"], "one bar"); let publishes = messages .iter() .filter( diff --git a/crates/lucisv_server/src/settings.rs b/crates/lucisv_server/src/settings.rs index f94d4ce..88ad7e5 100644 --- a/crates/lucisv_server/src/settings.rs +++ b/crates/lucisv_server/src/settings.rs @@ -28,6 +28,12 @@ use serde_json::Value; const LINE_LENGTH_RANGE: RangeInclusive = 40..=400; const INDENT_RANGE: RangeInclusive = 1..=8; +/// `lucisv.index.maxFileSize`'s default: 1 MiB. A source file bigger than this +/// is almost always a generated netlist or a dumped trace, which costs minutes +/// to index and answers nothing a user asked. `0` means no cap; see +/// `docs/features/indexing-ux/README.md`. +pub const DEFAULT_MAX_FILE_SIZE: u64 = 1024 * 1024; + /// The configuration section these settings live in — the key a push nests /// them under, and the `section` a pull asks for. One constant, because the /// two must name the same thing or the pull would answer settings the parser @@ -36,8 +42,11 @@ pub const SECTION: &str = "lucisv"; /// The `lucisv.*` settings in force, after validation. Every field is "no /// opinion" until a client says otherwise, which is exactly what an unset -/// VS Code setting means. -#[derive(Debug, Default, Clone, PartialEq, Eq)] +/// VS Code setting means — except the two whose own default is not silence +/// (`index.maxFileSize`, `index.logFiles`), which resolve to it here so no +/// use site has to remember what "unset" meant. See the hand-written +/// [`Default`] below. +#[derive(Debug, Clone, PartialEq, Eq)] pub struct ClientSettings { /// `lucisv.lineLength`. pub line_length: Option, @@ -60,6 +69,38 @@ pub struct ClientSettings { /// also formatted would format twice. See /// `docs/features/will-save-wait-until/README.md`. pub format_on_save: bool, + /// `lucisv.index.maxFileSize`: the largest *walked* file, in bytes, that + /// the workspace index will read. `0` is no cap. An open buffer is + /// indexed whatever its size — the user opened it deliberately. Defaults + /// to [`DEFAULT_MAX_FILE_SIZE`] rather than to 0, so a plain + /// `ClientSettings::default()` is the capped behaviour the server ships + /// with. + pub max_file_size: u64, + /// `lucisv.index.logFiles`: whether each file the index reads is named in + /// a `window/logMessage`, and each oversized one in a skip line. On + /// unless a client says otherwise — the Output panel it lands in is + /// hidden until somebody opens it. + pub log_files: bool, +} + +/// The settings a client that said nothing is treated as having asked for. +/// +/// Hand-written because two of them do not default to silence: the size cap +/// is on at 1 MiB and the file log is on. Every other field is its type's own +/// zero, exactly as the derive produced. +impl Default for ClientSettings { + fn default() -> ClientSettings { + ClientSettings { + line_length: None, + indent: None, + exclude: Vec::new(), + filelist: None, + inline_templates: None, + format_on_save: false, + max_file_size: DEFAULT_MAX_FILE_SIZE, + log_files: true, + } + } } /// Read the `lucisv` section out of a `workspace/didChangeConfiguration` payload. @@ -78,6 +119,12 @@ pub fn from_payload(settings: &Value) -> ClientSettings { // the section (including the `{"settings": null}` a client sends when it // syncs no section at all) means "no opinion about anything". let Some(lucisv) = settings.get(SECTION) else { return ClientSettings::default() }; + // `lucisv.index.maxFileSize` is a dotted id, and both doors nest it: VS + // Code's settings model turns every segment into an object, so the section + // arrives as `{"index": {"maxFileSize": …}}`. An `index` that is missing — + // or is not an object at all — leaves both of its keys at their defaults, + // which is what `Value::get` on a non-object already returns. + let index = lucisv.get("index"); ClientSettings { line_length: bounded(lucisv.get("lineLength"), LINE_LENGTH_RANGE), indent: bounded(lucisv.get("indent"), INDENT_RANGE), @@ -88,6 +135,12 @@ pub fn from_payload(settings: &Value) -> ClientSettings { // values included: the safe direction for a setting that rewrites the // user's buffer on every save is the one that does nothing. format_on_save: flag(lucisv.get("formatOnSave")).unwrap_or(false), + // The safe direction for these two is the shipped default, not zero: + // a wrong-typed cap that read as `0` would index the netlist the + // setting exists to skip. + max_file_size: count(index.and_then(|i| i.get("maxFileSize"))) + .unwrap_or(DEFAULT_MAX_FILE_SIZE), + log_files: flag(index.and_then(|i| i.get("logFiles"))).unwrap_or(true), } } @@ -151,6 +204,16 @@ fn bounded(value: Option<&Value>, range: RangeInclusive) -> Option { range.contains(&number).then_some(number as usize) } +/// A JSON count — any unsigned integer, `0` included — or nothing. +/// +/// Unbounded on purpose: there is no size a cap may not take, and a cap larger +/// than any file on disk is the same as no cap at all. `as_u64` still rejects +/// the negatives, the fractions, the strings and the booleans, exactly as +/// [`bounded`] does. +fn count(value: Option<&Value>) -> Option { + value?.as_u64() +} + /// Every string in a JSON array, or an empty list for anything else. Entries /// that are not strings are dropped rather than stringified: a number in an /// exclude list is a mistake, and guessing what it meant would hide it. @@ -183,11 +246,70 @@ mod tests { "exclude": exclude, "filelist": "", "inlineTemplates": true, - "formatOnSave": false + "formatOnSave": false, + "index": { "maxFileSize": 1048576, "logFiles": true } } }) } + #[test] + fn the_size_cap_defaults_to_a_mebibyte_and_zero_turns_it_off() { + assert_eq!(settings(json!({ "lucisv": {} })).max_file_size, DEFAULT_MAX_FILE_SIZE); + assert_eq!(DEFAULT_MAX_FILE_SIZE, 1_048_576, "1 MiB, as the setting's description says"); + // The whole sub-section missing is the same as the key missing. + assert_eq!(settings(json!({ "lucisv": { "index": {} } })).max_file_size, 1_048_576); + let off = settings(json!({ "lucisv": { "index": { "maxFileSize": 0 } } })); + assert_eq!(off.max_file_size, 0, "0 is the client asking for no cap at all"); + let raised = settings(json!({ "lucisv": { "index": { "maxFileSize": 20_000_000 } } })); + assert_eq!(raised.max_file_size, 20_000_000, "and there is no upper bound"); + } + + #[test] + fn a_wrong_typed_size_cap_leaves_the_default_standing() { + // The safe direction is the shipped cap: reading junk as `0` would + // turn the cap *off*, which is the failure the setting exists to + // prevent. + for bad in + [json!("1048576"), json!(-1), json!(1.5), json!(true), json!(null), json!([1048576])] + { + let found = settings(json!({ "lucisv": { "index": { "maxFileSize": bad } } })); + assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE, "maxFileSize {bad} is ignored"); + } + // An `index` that is not an object at all is the same as no `index`. + for bad in [json!(null), json!(7), json!("index"), json!([])] { + let found = settings(json!({ "lucisv": { "index": bad } })); + assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE, "index {bad} is ignored"); + assert!(found.log_files, "and so is its logFiles"); + } + } + + #[test] + fn the_file_log_is_on_until_a_client_turns_it_off() { + assert!(settings(json!({ "lucisv": {} })).log_files, "absence is on"); + assert!( + settings(json!({ "lucisv": { "index": {} } })).log_files, + "and so is an empty section" + ); + assert!(settings(json!({ "lucisv": { "index": { "logFiles": true } } })).log_files); + assert!(!settings(json!({ "lucisv": { "index": { "logFiles": false } } })).log_files); + for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] { + let found = settings(json!({ "lucisv": { "index": { "logFiles": bad } } })); + assert!(found.log_files, "logFiles {bad} must be ignored"); + } + } + + #[test] + fn the_index_settings_come_through_the_pull_door_too() { + // `from_section` is the same parser, and these two are the first + // nested keys to go through it — a section that lost the nesting on + // the way would silently un-cap every pulling client. + let section = json!({ "index": { "maxFileSize": 4096, "logFiles": false } }); + let pulled = from_section(§ion); + assert_eq!(pulled.max_file_size, 4096); + assert!(!pulled.log_files); + assert_eq!(pulled, settings(json!({ "lucisv": section })), "one set of rules"); + } + #[test] fn a_filelist_is_taken_when_it_names_something() { let found = settings(json!({ "lucisv": { "filelist": "rtl/files.f" } })); diff --git a/crates/lucisv_server/src/state.rs b/crates/lucisv_server/src/state.rs index 52fbb1d..a92c32d 100644 --- a/crates/lucisv_server/src/state.rs +++ b/crates/lucisv_server/src/state.rs @@ -12,7 +12,10 @@ use vlog_parser::ast::SourceFile; use vlog_parser::defines::{collect_defines, DefineTable}; use vlog_parser::token::Token; use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex, ParseDiagnostic}; -use vlog_semantic::{analyze, resolve_external, ExternalResolutions, Semantics, WorkspaceIndex}; +use vlog_semantic::{ + analyze, index_order, resolve_external, ExternalResolutions, IndexBuilder, Semantics, + WorkspaceIndex, +}; use lucisv_core::config::Discovery; use lucisv_core::walk::{collect_files, EXTENSIONS}; @@ -100,6 +103,38 @@ struct Sources { warnings: Vec, } +/// What an index rebuild reports about itself as it runs. +/// +/// This module speaks no protocol, so an event carries numbers and paths and +/// nothing that reads like a message; `server.rs` turns them into a progress +/// report and a log line (`docs/features/indexing-ux/README.md`). +pub enum IndexEvent<'a> { + /// One file is about to be parsed into the index: how many were parsed + /// before it, how many there are in all, and which one it is. `done` + /// counts from 0, so the file being reported is number `done + 1` of + /// `total`. + Parsing { done: usize, total: usize, path: &'a Path }, + /// A walked file was skipped without being read, because it is bigger + /// than the size cap in force. + Skipped { path: &'a Path, size: u64, cap: u64 }, +} + +/// The size of `path` when it is over `cap`, else `None` — the whole of the +/// `lucisv.index.maxFileSize` test. +/// +/// Metadata only: the point of the cap is that a 200 MB netlist is never read +/// into memory, so asking the filesystem how big it is has to come first. A +/// `cap` of 0 is the client asking for no cap, and a file whose metadata +/// cannot be read is not skipped here — it simply fails the read below, as it +/// always did. +fn oversize(path: &Path, cap: u64) -> Option { + if cap == 0 { + return None; + } + let size = fs::metadata(path).ok()?.len(); + (size > cap).then_some(size) +} + /// Every open buffer plus the workspace index they are resolved against. #[derive(Default)] pub struct Workspace { @@ -120,9 +155,25 @@ pub struct Workspace { impl Workspace { /// Adopt the workspace roots and build the index for the first time. /// Returns whatever the caller should tell the user about the scope. + /// + /// The unwatched form. `server.rs` always watches (it has a progress bar + /// to move), so this is reachable from tests alone — of which there are + /// several dozen across this crate, and none of them has an opinion about + /// progress reporting. + #[cfg(test)] pub fn open_roots(&mut self, roots: Vec) -> Vec { + self.open_roots_with(roots, &mut |_| {}) + } + + /// [`Workspace::open_roots`], watched — the startup build reports itself + /// exactly as every later rescan does. + pub fn open_roots_with( + &mut self, + roots: Vec, + watch: &mut dyn FnMut(IndexEvent), + ) -> Vec { self.roots = roots; - self.rebuild_index() + self.rebuild_index_with(watch) } /// Add and remove workspace roots mid-session, reporting whether the set @@ -177,13 +228,16 @@ impl Workspace { /// Adopt the settings a client pushed. /// - /// Returns `true` when the caller must rebuild the index: `exclude` and - /// `filelist` are the two that change *which files exist* as far as this - /// server is concerned. `lineLength` and `indent` are read afresh by every - /// formatting request, so they need no invalidation at all. + /// Returns `true` when the caller must rebuild the index: `exclude`, + /// `filelist` and `index.maxFileSize` are the three that change *which + /// files exist* as far as this server is concerned. `lineLength` and + /// `indent` are read afresh by every formatting request, so they need no + /// invalidation at all — and neither does `index.logFiles`, which changes + /// only how loudly the *next* rescan narrates itself. pub fn set_client_settings(&mut self, settings: ClientSettings) -> bool { - let rescan = - self.client.exclude != settings.exclude || self.client.filelist != settings.filelist; + let rescan = self.client.exclude != settings.exclude + || self.client.filelist != settings.filelist + || self.client.max_file_size != settings.max_file_size; self.client = settings; rescan } @@ -215,10 +269,37 @@ impl Workspace { /// Returns the warnings from resolving the scope — a filelist naming a /// file that is gone, say. Rendering them is `server.rs`'s job; this /// module speaks no protocol. + /// + /// The unwatched form, reachable from tests alone for the same reason + /// `open_roots` is. + #[cfg(test)] pub fn rebuild_index(&mut self) -> Vec { - let scope = self.collect_sources(); + self.rebuild_index_with(&mut |_| {}) + } + + /// [`Workspace::rebuild_index`], watched: `watch` is called once for every + /// file the size cap skipped and once for every file about to be parsed, + /// in index order and before the parse, so a caller can report where the + /// rescan has got to. + /// + /// The events cover the index build alone. The completion tables and the + /// include graph are built from the same list afterwards and are not + /// reported: they cost a small fraction of the parse, and a bar that went + /// to 100% and then sat there would be worse than one that ends. + pub fn rebuild_index_with(&mut self, watch: &mut dyn FnMut(IndexEvent)) -> Vec { + let scope = self.collect_sources(watch); let sources = scope.texts; - self.index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str()))); + // The same list the index will be built from, in the order it will be + // built in — asked of `vlog_semantic` rather than re-derived here, so + // the count reported is the count parsed. + let ordered = index_order(sources.iter().map(|(p, t)| (p.clone(), t.as_str()))); + let total = ordered.len(); + let mut builder = IndexBuilder::new(); + for (done, (path, text)) in ordered.into_iter().enumerate() { + watch(IndexEvent::Parsing { done, total, path: &path }); + builder.add_file(path, text); + } + self.index = builder.finish(); // Built here, from the same list, so a file the scope ladder excluded // contributes no completion candidates either. self.candidates = Candidates::build(&self.index, &sources); @@ -237,14 +318,31 @@ impl Workspace { /// kept: a refactoring is a rare, user-initiated request, and a second /// copy of the workspace in memory is a high price for saving one walk. pub fn sources(&self) -> Vec<(PathBuf, String)> { - self.collect_sources().texts + self.collect_sources(&mut |_| {}).texts } /// Read every in-scope file, with open buffers overriding disk. - fn collect_sources(&self) -> Sources { + /// + /// This is where `lucisv.index.maxFileSize` applies, and it applies to the + /// **walked** files only: an open buffer is folded in below whatever its + /// size, because the user opened it deliberately and an editor that + /// refused to understand the file on screen would be absurd. The check is + /// a `metadata` call ahead of the read, so an oversized file is never read + /// at all — which is the whole saving. + /// + /// A refactoring reads this same list through `sources()`, so a file the + /// cap keeps out of the index is also a file a workspace rename will not + /// rewrite. That is the consistent answer: the cap says which files exist + /// as far as this server is concerned. + fn collect_sources(&self, watch: &mut dyn FnMut(IndexEvent)) -> Sources { let scope = self.source_files(); + let cap = self.client.max_file_size; let mut texts: Vec<(PathBuf, String)> = Vec::new(); for path in scope.files { + if let Some(size) = oversize(&path, cap) { + watch(IndexEvent::Skipped { path: &path, size, cap }); + continue; + } if let Ok(text) = fs::read_to_string(&path) { texts.push((path, text)); } @@ -798,12 +896,198 @@ mod tests { !ws.set_client_settings(ClientSettings { format_on_save: true, ..Default::default() }), "turning the save hook on does not move files either" ); + // The file log changes how loudly a rescan narrates itself and nothing + // about which files exist, so it must not buy one. + assert!( + !ws.set_client_settings(ClientSettings { log_files: false, ..Default::default() }), + "turning the per-file log off does not move files either" + ); assert!(ws.set_client_settings(excluding(&["a"])), "a new exclude does"); + // The cap does move files, so it does. + assert!( + ws.set_client_settings(ClientSettings { + exclude: vec!["a".to_string()], + max_file_size: 4096, + ..Default::default() + }), + "a new cap rescans" + ); + assert!( + !ws.set_client_settings(ClientSettings { + exclude: vec!["a".to_string()], + max_file_size: 4096, + log_files: false, + ..Default::default() + }), + "the same cap with a different log setting does not" + ); + assert!( + ws.set_client_settings(ClientSettings { + exclude: vec!["a".to_string()], + log_files: false, + ..Default::default() + }), + "and going back to the default cap does" + ); + ws.set_client_settings(excluding(&["a"])); assert!(!ws.set_client_settings(excluding(&["a"])), "the same one again does not"); assert!(ws.set_client_settings(excluding(&["a", "b"])), "an added pattern does"); assert!(ws.set_client_settings(ClientSettings::default()), "and so does clearing it"); } + /// A `ClientSettings` with the size cap set to `bytes`. + fn capping(bytes: u64) -> ClientSettings { + ClientSettings { max_file_size: bytes, ..Default::default() } + } + + /// A file of `bytes` bytes that would declare `name` if anything read it. + /// Padded with a trailing comment, so what makes it big is not what makes + /// it a package. + fn fat_package(tree: &Tree, rel: &str, name: &str, bytes: usize) { + let head = format!("package {name};\n localparam K = 1;\nendpackage\n// "); + let mut text = String::with_capacity(bytes + head.len()); + text.push_str(&head); + while text.len() < bytes { + text.push('x'); + } + text.push('\n'); + tree.write(rel, &text); + } + + #[test] + fn a_walked_file_over_the_cap_is_left_out_of_the_index() { + let tree = Tree::new("capskip"); + tree.package("small.sv", "small_pkg"); + fat_package(&tree, "netlist.sv", "netlist_pkg", 4096); + + let mut ws = Workspace::default(); + ws.set_client_settings(capping(1024)); + ws.open_roots(vec![tree.path.clone()]); + assert_eq!( + indexed(&ws, &["small_pkg", "netlist_pkg"]), + ["small_pkg"], + "the big file is not in the index, and was never read" + ); + } + + #[test] + fn the_default_cap_is_a_mebibyte_and_zero_turns_it_off() { + // The shipped default, exercised against a file that really is over + // 1 MiB — the only way to prove the constant is the one in force. + let tree = Tree::new("capdefault"); + tree.package("small.sv", "small_pkg"); + fat_package(&tree, "huge.sv", "huge_pkg", 1024 * 1024 + 1); + + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + assert_eq!(indexed(&ws, &["small_pkg", "huge_pkg"]), ["small_pkg"], "capped by default"); + + // `0` is the client asking for no cap, and must be exactly the + // behaviour that existed before there was one. + assert!(ws.set_client_settings(capping(0)), "turning the cap off rescans"); + ws.rebuild_index(); + assert_eq!( + indexed(&ws, &["small_pkg", "huge_pkg"]), + ["small_pkg", "huge_pkg"], + "nothing capped" + ); + } + + #[test] + fn an_open_buffer_is_indexed_however_big_the_file_is() { + // The documented exemption: the cap is about files nobody asked for. + // A buffer the user opened is indexed and diagnosed whatever its size, + // or the editor would refuse to understand the file on screen. + let tree = Tree::new("capbuffer"); + fat_package(&tree, "huge.sv", "huge_pkg", 4096); + + let mut ws = Workspace::default(); + ws.set_client_settings(capping(1024)); + ws.open_roots(vec![tree.path.clone()]); + assert_eq!(indexed(&ws, &["huge_pkg"]), Vec::::new(), "premise: capped on disk"); + + let uri = crate::uri::path_to_uri(&tree.path.join("huge.sv")).expect("uri"); + let text = fs::read_to_string(tree.path.join("huge.sv")).expect("read"); + ws.set_document(uri, text); + ws.rebuild_index(); + assert_eq!(indexed(&ws, &["huge_pkg"]), ["huge_pkg"], "the open buffer is indexed in full"); + } + + #[test] + fn every_skipped_file_is_reported_with_its_size_and_the_cap() { + let tree = Tree::new("capevents"); + tree.package("small.sv", "small_pkg"); + fat_package(&tree, "netlist.sv", "netlist_pkg", 4096); + + let mut ws = Workspace::default(); + ws.set_client_settings(capping(1024)); + let mut skipped: Vec<(PathBuf, u64, u64)> = Vec::new(); + ws.open_roots_with(vec![tree.path.clone()], &mut |event| { + if let IndexEvent::Skipped { path, size, cap } = event { + skipped.push((path.to_path_buf(), size, cap)); + } + }); + assert_eq!(skipped.len(), 1, "{skipped:?}"); + assert_eq!(skipped[0].0, tree.path.join("netlist.sv")); + assert!(skipped[0].1 >= 4096, "the file's real size: {skipped:?}"); + assert_eq!(skipped[0].2, 1024, "and the cap it was measured against"); + } + + #[test] + fn the_watcher_sees_every_file_in_index_order_against_a_total_it_knew_first() { + // The denominator is the work list *after* the exclude and the cap: + // a bar counting towards a number that included files nobody was + // going to parse would stall short of the end every time. + let tree = Tree::new("capwatch"); + tree.package("b.sv", "b"); + tree.package("a.sv", "a"); + tree.package("skipped/c.sv", "c"); + fat_package(&tree, "d.sv", "d_pkg", 4096); + + let mut ws = Workspace::default(); + ws.set_client_settings(ClientSettings { + exclude: vec!["skipped".to_string()], + max_file_size: 1024, + ..Default::default() + }); + let mut seen: Vec<(usize, usize, PathBuf)> = Vec::new(); + ws.open_roots_with(vec![tree.path.clone()], &mut |event| { + if let IndexEvent::Parsing { done, total, path } = event { + seen.push((done, total, path.to_path_buf())); + } + }); + assert_eq!( + seen, + vec![(0, 2, tree.path.join("a.sv")), (1, 2, tree.path.join("b.sv")),], + "sorted, excluded and capped files absent, total known from the first event" + ); + assert_eq!(ws.index().files().len(), 2, "and the index holds exactly those"); + } + + #[test] + fn the_default_cap_changes_nothing_about_the_real_corpus() { + // The cap ships on, so the burden is to show it costs an existing + // project nothing: the index the default cap builds over `corpus/` + // must be the one no cap at all builds. It is — the largest corpus + // file is 94 KB, eleven times under the cap — and this test is what + // notices if a future corpus, or a future default, changes that. + let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + if !corpus.is_dir() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + + let mut capped = Workspace::default(); + capped.open_roots(vec![corpus.clone()]); + let mut uncapped = Workspace::default(); + uncapped.set_client_settings(capping(0)); + uncapped.open_roots(vec![corpus]); + + assert_eq!(capped.index().files(), uncapped.index().files(), "the same files, in order"); + assert_eq!(capped.index().counts(), uncapped.index().counts(), "and the same index"); + assert!(capped.index().files().len() > 500, "premise: the corpus was really scanned"); + } + #[test] fn a_filelist_change_asks_for_a_rescan_too() { // It changes which files exist as far as this server is concerned, diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index 6fb6b4d..34966cb 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -3206,20 +3206,29 @@ fn indexing_reports_its_progress_over_the_wire() { .collect(); // Two rescans: the startup build, then the save. Each one create, one - // begin, one end, on its own token. + // begin, one report per file (there is one file), one end, on its own + // token. assert_eq!( steps, vec![ ("create".to_string(), "lucisv-index-0".to_string()), ("begin".to_string(), "lucisv-index-0".to_string()), + ("report".to_string(), "lucisv-index-0".to_string()), ("end".to_string(), "lucisv-index-0".to_string()), ("create".to_string(), "lucisv-index-1".to_string()), ("begin".to_string(), "lucisv-index-1".to_string()), + ("report".to_string(), "lucisv-index-1".to_string()), ("end".to_string(), "lucisv-index-1".to_string()), ], "{messages:#?}" ); + // The report counts, on the wire: "1/1 m.sv" at 100%. + let report = + messages.iter().find(|m| m["params"]["value"]["kind"] == "report").expect("a report"); + assert_eq!(report["params"]["value"]["message"], "1/1 m.sv", "{report:#?}"); + assert_eq!(report["params"]["value"]["percentage"], 100, "{report:#?}"); + // The begin says what it is doing, and offers no cancel button — a rescan // that has started runs to completion, whatever `$/cancelRequest` can do // for the requests still queued. @@ -3237,6 +3246,93 @@ fn indexing_reports_its_progress_over_the_wire() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn the_size_cap_and_the_file_log_work_over_the_wire() { + // The three settings of `docs/features/indexing-ux/README.md` together, + // against the real binary: a pushed cap rescans, the oversized file is + // gone from the index, the log names every file and the skip, and the bar + // counts what is left. + let dir = temp_dir("indexcap"); + std::fs::write(dir.join("keep.sv"), "package keep_pkg;\n localparam K = 1;\nendpackage\n") + .expect("write"); + let mut fat = String::from("package netlist_pkg;\n localparam K = 1;\nendpackage\n// "); + while fat.len() < 4096 { + fat.push('x'); + } + fat.push('\n'); + std::fs::write(dir.join("netlist.sv"), &fat).expect("write"); + let root = format!("file://{}", dir.display()); + + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"window":{{"workDoneProgress":true}}}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + // The cap arrives the way VS Code sends a dotted setting: nested. + frame( + r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"index":{"maxFileSize":1024}}}}}"#, + ), + frame( + r#"{"jsonrpc":"2.0","id":2,"method":"workspace/symbol","params":{"query":"pkg"}}"#, + ), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + + // 1. The capped file is not in the index; the other one is. + let symbols = messages.iter().find(|m| m["id"] == 2).expect("symbol response"); + let names: Vec<&str> = symbols["result"] + .as_array() + .expect("an array") + .iter() + .filter_map(|s| s["name"].as_str()) + .collect(); + assert!(names.contains(&"keep_pkg"), "{symbols:#?}"); + assert!(!names.contains(&"netlist_pkg"), "the capped file is invisible: {symbols:#?}"); + + // 2. The log named every file it read, and the one it did not. + let logged: Vec<&str> = messages + .iter() + .filter(|m| m["method"] == "window/logMessage") + .filter_map(|m| m["params"]["message"].as_str()) + .collect(); + assert!( + messages + .iter() + .filter(|m| m["method"] == "window/logMessage") + .all(|m| m["params"]["type"] == 4), + "MessageType::LOG, which vscode-languageclient appends verbatim: {logged:?}" + ); + assert!( + logged.iter().any(|l| l.starts_with("indexing: ") && l.ends_with("keep.sv")), + "{logged:?}" + ); + let skip = logged + .iter() + .find(|l| l.starts_with("skipped (")) + .unwrap_or_else(|| panic!("a skip line: {logged:?}")); + assert!(skip.ends_with("netlist.sv"), "{skip}"); + assert!(skip.starts_with("skipped (4.0 KiB > 1.0 KiB cap): "), "{skip}"); + + // 3. The bar for the rescan the cap triggered: one file of one, and an + // end that counts the skip. + let after: Vec<&serde_json::Value> = messages + .iter() + .filter(|m| m["method"] == "$/progress" && m["params"]["token"] == "lucisv-index-1") + .collect(); + let kinds: Vec<&str> = + after.iter().filter_map(|m| m["params"]["value"]["kind"].as_str()).collect(); + assert_eq!(kinds, ["begin", "report", "end"], "the cap change rescanned: {after:#?}"); + assert_eq!(after[1]["params"]["value"]["message"], "1/1 keep.sv", "{after:#?}"); + assert_eq!(after[1]["params"]["value"]["percentage"], 100, "{after:#?}"); + assert_eq!(after[2]["params"]["value"]["message"], "1 file indexed, 1 skipped", "{after:#?}"); + + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn a_client_that_never_asked_for_progress_is_sent_none_over_the_wire() { let dir = temp_dir("noprogress"); diff --git a/crates/vlog_semantic/src/lib.rs b/crates/vlog_semantic/src/lib.rs index 7fb93c8..0fbe004 100644 --- a/crates/vlog_semantic/src/lib.rs +++ b/crates/vlog_semantic/src/lib.rs @@ -27,8 +27,8 @@ pub use model::{ SymbolId, SymbolKind, }; pub use workspace::{ - resolve_external, Def, Definition, ExternalResolutions, ExternalTarget, FileId, IndexCounts, - WorkspaceIndex, WorkspaceSymbol, + index_order, resolve_external, Def, Definition, ExternalResolutions, ExternalTarget, FileId, + IndexBuilder, IndexCounts, WorkspaceIndex, WorkspaceSymbol, }; use std::collections::HashMap; diff --git a/crates/vlog_semantic/src/workspace.rs b/crates/vlog_semantic/src/workspace.rs index 1f9adc7..59343ee 100644 --- a/crates/vlog_semantic/src/workspace.rs +++ b/crates/vlog_semantic/src/workspace.rs @@ -72,21 +72,16 @@ impl WorkspaceIndex { /// Pure: the same inputs always give the same index, whatever order they /// arrive in. Re-scanning a changed workspace means calling this again — /// there is no incremental update (TODO.md §6 defers that to salsa). + /// + /// This is exactly [`index_order`] followed by an [`IndexBuilder`] loop, + /// and stays the API every caller that does not care to watch the build + /// should use. pub fn build<'a>(files: impl IntoIterator) -> WorkspaceIndex { - let mut sources: Vec<(PathBuf, &str)> = files.into_iter().collect(); - sources.sort_by(|a, b| a.0.cmp(&b.0)); - // A path handed over twice is one file; the first copy wins. - sources.dedup_by(|a, b| a.0 == b.0); - - let mut index = WorkspaceIndex::default(); - for (path, src) in sources { - let file = FileId(index.files.len() as u32); - index.files.push(path); - let (tree, defines) = parse_and_collect(src); - index.defines.push(defines); - index.add_file(file, &analyze(&tree, src)); + let mut builder = IndexBuilder::new(); + for (path, src) in index_order(files) { + builder.add_file(path, src); } - index + builder.finish() } /// Every file the index covers, by [`FileId`]. @@ -248,6 +243,61 @@ impl WorkspaceIndex { } } +/// The file list an index will be built from, in the order it is built in: +/// sorted by path, one entry per path (a path handed over twice is one file, +/// and the first copy wins). +/// +/// Exposed because a caller that wants to *watch* a build — the server's +/// indexing progress bar — has to know the work list, and its length, before +/// the first file is parsed. Getting that ordering from here rather than +/// re-deriving it is what keeps a watched build and a plain +/// [`WorkspaceIndex::build`] the same index in the same order. +pub fn index_order<'a>( + files: impl IntoIterator, +) -> Vec<(PathBuf, &'a str)> { + let mut sources: Vec<(PathBuf, &str)> = files.into_iter().collect(); + sources.sort_by(|a, b| a.0.cmp(&b.0)); + // A path handed over twice is one file; the first copy wins. + sources.dedup_by(|a, b| a.0 == b.0); + sources +} + +/// A [`WorkspaceIndex`] under construction, one file at a time. +/// +/// The same work [`WorkspaceIndex::build`] does — that function is now a loop +/// over this one — split so a caller can do something between two files, which +/// in practice means reporting progress. Nothing here is incremental in the +/// salsa sense: a file can be added, never replaced or removed. +/// +/// **Feed it [`index_order`]'s list.** [`FileId`]s are handed out in call +/// order, and both the file ids and the disambiguation order of a name +/// declared twice are the path order that function establishes. +#[derive(Debug, Clone, Default)] +pub struct IndexBuilder { + index: WorkspaceIndex, +} + +impl IndexBuilder { + /// An empty index to add files to. + pub fn new() -> IndexBuilder { + IndexBuilder::default() + } + + /// Parse one file and record what it declares. + pub fn add_file(&mut self, path: PathBuf, src: &str) { + let file = FileId(self.index.files.len() as u32); + self.index.files.push(path); + let (tree, defines) = parse_and_collect(src); + self.index.defines.push(defines); + self.index.add_file(file, &analyze(&tree, src)); + } + + /// The finished index. + pub fn finish(self) -> WorkspaceIndex { + self.index + } +} + /// The headline numbers of a built index. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct IndexCounts { diff --git a/crates/vlog_semantic/tests/workspace.rs b/crates/vlog_semantic/tests/workspace.rs index f3f487d..a3c1679 100644 --- a/crates/vlog_semantic/tests/workspace.rs +++ b/crates/vlog_semantic/tests/workspace.rs @@ -282,6 +282,43 @@ fn the_same_path_twice_is_one_file() { assert_eq!(ws.units("m").len(), 1); } +#[test] +fn the_incremental_builder_is_what_build_is_made_of() { + // `WorkspaceIndex::build` is now `index_order` plus a loop over + // `IndexBuilder`, so a caller that runs that loop itself — the server, + // which reports progress between two files — must get the same index down + // to the file ids. Every other test in this file goes through `build` and + // is the other half of the proof: if the two ever disagreed, they would + // all be wrong together. + let files = [ + ("z.sv", "package z;\n localparam K = 1;\nendpackage\n"), + ("a.sv", "module a; endmodule\n"), + ("a.sv", "module never_seen; endmodule\n"), + ("m.sv", "module m; a u (); endmodule\n"), + ]; + let handed: Vec<(PathBuf, &str)> = files.iter().map(|(p, s)| (PathBuf::from(*p), *s)).collect(); + + // The work list, in the order the index is built in: sorted by path, the + // repeated `a.sv` folded into one — and knowable before any parsing, which + // is what makes a "37 of 200" progress report honest. + let ordered = vlog_semantic::index_order(handed.clone()); + let names: Vec<&str> = ordered.iter().filter_map(|(p, _)| p.to_str()).collect(); + assert_eq!(names, ["a.sv", "m.sv", "z.sv"], "sorted, and one entry per path"); + + let mut builder = vlog_semantic::IndexBuilder::new(); + for (path, src) in ordered { + builder.add_file(path, src); + } + let built = builder.finish(); + let whole = WorkspaceIndex::build(handed); + + assert_eq!(built.files(), whole.files(), "same files, same file ids"); + assert_eq!(built.counts(), whole.counts()); + assert_eq!(built.units("a")[0], whole.units("a")[0], "the first copy of a.sv won, both ways"); + assert!(built.units("never_seen").is_empty(), "and the second copy is gone"); + assert_eq!(built.member("z", "K").len(), 1); +} + // ---------------------------------------------------------------------- // Queries // ---------------------------------------------------------------------- diff --git a/docs/features/folders-and-config/README.md b/docs/features/folders-and-config/README.md index 1624806..9371e51 100644 --- a/docs/features/folders-and-config/README.md +++ b/docs/features/folders-and-config/README.md @@ -72,6 +72,12 @@ parser** a push does, so the two paths cannot drift. first index is built against the default scope, and a pulled `lucisv.exclude`/`lucisv.filelist` costs one extra rescan when it lands. Nothing is *wrong* in between, it is simply the wider scope. + **2026-08-27:** `lucisv.index.maxFileSize` joins those two — a pulled cap + that differs from the 1 MiB default costs the same one extra rescan — and + `lucisv.index.logFiles` shows the other face of the same fact: the startup + scan narrates itself at the default (on) whatever the user's setting says, + because their answer has not arrived yet. Both are + `docs/features/indexing-ux/README.md`. ## The settings model, stated once diff --git a/docs/features/indexing-ux/README.md b/docs/features/indexing-ux/README.md new file mode 100644 index 0000000..04303cf --- /dev/null +++ b/docs/features/indexing-ux/README.md @@ -0,0 +1,640 @@ +# indexing-ux + +## Goal + +Three things a user of a *large* workspace has been asking the index for, all +of them about knowing and controlling what the scan is doing. **(1) A per-file +size cap** — `lucisv.index.maxFileSize`, 1 MiB by default: a Verilog file +bigger than a mebibyte is almost always a generated netlist or a dumped trace, +and indexing one costs minutes and answers nothing anybody asked. **(2) A +counting progress bar** — the `$/progress` bar that `work-done-progress` put up +was deliberately indeterminate, because `rebuild_index` was one opaque call; +this round makes the build observable per file, so the bar says `137/860 +core_ibex_env.sv` and carries a real percentage. **(3) Per-file status in the +editor's output channel** — `lucisv.index.logFiles`, on by default: one +`window/logMessage` naming each file as it is parsed, plus a line for each file +the cap skipped, so "why is this symbol missing" and "why is this scan slow" +are answerable without a debugger. All three settings ride both settings doors +(push and pull) for free, because `settings.rs` is the one parser for both. + +## Assumptions + +- **The cap's blast radius is every `sources()` consumer, not just the + index** (QA log, 2026-08-27, lead-expanded): a capped file is invisible to + the workspace index, the hierarchy census (code-lens counts, + incomingCalls), type-hierarchy subtypes, cross-file navigation, rename's + collection sweep, and willRenameFiles' include rewriting. This is the one + coherent reading — "which files exist as far as this server is concerned" + — and nothing dangles, because the file is equally absent from every + layer. The honesty gap QA proved: a rename that would have touched a + capped file leaves its text stale on disk with no warning. Follow-up + filed (see the task the lead spawned): sweeps that WRITE should say when + the cap hid files from them. + + +- **The cap applies to walked files only; an open buffer is always indexed in + full.** The user opened it deliberately, and an editor that refused to + understand the file on screen because of a size setting would be absurd. + `collect_sources` reads the scope's files (capped) and *then* folds every + open buffer in over the top (uncapped) — the same override that has always + made a buffer beat disk. +- **The cap is enforced with `fs::metadata` before the read.** The whole + saving is that a 200 MB netlist is never read into memory; a cap applied + after `read_to_string` would be a cap that costs what it saves. A file whose + metadata cannot be read is not skipped — it simply fails the read, as it + always did. +- **`0` means no cap, and must be exactly today's behaviour.** Pinned against + the real corpus: the index built with the default cap and the index built + with `maxFileSize: 0` are the same files in the same order with the same + counts (`the_default_cap_changes_nothing_about_the_real_corpus`). It is + true today because the largest file in `corpus/` is 94 KB — eleven times + under the cap, and **zero** corpus files exceed 1 MiB — and that test is + what notices if a future corpus or a future default changes it. +- **A wrong-typed cap falls back to 1 MiB, not to 0.** Every other setting in + `settings.rs` drops a bad value and goes silent; here "silent" has to mean + the shipped default, because reading junk as `0` would turn the cap *off*, + which is the failure the setting exists to prevent. +- **The cap is a *server indexing* cap and nothing else.** It is not pushed + into `lucisv_core`'s walk and not into the CLI's formatting path: `lucisv + format` on a 4 MB file must still format it, and a `lucisv.toml` has no + key for this. It lives in `Workspace::collect_sources`, which is the one + place the server decides which files exist. +- **…which means a refactoring sees the cap too.** `Workspace::sources()` — + what a workspace rename and `find_references` read — goes through the same + `collect_sources`. That is the consistent answer rather than an oversight: a + file that is not in the index is not a file this server rewrites. Stated + here because it is the one non-obvious reach of the setting. +- **The denominator is the work list after `exclude` and after the cap.** It + is `vlog_semantic::index_order`'s length, known before the first parse, so + the bar counts towards a number the scan will actually reach. +- **The percentage only counts up, and the last file always reports.** See the + throttle below; `the_report_schedule_never_floods_and_never_stops_short` + checks both properties across nine workspace sizes. +- **`logFiles` defaults to on.** The owner asked for it, and the channel it + lands in is hidden until somebody opens it — `MessageType::LOG` goes through + `vscode-languageclient`'s `default:` branch straight to + `outputChannel.appendLine`, with no popup, no channel reveal and no trace + gate (read out of `node_modules/vscode-languageclient/lib/common/client.js`, + not assumed). A user who minds turns it off. +- **The startup scan runs at the defaults, because settings arrive after it.** + Both doors deliver settings only once `initialized` has been seen, so the + first index build always uses the 1 MiB cap and always logs its files, even + for a user who set neither. A differing cap then costs one extra rescan when + it lands — the same one `lucisv.exclude` has always cost + (`docs/features/folders-and-config/README.md`) — and a `logFiles: false` + takes effect from the second rescan onwards. This is visible in the + measurements below, where the "off" rows still carry the startup scan's 860 + lines. +- **The skip *count* survives with the log off.** The skip lines are gated by + `logFiles` like every other per-file line, but the progress `end` message + becomes `"N files indexed, M skipped"` whenever `M > 0`, whatever the log + setting says. A user who silenced the log should still learn that part of + their workspace is not in the index. +- **Changing the cap rescans; changing the log setting does not.** + `max_file_size` changes *which files exist* as far as this server is + concerned, exactly as `exclude` and `filelist` do, so it joins them in + `set_client_settings`'s change test. `log_files` changes only how loudly the + next rescan narrates itself. +- **The completion tables and the include graph are outside the bar's count.** + They are built from the same list after the index, and cost a small fraction + of the parse. A bar that reached 100% and then sat there would be worse than + one that ends. + +## Handshakes + +### `vlog_semantic` — one addition, `build` redefined over it + +`WorkspaceIndex::build` was one opaque call, so nothing outside the crate +could see a rebuild advance. It is now the loop over two new public items, +and its own signature and behaviour are unchanged: + +```rust +pub fn index_order<'a>(files: impl IntoIterator) + -> Vec<(PathBuf, &'a str)>; // sorted by path, one entry per path + +pub struct IndexBuilder; // new() / add_file(path, src) / finish() + +pub fn build<'a>(files: …) -> WorkspaceIndex { + let mut builder = IndexBuilder::new(); + for (path, src) in index_order(files) { builder.add_file(path, src); } + builder.finish() +} +``` + +- **Why the builder rather than a callback parameter.** A callback would have + put a `&mut dyn FnMut` in a crate whose whole documented character is + "pure: the same inputs always give the same index". The builder adds no + parameter to anything and no closure to any signature; the caller that wants + to watch simply runs the loop itself. +- **Why `index_order` is public alongside it.** The builder hands out + `FileId`s in call order, and *both* the file ids and the disambiguation + order of a name declared twice are the path order `build` used to establish + privately. Exporting the ordering rule is what keeps a watched build and a + plain `build` the same index — and the server needs the list's length before + the first parse anyway, for the progress denominator. It is the honest + alternative to a comment telling callers to sort. +- **Proof of equivalence: every existing `vlog_semantic` test is unchanged** + and every one of them goes through `build`. One new test + (`the_incremental_builder_is_what_build_is_made_of`) drives the builder path + directly and asserts the same `files()`, the same `counts()`, the same + winning `Def` for a path handed over twice. +- **Noted, not done:** `vlog_refactor::rename::Scope::build` re-derives the + same sort-and-dedup by hand, with a comment saying so + (`crates/vlog_refactor/src/rename.rs:148`). It could now call `index_order`. + Out of this round's scope; filed here. + +### `lucisv_server::state` + +- `Workspace::rebuild_index_with(&mut dyn FnMut(IndexEvent))` and + `open_roots_with(roots, …)` are the watched forms; `rebuild_index()` and + `open_roots()` keep their exact old signatures and behaviour as the + unwatched forms. `server.rs` always watches, so the unwatched pair is now + reachable from tests alone and is `#[cfg(test)]` — several dozen call sites + across the crate, none of which has an opinion about progress. +- `pub enum IndexEvent<'a> { Parsing { done, total, path }, Skipped { path, + size, cap } }`. Numbers and paths only: this module speaks no protocol, and + the wording of every message stays in `server.rs`. +- `ClientSettings::max_file_size` is read in `collect_sources`; nothing else + in `state.rs` changed. + +### `lucisv_server::settings` + +- Two new fields, `max_file_size: u64` and `log_files: bool`, parsed from + `lucisv.index.maxFileSize` / `lucisv.index.logFiles`. VS Code nests a dotted + setting id under each segment, so the section arrives as + `{"index": {"maxFileSize": …}}`; an `index` that is missing, `null`, or not + an object leaves both at their defaults. +- **`ClientSettings`'s `Default` is now hand-written.** Two of the fields do + not default to silence (1 MiB, and the log on), which a derive cannot say. + Every other field is its type's zero, exactly as the derive produced, so + every `..Default::default()` in the crate keeps meaning what it meant. +- `DEFAULT_MAX_FILE_SIZE` is public so the tests and the docs name one number. + +### `lucisv_server::server` + +- `IndexWatch` turns `IndexEvent`s into a `$/progress` report and a + `window/logMessage`, and counts the skips. It holds `&Connection` rather + than `&Server`, because the workspace is borrowed mutably for the whole of + the rebuild it is watching; `Server::new` and `reindex` therefore destructure + `self` into its `connection` and `workspace` fields around the call. Same + value, same operations, same order. +- `Server::notify` and `Server::progress` now delegate to free `notify_on` / + `progress_on` functions taking a `&Connection` — one implementation, two + callers, no duplicated send. +- `end_indexing` takes the skip count and says `"N files indexed, M skipped"` + when it is non-zero. +- `begin` still carries **no** percentage: the first honest one is the first + file's. + +### `editors/vscode` + +- Two new `contributes.configuration` properties. No `extension.js` change: + `synchronize: { configurationSection: 'lucisv' }` already pushes the whole + section including the nested `index` object, and `new LanguageClient('lucisv', + …)` already owns an output channel that `vscode-languageclient` appends every + `MessageType::LOG` message to verbatim. +- `smoke.js` sends `capabilities: {}` and no `index` section, so it takes the + no-bar path with the log at its default; it passes untouched. + +## Cost, measured + +Release build, this Mac, 860-file `corpus/`, min of three runs of a session +that does two full scans (startup + one save-triggered rescan): + +| progress | logFiles | wall | stdout | log lines | `report`s | +|---|---|---|---|---|---| +| off | off* | 668.8 ms | 1.16 MB | 860 | 0 | +| off | on | 670.9 ms | 1.34 MB | 1720 | 0 | +| on | off* | 687.0 ms | 1.50 MB | 860 | 1720 | +| on | on | 704.9 ms | 1.69 MB | 1720 | 1720 | + +\* the settings push lands *after* the startup scan, so the "off" rows still +carry the startup scan's 860 lines; only the second scan is quiet. That is +what makes the rows subtract cleanly. + +So, **per 860-file rescan**: 860 log lines ≈ 173 KB (≈ 201 B each, mostly +absolute path), 860 reports ≈ 160 KB (≈ 186 B each). Both features on cost +**≈ 18 ms on a ~690 ms two-scan session — about 2.6%**, and about 333 KB of +extra stdout per rescan. + +**Stated honestly: at 10,000 files the log is the part that gets ugly.** The +reports are throttled to at most 1000 per rescan whatever the size, so they +stay at ~190 KB; the log is not, so it would be ~2 MB of JSON on every save. +That is a real number and a real cost, and the follow-up is batching (one +`logMessage` per N files, or per directory) — **filed, not invented here**, +because a batching scheme designed without a user complaining about it would +be guessing at the wrong granularity. The escape hatch exists today: turn +`lucisv.index.logFiles` off. + +## The throttle rule + +```rust +const MAX_REPORTS: usize = 1000; +fn reports(done: usize, total: usize) -> bool { + let step = total.div_ceil(MAX_REPORTS).max(1); + (done + 1).is_multiple_of(step) || done + 1 == total +} +``` + +Up to 1000 files, `step` is 1 and every file reports. Past that, every +⌈total/1000⌉-th file reports — at most 1000 per rescan, so the bar still moves +in steps of a tenth of a percent, which is under a pixel. The `|| done + 1 == +total` is the reason 10,001 files do not leave the bar one file short of the +work it finished. Both regimes are pinned: the rule itself exhaustively for +nine sizes, and a real 1100-file workspace end to end. + +## Status / TODO + +- [x] `lucisv.index.maxFileSize`, bytes, default 1 MiB, `0` disables +- [x] Enforced on `fs::metadata` before the read, walked files only +- [x] Open buffers exempt, and pinned as such +- [x] A cap change rescans; `logFiles`, `lineLength`, `indent`, + `formatOnSave`, `inlineTemplates` still do not +- [x] `$/progress` `report`s carrying `n/total file.sv` and a real percentage +- [x] Throttled to ≤ 1000 reports per rescan, last file always reported +- [x] The same reports on the startup build and on every reindex trigger +- [x] `window/logMessage` (`MessageType::LOG`) per file, plus skip lines +- [x] Both gated by `lucisv.index.logFiles`, default on; skip **count** + survives with the log off, in the `end` message +- [x] `vlog_semantic::IndexBuilder` + `index_order`, with `build` redefined as + the loop over them and every existing test unchanged +- [x] `package.json` declares both settings, with the 0-disables semantics and + the open-buffer exemption in the descriptions +- [x] 21 new tests; 7 existing progress tests updated for the reports +- [ ] **Not done, deliberately:** no batching of the log lines. See "Cost, + measured" — the number is stated, the follow-up is named, and the + granularity is not guessed at. +- [ ] **Not done, deliberately:** no cap in `lucisv_core`'s walk or in the + CLI. `lucisv format` on a huge file must still format it. +- [ ] **Not done, deliberately:** no `lucisv.toml` key for the cap. It is an + editor-session resource setting, not a project style decision — the same + reason `serverPath` has no config key. +- [ ] **Filed, not done:** `vlog_refactor::rename::Scope::build` could call + `index_order` instead of re-deriving the sort/dedup. + +## Work log + +### 2026-08-27 — dev agent (indexing UX: cap, counting bar, per-file log) + +- **`vlog_semantic`: builder, not callback — and the reason is `FileId`.** + The brief allowed either and asked for a justification. The builder shape + did *not* fight the code, but it did expose an invariant: `build` sorted and + deduped privately, and both the file ids and a duplicate name's + disambiguation order depend on that. An `IndexBuilder` alone would have + pushed "remember to sort" onto every caller as a comment. Exporting + `index_order` beside it turns that into a call, and the server needed the + ordered list's *length* before parsing anyway (the progress denominator), so + the second public item has a real second use rather than being an + abstraction for a user that does not exist. `build` is now three lines over + the two of them; every existing `vlog_semantic` test is byte-identical and + green, which is the equivalence proof. +- **The cap went in `collect_sources`, one `fs::metadata` ahead of the read.** + That is the one place the walked list becomes text, so it is the cheapest + point and the only one where "never read the netlist" is true. Consequence + found and documented rather than papered over: `Workspace::sources()` — the + refactoring path — shares that function, so the cap reaches a workspace + rename too. That is the consistent reading of "which files exist as far as + this server is concerned", and it is now written down in Assumptions. +- **`ClientSettings::default()` is hand-written now.** Two settings whose + default is not silence (1 MiB, log on) cannot be derived, and pushing them + into `Option`s would have made every use site re-decide what unset means. + Every other field keeps the derive's value, so no existing + `..Default::default()` changed meaning — the whole suite passing unchanged + is the check. +- **A wrong-typed `maxFileSize` falls back to the default, not to 0.** This is + the one place this module's "drop it and go silent" rule needed a direction: + silence here is 1 MiB, because reading junk as 0 would silently un-cap. +- **Nested keys, because VS Code nests them.** `lucisv.index.maxFileSize` + arrives as `{"index": {"maxFileSize": …}}` through both doors; the parser + reads `lucisv.get("index")` once and a non-object `index` is the same as no + `index`. Pinned through `from_section` too, since these are the first nested + keys to go through the pull door. +- **`IndexWatch` holds `&Connection`, not `&Server`.** The workspace is + borrowed mutably for the whole rebuild, so `Server::new` and `reindex` + destructure `self` and hand the watcher the connection field. `notify` and + `progress` were re-pointed at free `notify_on`/`progress_on` functions so + there is still exactly one place a notification is sent. +- **The report message names the file, the log line names the path.** The bar + is a few dozen characters of status bar; the path belongs in the channel + that has room for it. +- **`human_size`, not a fixed MiB.** The first draft printed + `skipped (0.0 MiB > 0.0 MiB cap)` for a 4 KiB file under a 1 KiB cap — the + e2e test caught it. The cap is settable to anything, so the unit adapts: + bytes, KiB, MiB. +- **Seven existing tests were updated, all of them pinning "no report".** + That assumption is exactly what this round removes, so each one gained its + reports rather than being relaxed: + `the_startup_index_build_runs_under_the_first_bar`, + `a_save_puts_a_bar_up_and_takes_it_down_again`, + `the_bar_is_down_before_the_republish`, + `every_rescan_path_gets_its_own_bar_and_its_own_token` (its "no invented + percentages" line became "every report is inside its own bar", which is the + stronger property), + `the_refresh_rides_after_the_indexing_bar_comes_down`, + `the_startup_watcher_registration_arrives_after_the_indexing_bar_comes_down`, + `one_folder_notification_is_one_rescan_with_one_bar_and_one_generation`, plus + the e2e `indexing_reports_its_progress_over_the_wire`. +- **One surprise worth recording:** `package small;` does not index — + `small` is a SystemVerilog keyword (charge strength). Two new fixtures were + renamed to `small_pkg` after that cost ten minutes. +- Files touched: `crates/vlog_semantic/src/workspace.rs`, + `crates/vlog_semantic/src/lib.rs`, `crates/vlog_semantic/tests/workspace.rs`, + `crates/lucisv_server/src/settings.rs`, `crates/lucisv_server/src/state.rs`, + `crates/lucisv_server/src/server.rs`, `crates/lucisv_server/tests/e2e.rs`, + `editors/vscode/package.json`, `TODO.md`, + `docs/features/work-done-progress/README.md`, + `docs/features/lucisv-server/README.md`, this README. No new dependency, no + version bump, no `docs/site/`, no commits. + +**Verification.** `cargo fmt --all -- --check`: clean. `cargo clippy +--all-targets`: zero warnings. `cargo test --workspace`: **2197 passed, 0 +failed** (2176 on `HEAD` — 21 new). `cargo test -p vlog_formatter`: green. +`cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`: +`smoke: OK`. Corpus: 0 of 860 files exceed 1 MiB (largest, `picorv32.v`, is +94 KB), and the default-cap index is identical to the uncapped one — pinned +by a test, not just measured. + +The 21 tests, and what each is for: + +| test | pins | +|---|---| +| `the_size_cap_defaults_to_a_mebibyte_and_zero_turns_it_off` (settings) | the default, the empty sub-section, `0`, and no upper bound | +| `a_wrong_typed_size_cap_leaves_the_default_standing` (settings) | six wrong types, and four wrong shapes of `index` itself | +| `the_file_log_is_on_until_a_client_turns_it_off` (settings) | absence, both booleans, five wrong types | +| `the_index_settings_come_through_the_pull_door_too` (settings) | the nesting survives `from_section`, one set of rules | +| `a_walked_file_over_the_cap_is_left_out_of_the_index` (state) | the cap itself | +| `the_default_cap_is_a_mebibyte_and_zero_turns_it_off` (state) | a real >1 MiB file against the shipped default, then `0` | +| `an_open_buffer_is_indexed_however_big_the_file_is` (state) | the exemption | +| `every_skipped_file_is_reported_with_its_size_and_the_cap` (state) | the `Skipped` event's path, size and cap | +| `the_watcher_sees_every_file_in_index_order_against_a_total_it_knew_first` (state) | the denominator is post-exclude, post-cap; events are in index order | +| `the_default_cap_changes_nothing_about_the_real_corpus` (state) | cap-on == cap-off over `corpus/`, files and counts | +| `the_bar_counts_the_files_as_it_goes` (server) | `1/2 a.sv` at 50%, `2/2 b.sv` at 100% | +| `the_reports_thin_out_when_the_workspace_is_huge` (server) | 1100 real files: ≤1000 reports, monotonic, last is `1100/1100` | +| `the_report_schedule_never_floods_and_never_stops_short` (server) | the rule at 1, 2, 999, 1000, 1001, 1999, 2000, 12345, 40000 | +| `the_end_message_names_what_the_cap_skipped` (server) | `"1 file indexed, 1 skipped"`, with the log **off** | +| `a_capped_file_is_out_of_the_index_and_an_open_buffer_is_not` (server) | both halves of the cap through the real dispatch | +| `every_indexed_file_is_named_in_the_log_and_so_is_every_skip` (server) | one line per file, `MessageType::LOG`, the skip line's sizes | +| `the_file_log_goes_quiet_when_the_setting_is_off` (server) | not one line, skips included | +| `the_file_log_does_not_wait_for_a_progress_bar` (server) | the log is not gated on the progress capability | +| `a_new_cap_rescans_and_a_new_log_setting_does_not` (server) | the change detection, both directions, through `didChangeConfiguration` | +| `the_incremental_builder_is_what_build_is_made_of` (vlog_semantic) | builder == `build`: files, ids, counts, duplicate-path winner | +| `the_size_cap_and_the_file_log_work_over_the_wire` (e2e) | the real binary: nested setting → rescan → symbol gone, log lines, report and end message decoded off the wire | + +## QA log + +### 2026-08-27 — QA agent (one round: cap, counting bar, per-file log) + +**Gates.** `cargo fmt --all -- --check`: clean. `cargo clippy --all-targets +--workspace`: zero warnings. `cargo test --workspace`: **2197 passed, 0 +failed** (matches the dev's number exactly; one incidental failure of an +unrelated pre-existing timing-budget test, +`lens::tests::code_lenses_for_a_whole_file_cost_about_one_workspace_walk`, +during a run made while several other `cargo`/release builds were competing +for CPU in the background — reran clean in isolation twice, not a regression, +not touched by this round). `cargo test -p vlog_formatter`: 114 passed, +`verify.rs` untouched (confirmed via `git status`/`git diff` — it never +appears). `node smoke.js target/debug/lucisv-server`: OK. + +All temporary attack code below was added directly to the tracked files +listed, run, and then removed with a diff-identical revert verified against a +saved copy of the original `git diff` before continuing — no attack code +remains in the working tree. + +**1. FileId/ordering invariant — VERDICT: safe today, latent risk in the +abstraction.** `WorkspaceIndex::build` and `Workspace::rebuild_index_with` +(the only two callers of `IndexBuilder::add_file` in the tree) both feed it +`index_order`'s list, in order, so the two are provably identical — confirmed +independently by feeding a workspace with a case/depth-nontrivial duplicate +module name (`z_late.sv` / `a_early.sv`, both declaring `dup`) through `build` +and through a manual `index_order` + `IndexBuilder` loop: same `FileId`s, same +disambiguation winner (`a_early.sv` first, both ways). + +But `IndexBuilder` itself enforces nothing — it is a dumb accumulator, and the +ordering guarantee is carried entirely by the doc comment ("Feed it +`index_order`'s list"), not the type system. Direct attack, temporarily added +to `crates/vlog_semantic/tests/workspace.rs` and run: +```rust +let files = [ + ("z_late.sv", "module dup (input a); endmodule\n"), + ("a_early.sv", "module dup (input b); endmodule\n"), +]; +let mut wrong = IndexBuilder::new(); +for (p, s) in files { wrong.add_file(PathBuf::from(p), s); } // raw order, NOT index_order +let wrong = wrong.finish(); +let right = WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(*p), *s))); +assert_eq!(wrong.files(), right.files()); // FAILS +``` +Result: `wrong.files() == ["z_late.sv", "a_early.sv"]` vs. +`right.files() == ["a_early.sv", "z_late.sv"]` — `FileId(0)` and the `dup` +disambiguation winner both flip. So insertion order **does** leak into the +result the moment a caller bypasses `index_order`, exactly as the brief +warned. Severity: **MEDIUM, not HIGH** — both current production call sites +are verified correct, so this is not a live bug in this round's shipped code, +but it is a real footgun for the one thing the README itself flags as +"filed, not done" (`vlog_refactor::rename::Scope::build` migrating to +`IndexBuilder` later). Suggest, as a non-blocking follow-up: either have +`IndexBuilder::add_file` debug-assert paths arrive in non-decreasing order, +or fold `index_order` into `IndexBuilder` itself (e.g. buffer-then-sort on +`finish()`) so the invariant can't be bypassed by a future caller who didn't +read the doc comment. + +**2. The cap's blast radius through `sources()` — documentation gap, coherent +behavior.** `Workspace::sources()` is also consumed by +`crates/lucisv_server/src/hierarchy.rs:90` (codeLens counts / +`callers_of_each`), `ports.rs:61,87`, `nav.rs:132` (`find_references`), and +`type_hierarchy.rs:112` (subtypes) — not just `rename.rs`/`file_ops.rs`. The +indexing-ux README's Assumptions section and the `lucisv-server` README's new +paragraph name only the rename/refactoring reach ("a refactoring sees the cap +too"); the existing per-endpoint table rows for `callHierarchy/incomingCalls` +and `typeHierarchy/subtypes` (`docs/features/lucisv-server/README.md` lines +46 and 50) are untouched by this diff and say nothing about the cap, even +though those two consumers are exposed identically. The behavior itself is +coherent — a capped file is invisible everywhere consistently, nothing +dangles — but a future reader of those two table rows would not learn that a +netlist over the cap silently vanishes from an instantiation count or a +subtype list too. + +Concretely reproduced the rename case as the sharpest instance (temporarily +added to `crates/lucisv_server/src/rename.rs`, run, reverted): a workspace +with `sub.sv` (declares `sub`), `top.sv` (open, instantiates `sub`), and a +4 KB `netlist.sv` over a 1 KiB cap that *also* instantiates `sub`. Renaming +`sub` to `child`: +```rust +let (edit, warnings) = rename(&ws, &uri, at(TOP, "sub u_sub"), "child").expect("renames"); +// changes.len() == 2 (sub.sv, top.sv) — netlist.sv is absent +// warnings == [] — nothing at all says netlist.sv exists or was skipped +``` +So a rename leaves `netlist.sv` with a stale, now-broken reference to the old +name, **with zero warning anywhere in the rename response** — not in +`refactoring.warnings`, not in any diagnostic. The only place this is ever +surfaced is the output-panel skip line from whichever index build happened to +run earlier (`logFiles` on), which is decoupled in time from the specific +rename and easy to have scrolled past. Severity: **MEDIUM** — the "not +indexed → not rewritten" design is defensible and documented as intentional, +but the complete silence *at the point of the risky action* is a real UX gap. +Suggest as a follow-up: have `rename`/`find_references` check +`ws.sources()` against a cheap re-walk (or thread the skip list through) and +fold "N file(s) over the size cap may also reference this symbol" into +`refactoring.warnings` when the cap is non-zero. + +**3. Cap edge semantics.** +- **Exact boundary, pinned by hand (dev's suite doesn't cover it):** a file of + exactly 1024 bytes against a 1024-byte cap is **not** skipped — `oversize` + is `size > cap`, so the cap is inclusive (`≤ cap` survives). Verified with a + temporary test in `state.rs` creating a file measured at exactly 1024 bytes + on disk and confirming it appears in the index under a 1024-byte cap. + Correct and sensible, just untested — worth a permanent test. +- **Metadata failure:** confirmed consistent with the documented behavior — + `oversize`'s `fs::metadata(path).ok()?` returns `None` on failure, so the + file is not reported as skipped; it falls through to + `fs::read_to_string`, which will also fail for the same reason, and the + file is silently absent from `texts` exactly as it always was pre-cap. No + regression, no new silent-failure mode. +- **Growing file mid-scan:** not a race, as claimed — `oversize` and the read + are back-to-back for one file within one scan. +- **Symlinks:** verified directly (a symlink `link.sv` → a 5053-byte + `target_big.sv`, plus a `symlink_metadata` comparison showing 13 bytes for + the link itself vs. 5053 via `fs::metadata`). `oversize` uses `fs::metadata` + (follows the link), and so does the subsequent `fs::read_to_string` — the + cap is measured against the same bytes that would be read, not the + symlink's own size. Coherent, no bug. + +**4. Settings parsing.** +- Nested `{"index": {"maxFileSize": …}}` and the wrong-type→default fallback: + verified via the dev's own tests, both green. +- **Flat `{"index.maxFileSize": …}` shape (untested by the dev's suite):** + confirmed by a temporary test that `lucisv.get("index")` looks for a + literal `"index"` key, so a flattened dotted key is invisible to the parser + and silently resolves to the default (1 MiB) — same as `index` being + absent entirely. Coherent with the module's "drop it and go silent" + philosophy, but this specific shape isn't pinned by a test, unlike every + other edge case in this settings addition. Low-severity gap, easy add. +- Pull-door parity (`from_section`): verified via the dev's own test, green. + +**5. Throttle honesty.** The dev's own +`the_report_schedule_never_floods_and_never_stops_short` already covers the +rule exhaustively at 1, 2, 999, 1000, 1001, 1999, 2000, 12345, 40000, and +`the_reports_thin_out_when_the_workspace_is_huge` exercises it against 1100 +real files end to end. Both ran green in the full-suite run; no gaps found +worth a separate synthesis. + +**6. Logging gate.** Verified via the dev's own tests +(`the_file_log_goes_quiet_when_the_setting_is_off`, +`every_indexed_file_is_named_in_the_log_and_so_is_every_skip` asserting +`MessageType::LOG` specifically — not `INFO` — and +`the_file_log_does_not_wait_for_a_progress_bar`). All green. No gaps found. + +**7. The 8 updated tests.** Read every diff hunk. Seven of them +(`the_startup_index_build_runs_under_the_first_bar`, +`a_save_puts_a_bar_up_and_takes_it_down_again`, +`the_bar_is_down_before_the_republish`, +`the_refresh_rides_after_the_indexing_bar_comes_down`, +`the_startup_watcher_registration_arrives_after_the_indexing_bar_comes_down`, +`one_folder_notification_is_one_rescan_with_one_bar_and_one_generation`, and +the e2e `indexing_reports_its_progress_over_the_wire`) only insert `"report"` +entries into an already-asserted ordering sequence — their original point +(bar goes up, comes down, in the right place relative to X) is intact. +The eighth, `every_rescan_path_gets_its_own_bar_and_its_own_token`, is the one +whose point *was* "no report is ever invented" — that assumption is exactly +what this round removes, and it is replaced with the strictly stronger "every +report belongs to a currently-open bar" check, under an explicit `// Superseded +this round:` comment. That is the correct way to retire an assumption per +CLAUDE.md's house style, and it is the one case that needed it. + +**8. CLAUDE.md compliance.** +- No `unwrap()`/`expect()`/`panic!` outside `#[cfg(test)]` in any touched + non-test code (`server.rs`, `settings.rs`, `state.rs`, `workspace.rs`, + `lib.rs`) — checked directly, clean. +- Every new `pub` item (`index_order`, `IndexBuilder` + its three methods, + `IndexEvent`, `open_roots_with`, `rebuild_index_with`) has a doc comment. +- The feature README has all seven required sections exactly once (plus two + extra informational sections, "Cost, measured" and "The throttle rule", + which CLAUDE.md doesn't forbid). +- The superseded-assumption annotations in `TODO.md`, + `docs/features/work-done-progress/README.md`, and + `docs/features/folders-and-config/README.md` all follow the existing house + style (`~~struck~~` + a dated "Superseded ... by ..." note that keeps the + original reasoning legible) consistently. +- `verify.rs` is untouched — confirmed absent from `git status` and `git + diff` entirely. +- The new corpus-gated tests (`the_default_cap_changes_nothing_about_the_real_corpus` + in `state.rs`) follow the `if !corpus.is_dir() { eprintln!("corpus/ not + checked out — skipping"); return; }` convention exactly as the pre-existing + corpus tests in `vlog_semantic` do. + +**C. Beyond the list.** +- **`maxFileSize: 1`** (temporary test in `state.rs`): every walked file + skipped, index ends up with 0 files (not a panic, not an error), and an + opened buffer is still indexed in full afterward. Server stays functional + at the extreme. +- **`logFiles` toggled mid-session:** already covered by the dev's own + `the_end_message_names_what_the_cap_skipped` (toggles `logFiles` false in + the same session as a cap change) and `a_new_cap_rescans_and_a_new_log_setting_does_not`. + Both green; no gap found. +- **Overhead measurement, ~18 ms / 2.6% claim:** attempted an independent + spot-reproduction twice (a release/LTO build that did not finish in + reasonable time in this sandboxed environment, then a debug-mode custom + harness that hit a broken pipe in its own scratch code talking to the real + binary over a hand-rolled 860-file corpus session — a bug in the throwaway + harness, not reproduced against the dev's own passing corpus-based tests). + Not independently re-measured; **not verified numerically**. The mechanism + itself is architecturally sound for the claimed order of magnitude — one + extra `fs::metadata` call and one extra `window/logMessage`/`$/progress` + notification per file, both cheap, no additional passes over file content — + so I have no reason to doubt the figure, but I did not confirm it myself. +- **`human_size` rounding boundary — new finding, LOW-MEDIUM, cosmetic + only.** `human_size(1_048_575)` (one byte under 1 MiB) prints `"1024.0 + KiB"` instead of switching to the MiB branch, because `1_048_575.0 / 1024.0 + == 1023.999...` is `< MIB` so it takes the KiB arm, then rounds *up* to + `1024.0` at `{:.1}` precision. Same failure mode one level up: + `human_size(1_073_741_823)` (one byte under 1 GiB, which this function has + no branch for) prints `"1024.0 MiB"`. Verified directly: + ``` + 1048575 -> 1024.0 KiB + 1073741823 -> 1024.0 MiB + ``` + This is the same class of bug the e2e test already caught once (`"0.0 MiB > + 0.0 MiB"`), just at the opposite (upper) rounding edge, and only reachable + today via a skip line whose size or cap happens to land in one of those + windows — cosmetic, no effect on cap enforcement or index correctness. + Worth a follow-up fix (e.g. bump the branch threshold down by half a unit, + or format then re-check which unit the rounded string actually names). + +**Verdict: committable as-is.** No correctness regression, no invariant +violated, all four gates green, 2197/2197 tests passing. Two MEDIUM findings +(the `IndexBuilder` ordering footgun, and the silent rename-blast-radius gap) +are both documented-intentional-behavior-with-an-honesty-gap rather than bugs +in what shipped, and are appropriately deferred as dev follow-ups rather than +blockers. One LOW-MEDIUM new cosmetic finding (`human_size` rounding) and two +LOW test-coverage gaps (exact-boundary cap, flat settings key) are cheap to +add later and do not affect behavior today. + +## Review + +### 2026-08-27 — lead + +Reviewed the diff, the work log and the QA log; re-ran all gates myself, +clean. The three features land the way the owner asked and the details +show the right instincts: junk cap values fall back to 1 MiB rather +than 0 (misparse must never un-cap), the denominator is the real work +list known before the first parse, the skip count outlives the log +toggle, and the vlog_semantic change follows the established +redefinition pattern with `index_order` exported so the FileId +ordering rule is a call, not a comment. + +Rulings on QA's findings. The builder-ordering footgun (MEDIUM) is +real and correctly assessed as latent — both production callers funnel +through index_order, proven by QA's both-ways construction — and the +fix belongs to the next round, whose scope work is precisely the +future caller at risk: round 18's brief requires making the builder +order-insensitive or formally enforcing the contract, with QA's attack +as the acceptance test. The cap blast radius (MEDIUM) is accepted as +the one coherent reading — absent from every layer equally — and I +have expanded the Assumptions to name every consumer, with the +write-path warning gap (a rename silently leaving a capped file's text +stale) filed as a visible follow-up task rather than buried. The +human_size rounding bug (LOW) I fixed directly with the unit chosen by +what the rounded number reads as, plus the boundary test. The +unreproduced 18 ms overhead claim stands as the dev's measurement with +QA's non-verification noted — the mechanism is sound and the number is +not load-bearing. Accepted as shipped. diff --git a/docs/features/lucisv-server/README.md b/docs/features/lucisv-server/README.md index 5c83717..3052716 100644 --- a/docs/features/lucisv-server/README.md +++ b/docs/features/lucisv-server/README.md @@ -234,7 +234,7 @@ reasoning and the measurements: `docs/features/cancel-request/README.md`. | layer | rebuilt when | cost | |---|---|---| | a document's `Semantics` + tokens + diagnostics | every `didOpen`/`didChange` — **once per notification**, however many ranges it carried | one file, full recompute | -| the `WorkspaceIndex` | `initialize`, every `didSave`, every `workspace/didChangeWatchedFiles`, every `workspace/didChangeWorkspaceFolders` that moves the root set, and a changed `lucisv.exclude`/`lucisv.filelist` (pushed **or** pulled) | full re-scan of the roots | +| the `WorkspaceIndex` | `initialize`, every `didSave`, every `workspace/didChangeWatchedFiles`, every `workspace/didChangeWorkspaceFolders` that moves the root set, and a changed `lucisv.exclude`/`lucisv.filelist`/`lucisv.index.maxFileSize` (pushed **or** pulled) | full re-scan of the roots | | the `` `include`` graph | with the `WorkspaceIndex`, from the same file list | a line scan per file (~6ms over the 860-file corpus). An open buffer's *own* includes are re-resolved on every request instead, so a line just typed is clickable before the next save | **Per-file recompute on every keystroke** is the strategy TODO.md §6 states @@ -249,6 +249,17 @@ each file read, and then every open document with a path replaces the disk copy (adding itself if it exists only in the editor). So the index never disagrees with a buffer the user is looking at. +**Walked files over `lucisv.index.maxFileSize` (1 MiB by default) are not read +at all** — the size is taken from `fs::metadata` before the read, so a +generated netlist costs one `stat` rather than minutes of parsing. The cap is +on the *walk* only: an open buffer is folded in above, uncapped, because the +user opened it deliberately. `0` disables the cap, and the skipped count is +named in the progress bar's `end` message. Since the whole cap lives in +`collect_sources`, `Workspace::sources()` sees it too, so a workspace rename +does not rewrite a file the index does not hold. Rules, corpus numbers and the +per-file `window/logMessage` that accompanies a rescan: +`docs/features/indexing-ux/README.md`. + **The staleness window, stated plainly.** The index is rebuilt on save, not on change. Between editing file A and saving it, file B's cross-file answers (`definition` into A, `workspace/symbol` hits in A, hover falling back to A's diff --git a/docs/features/work-done-progress/README.md b/docs/features/work-done-progress/README.md index 7f9d41c..472caae 100644 --- a/docs/features/work-done-progress/README.md +++ b/docs/features/work-done-progress/README.md @@ -36,13 +36,20 @@ progress a client never asked for (TODO.md §9b). file-watcher (un)registrations use. Nothing is retried and nothing is remembered: the ids are minted from the one shared `request_ids` counter, so a progress answer can never be mistaken for an `applyEdit` answer. -- **No percentage, and no intermediate `report`.** `Workspace::rebuild_index` - is one opaque call: it walks the roots, reads every file, builds the index, - the completion tables and the include graph, and returns. There is no - progress to observe without threading a callback through three engine - layers, and an invented percentage — "it is probably about half done" — is a - lie the user would learn to distrust. An indeterminate bar is the honest - shape. +- ~~**No percentage, and no intermediate `report`.**~~ **Superseded + 2026-08-27 by `docs/features/indexing-ux/README.md`.** The original reasoning + stands as written and is kept here: `Workspace::rebuild_index` *was* one + opaque call — it walked the roots, read every file, built the index, the + completion tables and the include graph, and returned — so there was no + progress to observe, and an invented percentage ("it is probably about half + done") would have been a lie the user learned to distrust. The indeterminate + bar was the honest shape *for a build nobody could see inside*. What changed + is the premise, not the principle: `vlog_semantic` now exposes + `IndexBuilder`/`index_order`, `rebuild_index_with` drives that loop, and the + bar reports `n/total file.sv` with a percentage that is **counted, not + guessed**. The `begin` still carries no percentage — the first honest one is + the first file's — and the completion tables and include graph, which are + still built opaquely after the index, are still outside the count. - **The end message is the index's own file count**, read from `WorkspaceIndex::files().len()` after the scan. That number was already public and already computed; nothing was plumbed to obtain it. It counts the @@ -123,6 +130,11 @@ verified by running it. - [x] Tests: 8 unit (7 in `server.rs`, 1 in `main.rs`), 2 e2e over the wire - [x] TODO.md §9b checkbox, `docs/features/lucisv-server/README.md` staleness section +- [x] **Superseded 2026-08-27:** the "no percentage, no report" line above. + The counting reports, the size cap and the per-file log are + `docs/features/indexing-ux/README.md`; the create/begin/end skeleton, + the capability gate, the token scheme and the ordering against the + republish are all unchanged by it. - [ ] **Not done, deliberately:** no `$/progress` on anything else. Formatting, a rename across the workspace and `callHierarchy/incomingCalls` are the other candidates; all three are request-scoped, so they would use the diff --git a/editors/vscode/package.json b/editors/vscode/package.json index f6d732f..402985b 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -234,6 +234,17 @@ "type": "string", "default": "", "markdownDescription": "Path to an EDA filelist (`.f`), absolute or relative to the workspace folder. When set, **exactly** the files it names are indexed instead of the whole folder — `-f` nesting, `+incdir+`, `+define+`, `#`/`//` comments and `$VAR` expansion are all understood. Overrides a `filelist` key in the project's `lucisv.toml`; leave it empty to index the workspace folder." + }, + "lucisv.index.maxFileSize": { + "type": "number", + "default": 1048576, + "minimum": 0, + "markdownDescription": "Largest file, in bytes, the workspace index will read while scanning your folders. Anything bigger is almost always a generated netlist rather than a design file, and indexing one costs minutes and answers nothing. Set to `0` for no cap. A file you **open** is always indexed in full, however big it is — the cap applies to the folder scan only. Changing this rescans the workspace." + }, + "lucisv.index.logFiles": { + "type": "boolean", + "default": true, + "markdownDescription": "Name every file in the lucisv output channel as it is indexed, and every file the size cap skipped. Useful for finding out why a symbol is missing or why a scan is slow; turn it off if you would rather the channel stayed quiet. Files skipped by `#lucisv.index.maxFileSize#` are counted in the progress bar's final message either way." } } }