Typing costs one reanalysis per burst, not one per keystroke
Every `didChange` used to run a full reparse, reanalysis, lint and diagnostics publish. In a 10 000-line buffer that is 31 ms of work per keystroke, nearly all of it thrown away by the next one. The text stays exactly current after every notification — incremental sync is applied immediately, and while a change is pending the buffer the server holds *is* the pending text. Only the analysis is deferred, and it is flushed by the first thing that needs it: the next request, the next non-`didChange` notification, or a 150 ms quiet-period timer in the message loop. Requests therefore see exactly what they saw before; nothing answers from a stale buffer. The invariant this replaces was "one didChange = one set_document = one generation bump". It is now one *flush* = one `set_document` per dirty buffer. The observable consequence is that intermediate diagnostics states are no longer published, which the e2e test pins: what is drawn is always a state the buffer really passed through, there are simply fewer of them. Closing a buffer drops its pending text before the flush rather than after it, so a file closed mid-edit is not analyzed and republished for nobody a line before its squiggles are cleared. Also measures it over the wire, against the shipped binary: a burst of ten keystrokes produces one `publishDiagnostics`, counted at the drain rather than reasoned about. The burst is measured last, because every `wait_for` accepts any publish and an earlier position would let a second one be absorbed by the next row's wait and never counted. Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
1 parent
d94f9e3de0
commit
a4f23db2c7
2 files changed
+378
-50
No files matched your search
@@ -155,8 +155,21 @@ pub struct Server {
|
||||
/// one token, and a token is never reused: a client keys the bar it is
|
||||
/// showing off it.
|
||||
indexings: u32,
|
||||
/// Buffers that are text-current but analysis-stale: the newest applied
|
||||
/// text for each, in first-dirtied order. A `didChange` lands here instead
|
||||
/// of running a reparse, and every one of them is flushed — analyzed,
|
||||
/// republished — by the first thing that needs the analysis: the next
|
||||
/// request, the next non-`didChange` notification, or the quiet-period
|
||||
/// timer in `run`. See `docs/features/change-debounce/README.md`.
|
||||
dirty: Vec<(Uri, String)>,
|
||||
}
|
||||
|
||||
/// How long a burst of `didChange` notifications may sit unanalyzed once the
|
||||
/// typing has stopped, before the quiet-period timer flushes them anyway. The
|
||||
/// coalescing this buys — one reparse per burst instead of one per keystroke —
|
||||
/// is worth nothing if diagnostics never arrive until the next request does.
|
||||
const CHANGE_DEBOUNCE: std::time::Duration = std::time::Duration::from_millis(150);
|
||||
|
||||
/// What the workspace-rescan progress bar calls itself. One title for every
|
||||
/// rescan — startup, save, watched file, changed scope — because they are the
|
||||
/// same work and a user reading the status bar wants to know that.
|
||||
@@ -224,6 +237,7 @@ impl Server {
|
||||
tokens: HashMap::new(),
|
||||
token_results: 0,
|
||||
indexings: 0,
|
||||
dirty: Vec::new(),
|
||||
};
|
||||
// Nothing has been built yet, so there is no rebuild to owe: the
|
||||
// `true` this returns for a non-default `client` is the rebuild that
|
||||
@@ -270,14 +284,33 @@ impl Server {
|
||||
/// `$/cancelRequest` mean anything: while a handler runs, the client's
|
||||
/// later requests and its cancels for them pile up together, and a cancel
|
||||
/// found next to its request answers that request for free.
|
||||
///
|
||||
/// A buffer sitting dirty past [`CHANGE_DEBOUNCE`] with nothing arriving is
|
||||
/// flushed here rather than left waiting for a request that may never
|
||||
/// come — diagnostics are the one answer the client never asks for.
|
||||
pub fn run(&mut self) -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
use std::sync::mpsc::RecvTimeoutError;
|
||||
let queue = self.queue();
|
||||
while let Ok(message) = queue.recv() {
|
||||
loop {
|
||||
let message = if self.dirty.is_empty() {
|
||||
match queue.recv() {
|
||||
Ok(message) => message,
|
||||
Err(_) => return Ok(()),
|
||||
}
|
||||
} else {
|
||||
match queue.recv_timeout(CHANGE_DEBOUNCE) {
|
||||
Ok(message) => message,
|
||||
Err(RecvTimeoutError::Timeout) => {
|
||||
self.flush_dirty();
|
||||
continue;
|
||||
}
|
||||
Err(RecvTimeoutError::Disconnected) => return Ok(()),
|
||||
}
|
||||
};
|
||||
if self.process_batch(burst(&queue, message))? {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Move the incoming messages onto a queue of our own, and report it.
|
||||
@@ -355,6 +388,12 @@ impl Server {
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
fn request(&mut self, request: Request) -> Response {
|
||||
// A request answers from a buffer's analysis, so any change the client
|
||||
// has already sent is in effect before it is answered — the order
|
||||
// contract the loop has always promised. Here is also where a typing
|
||||
// burst is coalesced: the changes before this request all become one
|
||||
// `set_document` in `flush_dirty`.
|
||||
self.flush_dirty();
|
||||
let id = request.id.clone();
|
||||
let method = request.method.clone();
|
||||
// The large-file fast path answers first, and for most methods it
|
||||
@@ -1207,6 +1246,24 @@ impl Server {
|
||||
|
||||
fn notification(&mut self, notification: Notification) {
|
||||
let method = notification.method.clone();
|
||||
// A closing buffer's pending text is dropped *before* the flush, not
|
||||
// in the `didClose` arm below it: the flush would otherwise analyze
|
||||
// and publish diagnostics for a file the client has stopped looking
|
||||
// at, only for the close handler to clear them again a line later.
|
||||
// Every other dirty buffer still flushes, as it must — closing one
|
||||
// file says nothing about the rest (QA, change-debounce CD-1).
|
||||
if method == DidCloseTextDocument::METHOD {
|
||||
if let Some(uri) = closing_uri(¬ification) {
|
||||
self.dirty.retain(|(pending, _)| *pending != uri);
|
||||
}
|
||||
}
|
||||
// Everything but a `didChange` needs the buffers' analyses current —
|
||||
// a `didSave` rebuilds the index on top of them — so the same flush a
|
||||
// request gets happens here, with the one exception that *is* the
|
||||
// thing being deferred.
|
||||
if method != DidChangeTextDocument::METHOD {
|
||||
self.flush_dirty();
|
||||
}
|
||||
match method.as_str() {
|
||||
DidOpenTextDocument::METHOD => {
|
||||
if let Ok(p) = extract::<DidOpenTextDocumentParams>(notification) {
|
||||
@@ -1235,19 +1292,28 @@ impl Server {
|
||||
DidChangeTextDocument::METHOD => {
|
||||
if let Ok(p) = extract::<DidChangeTextDocumentParams>(notification) {
|
||||
// Incremental sync: the changes are ranges into the buffer
|
||||
// we hold, applied in order. A full-sync client's
|
||||
// rangeless change still replaces the whole buffer, so
|
||||
// "the last one wins" stays true for it. One notification
|
||||
// is one `set_document` — one reparse, one generation
|
||||
// bump — however many ranges it carried.
|
||||
// we hold — the newest applied text, which while dirty is
|
||||
// the pending one, not the last analyzed one — applied in
|
||||
// order. A full-sync client's rangeless change still
|
||||
// replaces the whole buffer, so "the last one wins" stays
|
||||
// true for it. A burst of changes is coalesced into one
|
||||
// `set_document` — one reparse, one generation bump — when
|
||||
// the buffer is flushed; see `mark_dirty`.
|
||||
if p.content_changes.is_empty() {
|
||||
return;
|
||||
}
|
||||
let uri = p.text_document.uri;
|
||||
let base = self.workspace.document(&uri).map_or("", |doc| doc.text.as_str());
|
||||
let text = sync::apply_changes(base, &p.content_changes);
|
||||
self.set_document(uri.clone(), text);
|
||||
self.publish(&uri);
|
||||
let text = {
|
||||
let base = self
|
||||
.dirty
|
||||
.iter()
|
||||
.find(|(pending, _)| *pending == uri)
|
||||
.map(|(_, text)| text.as_str())
|
||||
.or_else(|| self.workspace.document(&uri).map(|doc| doc.text.as_str()))
|
||||
.unwrap_or("");
|
||||
sync::apply_changes(base, &p.content_changes)
|
||||
};
|
||||
self.mark_dirty(uri, text);
|
||||
}
|
||||
}
|
||||
DidSaveTextDocument::METHOD => {
|
||||
@@ -1353,6 +1419,10 @@ impl Server {
|
||||
if let Ok(p) = extract::<DidCloseTextDocumentParams>(notification) {
|
||||
let uri = p.text_document.uri;
|
||||
self.config_warnings.remove(&uri);
|
||||
// The buffer's unanalyzed change is already gone — it was
|
||||
// dropped at the top of this function, ahead of the flush
|
||||
// that would otherwise have analyzed it.
|
||||
//
|
||||
// The remembered token answer goes with the buffer: the
|
||||
// client drops what it was holding too, and nothing may
|
||||
// grow with the number of files ever opened.
|
||||
@@ -1711,6 +1781,29 @@ impl Server {
|
||||
self.announce_fast_path(&uri, was_large);
|
||||
}
|
||||
|
||||
/// Hold a buffer's newest text for later analysis. A change already held
|
||||
/// is replaced in place, so the entry's position in the flush order — the
|
||||
/// order the buffers were first dirtied in — survives a burst.
|
||||
fn mark_dirty(&mut self, uri: Uri, text: String) {
|
||||
match self.dirty.iter_mut().find(|(pending, _)| *pending == uri) {
|
||||
Some(entry) => entry.1 = text,
|
||||
None => self.dirty.push((uri, text)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Analyze and republish every dirty buffer, oldest first. One flush is
|
||||
/// one `set_document` per buffer, so a whole typing burst costs one
|
||||
/// reparse per buffer it touched instead of one per keystroke.
|
||||
fn flush_dirty(&mut self) {
|
||||
if self.dirty.is_empty() {
|
||||
return;
|
||||
}
|
||||
for (uri, text) in std::mem::take(&mut self.dirty) {
|
||||
self.set_document(uri.clone(), text);
|
||||
self.publish(&uri);
|
||||
}
|
||||
}
|
||||
|
||||
/// Say once, in the output channel, that a buffer is on the large-file
|
||||
/// fast path.
|
||||
///
|
||||
@@ -2114,6 +2207,16 @@ fn extract<P: DeserializeOwned>(
|
||||
notification.extract(&method)
|
||||
}
|
||||
|
||||
/// The buffer a `didClose` names, read without consuming the notification —
|
||||
/// the close handler runs after the flush, and dropping a pending change has
|
||||
/// to happen before it. `None` for params that do not parse, which the
|
||||
/// handler below ignores in exactly the same way.
|
||||
fn closing_uri(notification: &Notification) -> Option<Uri> {
|
||||
serde_json::from_value::<DidCloseTextDocumentParams>(notification.params.clone())
|
||||
.ok()
|
||||
.map(|p| p.text_document.uri)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -4434,7 +4537,10 @@ mod tests {
|
||||
// incremental text sync
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// One `didChange`, carrying whatever changes were given.
|
||||
/// One `didChange`, carrying whatever changes were given. The flush at the
|
||||
/// end is the quiet-period timer firing: a test drives notifications one
|
||||
/// at a time, so the burst the loop would have coalesced never forms, and
|
||||
/// without this the buffer would sit dirty forever.
|
||||
fn change(session: &mut Session, uri: &Uri, version: u32, changes: Value) {
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
@@ -4443,10 +4549,15 @@ mod tests {
|
||||
"contentChanges": changes,
|
||||
}),
|
||||
);
|
||||
session.server.flush_dirty();
|
||||
}
|
||||
|
||||
/// The text the server currently holds for a buffer.
|
||||
/// The text the server currently holds for a buffer — the newest applied
|
||||
/// text, which while a change sits dirty is the pending one.
|
||||
fn buffer(session: &Session, uri: &Uri) -> String {
|
||||
if let Some((_, text)) = session.server.dirty.iter().find(|(pending, _)| pending == uri) {
|
||||
return text.clone();
|
||||
}
|
||||
session.server.workspace.document(uri).expect("an open buffer").text.clone()
|
||||
}
|
||||
|
||||
@@ -4498,6 +4609,87 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_burst_of_changes_coalesces_into_one_reparse() {
|
||||
// The change debounce's whole payoff: a burst of `didChange`
|
||||
// notifications costs one reparse when the next thing that needs the
|
||||
// analysis flushes them, not one per keystroke.
|
||||
let tree = Tree::new("debounce");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
|
||||
|
||||
let before = session.server.generation;
|
||||
session.batch(vec![
|
||||
changed(&uri, 2, "module m;\n wire a;\nendmodule\n"),
|
||||
changed(&uri, 3, "module m;\n wire a;\n wire b;\nendmodule\n"),
|
||||
]);
|
||||
// Text-current, analysis-stale: nothing has reparsed yet, and the
|
||||
// newest text is already what the server holds.
|
||||
assert_eq!(session.server.generation, before, "no keystroke reparses on its own");
|
||||
assert_eq!(buffer(&session, &uri), "module m;\n wire a;\n wire b;\nendmodule\n");
|
||||
|
||||
// The first request after the burst is answered from one flush.
|
||||
session.result(
|
||||
DocumentSymbolRequest::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
);
|
||||
assert_eq!(session.server.generation, before + 1, "one reparse for the whole burst");
|
||||
assert!(session.server.dirty.is_empty(), "and nothing is left pending");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_a_dirty_buffer_discards_its_change_and_leaves_the_others_alone() {
|
||||
// The debounce's other half: a buffer closed mid-edit is never
|
||||
// analyzed. Its pending text is dropped ahead of the flush at the top
|
||||
// of `notification`, so the client gets the one clearing publish and
|
||||
// nothing else — while every *other* dirty buffer still flushes,
|
||||
// because closing one file says nothing about the rest (QA, CD-1).
|
||||
let tree = Tree::new("closedirty");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let closing = session.open(&tree.path.join("closing.sv"), "module a;\nendmodule\n");
|
||||
let staying = session.open(&tree.path.join("staying.sv"), "module b;\nendmodule\n");
|
||||
let _ = session.published();
|
||||
|
||||
// Both buffers go dirty with text that would diagnose if analyzed.
|
||||
let before = session.server.generation;
|
||||
for (uri, text) in [
|
||||
(&closing, "module a;\n wire ;\nendmodule\n"),
|
||||
(&staying, "module b;\n wire ;\nendmodule\n"),
|
||||
] {
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{ "text": text }],
|
||||
}),
|
||||
);
|
||||
}
|
||||
assert_eq!(session.server.generation, before, "a keystroke reparses nothing on its own");
|
||||
|
||||
session.notify(
|
||||
DidCloseTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": closing } }),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
session.server.generation,
|
||||
before + 1,
|
||||
"one reparse — the buffer still open; the closing one's text went with it"
|
||||
);
|
||||
assert!(session.server.dirty.is_empty(), "nothing left pending");
|
||||
|
||||
let published = session.published();
|
||||
let closed: Vec<_> = published.iter().filter(|p| p.uri == closing).collect();
|
||||
assert_eq!(closed.len(), 1, "exactly one publish for the closed buffer: {published:?}");
|
||||
assert!(closed[0].diagnostics.is_empty(), "and it is the clearing one: {published:?}");
|
||||
let open: Vec<_> = published.iter().filter(|p| p.uri == staying).collect();
|
||||
assert_eq!(open.len(), 1, "the other buffer publishes once: {published:?}");
|
||||
assert!(
|
||||
!open[0].diagnostics.is_empty(),
|
||||
"the other buffer's pending edit was flushed as usual: {published:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_notification_is_one_generation_bump_however_many_ranges() {
|
||||
// The pull-diagnostics `resultId` is this counter. One reparse and one
|
||||
@@ -6308,12 +6500,11 @@ mod tests {
|
||||
// The rebuild republished it, and an edit to it is still diagnosed.
|
||||
let published = session.published();
|
||||
assert!(published.iter().any(|p| p.uri == uri), "{published:#?}");
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{ "text": "package open_pkg;\n localparam ;\nendpackage\n" }],
|
||||
}),
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
2,
|
||||
serde_json::json!([{ "text": "package open_pkg;\n localparam ;\nendpackage\n" }]),
|
||||
);
|
||||
let published = session.published();
|
||||
assert_eq!(published.len(), 1, "{published:#?}");
|
||||
@@ -6986,13 +7177,7 @@ mod tests {
|
||||
assert!(lines[0].contains("bytes"), "{}", lines[0]);
|
||||
|
||||
// A keystroke in it does not say it again.
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{ "text": big_source() }],
|
||||
}),
|
||||
);
|
||||
change(&mut session, &uri, 2, serde_json::json!([{ "text": big_source() }]));
|
||||
assert!(
|
||||
!session.logged().iter().any(|(_, m)| m.contains("large-file fast path")),
|
||||
"the line is per entry, not per notification"
|
||||
@@ -7016,12 +7201,11 @@ mod tests {
|
||||
|
||||
// The same buffer, edited past the threshold: one publish, empty, so
|
||||
// the squiggles go away rather than being left frozen on screen.
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{ "text": format!("module m;\n wire ;\n{}", " ".repeat(200)) }],
|
||||
}),
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
2,
|
||||
serde_json::json!([{ "text": format!("module m;\n wire ;\n{}", " ".repeat(200)) }]),
|
||||
);
|
||||
let cleared = session.published();
|
||||
assert_eq!(cleared.len(), 1, "one publish, as every change makes");
|
||||
@@ -7280,13 +7464,7 @@ mod tests {
|
||||
!session.server.workspace.document(&uri).expect("open").large,
|
||||
"the open buffer keeps the mode it was built in"
|
||||
);
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{ "text": big_source() }],
|
||||
}),
|
||||
);
|
||||
change(&mut session, &uri, 2, serde_json::json!([{ "text": big_source() }]));
|
||||
assert!(
|
||||
session.server.workspace.document(&uri).expect("open").large,
|
||||
"and takes the fast path at its next change"
|
||||
|
||||
@@ -2221,13 +2221,27 @@ impl Live {
|
||||
panic!("the server never said what was waited for; it said {seen:#?}");
|
||||
}
|
||||
|
||||
fn finish(mut self) {
|
||||
/// Shut the session down, and say how many `publishDiagnostics` arrived
|
||||
/// on the way out.
|
||||
///
|
||||
/// The count is what lets a measurement tell one flush from ten: a
|
||||
/// buffer left dirty by a burst is flushed before the next *request* is
|
||||
/// answered, so every publish a burst was going to produce has arrived by
|
||||
/// the time `shutdown` comes back. Most callers ignore the number.
|
||||
fn finish(mut self) -> usize {
|
||||
let published = std::cell::Cell::new(0usize);
|
||||
self.send(r#"{"jsonrpc":"2.0","id":99,"method":"shutdown","params":null}"#);
|
||||
self.wait_for(|m| m["id"] == 99);
|
||||
self.wait_for(|m| {
|
||||
if m["method"] == "textDocument/publishDiagnostics" {
|
||||
published.set(published.get() + 1);
|
||||
}
|
||||
m["id"] == 99
|
||||
});
|
||||
self.send(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#);
|
||||
drop(self.stdin);
|
||||
let status = self.child.wait().expect("the server exits");
|
||||
assert!(status.success(), "clean exit, got {status:?}");
|
||||
published.get()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3055,22 +3069,22 @@ fn incremental_changes_are_advertised_and_applied_over_the_wire() {
|
||||
assert_eq!(sync["openClose"], true, "{sync:#?}");
|
||||
assert_eq!(sync["save"]["includeText"], false, "a save re-sends nothing: {sync:#?}");
|
||||
|
||||
// 2. Each notification published once, and what it published describes
|
||||
// the composed buffer: the error is on the line the third range
|
||||
// inserted, and it clears when the fourth range finishes that line.
|
||||
// 2. The changes were coalesced: both notifications arrived before
|
||||
// anything needed their analysis, so one flush published the composed
|
||||
// buffer once — clean, because the fourth range finished the line the
|
||||
// third inserted. An intermediate publish of the broken half-state is
|
||||
// what the change debounce removed; what is drawn is always a state
|
||||
// the buffer actually passed through, just fewer of them.
|
||||
let published: Vec<_> =
|
||||
messages.iter().filter(|m| m["method"] == "textDocument/publishDiagnostics").collect();
|
||||
assert_eq!(published.len(), 3, "one per notification, not one per range: {published:#?}");
|
||||
assert_eq!(published.len(), 2, "one for the open, one for the flushed changes: {published:#?}");
|
||||
assert!(
|
||||
published[0]["params"]["diagnostics"].as_array().expect("an array").is_empty(),
|
||||
"the file opened clean: {published:#?}"
|
||||
);
|
||||
let diagnostics = published[1]["params"]["diagnostics"].as_array().expect("an array");
|
||||
assert_eq!(diagnostics.len(), 1, "{diagnostics:#?}");
|
||||
assert_eq!(diagnostics[0]["range"]["start"]["line"], 3, "the inserted line");
|
||||
assert!(
|
||||
published[2]["params"]["diagnostics"].as_array().expect("an array").is_empty(),
|
||||
"and the next range fixed it: {published:#?}"
|
||||
published[1]["params"]["diagnostics"].as_array().expect("an array").is_empty(),
|
||||
"and the composed buffer is clean: {published:#?}"
|
||||
);
|
||||
|
||||
// 3. And the buffer the server holds is exactly the composed text — read
|
||||
@@ -4592,3 +4606,139 @@ fn a_five_megabyte_buffer_opens_on_the_fast_path_over_the_wire() {
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Interactive latency — a measurement, not an assertion
|
||||
// ----------------------------------------------------------------------
|
||||
//
|
||||
// `docs/perf/README.md` records what one flush costs by calling the pieces
|
||||
// directly. What it could not record from inside the crate is the number a
|
||||
// user actually feels: the wall time from the `didChange` an editor sends on
|
||||
// a keystroke to the `publishDiagnostics` that redraws the squiggles. That
|
||||
// round trip crosses two pipes, a JSON encoder and decoder, the change
|
||||
// debounce's quiet-period timer and a whole `Document::new`, and only a
|
||||
// session against the real binary can time it.
|
||||
//
|
||||
// Like every measurement in `crates/lucisv_server/src/perf.rs` this asserts
|
||||
// nothing about duration — a test that fails when the machine is busy is a
|
||||
// test that gets deleted — and is `#[ignore]`d so an ordinary `cargo test`
|
||||
// never pays for it.
|
||||
|
||||
/// A generated module of about `lines` lines, ending in a comment line for
|
||||
/// keystrokes to land on.
|
||||
///
|
||||
/// A copy of `perf::generated_module`, because `lucisv_server` is a binary
|
||||
/// crate and an integration test cannot reach into its modules. The two
|
||||
/// differ in one line only — the trailing `// typing` comment this version
|
||||
/// adds for a keystroke to land on, which is trivia and not a token — and
|
||||
/// they must stay that close, or the two tables in `docs/perf/README.md`
|
||||
/// stop being readable against one another.
|
||||
fn generated_module(name: &str, lines: usize) -> String {
|
||||
let mut src = format!(
|
||||
"module {name} (\n input logic clk,\n input logic rst_n,\n \
|
||||
input logic [31:0] data_in,\n output logic [31:0] data_out\n);\n"
|
||||
);
|
||||
for n in 0..lines.saturating_sub(8) / 4 {
|
||||
src.push_str(&format!(
|
||||
" wire [31:0] w_{n};\n \
|
||||
assign w_{n} = data_in ^ {{32{{rst_n}}}};\n \
|
||||
reg [31:0] r_{n};\n \
|
||||
always @(posedge clk) r_{n} <= w_{n};\n"
|
||||
));
|
||||
}
|
||||
src.push_str(" assign data_out = data_in;\n // typing\nendmodule\n");
|
||||
src
|
||||
}
|
||||
|
||||
/// One keystroke: an `x` typed at `character` on `line`, as an editor with
|
||||
/// incremental sync sends it.
|
||||
fn keystroke(uri: &str, version: u32, line: u32, character: u32) -> String {
|
||||
format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":{version}}},"contentChanges":[{{"range":{{"start":{{"line":{line},"character":{character}}},"end":{{"line":{line},"character":{character}}}}},"text":"x"}}]}}}}"#
|
||||
)
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server --test e2e a_keystroke -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn a_keystroke_round_trip_over_the_wire() {
|
||||
for lines in [1_000usize, 10_000] {
|
||||
let dir = temp_dir(&format!("latency{lines}"));
|
||||
let file = dir.join("gen.sv");
|
||||
let source = generated_module("gen", lines);
|
||||
std::fs::write(&file, &source).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
// The `// typing` line, 0-based, and the column just past its text.
|
||||
let comment = source.find(" // typing").expect("the typing line");
|
||||
let line = source[..comment].matches('\n').count() as u32;
|
||||
let column = " // typing".len() as u32;
|
||||
|
||||
let mut live = Live::start();
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
|
||||
));
|
||||
live.wait_for(|m| m["id"] == 1);
|
||||
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
|
||||
live.send(WIDE_SCOPE);
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(&source).expect("json")
|
||||
));
|
||||
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
|
||||
// One keystroke, alone. Nothing else is coming, so what ends the wait
|
||||
// is the debounce's quiet-period timer: this is that timer, plus one
|
||||
// flush, plus the wire.
|
||||
let started = std::time::Instant::now();
|
||||
live.send(&keystroke(&uri, 2, line, column));
|
||||
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
let single = started.elapsed();
|
||||
|
||||
// The same keystroke, followed straight away by a request — which is
|
||||
// what a real editor does: VS Code asks for semantic tokens, inlay
|
||||
// hints and highlights the moment the buffer changes. A request
|
||||
// flushes the dirty buffer before it is answered, so the quiet-period
|
||||
// timer never runs and this is the flush and the wire alone.
|
||||
// Ten of them, and the mean: no timer is involved, so these are short
|
||||
// enough that a single one would be mostly scheduling noise.
|
||||
let runs = 10u32;
|
||||
let started = std::time::Instant::now();
|
||||
for k in 0..runs {
|
||||
live.send(&keystroke(&uri, 3 + k, line, column));
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{},"method":"textDocument/documentHighlight","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":{line},"character":4}}}}}}"#,
|
||||
50 + k
|
||||
));
|
||||
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
live.wait_for(|m| m["id"] == 50 + k);
|
||||
}
|
||||
let requested = started.elapsed() / runs;
|
||||
|
||||
// Ten keystrokes with no pause between them — a burst of typing. The
|
||||
// debounce's whole claim is that this costs one flush and not ten,
|
||||
// and the count below is that claim measured rather than reasoned
|
||||
// about: the wait consumes one publish and `finish` counts every
|
||||
// other one still queued when the shutdown reply comes back.
|
||||
//
|
||||
// This is deliberately the *last* thing measured. Every `wait_for`
|
||||
// above accepts any publish, so a second one the burst had produced
|
||||
// would be absorbed by whichever wait ran next and never counted —
|
||||
// with nothing between the burst and `finish`, there is no such wait.
|
||||
let started = std::time::Instant::now();
|
||||
for k in 0..10u32 {
|
||||
live.send(&keystroke(&uri, 13 + k, line, column + 1 + k));
|
||||
}
|
||||
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
let burst = started.elapsed();
|
||||
|
||||
let published = 1 + live.finish();
|
||||
|
||||
eprintln!(
|
||||
"keystroke round trip, {lines} lines: one change alone {single:?}, \
|
||||
a burst of ten {burst:?} for {published} publish(es), \
|
||||
one change a request follows {requested:?}"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user