Skip to content

Commit 2a5ecb7

Browse files
committed
fix: bound blocking OpenCLI process termination
1 parent 6e59945 commit 2a5ecb7

4 files changed

Lines changed: 176 additions & 28 deletions

File tree

‎.github/workflows/contracts.yml‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@ jobs:
124124
--suite argv=io.github.easy4j.opencli.contract.OpenCliStructuredArgvContractTest \
125125
--suite process=io.github.easy4j.opencli.contract.OpenCliProcessContractTest \
126126
--suite process=io.github.easy4j.opencli.contract.OpenCliProcessBoundaryTest \
127+
--suite process=io.github.easy4j.opencli.core.support.SubprocessCleanupFaultTest \
127128
--output contract-evidence/report.json
128129
- name: Upload actual JVM evidence
129130
if: always()
@@ -173,7 +174,7 @@ jobs:
173174
mvn -version > platform-evidence/maven.txt 2>&1
174175
result=0
175176
mvn -B --no-transfer-progress \
176-
-Dtest=OpenCliArgvContractTest,OpenCliStructuredArgvContractTest,OpenCliProcessContractTest,OpenCliProcessBoundaryTest,OpenCliWsReverseAgentSessionTest,OpenCliWsCollectRequestsTest,OpenCliProcessPrivacyTest \
177+
-Dtest=OpenCliArgvContractTest,OpenCliStructuredArgvContractTest,OpenCliProcessContractTest,OpenCliProcessBoundaryTest,SubprocessCleanupFaultTest,OpenCliWsReverseAgentSessionTest,OpenCliWsCollectRequestsTest,OpenCliProcessPrivacyTest \
177178
test > platform-evidence/maven.log 2>&1 || result=$?
178179
tail -100 platform-evidence/maven.log
179180
python scripts/contract_report.py \
@@ -187,6 +188,7 @@ jobs:
187188
--suite argv=io.github.easy4j.opencli.contract.OpenCliStructuredArgvContractTest \
188189
--suite process=io.github.easy4j.opencli.contract.OpenCliProcessContractTest \
189190
--suite process=io.github.easy4j.opencli.contract.OpenCliProcessBoundaryTest \
191+
--suite process=io.github.easy4j.opencli.core.support.SubprocessCleanupFaultTest \
190192
--suite protocol=io.github.easy4j.opencli.center.ws.OpenCliWsReverseAgentSessionTest \
191193
--suite protocol=io.github.easy4j.opencli.center.ws.OpenCliWsCollectRequestsTest \
192194
--suite process=io.github.easy4j.opencli.core.OpenCliProcessPrivacyTest \

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,3 +89,11 @@ JDK 17 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,117 项通过,0
8989
修复后,第一次非空写入才分配对应捕获数组,仍受流的配置上限约束。预取消路径的 stdout、stderr 容量均为零,读取线程的工作缓冲和 JVM 总堆内存属独立指标。红灯 2 项失败,修复后 JDK 17 定向 33 项通过。
9090

9191
JDK 17 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,118 项通过,0 失败、0 错误、0 跳过。
92+
93+
## 2026-11-18 OC-PROC-005 终止操作阻塞
94+
95+
故障注入让调用独占根进程的普通和强制终止分别等待释放信号。验证显式取消以及 Commons Exec watchdog 到期两条路径。设置清理宽限 250 ms,以 1,250 ms 为回归断言窗口。修复前两项均等待超时。
96+
97+
修复将 native 终止调用交给每次执行最多两个守护工作线程,普通和强制终止各发出一次。watchdog 回调只提交终止请求,既有锁不覆盖 native 终止操作。原始 `CANCELLED` 或 `EXECUTION_TIMEOUT` 保留。终止操作未结束时保留 `UNCONFIRMED`,不伪造退出码,并隔离当前运行时。测试最后释放注入的阻塞线程。该修复范围为 SDK 已持有的根进程,后代所有权仍待验收。
98+
99+
JDK 17 定向 29 项通过。JDK 17 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,120 项通过,0 失败、0 错误、0 跳过。平台契约证据增加 `SubprocessCleanupFaultTest`。

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

Lines changed: 93 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import java.io.File;
99
import java.io.IOException;
1010
import java.io.InputStream;
11+
import java.io.OutputStream;
1112
import java.util.ArrayList;
1213
import java.util.Arrays;
1314
import java.util.Collections;
@@ -118,7 +119,7 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
118119
long budget = nanos(request.timeoutMillis, "timeoutMillis");
119120
BoundedCapture out = new BoundedCapture(request.stdoutLimitBytes);
120121
BoundedCapture err = new BoundedCapture(request.stderrLimitBytes);
121-
Process process = null;
122+
CleanupProcess process = null;
122123
Reader stdoutReader = null;
123124
Reader stderrReader = null;
124125
ExecuteWatchdog watchdog = null;
@@ -130,6 +131,7 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
130131
long queueWaitMillis = 0L;
131132
Integer exit = null;
132133
boolean streamsDrained = true;
134+
boolean cleanupFinished = true;
133135
try {
134136
while (!acquired && reason == null) {
135137
if (Thread.interrupted()) {
@@ -168,7 +170,7 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
168170
builder.environment().clear();
169171
builder.environment().putAll(request.environment);
170172
}
171-
process = processStarter.start(builder);
173+
process = new CleanupProcess(processStarter.start(builder));
172174
process.getOutputStream().close();
173175
stdoutReader = new Reader(process.getInputStream(), out, "opencli-stdout");
174176
stderrReader = new Reader(process.getErrorStream(), err, "opencli-stderr");
@@ -226,23 +228,17 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
226228
long cleanupStart = System.nanoTime();
227229
long cleanupBudget = nanos(request.cleanupGraceMillis, "cleanupGraceMillis");
228230
if (Objects.nonNull(process)) {
229-
boolean forceSent = false;
230231
if (process.isAlive()) {
231-
try {
232-
process.destroy();
233-
} catch (RuntimeException ex) {
234-
cleanupOperationFailed = true;
235-
forceSent = true;
236-
if (!tryForceStop(process)) { cleanupOperationFailed = true; }
237-
}
232+
process.destroy();
238233
}
234+
long forceAfter = Math.min(TimeUnit.MILLISECONDS.toNanos(100L), cleanupBudget / 2L);
239235
while (remaining(cleanupStart, cleanupBudget) > 0
240-
&& (process.isAlive() || alive(stdoutReader) || alive(stderrReader))) {
236+
&& (process.isAlive() || alive(stdoutReader) || alive(stderrReader)
237+
|| process.hasPendingStop())) {
241238
if (Thread.interrupted()) { interrupted = true; }
242-
if (process.isAlive() && !forceSent
243-
&& System.nanoTime() - cleanupStart >= Math.min(TimeUnit.MILLISECONDS.toNanos(100L), cleanupBudget / 2)) {
244-
if (!tryForceStop(process)) { cleanupOperationFailed = true; }
245-
forceSent = true;
239+
if (process.isAlive() && (process.graceful.failed
240+
|| System.nanoTime() - cleanupStart >= forceAfter)) {
241+
process.destroyForcibly();
246242
}
247243
try {
248244
TimeUnit.NANOSECONDS.sleep(Math.min(POLL_NANOS,
@@ -251,13 +247,17 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
251247
interrupted = true;
252248
}
253249
}
254-
if (process.isAlive() && !tryForceStop(process)) { cleanupOperationFailed = true; }
250+
if (process.isAlive()) {
251+
process.destroyForcibly();
252+
}
253+
cleanupFinished = !process.hasPendingStop();
254+
cleanupOperationFailed |= !cleanupFinished || process.graceful.failed || process.forced.failed;
255255
if (!process.isAlive()) {
256256
exit = process.exitValue();
257257
}
258258
streamsDrained = !alive(stdoutReader) && !alive(stderrReader);
259-
if (Objects.isNull(exit) || !streamsDrained) {
260-
// A fixed runtime cannot accumulate unlimited uncertain children/readers.
259+
if (Objects.isNull(exit) || !streamsDrained || !cleanupFinished) {
260+
// Quarantine limits the number of unconfirmed children, readers and stop workers.
261261
quarantined = true;
262262
if (reason == TerminationReason.PROCESS_EXIT) { reason = TerminationReason.CLEANUP_UNCONFIRMED; }
263263
}
@@ -283,7 +283,8 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
283283
OpenCliExecutionDetails details = OpenCliExecutionDetails.builder()
284284
.terminationReason(reason)
285285
.cleanupState(process == null ? CleanupState.NOT_STARTED
286-
: Objects.isNull(exit) || !streamsDrained ? CleanupState.UNCONFIRMED : CleanupState.ROOT_EXIT_CONFIRMED)
286+
: Objects.isNull(exit) || !streamsDrained || !cleanupFinished
287+
? CleanupState.UNCONFIRMED : CleanupState.ROOT_EXIT_CONFIRMED)
287288
.processStarted(process != null).streamsDrained(streamsDrained)
288289
.cleanupOperationFailed(cleanupOperationFailed)
289290
.stdoutCapturedBytes(out.size()).stdoutObservedBytes(out.observed()).stdoutTruncated(out.isTruncated())
@@ -303,14 +304,81 @@ private static ExecuteWatchdog newWatchdog(long timeoutMillis) {
303304
}
304305

305306
private static boolean alive(Thread thread) { return thread != null && thread.isAlive(); }
306-
private static boolean tryForceStop(Process process) {
307-
try {
308-
process.destroyForcibly();
309-
return true;
310-
} catch (RuntimeException ex) {
311-
return false;
307+
/**
308+
* The watchdog holds its monitor when invoking destroy. Keep native stop calls
309+
* outside that monitor and the caller, as closing process pipes can block.
310+
*/
311+
private static final class CleanupProcess extends Process {
312+
private final Process delegate;
313+
private final StopRequest graceful = new StopRequest();
314+
private final StopRequest forced = new StopRequest();
315+
316+
CleanupProcess(Process delegate) {
317+
this.delegate = delegate;
318+
}
319+
320+
@Override
321+
public OutputStream getOutputStream() { return delegate.getOutputStream(); }
322+
323+
@Override
324+
public InputStream getInputStream() { return delegate.getInputStream(); }
325+
326+
@Override
327+
public InputStream getErrorStream() { return delegate.getErrorStream(); }
328+
329+
@Override
330+
public int waitFor() throws InterruptedException { return delegate.waitFor(); }
331+
332+
@Override
333+
public int exitValue() { return delegate.exitValue(); }
334+
335+
@Override
336+
public boolean isAlive() { return delegate.isAlive(); }
337+
338+
@Override
339+
public void destroy() {
340+
graceful.start("opencli-stop", delegate::destroy);
341+
}
342+
343+
@Override
344+
public Process destroyForcibly() {
345+
forced.start("opencli-force-stop", delegate::destroyForcibly);
346+
return this;
347+
}
348+
349+
boolean hasPendingStop() {
350+
return graceful.isPending() || forced.isPending();
312351
}
313352
}
353+
354+
private static final class StopRequest {
355+
private Thread worker;
356+
private volatile boolean failed;
357+
358+
synchronized void start(String name, Runnable signal) {
359+
if (Objects.nonNull(worker) || failed) {
360+
return;
361+
}
362+
try {
363+
worker = new Thread(() -> {
364+
try {
365+
signal.run();
366+
} catch (RuntimeException ex) {
367+
failed = true;
368+
}
369+
}, name);
370+
worker.setDaemon(true);
371+
worker.start();
372+
} catch (RuntimeException ex) {
373+
failed = true;
374+
}
375+
}
376+
377+
synchronized boolean isPending() {
378+
return alive(worker);
379+
}
380+
}
381+
314382
private static long remaining(long start, long budget) { return budget - (System.nanoTime() - start); }
315383
// The Windows JDK legacy serializer treats a surrounding quote pair as already encoded.
316384
@SuppressWarnings("removal")

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

Lines changed: 72 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,11 @@
77
import java.io.ByteArrayOutputStream;
88
import java.io.InputStream;
99
import java.io.OutputStream;
10+
import java.util.concurrent.CountDownLatch;
11+
import java.util.concurrent.ExecutorService;
12+
import java.util.concurrent.Executors;
13+
import java.util.concurrent.Future;
14+
import java.util.concurrent.TimeUnit;
1015
import java.util.concurrent.atomic.AtomicReference;
1116
import org.apache.commons.exec.CommandLine;
1217
import org.apache.commons.exec.ExecuteWatchdog;
@@ -148,6 +153,71 @@ void unconfirmedForcedStopQuarantinesRuntimeWithoutFabricatingExit() throws Exce
148153
assertEquals(1, starts[0]);
149154
}
150155

156+
@Test
157+
void blockedGracefulAndForcedStopDoNotHoldCallerPastCleanupGrace() throws Exception {
158+
assertBoundedStop(false, TerminationReason.CANCELLED);
159+
}
160+
161+
@Test
162+
void watchdogTimeoutDoesNotHoldCallerWhileNativeStopIsBlocked() throws Exception {
163+
assertBoundedStop(true, TerminationReason.EXECUTION_TIMEOUT);
164+
}
165+
166+
private static void assertBoundedStop(boolean watchdogExpires, TerminationReason expected) throws Exception {
167+
CountDownLatch gracefulEntered = new CountDownLatch(1);
168+
CountDownLatch forceEntered = new CountDownLatch(1);
169+
CountDownLatch release = new CountDownLatch(1);
170+
FakeProcess child = new FakeProcess(false) {
171+
@Override
172+
public void destroy() {
173+
waitForRelease(gracefulEntered, release);
174+
super.destroy();
175+
}
176+
177+
@Override
178+
public Process destroyForcibly() {
179+
waitForRelease(forceEntered, release);
180+
return super.destroyForcibly();
181+
}
182+
};
183+
OpenCliCancellationToken token = new OpenCliCancellationToken();
184+
SubprocessExecutionSupport.Runtime runtime = new SubprocessExecutionSupport.Runtime(1,
185+
builder -> {
186+
if (!watchdogExpires) {
187+
token.cancel();
188+
}
189+
return child;
190+
}, timeout -> watchdogExpires ? new ExecuteWatchdog(20L) : new FakeWatchdog(false));
191+
SubprocessExecutionSupport.ExecutionRequest request = new SubprocessExecutionSupport.ExecutionRequest(
192+
CommandLine.parse("fake"), null, null, 1000L, 16, 16, 250L, System.nanoTime(), token);
193+
194+
ExecutorService worker = Executors.newSingleThreadExecutor();
195+
try {
196+
Future<SubprocessExecutionSupport.RunSession> pending = worker.submit(() -> runtime.execute(request));
197+
assertTrue(gracefulEntered.await(1, TimeUnit.SECONDS));
198+
SubprocessExecutionSupport.RunSession session = pending.get(1250, TimeUnit.MILLISECONDS);
199+
assertEquals(0, forceEntered.getCount());
200+
assertEquals(expected, session.getExecutionDetails().getTerminationReason());
201+
assertEquals(CleanupState.UNCONFIRMED, session.getExecutionDetails().getCleanupState());
202+
assertTrue(session.getExecutionDetails().isCleanupOperationFailed());
203+
assertNull(session.getObservedExitCode());
204+
assertTrue(runtime.isQuarantined());
205+
} finally {
206+
release.countDown();
207+
worker.shutdownNow();
208+
assertTrue(worker.awaitTermination(2, TimeUnit.SECONDS));
209+
}
210+
}
211+
212+
private static void waitForRelease(CountDownLatch entered, CountDownLatch release) {
213+
entered.countDown();
214+
try {
215+
release.await(3, TimeUnit.SECONDS);
216+
} catch (InterruptedException failure) {
217+
Thread.currentThread().interrupt();
218+
}
219+
}
220+
151221
@Test
152222
void cancelledSubmissionDoesNotInitializeWatchdogOrSpawn() throws Exception {
153223
OpenCliCancellationToken token = new OpenCliCancellationToken();
@@ -233,9 +303,9 @@ public synchronized void stop() {
233303
public synchronized boolean killedProcess() { return false; }
234304
}
235305

236-
private static final class FakeProcess extends Process {
306+
private static class FakeProcess extends Process {
237307
private final boolean failDestroy;
238-
private boolean alive = true;
308+
private volatile boolean alive = true;
239309

240310
private final boolean failForce;
241311
private final boolean failStreamSetup;

0 commit comments

Comments
 (0)