Skip to content

Commit bd9a10a

Browse files
committed
Preserve unchecked OpenCLI subprocess pipe failures
1 parent 1946d9f commit bd9a10a

5 files changed

Lines changed: 86 additions & 8 deletions

File tree

‎openspec/changes/harden-opencli-process-lifecycle/tasks.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,3 +119,11 @@ Java 21 的一次运行中,未知后代仍在更新心跳,JUnit 已开始清
119119
Java 8、21 功能线的平台矩阵加入 Ubuntu,Java 17 保留现有 Ubuntu JVM 作业。三线平台作业均显式选择旧版输出流的有界写入用例。该用例通过本线 JVM 启动现有 LifecycleProbe,检查退出后从旧 API 写入时的字节上限,并验证此前记录的进程截断事实保持准确。
120120

121121
本地 macOS 上用三个分支的 Wrapper 复跑进程契约、结束竞态、读取失败及两个低层用例,每线 24 项通过,零失败、零错误、零跳过。Linux、macOS 和 Windows 的托管证据按精确功能提交核对。
122+
123+
## 输出读取异常和后代独立管道
124+
125+
OC-PROC-004/005。Java 17 基线 `1946d9f` 的两个故障注入场景均将运行时读取或关闭异常误报为 `PROCESS_EXIT`。Reader 现在报告 `IO_FAILURE`,保留已读取字节、实际直属退出码和显式低层原因。SDK 的默认异常摘要保留固定消息。故障注入用例确认原始 provider 标记不会进入默认诊断。
126+
127+
真实 JVM 进程夹具分别使用继承管道和独立输出文件。两种情况下,取消父进程后,未追踪的后代都继续更新心跳。独立输出用例确认 SDK 可报告 `ROOT_EXIT_CONFIRMED` 和已排空自己的读取线程,同时 `descendantsExitConfirmed` 为 false。继承管道未排空时继续标记 `UNCONFIRMED`。用例通过释放文件停止自己的后代,并等待其最后一次写入的确认。
128+
129+
Java 8 `1310c54`、Java 17 `1946d9f`、Java 21 `89da70e` 为修改前基线。各线使用 Wrapper 执行 `./mvnw -B -ntp -o clean verify`,分别通过 2,254、2,255、2,254 项,零失败、零错误、零跳过。报告为 `SubprocessStreamFailureTest` 与 `OpenCliProcessContractTest` 的 Surefire XML。此处给出直属进程和管道边界的运行证据。多平台的已声明能力与未追踪后代的限制继续由 3.2 验收。

‎src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -510,6 +510,8 @@ public void run() {
510510
}
511511
} catch (IOException ex) {
512512
failure = ex;
513+
} catch (RuntimeException ex) {
514+
failure = new IOException("Native process output stream failed", ex);
513515
}
514516
}
515517
}

‎src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,18 @@ public static void main(String[] args) throws Exception {
3131
writeStream(stream, Integer.parseInt(args[1]));
3232
return;
3333
}
34-
if ("inherited-pipes".equals(mode)) {
34+
if ("inherited-pipes".equals(mode) || "isolated-pipes".equals(mode)) {
3535
String executable = System.getProperty("os.name").startsWith("Windows") ? "java.exe" : "java";
3636
Path java = Paths.get(System.getProperty("java.home"), "bin", executable);
37-
new ProcessBuilder(java.toString(), "-cp", System.getProperty("java.class.path"),
38-
LifecycleProbe.class.getName(), "heartbeat", args[3], args[2], args[4]).inheritIO().start();
37+
ProcessBuilder descendant = new ProcessBuilder(java.toString(), "-cp", System.getProperty("java.class.path"),
38+
LifecycleProbe.class.getName(), "heartbeat", args[3], args[2], args[4]);
39+
if ("inherited-pipes".equals(mode)) {
40+
descendant.inheritIO();
41+
} else {
42+
Path log = Paths.get(args[3]).resolveSibling("descendant.log");
43+
descendant.redirectErrorStream(true).redirectOutput(log.toFile());
44+
}
45+
descendant.start();
3946
}
4047
if ("capture-hold".equals(mode)) {
4148
writeStream(System.out, Integer.parseInt(args[3]));

‎src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@
3232
import org.junit.jupiter.api.Test;
3333
import org.junit.jupiter.api.Timeout;
3434
import org.junit.jupiter.api.io.TempDir;
35+
import org.junit.jupiter.params.ParameterizedTest;
36+
import org.junit.jupiter.params.provider.ValueSource;
3537
import static org.junit.jupiter.api.Assertions.*;
3638

3739
/** C02 tests observe actual fixture processes, not private semaphore counters. */
@@ -431,8 +433,9 @@ void sharedRuntimeBoundsConcurrentChildrenAndCombinedCapture() throws Exception
431433
}
432434
}
433435

434-
@Test
435-
void cancelledParentWithInheritedPipesReturnsWithinCleanupBudget() throws Exception {
436+
@ParameterizedTest
437+
@ValueSource(strings = {"inherited-pipes", "isolated-pipes"})
438+
void cancelledParentPreservesUntrackedDescendantWithinCleanupBudget(String pipeMode) throws Exception {
436439
Path parent = dir.resolve("parent");
437440
Path descendant = dir.resolve("descendant");
438441
Path release = dir.resolve("release");
@@ -444,15 +447,18 @@ void cancelledParentWithInheritedPipesReturnsWithinCleanupBudget() throws Except
444447
ExecutorService worker = Executors.newSingleThreadExecutor();
445448
try {
446449
Future<OpenCliException> failure = worker.submit(() -> assertThrows(OpenCliException.class,
447-
() -> executor.invoke(Arrays.asList("inherited-pipes", parent.toString(),
450+
() -> executor.invoke(Arrays.asList(pipeMode, parent.toString(),
448451
release.toString(), descendant.toString(), stopped.toString()), token)));
449-
assertTrue(awaitFile(descendant, 5_000L), "descendant never inherited the pipes");
452+
assertTrue(awaitFile(descendant, 5_000L), "descendant never started");
450453
token.cancel();
451454
OpenCliExecutionDetails details = failure.get(1_500L, TimeUnit.MILLISECONDS).getPartialResult()
452455
.getExecutionDetails();
453456
assertEquals(TerminationReason.CANCELLED, details.getTerminationReason());
454457
assertFalse(details.isDescendantsExitConfirmed());
455-
if (!details.isStreamsDrained()) {
458+
if ("isolated-pipes".equals(pipeMode)) {
459+
assertTrue(details.isStreamsDrained());
460+
assertEquals(OpenCliExecutionDetails.CleanupState.ROOT_EXIT_CONFIRMED, details.getCleanupState());
461+
} else if (!details.isStreamsDrained()) {
456462
assertEquals(OpenCliExecutionDetails.CleanupState.UNCONFIRMED, details.getCleanupState());
457463
}
458464
byte[] firstHeartbeat = Files.readAllBytes(descendant);

‎src/test/java/io/github/easy4j/opencli/core/support/SubprocessStreamFailureTest.java‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import java.io.IOException;
99
import java.io.InputStream;
1010
import java.io.OutputStream;
11+
import java.io.PrintStream;
1112
import java.nio.charset.StandardCharsets;
1213
import java.util.concurrent.CountDownLatch;
1314
import java.util.concurrent.TimeUnit;
@@ -16,13 +17,17 @@
1617
import org.apache.commons.exec.ExecuteWatchdog;
1718
import org.junit.jupiter.api.Test;
1819
import org.junit.jupiter.api.Timeout;
20+
import org.junit.jupiter.api.parallel.Isolated;
21+
import org.junit.jupiter.params.ParameterizedTest;
22+
import org.junit.jupiter.params.provider.ValueSource;
1923

2024
import static org.junit.jupiter.api.Assertions.assertEquals;
2125
import static org.junit.jupiter.api.Assertions.assertFalse;
2226
import static org.junit.jupiter.api.Assertions.assertSame;
2327
import static org.junit.jupiter.api.Assertions.assertTrue;
2428

2529
/** Verifies that reader-thread I/O faults survive into the terminal result. */
30+
@Isolated
2631
@Timeout(5)
2732
class SubprocessStreamFailureTest {
2833

@@ -44,6 +49,56 @@ void partialOutputAndReadFailureRemainVisibleAfterRootExit() throws Exception {
4449
assertTrue(session.getExecutionDetails().isStreamsDrained());
4550
}
4651

52+
@ParameterizedTest
53+
@ValueSource(booleans = {false, true})
54+
void uncheckedPipeFailureKeepsPartialOutputAndDoesNotEscapeTheReader(boolean duringClose) throws Exception {
55+
String canary = "private-provider-pipe-fault";
56+
RuntimeException nativeFailure = new IllegalStateException(canary);
57+
InputStream output = new ByteArrayInputStream("abc".getBytes(StandardCharsets.UTF_8)) {
58+
@Override
59+
public synchronized int read(byte[] bytes, int offset, int length) {
60+
int read = super.read(bytes, offset, length);
61+
if (read < 0 && !duringClose) {
62+
throw nativeFailure;
63+
}
64+
return read;
65+
}
66+
67+
@Override
68+
public void close() {
69+
if (duringClose) {
70+
throw nativeFailure;
71+
}
72+
}
73+
};
74+
SubprocessExecutionSupport.Runtime runtime = new SubprocessExecutionSupport.Runtime(1,
75+
builder -> new ExitedProcess(output), timeout -> new IdleWatchdog());
76+
SubprocessExecutionSupport.ExecutionRequest request = new SubprocessExecutionSupport.ExecutionRequest(
77+
CommandLine.parse("fake"), null, null, 1_000L, 32, 32, 100L,
78+
System.nanoTime(), new OpenCliCancellationToken());
79+
80+
ByteArrayOutputStream diagnostics = new ByteArrayOutputStream();
81+
PrintStream previous = System.err;
82+
SubprocessExecutionSupport.RunSession session;
83+
try (PrintStream capture = new PrintStream(diagnostics, true, StandardCharsets.UTF_8.name())) {
84+
System.setErr(capture);
85+
try {
86+
session = runtime.execute(request);
87+
if (session.getHandler().getException() != null) {
88+
session.getHandler().getException().printStackTrace(capture);
89+
}
90+
} finally {
91+
System.setErr(previous);
92+
}
93+
}
94+
95+
assertEquals(TerminationReason.IO_FAILURE, session.getExecutionDetails().getTerminationReason());
96+
assertSame(nativeFailure, session.getIoFailure().getCause());
97+
assertEquals("abc", new String(session.getStdout().toByteArray(), StandardCharsets.UTF_8));
98+
assertTrue(session.getExecutionDetails().isStreamsDrained());
99+
assertFalse(diagnostics.toString(StandardCharsets.UTF_8.name()).contains(canary));
100+
}
101+
47102
@Test
48103
void readerFailureDuringRootExitPollDoesNotReportSuccessfulCompletion() throws Exception {
49104
IOException readFailure = new IOException("reader failed while root exit was observed");

0 commit comments

Comments
 (0)