Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

project: Fix agent hanging indefinitely when pulling workspace diagnostics (#61176)

Lukas Wirthc7148c8190d7
diff --git a/crates/project/src/lsp_store.rs b/crates/project/src/lsp_store.rs
index 38117a9731c..c1e5ca31f53 100644
--- a/crates/project/src/lsp_store.rs
+++ b/crates/project/src/lsp_store.rs
@@ -61,7 +61,7 @@ use collections::{BTreeMap, BTreeSet, HashMap, HashSet, btree_map};
use futures::{
AsyncWriteExt, Future, FutureExt, StreamExt,
channel::oneshot,
- future::{Either, Shared, join_all, pending, select},
+ future::{Either, Shared, join_all, select},
select, select_biased,
stream::FuturesUnordered,
};
@@ -123,7 +123,6 @@ use std::{
collections::{VecDeque, hash_map},
convert::TryInto,
ffi::OsStr,
- future::ready,
iter, mem,
ops::{ControlFlow, Range},
path::{self, Path, PathBuf},
@@ -14152,9 +14151,10 @@ fn lsp_workspace_diagnostics_refresh(
let mut requests = 0;
loop {
- let Some(mut completion_tx) = refresh_rx.recv().await else {
+ let Some(completion_tx) = refresh_rx.recv().await else {
return;
};
+ let mut completion_txs = completion_tx.into_iter().collect::<Vec<_>>();
'request: loop {
requests += 1;
@@ -14170,6 +14170,12 @@ fn lsp_workspace_diagnostics_refresh(
.await;
attempts += 1;
+ // Absorb refresh requests that queued up in the meantime, so their
+ // waiters are resolved by this attempt instead of waiting behind it.
+ while let Ok(queued_refresh) = refresh_rx.try_recv() {
+ completion_txs.extend(queued_refresh);
+ }
+
let Ok(previous_result_ids) = lsp_store.update(cx, |lsp_store, _| {
lsp_store
.result_ids_for_workspace_refresh(server.server_id(), &registration_id_shared)
@@ -14196,8 +14202,21 @@ fn lsp_workspace_diagnostics_refresh(
};
progress_rx.try_recv().ok();
- let timer = server.request_timer(timeout).fuse();
- let progress = pin!(progress_rx.recv().fuse());
+ // Restart the timeout whenever a partial result arrives: streaming
+ // servers may legitimately take longer than a single timeout period,
+ // but a server that stops streaming without completing the request
+ // should still time out instead of hanging forever.
+ let timer = async {
+ loop {
+ let timer = pin!(server.request_timer(timeout).fuse());
+ let progress = pin!(progress_rx.recv().fuse());
+ match select(timer, progress).await {
+ Either::Left((message, ..)) => break message,
+ Either::Right((Some(()), ..)) => {}
+ Either::Right((None, timer)) => break timer.await,
+ }
+ }
+ };
let response_result = server
.request_with_timer::<lsp::WorkspaceDiagnosticRequest, _>(
lsp::WorkspaceDiagnosticParams {
@@ -14208,10 +14227,7 @@ fn lsp_workspace_diagnostics_refresh(
partial_result_token: Some(lsp::ProgressToken::String(token)),
},
},
- select(timer, progress).then(|either| match either {
- Either::Left((message, ..)) => ready(message).left_future(),
- Either::Right(..) => pending::<String>().right_future(),
- }),
+ timer,
)
.await;
@@ -14220,6 +14236,16 @@ fn lsp_workspace_diagnostics_refresh(
match response_result {
ConnectionResult::Timeout => {
log::error!("Timeout during workspace diagnostics pull");
+ // Release everyone waiting on this refresh (e.g. the agent's
+ // diagnostics tool), including waiters that queued up while the
+ // request was in flight, so they can fall back to cached
+ // diagnostics instead of waiting through every retry.
+ while let Ok(queued_refresh) = refresh_rx.try_recv() {
+ completion_txs.extend(queued_refresh);
+ }
+ for tx in completion_txs.drain(..) {
+ tx.send(false).ok();
+ }
continue 'request;
}
ConnectionResult::ConnectionReset => {
@@ -14228,7 +14254,7 @@ fn lsp_workspace_diagnostics_refresh(
}
ConnectionResult::Result(Err(e)) => {
log::error!("Error during workspace diagnostics pull: {e:#}");
- if let Some(tx) = completion_tx.take() {
+ for tx in completion_txs.drain(..) {
tx.send(false).ok();
}
break 'request;
@@ -14248,7 +14274,7 @@ fn lsp_workspace_diagnostics_refresh(
{
return;
}
- if let Some(tx) = completion_tx.take() {
+ for tx in completion_txs.drain(..) {
tx.send(true).ok();
}
break 'request;
diff --git a/crates/project/tests/integration/project_tests.rs b/crates/project/tests/integration/project_tests.rs
index 6ec9f345021..bf90db372ea 100644
--- a/crates/project/tests/integration/project_tests.rs
+++ b/crates/project/tests/integration/project_tests.rs
@@ -4644,6 +4644,71 @@ async fn test_diagnostic_summaries_retained_on_buffer_close_with_workspace_diagn
});
}
+#[gpui::test]
+async fn test_workspace_diagnostics_pull_timeout_releases_waiters(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(path!("/dir"), json!({ "a.rs": "one two three" }))
+ .await;
+
+ let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(rust_lang());
+
+ let mut fake_servers = language_registry.register_fake_lsp(
+ "Rust",
+ FakeLspAdapter {
+ capabilities: lsp::ServerCapabilities {
+ diagnostic_provider: Some(lsp::DiagnosticServerCapabilities::Options(
+ lsp::DiagnosticOptions {
+ identifier: Some("test-ws-timeout".to_string()),
+ inter_file_dependencies: true,
+ workspace_diagnostics: true,
+ work_done_progress_options: Default::default(),
+ },
+ )),
+ ..lsp::ServerCapabilities::default()
+ },
+ initializer: Some(Box::new(move |fake_server| {
+ // Simulate a server that holds workspace diagnostic pull requests
+ // open forever without responding or streaming partial results.
+ fake_server.set_request_handler::<lsp::request::WorkspaceDiagnosticRequest, _, _>(
+ move |_, _| async move {
+ future::pending::<()>().await;
+ Err(anyhow::anyhow!("should never respond"))
+ },
+ );
+ })),
+ ..FakeLspAdapter::default()
+ },
+ );
+
+ let (_buffer, _handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/dir/a.rs"), cx)
+ })
+ .await
+ .unwrap();
+
+ let _fake_server = fake_servers.next().await.unwrap();
+ cx.executor().run_until_parked();
+
+ let lsp_store = project.read_with(cx, |project, _| project.lsp_store());
+ let pull_task = lsp_store.update(cx, |lsp_store, cx| {
+ lsp_store.pull_workspace_diagnostics_once(cx)
+ });
+
+ // The waiter must be released after the request times out, instead of
+ // being held through every retry of the background refresh loop.
+ cx.executor().advance_clock(DEFAULT_LSP_REQUEST_TIMEOUT * 2);
+ let refreshed = pull_task.await;
+ assert!(
+ !refreshed,
+ "pull should report a failed refresh when the server never responds"
+ );
+}
+
#[gpui::test]
async fn test_edits_from_lsp2_with_past_version(cx: &mut gpui::TestAppContext) {
init_test(cx);