This is an automated email from the ASF dual-hosted git repository.

lizhimins pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/rocketmq-dashboard.git


The following commit(s) were added to refs/heads/master by this push:
     new e4f360917 fix(ai): keep CLI diagnostics out of Qoder completions 
(#6777)
e4f360917 is described below

commit e4f360917c38b9be3e3c24763c6ab6a4798ad036
Author: 健康宝 <[email protected]>
AuthorDate: Fri Nov 27 11:57:10 2026 +0800

    fix(ai): keep CLI diagnostics out of Qoder completions (#6777)
---
 .../rocketmq/studio/ops/ai/CliAgentProvider.java   | 53 ++++++++++++++++++----
 .../studio/ops/ai/CliAgentProviderTest.java        | 33 ++++++++++++--
 2 files changed, 73 insertions(+), 13 deletions(-)

diff --git 
a/server/src/main/java/org/apache/rocketmq/studio/ops/ai/CliAgentProvider.java 
b/server/src/main/java/org/apache/rocketmq/studio/ops/ai/CliAgentProvider.java
index 6a226f0f5..755a7a6c2 100644
--- 
a/server/src/main/java/org/apache/rocketmq/studio/ops/ai/CliAgentProvider.java
+++ 
b/server/src/main/java/org/apache/rocketmq/studio/ops/ai/CliAgentProvider.java
@@ -91,12 +91,14 @@ public abstract class CliAgentProvider implements 
AgentProvider {
         List<String> command = buildCommand(config, prompt, modelOverride);
         ProcessBuilder builder = new ProcessBuilder(command);
         processEnvironment.apply(builder, childEnv(config));
-        // Merge stderr into stdout and drain the stream on a background 
thread. Reading stdout
-        // then stderr sequentially on the caller thread deadlocks once the 
child fills a pipe
-        // buffer (64 KiB), and a timeout that runs only after both reads can 
never fire while the
-        // child stays alive. With the merged stream drained in the 
background, waitFor can enforce
-        // the timeout and a hung child is destroyed instead of leaking the 
caller thread.
-        builder.redirectErrorStream(true);
+        // Keep stdout and stderr separate and drain both on background 
threads. Reading them
+        // sequentially on the caller thread deadlocks once the child fills a 
pipe buffer (64 KiB),
+        // and a timeout that runs only after both reads can never fire while 
the child stays alive.
+        // With both pipes drained in the background, waitFor can enforce the 
timeout and a hung
+        // child is destroyed instead of leaking the caller thread. stdout is 
the completion result;
+        // stderr is failure diagnostics — merged streams let a CLI's SDK 
warnings leak into the
+        // answer, and an answers-only-on-stderr run would pass the 
empty-completion check.
+        builder.redirectErrorStream(false);
         // CLIs wait for piped stdin and emit a warning that leaks into the 
reply unless
         // stdin is explicitly /dev/null; fall back to closing the pipe where 
unavailable.
         boolean devNullAvailable = new java.io.File("/dev/null").exists();
@@ -121,6 +123,13 @@ public abstract class CliAgentProvider implements 
AgentProvider {
                 throw new CompletionException(exception);
             }
         });
+        CompletableFuture<String> stderrFuture = 
CompletableFuture.supplyAsync(() -> {
+            try {
+                return readStderr(process);
+            } catch (IOException exception) {
+                throw new CompletionException(exception);
+            }
+        });
         boolean finished;
         try {
             finished = process.waitFor(TIMEOUT_SECONDS, TimeUnit.SECONDS);
@@ -149,6 +158,15 @@ public abstract class CliAgentProvider implements 
AgentProvider {
         } catch (TimeoutException exception) {
             output = "";
         }
+        String stderr;
+        try {
+            stderr = stderrFuture.get(10, TimeUnit.SECONDS);
+        } catch (ExecutionException | TimeoutException exception) {
+            stderr = "";
+        } catch (InterruptedException exception) {
+            Thread.currentThread().interrupt();
+            stderr = "";
+        }
         if (!finished) {
             process.destroyForcibly();
             throw new LlmGatewayException(504, "llm.provider.timeout",
@@ -156,9 +174,11 @@ public abstract class CliAgentProvider implements 
AgentProvider {
                     "Retry with a shorter prompt or check the gateway 
latency.");
         }
         if (process.exitValue() != 0) {
-            log.warn("{} CLI failed rc={}, output={}", binaryName(), 
process.exitValue(), abbreviate(output));
+            String diagnostics = StringUtils.hasText(stderr) ? stderr : output;
+            log.warn("{} CLI failed rc={}, output={}", binaryName(), 
process.exitValue(),
+                    abbreviate(diagnostics));
             throw new LlmGatewayException(502, "llm.provider.cli_error",
-                    binaryName() + " CLI failed: " + abbreviate(output),
+                    binaryName() + " CLI failed: " + abbreviate(diagnostics),
                     "Check the provider credentials, base URL and model 
name.");
         }
         String result = output.trim();
@@ -187,6 +207,23 @@ public abstract class CliAgentProvider implements 
AgentProvider {
         }
     }
 
+    private String readStderr(Process process) throws IOException {
+        // Diagnostics only: keep at most limitBytes of them, but keep 
draining to the end so a
+        // chatty child never blocks on a full stderr pipe while the 
completion is still unread.
+        int limitBytes = outputLimitBytes();
+        try (InputStream input = process.getErrorStream();
+             ByteArrayOutputStream output = new 
ByteArrayOutputStream(Math.min(limitBytes, 8192))) {
+            byte[] buffer = new byte[8192];
+            int read;
+            while ((read = input.read(buffer)) != -1) {
+                if (output.size() < limitBytes) {
+                    output.write(buffer, 0, Math.min(read, limitBytes - 
output.size()));
+                }
+            }
+            return output.toString(StandardCharsets.UTF_8);
+        }
+    }
+
     int outputLimitBytes() {
         return MAX_OUTPUT_BYTES;
     }
diff --git 
a/server/src/test/java/org/apache/rocketmq/studio/ops/ai/CliAgentProviderTest.java
 
b/server/src/test/java/org/apache/rocketmq/studio/ops/ai/CliAgentProviderTest.java
index 4259bc28f..81de582f6 100644
--- 
a/server/src/test/java/org/apache/rocketmq/studio/ops/ai/CliAgentProviderTest.java
+++ 
b/server/src/test/java/org/apache/rocketmq/studio/ops/ai/CliAgentProviderTest.java
@@ -113,7 +113,7 @@ class CliAgentProviderTest {
     @Test
     void completeSurvivesLargeStderrOutput() {
         // Write well over the 64 KiB pipe buffer to stderr, then print the 
completion on stdout.
-        // Before the fix, sequential stdout/stderr reads deadlocked the 
caller forever.
+        // Before the concurrent drains, sequential stdout/stderr reads 
deadlocked the caller forever.
         String script = "for i in $(seq 1 10000); do "
                 + "echo 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' 
>&2; done; "
                 + "echo DONE";
@@ -121,10 +121,33 @@ class CliAgentProviderTest {
 
         String result = cli.complete(null, "prompt", null);
 
-        assertThat(result).contains("DONE");
-        // All stderr bytes were drained as well (merged into the single 
output stream),
-        // well past the 64 KiB pipe buffer that used to deadlock the 
sequential reads.
-        assertThat(result.length()).isGreaterThan(500_000);
+        // The 500 KiB of stderr were drained concurrently (no deadlock), and 
none of it leaked
+        // into the completion: the result is exactly what stdout carried.
+        assertThat(result).isEqualTo("DONE");
+    }
+
+    @Test
+    void completeRejectsACompletionWhoseStdoutStayedEmptyTest() {
+        // A CLI that only ever writes warnings to stderr did not produce a 
completion; accepting
+        // the warning text as the answer bypassed the empty-completion check 
entirely.
+        FakeCli cli = new FakeCli("printf 'SDK warning: nothing written to 
stdout' >&2");
+
+        assertThatThrownBy(() -> cli.complete(null, "prompt", null))
+                .isInstanceOfSatisfying(LlmGatewayException.class, exception 
-> {
+                    assertThat(exception.getStatusCode()).isEqualTo(502);
+                    
assertThat(exception.getCode()).isEqualTo("llm.provider.empty_completion");
+                });
+    }
+
+    @Test
+    void completeReportsStderrDiagnosticsOnFailureTest() {
+        FakeCli cli = new FakeCli("printf 'quota exhausted' >&2; exit 3");
+
+        assertThatThrownBy(() -> cli.complete(null, "prompt", null))
+                .isInstanceOfSatisfying(LlmGatewayException.class, exception 
-> {
+                    
assertThat(exception.getCode()).isEqualTo("llm.provider.cli_error");
+                    assertThat(exception.getMessage()).contains("quota 
exhausted");
+                });
     }
 
     @Test

Reply via email to