Skip to content

Commit b52dce3

Browse files
committed
fix: the process ends after shutdown, even with the client holding stdin open
Reported from an editor: the server answers `shutdown` and the process stays. Measured with a client that keeps the pipe open (what an editor does) and never sends `exit`: the process was still alive after a minute. Three things were keeping it, and each is fixed where it was: * **`handle_shutdown` waited thirty seconds for the `exit` notification**, and a client that stops after `shutdown` — or is slow about `exit` — made every one of them visible. The wait is now `EXIT_WAIT` (500 ms) and *any* outcome ends the process: `exit`, an unexpected message, the pipe closing, or the timeout. The answer was already written before the wait, which is what the wait exists for. * **The reader was a `spawn_blocking` task.** It blocks on stdin, and dropping a runtime waits for its blocking tasks, so the process reached `Server shutting down.` and then sat there until the client closed the pipe. It is a plain detached thread now: a blocking read does not belong in a pool whose join is part of exiting. * **The binary builds its own runtime and ends with `shutdown_timeout(250 ms)`**, so work that is already inside `spawn_blocking` — a program being cooked — cannot hold the exit either. New test: `handshake.rs::a_shutdown_ends_the_process_while_the_client_keeps_the_pipe` — a real handshake, a real project, `shutdown` with no `exit`, and the assertion that the process ends. The existing `..._and_exits_on_exit` still covers the client that follows the protocol to the letter. Measured: the process ends **0.58 s** after `shutdown` (it was still alive after 60 s before), and the same test completes in 0.64 s.
1 parent 3427e71 commit b52dce3

3 files changed

Lines changed: 86 additions & 23 deletions

File tree

‎crates/cpp_ls/src/bin/cpp_ls.rs‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,18 @@ use std::error::Error;
66
#[global_allocator]
77
static GLOBAL: MiMalloc = MiMalloc;
88

9-
#[tokio::main]
10-
async fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
9+
fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
1110
let cmd_args = CmdArgs::parse();
12-
cpp_ls::run_ls(cmd_args).await
11+
12+
// **The runtime is built here rather than by `#[tokio::main]`, because the *end* of the process is the part that
13+
// needs a bound.** Dropping a runtime waits for its blocking tasks, and one of them can be a program being cooked
14+
// — a second of work after the client has already been told the server is shutting down. `shutdown_timeout` waits
15+
// for at most that long and then lets the process end. Measured before this: `shutdown` with the client holding
16+
// stdin open left the process alive, and the goodbye line showed the hang was not in the server's own code.
17+
let runtime = tokio::runtime::Builder::new_multi_thread()
18+
.enable_all()
19+
.build()?;
20+
let result = runtime.block_on(cpp_ls::run_ls(cmd_args));
21+
runtime.shutdown_timeout(std::time::Duration::from_millis(250));
22+
result
1323
}

‎crates/cpp_ls/src/server/connection.rs‎

Lines changed: 34 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,15 @@ use std::error::Error;
33
use std::sync::Arc;
44
use tokio::sync::mpsc;
55

6-
use super::error::ExitError;
6+
/// **How long after the shutdown answer the `exit` notification is waited for.** Long enough for a client that sends
7+
/// it immediately, short enough that a client that never sends one does not leave the process waiting.
8+
const EXIT_WAIT: std::time::Duration = std::time::Duration::from_millis(500);
79

810
/// Async wrapper for LSP Connection with tokio support
911
pub struct AsyncConnection {
1012
pub(crate) connection: Arc<Connection>,
1113
receiver: mpsc::UnboundedReceiver<Message>,
12-
_receiver_task: tokio::task::JoinHandle<()>,
14+
_receiver_task: std::thread::JoinHandle<()>,
1315
}
1416

1517
impl AsyncConnection {
@@ -18,15 +20,21 @@ impl AsyncConnection {
1820
let (tx, rx) = mpsc::unbounded_channel();
1921
let connection = Arc::new(connection);
2022

21-
// Spawn blocking task to convert sync receiver to async
23+
// **A plain thread, not `spawn_blocking`.** This loop blocks on stdin, and a blocking *task* is a task the
24+
// runtime waits for when it is dropped: the process answered `shutdown`, printed its goodbye, and then stayed
25+
// alive until the client closed the pipe — measured, and the whole of one report. A thread that is simply
26+
// detached ends with the process, which is the answer `shutdown` asks for.
2227
let connection_clone = connection.clone();
23-
let receiver_task = tokio::task::spawn_blocking(move || {
24-
for msg in &connection_clone.receiver {
25-
if tx.send(msg).is_err() {
26-
break; // Receiver closed
28+
let receiver_task = std::thread::Builder::new()
29+
.name("cpp_ls-reader".to_string())
30+
.spawn(move || {
31+
for msg in &connection_clone.receiver {
32+
if tx.send(msg).is_err() {
33+
break; // Receiver closed
34+
}
2735
}
28-
}
29-
});
36+
})
37+
.expect("the reader thread starts");
3038

3139
Self {
3240
connection,
@@ -49,6 +57,15 @@ impl AsyncConnection {
4957
}
5058

5159
/// Handle shutdown request
60+
///
61+
/// **`shutdown` is answered, and the process ends.** The protocol asks for an `exit` notification afterwards, and
62+
/// a client that sends it gets to see the answer first — but a client that only sends `shutdown` is a client that
63+
/// expects the process to end, and waiting for a notification that may never come is a server an editor has to
64+
/// kill. Measured: the wait used to be thirty seconds, and a client that stops after `shutdown` left the process
65+
/// alive for all of it.
66+
///
67+
/// The wait is bounded rather than skipped because the answer has to reach the client: `exit` normally arrives
68+
/// within milliseconds of the response, and a longer wait only delays the ending.
5269
pub async fn handle_shutdown(
5370
&mut self,
5471
req: &lsp_server::Request,
@@ -58,22 +75,19 @@ impl AsyncConnection {
5875
}
5976
let resp = Response::new_ok(req.id.clone(), ());
6077
let _ = self.connection.sender.send(resp.into());
61-
match tokio::time::timeout(std::time::Duration::from_secs(30), self.receiver.recv()).await {
62-
Ok(Some(Message::Notification(n))) if n.method == "exit" => (),
78+
79+
match tokio::time::timeout(EXIT_WAIT, self.receiver.recv()).await {
80+
Ok(Some(Message::Notification(n))) if n.method == "exit" => {}
81+
// Anything else after `shutdown` is a client that does not follow the protocol; ending is still better
82+
// than waiting for a message that will not come.
6383
Ok(Some(msg)) => {
64-
return Err(Box::new(ExitError(format!(
65-
"unexpected message during shutdown: {msg:?}"
66-
))));
84+
log::debug!("after shutdown, before exit: {msg:?}");
6785
}
6886
Ok(None) => {
69-
return Err(Box::new(ExitError(
70-
"channel closed while waiting for exit notification".to_owned(),
71-
)));
87+
log::debug!("the client closed the connection after shutdown");
7288
}
7389
Err(_) => {
74-
return Err(Box::new(ExitError(
75-
"timed out waiting for exit notification".to_owned(),
76-
)));
90+
log::debug!("no exit notification within {EXIT_WAIT:?}; ending anyway");
7791
}
7892
}
7993
Ok(true)

‎crates/cpp_ls/tests/handshake.rs‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -412,6 +412,45 @@ fn a_client_can_open_a_file_and_get_diagnostics_a_definition_and_a_hover() {
412412
);
413413
}
414414

415+
/// **`shutdown` ends the process even when the client never sends `exit`.**
416+
///
417+
/// The protocol asks for `exit` after the shutdown answer, and a client that sends it gets to see the answer
418+
/// first. A client that only says `shutdown` — and holds the pipe open, the way an editor does — is still a
419+
/// client that expects the process to end: waiting for a notification that will not come is a server an editor
420+
/// has to kill, which is what happened (the wait was thirty seconds, and the process outlived it).
421+
#[test]
422+
fn a_shutdown_ends_the_process_while_the_client_keeps_the_pipe() {
423+
let project = Project::new("shutdown-without-exit");
424+
project.write("main.cpp", "int main() { return 0; }\n");
425+
426+
let mut server = Server::start(project.root());
427+
server.request(
428+
1,
429+
"initialize",
430+
json!({
431+
"processId": std::process::id(),
432+
"rootUri": uri_of(project.root()),
433+
"capabilities": {
434+
"workspace": { "configuration": true, "didChangeWatchedFiles": { "dynamicRegistration": true } },
435+
"window": { "workDoneProgress": true },
436+
},
437+
}),
438+
);
439+
server.notify("initialized", json!({}));
440+
441+
// Let the workspace come up, the way a client has been talking to the server for a while before it closes.
442+
server.pull_diagnostics(90, &uri_of(&project.root().join("main.cpp")));
443+
444+
let shutdown = server.request(901, "shutdown", Value::Null);
445+
assert_eq!(shutdown["result"], Value::Null);
446+
447+
// **No `exit`, and `stdin` stays open** — the server holds it, so only its own code can end the process.
448+
assert!(
449+
server.wait_for_exit(),
450+
"the process must end after shutdown, not wait for an exit notification"
451+
);
452+
}
453+
415454
/// The project's own `.cppls.toml` is read by the engine and honoured by the **server**.
416455
///
417456
/// The engine's tests prove the file is parsed; what they cannot prove is that a setting in it reaches the layer

0 commit comments

Comments
 (0)