The didOpen delay: undriven-net asks the workspace census last, not once per declaration

TODO §46 (docs/features/didopen-cost). Closes take-3 finding §8.4 (§44b).

Measured first: on opentitan the open of a 42 192-line file cost
1 745 ms, of which the lint pass was 1 654 ms and `undriven-net` alone
1 608 ms — the rule asked `WorkspaceIndex::files_mentioning` (a walk over
all 3 976 indexed files) once per declaration, ahead of the local guards
that silence almost all of them. Six lines reordered so the oracle is
asked last, as `unused-signal` always did: same findings, same order
(pinned by a counting-oracle unit test that fails on a revert, and shown
byte-identical against 0.43.0 over a crafted workspace and four opentitan
IPs). didOpen → next request: 1 742 → 117 ms on the largest file,
51–95 → 5–8 ms on typical IPs, the same on every keystroke flush. No
debounce added; three wire-level pins with a debug-build bound.

Docs: take-3 §8.4 annotated, docs/perf/README.md entry.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5.1 committed 2026-09-05 08:15:37 -05:00
1 parent f7956060b3
commit 8145a67be6
6 files changed
+972 -18

No files matched your search

+204
View File
@@ -7963,3 +7963,207 @@ fn the_cli_and_the_server_run_the_same_rules_for_the_same_buffer() {
let _ = std::fs::remove_dir_all(&dir);
}
}
// ---------------------------------------------------------------------------
// TODO.md §46 — what a `didOpen` costs the request behind it
// ---------------------------------------------------------------------------
//
// `talk` writes a whole session before reading a byte, which is what every
// test above wants and what a *timing* test cannot use: the number this round
// is about is the gap between the `didOpen` frame going out and the next
// response coming back. `Live` — the held-open session two hundred lines up —
// is the one that can measure it. The three tests below are §46's contract:
// the open returns to the loop fast, the first request after it is answered
// from the **buffer**, and the diagnostics still arrive with no edit and no
// further request behind them.
/// A started session over `root`, indexed at the whole-workspace scope with
/// the scan already run — the barrier request at the end is what makes that
/// true, since the loop answers nothing until a rescan a message asked for has
/// finished.
fn live_at(root: &Path) -> Live {
let mut live = Live::start();
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"file://{}","capabilities":{{}}}}}}"#,
root.display()
));
live.wait_for(|m| m["id"] == 1);
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
live.send(WIDE_SCOPE);
live.send(r#"{"jsonrpc":"2.0","id":2,"method":"workspace/symbol","params":{"query":"zzz"}}"#);
live.wait_for(|m| m["id"] == 2);
live
}
/// The `didOpen` frame for a buffer.
fn open_frame(uri: &str, text: &str) -> String {
format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(text).expect("json")
)
}
/// Open `uri` and ask for a `hover` in the same write, and report how long the
/// hover took to come back.
///
/// That wait *is* the open: the loop is synchronous, so whatever the open does
/// before returning to it is what the hover queues behind.
fn open_then_hover(live: &mut Live, id: u32, uri: &str, text: &str) -> std::time::Duration {
let hover = format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":0,"character":8}}}}}}"#
);
let started = std::time::Instant::now();
live.send(&open_frame(uri, text));
live.send(&hover);
live.wait_for(|m| m["id"] == id);
started.elapsed()
}
/// A workspace of `files` small packages, so the index holds a *project*
/// rather than one buffer — which is what switches the cross-file lint rules
/// on at all (`LintRun::for_document`).
fn indexed_neighbours(dir: &Path, files: usize) {
for k in 0..files {
std::fs::write(
dir.join(format!("pkg{k}.sv")),
format!("package pkg{k};\n localparam int K{k} = {k};\nendpackage\n"),
)
.expect("write neighbour");
}
}
/// §46's contract, on the wire: a `didOpen` of a 2 000-line buffer must not
/// leave the request behind it waiting.
///
/// **An upper bound, not a benchmark, and a debug-build one.** `cargo test`
/// builds unoptimized, where one tolerant parse of 2 000 lines is ~53 ms all
/// by itself — measured on this machine, and stable to a millisecond across
/// runs. So the 200 ms here is that floor with room for a loaded CI box, not
/// the ≤ 25 ms §46 asked for: **that figure is a release number**, and the
/// release binary opens the same buffer in 2–4 ms.
///
/// **What this test does and does not catch.** It catches an open that starts
/// doing something *unbounded* — the shape §46 fixed. It cannot catch the
/// §46 defect itself at this size: the census walk that cost 1.6 s on
/// opentitan's 42 000-line `pinmux_reg_top.sv` costs milliseconds over a
/// forty-file fixture, and a fixture of opentitan's four thousand files has
/// no business in a unit-test suite. The exact pin for that is
/// `undriven_net`'s `the_project_is_asked_only_about_the_signals_that_would_be_reported`,
/// which counts the questions instead of timing them
/// (`docs/features/didopen-cost/README.md`).
///
/// Best of three distinct buffers: the first open of a process pays cold code
/// paths that have nothing to do with the buffer, and a wall-clock assertion
/// that cannot tolerate one scheduling hiccup is a flake, not a pin.
#[test]
fn opening_a_two_thousand_line_buffer_does_not_delay_the_request_behind_it() {
let dir = temp_dir("didopen_cost");
indexed_neighbours(&dir, 40);
let mut generated = Vec::new();
for n in 0..3 {
let name = format!("gen{n}");
// The generator the perf tables use: a thousand declarations, every
// one declared, driven and read — the cheap case for the *findings*
// and the expensive one for the walk that decides there are none.
let text = generated_module(&name, 2_000);
assert!(text.lines().count() >= 2_000, "the premise: a 2 000-line buffer");
let path = dir.join(format!("{name}.sv"));
std::fs::write(&path, &text).expect("write");
generated.push((path, text));
}
let mut live = live_at(&dir);
// A warm-up open of a small buffer, for the cold code paths.
let warm = format!("file://{}", dir.join("pkg0.sv").display());
open_then_hover(&mut live, 10, &warm, "package pkg0;\n localparam int K0 = 0;\nendpackage\n");
let mut best = std::time::Duration::MAX;
for (n, (path, text)) in generated.iter().enumerate() {
let uri = format!("file://{}", path.display());
best = best.min(open_then_hover(&mut live, 20 + n as u32, &uri, text));
}
live.finish();
let _ = std::fs::remove_dir_all(&dir);
assert!(
best <= std::time::Duration::from_millis(200),
"a didOpen of a 2 000-line buffer delayed the next request by {best:?}"
);
}
/// The other half of §46's contract: the request after an open is answered
/// from the **buffer**, not from what is on disk.
///
/// Nothing about the open was deferred — it still analyzes the buffer before
/// it returns to the loop — and this is what says so out loud. The buffer
/// names something the file on disk does not, and declares it on a line the
/// disk file does not, and the very first hover and the very first definition
/// after the open both find the buffer's.
#[test]
fn the_first_hover_after_an_open_sees_the_buffer_and_not_the_disk() {
let dir = temp_dir("didopen_buffer_wins");
indexed_neighbours(&dir, 4);
let file = dir.join("m.sv");
std::fs::write(
&file,
"module m;\n localparam int ON_DISK = 1;\n logic a;\n assign a = ON_DISK;\nendmodule\n",
)
.expect("write");
let uri = format!("file://{}", file.display());
// What the editor holds: a different name, declared on a different line.
let buffer = "module m;\n\n localparam int IN_BUFFER = 2;\n logic a;\n \
assign a = IN_BUFFER;\nendmodule\n";
let mut live = live_at(&dir);
live.send(&open_frame(&uri, buffer));
// The cursor on `IN_BUFFER` where line 4 reads it.
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":30,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":4,"character":16}}}}}}"#
));
let card = live.wait_for(|m| m["id"] == 30)["result"]["contents"]["value"]
.as_str()
.unwrap_or_default()
.to_string();
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":31,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":4,"character":16}}}}}}"#
));
let definition = live.wait_for(|m| m["id"] == 31);
live.finish();
let _ = std::fs::remove_dir_all(&dir);
assert!(card.contains("IN_BUFFER"), "the first hover did not read the buffer: {card:?}");
assert!(!card.contains("ON_DISK"), "the first hover read the disk file: {card:?}");
let locations = definition["result"].as_array().expect("an array of locations");
assert_eq!(locations.len(), 1, "one declaration, got {locations:#?}");
assert_eq!(locations[0]["range"]["start"]["line"], 2, "the buffer's line, not the disk's");
}
/// And the third: the open still publishes, with no edit and no further
/// request to trigger it.
///
/// **There is no debounce on the open.** §46 allowed the diagnostics to be
/// moved onto the change debounce and to arrive one quiet period later; they
/// were not, because the cost was never the publish — it was one rule inside
/// it. So the guarantee is the one this server has always had: the diagnostics
/// for an opened buffer go out inside the `didOpen`, ahead of anything queued
/// behind it.
#[test]
fn an_open_still_publishes_its_diagnostics_with_no_edit_behind_it() {
let dir = temp_dir("didopen_publishes");
indexed_neighbours(&dir, 4);
let file = dir.join("tabbed.sv");
let text = "module tabbed;\n\twire a;\nendmodule\n";
std::fs::write(&file, text).expect("write");
let uri = format!("file://{}", file.display());
let mut live = live_at(&dir);
live.send(&open_frame(&uri, text));
let published = live.wait_for(|m| {
m["method"] == "textDocument/publishDiagnostics" && m["params"]["uri"] == uri
});
live.finish();
let _ = std::fs::remove_dir_all(&dir);
let items = published["params"]["diagnostics"].as_array().expect("a diagnostics array");
let codes: Vec<&str> = items.iter().filter_map(|d| d["code"].as_str()).collect();
assert!(codes.contains(&"no-tabs"), "the open published nothing about the tab: {items:#?}");
}
+61 -10
View File
@@ -68,13 +68,6 @@ impl Rule for UndrivenNet {
if intentionally_unused(&decl.name) || !signals.judgeable(decl) || decl.has_init {
continue;
}
// A name another file in the project writes down may be driven
// from there — a hierarchical assignment, a `force` in a
// testbench, a `bind`-ed override — none of which this file can
// see. Silence is the only honest answer.
if ctx.mentioned_elsewhere(&decl.name) {
continue;
}
let Some(usage) = signals.usage(decl) else { continue };
// A `release`/`deassign` is a write that establishes no value, so
// it is not what saves a signal from this rule.
@@ -82,6 +75,25 @@ impl Rule for UndrivenNet {
if signals.connected(decl) || driven || usage.reads == 0 {
continue;
}
// A name another file in the project writes down may be driven
// from there — a hierarchical assignment, a `force` in a
// testbench, a `bind`-ed override — none of which this file can
// see. Silence is the only honest answer.
//
// **Asked last, of the handful of declarations that would
// otherwise be reported**, and not second, of every declaration in
// the file: the oracle walks every indexed file's word list per
// question (`WorkspaceIndex::files_mentioning`), so at the position
// this check used to sit at, a 42 000-line buffer asked it four
// thousand times and the rule cost 1.6 s of every `didOpen` and
// every keystroke flush. The guards above are all local and all
// O(1)-ish, the whole condition is one conjunction of `continue`s,
// and `unused-signal` — the twin rule with the same oracle — has
// always asked last. Same findings, in the same order
// (`docs/features/didopen-cost/README.md`).
if ctx.mentioned_elsewhere(&decl.name) {
continue;
}
found.push(Violation::new(
NAME,
format!("`{}` is read but never driven", decl.name),
@@ -107,17 +119,56 @@ mod tests {
.collect()
}
/// An oracle that says exactly these names are mentioned in another file.
struct Elsewhere(&'static [&'static str]);
/// An oracle that says exactly these names are mentioned in another file,
/// and counts how often it was asked.
struct Elsewhere(&'static [&'static str], std::sync::atomic::AtomicUsize);
impl Elsewhere {
fn new(names: &'static [&'static str]) -> Elsewhere {
Elsewhere(names, std::sync::atomic::AtomicUsize::new(0))
}
}
impl crate::MentionOracle for Elsewhere {
fn mentioned_elsewhere(&self, name: &str) -> bool {
self.1.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
self.0.contains(&name)
}
}
/// TODO.md §46: the oracle is asked about the declarations that would
/// otherwise be **reported**, not about every declaration in the file.
///
/// One question per real candidate is the whole of the fix: the server's
/// oracle walks every indexed file's word list per question, so asking it
/// ahead of the local guards cost 1.6 s of every `didOpen` of opentitan's
/// 42 000-line `pinmux_reg_top.sv` — see
/// `docs/features/didopen-cost/README.md`. Asserted on the count, because
/// the findings alone cannot tell the two orders apart.
#[test]
fn the_project_is_asked_only_about_the_signals_that_would_be_reported() {
// Ten signals: nine driven and read, one read and undriven.
let mut src = String::from("module m (output logic q);\n");
for k in 0..9 {
src.push_str(&format!(" wire d{k};\n assign d{k} = 1'b0;\n"));
}
src.push_str(" wire lonely;\n assign q = lonely");
for k in 0..9 {
src.push_str(&format!(" ^ d{k}"));
}
src.push_str(";\nendmodule\n");
let oracle = Elsewhere::new(&[]);
let ctx = LintContext::new(&src, None).with_oracle(&oracle);
let found = UndrivenNet.check(&ctx);
assert_eq!(found.len(), 1, "only the undriven one: {found:#?}");
assert!(found[0].message.contains("lonely"), "{:?}", found[0].message);
let asked = oracle.1.load(std::sync::atomic::Ordering::Relaxed);
assert_eq!(asked, 1, "the project was asked about the driven signals too");
}
fn names_in_a_project(src: &str, elsewhere: &'static [&'static str]) -> Vec<String> {
let oracle = Elsewhere(elsewhere);
let oracle = Elsewhere::new(elsewhere);
let ctx = LintContext::new(src, None).with_oracle(&oracle);
UndrivenNet
.check(&ctx)