Skip to content

Commit 9717538

Browse files
committed
fix(opencli): retain cleanup evidence when stop operations throw
1 parent f9c058b commit 9717538

5 files changed

Lines changed: 249 additions & 37 deletions

File tree

‎docs/implementation/c10-c01-execution.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ System.nanoTime 驱动提交到执行的总预算。排队到期不创建子进
6363
C01/C02 的 Change 继续 IN_PROGRESS;不能因为上述测试通过就整体勾选或 archive。
6464

6565
- C01:自定义 Object.toString() 返回 null 的输入已补拒绝测试;Windows/macOS 和三版本线实际完整回归尚未完成。
66-
- C02:底层 stop/destroy 抛 unchecked 异常时的收尾保护需要故障注入验证和补强;未知清理、取消/自然退出竞争及未确认后代的验收仍需继续。
66+
- C02:底层 stop/destroy 抛 unchecked 异常的收尾保护已有故障注入验证;取消/自然退出竞争、其他清理异常及未确认后代的验收仍需继续。
6767
- C09:HTTP、WS、诊断和异常 cause 链仍需独立隐私回归;本地参数日志减少不构成全域完成。
6868
- C03/C04/C05 尚未进入本轮新实现,C06/C07/C08 也尚未进入;不得跳过这些项关闭 C10。
6969
- 1.x/JDK8、3.x/JDK21、真实 OpenCLI 输出采集、CodeGraph 索引以及独立代码评审未完成。不能用本批 JDK17 证据代替它们。
@@ -83,3 +83,7 @@ C01/C02 的 Change 继续 IN_PROGRESS;不能因为上述测试通过就整体
8383
从现行 `feature/2.0.x` 建立 `feature/REQ-20261118-wandl-opencli-contracts-20`,合并旧草稿的 C10/C01/C02 实现,并保留现行基线新增的远端传输关闭和 `maxOutputBytes` 配置入口。输出超限按 C02 规格返回 `OUTPUT_LIMIT` 与有界部分结果;旧版“截断但成功”测试已改为核验该已确定的行为。新增自定义 `Object.toString()` 返回 null 的拒绝回归。
8484

8585
本地 JDK 17 `clean verify` 实际执行 2059 项 Java 测试,0 失败、0 错误、0 跳过;13 项 Python evidence-runner 自测通过;OpenSpec 1.14.1 strict 验证 10/10。修正 Surefire 的 JaCoCo agent 参数后,实际覆盖为 2550/2989 行(85.31%),低于现有 90% 告警目标;门禁配置未降低。当前新分支仍需自身精确提交的远端 CI、覆盖补足、C02 故障注入、跨平台和跨版本验证,因此 Change 保持进行中。
86+
87+
## 9. C02 清理操作异常回归
88+
89+
新增可控进程和 watchdog 故障注入:`destroy()` 抛异常时仍尝试强制终止;`watchdog.stop()` 抛异常时仍清理所拥有的进程;两种已确认退出路径都保留 `cleanupOperationFailed` 证据并释放许可。强制终止也失败时不虚构退出码,结果标记 `UNCONFIRMED`,隔离该 Runtime,拒绝后续启动。目标测试先以 2 项错误复现异常逃出清理路径,修复后扩展为 3 项通过。本地 JDK 17 完整 `clean verify` 执行 2062 项测试,0 失败、0 错误、0 跳过;实际 JaCoCo 2572/3008 行(85.51%),仍低于现有 90% 告警目标。此新增提交的远端 CI 需单独验证。

‎openspec/implementation-status.json‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,15 @@
88
"verifiedCodeTree": null,
99
"runId": null,
1010
"previousEvidence": {"head": "3bacc8d09b1eeeaa05d6137e2a7e9c350d6622ce", "tree": "f421af093023fb11683fcd4334806f12d9aa140c", "runId": 35564455068},
11-
"localValidation": {"javaTests": 2059, "failures": 0, "errors": 0, "skipped": 0, "jacocoCoveredLines": 2550, "jacocoTotalLines": 2989, "jacocoTarget": 0.90, "pythonRunnerSelfTests": 13, "openspecStrictChangesPassed": 10},
12-
"javaTests": {"tests": 2059, "failures": 0, "errors": 0, "skipped": 0},
11+
"localValidation": {"javaTests": 2062, "failures": 0, "errors": 0, "skipped": 0, "jacocoCoveredLines": 2572, "jacocoTotalLines": 3008, "jacocoTarget": 0.90, "pythonRunnerSelfTests": 13, "openspecStrictChangesPassed": 10},
12+
"javaTests": {"tests": 2062, "failures": 0, "errors": 0, "skipped": 0},
1313
"selectedContracts": {"argv": 43, "process": 14},
1414
"pythonRunnerSelfTests": 13,
1515
"officialOpenSpec": {"version": "1.14.1", "strictChangesPassed": 10, "failed": 0},
1616
"changes": {
1717
"C10": "FOUNDATION_IMPLEMENTED_ON_NAMED_FEATURE; FINAL_GATE_OPEN",
1818
"C01": "CORE_AND_NULL_STRING_EDGE_IMPLEMENTED; MULTIBRANCH_REVIEW_PENDING",
19-
"C02": "CORE_IMPLEMENTED; CLEANUP_FAULT_INJECTION_AND_MULTIBRANCH_REVIEW_PENDING",
19+
"C02": "CORE_AND_STOP_DESTROY_FAULT_INJECTION_IMPLEMENTED; CANCEL_RACE_AND_MULTIBRANCH_REVIEW_PENDING",
2020
"C03": "NOT_STARTED",
2121
"C04": "NOT_STARTED",
2222
"C05": "NOT_STARTED",

‎src/main/java/io/github/easy4j/opencli/core/OpenCliExecutionDetails.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ public enum CleanupState { NOT_STARTED, ROOT_EXIT_CONFIRMED, UNCONFIRMED }
2020
private final CleanupState cleanupState;
2121
private final boolean processStarted;
2222
private final boolean streamsDrained;
23+
/** A watchdog or process cleanup operation threw; later cleanup may still confirm root exit. */
24+
private final boolean cleanupOperationFailed;
2325
private final long stdoutCapturedBytes;
2426
private final long stdoutObservedBytes;
2527
private final boolean stdoutTruncated;

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

Lines changed: 76 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,16 @@
3030
* compatibility with the earlier low-level RunSession API.
3131
*/
3232
public final class SubprocessExecutionSupport {
33+
@FunctionalInterface
34+
interface ProcessStarter {
35+
Process start(ProcessBuilder builder) throws IOException;
36+
}
37+
38+
@FunctionalInterface
39+
interface WatchdogFactory {
40+
ExecuteWatchdog create(long timeoutMillis);
41+
}
42+
3343
public static final long WAIT_GRACE_MILLIS = 5_000L;
3444
public static final int DEFAULT_STDOUT_LIMIT = 8 * 1024 * 1024;
3545
public static final int DEFAULT_STDERR_LIMIT = 2 * 1024 * 1024;
@@ -80,14 +90,23 @@ public static RunSession execute(ExecutionRequest request) throws IOException, I
8090
public static final class Runtime {
8191
private final int maxConcurrentExecutions;
8292
private final Semaphore permits;
93+
private final ProcessStarter processStarter;
94+
private final WatchdogFactory watchdogFactory;
8395
private volatile boolean quarantined;
8496

8597
public Runtime(int maxConcurrent) {
98+
this(maxConcurrent, ProcessBuilder::start, timeoutMillis -> ExecuteWatchdog.builder()
99+
.setTimeout(Duration.ofMillis(timeoutMillis)).get());
100+
}
101+
102+
Runtime(int maxConcurrent, ProcessStarter processStarter, WatchdogFactory watchdogFactory) {
86103
if (maxConcurrent < 0) {
87104
throw new IllegalArgumentException("maxConcurrentExecutions must not be negative");
88105
}
89106
maxConcurrentExecutions = maxConcurrent == 0 ? DEFAULT_MAX_CONCURRENT : maxConcurrent;
90107
permits = new Semaphore(maxConcurrentExecutions, true);
108+
this.processStarter = Objects.requireNonNull(processStarter, "processStarter");
109+
this.watchdogFactory = Objects.requireNonNull(watchdogFactory, "watchdogFactory");
91110
}
92111

93112
public int getMaxConcurrentExecutions() { return maxConcurrentExecutions; }
@@ -101,12 +120,12 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
101120
Process process = null;
102121
Reader stdoutReader = null;
103122
Reader stderrReader = null;
104-
ExecuteWatchdog watchdog = ExecuteWatchdog.builder()
105-
.setTimeout(Duration.ofMillis(request.timeoutMillis)).get();
123+
ExecuteWatchdog watchdog = watchdogFactory.create(request.timeoutMillis);
106124
TerminationReason reason = null;
107125
IOException ioFailure = null;
108126
boolean acquired = false;
109127
boolean interrupted = false;
128+
boolean cleanupOperationFailed = false;
110129
long queueWaitMillis = 0L;
111130
try {
112131
while (!acquired && reason == null) {
@@ -146,15 +165,15 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
146165
builder.environment().clear();
147166
builder.environment().putAll(request.environment);
148167
}
149-
process = builder.start();
168+
process = processStarter.start(builder);
150169
process.getOutputStream().close();
151170
stdoutReader = new Reader(process.getInputStream(), out, "opencli-stdout");
152171
stderrReader = new Reader(process.getErrorStream(), err, "opencli-stderr");
153172
stdoutReader.start();
154173
stderrReader.start();
155174
long remaining = remaining(request.submittedAtNanos, budget);
156-
watchdog = ExecuteWatchdog.builder().setTimeout(Duration.ofMillis(
157-
Math.max(1L, TimeUnit.NANOSECONDS.toMillis(Math.max(0L, remaining))))).get();
175+
watchdog = watchdogFactory.create(
176+
Math.max(1L, TimeUnit.NANOSECONDS.toMillis(Math.max(0L, remaining))));
158177
watchdog.start(process);
159178
while (reason == null) {
160179
if (out.isTruncated() || err.isTruncated()) {
@@ -183,38 +202,53 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
183202
ioFailure = ex;
184203
reason = process == null ? TerminationReason.SPAWN_FAILED : TerminationReason.IO_FAILURE;
185204
} finally {
186-
watchdog.stop();
187-
long cleanupStart = System.nanoTime();
188-
long cleanupBudget = nanos(request.cleanupGraceMillis, "cleanupGraceMillis");
189-
if (process != null) {
190-
if (process.isAlive()) { process.destroy(); }
191-
boolean forceSent = false;
192-
while (remaining(cleanupStart, cleanupBudget) > 0
193-
&& (process.isAlive() || alive(stdoutReader) || alive(stderrReader))) {
194-
if (Thread.interrupted()) { interrupted = true; }
195-
if (process.isAlive() && !forceSent
196-
&& System.nanoTime() - cleanupStart >= Math.min(TimeUnit.MILLISECONDS.toNanos(100L), cleanupBudget / 2)) {
197-
process.destroyForcibly();
198-
forceSent = true;
205+
try {
206+
try {
207+
watchdog.stop();
208+
} catch (RuntimeException ex) {
209+
cleanupOperationFailed = true;
210+
}
211+
long cleanupStart = System.nanoTime();
212+
long cleanupBudget = nanos(request.cleanupGraceMillis, "cleanupGraceMillis");
213+
if (Objects.nonNull(process)) {
214+
boolean forceSent = false;
215+
if (process.isAlive()) {
216+
try {
217+
process.destroy();
218+
} catch (RuntimeException ex) {
219+
cleanupOperationFailed = true;
220+
forceSent = true;
221+
if (!tryForceStop(process)) { cleanupOperationFailed = true; }
222+
}
199223
}
200-
try {
201-
TimeUnit.NANOSECONDS.sleep(Math.min(POLL_NANOS,
202-
Math.max(1L, remaining(cleanupStart, cleanupBudget))));
203-
} catch (InterruptedException ex) {
204-
interrupted = true;
224+
while (remaining(cleanupStart, cleanupBudget) > 0
225+
&& (process.isAlive() || alive(stdoutReader) || alive(stderrReader))) {
226+
if (Thread.interrupted()) { interrupted = true; }
227+
if (process.isAlive() && !forceSent
228+
&& System.nanoTime() - cleanupStart >= Math.min(TimeUnit.MILLISECONDS.toNanos(100L), cleanupBudget / 2)) {
229+
if (!tryForceStop(process)) { cleanupOperationFailed = true; }
230+
forceSent = true;
231+
}
232+
try {
233+
TimeUnit.NANOSECONDS.sleep(Math.min(POLL_NANOS,
234+
Math.max(1L, remaining(cleanupStart, cleanupBudget))));
235+
} catch (InterruptedException ex) {
236+
interrupted = true;
237+
}
238+
}
239+
if (process.isAlive() && !tryForceStop(process)) { cleanupOperationFailed = true; }
240+
if (process.isAlive() || alive(stdoutReader) || alive(stderrReader)) {
241+
// A fixed runtime cannot accumulate unlimited uncertain children/readers.
242+
quarantined = true;
243+
if (reason == TerminationReason.PROCESS_EXIT) { reason = TerminationReason.CLEANUP_UNCONFIRMED; }
205244
}
206245
}
207-
if (process.isAlive()) { process.destroyForcibly(); }
208-
if (process.isAlive() || alive(stdoutReader) || alive(stderrReader)) {
209-
// A fixed runtime cannot accumulate unlimited uncertain children/readers.
210-
quarantined = true;
211-
if (reason == TerminationReason.PROCESS_EXIT) { reason = TerminationReason.CLEANUP_UNCONFIRMED; }
212-
}
246+
} finally {
247+
out.freeze();
248+
err.freeze();
249+
if (acquired) { permits.release(); }
250+
if (interrupted) { Thread.currentThread().interrupt(); }
213251
}
214-
out.freeze();
215-
err.freeze();
216-
if (acquired) { permits.release(); }
217-
if (interrupted) { Thread.currentThread().interrupt(); }
218252
}
219253
if (reason == TerminationReason.PROCESS_EXIT && (out.isTruncated() || err.isTruncated())) {
220254
reason = TerminationReason.OUTPUT_LIMIT;
@@ -233,6 +267,7 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
233267
.cleanupState(process == null ? CleanupState.NOT_STARTED
234268
: process.isAlive() ? CleanupState.UNCONFIRMED : CleanupState.ROOT_EXIT_CONFIRMED)
235269
.processStarted(process != null).streamsDrained(!alive(stdoutReader) && !alive(stderrReader))
270+
.cleanupOperationFailed(cleanupOperationFailed)
236271
.stdoutCapturedBytes(out.size()).stdoutObservedBytes(out.observed()).stdoutTruncated(out.isTruncated())
237272
.stderrCapturedBytes(err.size()).stderrObservedBytes(err.observed()).stderrTruncated(err.isTruncated())
238273
.elapsedMillis(elapsedMillis(request.submittedAtNanos)).queueWaitMillis(queueWaitMillis)
@@ -244,6 +279,14 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
244279
}
245280

246281
private static boolean alive(Thread thread) { return thread != null && thread.isAlive(); }
282+
private static boolean tryForceStop(Process process) {
283+
try {
284+
process.destroyForcibly();
285+
return true;
286+
} catch (RuntimeException ex) {
287+
return false;
288+
}
289+
}
247290
private static long remaining(long start, long budget) { return budget - (System.nanoTime() - start); }
248291
private static long elapsedMillis(long start) { return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); }
249292

0 commit comments

Comments
 (0)