Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Fix workspace diagnostics polling (#63336)
Kirill Bulatovab7d21d44491
diff --git a/Cargo.lock b/Cargo.lockindex 729a0aecacc..7b0c4f151f3 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3188,7 +3188,7 @@ dependencies = ["async-lock","cloud_api_types","futures 0.3.32",- "futures-lite 1.13.0",+ "futures-lite 2.6.1","gpui","gpui_tokio","http_client",diff --git a/crates/lsp/src/lsp.rs b/crates/lsp/src/lsp.rsindex 51317b2a733..0366fdf5850 100644--- a/crates/lsp/src/lsp.rs+++ b/crates/lsp/src/lsp.rs@@ -78,7 +78,7 @@ pub fn workspace_folder_for_uri(uri: Uri) -> WorkspaceFolder {type NotificationHandler = Box<dyn Send + FnMut(Option<RequestId>, Value, &mut AsyncApp)>;type PendingRespondTasks = Arc<Mutex<HashMap<RequestId, Task<()>>>>;-type ResponseHandler = Box<dyn Send + FnOnce(Result<String, Error>) -> Task<()>>;+type ResponseHandler = Box<dyn Send + FnOnce(Result<String, ResponseError>) -> Task<()>>;type IoHandler = Box<dyn Send + FnMut(IoKind, &str)>;/// Kind of language server stdio given to an IO handler.@@ -273,7 +273,7 @@ struct AnyResponse<'a> {jsonrpc: &'a str,id: RequestId,#[serde(default, skip_serializing_if = "Option::is_none")]- error: Option<Error>,+ error: Option<ResponseError>,#[serde(borrow, skip_serializing_if = "Option::is_none")]result: Option<&'a RawValue>,}@@ -294,7 +294,7 @@ struct Response<T> {enum LspResult<T> {#[serde(rename = "result")]Ok(Option<T>),- Error(Option<Error>),+ Error(Option<ResponseError>),}/// Language server protocol RPC notification message.@@ -322,14 +322,99 @@ struct NotificationOrRequest {params: Option<Value>,}-#[derive(Debug, Serialize, Deserialize)]-struct Error {- code: i64,- message: String,+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(from = "i64", into = "i64")]+pub enum ResponseErrorCode {+ ParseError,+ MethodNotFound,+ RequestFailed,+ ServerCancelled,+ ContentModified,+ Other(i64),+}++impl From<i64> for ResponseErrorCode {+ fn from(code: i64) -> Self {+ match code {+ -32700 => Self::ParseError,+ -32601 => Self::MethodNotFound,+ lsp_types::error_codes::REQUEST_FAILED => Self::RequestFailed,+ lsp_types::error_codes::SERVER_CANCELLED => Self::ServerCancelled,+ lsp_types::error_codes::CONTENT_MODIFIED => Self::ContentModified,+ code => Self::Other(code),+ }+ }+}++impl From<ResponseErrorCode> for i64 {+ fn from(code: ResponseErrorCode) -> Self {+ match code {+ ResponseErrorCode::ParseError => -32700,+ ResponseErrorCode::MethodNotFound => -32601,+ ResponseErrorCode::RequestFailed => lsp_types::error_codes::REQUEST_FAILED,+ ResponseErrorCode::ServerCancelled => lsp_types::error_codes::SERVER_CANCELLED,+ ResponseErrorCode::ContentModified => lsp_types::error_codes::CONTENT_MODIFIED,+ ResponseErrorCode::Other(code) => code,+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ResponseError {+ pub code: ResponseErrorCode,+ pub message: String,#[serde(default)]- data: Option<serde_json::Value>,+ pub data: Option<serde_json::Value>,+}++impl ResponseError {+ pub fn new(code: ResponseErrorCode, message: impl Into<String>) -> Self {+ Self {+ code,+ message: message.into(),+ data: None,+ }+ }++ pub fn server_cancelled() -> Self {+ Self::new(+ ResponseErrorCode::ServerCancelled,+ "server cancelled the request",+ )+ }++ pub fn method_not_found(method: &str) -> Self {+ Self::new(+ ResponseErrorCode::MethodNotFound,+ format!("Unrecognized method `{method}`"),+ )+ }++ pub fn is_request_denied(&self) -> bool {+ self.code == ResponseErrorCode::ServerCancelled+ || self.code == ResponseErrorCode::ContentModified+ }++ pub fn should_retrigger(&self) -> bool {+ self.code == ResponseErrorCode::ServerCancelled+ && self+ .data+ .clone()+ .and_then(|data| {+ serde_json::from_value::<DiagnosticServerCancellationData>(data).log_err()+ })+ .is_none_or(|data| data.retrigger_request)+ }}+impl std::fmt::Display for ResponseError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{}", self.message)+ }+}++impl std::error::Error for ResponseError {}+pub trait LspRequestFuture<O>: Future<Output = ConnectionResult<O>> {fn id(&self) -> i32;}@@ -533,11 +618,7 @@ impl LanguageServer {let response = AnyResponse {jsonrpc: JSON_RPC_VERSION,id: message_id,- error: Some(Error {- code: -32601,- message: format!("Unrecognized method `{}`", msg.method),- data: None,- }),+ error: Some(ResponseError::method_not_found(&msg.method)),result: None,};if let Ok(response) = serde_json::to_string(&response) {@@ -1280,11 +1361,15 @@ impl LanguageServer {Err(error) => Response {jsonrpc: JSON_RPC_VERSION,id: id.clone(),- value: LspResult::Error(Some(Error {- code: lsp_types::error_codes::REQUEST_FAILED,- message: error.to_string(),- data: None,- })),+ value: LspResult::Error(Some(+ match error.downcast::<ResponseError>() {+ Ok(response_error) => response_error,+ Err(error) => ResponseError::new(+ ResponseErrorCode::RequestFailed,+ error.to_string(),+ ),+ },+ )),},};if let Some(response) =@@ -1304,11 +1389,10 @@ impl LanguageServer {jsonrpc: JSON_RPC_VERSION,id,result: None,- error: Some(Error {- code: -32700, // Parse error- message: error.to_string(),- data: None,- }),+ error: Some(ResponseError::new(+ ResponseErrorCode::ParseError,+ error.to_string(),+ )),};if let Some(response) = serde_json::to_string(&response).log_err() {outbound_tx.try_send(response).ok();@@ -1428,29 +1512,6 @@ impl LanguageServer {)}- /// Send a RPC request to the language server with a custom timer.- /// Once the attached future becomes ready, the request will time out with the provided output message.- ///- /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)- pub fn request_with_timer<T: request::Request, U: Future<Output = String>>(- &self,- params: T::Params,- timer: U,- ) -> impl LspRequestFuture<T::Result> + use<T, U>- where- T::Result: 'static + Send,- {- Self::request_internal_with_timer::<T, U>(- &self.next_id,- &self.response_handlers,- &self.outbound_tx,- &self.notification_tx,- &self.executor,- timer,- params,- )- }-fn request_internal_with_timer<T, U>(next_id: &AtomicI32,response_handlers: &Arc<Mutex<Option<HashMap<RequestId, ResponseHandler>>>>,@@ -1494,7 +1555,7 @@ impl LanguageServer {Err(error).context("failed to deserialize response")}}- Err(error) => Err(anyhow!("{}", error.message)),+ Err(error) => Err(anyhow::Error::new(error)),};tx.send(response).ok();})@@ -2368,21 +2429,32 @@ mod tests {assert_eq!(notification.id, Some(expected_id));}+ #[test]+ fn test_response_error_code_roundtrip() {+ for (code, number) in [+ (ResponseErrorCode::ParseError, -32700),+ (ResponseErrorCode::MethodNotFound, -32601),+ (ResponseErrorCode::RequestFailed, -32803),+ (ResponseErrorCode::ServerCancelled, -32802),+ (ResponseErrorCode::ContentModified, -32801),+ (ResponseErrorCode::Other(-32099), -32099),+ ] {+ assert_eq!(i64::from(code), number);+ assert_eq!(ResponseErrorCode::from(number), code);+ }+ }+#[test]fn test_serialize_error_response_has_no_result() {let response = AnyResponse {jsonrpc: JSON_RPC_VERSION,id: RequestId::Int(0),- error: Some(Error {- code: -32601,- message: "Unrecognized method".to_string(),- data: None,- }),+ error: Some(ResponseError::method_not_found("foo")),result: None,};assert_eq!(serde_json::to_string(&response).unwrap(),- "{\"jsonrpc\":\"2.0\",\"id\":0,\"error\":{\"code\":-32601,\"message\":\"Unrecognized method\",\"data\":null}}"+ "{\"jsonrpc\":\"2.0\",\"id\":0,\"error\":{\"code\":-32601,\"message\":\"Unrecognized method `foo`\",\"data\":null}}");}diff --git a/crates/project/src/lsp_store.rs b/crates/project/src/lsp_store.rsindex ff4f393933a..e2211b724a8 100644--- a/crates/project/src/lsp_store.rs+++ b/crates/project/src/lsp_store.rs@@ -64,7 +64,7 @@ use collections::{BTreeMap, BTreeSet, HashMap, HashSet, btree_map};use futures::{AsyncWriteExt, Future, FutureExt, StreamExt,channel::oneshot,- future::{Either, Shared, join_all, select},+ future::{Shared, join_all},select, select_biased,stream::FuturesUnordered,};@@ -176,6 +176,10 @@ pub use worktree::{const SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);pub const SERVER_PROGRESS_THROTTLE_TIMEOUT: Duration = Duration::from_millis(100);const WORKSPACE_DIAGNOSTICS_TOKEN_START: &str = "id:";+const WORKSPACE_DIAGNOSTICS_REPULL_DELAY: Duration = Duration::from_secs(2);+const CROSS_BUFFER_DIAGNOSTICS_PULL_DELAY: Duration = Duration::from_millis(100);+const DOCUMENT_DIAGNOSTICS_RETRIGGER_LIMIT: usize = 3;+const DOCUMENT_DIAGNOSTICS_RETRIGGER_DELAY: Duration = Duration::from_millis(100);const SERVER_DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(10);static NEXT_PROMPT_REQUEST_ID: AtomicUsize = AtomicUsize::new(0);@@ -4602,6 +4606,18 @@ fn should_log_lsp_request_failure(message: &str) -> bool {!(message.ends_with("content modified") || message.ends_with("server cancelled the request"))}+fn should_log_lsp_response_error(error: &anyhow::Error) -> bool {+ error+ .downcast_ref::<lsp::ResponseError>()+ .is_none_or(|response_error| !response_error.is_request_denied())+}++fn lsp_pull_cancelled_with_retrigger(error: &anyhow::Error) -> bool {+ error+ .downcast_ref::<lsp::ResponseError>()+ .is_some_and(|response_error| response_error.should_retrigger())+}+impl LspStore {pub fn init(client: &AnyProtoClient) {client.add_entity_request_handler(Self::handle_lsp_query);@@ -5085,7 +5101,14 @@ impl LspStore {fn background_diagnostics_worker(cx: &mut Context<Self>) -> Task<()> {cx.spawn(async move |this, cx| {- while let Ok(Some(task)) = this.update(cx, |this, cx| this.refresh_next_buffer(cx)) {+ loop {+ cx.background_executor()+ .timer(CROSS_BUFFER_DIAGNOSTICS_PULL_DELAY)+ .await;+ let Ok(Some(task)) = this.update(cx, |this, cx| this.refresh_next_buffer(cx))+ else {+ return;+ };task.await.log_err();}})@@ -5840,16 +5863,18 @@ impl LspStore {let result = lsp_request.await.into_response();let response = result.map_err(|err| {- let err = err.context(format!(+ let context = format!("{} via {} failed",request.display_name(),- language_server.name(),- ));- let message = format!("{err:#}");- if should_log_lsp_request_failure(&message) {- log::warn!("{message}");+ language_server.name()+ );+ if should_log_lsp_response_error(&err) {+ let message = format!("{context}: {err}");+ if should_log_lsp_request_failure(&message) {+ log::warn!("{message}");+ }}- err+ err.context(context)})?;request@@ -8399,17 +8424,32 @@ impl LspStore {buffer: Entity<Buffer>,cx: &mut Context<Self>,) -> Task<anyhow::Result<()>> {- let diagnostics = self.pull_diagnostics(buffer, cx);+ let mut diagnostics_task = self.pull_diagnostics(buffer.clone(), cx);cx.spawn(async move |lsp_store, cx| {- let diagnostics = match diagnostics.await {- Ok(Some(diagnostics)) => diagnostics,- Ok(None) => return Ok(()),- Err(error) if should_log_lsp_request_failure(&format!("{error:#}")) => {- return Err(error).context("pulling diagnostics");- }- // This is a weird way to suppress diagnostic failures on server side cancellation,- // we should actually retry the request here?- Err(_) => return Ok(()),+ let mut retriggers_left = DOCUMENT_DIAGNOSTICS_RETRIGGER_LIMIT;+ let diagnostics = loop {+ match diagnostics_task.await {+ Ok(Some(diagnostics)) => break diagnostics,+ Ok(None) => return Ok(()),+ Err(error)+ if retriggers_left > 0 && lsp_pull_cancelled_with_retrigger(&error) =>+ {+ retriggers_left -= 1;+ cx.background_executor()+ .timer(DOCUMENT_DIAGNOSTICS_RETRIGGER_DELAY)+ .await;+ diagnostics_task = lsp_store.update(cx, |lsp_store, cx| {+ lsp_store.pull_diagnostics(buffer.clone(), cx)+ })?;+ }+ Err(error)+ if should_log_lsp_response_error(&error)+ && should_log_lsp_request_failure(&format!("{error:#}")) =>+ {+ return Err(error).context("pulling diagnostics");+ }+ Err(_) => return Ok(()),+ }};lsp_store.update(cx, |lsp_store, cx| {if lsp_store.as_local().is_none() {@@ -10018,7 +10058,9 @@ impl LspStore {match response_result {Ok(response) => responses.push((server_id, response)),// rust-analyzer likes to error with this when its still loading up- Err(e) if format!("{e:#}").ends_with("content modified") => (),+ Err(e)+ if !should_log_lsp_response_error(&e)+ || !should_log_lsp_request_failure(&format!("{e:#}")) => {}Err(e) => log::error!("Error handling response for request {request:?}: {e:#}"),}}@@ -11264,12 +11306,12 @@ impl LspStore {);}lsp::ProgressParamsValue::WorkspaceDiagnostic(report) => {- let registration_id = match progress_params.token {- lsp::NumberOrString::Number(_) => None,- lsp::NumberOrString::String(token) => token- .split_once(WORKSPACE_DIAGNOSTICS_TOKEN_START)- .map(|(_, id)| id.to_owned()),+ let lsp::NumberOrString::String(token) = progress_params.token else {+ return;};+ let registration_id = token+ .split_once(WORKSPACE_DIAGNOSTICS_TOKEN_START)+ .map(|(_, id)| id.to_owned());if let Some(LanguageServerState::Running {workspace_diagnostics_refresh_tasks,..@@ -11278,6 +11320,8 @@ impl LspStore {.and_then(|local| local.language_servers.get_mut(&language_server_id))&& let Some(workspace_diagnostics) =workspace_diagnostics_refresh_tasks.get_mut(®istration_id)+ && workspace_diagnostics.current_request_token.as_deref()+ == Some(token.as_str()){workspace_diagnostics.progress_tx.try_send(()).ok();self.apply_workspace_diagnostic_report(@@ -13528,6 +13572,27 @@ impl LspStore {/// Gets all result_ids for a workspace diagnostics pull request./// First, it tries to find buffer's result_id retrieved via the diagnostics pull; if it fails, it falls back to the workspace disagnostics pull result_id./// The latter is supposed to be of lower priority as we keep on pulling diagnostics for open buffers eagerly.+ fn set_workspace_refresh_token(+ &mut self,+ server_id: LanguageServerId,+ registration_id: &Option<String>,+ token: Option<String>,+ ) {+ if let Some(workspace_diagnostics) = self+ .as_local_mut()+ .and_then(|local| local.language_servers.get_mut(&server_id))+ .and_then(|state| match state {+ LanguageServerState::Running {+ workspace_diagnostics_refresh_tasks,+ ..+ } => workspace_diagnostics_refresh_tasks.get_mut(registration_id),+ _ => None,+ })+ {+ workspace_diagnostics.current_request_token = token;+ }+ }+pub fn result_ids_for_workspace_refresh(&self,server_id: LanguageServerId,@@ -13640,7 +13705,20 @@ impl LspStore {return;};for server_id in languages_servers {- let _ = self.pull_document_diagnostics_for_server(server_id, Some(buffer_id), cx);+ let inter_file_dependencies = self.as_local().is_some_and(|local| {+ local+ .language_server_dynamic_registrations+ .get(&server_id)+ .is_some_and(|registrations| {+ registrations+ .diagnostics+ .iter()+ .any(|(_, options)| diagnostics_inter_file_dependencies(options))+ })+ });+ if inter_file_dependencies {+ let _ = self.pull_document_diagnostics_for_server(server_id, Some(buffer_id), cx);+ }}}@@ -13946,7 +14024,9 @@ impl LspStore {match server_task.await {Ok(response) => responses.push((server_id, response)),// rust-analyzer likes to error with this when its still loading up- Err(e) if format!("{e:#}").ends_with("content modified") => (),+ Err(e)+ if !should_log_lsp_response_error(&e)+ || !should_log_lsp_request_failure(&format!("{e:#}")) => {}Err(e) => log::error!("Error handling response for request {request:?}: {e:#}"),@@ -14205,7 +14285,7 @@ fn lsp_workspace_diagnostics_refresh(let registration_id_shared = registration_id.as_ref().map(SharedString::from);let (progress_tx, mut progress_rx) = mpsc::channel(1);- let (mut refresh_tx, mut refresh_rx) = mpsc::channel::<Option<oneshot::Sender<bool>>>(1);+ let (mut refresh_tx, mut refresh_rx) = mpsc::channel::<Option<oneshot::Sender<bool>>>(8);refresh_tx.try_send(None).ok();let request_timeout = ProjectSettings::get_global(cx)@@ -14223,6 +14303,7 @@ fn lsp_workspace_diagnostics_refresh(let workspace_query_language_server = cx.spawn(async move |lsp_store, cx| {let mut attempts = 0;let max_attempts = 50;+ let retries_after_exhaustion = 3;let mut requests = 0;loop {@@ -14230,14 +14311,22 @@ fn lsp_workspace_diagnostics_refresh(return;};let mut completion_txs = completion_tx.into_iter().collect::<Vec<_>>();+ let mut queued_completion_txs = Vec::<oneshot::Sender<bool>>::new();'request: loop {requests += 1;if attempts > max_attempts {log::error!(- "Failed to pull workspace diagnostics {max_attempts} times, aborting"+ "Failed to pull workspace diagnostics {max_attempts} times, pausing until the next refresh");- return;+ for tx in completion_txs+ .drain(..)+ .chain(queued_completion_txs.drain(..))+ {+ tx.send(false).ok();+ }+ attempts = max_attempts + 1 - retries_after_exhaustion;+ break 'request;}let backoff_millis = (50 * (1 << attempts)).clamp(30, 1000);cx.background_executor()@@ -14247,11 +14336,26 @@ fn lsp_workspace_diagnostics_refresh(// Absorb refresh requests that queued up in the meantime, so their// waiters are resolved by this attempt instead of waiting behind it.+ completion_txs.append(&mut queued_completion_txs);while let Ok(queued_refresh) = refresh_rx.try_recv() {completion_txs.extend(queued_refresh);}+ let token = if let Some(registration_id) = ®istration_id {+ format!(+ "workspace/diagnostic/{}/{requests}/{WORKSPACE_DIAGNOSTICS_TOKEN_START}{registration_id}",+ server.server_id(),+ )+ } else {+ format!("workspace/diagnostic/{}/{requests}", server.server_id())+ };+let Ok(previous_result_ids) = lsp_store.update(cx, |lsp_store, _| {+ lsp_store.set_workspace_refresh_token(+ server.server_id(),+ ®istration_id,+ Some(token.clone()),+ );lsp_store.result_ids_for_workspace_refresh(server.server_id(), ®istration_id_shared).into_iter()@@ -14267,60 +14371,77 @@ fn lsp_workspace_diagnostics_refresh(return;};- let token = if let Some(registration_id) = ®istration_id {- format!(- "workspace/diagnostic/{}/{requests}/{WORKSPACE_DIAGNOSTICS_TOKEN_START}{registration_id}",- server.server_id(),- )- } else {- format!("workspace/diagnostic/{}/{requests}", server.server_id())- };-progress_rx.try_recv().ok();- // 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 {+ let mut refresh_requested = false;+ let mut request = pin!(+ server+ .request::<lsp::WorkspaceDiagnosticRequest>(+ lsp::WorkspaceDiagnosticParams {+ previous_result_ids,+ identifier: identifier.clone(),+ work_done_progress_params: Default::default(),+ partial_result_params: lsp::PartialResultParams {+ partial_result_token: Some(lsp::ProgressToken::String(token)),+ },+ },+ Duration::MAX,+ )+ .fuse()+ );+ let response_result = 'response: loop {+ let mut inactivity_timer = pin!(server.request_timer(timeout).fuse());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 mut progress = pin!(progress_rx.recv().fuse());+ let mut refresh = pin!(refresh_rx.recv().fuse());+ select_biased! {+ response = request => break 'response response,+ new_progress = progress => match new_progress {+ Some(()) => continue 'response,+ None => return,+ },+ new_refresh = refresh => match new_refresh {+ Some(completion_tx) => {+ refresh_requested = true;+ queued_completion_txs.extend(completion_tx);+ }+ None => return,+ },+ _ = inactivity_timer => {+ // 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.+ for tx in completion_txs+ .drain(..)+ .chain(queued_completion_txs.drain(..))+ {+ tx.send(false).ok();+ }+ continue 'response;+ }}}};- let response_result = server- .request_with_timer::<lsp::WorkspaceDiagnosticRequest, _>(- lsp::WorkspaceDiagnosticParams {- previous_result_ids,- identifier: identifier.clone(),- work_done_progress_params: Default::default(),- partial_result_params: lsp::PartialResultParams {- partial_result_token: Some(lsp::ProgressToken::String(token)),- },- },- timer,- )- .await;+ if lsp_store+ .update(cx, |lsp_store, _| {+ lsp_store.set_workspace_refresh_token(+ server.server_id(),+ ®istration_id,+ None,+ );+ })+ .is_err()+ {+ return;+ }// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#diagnostic_refresh// > If a server closes a workspace diagnostic pull request the client should re-trigger the request.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();- }+ debug_panic!(+ "Unexpected workspace diagnostics pull timeout without a request timer"+ );continue 'request;}ConnectionResult::ConnectionReset => {@@ -14328,11 +14449,23 @@ fn lsp_workspace_diagnostics_refresh(continue 'request;}ConnectionResult::Result(Err(e)) => {- log::error!("Error during workspace diagnostics pull: {e:#}");- for tx in completion_txs.drain(..) {- tx.send(false).ok();+ if lsp_pull_cancelled_with_retrigger(&e) {+ attempts = 0;+ } else {+ if should_log_lsp_response_error(&e) {+ log::error!("Error during workspace diagnostics pull: {e:#}");+ } else {+ log::debug!("Workspace diagnostics pull denied: {e:#}");+ }+ for tx in completion_txs.drain(..) {+ tx.send(false).ok();+ }+ if refresh_requested {+ continue 'request;+ }+ debug_assert!(queued_completion_txs.is_empty());+ break 'request;}- break 'request;}ConnectionResult::Result(Ok(pulled_diagnostics)) => {attempts = 0;@@ -14352,9 +14485,26 @@ fn lsp_workspace_diagnostics_refresh(for tx in completion_txs.drain(..) {tx.send(true).ok();}- break 'request;}}++ if refresh_requested {+ continue 'request;+ }+ let mut repull_timer = pin!(+ cx.background_executor()+ .timer(WORKSPACE_DIAGNOSTICS_REPULL_DELAY)+ .fuse()+ );+ let mut refresh = pin!(refresh_rx.recv().fuse());+ select_biased! {+ new_refresh = refresh => match new_refresh {+ Some(completion_tx) => completion_txs.extend(completion_tx),+ None => return,+ },+ _ = repull_timer => {}+ }+ continue 'request;}}});@@ -14362,10 +14512,24 @@ fn lsp_workspace_diagnostics_refresh(Some(WorkspaceRefreshTask {refresh_tx,progress_tx,+ current_request_token: None,task: workspace_query_language_server,})}+fn diagnostics_inter_file_dependencies(options: &DiagnosticServerCapabilities) -> bool {+ match options {+ lsp::DiagnosticServerCapabilities::Options(diagnostic_options) => {+ diagnostic_options.inter_file_dependencies+ }+ lsp::DiagnosticServerCapabilities::RegistrationOptions(registration_options) => {+ registration_options+ .diagnostic_options+ .inter_file_dependencies+ }+ }+}+fn buffer_diagnostic_identifier(options: &DiagnosticServerCapabilities) -> Option<SharedString> {match &options {lsp::DiagnosticServerCapabilities::Options(diagnostic_options) => diagnostic_options@@ -14895,6 +15059,7 @@ impl LanguageServerLogType {pub struct WorkspaceRefreshTask {refresh_tx: mpsc::Sender<Option<oneshot::Sender<bool>>>,progress_tx: mpsc::Sender<()>,+ current_request_token: Option<String>,#[allow(dead_code)]task: Task<()>,}@@ -15679,4 +15844,49 @@ mod tests {));assert!(should_log_lsp_request_failure("something else entirely"));}++ #[test]+ fn lsp_pull_cancelled_with_retrigger_follows_the_spec() {+ assert!(lsp_pull_cancelled_with_retrigger(&server_cancellation(+ None+ )));+ assert!(lsp_pull_cancelled_with_retrigger(&server_cancellation(+ Some(serde_json::json!({ "retriggerRequest": true }))+ )));+ assert!(!lsp_pull_cancelled_with_retrigger(&server_cancellation(+ Some(serde_json::json!({ "retriggerRequest": false }))+ )));+ assert!(lsp_pull_cancelled_with_retrigger(+ &server_cancellation(None).context("pulling diagnostics")+ ));+ assert!(!lsp_pull_cancelled_with_retrigger(&anyhow::Error::new(+ lsp::ResponseError::new(lsp::ResponseErrorCode::RequestFailed, "request failed")+ )));+ assert!(!lsp_pull_cancelled_with_retrigger(&anyhow::anyhow!(+ "server cancelled the request"+ )));+ }++ #[test]+ fn should_log_lsp_response_error_suppresses_denied_requests() {+ assert!(!should_log_lsp_response_error(&server_cancellation(None)));+ assert!(!should_log_lsp_response_error(&anyhow::Error::new(+ lsp::ResponseError::new(+ lsp::ResponseErrorCode::ContentModified,+ "content changed meanwhile",+ )+ )));+ assert!(should_log_lsp_response_error(&anyhow::Error::new(+ lsp::ResponseError::new(lsp::ResponseErrorCode::RequestFailed, "request failed")+ )));+ assert!(should_log_lsp_response_error(&anyhow::anyhow!(+ "something else entirely"+ )));+ }++ fn server_cancellation(data: Option<serde_json::Value>) -> anyhow::Error {+ let mut response_error = lsp::ResponseError::server_cancelled();+ response_error.data = data;+ anyhow::Error::new(response_error)+ }}diff --git a/crates/project/tests/integration/project_tests.rs b/crates/project/tests/integration/project_tests.rsindex 06d6c5da206..ca0b200b775 100644--- a/crates/project/tests/integration/project_tests.rs+++ b/crates/project/tests/integration/project_tests.rs@@ -27,7 +27,7 @@ use buffer_diff::{use collections::{BTreeSet, HashMap, HashSet};use encoding_rs;use fs::{FakeFs, PathEventKind, RealFs};-use futures::{FutureExt as _, StreamExt, future};+use futures::{FutureExt as _, StreamExt, channel::oneshot, future};use git::{GitHostingProviderRegistry,repository::{RepoPath, repo_path},@@ -4849,30 +4849,13 @@ async fn test_diagnostic_summaries_cleared_on_buffer_reload(cx: &mut gpui::TestAasync fn test_diagnostic_summaries_cleared_on_buffer_close_without_workspace_diagnostics(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-close-no-ws".to_string()),- inter_file_dependencies: true,- workspace_diagnostics: false,- work_done_progress_options: Default::default(),- },- )),- ..lsp::ServerCapabilities::default()- },+ let (project, mut fake_servers) = diagnostics_pull_project(+ cx,+ json!({ "a.rs": "one two three" }),+ DiagnosticsPullServer {+ identifier: "test-close-no-ws",+ inter_file_dependencies: true,+ workspace_diagnostics: false,initializer: Some(Box::new(move |fake_server| {fake_server.set_request_handler::<lsp::request::DocumentDiagnosticRequest, _, _>(move |_, _| async move {@@ -4901,9 +4884,9 @@ async fn test_diagnostic_summaries_cleared_on_buffer_close_without_workspace_dia},);})),- ..FakeLspAdapter::default()},- );+ )+ .await;let (buffer, handle) = project.update(cx, |project, cx| {@@ -4954,30 +4937,13 @@ async fn test_diagnostic_summaries_cleared_on_buffer_close_without_workspace_diaasync fn test_diagnostic_summaries_retained_on_buffer_close_with_workspace_diagnostics(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-close-ws".to_string()),- inter_file_dependencies: true,- workspace_diagnostics: true,- work_done_progress_options: Default::default(),- },- )),- ..lsp::ServerCapabilities::default()- },+ let (project, mut fake_servers) = diagnostics_pull_project(+ cx,+ json!({ "a.rs": "one two three" }),+ DiagnosticsPullServer {+ identifier: "test-close-ws",+ inter_file_dependencies: true,+ workspace_diagnostics: true,initializer: Some(Box::new(move |fake_server| {fake_server.set_request_handler::<lsp::request::DocumentDiagnosticRequest, _, _>(move |_, _| async move {@@ -5013,96 +4979,898 @@ async fn test_diagnostic_summaries_retained_on_buffer_close_with_workspace_diagn},);})),- ..FakeLspAdapter::default()},- );+ )+ .await;++ 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());+ lsp_store.update(cx, |lsp_store, cx| {+ lsp_store+ .pull_diagnostics_for_buffer(buffer.clone(), cx)+ .detach();+ });+ cx.executor().run_until_parked();++ project.update(cx, |project, cx| {+ assert_eq!(+ project.diagnostic_summary(false, cx),+ DiagnosticSummary {+ error_count: 1,+ warning_count: 0,+ }+ );+ });++ cx.update(|_| {+ drop(buffer);+ drop(handle);+ });+ cx.executor().run_until_parked();++ project.update(cx, |project, cx| {+ assert_eq!(+ project.diagnostic_summary(false, cx),+ DiagnosticSummary {+ error_count: 1,+ warning_count: 0,+ }+ );+ });+}++#[gpui::test]+async fn test_workspace_diagnostics_pull_timeout_releases_waiters(cx: &mut gpui::TestAppContext) {+ let (project, mut fake_servers) = diagnostics_pull_project(+ cx,+ json!({ "a.rs": "one two three" }),+ DiagnosticsPullServer {+ identifier: "test-ws-timeout",+ inter_file_dependencies: true,+ workspace_diagnostics: true,+ 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"))+ },+ );+ })),+ },+ )+ .await;++ 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_workspace_diagnostics_long_poll_is_kept_open(cx: &mut gpui::TestAppContext) {+ let workspace_requests = Arc::new(atomic::AtomicUsize::new(0));+ let partial_result_token = Arc::new(Mutex::new(None));+ let (project, mut fake_servers) = diagnostics_pull_project(+ cx,+ json!({ "a.rs": "one two three", "b.rs": "four five six" }),+ DiagnosticsPullServer {+ identifier: "test-ws-long-poll",+ inter_file_dependencies: true,+ workspace_diagnostics: true,+ initializer: Some(Box::new({+ let workspace_requests = workspace_requests.clone();+ let partial_result_token = partial_result_token.clone();+ move |fake_server| {+ fake_server+ .set_request_handler::<lsp::request::WorkspaceDiagnosticRequest, _, _>({+ let workspace_requests = workspace_requests.clone();+ let partial_result_token = partial_result_token.clone();+ move |params, _| {+ workspace_requests.fetch_add(1, atomic::Ordering::Release);+ *partial_result_token.lock() =+ params.partial_result_params.partial_result_token;+ async move {+ future::pending::<()>().await;+ Err(anyhow::anyhow!("should never respond"))+ }+ }+ });+ }+ })),+ },+ )+ .await;++ 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().advance_clock(Duration::from_secs(1));+ cx.executor().run_until_parked();+ assert_eq!(workspace_requests.load(atomic::Ordering::Acquire), 1);++ cx.executor().advance_clock(DEFAULT_LSP_REQUEST_TIMEOUT * 3);+ cx.executor().run_until_parked();+ assert_eq!(+ workspace_requests.load(atomic::Ordering::Acquire),+ 1,+ "an open workspace diagnostics request must be kept open instead of being cancelled and re-sent after a period of inactivity"+ );++ let token = partial_result_token+ .lock()+ .clone()+ .expect("the workspace diagnostics pull should carry a partial result token");+ fake_server.notify::<lsp::notification::Progress>(lsp::ProgressParams {+ token,+ value: lsp::ProgressParamsValue::WorkspaceDiagnostic(+ lsp::WorkspaceDiagnosticReportResult::Report(lsp::WorkspaceDiagnosticReport {+ items: vec![lsp::WorkspaceDocumentDiagnosticReport::Full(+ lsp::WorkspaceFullDocumentDiagnosticReport {+ uri: lsp::Uri::from_file_path(path!("/dir/b.rs")).unwrap(),+ version: None,+ full_document_diagnostic_report: lsp::FullDocumentDiagnosticReport {+ result_id: Some("ws-1".to_string()),+ items: vec![lsp::Diagnostic {+ range: lsp::Range::new(+ lsp::Position::new(0, 0),+ lsp::Position::new(0, 3),+ ),+ severity: Some(lsp::DiagnosticSeverity::ERROR),+ message: lsp::DiagnosticMessage::from("streamed error"),+ ..lsp::Diagnostic::default()+ }],+ },+ },+ )],+ }),+ ),+ });+ cx.executor().run_until_parked();+ project.update(cx, |project, cx| {+ assert_eq!(+ project.diagnostic_summary(false, cx),+ DiagnosticSummary {+ error_count: 1,+ warning_count: 0,+ },+ "partial results streamed over the open request must still be applied"+ );+ });++ cx.executor().advance_clock(DEFAULT_LSP_REQUEST_TIMEOUT * 3);+ cx.executor().run_until_parked();+ assert_eq!(+ workspace_requests.load(atomic::Ordering::Acquire),+ 1,+ "the request must stay open after streaming partial results"+ );+}++#[gpui::test]+async fn test_workspace_diagnostics_refresh_during_open_request_pulls_again(+ cx: &mut gpui::TestAppContext,+) {+ let workspace_requests = Arc::new(atomic::AtomicUsize::new(0));+ let (first_response_tx, first_response_rx) = oneshot::channel::<()>();+ let first_response_rx = Arc::new(Mutex::new(Some(first_response_rx)));+ let (project, mut fake_servers) = diagnostics_pull_project(+ cx,+ json!({ "a.rs": "one two three" }),+ DiagnosticsPullServer {+ identifier: "test-ws-repull",+ inter_file_dependencies: true,+ workspace_diagnostics: true,+ initializer: Some(Box::new({+ let workspace_requests = workspace_requests.clone();+ let first_response_rx = first_response_rx.clone();+ move |fake_server| {+ fake_server+ .set_request_handler::<lsp::request::WorkspaceDiagnosticRequest, _, _>({+ let workspace_requests = workspace_requests.clone();+ let first_response_rx = first_response_rx.clone();+ move |_, _| {+ workspace_requests.fetch_add(1, atomic::Ordering::Release);+ let first_response_rx = first_response_rx.lock().take();+ async move {+ if let Some(first_response_rx) = first_response_rx {+ first_response_rx.await.ok();+ }+ Ok(lsp::WorkspaceDiagnosticReportResult::Report(+ lsp::WorkspaceDiagnosticReport { items: Vec::new() },+ ))+ }+ }+ });+ }+ })),+ },+ )+ .await;++ 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().advance_clock(Duration::from_secs(1));+ cx.executor().run_until_parked();+ assert_eq!(workspace_requests.load(atomic::Ordering::Acquire), 1);++ 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)+ });+ cx.executor().advance_clock(Duration::from_secs(1));+ cx.executor().run_until_parked();+ assert_eq!(+ workspace_requests.load(atomic::Ordering::Acquire),+ 1,+ "a refresh must not cancel or duplicate the open workspace diagnostics request"+ );++ first_response_tx.send(()).unwrap();+ cx.executor().advance_clock(Duration::from_secs(1));+ cx.executor().run_until_parked();+ assert_eq!(+ workspace_requests.load(atomic::Ordering::Acquire),+ 2,+ "a refresh received while a pull was in flight must trigger one follow-up pull after it completes"+ );++ let refreshed = pull_task.await;+ assert!(+ refreshed,+ "the waiter must be resolved by the follow-up pull"+ );+}++#[gpui::test]+async fn test_workspace_diagnostics_refreshes_coalesce(cx: &mut gpui::TestAppContext) {+ let workspace_requests = Arc::new(atomic::AtomicUsize::new(0));+ let (first_response_tx, first_response_rx) = oneshot::channel::<()>();+ let first_response_rx = Arc::new(Mutex::new(Some(first_response_rx)));+ let (project, mut fake_servers) = diagnostics_pull_project(+ cx,+ json!({ "a.rs": "one two three" }),+ DiagnosticsPullServer {+ identifier: "test-ws-coalesce",+ inter_file_dependencies: true,+ workspace_diagnostics: true,+ initializer: Some(Box::new({+ let workspace_requests = workspace_requests.clone();+ let first_response_rx = first_response_rx.clone();+ move |fake_server| {+ fake_server+ .set_request_handler::<lsp::request::WorkspaceDiagnosticRequest, _, _>({+ let workspace_requests = workspace_requests.clone();+ let first_response_rx = first_response_rx.clone();+ move |_, _| {+ workspace_requests.fetch_add(1, atomic::Ordering::Release);+ let first_response_rx = first_response_rx.lock().take();+ async move {+ if let Some(first_response_rx) = first_response_rx {+ first_response_rx.await.ok();+ }+ Ok(lsp::WorkspaceDiagnosticReportResult::Report(+ lsp::WorkspaceDiagnosticReport { items: Vec::new() },+ ))+ }+ }+ });+ }+ })),+ },+ )+ .await;++ 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().advance_clock(Duration::from_secs(1));+ cx.executor().run_until_parked();+ assert_eq!(workspace_requests.load(atomic::Ordering::Acquire), 1);++ let lsp_store = project.read_with(cx, |project, _| project.lsp_store());+ let pull_tasks = (0..5)+ .map(|_| {+ lsp_store.update(cx, |lsp_store, cx| {+ lsp_store.pull_workspace_diagnostics_once(cx)+ })+ })+ .collect::<Vec<_>>();+ cx.executor().advance_clock(Duration::from_secs(1));+ cx.executor().run_until_parked();++ first_response_tx.send(()).unwrap();+ cx.executor().advance_clock(Duration::from_secs(1));+ cx.executor().run_until_parked();+ for pull_task in pull_tasks {+ let refreshed = pull_task.await;+ assert!(+ refreshed,+ "every coalesced waiter must be resolved by the follow-up pull"+ );+ }+ assert_eq!(+ workspace_requests.load(atomic::Ordering::Acquire),+ 2,+ "refreshes issued while a pull is in flight must coalesce into one follow-up pull"+ );+}++#[gpui::test]+async fn test_workspace_diagnostics_refresh_during_failed_request_pulls_again(+ cx: &mut gpui::TestAppContext,+) {+ let workspace_requests = Arc::new(atomic::AtomicUsize::new(0));+ let (first_response_tx, first_response_rx) = oneshot::channel::<()>();+ let first_response_rx = Arc::new(Mutex::new(Some(first_response_rx)));+ let (project, mut fake_servers) = diagnostics_pull_project(+ cx,+ json!({ "a.rs": "one two three" }),+ DiagnosticsPullServer {+ identifier: "test-ws-error-repull",+ inter_file_dependencies: true,+ workspace_diagnostics: true,+ initializer: Some(Box::new({+ let workspace_requests = workspace_requests.clone();+ let first_response_rx = first_response_rx.clone();+ move |fake_server| {+ fake_server+ .set_request_handler::<lsp::request::WorkspaceDiagnosticRequest, _, _>({+ let workspace_requests = workspace_requests.clone();+ let first_response_rx = first_response_rx.clone();+ move |_, _| {+ workspace_requests.fetch_add(1, atomic::Ordering::Release);+ let first_response_rx = first_response_rx.lock().take();+ async move {+ if let Some(first_response_rx) = first_response_rx {+ first_response_rx.await.ok();+ anyhow::bail!("server cancelled the request");+ }+ Ok(lsp::WorkspaceDiagnosticReportResult::Report(+ lsp::WorkspaceDiagnosticReport { items: Vec::new() },+ ))+ }+ }+ });+ }+ })),+ },+ )+ .await;++ 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().advance_clock(Duration::from_secs(1));+ cx.executor().run_until_parked();+ assert_eq!(workspace_requests.load(atomic::Ordering::Acquire), 1);++ 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)+ });+ cx.executor().advance_clock(Duration::from_secs(1));+ cx.executor().run_until_parked();+ assert_eq!(workspace_requests.load(atomic::Ordering::Acquire), 1);++ first_response_tx.send(()).unwrap();+ cx.executor().advance_clock(Duration::from_secs(1));+ cx.executor().run_until_parked();+ assert_eq!(+ workspace_requests.load(atomic::Ordering::Acquire),+ 2,+ "a refresh received while a failing pull was in flight must trigger one follow-up pull after the failure"+ );++ let refreshed = pull_task.await;+ assert!(+ refreshed,+ "the waiter must be resolved by the follow-up pull"+ );+}++#[gpui::test]+async fn test_cross_buffer_pull_respects_inter_file_dependencies(cx: &mut gpui::TestAppContext) {+ for inter_file_dependencies in [false, true] {+ let pulled_uris = Arc::new(Mutex::new(Vec::new()));+ let (project, mut fake_servers) =+ diagnostics_pull_project(+ cx,+ json!({ "a.rs": "one two three", "b.rs": "four five six" }),+ DiagnosticsPullServer {+ identifier: "test-inter-file-deps",+ inter_file_dependencies,+ workspace_diagnostics: false,+ initializer: Some(Box::new({+ let pulled_uris = pulled_uris.clone();+ move |fake_server| {+ fake_server+ .set_request_handler::<lsp::request::DocumentDiagnosticRequest, _, _>({+ let pulled_uris = pulled_uris.clone();+ move |params, _| {+ pulled_uris.lock().push(params.text_document.uri);+ async move {+ Ok(lsp::DocumentDiagnosticReportResult::Report(+ lsp::DocumentDiagnosticReport::Full(+ lsp::RelatedFullDocumentDiagnosticReport {+ related_documents: None,+ full_document_diagnostic_report:+ lsp::FullDocumentDiagnosticReport {+ result_id: None,+ items: Vec::new(),+ },+ },+ ),+ ))+ }+ }+ });+ }+ })),+ },+ )+ .await;++ let (buffer_a, _handle_a) = project+ .update(cx, |project, cx| {+ project.open_local_buffer_with_lsp(path!("/dir/a.rs"), cx)+ })+ .await+ .unwrap();+ let (_buffer_b, _handle_b) = project+ .update(cx, |project, cx| {+ project.open_local_buffer_with_lsp(path!("/dir/b.rs"), cx)+ })+ .await+ .unwrap();++ let _fake_server = fake_servers.next().await.unwrap();+ cx.executor().run_until_parked();+ pulled_uris.lock().clear();++ let buffer_a_id = buffer_a.read_with(cx, |buffer, _| buffer.remote_id());+ let lsp_store = project.read_with(cx, |project, _| project.lsp_store());+ lsp_store.update(cx, |lsp_store, cx| {+ lsp_store.pull_document_diagnostics_for_buffer_edit(buffer_a_id, cx);+ });+ cx.executor().advance_clock(Duration::from_secs(1));+ cx.executor().run_until_parked();++ let cross_buffer_pulls = pulled_uris+ .lock()+ .drain(..)+ .filter(|uri| *uri == lsp::Uri::from_file_path(path!("/dir/b.rs")).unwrap())+ .count();+ if inter_file_dependencies {+ assert_eq!(+ cross_buffer_pulls, 1,+ "an edit must re-pull other open buffers when the server declares inter file dependencies"+ );+ } else {+ assert_eq!(+ cross_buffer_pulls, 0,+ "an edit must not re-pull other open buffers when the server declares no inter file dependencies"+ );+ }+ }+}++#[gpui::test]+async fn test_workspace_diagnostics_repulled_after_server_closes_request(+ cx: &mut gpui::TestAppContext,+) {+ let workspace_requests = Arc::new(atomic::AtomicUsize::new(0));+ let (project, mut fake_servers) = diagnostics_pull_project(+ cx,+ json!({ "a.rs": "one two three" }),+ DiagnosticsPullServer {+ identifier: "test-ws-repull-on-close",+ inter_file_dependencies: true,+ workspace_diagnostics: true,+ initializer: Some(Box::new({+ let workspace_requests = workspace_requests.clone();+ move |fake_server| {+ fake_server+ .set_request_handler::<lsp::request::WorkspaceDiagnosticRequest, _, _>({+ let workspace_requests = workspace_requests.clone();+ move |_, _| {+ workspace_requests.fetch_add(1, atomic::Ordering::Release);+ async move {+ Ok(lsp::WorkspaceDiagnosticReportResult::Report(+ lsp::WorkspaceDiagnosticReport { items: Vec::new() },+ ))+ }+ }+ });+ }+ })),+ },+ )+ .await;++ 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().advance_clock(Duration::from_millis(100));+ cx.executor().run_until_parked();+ assert_eq!(workspace_requests.load(atomic::Ordering::Acquire), 1);++ cx.executor().advance_clock(Duration::from_secs(1));+ cx.executor().run_until_parked();+ assert_eq!(+ workspace_requests.load(atomic::Ordering::Acquire),+ 1,+ "the client must not re-pull before the repull delay elapses"+ );++ cx.executor().advance_clock(Duration::from_millis(1500));+ cx.executor().run_until_parked();+ assert_eq!(+ workspace_requests.load(atomic::Ordering::Acquire),+ 2,+ "the client must re-trigger the workspace pull after the server closes the request"+ );++ cx.executor().advance_clock(Duration::from_millis(2500));+ cx.executor().run_until_parked();+ assert_eq!(+ workspace_requests.load(atomic::Ordering::Acquire),+ 3,+ "the client must keep re-triggering the workspace pull after every completion"+ );+}++#[gpui::test]+async fn test_document_diagnostics_content_modified_is_suppressed(cx: &mut gpui::TestAppContext) {+ let (project, mut fake_servers) = diagnostics_pull_project(+ cx,+ json!({ "a.rs": "one two three" }),+ DiagnosticsPullServer {+ identifier: "test-doc-content-modified",+ inter_file_dependencies: false,+ workspace_diagnostics: false,+ initializer: Some(Box::new(move |fake_server| {+ fake_server.set_request_handler::<lsp::request::DocumentDiagnosticRequest, _, _>(+ move |_, _| async move {+ Err(anyhow::Error::new(lsp::ResponseError::new(+ lsp::ResponseErrorCode::ContentModified,+ "content changed meanwhile",+ )))+ },+ );+ })),+ },+ )+ .await;++ 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_diagnostics_for_buffer(buffer, cx)+ });+ cx.executor().run_until_parked();+ pull_task+ .await+ .expect("ContentModified pull failures must be suppressed instead of surfaced");+}++#[gpui::test]+async fn test_workspace_diagnostics_stale_partial_results_are_ignored(+ cx: &mut gpui::TestAppContext,+) {+ let partial_result_token = Arc::new(Mutex::new(None));+ let (project, mut fake_servers) = diagnostics_pull_project(+ cx,+ json!({ "a.rs": "one two three", "b.rs": "four five six" }),+ DiagnosticsPullServer {+ identifier: "test-ws-stale-progress",+ inter_file_dependencies: true,+ workspace_diagnostics: true,+ initializer: Some(Box::new({+ let partial_result_token = partial_result_token.clone();+ move |fake_server| {+ fake_server+ .set_request_handler::<lsp::request::WorkspaceDiagnosticRequest, _, _>({+ let partial_result_token = partial_result_token.clone();+ move |params, _| {+ *partial_result_token.lock() =+ params.partial_result_params.partial_result_token;+ async move {+ future::pending::<()>().await;+ Err(anyhow::anyhow!("should never respond"))+ }+ }+ });+ }+ })),+ },+ )+ .await;- let (buffer, handle) = project+ 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();+ let fake_server = fake_servers.next().await.unwrap();+ cx.executor().advance_clock(Duration::from_secs(1));cx.executor().run_until_parked();- let lsp_store = project.read_with(cx, |project, _| project.lsp_store());- lsp_store.update(cx, |lsp_store, cx| {- lsp_store- .pull_diagnostics_for_buffer(buffer.clone(), cx)- .detach();- });+ let lsp::ProgressToken::String(current_token) = partial_result_token+ .lock()+ .clone()+ .expect("the workspace diagnostics pull should carry a partial result token")+ else {+ panic!("expected a string partial result token");+ };+ let (token_prefix, _) = current_token+ .rsplit_once('/')+ .expect("workspace diagnostic tokens should contain request numbers");+ let stale_token = format!("{token_prefix}/999");++ for token in [+ lsp::NumberOrString::Number(1),+ lsp::NumberOrString::String(stale_token),+ ] {+ fake_server.notify::<lsp::notification::Progress>(lsp::ProgressParams {+ token,+ value: lsp::ProgressParamsValue::WorkspaceDiagnostic(+ lsp::WorkspaceDiagnosticReportResult::Report(lsp::WorkspaceDiagnosticReport {+ items: vec![lsp::WorkspaceDocumentDiagnosticReport::Full(+ lsp::WorkspaceFullDocumentDiagnosticReport {+ uri: lsp::Uri::from_file_path(path!("/dir/b.rs")).unwrap(),+ version: None,+ full_document_diagnostic_report: lsp::FullDocumentDiagnosticReport {+ result_id: Some("stale".to_string()),+ items: vec![lsp::Diagnostic {+ range: lsp::Range::new(+ lsp::Position::new(0, 0),+ lsp::Position::new(0, 3),+ ),+ severity: Some(lsp::DiagnosticSeverity::ERROR),+ message: lsp::DiagnosticMessage::from("stale error"),+ ..lsp::Diagnostic::default()+ }],+ },+ },+ )],+ }),+ ),+ });+ }cx.executor().run_until_parked();-project.update(cx, |project, cx| {assert_eq!(project.diagnostic_summary(false, cx),- DiagnosticSummary {- error_count: 1,- warning_count: 0,- }+ DiagnosticSummary::default(),+ "partial results with tokens of other requests must be ignored");});- cx.update(|_| {- drop(buffer);- drop(handle);+ fake_server.notify::<lsp::notification::Progress>(lsp::ProgressParams {+ token: lsp::ProgressToken::String(current_token),+ value: lsp::ProgressParamsValue::WorkspaceDiagnostic(+ lsp::WorkspaceDiagnosticReportResult::Report(lsp::WorkspaceDiagnosticReport {+ items: vec![lsp::WorkspaceDocumentDiagnosticReport::Full(+ lsp::WorkspaceFullDocumentDiagnosticReport {+ uri: lsp::Uri::from_file_path(path!("/dir/b.rs")).unwrap(),+ version: None,+ full_document_diagnostic_report: lsp::FullDocumentDiagnosticReport {+ result_id: Some("current".to_string()),+ items: vec![lsp::Diagnostic {+ range: lsp::Range::new(+ lsp::Position::new(0, 0),+ lsp::Position::new(0, 3),+ ),+ severity: Some(lsp::DiagnosticSeverity::ERROR),+ message: lsp::DiagnosticMessage::from("current error"),+ ..lsp::Diagnostic::default()+ }],+ },+ },+ )],+ }),+ ),});cx.executor().run_until_parked();-project.update(cx, |project, cx| {assert_eq!(project.diagnostic_summary(false, cx),DiagnosticSummary {error_count: 1,warning_count: 0,- }+ },+ "partial results with the current request's token must be applied");});}#[gpui::test]-async fn test_workspace_diagnostics_pull_timeout_releases_waiters(cx: &mut gpui::TestAppContext) {- init_test(cx);+async fn test_workspace_diagnostics_server_cancellation_retriggers(cx: &mut gpui::TestAppContext) {+ let workspace_requests = Arc::new(atomic::AtomicUsize::new(0));+ let (project, mut fake_servers) = diagnostics_pull_project(+ cx,+ json!({ "a.rs": "one two three" }),+ DiagnosticsPullServer {+ identifier: "test-ws-server-cancel",+ inter_file_dependencies: true,+ workspace_diagnostics: true,+ initializer: Some(Box::new({+ let workspace_requests = workspace_requests.clone();+ move |fake_server| {+ fake_server+ .set_request_handler::<lsp::request::WorkspaceDiagnosticRequest, _, _>({+ let workspace_requests = workspace_requests.clone();+ move |_, _| {+ let requests_received =+ workspace_requests.fetch_add(1, atomic::Ordering::Release) + 1;+ async move {+ if requests_received == 1 {+ Err(anyhow::Error::new(+ lsp::ResponseError::server_cancelled(),+ ))+ } else {+ Ok(lsp::WorkspaceDiagnosticReportResult::Report(+ lsp::WorkspaceDiagnosticReport { items: Vec::new() },+ ))+ }+ }+ }+ });+ }+ })),+ },+ )+ .await;- let fs = FakeFs::new(cx.executor());- fs.insert_tree(path!("/dir"), json!({ "a.rs": "one two three" }))- .await;+ let (_buffer, _handle) = project+ .update(cx, |project, cx| {+ project.open_local_buffer_with_lsp(path!("/dir/a.rs"), cx)+ })+ .await+ .unwrap();- 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 _fake_server = fake_servers.next().await.unwrap();+ cx.executor().advance_clock(Duration::from_millis(100));+ cx.executor().run_until_parked();+ assert_eq!(workspace_requests.load(atomic::Ordering::Acquire), 1);- 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"))- },- );+ cx.executor().advance_clock(Duration::from_secs(3));+ cx.executor().run_until_parked();+ assert_eq!(+ workspace_requests.load(atomic::Ordering::Acquire),+ 2,+ "the client must retrigger the workspace pull after the server cancels it with ServerCancelled"+ );+}++#[gpui::test]+async fn test_document_diagnostics_server_cancellation_retriggers(cx: &mut gpui::TestAppContext) {+ let document_requests = Arc::new(atomic::AtomicUsize::new(0));+ let (project, mut fake_servers) = diagnostics_pull_project(+ cx,+ json!({ "a.rs": "one two three" }),+ DiagnosticsPullServer {+ identifier: "test-doc-server-cancel",+ inter_file_dependencies: false,+ workspace_diagnostics: false,+ initializer: Some(Box::new({+ let document_requests = document_requests.clone();+ move |fake_server| {+ fake_server+ .set_request_handler::<lsp::request::DocumentDiagnosticRequest, _, _>({+ let document_requests = document_requests.clone();+ move |_, _| {+ let requests_received =+ document_requests.fetch_add(1, atomic::Ordering::Release) + 1;+ async move {+ if requests_received == 1 {+ Err(anyhow::Error::new(+ lsp::ResponseError::server_cancelled(),+ ))+ } else {+ Ok(lsp::DocumentDiagnosticReportResult::Report(+ lsp::DocumentDiagnosticReport::Full(+ lsp::RelatedFullDocumentDiagnosticReport {+ related_documents: None,+ full_document_diagnostic_report:+ lsp::FullDocumentDiagnosticReport {+ result_id: None,+ items: vec![lsp::Diagnostic {+ range: lsp::Range::new(+ lsp::Position::new(0, 0),+ lsp::Position::new(0, 3),+ ),+ severity: Some(+ lsp::DiagnosticSeverity::ERROR,+ ),+ message:+ lsp::DiagnosticMessage::from(+ "retried error",+ ),+ ..Default::default()+ }],+ },+ },+ ),+ ))+ }+ }+ }+ });+ }})),- ..FakeLspAdapter::default()},- );+ )+ .await;- let (_buffer, _handle) = project+ let (buffer, _handle) = project.update(cx, |project, cx| {project.open_local_buffer_with_lsp(path!("/dir/a.rs"), cx)})@@ -5114,48 +5882,41 @@ async fn test_workspace_diagnostics_pull_timeout_releases_waiters(cx: &mut gpui: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)+ lsp_store.pull_diagnostics_for_buffer(buffer, cx)});+ cx.executor().advance_clock(Duration::from_secs(1));+ cx.executor().run_until_parked();+ pull_task.await.unwrap();- // 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"+ assert_eq!(+ document_requests.load(atomic::Ordering::Acquire),+ 2,+ "the client must retrigger the document pull after the server cancels it with ServerCancelled");+ project.update(cx, |project, cx| {+ assert_eq!(+ project.diagnostic_summary(false, cx),+ DiagnosticSummary {+ error_count: 1,+ warning_count: 0,+ },+ "the retried document pull must produce diagnostics"+ );+ });}#[gpui::test]async fn test_workspace_diagnostics_refresh_is_answered_before_pulling(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 document_pulls_received = Arc::new(atomic::AtomicUsize::new(0));- 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-refresh-response-first".to_string()),- inter_file_dependencies: true,- workspace_diagnostics: true,- work_done_progress_options: Default::default(),- },- )),- ..lsp::ServerCapabilities::default()- },+ let (project, mut fake_servers) = diagnostics_pull_project(+ cx,+ json!({ "a.rs": "one two three" }),+ DiagnosticsPullServer {+ identifier: "test-refresh-response-first",+ inter_file_dependencies: true,+ workspace_diagnostics: true,initializer: Some(Box::new({let document_pulls_received = document_pulls_received.clone();move |fake_server| {@@ -5182,9 +5943,9 @@ async fn test_workspace_diagnostics_refresh_is_answered_before_pulling();}})),- ..FakeLspAdapter::default()},- );+ )+ .await;let (_buffer, _handle) = project.update(cx, |project, cx| {@@ -5208,6 +5969,13 @@ async fn test_workspace_diagnostics_refresh_is_answered_before_pulling(.expect("workspace/diagnostic/refresh must be answered without awaiting diagnostic pulls from the same server").into_response().expect("workspace/diagnostic/refresh should succeed");+ assert_eq!(+ document_pulls_received.load(atomic::Ordering::Acquire),+ 0,+ "the document diagnostics pull must wait for the cross-buffer pacing delay"+ );+ cx.executor().advance_clock(Duration::from_secs(1));+ cx.executor().run_until_parked();assert_eq!(document_pulls_received.load(atomic::Ordering::Acquire),1,@@ -5215,6 +5983,84 @@ async fn test_workspace_diagnostics_refresh_is_answered_before_pulling();}+#[gpui::test]+async fn test_workspace_diagnostics_pulls_recover_after_repeated_failures(+ cx: &mut gpui::TestAppContext,+) {+ let healthy = Arc::new(atomic::AtomicBool::new(false));+ let workspace_requests = Arc::new(atomic::AtomicUsize::new(0));+ let (project, mut fake_servers) = diagnostics_pull_project(+ cx,+ json!({ "a.rs": "one two three" }),+ DiagnosticsPullServer {+ identifier: "test-ws-failure-recovery",+ inter_file_dependencies: true,+ workspace_diagnostics: true,+ initializer: Some(Box::new({+ let healthy = healthy.clone();+ let workspace_requests = workspace_requests.clone();+ move |fake_server| {+ fake_server+ .set_request_handler::<lsp::request::WorkspaceDiagnosticRequest, _, _>({+ let healthy = healthy.clone();+ let workspace_requests = workspace_requests.clone();+ move |_, _| {+ workspace_requests.fetch_add(1, atomic::Ordering::Release);+ let healthy = healthy.load(atomic::Ordering::Acquire);+ async move {+ if healthy {+ Ok(lsp::WorkspaceDiagnosticReportResult::Report(+ lsp::WorkspaceDiagnosticReport { items: Vec::new() },+ ))+ } else {+ anyhow::bail!("workspace diagnostics failed")+ }+ }+ }+ });+ }+ })),+ },+ )+ .await;++ 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();+ let lsp_store = project.read_with(cx, |project, _| project.lsp_store());+ for _ in 0..60 {+ let pull_task = lsp_store.update(cx, |lsp_store, cx| {+ lsp_store.pull_workspace_diagnostics_once(cx)+ });+ cx.executor().advance_clock(Duration::from_secs(3));+ cx.executor().run_until_parked();+ pull_task.await;+ }++ healthy.store(true, atomic::Ordering::Release);+ let requests_before_recovery = workspace_requests.load(atomic::Ordering::Acquire);+ let pull_task = lsp_store.update(cx, |lsp_store, cx| {+ lsp_store.pull_workspace_diagnostics_once(cx)+ });+ cx.executor().advance_clock(Duration::from_secs(3));+ cx.executor().run_until_parked();+ let refreshed = pull_task.await;+ assert!(+ refreshed,+ "workspace diagnostics pulls must recover once the server stops failing"+ );+ assert_eq!(+ workspace_requests.load(atomic::Ordering::Acquire),+ requests_before_recovery + 1,+ "the recovery must send exactly one workspace diagnostics request"+ );+}+#[gpui::test]async fn test_edits_from_lsp2_with_past_version(cx: &mut gpui::TestAppContext) {init_test(cx);@@ -16788,6 +17634,51 @@ async fn test_initial_scan_complete(cx: &mut gpui::TestAppContext) {});}+struct DiagnosticsPullServer {+ identifier: &'static str,+ inter_file_dependencies: bool,+ workspace_diagnostics: bool,+ initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,+}++async fn diagnostics_pull_project(+ cx: &mut gpui::TestAppContext,+ files: serde_json::Value,+ server: DiagnosticsPullServer,+) -> (+ Entity<Project>,+ futures::channel::mpsc::UnboundedReceiver<lsp::FakeLanguageServer>,+) {+ init_test(cx);++ let fs = FakeFs::new(cx.executor());+ fs.insert_tree(path!("/dir"), files).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 fake_servers = language_registry.register_fake_lsp(+ "Rust",+ FakeLspAdapter {+ capabilities: lsp::ServerCapabilities {+ diagnostic_provider: Some(lsp::DiagnosticServerCapabilities::Options(+ lsp::DiagnosticOptions {+ identifier: Some(server.identifier.to_string()),+ inter_file_dependencies: server.inter_file_dependencies,+ workspace_diagnostics: server.workspace_diagnostics,+ work_done_progress_options: Default::default(),+ },+ )),+ ..lsp::ServerCapabilities::default()+ },+ initializer: server.initializer,+ ..FakeLspAdapter::default()+ },+ );+ (project, fake_servers)+}+pub fn init_test(cx: &mut gpui::TestAppContext) {zlog::init_test();