From 2fdc0243585a5358e593060e4f5121035067cdb7 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Thu, 3 Dec 2026 13:34:02 +0900 Subject: [PATCH] fix(kotlin): show the Gradle step of a kotlin-lsp import and warn when Gradle runs out of heap (#7670) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit While kotlin-lsp imports a Gradle project it sends no $/progress reports, so the import task showed only its title and was marked "no progress for 180 s" even while Gradle was busy, and a Gradle daemon that ran out of heap (stuck in GC, the import never finishing) went unreported. kotlin-lsp forwards the build tool's console output as intellij/importLog, which was dropped; it is now handled: each line keeps the running import task alive, "> Task :…" and "> Configure project …" lines become the task's message, and Gradle's max-heap message, OutOfMemoryError or "GC overhead limit exceeded" raises one warning per session with the configured heap and how to raise it. Closes #7668 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-lsp/src/handler.rs | 40 ++++++++ crates/ide-lsp/src/kotlin_lsp.rs | 54 +++++++++++ crates/ide-lsp/tests/mock_server.rs | 136 ++++++++++++++++++++++++++++ 3 files changed, 230 insertions(+) diff --git a/crates/ide-lsp/src/handler.rs b/crates/ide-lsp/src/handler.rs index 5fbb0d2df6..e92c15e551 100644 --- a/crates/ide-lsp/src/handler.rs +++ b/crates/ide-lsp/src/handler.rs @@ -320,6 +320,43 @@ impl ClientHandler { true } + /// kotlin-lsp's `intellij/importLog`: one line of the build tool's output while it + /// imports. It sends no `$/progress` report during that phase, so each line counts as + /// activity on its import task (a busy Gradle is not stuck), and a `> Task :…` line + /// becomes the task's message. Gradle running out of heap is raised as a warning. + fn kotlin_import_log(&self, mgr: &LspManager, params: &Value) { + let text = params.get("message").and_then(Value::as_str).unwrap_or_default(); + tracing::debug!(server = ?self.server.id, generation = self.generation, "[{}] import: {text}", self.server.name); + let step = crate::kotlin_lsp::import_step(text); + // The reader thread is outside the runtime: read the clock `watch_progress` compares with. + let _clock = mgr.runtime.enter(); + // Only a new step or a task marked stuck needs an event; other lines just keep it alive. + let reports: Vec = { + let mut progress = self.server.progress.lock(); + progress + .iter_mut() + .filter(|(_, p)| p.title.contains("Import")) + .filter_map(|(token, p)| { + p.last = tokio::time::Instant::now(); + (step.is_some() || p.stalled).then(|| token.clone()) + }) + .collect() + }; + for token in reports { + self.progress(mgr, json!({ "token": token, "value": { "kind": "report", "message": step } })); + } + if let Some(body) = crate::kotlin_lsp::gradle_out_of_memory(text) + && mgr.first_message(&self.server.name, "Gradle ran out of memory") + { + tracing::warn!(server = ?self.server.id, generation = self.generation, "[{}] {text}", self.server.name); + mgr.sink().emit(IdeEvent::Notify { + level: NotifyLevel::Warning, + title: "Gradle ran out of memory".into(), + body: Some(body), + }); + } + } + /// Ends every running task of a tsserver that died at its heap limit: the process /// behind them is gone, so no `end` will ever arrive. Without this the tasks sit /// as zombies until [`PROGRESS_STALE`] and the server stays "loading", holding @@ -772,6 +809,9 @@ impl Handler for ClientHandler { } } "tsserver/request" => mgr.forward_tsserver_requests(self.server.clone(), self.generation, params), + "intellij/importLog" if self.server.name == crate::kotlin_lsp::KOTLIN_LSP => { + self.kotlin_import_log(&mgr, ¶ms) + } "intellij/workspaceImportState" if self.server.name == crate::kotlin_lsp::KOTLIN_LSP => { crate::kotlin_lsp::record_import_state(&self.server, self.generation, ¶ms) } diff --git a/crates/ide-lsp/src/kotlin_lsp.rs b/crates/ide-lsp/src/kotlin_lsp.rs index 85c0ccbc9d..ee283c350b 100644 --- a/crates/ide-lsp/src/kotlin_lsp.rs +++ b/crates/ide-lsp/src/kotlin_lsp.rs @@ -58,6 +58,31 @@ pub(crate) fn record_import_state(server: &Server, generation: u64, params: &Val server.set_import_state(generation, ImportState { finished: params["phase"] == "FINISHED", failed }); } +/// The Gradle step an `intellij/importLog` line names (`> Task :app:compileKotlin`, +/// `> Configure project :app`), shown as the import task's message. +pub(crate) fn import_step(line: &str) -> Option<&str> { + let line = line.trim(); + (line.starts_with("> Task :") || line.starts_with("> Configure project ")).then_some(line) +} + +/// The warning for an `intellij/importLog` line saying the Gradle daemon ran out of heap +/// (it then spends minutes in GC and the import never finishes). Gradle's own message +/// spans several lines: `The Daemon will expire after the build after running out of JVM +/// heap space.` … `The currently configured max heap space is '4 GiB' and …`; the second +/// one names the heap, so it is the one recognized. +pub(crate) fn gradle_out_of_memory(line: &str) -> Option { + let heap = line.split_once("currently configured max heap space is '").and_then(|(_, rest)| rest.split_once('\'')); + let oom = + heap.is_some() || line.contains("java.lang.OutOfMemoryError") || line.contains("GC overhead limit exceeded"); + if !oom { + return None; + } + let configured = heap.map(|(heap, _)| format!(" (configured max heap: {heap})")).unwrap_or_default(); + Some(format!( + "The Gradle daemon importing the project ran out of memory{configured}, so the import may never finish. Raise -Xmx in org.gradle.jvmargs in gradle.properties, stop the Gradle daemon and restart kotlin-lsp." + )) +} + fn importing(server: &Server) -> bool { server.progress.lock().values().any(|p| p.title.contains("Importing")) } @@ -167,6 +192,35 @@ mod tests { use ide_core::{IdeEvent, SharedSink}; use std::sync::Arc; + #[test] + fn import_output_lines_that_name_a_gradle_step() { + assert_eq!(import_step("> Task :app:compileKotlin\n"), Some("> Task :app:compileKotlin")); + assert_eq!(import_step("> Configure project :lib"), Some("> Configure project :lib")); + for line in ["", "BUILD SUCCESSFUL in 3s", "> Task", "w: Some warning > Task :x", "> Transform x"] { + assert_eq!(import_step(line), None, "{line:?}"); + } + } + + #[test] + fn gradle_out_of_memory_lines() { + let heap = "The currently configured max heap space is '4 GiB' and the configured max metaspace is '384 MiB'."; + assert!(gradle_out_of_memory(heap).unwrap().contains("(configured max heap: 4 GiB)")); + let oom = + gradle_out_of_memory("Exception in thread \"x\" java.lang.OutOfMemoryError: Java heap space").unwrap(); + assert!(!oom.contains("configured max heap") && oom.contains("org.gradle.jvmargs"), "{oom}"); + assert!(gradle_out_of_memory("java.lang.OutOfMemoryError: GC overhead limit exceeded").is_some()); + // An unterminated quote names no heap, but is not Gradle's message either. + assert_eq!(gradle_out_of_memory("currently configured max heap space is '4 GiB"), None); + for line in [ + "", + "The Daemon will expire after the build after running out of JVM heap space.", + "These settings can be adjusted by setting 'org.gradle.jvmargs' in 'gradle.properties'.", + "> Task :app:compileKotlin", + ] { + assert_eq!(gradle_out_of_memory(line), None, "{line:?}"); + } + } + #[test] fn an_instance_that_was_replaced_does_not_record_its_import() { let cfg = toml::from_str("name = \"kotlin-lsp\"\ncommand = \"kotlin-lsp\"").unwrap(); diff --git a/crates/ide-lsp/tests/mock_server.rs b/crates/ide-lsp/tests/mock_server.rs index 0512117192..9b6bfe76be 100644 --- a/crates/ide-lsp/tests/mock_server.rs +++ b/crates/ide-lsp/tests/mock_server.rs @@ -8444,6 +8444,142 @@ fn debug_server_requests(s: &MockState) -> Vec { s.requested("workspace/executeCommand") } +/// One line of kotlin-lsp's `intellij/importLog` (the build tool's output while importing), +/// then a `window/showMessage` waited for: the handler has seen the line once it shows. +async fn import_log(h: &Harness, s: &MockState, line: &str) { + static SYNC: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let sync = format!("sync {}", SYNC.fetch_add(1, std::sync::atomic::Ordering::Relaxed)); + let peer = s.peer(); + peer.notify("intellij/importLog", json!({ "type": 3, "message": line })).unwrap(); + peer.notify("window/showMessage", json!({ "type": 2, "message": sync })).unwrap(); + eventually(|| h.events.lock().iter().any(|e| matches!(e, IdeEvent::Notify { body: Some(b), .. } if *b == sync))) + .await; +} + +/// The messages of the open "Importing" task's events, in order. +fn import_task_messages(h: &Harness) -> Vec> { + h.events + .lock() + .iter() + .filter_map(|e| match e { + IdeEvent::Task { title, message, done: false, .. } if title == "Importing" => Some(message.clone()), + _ => None, + }) + .collect() +} + +#[tokio::test(start_paused = true)] +async fn kotlin_import_output_keeps_the_import_task_alive_and_names_the_gradle_step() { + let (h, s) = kotlin_lsp_harness(); + h.open("Main.kt", "fun main() {}"); + h.wait_status("kotlin-lsp", ServerStatus::Ready).await; + // Output before any import task: nothing to update. + import_log(&h, &s, "> Task :app:preBuild UP-TO-DATE").await; + assert!(import_task_messages(&h).is_empty()); + + import_progress(&s, json!({ "kind": "begin", "title": "Importing" })); + h.wait_status("kotlin-lsp", ServerStatus::Busy).await; + import_log(&h, &s, "> Task :feature-home:compileReleaseJavaWithJavac").await; + assert_eq!( + import_task_messages(&h).last(), + Some(&Some("> Task :feature-home:compileReleaseJavaWithJavac".to_owned())) + ); + import_log(&h, &s, "> Configure project :feature-home").await; + assert_eq!(import_task_messages(&h).last(), Some(&Some("> Configure project :feature-home".to_owned()))); + + // Other output sends no event but counts as activity: the task outlives the stale window. + let events = import_task_messages(&h).len(); + for _ in 0..3 { + tokio::time::advance(Duration::from_secs(100)).await; + import_log(&h, &s, "Note: Some input files use unchecked or unsafe operations.").await; + } + assert_eq!(import_task_messages(&h).len(), events, "a plain output line sends no task event"); + assert_eq!(h.statuses("kotlin-lsp").last(), Some(&ServerStatus::Busy)); + assert!(!import_task_messages(&h).iter().flatten().any(|m| m.contains("no progress"))); + + // No output at all: marked stuck, keeping the last step. + tokio::time::advance(Duration::from_secs(200)).await; + h.wait_status("kotlin-lsp", ServerStatus::Ready).await; + let stalled = import_task_messages(&h).last().cloned().flatten().unwrap(); + assert_eq!(stalled, "> Configure project :feature-home — no progress for 180 s"); + + // Output again clears the mark, even without a step. + import_log(&h, &s, "BUILD SUCCESSFUL in 12m 3s").await; + h.wait_status("kotlin-lsp", ServerStatus::Busy).await; + assert_eq!(import_task_messages(&h).last(), Some(&Some("> Configure project :feature-home".to_owned()))); + + // The import finishes normally; output after it touches no task. + import_progress(&s, json!({ "kind": "end" })); + h.wait_status("kotlin-lsp", ServerStatus::Ready).await; + let events = import_task_messages(&h).len(); + import_log(&h, &s, "> Task :app:late").await; + assert_eq!(import_task_messages(&h).len(), events); + assert_eq!(h.statuses("kotlin-lsp").last(), Some(&ServerStatus::Ready)); +} + +#[tokio::test(flavor = "multi_thread")] +async fn gradle_running_out_of_heap_during_a_kotlin_import_warns_once() { + let (h, s) = kotlin_lsp_harness(); + h.open("Main.kt", "fun main() {}"); + h.wait_status("kotlin-lsp", ServerStatus::Ready).await; + let warnings = |h: &Harness| -> Vec { + h.events + .lock() + .iter() + .filter_map(|e| match e { + IdeEvent::Notify { level: ide_core::event::NotifyLevel::Warning, title, body: Some(b) } + if title == "Gradle ran out of memory" => + { + Some(b.clone()) + } + _ => None, + }) + .collect() + }; + for line in ["> Task :app:compileKotlin", "BUILD SUCCESSFUL", "Daemon will be stopped at the end of the build"] { + import_log(&h, &s, line).await; + } + assert!(warnings(&h).is_empty(), "ordinary output warns about nothing"); + + // Gradle's message, line by line, as kotlin-lsp forwards it; then the same again and a + // stack trace from another worker. + for _ in 0..2 { + for line in [ + "The Daemon will expire after the build after running out of JVM heap space.", + "The project memory settings are likely not configured or are configured to an insufficient value.", + "These settings can be adjusted by setting 'org.gradle.jvmargs' in 'gradle.properties'.", + "The currently configured max heap space is '4 GiB' and the configured max metaspace is '384 MiB'.", + ] { + import_log(&h, &s, line).await; + } + } + import_log(&h, &s, "Caused by: java.lang.OutOfMemoryError: Java heap space").await; + let warnings = warnings(&h); + assert_eq!(warnings.len(), 1, "{warnings:?}"); + assert!(warnings[0].contains("(configured max heap: 4 GiB)"), "{}", warnings[0]); + assert!(warnings[0].contains("org.gradle.jvmargs in gradle.properties"), "{}", warnings[0]); +} + +#[tokio::test(flavor = "multi_thread")] +async fn gradle_out_of_memory_without_the_heap_line_still_warns() { + let (h, s) = kotlin_lsp_harness(); + h.open("Main.kt", "fun main() {}"); + h.wait_status("kotlin-lsp", ServerStatus::Ready).await; + s.peer() + .notify( + "intellij/importLog", + json!({ "type": 2, "message": "java.lang.OutOfMemoryError: GC overhead limit exceeded" }), + ) + .unwrap(); + eventually(|| { + h.events.lock().iter().any(|e| { + matches!(e, IdeEvent::Notify { title, body: Some(b), .. } + if title == "Gradle ran out of memory" && !b.contains("configured max heap") && b.contains("gradle.properties")) + }) + }) + .await; +} + #[tokio::test(flavor = "multi_thread")] async fn waits_for_the_import_before_starting_the_debug_server() { // kotlin-lsp sends the progress end and FINISHED within the same millisecond, in either order.