target, String flag, Boolean enabled) {
if (Boolean.TRUE.equals(enabled)) {
diff --git a/src/main/java/io/github/easy4j/opencli/core/OpenCliCancellationToken.java b/src/main/java/io/github/easy4j/opencli/core/OpenCliCancellationToken.java
new file mode 100644
index 0000000..c90d2db
--- /dev/null
+++ b/src/main/java/io/github/easy4j/opencli/core/OpenCliCancellationToken.java
@@ -0,0 +1,14 @@
+package io.github.easy4j.opencli.core;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/** Cooperative cancellation for one local invocation; cancellation never affects another invocation. */
+public final class OpenCliCancellationToken {
+ private final AtomicBoolean cancelled = new AtomicBoolean();
+
+ /** Request cancellation. This operation is idempotent. */
+ public void cancel() { cancelled.set(true); }
+
+ /** @return whether cancellation has been requested */
+ public boolean isCancelled() { return cancelled.get(); }
+}
diff --git a/src/main/java/io/github/easy4j/opencli/core/OpenCliExecutionDetails.java b/src/main/java/io/github/easy4j/opencli/core/OpenCliExecutionDetails.java
new file mode 100644
index 0000000..6da55ff
--- /dev/null
+++ b/src/main/java/io/github/easy4j/opencli/core/OpenCliExecutionDetails.java
@@ -0,0 +1,35 @@
+package io.github.easy4j.opencli.core;
+
+import lombok.Builder;
+import lombok.Getter;
+
+/** Immutable execution evidence. Observed byte counts describe bytes read, not bytes produced remotely. */
+@Getter
+@Builder
+public final class OpenCliExecutionDetails {
+ /** First terminal condition selected by the invocation owner. */
+ public enum TerminationReason {
+ PROCESS_EXIT, QUEUE_TIMEOUT, EXECUTION_TIMEOUT, OUTPUT_LIMIT,
+ CANCELLED, SPAWN_FAILED, IO_FAILURE, CLEANUP_UNCONFIRMED, RUNTIME_UNAVAILABLE
+ }
+
+ /** Confirmation concerns the directly owned child, not an arbitrary process tree. */
+ public enum CleanupState { NOT_STARTED, ROOT_EXIT_CONFIRMED, UNCONFIRMED }
+
+ private final TerminationReason terminationReason;
+ private final CleanupState cleanupState;
+ private final boolean processStarted;
+ private final boolean streamsDrained;
+ /** A watchdog or process cleanup operation threw; later cleanup may still confirm root exit. */
+ private final boolean cleanupOperationFailed;
+ private final long stdoutCapturedBytes;
+ private final long stdoutObservedBytes;
+ private final boolean stdoutTruncated;
+ private final long stderrCapturedBytes;
+ private final long stderrObservedBytes;
+ private final boolean stderrTruncated;
+ private final long elapsedMillis;
+ private final long queueWaitMillis;
+ /** This portable backend does not claim ownership/termination of detached daemon descendants. */
+ private final boolean descendantsExitConfirmed;
+}
diff --git a/src/main/java/io/github/easy4j/opencli/core/OpenCliExecutor.java b/src/main/java/io/github/easy4j/opencli/core/OpenCliExecutor.java
index 4cd04e4..9b853ae 100644
--- a/src/main/java/io/github/easy4j/opencli/core/OpenCliExecutor.java
+++ b/src/main/java/io/github/easy4j/opencli/core/OpenCliExecutor.java
@@ -2,128 +2,101 @@
import io.github.easy4j.opencli.OpenCliExecutionTarget;
import io.github.easy4j.opencli.OpenCliProperties;
+import io.github.easy4j.opencli.core.OpenCliExecutionDetails.TerminationReason;
+import io.github.easy4j.opencli.core.support.SubprocessExecutionSupport;
import io.github.easy4j.opencli.exception.OpenCliException;
import io.github.easy4j.opencli.exception.OpenCliExecutableFailureException;
import io.github.easy4j.opencli.exception.OpenCliNonZeroExitException;
import io.github.easy4j.opencli.exception.OpenCliTimeoutException;
-import io.github.easy4j.opencli.parser.OpenCliParsedFields;
import io.github.easy4j.opencli.remote.OpenCliArgvToCollectParser;
import io.github.easy4j.opencli.remote.OpenCliCollectRequest;
import io.github.easy4j.opencli.remote.OpenCliRemoteAgentHttpClient;
-import io.github.easy4j.opencli.core.support.SubprocessExecutionSupport;
import io.github.easy4j.opencli.util.OpenCliStrings;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
+import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Objects;
-import java.util.UUID;
import lombok.Getter;
-import lombok.extern.slf4j.Slf4j;
import org.apache.commons.exec.CommandLine;
-import org.apache.commons.exec.DefaultExecuteResultHandler;
-import org.apache.commons.exec.ExecuteException;
-import org.apache.commons.exec.ExecuteWatchdog;
/**
- * 基于 Apache Commons Exec 的 OpenCLI 子进程执行封装。
- *
- * {@link #invoke(List)} 接受的参数为「紧跟可执行名之后」的完整 token 列表,形如
- * {@code [adapter, subcommand, ...]};本地模式下会自动拼接 {@link OpenCliProperties} 的
- * {@code leadingArguments}。
- *
- *
- * 当 {@link OpenCliProperties} 的 {@code executionTarget} 为
- * {@link OpenCliExecutionTarget#REMOTE_AGENT_HTTP} 时,
- * 通过 {@link OpenCliRemoteAgentHttpClient} 调用远端 {@code POST /collect};此时 {@code leadingArguments} 不参与请求,
- * argv 会被解析为 {@link OpenCliCollectRequest}(与 opencli-admin {@code agent_server} 契约一致)。
- *
- */
-@Slf4j
-@Getter/**
-
- * OpenCLI subprocess execution wrapper based on Apache Commons Exec.
- *
- * {@link #invoke(List)} accepts a token list that follows the executable name,
- * typically {@code [adapter, subcommand, ...]}. In local mode, {@link OpenCliProperties}
- * {@code leadingArguments} are automatically prepended.
- *
- * When {@link OpenCliProperties#getExecutionTarget()} is
- * {@link OpenCliExecutionTarget#REMOTE_AGENT_HTTP}, the invocation is forwarded to a
- * remote Agent via {@link OpenCliRemoteAgentHttpClient#collect(OpenCliCollectRequest)}.
-
+ * Literal-argv executor with a stable capacity owner, total local deadline and
+ * bounded output. Existing synchronous entry points are retained. Raw HTTP
+ * collect remains a separate legacy protocol, not a lossless process transport.
*
-
* @author Loong Wan
-
* @since 3.0.0
-
*/
-
+@Getter
public class OpenCliExecutor implements AutoCloseable {
-
private final OpenCliProperties properties;
-
- /**
- * 懒加载,仅远程模式使用。
- */
+ private final OpenCliProcessRuntime processRuntime;
private volatile OpenCliRemoteAgentHttpClient remoteAgentHttpClient;
- /**
- * @param properties 运行时配置,不得为 null
- */
+ /** @param properties configuration; process capacity is captured once */
public OpenCliExecutor(OpenCliProperties properties) {
- this.properties = Objects.requireNonNull(properties, "properties");
- SubprocessExecutionSupport.configureMaxConcurrentExecutions(properties.getMaxConcurrentExecutions());
+ this(properties, new OpenCliProcessRuntime(Objects.requireNonNull(properties, "properties")
+ .getMaxConcurrentExecutions()));
}
/**
- * 执行 {@code opencli ...} 完整 argv(不含可执行文件本身)。
- *
- * @param adapterAndRest 至少包含 adapter 名,后续为子命令与 flag;不得为 null
- * @return 包含成功标记的执行结果
+ * @param properties configuration
+ * @param processRuntime an explicitly shared, stable local capacity owner
*/
+ public OpenCliExecutor(OpenCliProperties properties, OpenCliProcessRuntime processRuntime) {
+ this.properties = Objects.requireNonNull(properties, "properties");
+ this.processRuntime = Objects.requireNonNull(processRuntime, "processRuntime");
+ }
+
+ /** @param adapterAndRest command and literal values @return execution result */
public OpenCliResult invoke(List adapterAndRest) {
- Objects.requireNonNull(adapterAndRest, "adapterAndRest");
- if (properties.getExecutionTarget() == OpenCliExecutionTarget.REMOTE_AGENT_HTTP) {
- log.debug("OpenCLI invoke remote agent argvSize={}", adapterAndRest.size());
- OpenCliCollectRequest req =
- OpenCliArgvToCollectParser.parse(
- adapterAndRest,
- properties.getRemoteOutputFormat(),
- properties.getRemoteCollectMode(),
- properties.getRemoteCdpEndpoint());
- return remoteAgent().collect(req);
- }
- log.debug("OpenCLI invoke local argvSize={}", adapterAndRest.size());
- CommandLine cmd = buildCommandLine(adapterAndRest);
- return run(cmd);
+ return invokeInternal(adapterAndRest, new OpenCliCancellationToken(), false);
}
/**
- * @return 远程 Agent HTTP 客户端(懒加载)
- */
- /**
- * 释放远程传输资源:仅当 REMOTE_AGENT_HTTP 模式下已懒加载 HTTP 客户端时
- * 生效(实例级 shutdown,不影响 JVM 中其它 Unirest 使用方);本地模式为
- * 空操作。close 之后远程调用不可用,本地调用不受影响。
+ * Cancellable local invocation. The legacy HTTP protocol does not claim a
+ * cancellable remote process; explicit tokens are rejected in remote mode.
+ *
+ * @param adapterAndRest command and literal values
+ * @param cancellationToken cancellation for this invocation only
+ * @return execution result
*/
- @Override
- public void close() {
- OpenCliRemoteAgentHttpClient client = remoteAgentHttpClient;
- if (Objects.nonNull(client)) {
- client.close();
+ public OpenCliResult invoke(List adapterAndRest, OpenCliCancellationToken cancellationToken) {
+ return invokeInternal(adapterAndRest, Objects.requireNonNull(cancellationToken, "cancellationToken"), true);
+ }
+
+ private OpenCliResult invokeInternal(List adapterAndRest,
+ OpenCliCancellationToken cancellationToken, boolean explicitCancellation) {
+ long submittedAtNanos = System.nanoTime();
+ long timeoutMillis = properties.getCommandTimeoutMillis();
+ List tokens = OpenCliArgSupport.snapshotValues(adapterAndRest, "adapterAndRest");
+ if (tokens.isEmpty()) {
+ throw new IllegalArgumentException("adapterAndRest must contain at least the command identifier");
+ }
+ if (OpenCliStrings.isBlank(tokens.get(0))) {
+ throw new IllegalArgumentException("adapterAndRest[0] command identifier must not be blank");
}
+ if (properties.getExecutionTarget() == OpenCliExecutionTarget.REMOTE_AGENT_HTTP) {
+ if (explicitCancellation) {
+ throw new UnsupportedOperationException("Explicit process cancellation is local-only for legacy collect");
+ }
+ OpenCliCollectRequest req = OpenCliArgvToCollectParser.parse(tokens,
+ properties.getRemoteOutputFormat(), properties.getRemoteCollectMode(), properties.getRemoteCdpEndpoint());
+ return remoteAgent().collect(req);
+ }
+ CommandLine commandLine = buildCommandLine(tokens);
+ return run(commandLine, timeoutMillis, submittedAtNanos, cancellationToken);
}
private OpenCliRemoteAgentHttpClient remoteAgent() {
- if (Objects.isNull(remoteAgentHttpClient)) {
+ if (remoteAgentHttpClient == null) {
synchronized (this) {
- if (Objects.isNull(remoteAgentHttpClient)) {
+ if (remoteAgentHttpClient == null) {
remoteAgentHttpClient = new OpenCliRemoteAgentHttpClient(properties);
}
}
@@ -131,59 +104,44 @@ private OpenCliRemoteAgentHttpClient remoteAgent() {
return remoteAgentHttpClient;
}
- /**
- * 便捷重载:可变参数形式。
- *
- * @param adapterAndRest adapter 及后续 CLI token
- * @return 执行结果
- */
- public OpenCliResult invoke(String... adapterAndRest) {
- List list = new ArrayList<>();
- if (Objects.nonNull(adapterAndRest)) {
- for (String s : adapterAndRest) {
- if (OpenCliStrings.isNotBlank(s)) {
- list.add(s.trim());
- }
- }
+ /** Close only the lazily created remote transport; local invocations own their processes. */
+ @Override
+ public void close() {
+ OpenCliRemoteAgentHttpClient client = remoteAgentHttpClient;
+ if (Objects.nonNull(client)) {
+ client.close();
}
- return invoke(list);
}
- /**
- * 拼装 {@link CommandLine}:executable + leading + tokens。
- */
- private CommandLine buildCommandLine(List adapterAndRest) {
- if (adapterAndRest.isEmpty()) {
- throw new IllegalArgumentException("adapterAndRest must contain at least the adapter id");
- }
- String exe = properties.getExecutable();
- if (OpenCliStrings.isBlank(exe)) {
+ /** @param adapterAndRest command and literal values @return execution result */
+ public OpenCliResult invoke(String... adapterAndRest) {
+ Objects.requireNonNull(adapterAndRest, "adapterAndRest");
+ return invoke(Arrays.asList(adapterAndRest));
+ }
+
+ private CommandLine buildCommandLine(List tokens) {
+ String executable = properties.getExecutable();
+ if (OpenCliStrings.isBlank(executable)) {
throw new IllegalStateException("opencli.executable must not be blank");
}
- CommandLine cmd = new CommandLine(exe.trim());
- appendCleanArgs(cmd, properties.getLeadingArguments());
- appendCleanArgs(cmd, adapterAndRest);
+ String normalized = executable.trim();
+ String lower = normalized.toLowerCase(Locale.ROOT);
+ if (System.getProperty("os.name").startsWith("Windows")
+ && (lower.endsWith(".cmd") || lower.endsWith(".bat"))) {
+ throw new UnsupportedOperationException("Use a native node executable plus the CLI JavaScript path; batch shims are not literal argv transports");
+ }
+ CommandLine cmd = new LiteralCommandLine(normalized);
+ appendLiteralArgs(cmd, properties.getLeadingArguments(), "leadingArguments");
+ appendLiteralArgs(cmd, tokens, "adapterAndRest");
return cmd;
}
- private static void appendCleanArgs(CommandLine cmd, List args) {
- if (Objects.isNull(args) || args.isEmpty()) {
- return;
- }
- for (String a : args) {
- if (OpenCliStrings.isNotBlank(a)) {
- cmd.addArgument(a.trim(), false);
- }
- }
+ private static void appendLiteralArgs(CommandLine cmd, List values, String field) {
+ if (values == null) { return; }
+ for (String value : OpenCliArgSupport.snapshotValues(values, field)) { cmd.addArgument(value, false); }
}
- /**
- * 将 {@code --key=value} 以句柄安全形式追加(含空格时由 Commons Exec 处理)。
- *
- * @param cmd 命令行
- * @param key 必须以 {@code --} 开头
- * @param value 非空值
- */
+ /** Legacy explicit-quoting helper; not used by the literal process path. */
public static void appendQuotedKeyValue(CommandLine cmd, String key, String value) {
Objects.requireNonNull(key, "key");
Objects.requireNonNull(value, "value");
@@ -194,159 +152,75 @@ public static void appendQuotedKeyValue(CommandLine cmd, String key, String valu
cmd.addArgument(prefix + "=" + value, true);
}
- private OpenCliResult run(CommandLine commandLine) {
- long timeoutMs = properties.getCommandTimeoutMillis();
- if (timeoutMs <= 0) {
+ private OpenCliResult run(CommandLine commandLine, long timeoutMillis, long submittedAtNanos,
+ OpenCliCancellationToken cancellationToken) {
+ if (timeoutMillis <= 0) {
throw new IllegalStateException("opencli.command-timeout-millis must be positive");
}
-
- File workingDirectory = resolveWorkingDirectory();
- Map environment = buildEnvironment();
- SubprocessExecutionSupport.ExecutionRequest request =
- new SubprocessExecutionSupport.ExecutionRequest(
- commandLine, workingDirectory, environment, timeoutMs,
- properties.getMaxOutputBytes());
-
- String correlationId = UUID.randomUUID().toString();
+ SubprocessExecutionSupport.ExecutionRequest request = new SubprocessExecutionSupport.ExecutionRequest(
+ commandLine, resolveWorkingDirectory(), buildEnvironment(), timeoutMillis,
+ effectiveCaptureLimit(properties.getMaxStdoutBytes()),
+ effectiveCaptureLimit(properties.getMaxStderrBytes()), properties.getCleanupGraceMillis(),
+ submittedAtNanos, cancellationToken);
try {
- SubprocessExecutionSupport.RunSession session = SubprocessExecutionSupport.execute(request);
- return completeAfterWait(
- correlationId,
- timeoutMs,
- session.getStdout(),
- session.getStderr(),
- session.getHandler(),
- session.getWatchdog(),
- session.isWaitTimedOut());
- } catch (IOException e) {
- log.warn("OpenCLI spawn failed correlationId={}", correlationId);
- throw new OpenCliExecutableFailureException(
- "OpenCLI could not be started correlationId=" + correlationId, null);
- } catch (InterruptedException e) {
+ return complete(processRuntime.execute(request));
+ } catch (IOException ex) {
+ throw new OpenCliExecutableFailureException("OpenCLI process could not be started", null);
+ } catch (InterruptedException ex) {
Thread.currentThread().interrupt();
- log.warn("OpenCLI interrupted correlationId={}", correlationId);
- throw new OpenCliException("Interrupted while awaiting OpenCLI subprocess correlationId=" + correlationId, null, null);
+ throw new OpenCliException("Interrupted while awaiting OpenCLI subprocess", ex, null);
}
}
- private File resolveWorkingDirectory() {
- String wdProperty = properties.getWorkingDirectory();
- if (OpenCliStrings.isNotBlank(wdProperty)) {
- File wd = new File(wdProperty.trim());
- if (!wd.isDirectory()) {
- throw new OpenCliExecutableFailureException(
- "opencli.working-directory is not an existing directory", null);
- }
- return wd;
- }
- return null;
+ private int effectiveCaptureLimit(int streamLimit) {
+ long legacyLimit = properties.getMaxOutputBytes();
+ return legacyLimit > 0 ? (int) Math.min(streamLimit, legacyLimit) : streamLimit;
}
- private OpenCliResult completeAfterWait(
- String correlationId,
- long timeoutMs,
- SubprocessExecutionSupport.BoundedOutputStream out,
- SubprocessExecutionSupport.BoundedOutputStream err,
- DefaultExecuteResultHandler handler,
- ExecuteWatchdog watchdog,
- boolean waitTimedOut) {
- String stdoutStr = new String(out.toByteArray(), StandardCharsets.UTF_8);
- String stderrStr = new String(err.toByteArray(), StandardCharsets.UTF_8);
- if (out.isOverflowed()) {
- log.warn("OpenCLI stdout truncated at maxOutputBytes={}", properties.getMaxOutputBytes());
- stdoutStr = stdoutStr + "\n[opencli-java-sdk] stdout truncated at maxOutputBytes="
- + properties.getMaxOutputBytes();
- }
- if (err.isOverflowed()) {
- log.warn("OpenCLI stderr truncated at maxOutputBytes={}", properties.getMaxOutputBytes());
- stderrStr = stderrStr + "\n[opencli-java-sdk] stderr truncated at maxOutputBytes="
- + properties.getMaxOutputBytes();
- }
- OpenCliParsedFields parsed = OpenCliOutputParser.parseBestEffort(stdoutStr, stderrStr);
-
- if (waitTimedOut || watchdog.killedProcess()) {
- log.warn("OpenCLI timed out correlationId={} timeoutMs={}", correlationId, timeoutMs);
- OpenCliResult partial = snapshot(stdoutStr, stderrStr, readExitQuietly(handler), parsed);
- throw new OpenCliTimeoutException(
- "OpenCLI timed out after " + timeoutMs + " ms correlationId=" + correlationId, partial);
- }
-
- Exception asyncFailure = handler.getException();
- if (asyncFailure instanceof ExecuteException) {
- ExecuteException ex = (ExecuteException) asyncFailure;
- log.warn("OpenCLI failed correlationId={} exitCode={}", correlationId, ex.getExitValue());
- OpenCliResult failed = snapshot(stdoutStr, stderrStr, normalizeExitValue(ex.getExitValue()), parsed);
- throw new OpenCliNonZeroExitException(
- "OpenCLI failed (exitCode=" + ex.getExitValue() + ") correlationId=" + correlationId, failed);
- }
- if (Objects.nonNull(asyncFailure)) {
- log.error("OpenCLI async failure correlationId={}", correlationId);
- OpenCliResult snapshot = snapshot(stdoutStr, stderrStr, readExitQuietly(handler), parsed);
- throw new OpenCliException(
- "OpenCLI async failure correlationId=" + correlationId, null, snapshot);
- }
-
- final int exit;
- try {
- exit = handler.getExitValue();
- } catch (IllegalStateException e) {
- throw new OpenCliException(
- "OpenCLI completed without observable exit code correlationId=" + correlationId,
- null,
- snapshot(stdoutStr, stderrStr, null, parsed));
- }
+ private OpenCliResult complete(SubprocessExecutionSupport.RunSession session) {
+ String stdout = new String(session.getStdout().toByteArray(), StandardCharsets.UTF_8);
+ String stderr = new String(session.getStderr().toByteArray(), StandardCharsets.UTF_8);
+ OpenCliExecutionDetails details = session.getExecutionDetails();
+ TerminationReason reason = details.getTerminationReason();
+ Integer exit = session.getObservedExitCode();
+ boolean success = reason == TerminationReason.PROCESS_EXIT && Integer.valueOf(0).equals(exit)
+ && details.isStreamsDrained();
+ OpenCliResult result = OpenCliResult.builder().stdout(stdout).stderr(stderr).exitCode(exit)
+ .success(success).parsed(OpenCliOutputParser.parseBestEffort(stdout, stderr))
+ .executionDetails(details).build();
+ if (success) { return result; }
+ if (reason == TerminationReason.QUEUE_TIMEOUT || reason == TerminationReason.EXECUTION_TIMEOUT) {
+ throw new OpenCliTimeoutException("OpenCLI deadline exceeded: " + reason, result);
+ }
+ if (reason == TerminationReason.SPAWN_FAILED) {
+ throw new OpenCliExecutableFailureException("OpenCLI process could not be started", null, result);
+ }
+ if (reason == TerminationReason.PROCESS_EXIT && exit != null && exit != 0) {
+ throw new OpenCliNonZeroExitException("OpenCLI returned nonzero exitCode=" + exit, result);
+ }
+ // Native I/O errors may include executable paths or other invocation data.
+ throw new OpenCliException("OpenCLI execution ended: " + reason, result);
+ }
- if (exit != 0) {
- log.warn("OpenCLI non-zero exit correlationId={} exitCode={}", correlationId, exit);
- OpenCliResult failed = snapshot(stdoutStr, stderrStr, exit, parsed);
- throw new OpenCliNonZeroExitException(
- "OpenCLI non-zero exit (exitCode=" + exit + ") correlationId=" + correlationId, failed);
+ private File resolveWorkingDirectory() {
+ String value = properties.getWorkingDirectory();
+ if (OpenCliStrings.isNotBlank(value)) {
+ File directory = new File(value.trim());
+ if (!directory.isDirectory()) {
+ throw new OpenCliExecutableFailureException("opencli.working-directory is not an existing directory", null);
+ }
+ return directory;
}
-
- return OpenCliResult.builder()
- .stdout(stdoutStr)
- .stderr(stderrStr)
- .exitCode(exit)
- .success(true)
- .parsed(parsed)
- .build();
+ return null;
}
private Map buildEnvironment() {
Map env = new HashMap<>(System.getenv());
- if (Objects.nonNull(properties.getEnvironment())) {
- for (Map.Entry e : properties.getEnvironment().entrySet()) {
- if (Objects.nonNull(e.getKey()) && Objects.nonNull(e.getValue())) {
- env.put(e.getKey(), e.getValue());
- }
+ if (properties.getEnvironment() != null) {
+ for (Map.Entry entry : new HashMap<>(properties.getEnvironment()).entrySet()) {
+ if (entry.getKey() != null && entry.getValue() != null) { env.put(entry.getKey(), entry.getValue()); }
}
}
return env;
}
-
- private static Integer readExitQuietly(DefaultExecuteResultHandler handler) {
- try {
- return normalizeExitValue(handler.getExitValue());
- } catch (IllegalStateException e) {
- return null;
- }
- }
-
- private static Integer normalizeExitValue(int raw) {
- if (raw == org.apache.commons.exec.Executor.INVALID_EXITVALUE) {
- return null;
- }
- return raw;
- }
-
- private static OpenCliResult snapshot(
- String stdoutStr, String stderrStr, Integer exitCode, OpenCliParsedFields parsed) {
- return OpenCliResult.builder()
- .stdout(Objects.isNull(stdoutStr) ? "" : stdoutStr)
- .stderr(Objects.isNull(stderrStr) ? "" : stderrStr)
- .exitCode(exitCode)
- .success(false)
- .parsed(parsed)
- .build();
- }
}
diff --git a/src/main/java/io/github/easy4j/opencli/core/OpenCliOption.java b/src/main/java/io/github/easy4j/opencli/core/OpenCliOption.java
new file mode 100644
index 0000000..b6ca790
--- /dev/null
+++ b/src/main/java/io/github/easy4j/opencli/core/OpenCliOption.java
@@ -0,0 +1,73 @@
+package io.github.easy4j.opencli.core;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * One immutable, schema-checked option occurrence. Preserve occurrence ordering
+ * by adding these to a request builder rather than using a Map for repeated flags.
+ *
+ * @author Loong Wan
+ * @since 3.0.0
+ */
+public final class OpenCliOption {
+ private final OpenCliOptionSchema schema;
+ private final String value;
+ private final boolean negated;
+
+ private OpenCliOption(OpenCliOptionSchema schema, String value, boolean negated) {
+ this.schema = schema;
+ this.value = value;
+ this.negated = negated;
+ }
+
+ /**
+ * @param schema a valued-option definition
+ * @param value non-null value; false is the literal value "false", not absence
+ * @return an occurrence capturing the value immediately
+ */
+ public static OpenCliOption value(OpenCliOptionSchema schema, Object value) {
+ Objects.requireNonNull(schema, "schema");
+ Objects.requireNonNull(value, "value");
+ if (schema.getKind() != OpenCliOptionSchema.Kind.VALUE) {
+ throw new IllegalArgumentException("A flag schema cannot consume a value");
+ }
+ return new OpenCliOption(schema, OpenCliArgSupport.stringValue(value, "option value"), false);
+ }
+
+ /** @param schema a flag definition @return explicit positive presence */
+ public static OpenCliOption present(OpenCliOptionSchema schema) {
+ Objects.requireNonNull(schema, "schema");
+ if (schema.getKind() == OpenCliOptionSchema.Kind.VALUE) {
+ throw new IllegalArgumentException("A valued option requires a value");
+ }
+ return new OpenCliOption(schema, null, false);
+ }
+
+ /** @param schema a negatable flag definition @return an explicit negative flag */
+ public static OpenCliOption negated(OpenCliOptionSchema schema) {
+ Objects.requireNonNull(schema, "schema");
+ if (schema.getKind() != OpenCliOptionSchema.Kind.NEGATABLE_FLAG) {
+ throw new IllegalArgumentException("This option schema does not declare negation");
+ }
+ return new OpenCliOption(schema, null, true);
+ }
+
+ /** @return immutable input definition */
+ public OpenCliOptionSchema getSchema() { return schema; }
+
+ /** @return the captured value, or null for a flag */
+ public String getValue() { return value; }
+
+ /** @return whether this is explicit negative presence */
+ public boolean isNegated() { return negated; }
+
+ /** @return immutable literal tokens; no quoting or trimming is applied */
+ public List toTokens() {
+ String flag = negated ? "--no-" + schema.getName().substring(2) : schema.getName();
+ return value == null ? Collections.singletonList(flag)
+ : Collections.unmodifiableList(Arrays.asList(flag, value));
+ }
+}
diff --git a/src/main/java/io/github/easy4j/opencli/core/OpenCliOptionSchema.java b/src/main/java/io/github/easy4j/opencli/core/OpenCliOptionSchema.java
new file mode 100644
index 0000000..3289973
--- /dev/null
+++ b/src/main/java/io/github/easy4j/opencli/core/OpenCliOptionSchema.java
@@ -0,0 +1,73 @@
+package io.github.easy4j.opencli.core;
+
+import java.util.Objects;
+import java.util.regex.Pattern;
+
+/**
+ * Explicit option input semantics. Definitions come from a known command contract,
+ * not guesses about a raw argument vector. This is not an output schema.
+ *
+ * @author Loong Wan
+ * @since 3.0.0
+ */
+public final class OpenCliOptionSchema {
+ /** Input arity and negation semantics. */
+ public enum Kind { FLAG, VALUE, NEGATABLE_FLAG }
+
+ private static final Pattern NAME = Pattern.compile("(?:--[A-Za-z0-9][A-Za-z0-9-]*|-[A-Za-z0-9])");
+ private final String name;
+ private final Kind kind;
+ private final boolean repeatable;
+
+ private OpenCliOptionSchema(String name, Kind kind, boolean repeatable) {
+ Objects.requireNonNull(name, "name");
+ if (!NAME.matcher(name).matches()) {
+ throw new IllegalArgumentException("Option schema requires a valid flag identifier");
+ }
+ if (kind == Kind.NEGATABLE_FLAG && (!name.startsWith("--") || name.startsWith("--no-"))) {
+ throw new IllegalArgumentException("Negatable schema requires a positive long flag identifier");
+ }
+ this.name = name;
+ this.kind = kind;
+ this.repeatable = repeatable;
+ }
+
+ /** @param name flag identifier @return a presence-only, nonrepeatable flag */
+ public static OpenCliOptionSchema flag(String name) {
+ return new OpenCliOptionSchema(name, Kind.FLAG, false);
+ }
+
+ /**
+ * @param name option identifier
+ * @param repeatable whether repeated occurrences are accepted by the command
+ * @return an option taking one literal value per occurrence
+ */
+ public static OpenCliOptionSchema value(String name, boolean repeatable) {
+ return new OpenCliOptionSchema(name, Kind.VALUE, repeatable);
+ }
+
+ /** @param name positive long flag identifier @return a flag supporting explicit negation */
+ public static OpenCliOptionSchema negatableFlag(String name) {
+ return new OpenCliOptionSchema(name, Kind.NEGATABLE_FLAG, false);
+ }
+
+ /** @return canonical flag identifier */
+ public String getName() { return name; }
+
+ /** @return declared input kind */
+ public Kind getKind() { return kind; }
+
+ /** @return whether the command accepts repeated occurrences */
+ public boolean isRepeatable() { return repeatable; }
+
+ @Override
+ public boolean equals(Object other) {
+ if (this == other) { return true; }
+ if (!(other instanceof OpenCliOptionSchema)) { return false; }
+ OpenCliOptionSchema that = (OpenCliOptionSchema) other;
+ return name.equals(that.name) && kind == that.kind && repeatable == that.repeatable;
+ }
+
+ @Override
+ public int hashCode() { return Objects.hash(name, kind, repeatable); }
+}
diff --git a/src/main/java/io/github/easy4j/opencli/core/OpenCliProcessRuntime.java b/src/main/java/io/github/easy4j/opencli/core/OpenCliProcessRuntime.java
new file mode 100644
index 0000000..d373f64
--- /dev/null
+++ b/src/main/java/io/github/easy4j/opencli/core/OpenCliProcessRuntime.java
@@ -0,0 +1,37 @@
+package io.github.easy4j.opencli.core;
+
+import io.github.easy4j.opencli.core.support.SubprocessExecutionSupport;
+import java.io.IOException;
+
+/**
+ * Stable process-capacity owner. Pass the same instance to multiple executors to
+ * share a limit deliberately; constructing an unrelated executor cannot replace it.
+ */
+public final class OpenCliProcessRuntime {
+ private final SubprocessExecutionSupport.Runtime runtime;
+
+ /** @param maxConcurrent positive limit, or zero for the CPU-derived default; negative is invalid */
+ public OpenCliProcessRuntime(int maxConcurrent) {
+ runtime = new SubprocessExecutionSupport.Runtime(maxConcurrent);
+ }
+
+ /** @return fixed capacity for this runtime */
+ public int getMaxConcurrentExecutions() { return runtime.getMaxConcurrentExecutions(); }
+
+ /** @return whether unconfirmed resource cleanup has quarantined this runtime */
+ public boolean isQuarantined() { return runtime.isQuarantined(); }
+
+ /**
+ * Low-level bridge used by the SDK executor. Results retain bounded process evidence;
+ * the executor maps terminal conditions to the existing SDK exception hierarchy.
+ *
+ * @param request immutable submission snapshot
+ * @return terminal execution evidence
+ * @throws IOException retained for compatibility with the low-level execution API
+ * @throws InterruptedException retained for compatibility; observed interruption is normally returned as CANCELLED
+ */
+ public SubprocessExecutionSupport.RunSession execute(SubprocessExecutionSupport.ExecutionRequest request)
+ throws IOException, InterruptedException {
+ return runtime.execute(request);
+ }
+}
diff --git a/src/main/java/io/github/easy4j/opencli/core/OpenCliResult.java b/src/main/java/io/github/easy4j/opencli/core/OpenCliResult.java
index 2dbfd7a..23d4631 100644
--- a/src/main/java/io/github/easy4j/opencli/core/OpenCliResult.java
+++ b/src/main/java/io/github/easy4j/opencli/core/OpenCliResult.java
@@ -46,4 +46,7 @@ public class OpenCliResult {
* 远端 Agent HTTP 响应全文;本地子进程模式或非调试场景下为 null。
*/
private final String remoteRawHttpBody;
+
+ /** Bounded local execution evidence, when available. */
+ private final OpenCliExecutionDetails executionDetails;
}
diff --git a/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java b/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
index fd3a6b5..cc3c7cd 100644
--- a/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
+++ b/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
@@ -1,235 +1,463 @@
package io.github.easy4j.opencli.core.support;
-import lombok.Getter;
-import org.apache.commons.exec.CommandLine;
-import org.apache.commons.exec.DefaultExecuteResultHandler;
-import org.apache.commons.exec.DefaultExecutor;
-import org.apache.commons.exec.ExecuteWatchdog;
-import org.apache.commons.exec.PumpStreamHandler;
-
+import io.github.easy4j.opencli.core.OpenCliCancellationToken;
+import io.github.easy4j.opencli.core.OpenCliExecutionDetails;
+import io.github.easy4j.opencli.core.OpenCliExecutionDetails.CleanupState;
+import io.github.easy4j.opencli.core.OpenCliExecutionDetails.TerminationReason;
import java.io.ByteArrayOutputStream;
-import java.io.OutputStream;
import java.io.File;
import java.io.IOException;
-import java.time.Duration;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Semaphore;
-import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.TimeUnit;
+import lombok.Getter;
+import org.apache.commons.exec.CommandLine;
+import org.apache.commons.exec.DefaultExecuteResultHandler;
+import org.apache.commons.exec.ExecuteException;
+import org.apache.commons.exec.ExecuteWatchdog;
+import java.time.Duration;
/**
- * Subprocess execution support based on Apache Commons Exec: watchdog timeout,
- * bounded {@code waitFor}, and concurrency throttling.
- *
- * @author Loong Wan
- * @since 3.0.0
- */public final class SubprocessExecutionSupport {
-
- /** Watchdog 触发后,handler 收尾等待的上限(毫秒)。 */
- public static final long WAIT_GRACE_MILLIS = 5_000L;
+ * Bounded, owned native-process execution. ProcessBuilder receives an exact argv
+ * vector, never a shell string. Commons Exec handler/watchdog views remain for
+ * compatibility with the earlier low-level RunSession API.
+ */
+public final class SubprocessExecutionSupport {
+ @FunctionalInterface
+ interface ProcessStarter {
+ Process start(ProcessBuilder builder) throws IOException;
+ }
- private static final int DEFAULT_MAX_CONCURRENT = Math.max(2, Runtime.getRuntime().availableProcessors());
+ @FunctionalInterface
+ interface WatchdogFactory {
+ ExecuteWatchdog create(long timeoutMillis);
+ }
- private static final AtomicReference CONCURRENCY_LIMIT =
- new AtomicReference<>(new Semaphore(DEFAULT_MAX_CONCURRENT));
+ public static final long WAIT_GRACE_MILLIS = 5_000L;
+ public static final int DEFAULT_STDOUT_LIMIT = 8 * 1024 * 1024;
+ public static final int DEFAULT_STDERR_LIMIT = 2 * 1024 * 1024;
+ private static final long POLL_NANOS = TimeUnit.MILLISECONDS.toNanos(10L);
+ private static final int DEFAULT_MAX_CONCURRENT = Math.max(2, java.lang.Runtime.getRuntime().availableProcessors());
+ private static final Object LEGACY_LOCK = new Object();
+ private static Runtime legacyRuntime = new Runtime(0);
+ private static int legacySubmissions;
- private SubprocessExecutionSupport() {
- }
+ private SubprocessExecutionSupport() { }
/**
- * 配置本机 CLI 子进程全局并发上限;{@code maxConcurrent <= 0} 时恢复为默认值。
+ * Configure only the deprecated static bridge, never an existing SDK client.
+ * Reconfiguration with active or queued submissions is rejected rather than
+ * creating a second live permit pool.
*
- * @param maxConcurrent 允许同时运行的子进程数
+ * @param maxConcurrent positive capacity or zero for the default
+ * @deprecated pass an explicit OpenCliProcessRuntime to executors instead
*/
+ @Deprecated
public static void configureMaxConcurrentExecutions(int maxConcurrent) {
- if (maxConcurrent <= 0) {
- CONCURRENCY_LIMIT.set(new Semaphore(DEFAULT_MAX_CONCURRENT));
- return;
+ synchronized (LEGACY_LOCK) {
+ if (legacySubmissions != 0) {
+ throw new IllegalStateException("Cannot reconfigure the legacy runtime while submissions exist");
+ }
+ legacyRuntime = new Runtime(maxConcurrent);
}
- CONCURRENCY_LIMIT.set(new Semaphore(maxConcurrent));
}
- /**
- * @return 未显式配置时的默认并发上限
- */
- public static int defaultMaxConcurrentExecutions() {
- return DEFAULT_MAX_CONCURRENT;
- }
+ public static int defaultMaxConcurrentExecutions() { return DEFAULT_MAX_CONCURRENT; }
- /**
- * 在并发许可内启动子进程并阻塞至结束、超时或被强制销毁。
- */
+ /** Legacy entry point using one stable, explicitly configured runtime. */
public static RunSession execute(ExecutionRequest request) throws IOException, InterruptedException {
Objects.requireNonNull(request, "request");
- Semaphore limit = CONCURRENCY_LIMIT.get();
- limit.acquire();
+ Runtime selected;
+ synchronized (LEGACY_LOCK) {
+ selected = legacyRuntime;
+ legacySubmissions++;
+ }
try {
- return executeWithinLimit(request);
+ return selected.execute(request);
} finally {
- limit.release();
+ synchronized (LEGACY_LOCK) { legacySubmissions--; }
+ }
+ }
+
+ /** Internal capacity/cleanup owner exposed through OpenCliProcessRuntime. */
+ public static final class Runtime {
+ private final int maxConcurrentExecutions;
+ private final Semaphore permits;
+ private final ProcessStarter processStarter;
+ private final WatchdogFactory watchdogFactory;
+ private volatile boolean quarantined;
+
+ public Runtime(int maxConcurrent) {
+ this(maxConcurrent, ProcessBuilder::start, SubprocessExecutionSupport::newWatchdog);
+ }
+
+ Runtime(int maxConcurrent, ProcessStarter processStarter, WatchdogFactory watchdogFactory) {
+ if (maxConcurrent < 0) {
+ throw new IllegalArgumentException("maxConcurrentExecutions must not be negative");
+ }
+ maxConcurrentExecutions = maxConcurrent == 0 ? DEFAULT_MAX_CONCURRENT : maxConcurrent;
+ permits = new Semaphore(maxConcurrentExecutions, true);
+ this.processStarter = Objects.requireNonNull(processStarter, "processStarter");
+ this.watchdogFactory = Objects.requireNonNull(watchdogFactory, "watchdogFactory");
+ }
+
+ public int getMaxConcurrentExecutions() { return maxConcurrentExecutions; }
+ public boolean isQuarantined() { return quarantined; }
+
+ public RunSession execute(ExecutionRequest request) throws IOException, InterruptedException {
+ Objects.requireNonNull(request, "request");
+ long budget = nanos(request.timeoutMillis, "timeoutMillis");
+ BoundedCapture out = new BoundedCapture(request.stdoutLimitBytes);
+ BoundedCapture err = new BoundedCapture(request.stderrLimitBytes);
+ Process process = null;
+ Reader stdoutReader = null;
+ Reader stderrReader = null;
+ ExecuteWatchdog watchdog = null;
+ TerminationReason reason = null;
+ IOException ioFailure = null;
+ boolean acquired = false;
+ boolean interrupted = false;
+ boolean cleanupOperationFailed = false;
+ long queueWaitMillis = 0L;
+ try {
+ while (!acquired && reason == null) {
+ if (Thread.interrupted()) {
+ interrupted = true;
+ reason = TerminationReason.CANCELLED;
+ } else if (request.cancellationToken.isCancelled()) {
+ reason = TerminationReason.CANCELLED;
+ } else if (quarantined) {
+ reason = TerminationReason.RUNTIME_UNAVAILABLE;
+ } else {
+ long remaining = remaining(request.submittedAtNanos, budget);
+ if (remaining <= 0) {
+ reason = TerminationReason.QUEUE_TIMEOUT;
+ } else {
+ acquired = permits.tryAcquire(Math.min(POLL_NANOS, remaining), TimeUnit.NANOSECONDS);
+ }
+ }
+ }
+ queueWaitMillis = elapsedMillis(request.submittedAtNanos);
+ if (acquired && reason == null) {
+ if (Thread.interrupted()) {
+ interrupted = true;
+ reason = TerminationReason.CANCELLED;
+ } else if (request.cancellationToken.isCancelled()) {
+ reason = TerminationReason.CANCELLED;
+ } else if (quarantined) {
+ reason = TerminationReason.RUNTIME_UNAVAILABLE;
+ } else if (remaining(request.submittedAtNanos, budget) <= 0) {
+ reason = TerminationReason.QUEUE_TIMEOUT;
+ }
+ }
+ if (acquired && reason == null) {
+ ProcessBuilder builder = new ProcessBuilder(request.nativeArgv);
+ if (request.workingDirectory != null) { builder.directory(request.workingDirectory); }
+ if (request.environment != null) {
+ builder.environment().clear();
+ builder.environment().putAll(request.environment);
+ }
+ process = processStarter.start(builder);
+ process.getOutputStream().close();
+ stdoutReader = new Reader(process.getInputStream(), out, "opencli-stdout");
+ stderrReader = new Reader(process.getErrorStream(), err, "opencli-stderr");
+ stdoutReader.start();
+ stderrReader.start();
+ long remaining = remaining(request.submittedAtNanos, budget);
+ try {
+ watchdog = watchdogFactory.create(
+ Math.max(1L, TimeUnit.NANOSECONDS.toMillis(Math.max(0L, remaining))));
+ watchdog.start(process);
+ } catch (RuntimeException ex) {
+ ioFailure = new IOException("Failed to initialize execution watchdog", ex);
+ reason = TerminationReason.IO_FAILURE;
+ }
+ while (reason == null) {
+ if (out.isTruncated() || err.isTruncated()) {
+ reason = TerminationReason.OUTPUT_LIMIT;
+ } else if (Thread.interrupted()) {
+ interrupted = true;
+ reason = TerminationReason.CANCELLED;
+ } else if (request.cancellationToken.isCancelled()) {
+ reason = TerminationReason.CANCELLED;
+ } else if (Objects.nonNull(stdoutReader.failure) || Objects.nonNull(stderrReader.failure)) {
+ ioFailure = Objects.nonNull(stdoutReader.failure)
+ ? stdoutReader.failure : stderrReader.failure;
+ reason = TerminationReason.IO_FAILURE;
+ } else if (!process.isAlive() && !stdoutReader.isAlive() && !stderrReader.isAlive()) {
+ reason = watchdog.killedProcess() ? TerminationReason.EXECUTION_TIMEOUT : TerminationReason.PROCESS_EXIT;
+ } else if (watchdog.killedProcess() || remaining(request.submittedAtNanos, budget) <= 0) {
+ reason = TerminationReason.EXECUTION_TIMEOUT;
+ } else {
+ TimeUnit.NANOSECONDS.sleep(Math.min(POLL_NANOS, Math.max(1L,
+ remaining(request.submittedAtNanos, budget))));
+ }
+ }
+ }
+ } catch (InterruptedException ex) {
+ interrupted = true;
+ reason = TerminationReason.CANCELLED;
+ } catch (IOException ex) {
+ ioFailure = ex;
+ reason = process == null ? TerminationReason.SPAWN_FAILED : TerminationReason.IO_FAILURE;
+ } catch (RuntimeException ex) {
+ ioFailure = new IOException("Native process setup or execution failure", ex);
+ reason = process == null ? TerminationReason.SPAWN_FAILED : TerminationReason.IO_FAILURE;
+ } finally {
+ try {
+ try {
+ if (Objects.nonNull(watchdog)) {
+ watchdog.stop();
+ }
+ } catch (RuntimeException ex) {
+ cleanupOperationFailed = true;
+ }
+ long cleanupStart = System.nanoTime();
+ long cleanupBudget = nanos(request.cleanupGraceMillis, "cleanupGraceMillis");
+ if (Objects.nonNull(process)) {
+ boolean forceSent = false;
+ if (process.isAlive()) {
+ try {
+ process.destroy();
+ } catch (RuntimeException ex) {
+ cleanupOperationFailed = true;
+ forceSent = true;
+ if (!tryForceStop(process)) { cleanupOperationFailed = true; }
+ }
+ }
+ while (remaining(cleanupStart, cleanupBudget) > 0
+ && (process.isAlive() || alive(stdoutReader) || alive(stderrReader))) {
+ if (Thread.interrupted()) { interrupted = true; }
+ if (process.isAlive() && !forceSent
+ && System.nanoTime() - cleanupStart >= Math.min(TimeUnit.MILLISECONDS.toNanos(100L), cleanupBudget / 2)) {
+ if (!tryForceStop(process)) { cleanupOperationFailed = true; }
+ forceSent = true;
+ }
+ try {
+ TimeUnit.NANOSECONDS.sleep(Math.min(POLL_NANOS,
+ Math.max(1L, remaining(cleanupStart, cleanupBudget))));
+ } catch (InterruptedException ex) {
+ interrupted = true;
+ }
+ }
+ if (process.isAlive() && !tryForceStop(process)) { cleanupOperationFailed = true; }
+ if (process.isAlive() || alive(stdoutReader) || alive(stderrReader)) {
+ // A fixed runtime cannot accumulate unlimited uncertain children/readers.
+ quarantined = true;
+ if (reason == TerminationReason.PROCESS_EXIT) { reason = TerminationReason.CLEANUP_UNCONFIRMED; }
+ }
+ }
+ } finally {
+ out.freeze();
+ err.freeze();
+ if (acquired) { permits.release(); }
+ if (interrupted) { Thread.currentThread().interrupt(); }
+ }
+ }
+ if (reason == TerminationReason.PROCESS_EXIT && (out.isTruncated() || err.isTruncated())) {
+ reason = TerminationReason.OUTPUT_LIMIT;
+ }
+ Integer exit = process != null && !process.isAlive() ? process.exitValue() : null;
+ DefaultExecuteResultHandler handler = new DefaultExecuteResultHandler();
+ if (ioFailure != null) {
+ handler.onProcessFailed(new ExecuteException("Native process I/O failure", exit == null ? -1 : exit, ioFailure));
+ } else if (exit != null && exit != 0) {
+ handler.onProcessFailed(new ExecuteException("Native process returned nonzero status", exit));
+ } else if (exit != null) {
+ handler.onProcessComplete(exit);
+ }
+ OpenCliExecutionDetails details = OpenCliExecutionDetails.builder()
+ .terminationReason(reason)
+ .cleanupState(process == null ? CleanupState.NOT_STARTED
+ : process.isAlive() ? CleanupState.UNCONFIRMED : CleanupState.ROOT_EXIT_CONFIRMED)
+ .processStarted(process != null).streamsDrained(!alive(stdoutReader) && !alive(stderrReader))
+ .cleanupOperationFailed(cleanupOperationFailed)
+ .stdoutCapturedBytes(out.size()).stdoutObservedBytes(out.observed()).stdoutTruncated(out.isTruncated())
+ .stderrCapturedBytes(err.size()).stderrObservedBytes(err.observed()).stderrTruncated(err.isTruncated())
+ .elapsedMillis(elapsedMillis(request.submittedAtNanos)).queueWaitMillis(queueWaitMillis)
+ .descendantsExitConfirmed(false).build();
+ // Preserve the legacy RunSession watchdog view even when nothing was started.
+ ExecuteWatchdog watchdogView = Objects.nonNull(watchdog) ? watchdog : newWatchdog(request.timeoutMillis);
+ return new RunSession(out, err, handler, watchdogView, request.timeoutMillis,
+ reason == TerminationReason.QUEUE_TIMEOUT || reason == TerminationReason.EXECUTION_TIMEOUT,
+ details, exit, ioFailure);
}
}
- private static RunSession executeWithinLimit(ExecutionRequest request) throws IOException, InterruptedException {
- long timeoutMs = Math.max(1L, request.getTimeoutMillis());
- BoundedOutputStream out = new BoundedOutputStream(request.getMaxOutputBytes());
- BoundedOutputStream err = new BoundedOutputStream(request.getMaxOutputBytes());
+ private static ExecuteWatchdog newWatchdog(long timeoutMillis) {
+ return ExecuteWatchdog.builder().setTimeout(Duration.ofMillis(timeoutMillis)).get();
+ }
+
+ private static boolean alive(Thread thread) { return thread != null && thread.isAlive(); }
+ private static boolean tryForceStop(Process process) {
+ try {
+ process.destroyForcibly();
+ return true;
+ } catch (RuntimeException ex) {
+ return false;
+ }
+ }
+ private static long remaining(long start, long budget) { return budget - (System.nanoTime() - start); }
+ private static long elapsedMillis(long start) { return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); }
- DefaultExecutor.Builder builder = DefaultExecutor.builder();
- if (request.getWorkingDirectory() != null) {
- builder.setWorkingDirectory(request.getWorkingDirectory());
+ private static long nanos(long millis, String field) {
+ if (millis <= 0 || millis > Long.MAX_VALUE / 1_000_000L) {
+ throw new IllegalArgumentException(field + " must be positive and fit a monotonic nanosecond budget");
}
- DefaultExecutor executor = builder.get();
- executor.setStreamHandler(new PumpStreamHandler(out, err));
+ return millis * 1_000_000L;
+ }
- ExecuteWatchdog watchdog =
- ExecuteWatchdog.builder().setTimeout(Duration.ofMillis(timeoutMs)).get();
- executor.setWatchdog(watchdog);
+ private static final class BoundedCapture extends ByteArrayOutputStream {
+ private final int limit;
+ private long observed;
+ private boolean truncated;
+ private boolean frozen;
- DefaultExecuteResultHandler handler = new DefaultExecuteResultHandler();
- Map environment = request.getEnvironment();
- if (environment != null) {
- executor.execute(request.getCommandLine(), environment, handler);
- } else {
- executor.execute(request.getCommandLine(), handler);
+ BoundedCapture(int limit) {
+ super(Math.min(8192, limit));
+ this.limit = limit;
}
- boolean finished = awaitResult(handler, timeoutMs + WAIT_GRACE_MILLIS);
- boolean waitTimedOut = !finished;
- if (waitTimedOut) {
- watchdog.destroyProcess();
- awaitResult(handler, WAIT_GRACE_MILLIS);
+ @Override
+ public synchronized void write(byte[] bytes, int offset, int length) {
+ if (frozen) { return; }
+ observed = observed > Long.MAX_VALUE - length ? Long.MAX_VALUE : observed + length;
+ int retained = Math.min(length, limit - count);
+ super.write(bytes, offset, retained);
+ truncated |= retained < length;
}
- return new RunSession(out, err, handler, watchdog, timeoutMs, waitTimedOut);
+ @Override
+ public synchronized void write(int value) { write(new byte[]{(byte) value}, 0, 1); }
+ synchronized boolean isTruncated() { return truncated; }
+ synchronized long observed() { return observed; }
+ synchronized void freeze() { frozen = true; }
}
- private static boolean awaitResult(DefaultExecuteResultHandler handler, long timeoutMillis)
- throws InterruptedException {
- long deadline = System.currentTimeMillis() + Math.max(1L, timeoutMillis);
- while (!handler.hasResult()) {
- if (System.currentTimeMillis() >= deadline) {
- return false;
+ private static final class Reader extends Thread {
+ private final InputStream input;
+ private final BoundedCapture capture;
+ private volatile IOException failure;
+
+ Reader(InputStream input, BoundedCapture capture, String name) {
+ super(name);
+ this.input = input;
+ this.capture = capture;
+ setDaemon(true);
+ }
+
+ @Override
+ public void run() {
+ try (InputStream stream = input) {
+ byte[] buffer = new byte[8192];
+ int size;
+ while ((size = stream.read(buffer)) != -1) {
+ capture.write(buffer, 0, size);
+ if (capture.isTruncated()) { return; }
+ }
+ } catch (IOException ex) {
+ failure = ex;
}
- Thread.sleep(Math.min(50L, deadline - System.currentTimeMillis()));
}
- return true;
}
@Getter
public static final class ExecutionRequest {
-
private final CommandLine commandLine;
+ private final List nativeArgv;
private final File workingDirectory;
private final Map environment;
private final long timeoutMillis;
- private final long maxOutputBytes;
-
- public ExecutionRequest(
- CommandLine commandLine,
- File workingDirectory,
- Map environment,
- long timeoutMillis) {
- this(commandLine, workingDirectory, environment, timeoutMillis, 0L);
- }
+ private final int stdoutLimitBytes;
+ private final int stderrLimitBytes;
+ private final long cleanupGraceMillis;
+ private final long submittedAtNanos;
+ private final OpenCliCancellationToken cancellationToken;
+
+ public ExecutionRequest(CommandLine commandLine, File workingDirectory,
+ Map environment, long timeoutMillis) {
+ this(commandLine, workingDirectory, environment, timeoutMillis,
+ DEFAULT_STDOUT_LIMIT, DEFAULT_STDERR_LIMIT, WAIT_GRACE_MILLIS,
+ System.nanoTime(), new OpenCliCancellationToken());
+ }
+
+ /** Legacy per-stream ceiling; nonpositive values retain finite default budgets. */
+ public ExecutionRequest(CommandLine commandLine, File workingDirectory,
+ Map environment, long timeoutMillis, long maxOutputBytes) {
+ this(commandLine, workingDirectory, environment, timeoutMillis,
+ legacyLimit(maxOutputBytes, DEFAULT_STDOUT_LIMIT),
+ legacyLimit(maxOutputBytes, DEFAULT_STDERR_LIMIT), WAIT_GRACE_MILLIS,
+ System.nanoTime(), new OpenCliCancellationToken());
+ }
- public ExecutionRequest(
- CommandLine commandLine,
- File workingDirectory,
- Map environment,
- long timeoutMillis,
- long maxOutputBytes) {
- this.commandLine = Objects.requireNonNull(commandLine, "commandLine");
- this.workingDirectory = workingDirectory;
- this.environment = environment;
- this.timeoutMillis = timeoutMillis;
- this.maxOutputBytes = maxOutputBytes;
+ private static int legacyLimit(long maxOutputBytes, int defaultLimit) {
+ return maxOutputBytes > 0 ? (int) Math.min(defaultLimit, maxOutputBytes) : defaultLimit;
+ }
+
+ public ExecutionRequest(CommandLine commandLine, File workingDirectory,
+ Map environment, long timeoutMillis, int stdoutLimitBytes,
+ int stderrLimitBytes, long cleanupGraceMillis, long submittedAtNanos,
+ OpenCliCancellationToken cancellationToken) {
+ this.commandLine = Objects.requireNonNull(commandLine, "commandLine");
+ List argv = new ArrayList<>(Arrays.asList(commandLine.toStrings()));
+ for (int i = 0; i < argv.size(); i++) {
+ if (argv.get(i) == null) { throw new IllegalArgumentException("nativeArgv[" + i + "] must not be null"); }
+ }
+ nativeArgv = Collections.unmodifiableList(argv);
+ this.workingDirectory = workingDirectory;
+ this.environment = environment == null ? null : Collections.unmodifiableMap(new HashMap<>(environment));
+ nanos(timeoutMillis, "timeoutMillis");
+ nanos(cleanupGraceMillis, "cleanupGraceMillis");
+ if (stdoutLimitBytes <= 0 || stderrLimitBytes <= 0) {
+ throw new IllegalArgumentException("stdout/stderr capture budgets must be positive");
}
+ this.timeoutMillis = timeoutMillis;
+ this.stdoutLimitBytes = stdoutLimitBytes;
+ this.stderrLimitBytes = stderrLimitBytes;
+ this.cleanupGraceMillis = cleanupGraceMillis;
+ this.submittedAtNanos = submittedAtNanos;
+ this.cancellationToken = Objects.requireNonNull(cancellationToken, "cancellationToken");
+ }
}
@Getter
public static final class RunSession {
-
- private final BoundedOutputStream stdout;
- private final BoundedOutputStream stderr;
+ private final ByteArrayOutputStream stdout;
+ private final ByteArrayOutputStream stderr;
private final DefaultExecuteResultHandler handler;
private final ExecuteWatchdog watchdog;
private final long timeoutMillis;
private final boolean waitTimedOut;
-
- RunSession(
- BoundedOutputStream stdout,
- BoundedOutputStream stderr,
- DefaultExecuteResultHandler handler,
- ExecuteWatchdog watchdog,
- long timeoutMillis,
- boolean waitTimedOut) {
+ private final OpenCliExecutionDetails executionDetails;
+ private final Integer observedExitCode;
+ private final IOException ioFailure;
+
+ RunSession(ByteArrayOutputStream stdout, ByteArrayOutputStream stderr,
+ DefaultExecuteResultHandler handler, ExecuteWatchdog watchdog, long timeoutMillis,
+ boolean waitTimedOut, OpenCliExecutionDetails executionDetails,
+ Integer observedExitCode, IOException ioFailure) {
this.stdout = stdout;
this.stderr = stderr;
this.handler = handler;
this.watchdog = watchdog;
this.timeoutMillis = timeoutMillis;
this.waitTimedOut = waitTimedOut;
+ this.executionDetails = executionDetails;
+ this.observedExitCode = observedExitCode;
+ this.ioFailure = ioFailure;
}
- public boolean timedOut() {
- return waitTimedOut || watchdog.killedProcess();
- }
+ public boolean timedOut() { return waitTimedOut; }
- boolean isStdoutOverflowed() {
- return stdout.isOverflowed();
- }
+ boolean isStdoutOverflowed() { return executionDetails.isStdoutTruncated(); }
- boolean isStderrOverflowed() {
- return stderr.isOverflowed();
- }
- }
-
- /**
- * 有界内存输出流:超过上限的字节直接丢弃(保留前 maxBytes 字节),
- * 并置溢出标志供调用方追加截断标记。close 为空操作(纯内存流)。
- */
- public static final class BoundedOutputStream extends OutputStream {
-
- private final ByteArrayOutputStream delegate = new ByteArrayOutputStream();
- private final long maxBytes;
- private boolean overflowed;
-
- BoundedOutputStream(long maxBytes) {
- // maxBytes <= 0 视为不限制
- this.maxBytes = Math.max(0L, maxBytes);
- }
-
- @Override
- public synchronized void write(int b) {
- write(new byte[] {(byte) b}, 0, 1);
- }
-
- @Override
- public synchronized void write(byte[] b, int off, int len) {
- if (maxBytes == 0L) {
- delegate.write(b, off, len);
- return;
- }
- long remaining = maxBytes - delegate.size();
- if (remaining <= 0L) {
- overflowed = true;
- return;
- }
- if (len > remaining) {
- delegate.write(b, off, (int) remaining);
- overflowed = true;
- } else {
- delegate.write(b, off, len);
- }
- }
-
- public synchronized byte[] toByteArray() {
- return delegate.toByteArray();
- }
-
- public synchronized boolean isOverflowed() {
- return overflowed;
- }
+ boolean isStderrOverflowed() { return executionDetails.isStderrTruncated(); }
}
}
diff --git a/src/main/java/io/github/easy4j/opencli/exception/OpenCliExecutableFailureException.java b/src/main/java/io/github/easy4j/opencli/exception/OpenCliExecutableFailureException.java
index 378bd95..270f2c7 100644
--- a/src/main/java/io/github/easy4j/opencli/exception/OpenCliExecutableFailureException.java
+++ b/src/main/java/io/github/easy4j/opencli/exception/OpenCliExecutableFailureException.java
@@ -2,14 +2,14 @@
import io.github.easy4j.opencli.core.OpenCliResult;
-/**
- * Thrown when the OpenCLI executable cannot be started (PATH, permissions, invalid arguments, etc.).
- *
- * @author Loong Wan
- * @since 3.0.0
- */public class OpenCliExecutableFailureException extends OpenCliException {
-
+/** Failure to start the configured executable. */
+public class OpenCliExecutableFailureException extends OpenCliException {
public OpenCliExecutableFailureException(String message, Throwable cause) {
super(message, cause, null);
}
+
+ /** Retains a no-process-started snapshot without inventing an exit code. */
+ public OpenCliExecutableFailureException(String message, Throwable cause, OpenCliResult partialResult) {
+ super(message, cause, partialResult);
+ }
}
diff --git a/src/test/java/io/github/easy4j/opencli/contract/ContractProbe.java b/src/test/java/io/github/easy4j/opencli/contract/ContractProbe.java
new file mode 100644
index 0000000..3c50a12
--- /dev/null
+++ b/src/test/java/io/github/easy4j/opencli/contract/ContractProbe.java
@@ -0,0 +1,16 @@
+package io.github.easy4j.opencli.contract;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+
+/** Offline child process: emits every actual JVM argument, including empty values. */
+public final class ContractProbe {
+ private ContractProbe() { }
+
+ public static void main(String[] args) {
+ System.out.println("argc:" + args.length);
+ for (String arg : args) {
+ System.out.println("arg:" + Base64.getEncoder().encodeToString(arg.getBytes(StandardCharsets.UTF_8)));
+ }
+ }
+}
diff --git a/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java b/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java
new file mode 100644
index 0000000..88247cf
--- /dev/null
+++ b/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java
@@ -0,0 +1,44 @@
+package io.github.easy4j.opencli.contract;
+
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Arrays;
+
+/** Offline, self-bounded child fixture. Release files allow cleanup even against a broken SDK. */
+public final class LifecycleProbe {
+ private LifecycleProbe() { }
+
+ public static void main(String[] args) throws Exception {
+ String mode = args[0];
+ if ("utf8".equals(mode)) {
+ System.out.write("中文".getBytes(StandardCharsets.UTF_8));
+ return;
+ }
+ if ("stdout".equals(mode) || "stderr".equals(mode)) {
+ byte[] block = new byte[8192];
+ Arrays.fill(block, (byte) 'x');
+ int remaining = Integer.parseInt(args[1]);
+ while (remaining > 0) {
+ int size = Math.min(block.length, remaining);
+ if ("stdout".equals(mode)) { System.out.write(block, 0, size); }
+ else { System.err.write(block, 0, size); }
+ remaining -= size;
+ }
+ return;
+ }
+ Path marker = Paths.get(args[1]);
+ Files.write(marker, "started".getBytes(StandardCharsets.UTF_8));
+ if ("write".equals(mode)) { return; }
+ Path release = Paths.get(args[2]);
+ long start = System.nanoTime();
+ int tick = 0;
+ while (!Files.exists(release) && System.nanoTime() - start < 10_000_000_000L) {
+ if ("heartbeat".equals(mode)) {
+ Files.write(marker, Integer.toString(++tick).getBytes(StandardCharsets.UTF_8));
+ }
+ Thread.sleep(20L);
+ }
+ }
+}
diff --git a/src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java b/src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java
new file mode 100644
index 0000000..e50a631
--- /dev/null
+++ b/src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java
@@ -0,0 +1,171 @@
+package io.github.easy4j.opencli.contract;
+
+import io.github.easy4j.opencli.OpenCliProperties;
+import io.github.easy4j.opencli.browser.OpenCliBrowserClient;
+import io.github.easy4j.opencli.core.OpenCliAdapterChannel;
+import io.github.easy4j.opencli.core.OpenCliAdapterCommandRequest;
+import io.github.easy4j.opencli.core.OpenCliArgSupport;
+import io.github.easy4j.opencli.core.OpenCliExecutor;
+import io.github.easy4j.opencli.core.OpenCliResult;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.StringReader;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Stream;
+import org.junit.jupiter.api.DynamicTest;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestFactory;
+import static org.junit.jupiter.api.Assertions.*;
+
+/** Shared Java 8-compatible contract tests, with a real child rather than Recording executor. */
+class OpenCliArgvContractTest {
+ private static OpenCliProperties properties() {
+ OpenCliProperties p = new OpenCliProperties();
+ String exe = System.getProperty("os.name").startsWith("Windows") ? "java.exe" : "java";
+ p.setExecutable(new File(new File(System.getProperty("java.home"), "bin"), exe).getAbsolutePath());
+ p.setLeadingArguments(new ArrayList<>(Arrays.asList("-cp",
+ System.getProperty("surefire.test.class.path", System.getProperty("java.class.path")),
+ ContractProbe.class.getName())));
+ p.setCommandTimeoutMillis(10000L);
+ return p;
+ }
+
+ private static List received(OpenCliResult result) throws Exception {
+ assertTrue(result.isSuccess());
+ List actual = new ArrayList<>();
+ try (BufferedReader reader = new BufferedReader(new StringReader(result.getStdout()))) {
+ String header = reader.readLine();
+ assertNotNull(header, "child produced no argv evidence");
+ assertTrue(header.startsWith("argc:"), "missing child protocol header");
+ int count = Integer.parseInt(header.substring(5));
+ for (int i = 0; i < count; i++) {
+ String line = reader.readLine();
+ assertNotNull(line, "incomplete child output");
+ assertTrue(line.startsWith("arg:"));
+ actual.add(new String(Base64.getDecoder().decode(line.substring(4)), StandardCharsets.UTF_8));
+ }
+ assertNull(reader.readLine(), "unexpected extra child output");
+ }
+ return actual;
+ }
+
+ @TestFactory
+ Stream sharedVectorsReachEveryRawEntryPoint() throws Exception {
+ List tests = new ArrayList<>();
+ InputStream resource = getClass().getResourceAsStream("/opencli-contracts/v1/argv.tsv");
+ assertNotNull(resource, "shared fixture is required");
+ try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource, StandardCharsets.UTF_8))) {
+ String line;
+ while ((line = reader.readLine()) != null) {
+ String[] fields = line.split("\t", -1);
+ List expected = new ArrayList<>();
+ for (int i = 1; i < fields.length; i++) {
+ expected.add(new String(Base64.getDecoder().decode(fields[i]), StandardCharsets.UTF_8));
+ }
+ for (int mode = 0; mode < 4; mode++) {
+ final int entry = mode;
+ tests.add(DynamicTest.dynamicTest(fields[0] + "/entry-" + mode, () -> {
+ OpenCliExecutor executor = new OpenCliExecutor(properties());
+ List before = new ArrayList<>(expected);
+ OpenCliResult result;
+ if (entry == 0) {
+ result = executor.invoke(expected);
+ } else if (entry == 1) {
+ result = executor.invoke(expected.toArray(new String[0]));
+ } else {
+ OpenCliAdapterChannel channel = new OpenCliAdapterChannel(executor, expected.get(0));
+ List rest = expected.subList(1, expected.size());
+ result = entry == 2 ? channel.invoke(rest) : channel.invoke(rest.toArray(new String[0]));
+ }
+ assertEquals(before, expected, "caller list changed");
+ assertEquals(expected, received(result), "full argv changed at child boundary");
+ }));
+ }
+ }
+ }
+ assertEquals(24, tests.size(), "fixture denominator changed; review sources.lock.json");
+ return tests.stream();
+ }
+
+ @Test
+ void structuredPositionalsAndValuesReachChildUnchanged() throws Exception {
+ Map options = new LinkedHashMap<>();
+ options.put("text", " value ");
+ OpenCliAdapterCommandRequest request = OpenCliAdapterCommandRequest.builder()
+ .subcommand("echo").positional("").positional(" positional ").options(options).build();
+ assertEquals(Arrays.asList("demo", "echo", "", " positional ", "--text", " value "),
+ received(new OpenCliAdapterChannel(new OpenCliExecutor(properties()), "demo").invoke(request)));
+ }
+
+ @Test
+ void typedBrowserFillCanClearAField() throws Exception {
+ OpenCliBrowserClient browser = new OpenCliBrowserClient(new OpenCliExecutor(properties()));
+ assertEquals(Arrays.asList("browser", "contract", "fill", "#input", ""),
+ received(browser.session("contract").fill("#input", "", null, null)));
+ }
+
+ @Test
+ void rawMergePreservesEmptyAndPaddedValues() throws Exception {
+ List prefix = Arrays.asList("demo", "echo", "");
+ List extra = Arrays.asList(" x ", "--", "-literal");
+ assertEquals(Arrays.asList("demo", "echo", "", " x ", "--", "-literal"),
+ received(new OpenCliExecutor(properties()).invoke(OpenCliArgSupport.merge(prefix, extra))));
+ assertEquals(Arrays.asList("demo", "echo", ""), prefix);
+ }
+
+ @Test
+ void leadingArgumentsPreserveEmptyAndPaddedValues() throws Exception {
+ OpenCliProperties p = properties();
+ p.getLeadingArguments().add("");
+ p.getLeadingArguments().add(" leading ");
+ assertEquals(Arrays.asList("", " leading ", "demo"),
+ received(new OpenCliExecutor(p).invoke("demo")));
+ }
+
+ @Test
+ void nullRawTokenIsRejectedWithoutLeakingOtherTokens() {
+ OpenCliExecutor executor = new OpenCliExecutor(properties());
+ IllegalArgumentException error = assertThrows(IllegalArgumentException.class,
+ () -> executor.invoke(Arrays.asList("demo", "SECRET_MARKER", null)));
+ assertTrue(error.getMessage().contains("2"), "validation must identify null index");
+ assertFalse(error.getMessage().contains("SECRET_MARKER"));
+ }
+
+ @Test
+ void blankCommandIdentifierIsRejectedBeforeSpawn() {
+ OpenCliExecutor executor = new OpenCliExecutor(properties());
+ assertThrows(IllegalArgumentException.class, () -> executor.invoke(Arrays.asList("", "demo")));
+ assertThrows(IllegalArgumentException.class, () -> OpenCliAdapterCommandRequest.builder()
+ .subcommand(" ").build().toSubcommandAndArgs());
+ }
+
+ @Test
+ void nullVarargsContainerIsRejectedConsistently() {
+ OpenCliExecutor executor = new OpenCliExecutor(properties());
+ assertThrows(NullPointerException.class, () -> executor.invoke((String[]) null));
+ assertThrows(NullPointerException.class,
+ () -> new OpenCliAdapterChannel(executor, "demo").invoke((String[]) null));
+ }
+
+ @Test
+ void nullLeadingTokenIsRejectedBeforeSpawn() {
+ OpenCliProperties p = properties();
+ p.getLeadingArguments().add(null);
+ assertThrows(IllegalArgumentException.class, () -> new OpenCliExecutor(p).invoke("demo"));
+ }
+
+ @Test
+ void nullMergedTokenIsRejected() {
+ assertThrows(IllegalArgumentException.class,
+ () -> OpenCliArgSupport.merge(Arrays.asList("demo", null), Collections.emptyList()));
+ }
+}
diff --git a/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessBoundaryTest.java b/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessBoundaryTest.java
new file mode 100644
index 0000000..389140c
--- /dev/null
+++ b/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessBoundaryTest.java
@@ -0,0 +1,162 @@
+package io.github.easy4j.opencli.contract;
+
+import io.github.easy4j.opencli.OpenCliProperties;
+import io.github.easy4j.opencli.core.OpenCliCancellationToken;
+import io.github.easy4j.opencli.core.OpenCliExecutionDetails.TerminationReason;
+import io.github.easy4j.opencli.core.OpenCliExecutor;
+import io.github.easy4j.opencli.core.OpenCliResult;
+import io.github.easy4j.opencli.exception.OpenCliException;
+import io.github.easy4j.opencli.exception.OpenCliTimeoutException;
+import java.io.File;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.api.io.TempDir;
+import static org.junit.jupiter.api.Assertions.*;
+
+/** Additional finite-budget and immutable-submission regression vectors. */
+@Timeout(20)
+class OpenCliProcessBoundaryTest {
+ @TempDir Path dir;
+
+ private static OpenCliProperties properties() {
+ OpenCliProperties p = new OpenCliProperties();
+ String exe = System.getProperty("os.name").startsWith("Windows") ? "java.exe" : "java";
+ p.setExecutable(new File(new File(System.getProperty("java.home"), "bin"), exe).getAbsolutePath());
+ p.setLeadingArguments(new ArrayList<>(Arrays.asList("-cp",
+ System.getProperty("surefire.test.class.path", System.getProperty("java.class.path")),
+ LifecycleProbe.class.getName())));
+ p.setCommandTimeoutMillis(10000L);
+ p.setMaxConcurrentExecutions(1);
+ return p;
+ }
+
+ private static void await(Path path) throws Exception {
+ long started = System.nanoTime();
+ while (!Files.exists(path) && System.nanoTime() - started < TimeUnit.SECONDS.toNanos(3L)) { Thread.sleep(10L); }
+ assertTrue(Files.exists(path), "fixture did not start");
+ }
+
+ @Test
+ void utf8TruncationReportsBytesNotReencodedCharacters() {
+ OpenCliProperties p = properties();
+ p.setMaxStdoutBytes(4);
+ OpenCliException failure = assertThrows(OpenCliException.class, () -> new OpenCliExecutor(p).invoke("utf8"));
+ OpenCliResult partial = failure.getPartialResult();
+ assertNotNull(partial);
+ assertEquals(TerminationReason.OUTPUT_LIMIT, partial.getExecutionDetails().getTerminationReason());
+ assertEquals(4L, partial.getExecutionDetails().getStdoutCapturedBytes());
+ assertEquals(6L, partial.getExecutionDetails().getStdoutObservedBytes());
+ assertEquals("中\uFFFD", partial.getStdout());
+ assertTrue(partial.getExecutionDetails().isStdoutTruncated());
+ }
+
+ @Test
+ void invalidBudgetsFailBeforeChildCreation() {
+ for (int choice = 0; choice < 5; choice++) {
+ OpenCliProperties p = properties();
+ if (choice == 0) { p.setMaxStdoutBytes(0); }
+ if (choice == 1) { p.setMaxStderrBytes(-1); }
+ if (choice == 2) { p.setCleanupGraceMillis(0); }
+ if (choice == 3) { p.setCommandTimeoutMillis(Long.MAX_VALUE); }
+ if (choice == 4) { p.setCleanupGraceMillis(Long.MAX_VALUE); }
+ Path marker = dir.resolve("invalid-" + choice);
+ assertThrows(IllegalArgumentException.class, () -> new OpenCliExecutor(p).invoke("write", marker.toString()));
+ assertFalse(Files.exists(marker));
+ }
+ }
+
+ @Test
+ void explicitCancellationOfRunningChildRetainsBoundedEvidence() throws Exception {
+ OpenCliExecutor executor = new OpenCliExecutor(properties());
+ OpenCliCancellationToken token = new OpenCliCancellationToken();
+ Path heartbeat = dir.resolve("heartbeat");
+ Path release = dir.resolve("release");
+ ExecutorService worker = Executors.newSingleThreadExecutor();
+ try {
+ Future future = worker.submit(() -> executor.invoke(
+ Arrays.asList("heartbeat", heartbeat.toString(), release.toString()), token));
+ await(heartbeat);
+ token.cancel();
+ ExecutionException failed = assertThrows(ExecutionException.class, () -> future.get(3, TimeUnit.SECONDS));
+ assertTrue(failed.getCause() instanceof OpenCliException);
+ OpenCliResult partial = ((OpenCliException) failed.getCause()).getPartialResult();
+ assertEquals(TerminationReason.CANCELLED, partial.getExecutionDetails().getTerminationReason());
+ assertTrue(partial.getExecutionDetails().isProcessStarted());
+ assertFalse(partial.getExecutionDetails().isDescendantsExitConfirmed());
+ String stopped = new String(Files.readAllBytes(heartbeat), StandardCharsets.UTF_8);
+ Thread.sleep(100L);
+ assertEquals(stopped, new String(Files.readAllBytes(heartbeat), StandardCharsets.UTF_8));
+ assertTrue(executor.invoke("write", dir.resolve("next").toString()).isSuccess());
+ } finally {
+ Files.write(release, new byte[]{1});
+ worker.shutdownNow();
+ assertTrue(worker.awaitTermination(5, TimeUnit.SECONDS));
+ }
+ }
+
+ @Test
+ void queuedTokenCancellationDoesNotStartTheWaitingChild() throws Exception {
+ OpenCliExecutor executor = new OpenCliExecutor(properties());
+ Path first = dir.resolve("first");
+ Path second = dir.resolve("second");
+ Path gate = dir.resolve("release");
+ OpenCliCancellationToken token = new OpenCliCancellationToken();
+ ExecutorService workers = Executors.newFixedThreadPool(2);
+ try {
+ Future one = workers.submit(() -> executor.invoke("hold", first.toString(), gate.toString()));
+ await(first);
+ Future two = workers.submit(() -> executor.invoke(Arrays.asList("write", second.toString()), token));
+ Thread.sleep(100L);
+ token.cancel();
+ ExecutionException failed = assertThrows(ExecutionException.class, () -> two.get(2, TimeUnit.SECONDS));
+ OpenCliResult partial = ((OpenCliException) failed.getCause()).getPartialResult();
+ assertEquals(TerminationReason.CANCELLED, partial.getExecutionDetails().getTerminationReason());
+ assertFalse(partial.getExecutionDetails().isProcessStarted());
+ assertNull(partial.getExitCode());
+ assertFalse(Files.exists(second));
+ Files.write(gate, new byte[]{1});
+ assertTrue(one.get(3, TimeUnit.SECONDS).isSuccess());
+ } finally {
+ Files.write(gate, new byte[]{1});
+ workers.shutdownNow();
+ assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));
+ }
+ }
+
+ @Test
+ void timeoutAndCaptureConfigurationAreCopiedForReverseWorkers() {
+ OpenCliProperties p = properties();
+ p.setMaxStdoutBytes(123);
+ p.setMaxStderrBytes(456);
+ p.setCleanupGraceMillis(789);
+ OpenCliProperties copy = p.copyForLocalCliExecution();
+ assertEquals(123, copy.getMaxStdoutBytes());
+ assertEquals(456, copy.getMaxStderrBytes());
+ assertEquals(789L, copy.getCleanupGraceMillis());
+ }
+
+ @Test
+ void repeatedExecutionTimeoutsDoNotBecomeNonzeroOrIoFailures() {
+ OpenCliProperties p = properties();
+ p.setCommandTimeoutMillis(100L);
+ OpenCliExecutor executor = new OpenCliExecutor(p);
+ for (int i = 0; i < 5; i++) {
+ Path marker = dir.resolve("timeout-" + i);
+ OpenCliTimeoutException failure = assertThrows(OpenCliTimeoutException.class,
+ () -> executor.invoke("hold", marker.toString(), dir.resolve("never-release").toString()));
+ assertEquals(TerminationReason.EXECUTION_TIMEOUT, failure.getPartialResult().getExecutionDetails().getTerminationReason());
+ assertFalse(executor.getProcessRuntime().isQuarantined());
+ }
+ }
+}
diff --git a/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java b/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java
new file mode 100644
index 0000000..5cb4397
--- /dev/null
+++ b/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java
@@ -0,0 +1,233 @@
+package io.github.easy4j.opencli.contract;
+
+import io.github.easy4j.opencli.OpenCliProperties;
+import io.github.easy4j.opencli.core.OpenCliExecutor;
+import io.github.easy4j.opencli.core.OpenCliResult;
+import io.github.easy4j.opencli.exception.OpenCliException;
+import io.github.easy4j.opencli.exception.OpenCliTimeoutException;
+import java.io.File;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.api.io.TempDir;
+import static org.junit.jupiter.api.Assertions.*;
+
+/** C02 tests observe actual fixture processes, not private semaphore counters. */
+@Timeout(20)
+class OpenCliProcessContractTest {
+ @TempDir Path dir;
+
+ private static OpenCliProperties properties(int maxConcurrent) {
+ OpenCliProperties p = new OpenCliProperties();
+ String exe = System.getProperty("os.name").startsWith("Windows") ? "java.exe" : "java";
+ p.setExecutable(new File(new File(System.getProperty("java.home"), "bin"), exe).getAbsolutePath());
+ p.setLeadingArguments(new ArrayList<>(Arrays.asList("-cp",
+ System.getProperty("surefire.test.class.path", System.getProperty("java.class.path")),
+ LifecycleProbe.class.getName())));
+ p.setCommandTimeoutMillis(10000L);
+ p.setMaxConcurrentExecutions(maxConcurrent);
+ return p;
+ }
+
+ private static boolean awaitFile(Path path, long millis) throws Exception {
+ long start = System.nanoTime();
+ while (System.nanoTime() - start < TimeUnit.MILLISECONDS.toNanos(millis)) {
+ if (Files.exists(path)) { return true; }
+ Thread.sleep(10L);
+ }
+ return Files.exists(path);
+ }
+
+ private static void release(Path path) {
+ try { Files.write(path, new byte[]{1}); }
+ catch (Exception ex) { throw new AssertionError("fixture cleanup failed", ex); }
+ }
+
+ private static Object getter(Object object, String name) {
+ assertNotNull(object, "partial evidence is required");
+ return assertDoesNotThrow(() -> object.getClass().getMethod(name).invoke(object),
+ "required execution evidence is missing: " + name);
+ }
+
+ private static Object details(OpenCliResult result) { return getter(result, "getExecutionDetails"); }
+
+ @Test
+ void anotherClientCannotReplaceAnActiveClientsLimiter() throws Exception {
+ OpenCliExecutor a = new OpenCliExecutor(properties(1));
+ Path first = dir.resolve("first");
+ Path second = dir.resolve("second");
+ Path gate = dir.resolve("release");
+ ExecutorService workers = Executors.newFixedThreadPool(2);
+ try {
+ Future one = workers.submit(() -> a.invoke("hold", first.toString(), gate.toString()));
+ assertTrue(awaitFile(first, 3000), "first child did not start");
+ new OpenCliExecutor(properties(4));
+ Future two = workers.submit(() -> a.invoke("write", second.toString()));
+ assertFalse(awaitFile(second, 600), "constructing B bypassed A's active limiter");
+ release(gate);
+ assertTrue(one.get(5, TimeUnit.SECONDS).isSuccess());
+ assertTrue(two.get(5, TimeUnit.SECONDS).isSuccess());
+ } finally {
+ release(gate);
+ workers.shutdownNow();
+ assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));
+ }
+ }
+
+ @Test
+ void queuedDeadlineExpiresWithoutSpawning() throws Exception {
+ OpenCliProperties p = properties(1);
+ OpenCliExecutor executor = new OpenCliExecutor(p);
+ Path first = dir.resolve("first");
+ Path second = dir.resolve("must-not-start");
+ Path gate = dir.resolve("release");
+ ExecutorService worker = Executors.newSingleThreadExecutor();
+ ScheduledExecutorService cleanup = Executors.newSingleThreadScheduledExecutor();
+ try {
+ Future one = worker.submit(() -> executor.invoke("hold", first.toString(), gate.toString()));
+ assertTrue(awaitFile(first, 3000));
+ p.setCommandTimeoutMillis(50L);
+ cleanup.schedule(() -> release(gate), 1500L, TimeUnit.MILLISECONDS);
+ long started = System.nanoTime();
+ OpenCliTimeoutException failure = assertThrows(OpenCliTimeoutException.class,
+ () -> executor.invoke("write", second.toString()));
+ long elapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started);
+ assertTrue(elapsed < 750L, "queue wait ignored total deadline: " + elapsed);
+ assertFalse(Files.exists(second), "queue-expired child was started");
+ Object evidence = details(failure.getPartialResult());
+ assertEquals("QUEUE_TIMEOUT", String.valueOf(getter(evidence, "getTerminationReason")));
+ assertEquals(false, getter(evidence, "isProcessStarted"));
+ assertNull(failure.getPartialResult().getExitCode());
+ release(gate);
+ assertTrue(one.get(5, TimeUnit.SECONDS).isSuccess());
+ } finally {
+ release(gate);
+ worker.shutdownNow();
+ cleanup.shutdownNow();
+ assertTrue(worker.awaitTermination(5, TimeUnit.SECONDS));
+ assertTrue(cleanup.awaitTermination(5, TimeUnit.SECONDS));
+ }
+ }
+
+ @Test
+ void stdoutDefaultBudgetFailsInsteadOfReturningUnboundedSuccess() {
+ OpenCliException failure = assertThrows(OpenCliException.class,
+ () -> new OpenCliExecutor(properties(1)).invoke("stdout", Integer.toString(9 * 1024 * 1024)));
+ OpenCliResult partial = failure.getPartialResult();
+ Object evidence = details(partial);
+ assertEquals("OUTPUT_LIMIT", String.valueOf(getter(evidence, "getTerminationReason")));
+ assertEquals(8L * 1024 * 1024, ((Number) getter(evidence, "getStdoutCapturedBytes")).longValue());
+ assertTrue(((Number) getter(evidence, "getStdoutObservedBytes")).longValue() > 8L * 1024 * 1024);
+ assertEquals(true, getter(evidence, "isStdoutTruncated"));
+ assertFalse(partial.isSuccess());
+ }
+
+ @Test
+ void stderrHasItsOwnSmallerBudget() {
+ OpenCliException failure = assertThrows(OpenCliException.class,
+ () -> new OpenCliExecutor(properties(1)).invoke("stderr", Integer.toString(3 * 1024 * 1024)));
+ Object evidence = details(failure.getPartialResult());
+ assertEquals("OUTPUT_LIMIT", String.valueOf(getter(evidence, "getTerminationReason")));
+ assertEquals(2L * 1024 * 1024, ((Number) getter(evidence, "getStderrCapturedBytes")).longValue());
+ assertEquals(true, getter(evidence, "isStderrTruncated"));
+ }
+
+ @Test
+ void interruptionStopsTheOwnedHeartbeatAndRestoresFlag() throws Exception {
+ OpenCliExecutor executor = new OpenCliExecutor(properties(1));
+ Path heartbeat = dir.resolve("heartbeat");
+ Path gate = dir.resolve("release");
+ AtomicBoolean restored = new AtomicBoolean();
+ AtomicReference error = new AtomicReference<>();
+ Thread caller = new Thread(() -> {
+ try { executor.invoke("heartbeat", heartbeat.toString(), gate.toString()); }
+ catch (Throwable failure) { error.set(failure); restored.set(Thread.currentThread().isInterrupted()); }
+ }, "contract-interrupted-caller");
+ try {
+ caller.start();
+ assertTrue(awaitFile(heartbeat, 3000));
+ Thread.sleep(80L);
+ caller.interrupt();
+ caller.join(1500L);
+ assertFalse(caller.isAlive(), "interrupted call did not finish cleanup");
+ assertTrue(error.get() instanceof OpenCliException);
+ assertTrue(restored.get(), "caller interrupt flag was lost");
+ String observed = new String(Files.readAllBytes(heartbeat), StandardCharsets.UTF_8);
+ Thread.sleep(250L);
+ assertEquals(observed, new String(Files.readAllBytes(heartbeat), StandardCharsets.UTF_8),
+ "owned child kept running after interrupted call returned");
+ OpenCliException failure = (OpenCliException) error.get();
+ assertEquals("CANCELLED", String.valueOf(getter(details(failure.getPartialResult()), "getTerminationReason")));
+ assertEquals("ROOT_EXIT_CONFIRMED", String.valueOf(getter(details(failure.getPartialResult()), "getCleanupState")));
+ Path next = dir.resolve("next");
+ assertTrue(executor.invoke("write", next.toString()).isSuccess(), "permit leaked after cancellation");
+ } finally {
+ release(gate);
+ caller.interrupt();
+ caller.join(5000L);
+ }
+ }
+
+ @Test
+ void negativeConcurrencyIsNotSilentlyTreatedAsDefault() {
+ assertThrows(IllegalArgumentException.class, () -> new OpenCliExecutor(properties(-1)));
+ }
+
+ @Test
+ void explicitSharedRuntimeLimitsBothClients() throws Exception {
+ Class> runtimeType = assertDoesNotThrow(() -> Class.forName("io.github.easy4j.opencli.core.OpenCliProcessRuntime"));
+ Object runtime = runtimeType.getConstructor(int.class).newInstance(1);
+ OpenCliExecutor a = OpenCliExecutor.class.getConstructor(OpenCliProperties.class, runtimeType)
+ .newInstance(properties(4), runtime);
+ OpenCliExecutor b = OpenCliExecutor.class.getConstructor(OpenCliProperties.class, runtimeType)
+ .newInstance(properties(4), runtime);
+ Path first = dir.resolve("shared-first");
+ Path second = dir.resolve("shared-second");
+ Path gate = dir.resolve("release");
+ ExecutorService workers = Executors.newFixedThreadPool(2);
+ try {
+ Future one = workers.submit(() -> a.invoke("hold", first.toString(), gate.toString()));
+ assertTrue(awaitFile(first, 3000));
+ Future two = workers.submit(() -> b.invoke("write", second.toString()));
+ assertFalse(awaitFile(second, 500), "shared runtime did not enforce its one permit");
+ release(gate);
+ assertTrue(one.get(5, TimeUnit.SECONDS).isSuccess());
+ assertTrue(two.get(5, TimeUnit.SECONDS).isSuccess());
+ } finally {
+ release(gate);
+ workers.shutdownNow();
+ assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));
+ }
+ }
+
+ @Test
+ void preCancelledRequestNeverStartsAProcess() throws Exception {
+ Class> tokenType = assertDoesNotThrow(() -> Class.forName("io.github.easy4j.opencli.core.OpenCliCancellationToken"));
+ Object token = tokenType.getConstructor().newInstance();
+ tokenType.getMethod("cancel").invoke(token);
+ Path marker = dir.resolve("pre-cancelled");
+ OpenCliExecutor executor = new OpenCliExecutor(properties(1));
+ java.lang.reflect.InvocationTargetException failure = assertThrows(java.lang.reflect.InvocationTargetException.class,
+ () -> OpenCliExecutor.class.getMethod("invoke", List.class, tokenType)
+ .invoke(executor, Arrays.asList("write", marker.toString()), token));
+ assertTrue(failure.getCause() instanceof OpenCliException);
+ OpenCliResult partial = ((OpenCliException) failure.getCause()).getPartialResult();
+ assertEquals("CANCELLED", String.valueOf(getter(details(partial), "getTerminationReason")));
+ assertEquals(false, getter(details(partial), "isProcessStarted"));
+ assertNull(partial.getExitCode());
+ assertFalse(Files.exists(marker));
+ }
+}
diff --git a/src/test/java/io/github/easy4j/opencli/contract/OpenCliStructuredArgvContractTest.java b/src/test/java/io/github/easy4j/opencli/contract/OpenCliStructuredArgvContractTest.java
new file mode 100644
index 0000000..c23685d
--- /dev/null
+++ b/src/test/java/io/github/easy4j/opencli/contract/OpenCliStructuredArgvContractTest.java
@@ -0,0 +1,180 @@
+package io.github.easy4j.opencli.contract;
+
+import io.github.easy4j.opencli.OpenCliProperties;
+import io.github.easy4j.opencli.core.OpenCliAdapterChannel;
+import io.github.easy4j.opencli.core.OpenCliAdapterCommandRequest;
+import io.github.easy4j.opencli.core.OpenCliExecutor;
+import io.github.easy4j.opencli.core.OpenCliResult;
+import java.io.File;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.*;
+
+/** Public binary/API contract: missing methods fail assertions rather than preventing the RED build. */
+class OpenCliStructuredArgvContractTest {
+ private static Class> type(String simpleName) {
+ return assertDoesNotThrow(() -> Class.forName("io.github.easy4j.opencli.core." + simpleName),
+ "required ordered-option API is not implemented");
+ }
+
+ private static Object call(Class> owner, Object receiver, String name, Class>[] parameterTypes, Object... args) {
+ Method method = assertDoesNotThrow(() -> owner.getMethod(name, parameterTypes),
+ "required public method is not implemented: " + name);
+ try {
+ return method.invoke(receiver, args);
+ } catch (InvocationTargetException ex) {
+ Throwable cause = ex.getCause();
+ if (cause instanceof RuntimeException) {
+ throw (RuntimeException) cause;
+ }
+ throw new AssertionError("unexpected checked failure", cause);
+ } catch (ReflectiveOperationException ex) {
+ throw new AssertionError("public API is inaccessible", ex);
+ }
+ }
+
+ private static Object schema(String form, String name, boolean repeatable) {
+ Class> owner = type("OpenCliOptionSchema");
+ return "value".equals(form)
+ ? call(owner, null, form, new Class>[]{String.class, boolean.class}, name, repeatable)
+ : call(owner, null, form, new Class>[]{String.class}, name);
+ }
+
+ private static Object value(Object definition, Object value) {
+ return call(type("OpenCliOption"), null, "value",
+ new Class>[]{type("OpenCliOptionSchema"), Object.class}, definition, value);
+ }
+
+ private static Object flag(String form, Object definition) {
+ return call(type("OpenCliOption"), null, form,
+ new Class>[]{type("OpenCliOptionSchema")}, definition);
+ }
+
+ private static void add(Object builder, Object occurrence) {
+ call(builder.getClass(), builder, "option", new Class>[]{type("OpenCliOption")}, occurrence);
+ }
+
+ private static List run(OpenCliAdapterCommandRequest request) {
+ OpenCliProperties p = new OpenCliProperties();
+ String exe = System.getProperty("os.name").startsWith("Windows") ? "java.exe" : "java";
+ p.setExecutable(new File(new File(System.getProperty("java.home"), "bin"), exe).getAbsolutePath());
+ p.setLeadingArguments(new ArrayList<>(Arrays.asList("-cp",
+ System.getProperty("surefire.test.class.path", System.getProperty("java.class.path")),
+ ContractProbe.class.getName())));
+ p.setCommandTimeoutMillis(10000L);
+ OpenCliResult result = new OpenCliAdapterChannel(new OpenCliExecutor(p), "demo").invoke(request);
+ assertTrue(result.isSuccess());
+ String[] lines = result.getStdout().split("\r?\n");
+ List actual = new ArrayList<>();
+ for (int i = 1; i < lines.length; i++) {
+ assertTrue(lines[i].startsWith("arg:"));
+ actual.add(new String(Base64.getDecoder().decode(lines[i].substring(4)), StandardCharsets.UTF_8));
+ }
+ assertEquals("argc:" + actual.size(), lines[0]);
+ return actual;
+ }
+
+ @Test
+ void orderedRepeatedValuesAndExplicitFalseReachChild() {
+ Object tags = schema("value", "--tag", true);
+ Object enabled = schema("value", "--enabled", false);
+ OpenCliAdapterCommandRequest.OpenCliAdapterCommandRequestBuilder b = OpenCliAdapterCommandRequest.builder().subcommand("echo");
+ add(b, value(tags, " A "));
+ add(b, value(enabled, false));
+ add(b, value(tags, ""));
+ assertEquals(Arrays.asList("demo", "echo", "--tag", " A ", "--enabled", "false", "--tag", ""), run(b.build()));
+ }
+
+ @Test
+ void explicitNegationIsDifferentFromAbsenceAndPresence() {
+ Object cache = schema("negatableFlag", "--cache", false);
+ OpenCliAdapterCommandRequest.OpenCliAdapterCommandRequestBuilder b = OpenCliAdapterCommandRequest.builder().subcommand("echo");
+ add(b, flag("negated", cache));
+ assertEquals(Arrays.asList("demo", "echo", "--no-cache"), run(b.build()));
+ OpenCliAdapterCommandRequest.OpenCliAdapterCommandRequestBuilder present = OpenCliAdapterCommandRequest.builder().subcommand("echo");
+ add(present, flag("present", cache));
+ assertEquals(Arrays.asList("demo", "echo", "--cache"), run(present.build()));
+ assertEquals(Arrays.asList("demo", "echo"), run(OpenCliAdapterCommandRequest.builder().subcommand("echo").build()));
+ }
+
+ @Test
+ void flagSchemaCannotSilentlyConsumeAValue() {
+ Object verbose = schema("flag", "--verbose", false);
+ assertThrows(IllegalArgumentException.class, () -> value(verbose, false));
+ assertThrows(IllegalArgumentException.class, () -> flag("negated", verbose));
+ }
+
+ @Test
+ void nonrepeatableOptionCannotAppearTwice() {
+ Object once = schema("value", "--limit", false);
+ OpenCliAdapterCommandRequest.OpenCliAdapterCommandRequestBuilder b = OpenCliAdapterCommandRequest.builder().subcommand("echo");
+ add(b, value(once, 1));
+ add(b, value(once, 2));
+ assertThrows(IllegalArgumentException.class, () -> b.build().toSubcommandAndArgs());
+ }
+
+ @Test
+ void legacyAndOrderedOptionsCannotCollide() {
+ Object limit = schema("value", "--limit", true);
+ OpenCliAdapterCommandRequest.OpenCliAdapterCommandRequestBuilder b = OpenCliAdapterCommandRequest.builder().subcommand("echo")
+ .options(Collections.singletonMap("limit", "1"));
+ add(b, value(limit, "2"));
+ assertThrows(IllegalArgumentException.class, () -> b.build().toSubcommandAndArgs());
+ }
+
+ @Test
+ void mutableOccurrenceValueIsCapturedWhenCreated() {
+ StringBuilder text = new StringBuilder(" before ");
+ Object occurrence = value(schema("value", "--text", false), text);
+ text.append("after");
+ OpenCliAdapterCommandRequest.OpenCliAdapterCommandRequestBuilder b = OpenCliAdapterCommandRequest.builder().subcommand("echo");
+ add(b, occurrence);
+ assertEquals(Arrays.asList("demo", "echo", "--text", " before "), run(b.build()));
+ }
+
+ @Test
+ void malformedSchemaIdentifiersAreRejected() {
+ Class> owner = type("OpenCliOptionSchema");
+ assertThrows(IllegalArgumentException.class,
+ () -> call(owner, null, "flag", new Class>[]{String.class}, "--x y"));
+ assertThrows(IllegalArgumentException.class,
+ () -> call(owner, null, "flag", new Class>[]{String.class}, ""));
+ }
+
+ @Test
+ void legacyMapIsCapturedRatherThanAliased() {
+ Map options = new LinkedHashMap<>();
+ options.put("text", " before ");
+ OpenCliAdapterCommandRequest request = OpenCliAdapterCommandRequest.builder().subcommand("echo").options(options).build();
+ options.put("text", "after");
+ assertEquals(Arrays.asList("demo", "echo", "--text", " before "), run(request));
+ }
+
+ @Test
+ void mutableLegacyValueCannotChangeAnExistingRequest() {
+ StringBuilder text = new StringBuilder(" before ");
+ OpenCliAdapterCommandRequest request = OpenCliAdapterCommandRequest.builder().subcommand("echo")
+ .options(Collections.singletonMap("text", text)).build();
+ text.append("after");
+ assertEquals(Arrays.asList("demo", "echo", "--text", " before "), run(request));
+ }
+
+ @Test
+ void reusingBuilderDoesNotMutatePreviousRequest() {
+ Object tags = schema("value", "--tag", true);
+ OpenCliAdapterCommandRequest.OpenCliAdapterCommandRequestBuilder b = OpenCliAdapterCommandRequest.builder().subcommand("echo");
+ add(b, value(tags, "A"));
+ OpenCliAdapterCommandRequest first = b.build();
+ add(b, value(tags, "B"));
+ assertEquals(Arrays.asList("demo", "echo", "--tag", "A"), run(first));
+ }
+}
diff --git a/src/test/java/io/github/easy4j/opencli/core/OpenCliAdapterCommandRequestTest.java b/src/test/java/io/github/easy4j/opencli/core/OpenCliAdapterCommandRequestTest.java
index 8f2c36b..3798564 100644
--- a/src/test/java/io/github/easy4j/opencli/core/OpenCliAdapterCommandRequestTest.java
+++ b/src/test/java/io/github/easy4j/opencli/core/OpenCliAdapterCommandRequestTest.java
@@ -6,6 +6,33 @@
class OpenCliAdapterCommandRequestTest {
+ @Test
+ void shouldRejectLegacyOptionWithNullStringFormBeforeSnapshot() {
+ Map opts = new LinkedHashMap<>();
+ opts.put("--value", new Object() {
+ @Override
+ public String toString() {
+ return null;
+ }
+ });
+
+ assertThrows(IllegalArgumentException.class,
+ () -> OpenCliAdapterCommandRequest.builder().subcommand("ask").options(opts));
+ }
+
+ @Test
+ void shouldRejectOrderedOptionWithNullStringForm() {
+ Object value = new Object() {
+ @Override
+ public String toString() {
+ return null;
+ }
+ };
+
+ assertThrows(IllegalArgumentException.class,
+ () -> OpenCliOption.value(OpenCliOptionSchema.value("--value", false), value));
+ }
+
@Test
void shouldBuildWithPositionals() {
OpenCliAdapterCommandRequest req = OpenCliAdapterCommandRequest.builder()
@@ -116,7 +143,7 @@ void shouldReturnImmutableOptions() {
}
@Test
- void shouldSkipNullPositionalInToSubcommandAndArgs() {
+ void shouldPreserveEmptyPositionalInToSubcommandAndArgs() {
OpenCliAdapterCommandRequest req = OpenCliAdapterCommandRequest.builder()
.subcommand("sub")
.positional("a")
@@ -124,7 +151,7 @@ void shouldSkipNullPositionalInToSubcommandAndArgs() {
.positional("b")
.build();
List argv = req.toSubcommandAndArgs();
- assertEquals(Arrays.asList("sub", "a", "b"), argv);
+ assertEquals(Arrays.asList("sub", "a", "", "b"), argv);
}
@Test
diff --git a/src/test/java/io/github/easy4j/opencli/core/OpenCliArgSupportTest.java b/src/test/java/io/github/easy4j/opencli/core/OpenCliArgSupportTest.java
index f5efc59..20f0abc 100644
--- a/src/test/java/io/github/easy4j/opencli/core/OpenCliArgSupportTest.java
+++ b/src/test/java/io/github/easy4j/opencli/core/OpenCliArgSupportTest.java
@@ -4,6 +4,7 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+import java.util.UUID;
import org.junit.jupiter.api.Test;
class OpenCliArgSupportTest {
@@ -15,9 +16,15 @@ void shouldMergeNonNullLists() {
}
@Test
- void shouldFilterNullAndBlankWhenMerging() {
- List result = OpenCliArgSupport.merge(Arrays.asList("a", null, "", " ", "b"), Arrays.asList("c"));
- assertEquals(Arrays.asList("a", "b", "c"), result);
+ void shouldRejectNullElementWhenMerging() {
+ assertThrows(IllegalArgumentException.class,
+ () -> OpenCliArgSupport.merge(Arrays.asList("a", null, "", " ", "b"), Arrays.asList("c")));
+ }
+
+ @Test
+ void shouldPreserveEmptyAndBlankWhenMerging() {
+ assertEquals(Arrays.asList("a", "", " ", "b", "c"),
+ OpenCliArgSupport.merge(Arrays.asList("a", "", " ", "b"), Arrays.asList("c")));
}
@Test
@@ -56,7 +63,12 @@ void shouldAddOptionEqualsStrippingTrailingEquals() {
@Test
void shouldThrowWhenNameDoesNotStartWithDash() {
List target = new ArrayList<>();
- assertThrows(IllegalArgumentException.class, () -> OpenCliArgSupport.addOptionEquals(target, "key", "value"));
+ String optionCanary = "private-option-" + UUID.randomUUID();
+ IllegalArgumentException failure = assertThrows(IllegalArgumentException.class,
+ () -> OpenCliArgSupport.addOptionEquals(target, optionCanary, "value"));
+ assertTrue(failure.getMessage().contains("must start with '--'"));
+ assertFalse(failure.toString().contains(optionCanary));
+ assertTrue(target.isEmpty());
}
@Test
@@ -80,6 +92,21 @@ void shouldNotAddOptionPairIfPresentWhenValueNull() {
assertTrue(target.isEmpty());
}
+ @Test
+ void shouldRejectNonNullValueWhoseStringFormIsNull() {
+ List target = new ArrayList<>();
+ Object value = new Object() {
+ @Override
+ public String toString() {
+ return null;
+ }
+ };
+
+ assertThrows(IllegalArgumentException.class,
+ () -> OpenCliArgSupport.addOptionPairIfPresent(target, "--flag", value));
+ assertTrue(target.isEmpty());
+ }
+
@Test
void shouldAddFlagIfTrue() {
List target = new ArrayList<>();
diff --git a/src/test/java/io/github/easy4j/opencli/core/OpenCliExecutorFullTest.java b/src/test/java/io/github/easy4j/opencli/core/OpenCliExecutorFullTest.java
index ed0cfba..163f873 100644
--- a/src/test/java/io/github/easy4j/opencli/core/OpenCliExecutorFullTest.java
+++ b/src/test/java/io/github/easy4j/opencli/core/OpenCliExecutorFullTest.java
@@ -3,6 +3,7 @@
import static org.junit.jupiter.api.Assertions.*;
import io.github.easy4j.opencli.OpenCliExecutionTarget;
import io.github.easy4j.opencli.OpenCliProperties;
+import io.github.easy4j.opencli.exception.OpenCliException;
import java.util.Arrays;
import org.apache.commons.exec.CommandLine;
import org.junit.jupiter.api.Test;
@@ -35,19 +36,23 @@ void shouldAppendQuotedKeyValueWithTrailingEquals() {
}
@Test
- void shouldTruncateOversizedOutputWithMarker() {
+ void shouldReportBoundedOutputLimitWithPartialEvidence() {
OpenCliProperties props = new OpenCliProperties();
props.setExecutable("/bin/sh");
props.setMaxOutputBytes(64L);
props.setCommandTimeoutMillis(30_000L);
OpenCliExecutor executor = new OpenCliExecutor(props);
- OpenCliResult result = executor.invoke("-c",
- "printf 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'");
-
- assertTrue(result.isSuccess(), "truncation must not fail the run");
- assertTrue(result.getStdout().contains("truncated"),
- "overflow must leave a truncation marker: " + result.getStdout());
+ OpenCliException failure = assertThrows(OpenCliException.class, () -> executor.invoke("-c",
+ "printf 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'"));
+ OpenCliResult result = failure.getPartialResult();
+ assertNotNull(result);
+ assertFalse(result.isSuccess());
+ assertEquals(OpenCliExecutionDetails.TerminationReason.OUTPUT_LIMIT,
+ result.getExecutionDetails().getTerminationReason());
+ assertTrue(result.getExecutionDetails().isStdoutTruncated());
+ assertEquals(64L, result.getExecutionDetails().getStdoutCapturedBytes());
+ assertEquals(64, result.getStdout().getBytes(java.nio.charset.StandardCharsets.UTF_8).length);
}
@Test
diff --git a/src/test/java/io/github/easy4j/opencli/core/support/SubprocessCleanupFaultTest.java b/src/test/java/io/github/easy4j/opencli/core/support/SubprocessCleanupFaultTest.java
new file mode 100644
index 0000000..79fd220
--- /dev/null
+++ b/src/test/java/io/github/easy4j/opencli/core/support/SubprocessCleanupFaultTest.java
@@ -0,0 +1,292 @@
+package io.github.easy4j.opencli.core.support;
+
+import io.github.easy4j.opencli.core.OpenCliCancellationToken;
+import io.github.easy4j.opencli.core.OpenCliExecutionDetails.CleanupState;
+import io.github.easy4j.opencli.core.OpenCliExecutionDetails.TerminationReason;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.commons.exec.CommandLine;
+import org.apache.commons.exec.ExecuteWatchdog;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import static org.junit.jupiter.api.Assertions.*;
+
+/** Fault injection for cleanup operations after an invocation-owned child starts. */
+@Timeout(5)
+class SubprocessCleanupFaultTest {
+ @Test
+ void destroyFailureStillForcesOwnedChildAndReleasesPermit() throws Exception {
+ assertCleanupSurvives(false, true);
+ }
+
+ @Test
+ void watchdogStopFailureStillCleansOwnedChildAndReleasesPermit() throws Exception {
+ assertCleanupSurvives(true, false);
+ }
+
+ @Test
+ void watchdogStartFailureStillCleansOwnedChildAndReleasesPermit() throws Exception {
+ int[] starts = new int[1];
+ FakeProcess[] last = new FakeProcess[1];
+ SubprocessExecutionSupport.Runtime runtime = new SubprocessExecutionSupport.Runtime(1,
+ builder -> {
+ starts[0]++;
+ last[0] = new FakeProcess(false);
+ return last[0];
+ }, timeout -> new FakeWatchdog(false, true));
+
+ for (int attempt = 0; attempt < 2; attempt++) {
+ SubprocessExecutionSupport.ExecutionRequest request = new SubprocessExecutionSupport.ExecutionRequest(
+ CommandLine.parse("fake"), null, null, 1000L, 16, 16, 200L,
+ System.nanoTime(), new OpenCliCancellationToken());
+
+ SubprocessExecutionSupport.RunSession session = runtime.execute(request);
+
+ assertEquals(TerminationReason.IO_FAILURE,
+ session.getExecutionDetails().getTerminationReason());
+ assertInstanceOf(IllegalStateException.class, session.getIoFailure().getCause());
+ assertEquals(CleanupState.ROOT_EXIT_CONFIRMED,
+ session.getExecutionDetails().getCleanupState());
+ assertFalse(last[0].isAlive());
+ assertFalse(runtime.isQuarantined());
+ }
+ assertEquals(2, starts[0]);
+ }
+
+ @Test
+ void watchdogCreationFailureAfterSpawnStillCleansChildAndReleasesPermit() throws Exception {
+ int[] starts = new int[1];
+ FakeProcess[] last = new FakeProcess[1];
+ SubprocessExecutionSupport.Runtime runtime = new SubprocessExecutionSupport.Runtime(1,
+ builder -> {
+ starts[0]++;
+ last[0] = new FakeProcess(false);
+ return last[0];
+ }, timeout -> {
+ assertNotNull(last[0], "watchdog must be created after spawn");
+ throw new IllegalStateException("injected watchdog creation failure");
+ });
+
+ for (int attempt = 0; attempt < 2; attempt++) {
+ SubprocessExecutionSupport.ExecutionRequest request = new SubprocessExecutionSupport.ExecutionRequest(
+ CommandLine.parse("fake"), null, null, 1000L, 16, 16, 200L,
+ System.nanoTime(), new OpenCliCancellationToken());
+
+ SubprocessExecutionSupport.RunSession session = runtime.execute(request);
+
+ assertEquals(TerminationReason.IO_FAILURE,
+ session.getExecutionDetails().getTerminationReason());
+ assertInstanceOf(IllegalStateException.class, session.getIoFailure().getCause());
+ assertEquals(CleanupState.ROOT_EXIT_CONFIRMED,
+ session.getExecutionDetails().getCleanupState());
+ assertFalse(last[0].isAlive());
+ assertFalse(runtime.isQuarantined());
+ }
+ assertEquals(2, starts[0]);
+ }
+
+ @Test
+ void processStreamSetupFailureStillCleansChildAndReleasesPermit() throws Exception {
+ int[] starts = new int[1];
+ FakeProcess[] last = new FakeProcess[1];
+ SubprocessExecutionSupport.Runtime runtime = new SubprocessExecutionSupport.Runtime(1,
+ builder -> {
+ starts[0]++;
+ last[0] = new FakeProcess(false, false, true);
+ return last[0];
+ }, timeout -> new FakeWatchdog(false));
+
+ for (int attempt = 0; attempt < 2; attempt++) {
+ SubprocessExecutionSupport.ExecutionRequest request = new SubprocessExecutionSupport.ExecutionRequest(
+ CommandLine.parse("fake"), null, null, 1000L, 16, 16, 200L,
+ System.nanoTime(), new OpenCliCancellationToken());
+
+ SubprocessExecutionSupport.RunSession session = runtime.execute(request);
+
+ assertEquals(TerminationReason.IO_FAILURE,
+ session.getExecutionDetails().getTerminationReason());
+ assertInstanceOf(IllegalStateException.class, session.getIoFailure().getCause());
+ assertEquals(CleanupState.ROOT_EXIT_CONFIRMED,
+ session.getExecutionDetails().getCleanupState());
+ assertFalse(last[0].isAlive());
+ assertFalse(runtime.isQuarantined());
+ }
+ assertEquals(2, starts[0]);
+ }
+
+ @Test
+ void unconfirmedForcedStopQuarantinesRuntimeWithoutFabricatingExit() throws Exception {
+ OpenCliCancellationToken token = new OpenCliCancellationToken();
+ int[] starts = new int[1];
+ SubprocessExecutionSupport.Runtime runtime = new SubprocessExecutionSupport.Runtime(1,
+ builder -> {
+ starts[0]++;
+ token.cancel();
+ return new FakeProcess(true, true);
+ }, timeout -> new FakeWatchdog(false));
+ SubprocessExecutionSupport.ExecutionRequest request = new SubprocessExecutionSupport.ExecutionRequest(
+ CommandLine.parse("fake"), null, null, 1000L, 16, 16, 50L,
+ System.nanoTime(), token);
+
+ SubprocessExecutionSupport.RunSession session = runtime.execute(request);
+
+ assertEquals(TerminationReason.CANCELLED,
+ session.getExecutionDetails().getTerminationReason());
+ assertEquals(CleanupState.UNCONFIRMED,
+ session.getExecutionDetails().getCleanupState());
+ assertTrue(session.getExecutionDetails().isCleanupOperationFailed());
+ assertNull(session.getObservedExitCode());
+ assertTrue(runtime.isQuarantined());
+ SubprocessExecutionSupport.ExecutionRequest next = new SubprocessExecutionSupport.ExecutionRequest(
+ CommandLine.parse("fake"), null, null, 1000L, 16, 16, 50L,
+ System.nanoTime(), new OpenCliCancellationToken());
+ assertEquals(TerminationReason.RUNTIME_UNAVAILABLE,
+ runtime.execute(next).getExecutionDetails().getTerminationReason());
+ assertEquals(1, starts[0]);
+ }
+
+ @Test
+ void cancelledSubmissionDoesNotInitializeWatchdogOrSpawn() throws Exception {
+ OpenCliCancellationToken token = new OpenCliCancellationToken();
+ token.cancel();
+ SubprocessExecutionSupport.Runtime runtime = new SubprocessExecutionSupport.Runtime(1,
+ builder -> fail("cancelled submission must not spawn"),
+ timeout -> fail("cancelled submission must not initialize a watchdog"));
+ SubprocessExecutionSupport.ExecutionRequest request = new SubprocessExecutionSupport.ExecutionRequest(
+ CommandLine.parse("fake"), null, null, 1000L, 16, 16, 200L, System.nanoTime(), token);
+
+ SubprocessExecutionSupport.RunSession session = runtime.execute(request);
+
+ assertEquals(TerminationReason.CANCELLED, session.getExecutionDetails().getTerminationReason());
+ assertEquals(CleanupState.NOT_STARTED, session.getExecutionDetails().getCleanupState());
+ assertNull(session.getObservedExitCode());
+ assertNotNull(session.getWatchdog());
+ }
+
+ private static void assertCleanupSurvives(boolean failStop, boolean failDestroy) throws Exception {
+ OpenCliCancellationToken token = new OpenCliCancellationToken();
+ AtomicReference currentToken = new AtomicReference<>(token);
+ FakeProcess[] last = new FakeProcess[1];
+ SubprocessExecutionSupport.Runtime runtime = new SubprocessExecutionSupport.Runtime(1,
+ builder -> {
+ last[0] = new FakeProcess(failDestroy);
+ currentToken.get().cancel();
+ return last[0];
+ }, timeout -> new FakeWatchdog(failStop));
+ SubprocessExecutionSupport.ExecutionRequest request = new SubprocessExecutionSupport.ExecutionRequest(
+ CommandLine.parse("fake"), null, null, 1000L, 16, 16, 200L,
+ System.nanoTime(), token);
+
+ SubprocessExecutionSupport.RunSession session = runtime.execute(request);
+
+ assertEquals(TerminationReason.CANCELLED,
+ session.getExecutionDetails().getTerminationReason());
+ assertEquals(CleanupState.ROOT_EXIT_CONFIRMED,
+ session.getExecutionDetails().getCleanupState());
+ assertTrue(session.getExecutionDetails().isCleanupOperationFailed());
+ assertFalse(last[0].isAlive());
+ assertFalse(runtime.isQuarantined());
+
+ OpenCliCancellationToken nextToken = new OpenCliCancellationToken();
+ currentToken.set(nextToken);
+ SubprocessExecutionSupport.ExecutionRequest next = new SubprocessExecutionSupport.ExecutionRequest(
+ CommandLine.parse("fake"), null, null, 1000L, 16, 16, 200L,
+ System.nanoTime(), nextToken);
+ assertNotEquals(TerminationReason.QUEUE_TIMEOUT,
+ runtime.execute(next).getExecutionDetails().getTerminationReason());
+ }
+
+ private static final class FakeWatchdog extends ExecuteWatchdog {
+ private final boolean failStop;
+ private final boolean failStart;
+
+ FakeWatchdog(boolean failStop) {
+ this(failStop, false);
+ }
+
+ FakeWatchdog(boolean failStop, boolean failStart) {
+ super(1000L);
+ this.failStop = failStop;
+ this.failStart = failStart;
+ }
+
+ @Override
+ public synchronized void start(Process process) {
+ if (failStart) {
+ throw new IllegalStateException("injected watchdog start failure");
+ }
+ }
+
+ @Override
+ public synchronized void stop() {
+ if (failStop) {
+ throw new IllegalStateException("injected watchdog stop failure");
+ }
+ }
+
+ @Override
+ public synchronized boolean killedProcess() { return false; }
+ }
+
+ private static final class FakeProcess extends Process {
+ private final boolean failDestroy;
+ private boolean alive = true;
+
+ private final boolean failForce;
+ private final boolean failStreamSetup;
+
+ FakeProcess(boolean failDestroy) { this(failDestroy, false, false); }
+
+ FakeProcess(boolean failDestroy, boolean failForce) {
+ this(failDestroy, failForce, false);
+ }
+
+ FakeProcess(boolean failDestroy, boolean failForce, boolean failStreamSetup) {
+ this.failDestroy = failDestroy;
+ this.failForce = failForce;
+ this.failStreamSetup = failStreamSetup;
+ }
+
+ @Override
+ public OutputStream getOutputStream() {
+ if (failStreamSetup) {
+ throw new IllegalStateException("injected process stream setup failure");
+ }
+ return new ByteArrayOutputStream();
+ }
+
+ @Override
+ public InputStream getInputStream() { return new ByteArrayInputStream(new byte[0]); }
+
+ @Override
+ public InputStream getErrorStream() { return new ByteArrayInputStream(new byte[0]); }
+
+ @Override
+ public int waitFor() { return 143; }
+
+ @Override
+ public int exitValue() {
+ if (alive) { throw new IllegalThreadStateException(); }
+ return 143;
+ }
+
+ @Override
+ public void destroy() {
+ if (failDestroy) { throw new IllegalStateException("injected process destroy failure"); }
+ alive = false;
+ }
+
+ @Override
+ public Process destroyForcibly() {
+ if (failForce) { throw new IllegalStateException("injected forced stop failure"); }
+ alive = false;
+ return this;
+ }
+
+ @Override
+ public boolean isAlive() { return alive; }
+ }
+}
diff --git a/src/test/java/io/github/easy4j/opencli/core/support/SubprocessCompletionRaceTest.java b/src/test/java/io/github/easy4j/opencli/core/support/SubprocessCompletionRaceTest.java
new file mode 100644
index 0000000..c52b42c
--- /dev/null
+++ b/src/test/java/io/github/easy4j/opencli/core/support/SubprocessCompletionRaceTest.java
@@ -0,0 +1,190 @@
+package io.github.easy4j.opencli.core.support;
+
+import io.github.easy4j.opencli.core.OpenCliCancellationToken;
+import io.github.easy4j.opencli.core.OpenCliExecutionDetails.CleanupState;
+import io.github.easy4j.opencli.core.OpenCliExecutionDetails.TerminationReason;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.commons.exec.CommandLine;
+import org.apache.commons.exec.ExecuteWatchdog;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** Verifies terminal evidence when cancellation, watchdog expiry and natural exit coincide. */
+@Timeout(10)
+class SubprocessCompletionRaceTest {
+
+ @Test
+ void simultaneousSignalsKeepOneResultAndReuseThePermit() throws Exception {
+ AtomicInteger starts = new AtomicInteger();
+ AtomicReference currentToken = new AtomicReference<>();
+ SubprocessExecutionSupport.Runtime runtime = new SubprocessExecutionSupport.Runtime(1,
+ builder -> {
+ starts.incrementAndGet();
+ currentToken.get().cancel();
+ return new ExitedProcess("partial");
+ }, timeout -> new ExpiredWatchdog());
+
+ for (int attempt = 0; attempt < 32; attempt++) {
+ OpenCliCancellationToken token = new OpenCliCancellationToken();
+ currentToken.set(token);
+ SubprocessExecutionSupport.ExecutionRequest request = new SubprocessExecutionSupport.ExecutionRequest(
+ CommandLine.parse("fake"), null, null, 1_000L, 32, 32, 100L,
+ System.nanoTime(), token);
+ SubprocessExecutionSupport.RunSession session = runtime.execute(request);
+
+ assertEquals(TerminationReason.CANCELLED,
+ session.getExecutionDetails().getTerminationReason());
+ assertEquals(CleanupState.ROOT_EXIT_CONFIRMED,
+ session.getExecutionDetails().getCleanupState());
+ assertEquals(0, session.getObservedExitCode());
+ assertEquals("partial", session.getStdout().toString(StandardCharsets.UTF_8.name()));
+ assertEquals(7, session.getExecutionDetails().getStdoutCapturedBytes());
+ assertTrue(session.getExecutionDetails().isStreamsDrained());
+ assertFalse(runtime.isQuarantined());
+ }
+ assertEquals(32, starts.get());
+ }
+
+ @Test
+ void interruptedRunnerCleansOwnedChildRestoresFlagAndReusesPermit() throws Exception {
+ CountDownLatch childRunning = new CountDownLatch(1);
+ AtomicInteger starts = new AtomicInteger();
+ AtomicReference currentToken = new AtomicReference<>();
+ AtomicReference firstProcess = new AtomicReference<>();
+ AtomicReference firstResult = new AtomicReference<>();
+ AtomicReference failure = new AtomicReference<>();
+ AtomicBoolean interruptRestored = new AtomicBoolean();
+ SubprocessExecutionSupport.Runtime runtime = new SubprocessExecutionSupport.Runtime(1,
+ builder -> {
+ if (starts.incrementAndGet() == 1) {
+ LiveProcess process = new LiveProcess();
+ firstProcess.set(process);
+ return process;
+ }
+ currentToken.get().cancel();
+ return new ExitedProcess("second");
+ }, timeout -> new ExecuteWatchdog(timeout) {
+ @Override
+ public synchronized void start(Process process) { childRunning.countDown(); }
+
+ @Override
+ public synchronized boolean killedProcess() { return false; }
+ });
+ OpenCliCancellationToken firstToken = new OpenCliCancellationToken();
+ currentToken.set(firstToken);
+ Thread runner = new Thread(() -> {
+ try {
+ firstResult.set(runtime.execute(new SubprocessExecutionSupport.ExecutionRequest(
+ CommandLine.parse("fake"), null, null, 2_000L, 32, 32, 100L,
+ System.nanoTime(), firstToken)));
+ interruptRestored.set(Thread.currentThread().isInterrupted());
+ } catch (Throwable ex) {
+ failure.set(ex);
+ }
+ });
+
+ runner.start();
+ assertTrue(childRunning.await(2, TimeUnit.SECONDS));
+ runner.interrupt();
+ runner.join(2_000L);
+
+ assertFalse(runner.isAlive());
+ assertNull(failure.get());
+ assertEquals(TerminationReason.CANCELLED,
+ firstResult.get().getExecutionDetails().getTerminationReason());
+ assertEquals(CleanupState.ROOT_EXIT_CONFIRMED,
+ firstResult.get().getExecutionDetails().getCleanupState());
+ assertFalse(firstProcess.get().isAlive());
+ assertTrue(interruptRestored.get());
+
+ OpenCliCancellationToken nextToken = new OpenCliCancellationToken();
+ currentToken.set(nextToken);
+ SubprocessExecutionSupport.RunSession next = runtime.execute(new SubprocessExecutionSupport.ExecutionRequest(
+ CommandLine.parse("fake"), null, null, 500L, 32, 32, 100L,
+ System.nanoTime(), nextToken));
+ assertEquals(2, starts.get());
+ assertEquals(TerminationReason.CANCELLED,
+ next.getExecutionDetails().getTerminationReason());
+ }
+
+ private static final class ExpiredWatchdog extends ExecuteWatchdog {
+ ExpiredWatchdog() { super(1_000L); }
+
+ @Override
+ public synchronized void start(Process process) { }
+
+ @Override
+ public synchronized boolean killedProcess() { return true; }
+ }
+
+ private static final class ExitedProcess extends Process {
+ private final InputStream output;
+
+ ExitedProcess(String text) {
+ output = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8));
+ }
+
+ @Override
+ public OutputStream getOutputStream() { return new ByteArrayOutputStream(); }
+
+ @Override
+ public InputStream getInputStream() { return output; }
+
+ @Override
+ public InputStream getErrorStream() { return new ByteArrayInputStream(new byte[0]); }
+
+ @Override
+ public int waitFor() { return 0; }
+
+ @Override
+ public int exitValue() { return 0; }
+
+ @Override
+ public void destroy() { }
+
+ @Override
+ public boolean isAlive() { return false; }
+ }
+
+ private static final class LiveProcess extends Process {
+ private volatile boolean alive = true;
+
+ @Override
+ public OutputStream getOutputStream() { return new ByteArrayOutputStream(); }
+
+ @Override
+ public InputStream getInputStream() { return new ByteArrayInputStream(new byte[0]); }
+
+ @Override
+ public InputStream getErrorStream() { return new ByteArrayInputStream(new byte[0]); }
+
+ @Override
+ public int waitFor() { return 143; }
+
+ @Override
+ public int exitValue() {
+ if (alive) { throw new IllegalThreadStateException(); }
+ return 143;
+ }
+
+ @Override
+ public void destroy() { alive = false; }
+
+ @Override
+ public boolean isAlive() { return alive; }
+ }
+}
diff --git a/src/test/java/io/github/easy4j/opencli/core/support/SubprocessStreamFailureTest.java b/src/test/java/io/github/easy4j/opencli/core/support/SubprocessStreamFailureTest.java
new file mode 100644
index 0000000..8a6e8fd
--- /dev/null
+++ b/src/test/java/io/github/easy4j/opencli/core/support/SubprocessStreamFailureTest.java
@@ -0,0 +1,93 @@
+package io.github.easy4j.opencli.core.support;
+
+import io.github.easy4j.opencli.core.OpenCliCancellationToken;
+import io.github.easy4j.opencli.core.OpenCliExecutionDetails.TerminationReason;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import org.apache.commons.exec.CommandLine;
+import org.apache.commons.exec.ExecuteWatchdog;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** Verifies that reader-thread I/O faults survive into the terminal result. */
+@Timeout(5)
+class SubprocessStreamFailureTest {
+
+ @Test
+ void partialOutputAndReadFailureRemainVisibleAfterRootExit() throws Exception {
+ IOException readFailure = new IOException("injected stdout read failure");
+ SubprocessExecutionSupport.Runtime runtime = new SubprocessExecutionSupport.Runtime(1,
+ builder -> new ExitedProcess(readFailure), timeout -> new IdleWatchdog());
+ SubprocessExecutionSupport.ExecutionRequest request = new SubprocessExecutionSupport.ExecutionRequest(
+ CommandLine.parse("fake"), null, null, 1_000L, 32, 32, 100L,
+ System.nanoTime(), new OpenCliCancellationToken());
+
+ SubprocessExecutionSupport.RunSession session = runtime.execute(request);
+
+ assertEquals(TerminationReason.IO_FAILURE,
+ session.getExecutionDetails().getTerminationReason());
+ assertSame(readFailure, session.getIoFailure());
+ assertEquals("abc", session.getStdout().toString(StandardCharsets.UTF_8.name()));
+ assertTrue(session.getExecutionDetails().isStreamsDrained());
+ }
+
+ private static final class IdleWatchdog extends ExecuteWatchdog {
+ IdleWatchdog() { super(1_000L); }
+
+ @Override
+ public synchronized void start(Process process) { }
+ }
+
+ private static final class ExitedProcess extends Process {
+ private final InputStream output;
+
+ ExitedProcess(IOException readFailure) {
+ output = new InputStream() {
+ private boolean emitted;
+
+ @Override
+ public int read() throws IOException {
+ throw new UnsupportedOperationException("Reader uses block reads");
+ }
+
+ @Override
+ public int read(byte[] bytes, int offset, int length) throws IOException {
+ if (emitted) { throw readFailure; }
+ byte[] partial = "abc".getBytes(StandardCharsets.UTF_8);
+ System.arraycopy(partial, 0, bytes, offset, partial.length);
+ emitted = true;
+ return partial.length;
+ }
+ };
+ }
+
+ @Override
+ public OutputStream getOutputStream() { return new ByteArrayOutputStream(); }
+
+ @Override
+ public InputStream getInputStream() { return output; }
+
+ @Override
+ public InputStream getErrorStream() { return new ByteArrayInputStream(new byte[0]); }
+
+ @Override
+ public int waitFor() { return 0; }
+
+ @Override
+ public int exitValue() { return 0; }
+
+ @Override
+ public void destroy() { }
+
+ @Override
+ public boolean isAlive() { return false; }
+ }
+}
diff --git a/src/test/resources/opencli-contracts/v1/SHA256SUMS b/src/test/resources/opencli-contracts/v1/SHA256SUMS
new file mode 100644
index 0000000..c7a5e08
--- /dev/null
+++ b/src/test/resources/opencli-contracts/v1/SHA256SUMS
@@ -0,0 +1,2 @@
+e7e6dd57e81e24e92a7cb0de0e1204f95025f80310f5dc34d820aa7419636f78 argv.tsv
+2fa30626c415bb3c152bc4c2827cd9282ba710654f6a56fb7bde70a83b2bc192 sources.lock.json
diff --git a/src/test/resources/opencli-contracts/v1/argv.tsv b/src/test/resources/opencli-contracts/v1/argv.tsv
new file mode 100644
index 0000000..bb4ce3a
--- /dev/null
+++ b/src/test/resources/opencli-contracts/v1/argv.tsv
@@ -0,0 +1,6 @@
+ordinary ZGVtbw== ZWNobw== aGVsbG8=
+empty ZGVtbw== ZWNobw==
+whitespace ZGVtbw== ZWNobw== ICB4ICA= ICAg
+unicode-newline ZGVtbw== ZWNobw== CuS4reaWhwo= 8J+Zgg==
+literal-shell ZGVtbw== ZWNobw== JChwcmludGYgU0hPVUxEX05PVF9SVU4pOyAq LS0= LWxpdGVyYWw=
+equals-quotes ZGVtbw== ZWNobw== LS1rZXk9YT1i ImxpdGVyYWwi Qzpc6Lev5b6EXGZpbGUgbmFtZQ==
diff --git a/src/test/resources/opencli-contracts/v1/sources.lock.json b/src/test/resources/opencli-contracts/v1/sources.lock.json
new file mode 100644
index 0000000..a1ed16b
--- /dev/null
+++ b/src/test/resources/opencli-contracts/v1/sources.lock.json
@@ -0,0 +1,58 @@
+{
+ "schemaVersion": 1,
+ "observedAt": "2026-09-21",
+ "scope": "Synthetic offline argv vectors; not captures from OpenCLI or websites.",
+ "source": {
+ "kind": "specification",
+ "requirements": [
+ "OC-ARGV-001",
+ "OC-ARGV-002",
+ "OC-ARGV-004",
+ "OC-ARGV-005"
+ ],
+ "ref": "d0c8056990f7a47fcc202acffa387ba066bcfc67",
+ "path": "openspec/changes/harden-opencli-argv-contract/specs/opencli-argv-contract/spec.md"
+ },
+ "files": [
+ {
+ "path": "argv.tsv",
+ "sha256": "e7e6dd57e81e24e92a7cb0de0e1204f95025f80310f5dc34d820aa7419636f78",
+ "vectors": 6,
+ "encoding": "case-id then tab-separated base64 UTF-8 tokens; preserve trailing empty fields"
+ }
+ ],
+ "branches": [
+ {
+ "branch": "feature/1.0.x",
+ "base": "abba809f11dae68437c39d2ea5a2f4cf8798c0ef",
+ "java": 8,
+ "jackson": 2,
+ "mavenMajor": 3
+ },
+ {
+ "branch": "feature/2.0.x",
+ "base": "d0c8056990f7a47fcc202acffa387ba066bcfc67",
+ "java": 17,
+ "jackson": 2,
+ "mavenMajor": 3,
+ "canonical": true
+ },
+ {
+ "branch": "feature/3.0.x",
+ "base": "6e38904bdfcae90ec617e8d29bf3d8cf2f002893",
+ "java": 21,
+ "jackson": 3,
+ "mavenMajor": 4
+ }
+ ],
+ "allowedDifferences": [
+ "JDK baseline",
+ "Jackson imports/decoder internals",
+ "Maven wrapper/POM schema"
+ ],
+ "forbiddenDifferences": [
+ "raw token contents/order/count",
+ "null validation",
+ "observable semantics of shared vectors"
+ ]
+}
From 037f8bf4dfd390360743ee78f4cc3e420772ece4 Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Wed, 18 Nov 2026 21:18:29 +0800
Subject: [PATCH 005/105] Backport consistent OpenCLI cleanup deadline evidence
---
.../opencli/core/OpenCliExecutionDetails.java | 2 +-
.../support/SubprocessExecutionSupport.java | 13 ++--
.../support/SubprocessStreamFailureTest.java | 60 ++++++++++++++++++-
3 files changed, 67 insertions(+), 8 deletions(-)
diff --git a/src/main/java/io/github/easy4j/opencli/core/OpenCliExecutionDetails.java b/src/main/java/io/github/easy4j/opencli/core/OpenCliExecutionDetails.java
index 6da55ff..bc9f69f 100644
--- a/src/main/java/io/github/easy4j/opencli/core/OpenCliExecutionDetails.java
+++ b/src/main/java/io/github/easy4j/opencli/core/OpenCliExecutionDetails.java
@@ -13,7 +13,7 @@ public enum TerminationReason {
CANCELLED, SPAWN_FAILED, IO_FAILURE, CLEANUP_UNCONFIRMED, RUNTIME_UNAVAILABLE
}
- /** Confirmation concerns the directly owned child, not an arbitrary process tree. */
+ /** Confirmation covers the directly owned child and its output readers at the cleanup deadline. */
public enum CleanupState { NOT_STARTED, ROOT_EXIT_CONFIRMED, UNCONFIRMED }
private final TerminationReason terminationReason;
diff --git a/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java b/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
index cc3c7cd..98a5420 100644
--- a/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
+++ b/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
@@ -126,6 +126,8 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
boolean interrupted = false;
boolean cleanupOperationFailed = false;
long queueWaitMillis = 0L;
+ Integer exit = null;
+ boolean streamsDrained = true;
try {
while (!acquired && reason == null) {
if (Thread.interrupted()) {
@@ -248,7 +250,11 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
}
}
if (process.isAlive() && !tryForceStop(process)) { cleanupOperationFailed = true; }
- if (process.isAlive() || alive(stdoutReader) || alive(stderrReader)) {
+ if (!process.isAlive()) {
+ exit = process.exitValue();
+ }
+ streamsDrained = !alive(stdoutReader) && !alive(stderrReader);
+ if (Objects.isNull(exit) || !streamsDrained) {
// A fixed runtime cannot accumulate unlimited uncertain children/readers.
quarantined = true;
if (reason == TerminationReason.PROCESS_EXIT) { reason = TerminationReason.CLEANUP_UNCONFIRMED; }
@@ -264,7 +270,6 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
if (reason == TerminationReason.PROCESS_EXIT && (out.isTruncated() || err.isTruncated())) {
reason = TerminationReason.OUTPUT_LIMIT;
}
- Integer exit = process != null && !process.isAlive() ? process.exitValue() : null;
DefaultExecuteResultHandler handler = new DefaultExecuteResultHandler();
if (ioFailure != null) {
handler.onProcessFailed(new ExecuteException("Native process I/O failure", exit == null ? -1 : exit, ioFailure));
@@ -276,8 +281,8 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
OpenCliExecutionDetails details = OpenCliExecutionDetails.builder()
.terminationReason(reason)
.cleanupState(process == null ? CleanupState.NOT_STARTED
- : process.isAlive() ? CleanupState.UNCONFIRMED : CleanupState.ROOT_EXIT_CONFIRMED)
- .processStarted(process != null).streamsDrained(!alive(stdoutReader) && !alive(stderrReader))
+ : Objects.isNull(exit) || !streamsDrained ? CleanupState.UNCONFIRMED : CleanupState.ROOT_EXIT_CONFIRMED)
+ .processStarted(process != null).streamsDrained(streamsDrained)
.cleanupOperationFailed(cleanupOperationFailed)
.stdoutCapturedBytes(out.size()).stdoutObservedBytes(out.observed()).stdoutTruncated(out.isTruncated())
.stderrCapturedBytes(err.size()).stderrObservedBytes(err.observed()).stderrTruncated(err.isTruncated())
diff --git a/src/test/java/io/github/easy4j/opencli/core/support/SubprocessStreamFailureTest.java b/src/test/java/io/github/easy4j/opencli/core/support/SubprocessStreamFailureTest.java
index 8a6e8fd..44c407d 100644
--- a/src/test/java/io/github/easy4j/opencli/core/support/SubprocessStreamFailureTest.java
+++ b/src/test/java/io/github/easy4j/opencli/core/support/SubprocessStreamFailureTest.java
@@ -1,6 +1,7 @@
package io.github.easy4j.opencli.core.support;
import io.github.easy4j.opencli.core.OpenCliCancellationToken;
+import io.github.easy4j.opencli.core.OpenCliExecutionDetails.CleanupState;
import io.github.easy4j.opencli.core.OpenCliExecutionDetails.TerminationReason;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -8,12 +9,15 @@
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.ExecuteWatchdog;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -39,7 +43,53 @@ void partialOutputAndReadFailureRemainVisibleAfterRootExit() throws Exception {
assertTrue(session.getExecutionDetails().isStreamsDrained());
}
- private static final class IdleWatchdog extends ExecuteWatchdog {
+ @Test
+ void openReaderKeepsCleanupUnconfirmedAfterRootExit() throws Exception {
+ CountDownLatch releaseReader = new CountDownLatch(1);
+ CountDownLatch readerClosed = new CountDownLatch(1);
+ InputStream output = new InputStream() {
+ @Override
+ public int read() throws IOException {
+ try {
+ releaseReader.await();
+ return -1;
+ } catch (InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ throw new IOException(ex);
+ }
+ }
+
+ @Override
+ public void close() {
+ readerClosed.countDown();
+ }
+ };
+ OpenCliCancellationToken token = new OpenCliCancellationToken();
+ SubprocessExecutionSupport.Runtime runtime = new SubprocessExecutionSupport.Runtime(1,
+ builder -> new ExitedProcess(output), timeout -> new IdleWatchdog() {
+ @Override
+ public synchronized void start(Process process) {
+ token.cancel();
+ }
+ });
+ SubprocessExecutionSupport.ExecutionRequest request = new SubprocessExecutionSupport.ExecutionRequest(
+ CommandLine.parse("fake"), null, null, 1_000L, 32, 32, 50L, System.nanoTime(), token);
+
+ try {
+ SubprocessExecutionSupport.RunSession session = runtime.execute(request);
+
+ assertEquals(TerminationReason.CANCELLED, session.getExecutionDetails().getTerminationReason());
+ assertEquals(0, session.getObservedExitCode());
+ assertEquals(CleanupState.UNCONFIRMED, session.getExecutionDetails().getCleanupState());
+ assertFalse(session.getExecutionDetails().isStreamsDrained());
+ assertTrue(runtime.isQuarantined());
+ } finally {
+ releaseReader.countDown();
+ assertTrue(readerClosed.await(1, TimeUnit.SECONDS));
+ }
+ }
+
+ private static class IdleWatchdog extends ExecuteWatchdog {
IdleWatchdog() { super(1_000L); }
@Override
@@ -49,8 +99,12 @@ public synchronized void start(Process process) { }
private static final class ExitedProcess extends Process {
private final InputStream output;
+ ExitedProcess(InputStream output) {
+ this.output = output;
+ }
+
ExitedProcess(IOException readFailure) {
- output = new InputStream() {
+ this(new InputStream() {
private boolean emitted;
@Override
@@ -66,7 +120,7 @@ public int read(byte[] bytes, int offset, int length) throws IOException {
emitted = true;
return partial.length;
}
- };
+ });
}
@Override
From 740608ca71ee8ff11de072338d0554c620c9afa3 Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Wed, 18 Nov 2026 21:22:03 +0800
Subject: [PATCH 006/105] Verify native subprocess contracts on macOS and
Windows
---
.github/workflows/platform-contracts.yml | 72 ++++++++++++
scripts/contract_report.py | 110 ++++++++++++++++++
.../support/SubprocessExecutionSupport.java | 45 ++++++-
.../contract/OpenCliArgvContractTest.java | 24 ++++
.../opencli-contracts/argv-probe.cjs | 5 +
5 files changed, 255 insertions(+), 1 deletion(-)
create mode 100644 .github/workflows/platform-contracts.yml
create mode 100644 scripts/contract_report.py
create mode 100644 src/test/resources/opencli-contracts/argv-probe.cjs
diff --git a/.github/workflows/platform-contracts.yml b/.github/workflows/platform-contracts.yml
new file mode 100644
index 0000000..d513a18
--- /dev/null
+++ b/.github/workflows/platform-contracts.yml
@@ -0,0 +1,72 @@
+name: Platform subprocess contracts
+
+on:
+ push:
+ branches: [feature/REQ-20261118-wandl-opencli-privacy-10]
+
+permissions:
+ contents: read
+
+jobs:
+ process-platform:
+ name: Subprocess contracts (${{ matrix.os }})
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [macos-15-intel, windows-latest]
+ runs-on: ${{ matrix.os }}
+ timeout-minutes: 15
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - uses: actions/checkout@v7
+ - uses: actions/setup-java@v5
+ with:
+ distribution: temurin
+ java-version: '8'
+ cache: maven
+ - uses: actions/setup-python@v7
+ with:
+ python-version: '3.13'
+ - uses: actions/setup-node@v4
+ if: runner.os == 'Windows'
+ with:
+ node-version: '22'
+ - name: Exercise real subprocess contracts
+ run: |
+ mkdir -p platform-evidence
+ if [[ "$RUNNER_OS" == Windows ]]; then
+ OPENCLI_CONTRACT_NODE_EXECUTABLE="$(node -p 'process.execPath')"
+ export OPENCLI_CONTRACT_NODE_EXECUTABLE
+ fi
+ java -version > platform-evidence/java.txt 2>&1
+ mvn -version > platform-evidence/maven.txt 2>&1
+ result=0
+ mvn -B --no-transfer-progress \
+ -Dtest=OpenCliArgvContractTest,OpenCliStructuredArgvContractTest,OpenCliProcessContractTest,OpenCliProcessBoundaryTest,SubprocessStreamFailureTest \
+ test > platform-evidence/maven.log 2>&1 || result=$?
+ tail -100 platform-evidence/maven.log
+ python scripts/contract_report.py \
+ --reports target/surefire-reports \
+ --head "$(git rev-parse HEAD)" \
+ --branch "$GITHUB_REF_NAME" \
+ --java-version-file platform-evidence/java.txt \
+ --maven-version-file platform-evidence/maven.txt \
+ --exit-code "$result" \
+ --suite argv=io.github.easy4j.opencli.contract.OpenCliArgvContractTest \
+ --suite argv=io.github.easy4j.opencli.contract.OpenCliStructuredArgvContractTest \
+ --suite process=io.github.easy4j.opencli.contract.OpenCliProcessContractTest \
+ --suite process=io.github.easy4j.opencli.contract.OpenCliProcessBoundaryTest,SubprocessStreamFailureTest \
+ --suite cleanup=io.github.easy4j.opencli.core.support.SubprocessStreamFailureTest \
+ --output platform-evidence/report.json
+ exit "$result"
+ - name: Upload platform subprocess evidence
+ if: always()
+ uses: actions/upload-artifact@v7
+ with:
+ name: subprocess-${{ matrix.os }}-${{ github.sha }}
+ path: |
+ platform-evidence
+ target/surefire-reports
+ if-no-files-found: error
diff --git a/scripts/contract_report.py b/scripts/contract_report.py
new file mode 100644
index 0000000..b0c8c78
--- /dev/null
+++ b/scripts/contract_report.py
@@ -0,0 +1,110 @@
+#!/usr/bin/env python3
+"""Build fail-closed, layer-specific evidence from real Surefire XML reports.
+
+This is not a code coverage percentage or a claim that OpenCLI websites work.
+Only explicitly selected suites contribute to a layer. No network is used.
+"""
+import argparse
+import json
+import pathlib
+import re
+import sys
+import xml.etree.ElementTree as ET
+
+LAYERS = ('enumeration', 'argv', 'process', 'protocol', 'typed-result', 'real-execution')
+
+
+def _suite_summary(suite):
+ declared = {key: int(suite.attrib.get(key, '0')) for key in ('tests', 'failures', 'errors', 'skipped')}
+ cases = suite.findall('testcase')
+ actual = {'tests': len(cases), 'failures': sum(c.find('failure') is not None for c in cases),
+ 'errors': sum(c.find('error') is not None for c in cases),
+ 'skipped': sum(c.find('skipped') is not None for c in cases)}
+ if declared != actual or any(v < 0 for v in declared.values()):
+ raise ValueError('declared testcase counts disagree with XML evidence')
+ actual['executed'] = actual['tests'] - actual['skipped']
+ return actual
+
+
+def build_report(reports_dir, *, head, branch, java_version, maven_version, exit_code, required_suites):
+ """Return a JSON-serializable report; malformed/missing evidence fails closed."""
+ problems = []
+ if not re.fullmatch(r'[0-9a-fA-F]{40}', head or ''):
+ problems.append('exact 40-character source HEAD is required')
+ if not branch or not java_version.strip() or not maven_version.strip():
+ problems.append('branch and actual tool versions are required')
+ if exit_code != 0:
+ problems.append('verification command exited nonzero')
+ if not required_suites or any(layer not in LAYERS or not names for layer, names in required_suites.items()):
+ problems.append('non-empty required suites must use recognized layers')
+ suites = {}
+ for path in sorted(pathlib.Path(reports_dir).glob('TEST-*.xml')):
+ try:
+ root = ET.parse(path).getroot()
+ nodes = [root] if root.tag == 'testsuite' else list(root.findall('testsuite'))
+ if not nodes:
+ raise ValueError('no testsuite')
+ for suite in nodes:
+ name = suite.attrib['name']
+ if name in suites:
+ raise ValueError('duplicate testsuite')
+ suites[name] = _suite_summary(suite)
+ except (ET.ParseError, OSError, KeyError, ValueError):
+ problems.append('invalid or duplicate Surefire report: ' + path.name)
+ layers = {}
+ for layer in LAYERS:
+ names = list(required_suites.get(layer, []))
+ counts = dict.fromkeys(('tests', 'executed', 'skipped', 'failures', 'errors'), 0)
+ missing = [name for name in names if name not in suites]
+ for name in names:
+ for key in counts:
+ counts[key] += suites.get(name, {}).get(key, 0)
+ state = 'NOT_RUN'
+ if names:
+ state = 'PASS' if (not missing and counts['executed'] > 0 and
+ not any(counts[key] for key in ('skipped', 'failures', 'errors'))) else 'FAIL'
+ layers[layer] = dict(counts, status=state, requiredSuites=names, missingSuites=missing)
+ if state == 'FAIL':
+ problems.append('required layer lacks passing, non-skipped execution: ' + layer)
+ return {'schemaVersion': 1, 'status': 'FAIL' if problems else 'PASS',
+ 'head': head, 'branch': branch, 'javaVersion': java_version,
+ 'mavenVersion': maven_version, 'commandExitCode': exit_code,
+ 'layers': layers, 'problems': problems,
+ 'scope': 'Explicit Surefire suites only; synthetic argv/process probes are not live OpenCLI verification.'}
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--reports', type=pathlib.Path, required=True)
+ parser.add_argument('--head', required=True)
+ parser.add_argument('--branch', required=True)
+ parser.add_argument('--java-version-file', type=pathlib.Path, required=True)
+ parser.add_argument('--maven-version-file', type=pathlib.Path, required=True)
+ parser.add_argument('--exit-code', type=int, required=True)
+ parser.add_argument('--suite', action='append', required=True, help='layer=fully.qualified.TestClass; repeatable')
+ parser.add_argument('--output', type=pathlib.Path, required=True)
+ args = parser.parse_args(argv)
+ required = {}
+ for item in args.suite:
+ layer, separator, name = item.partition('=')
+ if not separator or layer not in LAYERS or not name:
+ parser.error('--suite must be recognized-layer=fully.qualified.TestClass')
+ if name in required.setdefault(layer, []):
+ parser.error('duplicate --suite')
+ required[layer].append(name)
+ try:
+ report = build_report(args.reports, head=args.head, branch=args.branch,
+ java_version=args.java_version_file.read_text(encoding='utf-8'),
+ maven_version=args.maven_version_file.read_text(encoding='utf-8'),
+ exit_code=args.exit_code, required_suites=required)
+ except OSError as exc:
+ print('Missing tool-version evidence: ' + exc.__class__.__name__, file=sys.stderr)
+ return 1
+ args.output.parent.mkdir(parents=True, exist_ok=True)
+ args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
+ print(json.dumps({'status': report['status'], 'head': report['head'], 'layers': report['layers']}))
+ return 0 if report['status'] == 'PASS' else 1
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java b/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
index 98a5420..76248eb 100644
--- a/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
+++ b/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
@@ -13,6 +13,7 @@
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Semaphore;
@@ -160,7 +161,7 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
}
}
if (acquired && reason == null) {
- ProcessBuilder builder = new ProcessBuilder(request.nativeArgv);
+ ProcessBuilder builder = new ProcessBuilder(processArguments(request.nativeArgv));
if (request.workingDirectory != null) { builder.directory(request.workingDirectory); }
if (request.environment != null) {
builder.environment().clear();
@@ -310,6 +311,48 @@ private static boolean tryForceStop(Process process) {
}
}
private static long remaining(long start, long budget) { return budget - (System.nanoTime() - start); }
+ // The Windows JDK legacy serializer treats a surrounding quote pair as already encoded.
+ @SuppressWarnings("removal")
+ private static List processArguments(List argv) {
+ String executable = argv.get(0).toLowerCase(Locale.ROOT);
+ if (!System.getProperty("os.name").startsWith("Windows") || !executable.endsWith(".exe")
+ || executable.endsWith("cmd.exe") || Objects.nonNull(System.getSecurityManager())
+ || "false".equalsIgnoreCase(System.getProperty("jdk.lang.Process.allowAmbiguousCommands"))) {
+ return argv;
+ }
+ List arguments = new ArrayList<>(argv);
+ for (int i = 1; i < arguments.size(); i++) {
+ String argument = arguments.get(i);
+ if (argument.indexOf('"') >= 0) {
+ arguments.set(i, quoteWindowsExecutableArgument(argument));
+ }
+ }
+ return arguments;
+ }
+
+ /** Windows CRT quoting for arguments with literal quotes in a native executable. */
+ private static String quoteWindowsExecutableArgument(String argument) {
+ StringBuilder quoted = new StringBuilder(argument.length() + 2).append('"');
+ int backslashes = 0;
+ for (int i = 0; i < argument.length(); i++) {
+ char character = argument.charAt(i);
+ if (character == '\\') {
+ backslashes++;
+ continue;
+ }
+ int escaped = character == '"' ? backslashes * 2 + 1 : backslashes;
+ for (int j = 0; j < escaped; j++) {
+ quoted.append('\\');
+ }
+ quoted.append(character);
+ backslashes = 0;
+ }
+ for (int i = 0; i < backslashes * 2; i++) {
+ quoted.append('\\');
+ }
+ return quoted.append('"').toString();
+ }
+
private static long elapsedMillis(long start) { return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); }
private static long nanos(long millis, String field) {
diff --git a/src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java b/src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java
index e50a631..1bad49f 100644
--- a/src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java
+++ b/src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java
@@ -12,6 +12,9 @@
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
@@ -19,6 +22,7 @@
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Objects;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.api.DynamicTest;
@@ -35,6 +39,18 @@ private static OpenCliProperties properties() {
p.setLeadingArguments(new ArrayList<>(Arrays.asList("-cp",
System.getProperty("surefire.test.class.path", System.getProperty("java.class.path")),
ContractProbe.class.getName())));
+ String node = System.getenv("OPENCLI_CONTRACT_NODE_EXECUTABLE");
+ if (System.getProperty("os.name").startsWith("Windows") && Objects.nonNull(node)) {
+ URL probe = OpenCliArgvContractTest.class.getResource("/opencli-contracts/argv-probe.cjs");
+ p.setExecutable(node);
+ try {
+ URI location = Objects.requireNonNull(probe, "Windows argv fixture is required").toURI();
+ p.getLeadingArguments().clear();
+ p.getLeadingArguments().add(new File(location).getAbsolutePath());
+ } catch (URISyntaxException e) {
+ throw new AssertionError("Invalid Windows argv fixture location", e);
+ }
+ }
p.setCommandTimeoutMillis(10000L);
return p;
}
@@ -96,6 +112,14 @@ Stream sharedVectorsReachEveryRawEntryPoint() throws Exception {
return tests.stream();
}
+ @Test
+ void literalQuotesAndAdjacentBackslashesReachChildUnchanged() throws Exception {
+ List tokens = Arrays.asList("demo", "echo", "\"quoted\"",
+ "folder\\\"name with spaces\\", "two\\\\\"quotes\"\" and trailing\\\\");
+ OpenCliResult result = new OpenCliExecutor(properties()).invoke(tokens);
+ assertEquals(tokens, received(result));
+ }
+
@Test
void structuredPositionalsAndValuesReachChildUnchanged() throws Exception {
Map options = new LinkedHashMap<>();
diff --git a/src/test/resources/opencli-contracts/argv-probe.cjs b/src/test/resources/opencli-contracts/argv-probe.cjs
new file mode 100644
index 0000000..88daed0
--- /dev/null
+++ b/src/test/resources/opencli-contracts/argv-probe.cjs
@@ -0,0 +1,5 @@
+const args = process.argv.slice(2);
+console.log(`argc:${args.length}`);
+for (const arg of args) {
+ console.log(`arg:${Buffer.from(arg, 'utf8').toString('base64')}`);
+}
From ca34757b111dd38676a8cf4484c7ca514512380c Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Wed, 18 Nov 2026 21:27:42 +0800
Subject: [PATCH 007/105] fix: preserve trailing slashes in Windows JDK 8
arguments
---
.github/workflows/platform-contracts.yml | 4 ++--
.../opencli/core/support/SubprocessExecutionSupport.java | 9 ++++++++-
2 files changed, 10 insertions(+), 3 deletions(-)
diff --git a/.github/workflows/platform-contracts.yml b/.github/workflows/platform-contracts.yml
index d513a18..0c57fe8 100644
--- a/.github/workflows/platform-contracts.yml
+++ b/.github/workflows/platform-contracts.yml
@@ -57,8 +57,8 @@ jobs:
--suite argv=io.github.easy4j.opencli.contract.OpenCliArgvContractTest \
--suite argv=io.github.easy4j.opencli.contract.OpenCliStructuredArgvContractTest \
--suite process=io.github.easy4j.opencli.contract.OpenCliProcessContractTest \
- --suite process=io.github.easy4j.opencli.contract.OpenCliProcessBoundaryTest,SubprocessStreamFailureTest \
- --suite cleanup=io.github.easy4j.opencli.core.support.SubprocessStreamFailureTest \
+ --suite process=io.github.easy4j.opencli.contract.OpenCliProcessBoundaryTest \
+ --suite process=io.github.easy4j.opencli.core.support.SubprocessStreamFailureTest \
--output platform-evidence/report.json
exit "$result"
- name: Upload platform subprocess evidence
diff --git a/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java b/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
index 76248eb..4efe49e 100644
--- a/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
+++ b/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
@@ -347,10 +347,17 @@ private static String quoteWindowsExecutableArgument(String argument) {
quoted.append(character);
backslashes = 0;
}
+ quoted.append('"');
+ if (backslashes == 0) {
+ return quoted.toString();
+ }
+
+ // JDK 8 treats a final quote after a backslash as escaped. Close the quoted
+ // text first and use an empty quoted segment after the escaped trailing slashes.
for (int i = 0; i < backslashes * 2; i++) {
quoted.append('\\');
}
- return quoted.append('"').toString();
+ return quoted.append('"').append('"').toString();
}
private static long elapsedMillis(long start) { return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); }
From 86564e47c30bf8ac5d873178cc501780d760dd10 Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Wed, 18 Nov 2026 21:35:52 +0800
Subject: [PATCH 008/105] test: verify bounded OpenCLI network follow outcomes
---
.../harden-opencli-process-lifecycle/tasks.md | 6 +
.../opencli/contract/LifecycleProbe.java | 32 ++++++
.../contract/OpenCliProcessContractTest.java | 108 ++++++++++++++++++
3 files changed, 146 insertions(+)
diff --git a/openspec/changes/harden-opencli-process-lifecycle/tasks.md b/openspec/changes/harden-opencli-process-lifecycle/tasks.md
index 253d98a..3e07948 100644
--- a/openspec/changes/harden-opencli-process-lifecycle/tasks.md
+++ b/openspec/changes/harden-opencli-process-lifecycle/tasks.md
@@ -24,3 +24,9 @@
## 证据交付模板(实施时填写)
每项任务的完成记录包含:Requirement/Scenario、分支HEAD、测试命令、失败→通过证据、测试数/跳过数、退出码、报告位置。没有记录的任务保持未完成。
+
+## OC-PROC-006 本地同步采集验证
+
+`OpenCliProcessContractTest` 经 typed `browser network --follow` 入口运行真实 JVM fixture,校验 CLI argv,并覆盖正常退出、CLI 非零退出、输出超限、调用线程中断、执行超时,以及禁用时限时启动前拒绝。超时测试同时启动独立进程,确认该进程仍运行并可自行正常退出。JDK 8 执行 `mvn -B -ntp -o clean verify` 退出 0,全量 2,095 项(其中该类 14 项),0 失败、0 错误、0 跳过。
+
+本记录覆盖当前本地同步入口。平台矩阵、真实 OpenCLI 持续输出、受控 sink 和后代进程所有权仍需独立证据。
diff --git a/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java b/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java
index 88247cf..1b0c7a1 100644
--- a/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java
+++ b/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java
@@ -12,6 +12,10 @@ private LifecycleProbe() { }
public static void main(String[] args) throws Exception {
String mode = args[0];
+ if ("network-follow".equals(mode)) {
+ networkFollow(args);
+ return;
+ }
if ("utf8".equals(mode)) {
System.out.write("中文".getBytes(StandardCharsets.UTF_8));
return;
@@ -41,4 +45,32 @@ public static void main(String[] args) throws Exception {
Thread.sleep(20L);
}
}
+
+ private static void networkFollow(String[] args) throws Exception {
+ if (!Arrays.asList("browser", "fixture", "network", "--follow")
+ .equals(Arrays.asList(args).subList(3, args.length))) {
+ throw new IllegalArgumentException("unexpected network follow argv");
+ }
+ System.out.print("event-one\n");
+ System.out.flush();
+ switch (args[1]) {
+ case "complete":
+ Thread.sleep(30L);
+ System.out.print("event-two\n");
+ break;
+ case "overflow":
+ main(new String[]{"stdout", "4096"});
+ break;
+ case "failed":
+ System.err.print("fixture failed");
+ System.exit(23);
+ break;
+ case "wait":
+ Files.write(Paths.get(args[2]), new byte[]{1});
+ Thread.sleep(8000L);
+ break;
+ default:
+ throw new IllegalArgumentException("unexpected network follow mode");
+ }
+ }
}
diff --git a/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java b/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java
index 5cb4397..aeb28af 100644
--- a/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java
+++ b/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java
@@ -1,9 +1,14 @@
package io.github.easy4j.opencli.contract;
import io.github.easy4j.opencli.OpenCliProperties;
+import io.github.easy4j.opencli.browser.OpenCliBrowserClient;
+import io.github.easy4j.opencli.browser.OpenCliBrowserSession;
+import io.github.easy4j.opencli.browser.OpenCliBrowserSession.OpenCliBrowserNetworkOptions;
+import io.github.easy4j.opencli.core.OpenCliExecutionDetails.TerminationReason;
import io.github.easy4j.opencli.core.OpenCliExecutor;
import io.github.easy4j.opencli.core.OpenCliResult;
import io.github.easy4j.opencli.exception.OpenCliException;
+import io.github.easy4j.opencli.exception.OpenCliNonZeroExitException;
import io.github.easy4j.opencli.exception.OpenCliTimeoutException;
import java.io.File;
import java.nio.charset.StandardCharsets;
@@ -64,6 +69,109 @@ private static Object getter(Object object, String name) {
private static Object details(OpenCliResult result) { return getter(result, "getExecutionDetails"); }
+ private OpenCliBrowserSession followSession(OpenCliProperties properties, String mode) {
+ properties.getLeadingArguments().addAll(Arrays.asList("network-follow", mode, dir.resolve("follow-ready").toString()));
+ return new OpenCliBrowserClient(new OpenCliExecutor(properties)).session("fixture");
+ }
+
+ private OpenCliResult follow(OpenCliBrowserSession session) {
+ return session.network(OpenCliBrowserNetworkOptions.builder().follow(true).build(), null);
+ }
+
+ @Test
+ void networkFollowReturnsCapturedEventsAfterNormalExit() {
+ OpenCliResult result = follow(followSession(properties(1), "complete"));
+ assertTrue(result.isSuccess());
+ assertEquals("event-one\nevent-two\n", result.getStdout());
+ assertEquals(TerminationReason.PROCESS_EXIT, result.getExecutionDetails().getTerminationReason());
+ }
+
+ @Test
+ void networkFollowStopsAtCaptureLimitWithPartialOutput() {
+ OpenCliProperties properties = properties(1);
+ properties.setMaxStdoutBytes(32);
+ OpenCliBrowserSession session = followSession(properties, "overflow");
+ OpenCliException failure = assertThrows(OpenCliException.class, () -> follow(session));
+ OpenCliResult partial = failure.getPartialResult();
+ assertEquals(TerminationReason.OUTPUT_LIMIT, partial.getExecutionDetails().getTerminationReason());
+ assertEquals(32L, partial.getExecutionDetails().getStdoutCapturedBytes());
+ assertTrue(partial.getStdout().startsWith("event-one\n"));
+ assertFalse(partial.isSuccess());
+ }
+
+ @Test
+ void networkFollowReportsTheCliExitCode() {
+ OpenCliBrowserSession session = followSession(properties(1), "failed");
+ OpenCliNonZeroExitException failure = assertThrows(OpenCliNonZeroExitException.class, () -> follow(session));
+ OpenCliResult partial = failure.getPartialResult();
+ assertEquals(Integer.valueOf(23), partial.getExitCode());
+ assertEquals("fixture failed", partial.getStderr());
+ assertEquals(TerminationReason.PROCESS_EXIT, partial.getExecutionDetails().getTerminationReason());
+ }
+
+ @Test
+ void networkFollowRejectsDisabledDeadlineBeforeSpawning() {
+ OpenCliProperties properties = properties(1);
+ properties.setCommandTimeoutMillis(0L);
+ OpenCliBrowserSession session = followSession(properties, "wait");
+ IllegalStateException failure = assertThrows(IllegalStateException.class, () -> follow(session));
+ assertEquals("opencli.command-timeout-millis must be positive", failure.getMessage());
+ assertFalse(Files.exists(dir.resolve("follow-ready")));
+ }
+
+ @Test
+ void networkFollowTimeoutLeavesAnIndependentProcessRunning() throws Exception {
+ OpenCliExecutor independent = new OpenCliExecutor(properties(1));
+ Path started = dir.resolve("independent-started");
+ Path gate = dir.resolve("independent-release");
+ ExecutorService worker = Executors.newSingleThreadExecutor();
+ try {
+ Future other = worker.submit(() -> independent.invoke("hold", started.toString(), gate.toString()));
+ assertTrue(awaitFile(started, 5000L));
+
+ OpenCliProperties properties = properties(1);
+ properties.setCommandTimeoutMillis(2500L);
+ OpenCliBrowserSession session = followSession(properties, "wait");
+ OpenCliTimeoutException timeout = assertThrows(OpenCliTimeoutException.class, () -> follow(session));
+ OpenCliResult partial = timeout.getPartialResult();
+ assertEquals(TerminationReason.EXECUTION_TIMEOUT, partial.getExecutionDetails().getTerminationReason());
+ assertEquals("event-one\n", partial.getStdout());
+
+ assertFalse(other.isDone(), "timeout must leave independent invocation running");
+ release(gate);
+ assertTrue(other.get(5, TimeUnit.SECONDS).isSuccess());
+ } finally {
+ release(gate);
+ worker.shutdownNow();
+ assertTrue(worker.awaitTermination(5, TimeUnit.SECONDS));
+ }
+ }
+
+ @Test
+ void networkFollowPreservesCancellationAfterAnEvent() throws Exception {
+ OpenCliBrowserSession session = followSession(properties(1), "wait");
+ AtomicReference partial = new AtomicReference<>();
+ Thread caller = new Thread(() -> {
+ try {
+ follow(session);
+ } catch (OpenCliException failure) {
+ partial.set(failure.getPartialResult());
+ }
+ }, "network-follow-caller");
+ try {
+ caller.start();
+ assertTrue(awaitFile(dir.resolve("follow-ready"), 5000L));
+ caller.interrupt();
+ caller.join(5000L);
+ assertFalse(caller.isAlive());
+ assertNotNull(partial.get());
+ assertEquals(TerminationReason.CANCELLED, partial.get().getExecutionDetails().getTerminationReason());
+ } finally {
+ caller.interrupt();
+ caller.join(5000L);
+ }
+ }
+
@Test
void anotherClientCannotReplaceAnActiveClientsLimiter() throws Exception {
OpenCliExecutor a = new OpenCliExecutor(properties(1));
From 896a637f2e9bda5210b074ab0ef9eb244db31836 Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Wed, 18 Nov 2026 21:53:30 +0800
Subject: [PATCH 009/105] fix: backport reverse WebSocket worker safeguards
---
README.md | 4 +
README.zh-CN.md | 4 +
.../harden-opencli-reverse-agent/tasks.md | 4 +
.../OpenCliWsAgentConnectionProperties.java | 6 +
.../center/ws/OpenCliWsCollectRequests.java | 132 +++++
.../ws/OpenCliWsReverseAgentClient.java | 184 ++++--
.../ws/OpenCliWsCollectRequestsTest.java | 45 ++
.../ws/OpenCliWsReverseAgentSessionTest.java | 540 ++++++++++++++++++
.../opencli/contract/LifecycleProbe.java | 8 +-
9 files changed, 871 insertions(+), 56 deletions(-)
create mode 100644 src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsCollectRequests.java
create mode 100644 src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsCollectRequestsTest.java
create mode 100644 src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java
diff --git a/README.md b/README.md
index 08ccaff..b6a8726 100644
--- a/README.md
+++ b/README.md
@@ -224,6 +224,10 @@ agent.close();
Protocol: edge sends `register`; center replies `registered`; center sends `collect` (request_id, site, command, args, positional_args, format, mode); the SDK executes `opencli` locally (via `copyForLocalCliExecution()` to avoid loops) and replies `result`; plus `ping` / `pong`.
+The reverse agent accepts up to four concurrent collect tasks and 32 queued tasks by default. Set `maxConcurrentCollects` and `maxPendingCollects` on the connection properties before constructing the agent to change the limits. A queue capacity of zero disables waiting. When full, the agent replies with a failed `result` and the error `worker is busy`.
+
+Collect request IDs must be nonblank strings of at most 128 UTF-8 bytes. The agent suppresses identical in-flight requests and rejects a reused ID with a different payload. An explicit retry may return a result marked `cached: true`. The in-memory cache keeps up to 1,024 completed results for at most ten minutes. Replay across reconnects requires the same TLS-verified endpoint. Plain WebSocket connections keep session-local deduplication. Restarting the agent discards its cache.
+
### Diagnostic export
Call `OpenCliDiagnosticExport.export(result, 512)` explicitly with an `OpenCliResult` or an exception's partial result. The byte budget applies to UTF-8 text. Output contains only status and field lengths, with a `truncated=true` marker when fields do not fit. Field lengths can disclose how much data was present.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 89693d5..06d0272 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -223,6 +223,10 @@ agent.close();
协议摘要:边缘发送 `register`;中心回执 `registered`;中心下发 `collect`(request_id、site、command、args、positional_args、format、mode);SDK 在本机执行 `opencli`(通过 `copyForLocalCliExecution()` 强制本地子进程,避免回路)并回执 `result`;另有 `ping` / `pong`。
+反向 Agent 默认最多同时执行 4 个 collect 任务,另有 32 个等待名额。构建 Agent 前,可在连接配置中设置 `maxConcurrentCollects` 和 `maxPendingCollects`。等待容量为零时直接拒绝超额请求。容量用尽时返回失败的 `result`,错误为 `worker is busy`。
+
+collect 请求 ID 必须为非空白字符串,长度上限 128 个 UTF-8 字节。相同的在途请求只执行一次,同一个 ID 对应不同载荷时会明确拒绝。显式重试已完成的请求有可能收到标记为 `cached: true` 的结果。内存缓存最多保留 1,024 条完成结果,每条最长 10 分钟。跨连接重放要求使用同一个经过 TLS 校验的端点,明文 WebSocket 的去重范围为当前连接。Agent 重启后会清空缓存。
+
### 诊断导出
如需导出诊断,请调用 `OpenCliDiagnosticExport.export(result, 512)`,传入 `OpenCliResult` 或异常中的部分结果。上限按 UTF-8 字节计算。输出只包含状态和字段长度,字段放不下时会标明 `truncated=true`。字段长度仍可能反映数据规模。
diff --git a/openspec/changes/harden-opencli-reverse-agent/tasks.md b/openspec/changes/harden-opencli-reverse-agent/tasks.md
index f7ff684..e113e5c 100644
--- a/openspec/changes/harden-opencli-reverse-agent/tasks.md
+++ b/openspec/changes/harden-opencli-reverse-agent/tasks.md
@@ -25,3 +25,7 @@
## 证据交付模板(实施时填写)
每项任务的完成记录包含:Requirement/Scenario、分支HEAD、测试命令、失败→通过证据、测试数/跳过数、退出码、报告位置。没有记录的任务保持未完成。
+
+## JDK 8 回移验证
+
+回移 JDK 17 版本的注册前拒绝、执行与等待上限、关闭保护、请求去重、缓存过期和连接隔离。通过本地回环服务器、真实子进程和测试证书验证普通连接和 TLS 重连。运行 `mvn -B -ntp -o clean verify`,2,112 项测试通过,零失败、零跳过,JaCoCo 行覆盖率为 2,905 / 3,167(91.73%)。
diff --git a/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsAgentConnectionProperties.java b/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsAgentConnectionProperties.java
index ce45a13..7aa4c9d 100644
--- a/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsAgentConnectionProperties.java
+++ b/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsAgentConnectionProperties.java
@@ -59,6 +59,12 @@ public class OpenCliWsAgentConnectionProperties {
*/
private String nodeType = "shell";
+ /** 并行执行的 collect 任务上限,必须为正数。 */
+ private int maxConcurrentCollects = 4;
+
+ /** 排队的 collect 任务上限,零表示没有等待队列。 */
+ private int maxPendingCollects = 32;
+
/**
* 首次 {@code registered} 应答等待上限(毫秒)。
*/
diff --git a/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsCollectRequests.java b/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsCollectRequests.java
new file mode 100644
index 0000000..808290d
--- /dev/null
+++ b/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsCollectRequests.java
@@ -0,0 +1,132 @@
+package io.github.easy4j.opencli.center.ws;
+
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.LongSupplier;
+
+/** Tracks accepted requests and bounded, instance-local replay results. */
+final class OpenCliWsCollectRequests {
+
+ enum Status {
+ ACCEPTED, IN_FLIGHT, CONFLICT, CACHED
+ }
+
+ static final class Key {
+ private final Object center;
+ private final String requestId;
+
+ Key(Object center, String requestId) {
+ this.center = center;
+ this.requestId = requestId;
+ }
+
+ String requestId() {
+ return requestId;
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (!(other instanceof Key)) {
+ return false;
+ }
+ Key key = (Key) other;
+ return center.equals(key.center) && requestId.equals(key.requestId);
+ }
+
+ @Override
+ public int hashCode() {
+ return 31 * center.hashCode() + requestId.hashCode();
+ }
+ }
+
+ static final class Admission {
+ private final Status status;
+ private final ObjectNode cachedResult;
+
+ Admission(Status status, ObjectNode cachedResult) {
+ this.status = status;
+ this.cachedResult = cachedResult;
+ }
+
+ Status status() {
+ return status;
+ }
+
+ ObjectNode cachedResult() {
+ return cachedResult;
+ }
+ }
+
+ private static final class Completed {
+ private final byte[] digest;
+ private final ObjectNode result;
+ private final long completedAt;
+
+ Completed(byte[] digest, ObjectNode result, long completedAt) {
+ this.digest = digest;
+ this.result = result;
+ this.completedAt = completedAt;
+ }
+ }
+
+ private final Map inFlight = new HashMap<>();
+ private final Map completed = new LinkedHashMap<>();
+ private final int maxCompleted;
+ private final long ttlNanos;
+ private final LongSupplier clock;
+
+ OpenCliWsCollectRequests(int maxCompleted, long ttlNanos, LongSupplier clock) {
+ this.maxCompleted = maxCompleted;
+ this.ttlNanos = ttlNanos;
+ this.clock = clock;
+ }
+
+ synchronized Admission reserve(Key key, byte[] digest) {
+ byte[] active = inFlight.get(key);
+ if (Objects.nonNull(active)) {
+ return new Admission(Arrays.equals(active, digest) ? Status.IN_FLIGHT : Status.CONFLICT, null);
+ }
+ expire(clock.getAsLong());
+ Completed previous = completed.get(key);
+ if (Objects.nonNull(previous)) {
+ if (!Arrays.equals(previous.digest, digest)) {
+ return new Admission(Status.CONFLICT, null);
+ }
+ return new Admission(Status.CACHED, previous.result.deepCopy().put("cached", true));
+ }
+ inFlight.put(key, digest);
+ return new Admission(Status.ACCEPTED, null);
+ }
+
+ synchronized void complete(Key key, ObjectNode result) {
+ byte[] digest = inFlight.remove(key);
+ if (Objects.isNull(digest) || Objects.isNull(result)) {
+ return;
+ }
+ long now = clock.getAsLong();
+ expire(now);
+ if (completed.size() >= maxCompleted) {
+ Iterator entries = completed.keySet().iterator();
+ entries.next();
+ entries.remove();
+ }
+ completed.put(key, new Completed(digest, result, now));
+ }
+
+ synchronized void clear() {
+ inFlight.clear();
+ completed.clear();
+ }
+
+ private void expire(long now) {
+ Iterator entries = completed.values().iterator();
+ while (entries.hasNext() && now - entries.next().completedAt >= ttlNanos) {
+ entries.remove();
+ }
+ }
+}
diff --git a/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentClient.java b/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentClient.java
index b1a5fd8..026d669 100644
--- a/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentClient.java
+++ b/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentClient.java
@@ -8,9 +8,10 @@
import io.github.easy4j.opencli.core.OpenCliExecutor;
import io.github.easy4j.opencli.core.OpenCliResult;
import io.github.easy4j.opencli.exception.OpenCliException;
-import io.github.easy4j.opencli.exception.OpenCliNonZeroExitException;
import io.github.easy4j.opencli.util.OpenCliStrings;
import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
@@ -18,9 +19,13 @@
import java.util.List;
import java.util.Map;
import java.util.Objects;
+import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.SynchronousQueue;
+import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import lombok.extern.slf4j.Slf4j;
@@ -48,18 +53,15 @@
public final class OpenCliWsReverseAgentClient implements AutoCloseable {
private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final long CLOSE_WAIT_NANOS = TimeUnit.SECONDS.toNanos(5);
private final OpenCliExecutor localExecutor;
private final OpenCliWsAgentConnectionProperties connectionProperties;
- private final ExecutorService collectPool =
- Executors.newCachedThreadPool(
- r -> {
- Thread t = new Thread(r, "opencli-ws-collect");
- t.setDaemon(true);
- return t;
- });
+ private final ExecutorService collectPool;
+ private final OpenCliWsCollectRequests collectRequests =
+ new OpenCliWsCollectRequests(1024, TimeUnit.MINUTES.toNanos(10), System::nanoTime);
private volatile boolean shutdownRequested;
@@ -76,6 +78,17 @@ public OpenCliWsReverseAgentClient(
Objects.requireNonNull(openCliProperties, "openCliProperties");
this.connectionProperties =
Objects.requireNonNull(connectionProperties, "connectionProperties");
+ int workers = connectionProperties.getMaxConcurrentCollects();
+ int pending = connectionProperties.getMaxPendingCollects();
+ if (workers <= 0 || pending < 0 || (long) workers + pending >= Integer.MAX_VALUE) {
+ throw new IllegalArgumentException("Collect capacity requires positive concurrency and a finite pending queue");
+ }
+ BlockingQueue queue = pending == 0 ? new SynchronousQueue<>() : new LinkedBlockingQueue<>(pending);
+ this.collectPool = new ThreadPoolExecutor(workers, workers, 0L, TimeUnit.MILLISECONDS, queue, runnable -> {
+ Thread thread = new Thread(runnable, "opencli-ws-collect");
+ thread.setDaemon(true);
+ return thread;
+ });
this.localExecutor = new OpenCliExecutor(openCliProperties.copyForLocalCliExecution());
}
@@ -83,6 +96,9 @@ public OpenCliWsReverseAgentClient(
* 启动后台重连线程。
*/
public synchronized void start() {
+ if (collectPool.isShutdown()) {
+ throw new IllegalStateException("WebSocket worker is closed");
+ }
if (runnerThread != null && runnerThread.isAlive()) {
return;
}
@@ -113,8 +129,26 @@ public synchronized void stop() {
@Override
public void close() {
- stop();
- collectPool.shutdown();
+ Thread runner;
+ synchronized (this) {
+ if (collectPool.isShutdown()) {
+ return;
+ }
+ stop();
+ collectPool.shutdownNow();
+ collectRequests.clear();
+ runner = runnerThread;
+ }
+ long deadline = System.nanoTime() + CLOSE_WAIT_NANOS;
+ try {
+ collectPool.awaitTermination(CLOSE_WAIT_NANOS, TimeUnit.NANOSECONDS);
+ long remaining = deadline - System.nanoTime();
+ if (remaining > 0 && Objects.nonNull(runner) && runner != Thread.currentThread()) {
+ TimeUnit.NANOSECONDS.timedJoin(runner, remaining);
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
}
private void runLoop() {
@@ -153,9 +187,10 @@ private void runLoop() {
private void runOneSession() throws Exception {
validateConnectionProperties();
- String wsUrl =
- OpenCliCenterWsUrls.toAgentWebSocketUrl(
- connectionProperties.getCentralApiBaseUrl(), connectionProperties.getWebSocketPath());
+ URI endpoint = URI.create(OpenCliCenterWsUrls.toAgentWebSocketUrl(
+ connectionProperties.getCentralApiBaseUrl(), connectionProperties.getWebSocketPath()));
+ // The default TLS client verifies the endpoint hostname. Plain WS has session-local identity.
+ Object centerIdentity = "wss".equalsIgnoreCase(endpoint.getScheme()) ? endpoint : new Object();
final CountDownLatch registered = new CountDownLatch(1);
final CountDownLatch sessionClosed = new CountDownLatch(1);
@@ -163,7 +198,7 @@ private void runOneSession() throws Exception {
log.info("opencli ws connecting");
WebSocketClient client =
- new WebSocketClient(URI.create(wsUrl)) {
+ new WebSocketClient(endpoint) {
@Override
public void onOpen(ServerHandshake handshake) {
try {
@@ -178,7 +213,7 @@ public void onOpen(ServerHandshake handshake) {
@Override
public void onMessage(String message) {
try {
- handleTextMessage(this, message, registered, handshakeFailure);
+ handleTextMessage(this, centerIdentity, message, registered, handshakeFailure);
} catch (Exception e) {
log.warn("handle ws message failed");
}
@@ -276,6 +311,7 @@ private String buildRegisterJson() throws Exception {
private void handleTextMessage(
WebSocketClient ws,
+ Object centerIdentity,
String payload,
CountDownLatch registered,
AtomicReference handshakeFailure)
@@ -294,13 +330,61 @@ private void handleTextMessage(
return;
}
if ("collect".equals(type)) {
- final JsonNode msg = root;
- collectPool.submit(() -> runCollectSafe(ws, msg));
+ JsonNode id = root.path("request_id");
+ String requestId = id.isTextual() ? id.textValue() : "";
+ if ((OpenCliStrings.isBlank(requestId) || requestId.codePoints().allMatch(Character::isWhitespace)) || requestId.getBytes(StandardCharsets.UTF_8).length > 128) {
+ sendResult(ws, result("", false, Collections.emptyList(), "invalid worker request ID"));
+ return;
+ }
+ if (shutdownRequested || !ws.isOpen() || registered.getCount() > 0
+ || Objects.nonNull(handshakeFailure.get())) {
+ sendResult(ws, result(requestId, false, Collections.emptyList(), "worker is not registered"));
+ return;
+ }
+ admitCollect(ws, centerIdentity, requestId, root);
+ }
+ }
+
+ private void admitCollect(WebSocketClient ws, Object centerIdentity, String requestId, JsonNode payload)
+ throws Exception {
+ OpenCliWsCollectRequests.Key key = new OpenCliWsCollectRequests.Key(centerIdentity, requestId);
+ byte[] digest = MessageDigest.getInstance("SHA-256").digest(MAPPER.writeValueAsBytes(payload));
+ OpenCliWsCollectRequests.Admission admission = collectRequests.reserve(key, digest);
+ switch (admission.status()) {
+ case IN_FLIGHT:
+ return;
+ case CONFLICT:
+ sendResult(ws, result(requestId, false, Collections.emptyList(), "worker request ID conflict"));
+ return;
+ case CACHED:
+ sendResult(ws, admission.cachedResult());
+ return;
+ case ACCEPTED:
+ try {
+ collectPool.execute(() -> runCollectSafe(ws, key, payload));
+ } catch (RejectedExecutionException e) {
+ collectRequests.complete(key, null);
+ sendResult(ws, result(requestId, false, Collections.emptyList(), "worker is busy"));
+ }
+ return;
+ }
+ }
+
+ private void runCollectSafe(WebSocketClient ws, OpenCliWsCollectRequests.Key key, JsonNode msg) {
+ ObjectNode response = null;
+ try {
+ if (!collectPool.isShutdown() && !Thread.currentThread().isInterrupted()) {
+ response = executeCollect(key.requestId(), msg);
+ }
+ } finally {
+ collectRequests.complete(key, response);
+ }
+ if (Objects.nonNull(response) && ws.isOpen()) {
+ sendResult(ws, response);
}
}
- private void runCollectSafe(WebSocketClient ws, JsonNode msg) {
- String requestId = msg.path("request_id").asText("");
+ private ObjectNode executeCollect(String requestId, JsonNode msg) {
try {
String site = msg.path("site").asText("");
String command = msg.path("command").asText("");
@@ -313,27 +397,17 @@ private void runCollectSafe(WebSocketClient ws, JsonNode msg) {
OpenCliResult r = localExecutor.invoke(argv);
List items = OpenCliWsCollectStdoutItems.parseItems(r.getStdout(), format);
if (!r.isSuccess()) {
- sendResult(ws, requestId, false, items, "opencli reported failure");
- return;
+ return result(requestId, false, items, "opencli reported failure");
}
- sendResult(ws, requestId, true, items, null);
- } catch (OpenCliNonZeroExitException e) {
- OpenCliResult partial = e.getPartialResult();
- String err =
- Objects.nonNull(partial) && OpenCliStrings.isNotBlank(partial.getStderr())
- ? partial.getStderr()
- : e.getMessage();
- sendResult(ws, requestId, false, Collections.emptyList(), err);
+ return result(requestId, true, items, null);
} catch (OpenCliException e) {
OpenCliResult partial = e.getPartialResult();
- String err =
- Objects.nonNull(partial) && OpenCliStrings.isNotBlank(partial.getStderr())
- ? partial.getStderr()
- : e.getMessage();
- sendResult(ws, requestId, false, Collections.emptyList(), err);
+ String err = Objects.nonNull(partial) && OpenCliStrings.isNotBlank(partial.getStderr())
+ ? partial.getStderr() : e.getMessage();
+ return result(requestId, false, Collections.emptyList(), err);
} catch (Exception e) {
log.warn("collect execution failed");
- sendResult(ws, requestId, false, Collections.emptyList(), "collect execution failed");
+ return result(requestId, false, Collections.emptyList(), "collect execution failed");
}
}
@@ -385,26 +459,26 @@ private static List readPositionalList(JsonNode node) {
return list;
}
- private static void sendResult(
- WebSocketClient ws, String requestId, boolean success, List items, String error) {
+ private static ObjectNode result(String requestId, boolean success, List items, String error) {
+ ObjectNode out = MAPPER.createObjectNode();
+ out.put("type", "result");
+ out.put("request_id", requestId);
+ out.put("success", success);
+ ArrayNode arr = out.putArray("items");
+ if (Objects.nonNull(items)) {
+ items.forEach(arr::add);
+ }
+ if (Objects.isNull(error) || error.isEmpty()) {
+ out.putNull("error");
+ } else {
+ out.put("error", error);
+ }
+ return out;
+ }
+
+ private static void sendResult(WebSocketClient ws, ObjectNode result) {
try {
- ObjectNode out = MAPPER.createObjectNode();
- out.put("type", "result");
- out.put("request_id", requestId);
- out.put("success", success);
- ArrayNode arr = MAPPER.createArrayNode();
- if (Objects.nonNull(items)) {
- for (JsonNode i : items) {
- arr.add(i);
- }
- }
- out.set("items", arr);
- if (Objects.isNull(error) || error.isEmpty()) {
- out.putNull("error");
- } else {
- out.put("error", error);
- }
- ws.send(MAPPER.writeValueAsString(out));
+ ws.send(MAPPER.writeValueAsString(result));
} catch (Exception e) {
log.error("failed to send WS result");
}
diff --git a/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsCollectRequestsTest.java b/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsCollectRequestsTest.java
new file mode 100644
index 0000000..9e90c2d
--- /dev/null
+++ b/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsCollectRequestsTest.java
@@ -0,0 +1,45 @@
+package io.github.easy4j.opencli.center.ws;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import java.util.concurrent.atomic.AtomicLong;
+import org.junit.jupiter.api.Test;
+
+import static io.github.easy4j.opencli.center.ws.OpenCliWsCollectRequests.Status.ACCEPTED;
+import static io.github.easy4j.opencli.center.ws.OpenCliWsCollectRequests.Status.CACHED;
+import static io.github.easy4j.opencli.center.ws.OpenCliWsCollectRequests.Status.CONFLICT;
+import static io.github.easy4j.opencli.center.ws.OpenCliWsCollectRequests.Status.IN_FLIGHT;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class OpenCliWsCollectRequestsTest {
+
+ @Test
+ void evictsAndExpiresCompletedResultsWithoutDroppingActiveReservations() {
+ AtomicLong clock = new AtomicLong();
+ OpenCliWsCollectRequests requests = new OpenCliWsCollectRequests(1, 100, clock::get);
+ OpenCliWsCollectRequests.Key active = new OpenCliWsCollectRequests.Key("center", "active");
+ OpenCliWsCollectRequests.Key first = new OpenCliWsCollectRequests.Key("center", "first");
+ OpenCliWsCollectRequests.Key second = new OpenCliWsCollectRequests.Key("center", "second");
+ byte[] digest = {1};
+ ObjectNode result = new ObjectMapper().createObjectNode().put("success", true);
+
+ assertEquals(ACCEPTED, requests.reserve(active, digest).status());
+ assertEquals(ACCEPTED, requests.reserve(first, digest).status());
+ requests.complete(first, result);
+ assertEquals(ACCEPTED, requests.reserve(second, digest).status());
+ requests.complete(second, result);
+
+ assertEquals(IN_FLIGHT, requests.reserve(active, digest).status());
+ assertEquals(CONFLICT, requests.reserve(active, new byte[] {2}).status());
+ assertEquals(ACCEPTED, requests.reserve(first, digest).status());
+ assertEquals(CACHED, requests.reserve(second, digest).status());
+ assertTrue(requests.reserve(second, digest).cachedResult().path("cached").asBoolean());
+ assertFalse(result.has("cached"));
+
+ clock.set(100);
+ assertEquals(ACCEPTED, requests.reserve(second, digest).status());
+ assertEquals(IN_FLIGHT, requests.reserve(active, digest).status());
+ }
+}
diff --git a/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java b/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java
new file mode 100644
index 0000000..200a3cd
--- /dev/null
+++ b/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java
@@ -0,0 +1,540 @@
+package io.github.easy4j.opencli.center.ws;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.easy4j.opencli.OpenCliProperties;
+import io.github.easy4j.opencli.contract.ContractProbe;
+import io.github.easy4j.opencli.contract.LifecycleProbe;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.security.KeyStore;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.List;
+import java.util.Objects;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManagerFactory;
+import org.java_websocket.WebSocket;
+import org.java_websocket.handshake.ClientHandshake;
+import org.java_websocket.server.DefaultSSLWebSocketServerFactory;
+import org.java_websocket.server.WebSocketServer;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.api.parallel.Isolated;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+@Isolated
+class OpenCliWsReverseAgentSessionTest {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final String AGENT_URL = "http://127.0.0.1:19823";
+
+ @Test
+ void exchangesRegistrationAndCollectResultsAndReconnectsAfterRemoteClose() throws Exception {
+ try (LocalCenter center = new LocalCenter()) {
+ OpenCliWsAgentConnectionProperties connection = center.agentProperties();
+ connection.setMode("");
+ connection.setNodeType("");
+ connection.setLabel(null);
+ try (OpenCliWsReverseAgentClient agent = new OpenCliWsReverseAgentClient(probe(ContractProbe.class.getName()), connection)) {
+ agent.start();
+ WireMessage registration = center.receive("register");
+ assertEquals(AGENT_URL, registration.body.path("agent_url").asText());
+ assertEquals("cdp", registration.body.path("mode").asText());
+ assertEquals("shell", registration.body.path("node_type").asText());
+ assertTrue(registration.body.path("label").asText().isEmpty());
+
+ registration.socket.send("{\"type\":\"registered\"}");
+ agent.start();
+ registration.socket.send("malformed-json");
+ registration.socket.send("{\"type\":\"pong\"}");
+ registration.socket.send("{\"type\":\"ping\"}");
+ center.receive("pong");
+
+ registration.socket.send("{\"type\":\"collect\",\"request_id\":\"valid\","
+ + "\"site\":\"demo\",\"command\":\"echo\",\"format\":\"text\","
+ + "\"positional_args\":[\" kept \",null,42],\"args\":{"
+ + "\"flag\":null,\"boolean\":false,\"count\":7,\"long\":2147483648,"
+ + "\"double\":1.5,\"text\":\"a b\",\"structured\":{\"key\":1}}}");
+ JsonNode result = center.receive("result").body;
+ assertEquals("valid", result.path("request_id").asText());
+ assertTrue(result.path("success").asBoolean());
+ assertTrue(result.path("error").isNull());
+ List argv = Arrays.stream(result.path("items").get(0).path("content").asText().split("\\R"))
+ .filter(line -> line.startsWith("arg:"))
+ .map(line -> new String(Base64.getDecoder().decode(line.substring(4)), StandardCharsets.UTF_8))
+ .collect(Collectors.toList());
+ assertEquals(Arrays.asList("demo", "echo", " kept ", "42", "--flag", "--boolean",
+ "false", "--count", "7", "--long", "2147483648", "--double", "1.5", "--text",
+ "a b", "--structured", "{\"key\":1}", "-f", "text"), argv);
+
+ registration.socket.send("{\"type\":\"collect\",\"request_id\":\"invalid\",\"command\":\"echo\"}");
+ JsonNode invalid = center.receive("result").body;
+ assertEquals("invalid", invalid.path("request_id").asText());
+ assertFalse(invalid.path("success").asBoolean());
+ assertTrue(invalid.path("items").isEmpty());
+ assertEquals("collect execution failed", invalid.path("error").asText());
+
+ registration.socket.close();
+ WireMessage retry = center.receive("register");
+ assertNotSame(registration.socket, retry.socket);
+ assertEquals(registration.body, retry.body);
+ }
+ }
+ }
+
+ @Test
+ void collectBeforeRegistrationAcknowledgementDoesNotStartChild(@TempDir Path temporary) throws Exception {
+ Path marker = temporary.resolve("child-started");
+ try (LocalCenter center = new LocalCenter();
+ OpenCliWsReverseAgentClient agent = new OpenCliWsReverseAgentClient(
+ probe(LifecycleProbe.class.getName()), center.agentProperties())) {
+ agent.start();
+ WireMessage registration = center.receive("register");
+ registration.socket.send(MAPPER.createObjectNode()
+ .put("type", "collect").put("request_id", "early").put("site", "write")
+ .put("command", marker.toString()).toString());
+ JsonNode rejected = center.receive("result").body;
+ assertEquals("early", rejected.path("request_id").asText());
+ assertFalse(Files.exists(marker), "an unregistered collect started a child");
+ assertFalse(rejected.path("success").asBoolean());
+ assertEquals("worker is not registered", rejected.path("error").asText());
+ }
+ }
+
+ @Test
+ void defaultsToFourActiveCollects(@TempDir Path temporary) throws Exception {
+ Path release = temporary.resolve("release");
+ OpenCliProperties properties = probe(LifecycleProbe.class.getName());
+ properties.setMaxConcurrentExecutions(8);
+ properties.setCommandTimeoutMillis(10_000);
+ try (LocalCenter center = new LocalCenter();
+ OpenCliWsReverseAgentClient agent = new OpenCliWsReverseAgentClient(properties, center.agentProperties())) {
+ agent.start();
+ WebSocket socket = center.receive("register").socket;
+ socket.send("{\"type\":\"registered\"}");
+ try {
+ for (int index = 0; index < 4; index++) {
+ sendHeldCollect(socket, "collect-" + index, temporary.resolve("child-" + index), release);
+ }
+ for (int index = 0; index < 4; index++) {
+ assertTrue(awaitMarker(temporary.resolve("child-" + index), 5_000), "initial child did not start");
+ }
+ Path queued = temporary.resolve("child-4");
+ sendHeldCollect(socket, "collect-4", queued, release);
+ assertFalse(awaitMarker(queued, 1_250), "a fifth collect started before a worker was free");
+ } finally {
+ Files.createFile(release);
+ }
+ Set completed = new HashSet<>();
+ for (int index = 0; index < 5; index++) {
+ JsonNode result = center.receive("result").body;
+ assertTrue(result.path("success").asBoolean(), result::toString);
+ completed.add(result.path("request_id").asText());
+ }
+ assertEquals(new HashSet<>(Arrays.asList("collect-0", "collect-1", "collect-2", "collect-3", "collect-4")),
+ completed);
+ assertTrue(Files.exists(temporary.resolve("child-4")));
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = {0, 1})
+ void rejectsOverflowWithoutLaunchingAnotherChild(int queueCapacity, @TempDir Path temporary) throws Exception {
+ Path release = temporary.resolve("release");
+ Path active = temporary.resolve("active");
+ Path queued = temporary.resolve("queued");
+ Path rejected = temporary.resolve("rejected");
+ try (LocalCenter center = new LocalCenter()) {
+ OpenCliWsAgentConnectionProperties connection = center.agentProperties();
+ connection.setMaxConcurrentCollects(1);
+ connection.setMaxPendingCollects(queueCapacity);
+ try (OpenCliWsReverseAgentClient agent = new OpenCliWsReverseAgentClient(
+ probe(LifecycleProbe.class.getName()), connection)) {
+ agent.start();
+ WebSocket socket = center.receive("register").socket;
+ socket.send("{\"type\":\"registered\"}");
+ try {
+ sendHeldCollect(socket, "active", active, release);
+ assertTrue(awaitMarker(active, 3_000), "first collect did not start");
+ if (queueCapacity > 0) {
+ sendHeldCollect(socket, "queued", queued, release);
+ }
+ sendHeldCollect(socket, "overflow", rejected, release);
+ JsonNode busy = center.receive("result").body;
+ assertEquals("overflow", busy.path("request_id").asText());
+ assertFalse(busy.path("success").asBoolean());
+ assertEquals("worker is busy", busy.path("error").asText());
+ assertFalse(Files.exists(rejected));
+ assertFalse(Files.exists(queued));
+ } finally {
+ Files.createFile(release);
+ }
+ JsonNode completed = center.receive("result").body;
+ assertEquals("active", completed.path("request_id").asText());
+ assertTrue(completed.path("success").asBoolean());
+ if (queueCapacity > 0) {
+ JsonNode drained = center.receive("result").body;
+ assertEquals("queued", drained.path("request_id").asText());
+ assertTrue(drained.path("success").asBoolean());
+ assertTrue(Files.exists(queued));
+ }
+ assertFalse(Files.exists(rejected));
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @CsvSource({"0,32", "-1,32", "4,-1", "4,2147483647", "4,2147483644"})
+ void rejectsInvalidCapacityBeforeConnection(int workers, int pending) {
+ OpenCliWsAgentConnectionProperties connection = new OpenCliWsAgentConnectionProperties();
+ connection.setMaxConcurrentCollects(workers);
+ connection.setMaxPendingCollects(pending);
+ assertThrows(IllegalArgumentException.class,
+ () -> new OpenCliWsReverseAgentClient(new OpenCliProperties(), connection));
+ }
+
+ @Test
+ void closeDropsQueuedCollectsAndRejectsRestart(@TempDir Path temporary) throws Exception {
+ Path release = temporary.resolve("release");
+ Path active = temporary.resolve("active");
+ Path queued = temporary.resolve("queued");
+ try (LocalCenter center = new LocalCenter()) {
+ OpenCliWsAgentConnectionProperties connection = center.agentProperties();
+ connection.setMaxConcurrentCollects(1);
+ connection.setMaxPendingCollects(1);
+ try (OpenCliWsReverseAgentClient agent = new OpenCliWsReverseAgentClient(
+ probe(LifecycleProbe.class.getName()), connection)) {
+ agent.start();
+ WebSocket socket = center.receive("register").socket;
+ socket.send("{\"type\":\"registered\"}");
+ try {
+ sendHeldCollect(socket, "active", active, release);
+ assertTrue(awaitMarker(active, 3_000), "first collect did not start");
+ sendHeldCollect(socket, "queued", queued, release);
+ socket.send("{\"type\":\"ping\"}");
+ center.receive("pong");
+ agent.close();
+ } finally {
+ Files.createFile(release);
+ }
+ assertFalse(awaitMarker(queued, 1_250), "queued collect started after close");
+ agent.close();
+ assertThrows(IllegalStateException.class, agent::start);
+ }
+ }
+ }
+
+ @Test
+ void duplicateRequestRunsOnceAndReplaysCompletedResult(@TempDir Path temporary) throws Exception {
+ Path marker = temporary.resolve("starts");
+ Path release = temporary.resolve("release");
+ Path changed = temporary.resolve("changed");
+ String payload = collect("same", "count-hold", marker)
+ .set("positional_args", MAPPER.createArrayNode().add(release.toString())).toString();
+ try (LocalCenter center = new LocalCenter();
+ OpenCliWsReverseAgentClient agent = new OpenCliWsReverseAgentClient(
+ probe(LifecycleProbe.class.getName()), center.agentProperties())) {
+ agent.start();
+ WebSocket socket = center.receive("register").socket;
+ socket.send("{\"type\":\"registered\"}");
+ try {
+ socket.send(payload);
+ assertTrue(awaitMarker(marker, 3_000), "original child did not start");
+ socket.send(payload);
+ socket.send(collect("same", "write", changed).toString());
+ JsonNode conflict = center.receive("result").body;
+ assertFalse(Files.exists(changed), "conflicting request started a child");
+ assertFalse(conflict.path("success").asBoolean());
+ assertEquals("worker request ID conflict", conflict.path("error").asText());
+ } finally {
+ Files.createFile(release);
+ }
+ JsonNode completed = center.receive("result").body;
+ assertTrue(completed.path("success").asBoolean());
+ assertFalse(completed.has("cached"));
+ socket.send(payload);
+ JsonNode replayed = center.receive("result").body;
+ assertTrue(replayed.path("cached").asBoolean());
+ assertEquals(completed.path("items"), replayed.path("items"));
+ assertEquals(Arrays.asList("started"), Files.readAllLines(marker, StandardCharsets.UTF_8));
+ }
+ }
+
+ @Test
+ void rejectsInvalidRequestIdsBeforeExecution(@TempDir Path temporary) throws Exception {
+ Path marker = temporary.resolve("invalid-id-start");
+ try (LocalCenter center = new LocalCenter();
+ OpenCliWsReverseAgentClient agent = new OpenCliWsReverseAgentClient(
+ probe(LifecycleProbe.class.getName()), center.agentProperties())) {
+ agent.start();
+ WebSocket socket = center.receive("register").socket;
+ socket.send("{\"type\":\"registered\"}");
+ for (JsonNode invalid : Arrays.asList(MAPPER.nullNode(), MAPPER.getNodeFactory().textNode(" "),
+ MAPPER.getNodeFactory().numberNode(42), MAPPER.getNodeFactory().textNode(String.join("", Collections.nCopies(43, "界"))))) {
+ ObjectNode payload = collect("unused", "write", marker);
+ payload.set("request_id", invalid);
+ socket.send(payload.toString());
+ JsonNode reply = center.receive("result").body;
+ assertEquals("", reply.path("request_id").asText());
+ assertFalse(reply.path("success").asBoolean());
+ assertEquals("invalid worker request ID", reply.path("error").asText());
+ assertFalse(Files.exists(marker));
+ }
+ String limit = String.join("", Collections.nCopies(42, "界")) + "ab";
+ socket.send(collect(limit, "write", marker).toString());
+ JsonNode accepted = center.receive("result").body;
+ assertEquals(limit, accepted.path("request_id").asText());
+ assertTrue(accepted.path("success").asBoolean());
+ assertTrue(Files.exists(marker));
+ }
+ }
+
+ @Test
+ void plainWebSocketReconnectDoesNotExposePreviousSessionCache(@TempDir Path temporary) throws Exception {
+ verifyReconnectReplay(temporary, null, false);
+ }
+
+ @Test
+ void verifiedTlsReconnectReplaysOnlyAfterAnExplicitRetry(@TempDir Path temporary) throws Exception {
+ Path storePath = temporary.resolve("center.p12");
+ String keytool = System.getProperty("os.name").startsWith("Windows") ? "keytool.exe" : "keytool";
+ Path tool = Paths.get(System.getProperty("java.home"), "bin", keytool);
+ Process keygen = new ProcessBuilder(tool.toString(), "-genkeypair", "-alias", "center", "-keyalg", "RSA",
+ "-keysize", "2048", "-dname", "CN=localhost", "-ext", "SAN=IP:127.0.0.1", "-validity", "1",
+ "-storetype", "PKCS12", "-keystore", storePath.toString(), "-storepass", "test-password")
+ .redirectErrorStream(true).redirectOutput(temporary.resolve("keytool.log").toFile()).start();
+ try {
+ assertTrue(keygen.waitFor(10, TimeUnit.SECONDS));
+ assertEquals(0, keygen.exitValue());
+ } finally {
+ if (keygen.isAlive()) {
+ keygen.destroyForcibly();
+ }
+ }
+ KeyStore store = KeyStore.getInstance("PKCS12");
+ try (InputStream input = Files.newInputStream(storePath)) {
+ store.load(input, "test-password".toCharArray());
+ }
+ KeyManagerFactory keys = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
+ keys.init(store, "test-password".toCharArray());
+ SSLContext server = SSLContext.getInstance("TLS");
+ server.init(keys.getKeyManagers(), null, null);
+ TrustManagerFactory trust = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+ trust.init(store);
+ SSLContext trustedClient = SSLContext.getInstance("TLS");
+ trustedClient.init(null, trust.getTrustManagers(), null);
+ SSLContext previous = SSLContext.getDefault();
+ try {
+ SSLContext.setDefault(trustedClient);
+ verifyReconnectReplay(temporary, server, true);
+ } finally {
+ SSLContext.setDefault(previous);
+ }
+ }
+
+ private static void verifyReconnectReplay(Path temporary, SSLContext tls, boolean expectCache) throws Exception {
+ Path marker = temporary.resolve("reconnect-start");
+ Path release = temporary.resolve("reconnect-release");
+ ObjectNode request = collect("resend", "count-hold", marker);
+ request.putArray("positional_args").add(release.toString());
+ try (LocalCenter center = new LocalCenter(tls)) {
+ OpenCliWsAgentConnectionProperties connection = center.agentProperties();
+ connection.setMaxConcurrentCollects(1);
+ try (OpenCliWsReverseAgentClient agent = new OpenCliWsReverseAgentClient(
+ probe(LifecycleProbe.class.getName()), connection)) {
+ agent.start();
+ WebSocket first = center.receive("register").socket;
+ first.send("{\"type\":\"registered\"}");
+ try {
+ first.send(request.toString());
+ assertTrue(awaitMarker(marker, 3_000));
+ first.close();
+ WebSocket second = center.receive("register").socket;
+ second.send("{\"type\":\"registered\"}");
+ second.send("{\"type\":\"ping\"}");
+ center.receive("pong");
+ Files.createFile(release);
+ second.send(collect("barrier", "write", temporary.resolve("barrier")).toString());
+ JsonNode barrier = center.receive("result").body;
+ assertEquals("barrier", barrier.path("request_id").asText());
+ assertTrue(barrier.path("success").asBoolean());
+ assertEquals(Arrays.asList("started"), Files.readAllLines(marker, StandardCharsets.UTF_8));
+
+ second.send(request.toString());
+ JsonNode reply = center.receive("result").body;
+ assertTrue(reply.path("success").asBoolean(), reply::toString);
+ assertEquals(expectCache, reply.path("cached").asBoolean());
+ assertEquals(expectCache ? Arrays.asList("started") : Arrays.asList("started", "started"),
+ Files.readAllLines(marker, StandardCharsets.UTF_8));
+ } finally {
+ if (!Files.exists(release)) {
+ Files.createFile(release);
+ }
+ }
+ }
+ }
+ }
+
+ private static ObjectNode collect(String id, String command, Path marker) {
+ return MAPPER.createObjectNode().put("type", "collect").put("request_id", id)
+ .put("site", command).put("command", marker.toString());
+ }
+
+ private static void sendHeldCollect(WebSocket socket, String id, Path marker, Path release) {
+ ObjectNode message = MAPPER.createObjectNode()
+ .put("type", "collect").put("request_id", id).put("site", "hold").put("command", marker.toString());
+ message.putArray("positional_args").add(release.toString());
+ socket.send(message.toString());
+ }
+
+ private static boolean awaitMarker(Path marker, long timeoutMillis) throws InterruptedException {
+ long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMillis);
+ while (!Files.exists(marker) && System.nanoTime() < deadline) {
+ Thread.sleep(10);
+ }
+ return Files.exists(marker);
+ }
+
+ @Test
+ void retriesAfterHandshakeCloseAndReturnsChildFailureToCenter() throws Exception {
+ try (LocalCenter center = new LocalCenter();
+ OpenCliWsReverseAgentClient agent = new OpenCliWsReverseAgentClient(
+ probe("io.github.easy4j.opencli.contract.MissingFixture"), center.agentProperties())) {
+ agent.start();
+ WireMessage first = center.receive("register");
+ first.socket.close();
+ WireMessage second = center.receive("register");
+ assertNotSame(first.socket, second.socket);
+ second.socket.send("{\"type\":\"registered\"}");
+ second.socket.send("{\"type\":\"collect\",\"request_id\":\"child-failure\","
+ + "\"site\":\"demo\",\"command\":\"echo\"}");
+ JsonNode result = center.receive("result").body;
+ assertEquals("child-failure", result.path("request_id").asText());
+ assertFalse(result.path("success").asBoolean());
+ assertTrue(result.path("items").isEmpty());
+ assertTrue(result.path("error").asText().contains("io.github.easy4j.opencli.contract.MissingFixture"));
+ }
+ }
+
+ private static OpenCliProperties probe(String mainClass) {
+ OpenCliProperties properties = new OpenCliProperties();
+ String executable = System.getProperty("os.name").startsWith("Windows") ? "java.exe" : "java";
+ properties.setExecutable(new File(new File(System.getProperty("java.home"), "bin"), executable).getAbsolutePath());
+ properties.setLeadingArguments(Arrays.asList("-cp",
+ System.getProperty("surefire.test.class.path", System.getProperty("java.class.path")), mainClass));
+ properties.setCommandTimeoutMillis(5_000);
+ return properties;
+ }
+
+ private static final class WireMessage {
+ private final WebSocket socket;
+ private final JsonNode body;
+
+ private WireMessage(WebSocket socket, JsonNode body) {
+ this.socket = socket;
+ this.body = body;
+ }
+ }
+
+ private static final class LocalCenter extends WebSocketServer implements AutoCloseable {
+ private final CountDownLatch started = new CountDownLatch(1);
+ private final BlockingQueue messages = new LinkedBlockingQueue<>();
+ private final AtomicReference failure = new AtomicReference<>();
+
+ private final boolean secure;
+
+ private LocalCenter() throws Exception {
+ this(null);
+ }
+
+ private LocalCenter(SSLContext tls) throws Exception {
+ super(new InetSocketAddress("127.0.0.1", 0), 1);
+ this.secure = Objects.nonNull(tls);
+ if (secure) {
+ setWebSocketFactory(new DefaultSSLWebSocketServerFactory(tls));
+ }
+ start();
+ if (!started.await(5, TimeUnit.SECONDS) || Objects.nonNull(failure.get())) {
+ stop(1_000);
+ throw new IllegalStateException("WebSocket test server failed to start", failure.get());
+ }
+ }
+
+ private OpenCliWsAgentConnectionProperties agentProperties() {
+ OpenCliWsAgentConnectionProperties properties = new OpenCliWsAgentConnectionProperties();
+ properties.setCentralApiBaseUrl((secure ? "https" : "http") + "://127.0.0.1:" + getPort());
+ properties.setAgentAdvertiseUrl(AGENT_URL);
+ properties.setMinReconnectDelayMillis(25);
+ properties.setMaxReconnectDelayMillis(50);
+ properties.setHandshakeTimeoutMillis(5_000);
+ return properties;
+ }
+
+ private WireMessage receive(String type) throws InterruptedException {
+ WireMessage message = messages.poll(8, TimeUnit.SECONDS);
+ assertNull(failure.get());
+ assertNotNull(message, "Expected WebSocket " + type + " response");
+ assertEquals(type, message.body.path("type").asText());
+ return message;
+ }
+
+ @Override
+ public void onOpen(WebSocket socket, ClientHandshake handshake) { }
+
+ @Override
+ public void onClose(WebSocket socket, int code, String reason, boolean remote) { }
+
+ @Override
+ public void onMessage(WebSocket socket, String payload) {
+ try {
+ messages.add(new WireMessage(socket, MAPPER.readTree(payload)));
+ } catch (IOException e) {
+ failure.compareAndSet(null, e);
+ }
+ }
+
+ @Override
+ public void onError(WebSocket socket, Exception error) {
+ failure.compareAndSet(null, error);
+ started.countDown();
+ }
+
+ @Override
+ public void onStart() {
+ started.countDown();
+ }
+
+ @Override
+ public void close() throws InterruptedException {
+ stop(1_000);
+ }
+ }
+}
diff --git a/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java b/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java
index 1b0c7a1..6bbe2d2 100644
--- a/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java
+++ b/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java
@@ -4,6 +4,7 @@
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
+import java.nio.file.StandardOpenOption;
import java.util.Arrays;
/** Offline, self-bounded child fixture. Release files allow cleanup even against a broken SDK. */
@@ -33,7 +34,12 @@ public static void main(String[] args) throws Exception {
return;
}
Path marker = Paths.get(args[1]);
- Files.write(marker, "started".getBytes(StandardCharsets.UTF_8));
+ if ("count-hold".equals(mode)) {
+ Files.write(marker, "started\n".getBytes(StandardCharsets.UTF_8),
+ StandardOpenOption.CREATE, StandardOpenOption.APPEND);
+ } else {
+ Files.write(marker, "started".getBytes(StandardCharsets.UTF_8));
+ }
if ("write".equals(mode)) { return; }
Path release = Paths.get(args[2]);
long start = System.nanoTime();
From 1f7fbadbd0f87ca6ead55d1401a8722be2b60324 Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Wed, 18 Nov 2026 21:54:06 +0800
Subject: [PATCH 010/105] ci: exercise reverse WebSocket contracts across
platforms
---
.github/workflows/platform-contracts.yml | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/.github/workflows/platform-contracts.yml b/.github/workflows/platform-contracts.yml
index 0c57fe8..ec39611 100644
--- a/.github/workflows/platform-contracts.yml
+++ b/.github/workflows/platform-contracts.yml
@@ -44,7 +44,7 @@ jobs:
mvn -version > platform-evidence/maven.txt 2>&1
result=0
mvn -B --no-transfer-progress \
- -Dtest=OpenCliArgvContractTest,OpenCliStructuredArgvContractTest,OpenCliProcessContractTest,OpenCliProcessBoundaryTest,SubprocessStreamFailureTest \
+ -Dtest=OpenCliArgvContractTest,OpenCliStructuredArgvContractTest,OpenCliProcessContractTest,OpenCliProcessBoundaryTest,SubprocessStreamFailureTest,OpenCliWsReverseAgentSessionTest,OpenCliWsCollectRequestsTest \
test > platform-evidence/maven.log 2>&1 || result=$?
tail -100 platform-evidence/maven.log
python scripts/contract_report.py \
@@ -59,6 +59,8 @@ jobs:
--suite process=io.github.easy4j.opencli.contract.OpenCliProcessContractTest \
--suite process=io.github.easy4j.opencli.contract.OpenCliProcessBoundaryTest \
--suite process=io.github.easy4j.opencli.core.support.SubprocessStreamFailureTest \
+ --suite protocol=io.github.easy4j.opencli.center.ws.OpenCliWsReverseAgentSessionTest \
+ --suite protocol=io.github.easy4j.opencli.center.ws.OpenCliWsCollectRequestsTest \
--output platform-evidence/report.json
exit "$result"
- name: Upload platform subprocess evidence
From 293c281a93c22a077d0f6a9b5ba2663bd6a6ea38 Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Wed, 18 Nov 2026 22:24:13 +0800
Subject: [PATCH 011/105] test: exercise OpenCLI process privacy across
platforms
---
.github/workflows/platform-contracts.yml | 3 +-
.../opencli/contract/LifecycleProbe.java | 24 +++++++++
.../core/OpenCliProcessPrivacyTest.java | 53 +++++++++++++------
3 files changed, 64 insertions(+), 16 deletions(-)
diff --git a/.github/workflows/platform-contracts.yml b/.github/workflows/platform-contracts.yml
index ec39611..5693d49 100644
--- a/.github/workflows/platform-contracts.yml
+++ b/.github/workflows/platform-contracts.yml
@@ -44,7 +44,7 @@ jobs:
mvn -version > platform-evidence/maven.txt 2>&1
result=0
mvn -B --no-transfer-progress \
- -Dtest=OpenCliArgvContractTest,OpenCliStructuredArgvContractTest,OpenCliProcessContractTest,OpenCliProcessBoundaryTest,SubprocessStreamFailureTest,OpenCliWsReverseAgentSessionTest,OpenCliWsCollectRequestsTest \
+ -Dtest=OpenCliArgvContractTest,OpenCliStructuredArgvContractTest,OpenCliProcessContractTest,OpenCliProcessBoundaryTest,SubprocessStreamFailureTest,OpenCliWsReverseAgentSessionTest,OpenCliWsCollectRequestsTest,OpenCliProcessPrivacyTest \
test > platform-evidence/maven.log 2>&1 || result=$?
tail -100 platform-evidence/maven.log
python scripts/contract_report.py \
@@ -61,6 +61,7 @@ jobs:
--suite process=io.github.easy4j.opencli.core.support.SubprocessStreamFailureTest \
--suite protocol=io.github.easy4j.opencli.center.ws.OpenCliWsReverseAgentSessionTest \
--suite protocol=io.github.easy4j.opencli.center.ws.OpenCliWsCollectRequestsTest \
+ --suite process=io.github.easy4j.opencli.core.OpenCliProcessPrivacyTest \
--output platform-evidence/report.json
exit "$result"
- name: Upload platform subprocess evidence
diff --git a/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java b/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java
index 6bbe2d2..6d4f20c 100644
--- a/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java
+++ b/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java
@@ -13,6 +13,10 @@ private LifecycleProbe() { }
public static void main(String[] args) throws Exception {
String mode = args[0];
+ if ("privacy".equals(mode)) {
+ exercisePrivacy(args[1], args[2]);
+ return;
+ }
if ("network-follow".equals(mode)) {
networkFollow(args);
return;
@@ -52,6 +56,26 @@ public static void main(String[] args) throws Exception {
}
}
+ private static void exercisePrivacy(String outcome, String canary) throws Exception {
+ switch (outcome) {
+ case "nonzero":
+ System.err.print(canary);
+ System.exit(7);
+ return;
+ case "timeout":
+ System.err.print(canary);
+ System.err.flush();
+ Thread.sleep(8000L);
+ return;
+ case "overflow":
+ System.out.print(canary);
+ main(new String[] {"stdout", "4096"});
+ return;
+ default:
+ throw new IllegalArgumentException("unknown privacy fixture outcome");
+ }
+ }
+
private static void networkFollow(String[] args) throws Exception {
if (!Arrays.asList("browser", "fixture", "network", "--follow")
.equals(Arrays.asList(args).subList(3, args.length))) {
diff --git a/src/test/java/io/github/easy4j/opencli/core/OpenCliProcessPrivacyTest.java b/src/test/java/io/github/easy4j/opencli/core/OpenCliProcessPrivacyTest.java
index e1a4a0f..03c9515 100644
--- a/src/test/java/io/github/easy4j/opencli/core/OpenCliProcessPrivacyTest.java
+++ b/src/test/java/io/github/easy4j/opencli/core/OpenCliProcessPrivacyTest.java
@@ -1,23 +1,26 @@
package io.github.easy4j.opencli.core;
import io.github.easy4j.opencli.OpenCliProperties;
+import io.github.easy4j.opencli.contract.LifecycleProbe;
import io.github.easy4j.opencli.exception.OpenCliException;
import io.github.easy4j.opencli.exception.OpenCliNonZeroExitException;
import io.github.easy4j.opencli.exception.OpenCliTimeoutException;
import java.io.ByteArrayOutputStream;
+import java.io.File;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
import java.util.UUID;
import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.condition.EnabledOnOs;
-import org.junit.jupiter.api.condition.OS;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.api.io.TempDir;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
class OpenCliProcessPrivacyTest {
@@ -33,34 +36,54 @@ void keepsMissingExecutablePathOutOfLogsAndStackTrace(@TempDir Path directory) t
}
@Test
- @EnabledOnOs({OS.LINUX, OS.MAC})
void preservesStderrOnNonzeroExitWithoutLeakingArgsOrStderr() throws Exception {
String canary = "stderr-" + UUID.randomUUID();
- OpenCliProperties properties = new OpenCliProperties();
- properties.setExecutable("/bin/sh");
-
- try (OpenCliExecutor executor = new OpenCliExecutor(properties)) {
+ try (OpenCliExecutor executor = new OpenCliExecutor(childProperties())) {
OpenCliNonZeroExitException failure = assertPrivateFailure(OpenCliNonZeroExitException.class, canary,
- () -> executor.invoke("-c", "printf '%s' \"$1\" >&2; exit 7", "fixture", canary));
+ () -> executor.invoke("privacy", "nonzero", canary));
assertEquals(canary, failure.getPartialResult().getStderr());
assertEquals(Integer.valueOf(7), failure.getPartialResult().getExitCode());
}
}
@Test
- @EnabledOnOs({OS.LINUX, OS.MAC})
- void keepsArgumentsOutOfTimeoutDiagnostics() throws Exception {
+ void keepsArgumentsAndPartialStderrOutOfTimeoutDiagnostics() throws Exception {
String canary = "timeout-" + UUID.randomUUID();
- OpenCliProperties properties = new OpenCliProperties();
- properties.setExecutable("/bin/sh");
- properties.setCommandTimeoutMillis(200);
+ OpenCliProperties properties = childProperties();
+ properties.setCommandTimeoutMillis(2500);
+
+ try (OpenCliExecutor executor = new OpenCliExecutor(properties)) {
+ OpenCliTimeoutException failure = assertPrivateFailure(OpenCliTimeoutException.class, canary,
+ () -> executor.invoke("privacy", "timeout", canary));
+ assertEquals(canary, failure.getPartialResult().getStderr());
+ }
+ }
+
+ @Test
+ void keepsPartialStdoutOutOfOutputLimitDiagnostics() throws Exception {
+ String canary = "overflow-" + UUID.randomUUID();
+ OpenCliProperties properties = childProperties();
+ properties.setMaxStdoutBytes(128);
try (OpenCliExecutor executor = new OpenCliExecutor(properties)) {
- assertPrivateFailure(OpenCliTimeoutException.class, canary,
- () -> executor.invoke("-c", "exec sleep 5", "fixture", canary));
+ OpenCliException failure = assertPrivateFailure(OpenCliException.class, canary,
+ () -> executor.invoke("privacy", "overflow", canary));
+ assertEquals("OUTPUT_LIMIT", failure.getPartialResult().getExecutionDetails().getTerminationReason().name());
+ assertEquals(128, failure.getPartialResult().getStdout().length());
+ assertTrue(failure.getPartialResult().getStdout().startsWith(canary));
}
}
+ private static OpenCliProperties childProperties() {
+ OpenCliProperties properties = new OpenCliProperties();
+ String executable = System.getProperty("os.name").startsWith("Windows") ? "java.exe" : "java";
+ properties.setExecutable(new File(new File(System.getProperty("java.home"), "bin"), executable).getAbsolutePath());
+ properties.setLeadingArguments(new ArrayList<>(Arrays.asList("-cp",
+ System.getProperty("surefire.test.class.path", System.getProperty("java.class.path")),
+ LifecycleProbe.class.getName())));
+ return properties;
+ }
+
private static T assertPrivateFailure(
Class type, String canary, Executable invocation) throws Exception {
ByteArrayOutputStream output = new ByteArrayOutputStream();
From 08dd848b2224bdecf25a0636e3f078b8c7ea3561 Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Wed, 18 Nov 2026 23:08:09 +0800
Subject: [PATCH 012/105] docs: record live OpenCLI network follow verification
---
.../harden-opencli-process-lifecycle/tasks.md | 14 +++++++++++++-
1 file changed, 13 insertions(+), 1 deletion(-)
diff --git a/openspec/changes/harden-opencli-process-lifecycle/tasks.md b/openspec/changes/harden-opencli-process-lifecycle/tasks.md
index 3e07948..cbd5636 100644
--- a/openspec/changes/harden-opencli-process-lifecycle/tasks.md
+++ b/openspec/changes/harden-opencli-process-lifecycle/tasks.md
@@ -29,4 +29,16 @@
`OpenCliProcessContractTest` 经 typed `browser network --follow` 入口运行真实 JVM fixture,校验 CLI argv,并覆盖正常退出、CLI 非零退出、输出超限、调用线程中断、执行超时,以及禁用时限时启动前拒绝。超时测试同时启动独立进程,确认该进程仍运行并可自行正常退出。JDK 8 执行 `mvn -B -ntp -o clean verify` 退出 0,全量 2,095 项(其中该类 14 项),0 失败、0 错误、0 跳过。
-本记录覆盖当前本地同步入口。平台矩阵、真实 OpenCLI 持续输出、受控 sink 和后代进程所有权仍需独立证据。
+## 2026-11-18 OC-PROC-006 真实 OpenCLI 验证
+
+使用 macOS 27.0.1 ARM64、Node 24.18.0、OpenCLI 1.8.6、Chrome for Testing 158.0.8127.18 和 [Browser Bridge 1.0.22](https://github.com/jackwener/OpenCLI/releases/tag/v1.8.6)。扩展归档的 SHA-256 为 `9d2e3d053948beab5d97124aa79b1532d2122e33e461eca56cac113afd33207a`。每条维护线使用新的临时浏览器配置和显式 profile 路由。页面和数据接口仅绑定回环地址,每 120 ms 发起一次带序号的请求。
+
+SDK 通过 `OpenCliBrowserSession.network` 设置 `follow(true)` 和 `all(true)`,实际运行 `opencli --profile browser network --follow --all`。探针分别使用 4,500 ms 时限和 64 KiB 上限,以及 12,000 ms 时限和 2,048 字节上限。每次解析部分 stdout 中完整的 JSON 行,确认来自测试接口、HTTP 状态为 200,且至少有两个不同请求。每条维护线用对应 JDK 执行 `test-compile`,JDK 21 使用仓库 Maven Wrapper。
+
+| JDK | 参与验证的功能分支提交 | 执行超时,完整事件 / 捕获字节 / 耗时 | 输出超限,完整事件 / 捕获字节 / 观测字节 / 耗时 |
+| --- | --- | --- | --- |
+| 8 | `293c281a93c22a077d0f6a9b5ba2663bd6a6ea38` | 34 / 6,044 / 4,519 ms | 11 / 2,048 / 2,844 / 2,220 ms |
+| 17 | `d22a1937ca43f03cb17a707710fb8899fa963b6d` | 34 / 6,044 / 4,524 ms | 11 / 2,048 / 2,132 / 2,204 ms |
+| 21 | `1ed41f928b4c906cb0499955687d33270c70c2ca` | 33 / 5,866 / 4,518 ms | 11 / 2,048 / 2,844 / 2,208 ms |
+
+6 个场景通过,0 失败、0 跳过。SDK 分别返回 `EXECUTION_TIMEOUT` 和 `OUTPUT_LIMIT`,均附带部分输出和 `ROOT_EXIT_CONFIRMED`。每组验证确认共享 daemon 的 PID 和隔离浏览器进程在两次调用后仍存活,后续标签页查询仍成功。当前结果验证 macOS 上的同步有界采集。受控 sink、后代进程所有权和其他操作系统上的真实浏览器验收仍待验证。
From 3761a0e78320ce3d67a97bfc437fda056bac8157 Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Wed, 18 Nov 2026 23:16:56 +0800
Subject: [PATCH 013/105] test: record OpenCLI error parser review evidence
---
.../evidence/2026-11-18-upstream-stderr.md | 39 +++++++++++++++++++
.../evidence/2026-11-18-yaml-parser-review.md | 16 ++++++++
.../preserve-opencli-error-envelope/tasks.md | 6 +--
.../resources/opencli-contracts/v1/SHA256SUMS | 3 ++
.../opencli-contracts/v1/error-argument.yaml | 6 +++
.../v1/error-auth-required.yaml | 6 +++
.../v1/error-empty-result-autofix.yaml | 8 ++++
7 files changed, 81 insertions(+), 3 deletions(-)
create mode 100644 openspec/changes/preserve-opencli-error-envelope/evidence/2026-11-18-upstream-stderr.md
create mode 100644 openspec/changes/preserve-opencli-error-envelope/evidence/2026-11-18-yaml-parser-review.md
create mode 100644 src/test/resources/opencli-contracts/v1/error-argument.yaml
create mode 100644 src/test/resources/opencli-contracts/v1/error-auth-required.yaml
create mode 100644 src/test/resources/opencli-contracts/v1/error-empty-result-autofix.yaml
diff --git a/openspec/changes/preserve-opencli-error-envelope/evidence/2026-11-18-upstream-stderr.md b/openspec/changes/preserve-opencli-error-envelope/evidence/2026-11-18-upstream-stderr.md
new file mode 100644
index 0000000..3c9dbb0
--- /dev/null
+++ b/openspec/changes/preserve-opencli-error-envelope/evidence/2026-11-18-upstream-stderr.md
@@ -0,0 +1,39 @@
+# OpenCLI 1.8.8 错误输出采样
+
+采样日期为 2026-11-18。运行环境使用 Node 24.18.0,npm 依赖安装在临时目录,三个样本各用隔离的 HOME。来源为 npm 包 `@jackwener/opencli@1.8.8`,包的发布校验值为 `sha512-T0rp89sVWMKdnQHoYwkRDuACy7k/lCvVScOZmpqnBhd1AnXG6XLYSYO6U0D/Zdj8qq9kQqgop3qmElNcbMr+sw==`。相关源码见已锁定的 [Adapter 渲染器](https://github.com/jackwener/OpenCLI/blob/8271afc67e8504bda94c147f446ee29775d08274/src/commanderAdapter.ts#L159) 和 [错误模型](https://github.com/jackwener/OpenCLI/blob/8271afc67e8504bda94c147f446ee29775d08274/src/errors.ts)。
+
+| 样本 | 执行方式 | 进程退出码 | YAML `error.exitCode` | stdout |
+|---|---|---:|---:|---:|
+| `error-argument.yaml` | 原生只读命令 `opencli 12306 stations '' -f json`,空参数在请求站点前被拒绝 | 2 | 2 | 0 字节 |
+| `error-auth-required.yaml` | 官方 Adapter 渲染受控 `AuthRequiredError` | 77 | 77 | 0 字节 |
+| `error-empty-result-autofix.yaml` | 官方 Adapter 渲染受控 `EmptyResultError` | 66 | 66 | 0 字节 |
+
+样本保存在 `src/test/resources/opencli-contracts/v1`,stderr 按字节保存,摘要见同目录的 `SHA256SUMS`。即使指定 `-f json`,三例的 stderr 均为 YAML。官方渲染器为 `EMPTY_RESULT` 附加 `# AutoFix` 注释,`AUTH_REQUIRED` 的样本没有该注释。如果后续 decoder 测试组合这两个字段,应标注为合成回归样本。
+
+## 复核受控样本
+
+在临时目录安装锁定包后,将下列内容保存为 `capture.mjs`,分别设置 `OPENCLI_FIXTURE=auth` 或 `OPENCLI_FIXTURE=empty`,用 Node 运行并独立收集 stdout、stderr 与退出码。
+
+```javascript
+import { Command } from 'commander';
+import { registerCommandToProgram } from './node_modules/@jackwener/opencli/dist/src/commanderAdapter.js';
+import { AuthRequiredError, EmptyResultError } from './node_modules/@jackwener/opencli/dist/src/errors.js';
+
+const program = new Command().name('opencli');
+registerCommandToProgram(program.command('fixture'), {
+ site: 'fixture',
+ name: 'check',
+ description: 'Offline fixture',
+ args: [],
+ browser: false,
+ func() {
+ if (process.env.OPENCLI_FIXTURE === 'auth') {
+ throw new AuthRequiredError('example.invalid');
+ }
+ throw new EmptyResultError('fixture/check', 'No rows in the offline fixture');
+ },
+});
+await program.parseAsync(['fixture', 'check', '-f', 'json'], { from: 'user' });
+```
+
+两个受控 Adapter 均在本地抛出错误。未执行登录、真实站点请求、写操作或注释中的修复命令。本次证据只完成 C03 任务 1.1,decoder 的实现和验收仍待评审。
diff --git a/openspec/changes/preserve-opencli-error-envelope/evidence/2026-11-18-yaml-parser-review.md b/openspec/changes/preserve-opencli-error-envelope/evidence/2026-11-18-yaml-parser-review.md
new file mode 100644
index 0000000..3bab2d6
--- /dev/null
+++ b/openspec/changes/preserve-opencli-error-envelope/evidence/2026-11-18-yaml-parser-review.md
@@ -0,0 +1,16 @@
+# C03 YAML 解析器候选验证(2026-11-18)
+
+C03 评审候选为 `org.yaml:snakeyaml:2.7`,三条 Java 维护线可共用。SnakeYAML Engine 的当前维护线要求 Java 11 或更新版本。[SnakeYAML](https://github.com/snakeyaml/snakeyaml) · [SnakeYAML Engine](https://github.com/snakeyaml/snakeyaml-engine) · [Maven Central 发布包](https://repo.maven.apache.org/maven2/org/yaml/snakeyaml/2.7/)
+
+## 探针结果
+
+独立探针使用 SHA-256 为 `2e194eba45a67dee19a4e272f4a04b18de8054e9f598b094382f6dae0b0e4b5e` 的 2.7 JAR。以 JDK 8 编译一次,在 8u504、17.0.21、21.0.13.0.2 各执行 30 个断言。三轮退出码均为 0。使用三个 [OpenCLI 1.8.8 真实 stderr 样本](2026-11-18-upstream-stderr.md) 及合成输入。探针未接入 SDK,SDK 当前行为仍由既有执行器决定。
+
+- 三个真实样本均读出 `ok: false`、原始错误码及整数退出码。带 `# AutoFix` 的样本正常解析。合成 JSON 子集保留未识别的错误码和 trace 路径。普通单行文本得到字符串,后续 envelope 校验应按原执行状态处理。
+- 普通 `SafeConstructor` 的 YAML 1.1 规则会将 `no`、`off` 和日期转成布尔值与日期类型。自定义隐式解析范围只接受 JSON 形式的布尔、空值、整数和小数。日期样式、`no`、`off` 和前导零字符串在探针中均保留原值。
+- 默认浮点映射会将 `1e400` 转为无穷大,并对长小数取近似值。探针改用 `BigDecimal` 保留两者,后续模型应避免以浮点近似值覆盖扩展字段。
+- 用库的事件流预检,拒绝锚点和别名、显式标记、多个文档及超过 32 层的集合。用加载选项拒绝重复键。UTF-8 字节检查在入口执行,加载器另外限制码点数。探针验证了 32 层和 256 KiB 边界、多字节超限、截断的 JSON 形态以及被禁止的 YAML 特性。普通运行日志仅记录断言数量。
+
+## 实现评审范围
+
+建议在 JSON 路径复用各分支已有 Jackson,并以严格 JSON 判定处理疑似 JSON 的失败输入。YAML 路径建议采用事件预检和受限构造,再检查 envelope 形状及字符串键。需用 SDK 测试验证退出码来源、解析状态、超时优先级、日志脱敏和无重试副作用。评审前保留 C03 任务 2.1 未勾选,三个 POM 均未引入该候选依赖。
diff --git a/openspec/changes/preserve-opencli-error-envelope/tasks.md b/openspec/changes/preserve-opencli-error-envelope/tasks.md
index fee0afa..b8ab4f1 100644
--- a/openspec/changes/preserve-opencli-error-envelope/tasks.md
+++ b/openspec/changes/preserve-opencli-error-envelope/tasks.md
@@ -1,17 +1,17 @@
# C03 Tasks · 上游错误协议解析与证据保真
-> 全部为待执行实现任务。文档/格式检查通过不允许提前勾选。
+> 已采集上游 stderr 样本,decoder 实现待评审。文档/格式检查通过不允许提前勾选。
关联规范:[spec](specs/opencli-error-envelope/spec.md)。
## 1. 错误 fixture
-- [ ] 1.1 从锁定上游 renderError/真实只读负例建立 YAML fixture,保存版本与 hash。
+- [x] 1.1 从锁定上游 renderError/真实只读负例建立 YAML fixture,保存版本与 hash。见 [上游 stderr 采样](evidence/2026-11-18-upstream-stderr.md)。
- [ ] 1.2 补 JSON、纯文本、AutoFix 注释、exit mismatch、unknown code、malformed 和恶意 YAML 失败测试。
## 2. decoder 与结果
-- [ ] 2.1 选定三线可用的安全 YAML 实现并验证安全配置,不复制不兼容 Jackson imports。
+- [ ] 2.1 选定三线可用的安全 YAML 实现并验证安全配置,不复制不兼容 Jackson imports。见 [三线候选探针](evidence/2026-11-18-yaml-parser-review.md)。
- [ ] 2.2 实现有界 shape 校验和 provenance 模型,保留 help/trace/unknown fields。
- [ ] 2.3 接入本地异常与 partial result,避免 parser 抢占 primary failure。
diff --git a/src/test/resources/opencli-contracts/v1/SHA256SUMS b/src/test/resources/opencli-contracts/v1/SHA256SUMS
index c7a5e08..3a1f826 100644
--- a/src/test/resources/opencli-contracts/v1/SHA256SUMS
+++ b/src/test/resources/opencli-contracts/v1/SHA256SUMS
@@ -1,2 +1,5 @@
e7e6dd57e81e24e92a7cb0de0e1204f95025f80310f5dc34d820aa7419636f78 argv.tsv
2fa30626c415bb3c152bc4c2827cd9282ba710654f6a56fb7bde70a83b2bc192 sources.lock.json
+2de5245d5a5692dc66d5fbc948d9c0929ba4baf12141ae2d9477771f7b17fb4f error-argument.yaml
+317a108a2d666fbf33554059b48691f363a33cd7a53bd8a94396bba045c9d522 error-auth-required.yaml
+1f587e1dc2f45648796dea428d3957560534b864e927d4d40db36563a5042b7f error-empty-result-autofix.yaml
diff --git a/src/test/resources/opencli-contracts/v1/error-argument.yaml b/src/test/resources/opencli-contracts/v1/error-argument.yaml
new file mode 100644
index 0000000..f3c7315
--- /dev/null
+++ b/src/test/resources/opencli-contracts/v1/error-argument.yaml
@@ -0,0 +1,6 @@
+ok: false
+error:
+ code: ARGUMENT
+ message: Argument "keyword" is required.
+ help: Chinese substring (上海), telecode (AOH), or pinyin (shanghai)
+ exitCode: 2
diff --git a/src/test/resources/opencli-contracts/v1/error-auth-required.yaml b/src/test/resources/opencli-contracts/v1/error-auth-required.yaml
new file mode 100644
index 0000000..3190d87
--- /dev/null
+++ b/src/test/resources/opencli-contracts/v1/error-auth-required.yaml
@@ -0,0 +1,6 @@
+ok: false
+error:
+ code: AUTH_REQUIRED
+ message: Not logged in to example.invalid
+ help: Please open Chrome or Chromium and log in to https://example.invalid
+ exitCode: 77
diff --git a/src/test/resources/opencli-contracts/v1/error-empty-result-autofix.yaml b/src/test/resources/opencli-contracts/v1/error-empty-result-autofix.yaml
new file mode 100644
index 0000000..2ea1e1a
--- /dev/null
+++ b/src/test/resources/opencli-contracts/v1/error-empty-result-autofix.yaml
@@ -0,0 +1,8 @@
+ok: false
+error:
+ code: EMPTY_RESULT
+ message: fixture/check returned no data
+ help: No rows in the offline fixture
+ exitCode: 66
+# AutoFix: re-run with --trace=retain-on-failure for trace artifact
+# opencli fixture check --trace retain-on-failure
From 4d42b937ba7366e4c5b15c2120123e660ef51e1b Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Wed, 18 Nov 2026 23:21:13 +0800
Subject: [PATCH 014/105] fix: cap OpenCLI capture buffer allocation
---
.../harden-opencli-process-lifecycle/tasks.md | 8 ++++++++
.../core/support/SubprocessExecutionSupport.java | 8 +++++++-
.../support/SubprocessExecutionSupportTest.java | 16 ++++++++++++++++
3 files changed, 31 insertions(+), 1 deletion(-)
diff --git a/openspec/changes/harden-opencli-process-lifecycle/tasks.md b/openspec/changes/harden-opencli-process-lifecycle/tasks.md
index cbd5636..a43041b 100644
--- a/openspec/changes/harden-opencli-process-lifecycle/tasks.md
+++ b/openspec/changes/harden-opencli-process-lifecycle/tasks.md
@@ -42,3 +42,11 @@ SDK 通过 `OpenCliBrowserSession.network` 设置 `follow(true)` 和 `all(true)`
| 21 | `1ed41f928b4c906cb0499955687d33270c70c2ca` | 33 / 5,866 / 4,518 ms | 11 / 2,048 / 2,844 / 2,208 ms |
6 个场景通过,0 失败、0 跳过。SDK 分别返回 `EXECUTION_TIMEOUT` 和 `OUTPUT_LIMIT`,均附带部分输出和 `ROOT_EXIT_CONFIRMED`。每组验证确认共享 daemon 的 PID 和隔离浏览器进程在两次调用后仍存活,后续标签页查询仍成功。当前结果验证 macOS 上的同步有界采集。受控 sink、后代进程所有权和其他操作系统上的真实浏览器验收仍待验证。
+
+## 2026-11-18 OC-PROC-003 捕获数组扩容
+
+JDK 17 红灯测试以 8,193 字节作为捕获上限,分两次写满,观察到旧实现把 backing array 扩到 16,384 字节。修复对单次分配容量应用捕获上限。回归验证 8,193 字节数组、原样保留的前缀、准确的观测字节数及截断标记。
+
+JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,114 项通过,0 失败、0 错误、0 跳过。真实 OpenCLI 1.8.6 两项复验通过。4,500 ms 时限返回 `EXECUTION_TIMEOUT` 并保留 34 条完整事件。2 KiB 上限返回 `OUTPUT_LIMIT` 并保留 2,048 字节和 11 条完整事件。两次均确认 SDK 启动的 CLI 子进程已退出,后续 daemon 查询可用。
+
+本次测量单个捕获数组的容量。整体堆内存峰值还包含扩容时的数组复制、输出快照和并发调用,任务 1.2 继续跟踪。
diff --git a/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java b/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
index 4efe49e..06f5f06 100644
--- a/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
+++ b/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
@@ -369,7 +369,7 @@ private static long nanos(long millis, String field) {
return millis * 1_000_000L;
}
- private static final class BoundedCapture extends ByteArrayOutputStream {
+ static final class BoundedCapture extends ByteArrayOutputStream {
private final int limit;
private long observed;
private boolean truncated;
@@ -385,12 +385,18 @@ public synchronized void write(byte[] bytes, int offset, int length) {
if (frozen) { return; }
observed = observed > Long.MAX_VALUE - length ? Long.MAX_VALUE : observed + length;
int retained = Math.min(length, limit - count);
+ int required = count + retained;
+ if (required > buf.length) {
+ int doubled = (int) Math.min(2L * buf.length, limit);
+ buf = Arrays.copyOf(buf, Math.max(required, doubled));
+ }
super.write(bytes, offset, retained);
truncated |= retained < length;
}
@Override
public synchronized void write(int value) { write(new byte[]{(byte) value}, 0, 1); }
+ synchronized int bufferCapacity() { return buf.length; }
synchronized boolean isTruncated() { return truncated; }
synchronized long observed() { return observed; }
synchronized void freeze() { frozen = true; }
diff --git a/src/test/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupportTest.java b/src/test/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupportTest.java
index 910ac18..8855f8f 100644
--- a/src/test/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupportTest.java
+++ b/src/test/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupportTest.java
@@ -5,6 +5,22 @@
class SubprocessExecutionSupportTest {
+ @Test
+ void shouldBoundBackingBufferGrowthAtTheConfiguredLimit() {
+ int limit = 8_193;
+ SubprocessExecutionSupport.BoundedCapture capture = new SubprocessExecutionSupport.BoundedCapture(limit);
+ byte[] chunk = new byte[8_192];
+ capture.write(chunk, 0, chunk.length);
+ capture.write(99);
+ capture.write(100);
+
+ assertEquals(limit, capture.bufferCapacity());
+ assertEquals(limit, capture.size());
+ assertEquals(99, capture.toByteArray()[limit - 1]);
+ assertEquals(limit + 1L, capture.observed());
+ assertTrue(capture.isTruncated());
+ }
+
@Test
void shouldReturnDefaultMaxConcurrent() {
int defaultVal = SubprocessExecutionSupport.defaultMaxConcurrentExecutions();
From 0e52caca7cef9b31752d343363f7addc756cdef8 Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Wed, 18 Nov 2026 23:26:33 +0800
Subject: [PATCH 015/105] test: verify OpenCLI saturated process and capture
limits
---
.../harden-opencli-process-lifecycle/tasks.md | 12 +++-
.../opencli/contract/LifecycleProbe.java | 28 +++++---
.../contract/OpenCliProcessContractTest.java | 67 +++++++++++++++++++
3 files changed, 96 insertions(+), 11 deletions(-)
diff --git a/openspec/changes/harden-opencli-process-lifecycle/tasks.md b/openspec/changes/harden-opencli-process-lifecycle/tasks.md
index a43041b..eaafa19 100644
--- a/openspec/changes/harden-opencli-process-lifecycle/tasks.md
+++ b/openspec/changes/harden-opencli-process-lifecycle/tasks.md
@@ -7,7 +7,7 @@
## 1. 资源回归
- [ ] 1.1 用可控子进程分别编写排队超时、并发 Client、取消、超限与 cleanup 竞态失败测试。
-- [ ] 1.2 测量在途进程与 capture 峰值;保留失败证据而不运行真实用户网站。
+- [x] 1.2 测量在途进程与 capture 峰值;保留失败证据而不运行真实用户网站。见本文 OC-PROC-001/002/003 饱和验证。
## 2. 执行核修复
@@ -49,4 +49,12 @@ JDK 17 红灯测试以 8,193 字节作为捕获上限,分两次写满,观察
JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,114 项通过,0 失败、0 错误、0 跳过。真实 OpenCLI 1.8.6 两项复验通过。4,500 ms 时限返回 `EXECUTION_TIMEOUT` 并保留 34 条完整事件。2 KiB 上限返回 `OUTPUT_LIMIT` 并保留 2,048 字节和 11 条完整事件。两次均确认 SDK 启动的 CLI 子进程已退出,后续 daemon 查询可用。
-本次测量单个捕获数组的容量。整体堆内存峰值还包含扩容时的数组复制、输出快照和并发调用,任务 1.2 继续跟踪。
+本次测量单个捕获数组的容量。整体堆内存还包含扩容时的数组复制、输出快照和并发调用,按独立指标记录。
+
+## 2026-11-18 OC-PROC-001/002/003 饱和验证
+
+`OpenCliProcessContractTest#sharedRuntimeBoundsConcurrentChildrenAndCombinedCapture` 使用三个客户端共享两个执行许可。两个真实 JVM 子进程分别写入 131,073 字节 stdout 和 65,539 字节 stderr,然后发出就绪标记并等待同一释放信号。两个子进程仍在途时提交四次调用,四次均返回 `QUEUE_TIMEOUT`,执行详情和子进程标记均确认没有启动进程。该场景在途峰值为 2。
+
+释放后,两次调用均确认根进程退出,四条输出流保留 393,224 字节,恰好达到两个执行槽的合计捕获预算,零截断。这个数值由执行详情测得,对应离线 fixture 的捕获量。JVM 整体堆内存还包含其他分配,本场景不对其计量。
+
+JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,115 项通过,0 失败、0 错误、0 跳过。
diff --git a/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java b/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java
index 6d4f20c..e8a2d55 100644
--- a/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java
+++ b/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java
@@ -1,5 +1,6 @@
package io.github.easy4j.opencli.contract;
+import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -26,17 +27,14 @@ public static void main(String[] args) throws Exception {
return;
}
if ("stdout".equals(mode) || "stderr".equals(mode)) {
- byte[] block = new byte[8192];
- Arrays.fill(block, (byte) 'x');
- int remaining = Integer.parseInt(args[1]);
- while (remaining > 0) {
- int size = Math.min(block.length, remaining);
- if ("stdout".equals(mode)) { System.out.write(block, 0, size); }
- else { System.err.write(block, 0, size); }
- remaining -= size;
- }
+ PrintStream stream = "stdout".equals(mode) ? System.out : System.err;
+ writeStream(stream, Integer.parseInt(args[1]));
return;
}
+ if ("capture-hold".equals(mode)) {
+ writeStream(System.out, Integer.parseInt(args[3]));
+ writeStream(System.err, Integer.parseInt(args[4]));
+ }
Path marker = Paths.get(args[1]);
if ("count-hold".equals(mode)) {
Files.write(marker, "started\n".getBytes(StandardCharsets.UTF_8),
@@ -56,6 +54,18 @@ public static void main(String[] args) throws Exception {
}
}
+ private static void writeStream(PrintStream stream, int bytes) {
+ byte[] block = new byte[8192];
+ Arrays.fill(block, (byte) 'x');
+ int remaining = bytes;
+ while (remaining > 0) {
+ int size = Math.min(block.length, remaining);
+ stream.write(block, 0, size);
+ remaining -= size;
+ }
+ stream.flush();
+ }
+
private static void exercisePrivacy(String outcome, String canary) throws Exception {
switch (outcome) {
case "nonzero":
diff --git a/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java b/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java
index aeb28af..0d49fb9 100644
--- a/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java
+++ b/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java
@@ -4,8 +4,10 @@
import io.github.easy4j.opencli.browser.OpenCliBrowserClient;
import io.github.easy4j.opencli.browser.OpenCliBrowserSession;
import io.github.easy4j.opencli.browser.OpenCliBrowserSession.OpenCliBrowserNetworkOptions;
+import io.github.easy4j.opencli.core.OpenCliExecutionDetails;
import io.github.easy4j.opencli.core.OpenCliExecutionDetails.TerminationReason;
import io.github.easy4j.opencli.core.OpenCliExecutor;
+import io.github.easy4j.opencli.core.OpenCliProcessRuntime;
import io.github.easy4j.opencli.core.OpenCliResult;
import io.github.easy4j.opencli.exception.OpenCliException;
import io.github.easy4j.opencli.exception.OpenCliNonZeroExitException;
@@ -321,6 +323,71 @@ void explicitSharedRuntimeLimitsBothClients() throws Exception {
}
}
+ @Test
+ void sharedRuntimeBoundsConcurrentChildrenAndCombinedCapture() throws Exception {
+ int stdoutLimit = 131_073;
+ int stderrLimit = 65_539;
+ OpenCliProcessRuntime runtime = new OpenCliProcessRuntime(2);
+ OpenCliProperties capture = properties(6);
+ capture.setMaxStdoutBytes(stdoutLimit);
+ capture.setMaxStderrBytes(stderrLimit);
+ OpenCliProperties queued = properties(6);
+ queued.setCommandTimeoutMillis(750L);
+ OpenCliExecutor first = new OpenCliExecutor(capture, runtime);
+ OpenCliExecutor second = new OpenCliExecutor(capture, runtime);
+ OpenCliExecutor waiting = new OpenCliExecutor(queued, runtime);
+ Path gate = dir.resolve("capture-release");
+ List markers = Arrays.asList(dir.resolve("capture-first"), dir.resolve("capture-second"));
+ ExecutorService workers = Executors.newFixedThreadPool(6);
+ try {
+ Future one = workers.submit(() -> first.invoke("capture-hold",
+ markers.get(0).toString(), gate.toString(), Integer.toString(stdoutLimit),
+ Integer.toString(stderrLimit)));
+ Future two = workers.submit(() -> second.invoke("capture-hold",
+ markers.get(1).toString(), gate.toString(), Integer.toString(stdoutLimit),
+ Integer.toString(stderrLimit)));
+ assertTrue(awaitFile(markers.get(0), 5_000L));
+ assertTrue(awaitFile(markers.get(1), 5_000L));
+
+ List> contenders = new ArrayList<>();
+ for (int index = 0; index < 4; index++) {
+ Path marker = dir.resolve("queued-" + index);
+ contenders.add(workers.submit(() -> {
+ OpenCliTimeoutException timeout = assertThrows(OpenCliTimeoutException.class,
+ () -> waiting.invoke("write", marker.toString()));
+ OpenCliExecutionDetails evidence = timeout.getPartialResult().getExecutionDetails();
+ assertEquals(TerminationReason.QUEUE_TIMEOUT, evidence.getTerminationReason());
+ assertFalse(evidence.isProcessStarted());
+ assertFalse(Files.exists(marker), "a queued invocation spawned a child");
+ }));
+ }
+ for (Future> contender : contenders) {
+ contender.get(4, TimeUnit.SECONDS);
+ }
+ assertFalse(one.isDone());
+ assertFalse(two.isDone());
+
+ release(gate);
+ long aggregateBytes = 0;
+ for (Future active : Arrays.asList(one, two)) {
+ OpenCliResult result = active.get(5, TimeUnit.SECONDS);
+ assertTrue(result.isSuccess());
+ OpenCliExecutionDetails evidence = result.getExecutionDetails();
+ assertEquals(stdoutLimit, evidence.getStdoutCapturedBytes());
+ assertEquals(stderrLimit, evidence.getStderrCapturedBytes());
+ assertFalse(evidence.isStdoutTruncated());
+ assertFalse(evidence.isStderrTruncated());
+ assertEquals(OpenCliExecutionDetails.CleanupState.ROOT_EXIT_CONFIRMED, evidence.getCleanupState());
+ aggregateBytes += evidence.getStdoutCapturedBytes() + evidence.getStderrCapturedBytes();
+ }
+ assertEquals(393_224L, aggregateBytes);
+ } finally {
+ release(gate);
+ workers.shutdownNow();
+ assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));
+ }
+ }
+
@Test
void preCancelledRequestNeverStartsAProcess() throws Exception {
Class> tokenType = assertDoesNotThrow(() -> Class.forName("io.github.easy4j.opencli.core.OpenCliCancellationToken"));
From 77569f8b20e0f382a9dab1027eeeffc8d1ecdde3 Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Wed, 18 Nov 2026 23:32:09 +0800
Subject: [PATCH 016/105] test: cover cancellation with inherited OpenCLI pipes
---
.../harden-opencli-process-lifecycle/tasks.md | 10 ++++-
.../opencli/contract/LifecycleProbe.java | 6 +++
.../contract/OpenCliProcessContractTest.java | 39 +++++++++++++++++++
3 files changed, 54 insertions(+), 1 deletion(-)
diff --git a/openspec/changes/harden-opencli-process-lifecycle/tasks.md b/openspec/changes/harden-opencli-process-lifecycle/tasks.md
index eaafa19..b255130 100644
--- a/openspec/changes/harden-opencli-process-lifecycle/tasks.md
+++ b/openspec/changes/harden-opencli-process-lifecycle/tasks.md
@@ -6,7 +6,7 @@
## 1. 资源回归
-- [ ] 1.1 用可控子进程分别编写排队超时、并发 Client、取消、超限与 cleanup 竞态失败测试。
+- [x] 1.1 用可控子进程分别编写排队超时、并发 Client、取消、超限与 cleanup 竞态失败测试。见本文 OC-PROC-004/005 回归矩阵。
- [x] 1.2 测量在途进程与 capture 峰值;保留失败证据而不运行真实用户网站。见本文 OC-PROC-001/002/003 饱和验证。
## 2. 执行核修复
@@ -58,3 +58,11 @@ JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,114 项通过,0
释放后,两次调用均确认根进程退出,四条输出流保留 393,224 字节,恰好达到两个执行槽的合计捕获预算,零截断。这个数值由执行详情测得,对应离线 fixture 的捕获量。JVM 整体堆内存还包含其他分配,本场景不对其计量。
JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,115 项通过,0 失败、0 错误、0 跳过。
+
+## 2026-11-18 OC-PROC-004/005 回归矩阵
+
+`OpenCliProcessContractTest` 使用真实子进程覆盖排队超时、独立和共享 Client 限流、取消及独立流超限。`SubprocessCompletionRaceTest` 用同步屏障覆盖输出超限、取消、watchdog 与进程结束竞争,确认唯一结果和许可复用。`SubprocessCleanupFaultTest` 注入 watchdog 初始化、流初始化、终止和清理异常,覆盖最初失败保留及无法确认退出的运行时隔离。
+
+新增真实继承管道回归。根进程启动继承 stdout、stderr 的独立 JVM,后者通过文件汇报心跳。观察到后代进程启动后取消调用。清理宽限配置为 250 ms,测试允许 1,500 ms 等待窗口,包含线程调度。SDK 仍返回 `CANCELLED`,流未排空时必须报告 `UNCONFIRMED`,并且不声称后代已退出。断言取消后后代心跳仍更新,最后由测试自己的释放文件终止它。
+
+JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,116 项通过,0 失败、0 错误、0 跳过。该场景验证未追踪后代的安全边界,后代所有权和回收能力仍由 2.3、3.2 跟踪。
diff --git a/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java b/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java
index e8a2d55..3ed062b 100644
--- a/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java
+++ b/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java
@@ -31,6 +31,12 @@ public static void main(String[] args) throws Exception {
writeStream(stream, Integer.parseInt(args[1]));
return;
}
+ if ("inherited-pipes".equals(mode)) {
+ String executable = System.getProperty("os.name").startsWith("Windows") ? "java.exe" : "java";
+ Path java = Paths.get(System.getProperty("java.home"), "bin", executable);
+ new ProcessBuilder(java.toString(), "-cp", System.getProperty("java.class.path"),
+ LifecycleProbe.class.getName(), "heartbeat", args[3], args[2]).inheritIO().start();
+ }
if ("capture-hold".equals(mode)) {
writeStream(System.out, Integer.parseInt(args[3]));
writeStream(System.err, Integer.parseInt(args[4]));
diff --git a/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java b/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java
index 0d49fb9..cd22ee2 100644
--- a/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java
+++ b/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java
@@ -4,6 +4,7 @@
import io.github.easy4j.opencli.browser.OpenCliBrowserClient;
import io.github.easy4j.opencli.browser.OpenCliBrowserSession;
import io.github.easy4j.opencli.browser.OpenCliBrowserSession.OpenCliBrowserNetworkOptions;
+import io.github.easy4j.opencli.core.OpenCliCancellationToken;
import io.github.easy4j.opencli.core.OpenCliExecutionDetails;
import io.github.easy4j.opencli.core.OpenCliExecutionDetails.TerminationReason;
import io.github.easy4j.opencli.core.OpenCliExecutor;
@@ -388,6 +389,44 @@ void sharedRuntimeBoundsConcurrentChildrenAndCombinedCapture() throws Exception
}
}
+ @Test
+ void cancelledParentWithInheritedPipesReturnsWithinCleanupBudget() throws Exception {
+ Path parent = dir.resolve("parent");
+ Path descendant = dir.resolve("descendant");
+ Path release = dir.resolve("release");
+ OpenCliCancellationToken token = new OpenCliCancellationToken();
+ OpenCliProperties properties = properties(1);
+ properties.setCleanupGraceMillis(250L);
+ OpenCliExecutor executor = new OpenCliExecutor(properties);
+ ExecutorService worker = Executors.newSingleThreadExecutor();
+ try {
+ Future failure = worker.submit(() -> assertThrows(OpenCliException.class,
+ () -> executor.invoke(Arrays.asList("inherited-pipes", parent.toString(),
+ release.toString(), descendant.toString()), token)));
+ assertTrue(awaitFile(descendant, 5_000L), "descendant never inherited the pipes");
+ token.cancel();
+ OpenCliExecutionDetails details = failure.get(1_500L, TimeUnit.MILLISECONDS).getPartialResult()
+ .getExecutionDetails();
+ assertEquals(TerminationReason.CANCELLED, details.getTerminationReason());
+ assertFalse(details.isDescendantsExitConfirmed());
+ if (!details.isStreamsDrained()) {
+ assertEquals(OpenCliExecutionDetails.CleanupState.UNCONFIRMED, details.getCleanupState());
+ }
+ byte[] firstHeartbeat = Files.readAllBytes(descendant);
+ long start = System.nanoTime();
+ while (Arrays.equals(firstHeartbeat, Files.readAllBytes(descendant))
+ && System.nanoTime() - start < TimeUnit.SECONDS.toNanos(1)) {
+ Thread.sleep(20L);
+ }
+ assertFalse(Arrays.equals(firstHeartbeat, Files.readAllBytes(descendant)),
+ "the untracked descendant was stopped by cancellation");
+ } finally {
+ release(release);
+ worker.shutdownNow();
+ assertTrue(worker.awaitTermination(5, TimeUnit.SECONDS));
+ }
+ }
+
@Test
void preCancelledRequestNeverStartsAProcess() throws Exception {
Class> tokenType = assertDoesNotThrow(() -> Class.forName("io.github.easy4j.opencli.core.OpenCliCancellationToken"));
From 61ea55d927ce754e24cdd6ea17ee3558e8c0fa8c Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Wed, 18 Nov 2026 23:36:55 +0800
Subject: [PATCH 017/105] fix: allocate OpenCLI output capture on first write
---
.../harden-opencli-process-lifecycle/tasks.md | 8 ++++++++
.../core/support/SubprocessExecutionSupport.java | 9 +++++----
.../core/support/SubprocessCleanupFaultTest.java | 2 ++
.../support/SubprocessExecutionSupportTest.java | 13 +++++++++++++
4 files changed, 28 insertions(+), 4 deletions(-)
diff --git a/openspec/changes/harden-opencli-process-lifecycle/tasks.md b/openspec/changes/harden-opencli-process-lifecycle/tasks.md
index b255130..f627d32 100644
--- a/openspec/changes/harden-opencli-process-lifecycle/tasks.md
+++ b/openspec/changes/harden-opencli-process-lifecycle/tasks.md
@@ -66,3 +66,11 @@ JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,115 项通过,0
新增真实继承管道回归。根进程启动继承 stdout、stderr 的独立 JVM,后者通过文件汇报心跳。观察到后代进程启动后取消调用。清理宽限配置为 250 ms,测试允许 1,500 ms 等待窗口,包含线程调度。SDK 仍返回 `CANCELLED`,流未排空时必须报告 `UNCONFIRMED`,并且不声称后代已退出。断言取消后后代心跳仍更新,最后由测试自己的释放文件终止它。
JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,116 项通过,0 失败、0 错误、0 跳过。该场景验证未追踪后代的安全边界,后代所有权和回收能力仍由 2.3、3.2 跟踪。
+
+## 2026-11-18 OC-PROC-003 输出缓冲区按需分配
+
+修复前,构造捕获对象即分配每个输出流的初始数组,默认两个共 16 KiB,包括仍排队或在启动前取消的调用。JDK 17 的两项回归分别观测到预取消路径的 16 字节测试配置和普通空写路径的 8,192 字节数组容量,预期均为零。
+
+修复后,第一次非空写入才分配对应捕获数组,仍受流的配置上限约束。预取消路径的 stdout、stderr 容量均为零,读取线程的工作缓冲和 JVM 总堆内存属独立指标。红灯 2 项失败,修复后 JDK 17 定向 33 项通过。
+
+JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,117 项通过,0 失败、0 错误、0 跳过。
diff --git a/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java b/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
index 06f5f06..870b648 100644
--- a/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
+++ b/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
@@ -44,6 +44,7 @@ interface WatchdogFactory {
public static final long WAIT_GRACE_MILLIS = 5_000L;
public static final int DEFAULT_STDOUT_LIMIT = 8 * 1024 * 1024;
public static final int DEFAULT_STDERR_LIMIT = 2 * 1024 * 1024;
+ private static final int READ_BUFFER_BYTES = 8192;
private static final long POLL_NANOS = TimeUnit.MILLISECONDS.toNanos(10L);
private static final int DEFAULT_MAX_CONCURRENT = Math.max(2, java.lang.Runtime.getRuntime().availableProcessors());
private static final Object LEGACY_LOCK = new Object();
@@ -376,7 +377,7 @@ static final class BoundedCapture extends ByteArrayOutputStream {
private boolean frozen;
BoundedCapture(int limit) {
- super(Math.min(8192, limit));
+ super(0);
this.limit = limit;
}
@@ -387,8 +388,8 @@ public synchronized void write(byte[] bytes, int offset, int length) {
int retained = Math.min(length, limit - count);
int required = count + retained;
if (required > buf.length) {
- int doubled = (int) Math.min(2L * buf.length, limit);
- buf = Arrays.copyOf(buf, Math.max(required, doubled));
+ int growth = (int) Math.min(limit, Math.max(READ_BUFFER_BYTES, 2L * buf.length));
+ buf = Arrays.copyOf(buf, Math.max(required, growth));
}
super.write(bytes, offset, retained);
truncated |= retained < length;
@@ -417,7 +418,7 @@ private static final class Reader extends Thread {
@Override
public void run() {
try (InputStream stream = input) {
- byte[] buffer = new byte[8192];
+ byte[] buffer = new byte[READ_BUFFER_BYTES];
int size;
while ((size = stream.read(buffer)) != -1) {
capture.write(buffer, 0, size);
diff --git a/src/test/java/io/github/easy4j/opencli/core/support/SubprocessCleanupFaultTest.java b/src/test/java/io/github/easy4j/opencli/core/support/SubprocessCleanupFaultTest.java
index 79fd220..b5c20e5 100644
--- a/src/test/java/io/github/easy4j/opencli/core/support/SubprocessCleanupFaultTest.java
+++ b/src/test/java/io/github/easy4j/opencli/core/support/SubprocessCleanupFaultTest.java
@@ -164,6 +164,8 @@ void cancelledSubmissionDoesNotInitializeWatchdogOrSpawn() throws Exception {
assertEquals(CleanupState.NOT_STARTED, session.getExecutionDetails().getCleanupState());
assertNull(session.getObservedExitCode());
assertNotNull(session.getWatchdog());
+ assertEquals(0, ((SubprocessExecutionSupport.BoundedCapture) session.getStdout()).bufferCapacity());
+ assertEquals(0, ((SubprocessExecutionSupport.BoundedCapture) session.getStderr()).bufferCapacity());
}
private static void assertCleanupSurvives(boolean failStop, boolean failDestroy) throws Exception {
diff --git a/src/test/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupportTest.java b/src/test/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupportTest.java
index 8855f8f..9123715 100644
--- a/src/test/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupportTest.java
+++ b/src/test/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupportTest.java
@@ -5,6 +5,19 @@
class SubprocessExecutionSupportTest {
+ @Test
+ void shouldAllocateOutputStorageOnlyOnFirstNonemptyWrite() {
+ SubprocessExecutionSupport.BoundedCapture capture = new SubprocessExecutionSupport.BoundedCapture(12_000);
+ byte[] empty = new byte[0];
+ capture.write(empty, 0, empty.length);
+
+ assertEquals(0, capture.bufferCapacity());
+ capture.write(99);
+ assertEquals(1, capture.size());
+ assertEquals(99, capture.toByteArray()[0]);
+ assertEquals(8_192, capture.bufferCapacity());
+ }
+
@Test
void shouldBoundBackingBufferGrowthAtTheConfiguredLimit() {
int limit = 8_193;
From d52c57f8465c8672eeaecf76d71bac52a0076c6b Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Wed, 18 Nov 2026 23:44:01 +0800
Subject: [PATCH 018/105] fix: bound blocking OpenCLI process termination
---
.github/workflows/platform-contracts.yml | 3 +-
.../harden-opencli-process-lifecycle/tasks.md | 8 ++
.../support/SubprocessExecutionSupport.java | 118 ++++++++++++++----
.../support/SubprocessCleanupFaultTest.java | 74 ++++++++++-
4 files changed, 175 insertions(+), 28 deletions(-)
diff --git a/.github/workflows/platform-contracts.yml b/.github/workflows/platform-contracts.yml
index 5693d49..df48f21 100644
--- a/.github/workflows/platform-contracts.yml
+++ b/.github/workflows/platform-contracts.yml
@@ -44,7 +44,7 @@ jobs:
mvn -version > platform-evidence/maven.txt 2>&1
result=0
mvn -B --no-transfer-progress \
- -Dtest=OpenCliArgvContractTest,OpenCliStructuredArgvContractTest,OpenCliProcessContractTest,OpenCliProcessBoundaryTest,SubprocessStreamFailureTest,OpenCliWsReverseAgentSessionTest,OpenCliWsCollectRequestsTest,OpenCliProcessPrivacyTest \
+ -Dtest=OpenCliArgvContractTest,OpenCliStructuredArgvContractTest,OpenCliProcessContractTest,OpenCliProcessBoundaryTest,SubprocessCleanupFaultTest,SubprocessStreamFailureTest,OpenCliWsReverseAgentSessionTest,OpenCliWsCollectRequestsTest,OpenCliProcessPrivacyTest \
test > platform-evidence/maven.log 2>&1 || result=$?
tail -100 platform-evidence/maven.log
python scripts/contract_report.py \
@@ -58,6 +58,7 @@ jobs:
--suite argv=io.github.easy4j.opencli.contract.OpenCliStructuredArgvContractTest \
--suite process=io.github.easy4j.opencli.contract.OpenCliProcessContractTest \
--suite process=io.github.easy4j.opencli.contract.OpenCliProcessBoundaryTest \
+ --suite process=io.github.easy4j.opencli.core.support.SubprocessCleanupFaultTest \
--suite process=io.github.easy4j.opencli.core.support.SubprocessStreamFailureTest \
--suite protocol=io.github.easy4j.opencli.center.ws.OpenCliWsReverseAgentSessionTest \
--suite protocol=io.github.easy4j.opencli.center.ws.OpenCliWsCollectRequestsTest \
diff --git a/openspec/changes/harden-opencli-process-lifecycle/tasks.md b/openspec/changes/harden-opencli-process-lifecycle/tasks.md
index f627d32..c631a58 100644
--- a/openspec/changes/harden-opencli-process-lifecycle/tasks.md
+++ b/openspec/changes/harden-opencli-process-lifecycle/tasks.md
@@ -74,3 +74,11 @@ JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,116 项通过,0
修复后,第一次非空写入才分配对应捕获数组,仍受流的配置上限约束。预取消路径的 stdout、stderr 容量均为零,读取线程的工作缓冲和 JVM 总堆内存属独立指标。红灯 2 项失败,修复后 JDK 17 定向 33 项通过。
JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,117 项通过,0 失败、0 错误、0 跳过。
+
+## 2026-11-18 OC-PROC-005 终止操作阻塞
+
+故障注入让调用独占根进程的普通和强制终止分别等待释放信号。验证显式取消以及 Commons Exec watchdog 到期两条路径。设置清理宽限 250 ms,以 1,250 ms 为回归断言窗口。修复前两项均等待超时。
+
+修复将 native 终止调用交给每次执行最多两个守护工作线程,普通和强制终止各发出一次。watchdog 回调只提交终止请求,既有锁不覆盖 native 终止操作。原始 `CANCELLED` 或 `EXECUTION_TIMEOUT` 保留。终止操作未结束时保留 `UNCONFIRMED`,不伪造退出码,并隔离当前运行时。测试最后释放注入的阻塞线程。该修复范围为 SDK 已持有的根进程,后代所有权仍待验收。
+
+JDK 17 定向 29 项通过。JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,119 项通过,0 失败、0 错误、0 跳过。平台契约证据增加 `SubprocessCleanupFaultTest`。
diff --git a/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java b/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
index 870b648..40ee072 100644
--- a/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
+++ b/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
@@ -8,6 +8,7 @@
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
+import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -118,7 +119,7 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
long budget = nanos(request.timeoutMillis, "timeoutMillis");
BoundedCapture out = new BoundedCapture(request.stdoutLimitBytes);
BoundedCapture err = new BoundedCapture(request.stderrLimitBytes);
- Process process = null;
+ CleanupProcess process = null;
Reader stdoutReader = null;
Reader stderrReader = null;
ExecuteWatchdog watchdog = null;
@@ -130,6 +131,7 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
long queueWaitMillis = 0L;
Integer exit = null;
boolean streamsDrained = true;
+ boolean cleanupFinished = true;
try {
while (!acquired && reason == null) {
if (Thread.interrupted()) {
@@ -168,7 +170,7 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
builder.environment().clear();
builder.environment().putAll(request.environment);
}
- process = processStarter.start(builder);
+ process = new CleanupProcess(processStarter.start(builder));
process.getOutputStream().close();
stdoutReader = new Reader(process.getInputStream(), out, "opencli-stdout");
stderrReader = new Reader(process.getErrorStream(), err, "opencli-stderr");
@@ -226,23 +228,17 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
long cleanupStart = System.nanoTime();
long cleanupBudget = nanos(request.cleanupGraceMillis, "cleanupGraceMillis");
if (Objects.nonNull(process)) {
- boolean forceSent = false;
if (process.isAlive()) {
- try {
- process.destroy();
- } catch (RuntimeException ex) {
- cleanupOperationFailed = true;
- forceSent = true;
- if (!tryForceStop(process)) { cleanupOperationFailed = true; }
- }
+ process.destroy();
}
+ long forceAfter = Math.min(TimeUnit.MILLISECONDS.toNanos(100L), cleanupBudget / 2L);
while (remaining(cleanupStart, cleanupBudget) > 0
- && (process.isAlive() || alive(stdoutReader) || alive(stderrReader))) {
+ && (process.isAlive() || alive(stdoutReader) || alive(stderrReader)
+ || process.hasPendingStop())) {
if (Thread.interrupted()) { interrupted = true; }
- if (process.isAlive() && !forceSent
- && System.nanoTime() - cleanupStart >= Math.min(TimeUnit.MILLISECONDS.toNanos(100L), cleanupBudget / 2)) {
- if (!tryForceStop(process)) { cleanupOperationFailed = true; }
- forceSent = true;
+ if (process.isAlive() && (process.graceful.failed
+ || System.nanoTime() - cleanupStart >= forceAfter)) {
+ process.destroyForcibly();
}
try {
TimeUnit.NANOSECONDS.sleep(Math.min(POLL_NANOS,
@@ -251,13 +247,17 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
interrupted = true;
}
}
- if (process.isAlive() && !tryForceStop(process)) { cleanupOperationFailed = true; }
+ if (process.isAlive()) {
+ process.destroyForcibly();
+ }
+ cleanupFinished = !process.hasPendingStop();
+ cleanupOperationFailed |= !cleanupFinished || process.graceful.failed || process.forced.failed;
if (!process.isAlive()) {
exit = process.exitValue();
}
streamsDrained = !alive(stdoutReader) && !alive(stderrReader);
- if (Objects.isNull(exit) || !streamsDrained) {
- // A fixed runtime cannot accumulate unlimited uncertain children/readers.
+ if (Objects.isNull(exit) || !streamsDrained || !cleanupFinished) {
+ // Quarantine limits the number of unconfirmed children, readers and stop workers.
quarantined = true;
if (reason == TerminationReason.PROCESS_EXIT) { reason = TerminationReason.CLEANUP_UNCONFIRMED; }
}
@@ -283,7 +283,8 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
OpenCliExecutionDetails details = OpenCliExecutionDetails.builder()
.terminationReason(reason)
.cleanupState(process == null ? CleanupState.NOT_STARTED
- : Objects.isNull(exit) || !streamsDrained ? CleanupState.UNCONFIRMED : CleanupState.ROOT_EXIT_CONFIRMED)
+ : Objects.isNull(exit) || !streamsDrained || !cleanupFinished
+ ? CleanupState.UNCONFIRMED : CleanupState.ROOT_EXIT_CONFIRMED)
.processStarted(process != null).streamsDrained(streamsDrained)
.cleanupOperationFailed(cleanupOperationFailed)
.stdoutCapturedBytes(out.size()).stdoutObservedBytes(out.observed()).stdoutTruncated(out.isTruncated())
@@ -303,14 +304,81 @@ private static ExecuteWatchdog newWatchdog(long timeoutMillis) {
}
private static boolean alive(Thread thread) { return thread != null && thread.isAlive(); }
- private static boolean tryForceStop(Process process) {
- try {
- process.destroyForcibly();
- return true;
- } catch (RuntimeException ex) {
- return false;
+ /**
+ * The watchdog holds its monitor when invoking destroy. Keep native stop calls
+ * outside that monitor and the caller, as closing process pipes can block.
+ */
+ private static final class CleanupProcess extends Process {
+ private final Process delegate;
+ private final StopRequest graceful = new StopRequest();
+ private final StopRequest forced = new StopRequest();
+
+ CleanupProcess(Process delegate) {
+ this.delegate = delegate;
+ }
+
+ @Override
+ public OutputStream getOutputStream() { return delegate.getOutputStream(); }
+
+ @Override
+ public InputStream getInputStream() { return delegate.getInputStream(); }
+
+ @Override
+ public InputStream getErrorStream() { return delegate.getErrorStream(); }
+
+ @Override
+ public int waitFor() throws InterruptedException { return delegate.waitFor(); }
+
+ @Override
+ public int exitValue() { return delegate.exitValue(); }
+
+ @Override
+ public boolean isAlive() { return delegate.isAlive(); }
+
+ @Override
+ public void destroy() {
+ graceful.start("opencli-stop", delegate::destroy);
+ }
+
+ @Override
+ public Process destroyForcibly() {
+ forced.start("opencli-force-stop", delegate::destroyForcibly);
+ return this;
+ }
+
+ boolean hasPendingStop() {
+ return graceful.isPending() || forced.isPending();
}
}
+
+ private static final class StopRequest {
+ private Thread worker;
+ private volatile boolean failed;
+
+ synchronized void start(String name, Runnable signal) {
+ if (Objects.nonNull(worker) || failed) {
+ return;
+ }
+ try {
+ worker = new Thread(() -> {
+ try {
+ signal.run();
+ } catch (RuntimeException ex) {
+ failed = true;
+ }
+ }, name);
+ worker.setDaemon(true);
+ worker.start();
+ } catch (RuntimeException ex) {
+ failed = true;
+ }
+ }
+
+ synchronized boolean isPending() {
+ return alive(worker);
+ }
+ }
+
private static long remaining(long start, long budget) { return budget - (System.nanoTime() - start); }
// The Windows JDK legacy serializer treats a surrounding quote pair as already encoded.
@SuppressWarnings("removal")
diff --git a/src/test/java/io/github/easy4j/opencli/core/support/SubprocessCleanupFaultTest.java b/src/test/java/io/github/easy4j/opencli/core/support/SubprocessCleanupFaultTest.java
index b5c20e5..59f4a78 100644
--- a/src/test/java/io/github/easy4j/opencli/core/support/SubprocessCleanupFaultTest.java
+++ b/src/test/java/io/github/easy4j/opencli/core/support/SubprocessCleanupFaultTest.java
@@ -7,6 +7,11 @@
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.ExecuteWatchdog;
@@ -148,6 +153,71 @@ void unconfirmedForcedStopQuarantinesRuntimeWithoutFabricatingExit() throws Exce
assertEquals(1, starts[0]);
}
+ @Test
+ void blockedGracefulAndForcedStopDoNotHoldCallerPastCleanupGrace() throws Exception {
+ assertBoundedStop(false, TerminationReason.CANCELLED);
+ }
+
+ @Test
+ void watchdogTimeoutDoesNotHoldCallerWhileNativeStopIsBlocked() throws Exception {
+ assertBoundedStop(true, TerminationReason.EXECUTION_TIMEOUT);
+ }
+
+ private static void assertBoundedStop(boolean watchdogExpires, TerminationReason expected) throws Exception {
+ CountDownLatch gracefulEntered = new CountDownLatch(1);
+ CountDownLatch forceEntered = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ FakeProcess child = new FakeProcess(false) {
+ @Override
+ public void destroy() {
+ waitForRelease(gracefulEntered, release);
+ super.destroy();
+ }
+
+ @Override
+ public Process destroyForcibly() {
+ waitForRelease(forceEntered, release);
+ return super.destroyForcibly();
+ }
+ };
+ OpenCliCancellationToken token = new OpenCliCancellationToken();
+ SubprocessExecutionSupport.Runtime runtime = new SubprocessExecutionSupport.Runtime(1,
+ builder -> {
+ if (!watchdogExpires) {
+ token.cancel();
+ }
+ return child;
+ }, timeout -> watchdogExpires ? new ExecuteWatchdog(20L) : new FakeWatchdog(false));
+ SubprocessExecutionSupport.ExecutionRequest request = new SubprocessExecutionSupport.ExecutionRequest(
+ CommandLine.parse("fake"), null, null, 1000L, 16, 16, 250L, System.nanoTime(), token);
+
+ ExecutorService worker = Executors.newSingleThreadExecutor();
+ try {
+ Future pending = worker.submit(() -> runtime.execute(request));
+ assertTrue(gracefulEntered.await(1, TimeUnit.SECONDS));
+ SubprocessExecutionSupport.RunSession session = pending.get(1250, TimeUnit.MILLISECONDS);
+ assertEquals(0, forceEntered.getCount());
+ assertEquals(expected, session.getExecutionDetails().getTerminationReason());
+ assertEquals(CleanupState.UNCONFIRMED, session.getExecutionDetails().getCleanupState());
+ assertTrue(session.getExecutionDetails().isCleanupOperationFailed());
+ assertNull(session.getObservedExitCode());
+ assertTrue(runtime.isQuarantined());
+ } finally {
+ release.countDown();
+ worker.shutdownNow();
+ assertTrue(worker.awaitTermination(2, TimeUnit.SECONDS));
+ }
+ }
+
+ private static void waitForRelease(CountDownLatch entered, CountDownLatch release) {
+ entered.countDown();
+ try {
+ release.await(3, TimeUnit.SECONDS);
+ } catch (InterruptedException failure) {
+ Thread.currentThread().interrupt();
+ }
+ }
+
@Test
void cancelledSubmissionDoesNotInitializeWatchdogOrSpawn() throws Exception {
OpenCliCancellationToken token = new OpenCliCancellationToken();
@@ -233,9 +303,9 @@ public synchronized void stop() {
public synchronized boolean killedProcess() { return false; }
}
- private static final class FakeProcess extends Process {
+ private static class FakeProcess extends Process {
private final boolean failDestroy;
- private boolean alive = true;
+ private volatile boolean alive = true;
private final boolean failForce;
private final boolean failStreamSetup;
From d4da616ad65d4986a7a18383db6e897451c8e38a Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Wed, 18 Nov 2026 23:53:01 +0800
Subject: [PATCH 019/105] test: verify OpenCLI argv snapshot while queued
---
.../harden-opencli-argv-contract/tasks.md | 24 ++++++----
.../contract/OpenCliArgvContractTest.java | 2 +-
.../contract/OpenCliProcessContractTest.java | 45 +++++++++++++++++++
3 files changed, 62 insertions(+), 9 deletions(-)
diff --git a/openspec/changes/harden-opencli-argv-contract/tasks.md b/openspec/changes/harden-opencli-argv-contract/tasks.md
index fc170fd..457c60d 100644
--- a/openspec/changes/harden-opencli-argv-contract/tasks.md
+++ b/openspec/changes/harden-opencli-argv-contract/tasks.md
@@ -1,26 +1,34 @@
# C01 Tasks · 参数保真与统一调用契约
-> 全部为待执行实现任务。文档/格式检查通过不允许提前勾选。
+> 已勾选项对应真实子进程契约及历史失败证据。保留 3.4 的评审和归档门禁。
关联规范:[spec](specs/opencli-argv-contract/spec.md)。
## 1. 失败测试
-- [ ] 1.1 在现有 core/support 测试区新增 Java argv echo fixture,覆盖空值、空白、Unicode、换行、-- 和重复 flag。
-- [ ] 1.2 先在实现前运行新增用例,保存真实失败输出;禁止只断言命令前缀。
+- [x] 1.1 在现有 core/support 测试区新增 Java argv echo fixture,覆盖空值、空白、Unicode、换行、-- 和重复 flag。
+- [x] 1.2 先在实现前运行新增用例,保存真实失败输出;禁止只断言命令前缀。
## 2. 最小实现
-- [ ] 2.1 统一 Executor/AdapterChannel/参数 helpers 的值保真路径,并对输入列表做快照。
-- [ ] 2.2 为 null/标识符错误建立不包含业务值的校验;增量支持有序 option occurrences 和 false 语义。
+- [x] 2.1 统一 Executor/AdapterChannel/参数 helpers 的值保真路径,并对输入列表做快照。
+- [x] 2.2 为 null/标识符错误建立不包含业务值的校验;增量支持有序 option occurrences 和 false 语义。
## 3. 迁移与验证
-- [ ] 3.1 补 List/varargs/typed/request 等价与用户列表不被修改的测试。
-- [ ] 3.2 检查 Windows launcher 与引号边界,未测试的平台明确保留未验证状态。
-- [ ] 3.3 分别在三条 feature 线运行共享 vectors 和现有测试,记录允许差异。
+- [x] 3.1 补 List/varargs/typed/request 等价与用户列表不被修改的测试。
+- [x] 3.2 检查 Windows launcher 与引号边界,未测试的平台明确保留未验证状态。
+- [x] 3.3 分别在三条 feature 线运行共享 vectors 和现有测试,记录允许差异。
- [ ] 3.4 评审迁移说明与完整 diff;需求通过后再申请 archive,不在文档阶段勾选。
## 证据交付模板(实施时填写)
每项任务的完成记录包含:Requirement/Scenario、分支HEAD、测试命令、失败→通过证据、测试数/跳过数、退出码、报告位置。没有记录的任务保持未完成。
+
+## C01 实现与参数保真证据(2026-11-18)
+
+- OC-ARGV-001、002、004、005。提交 `cdc8b66e74730ab1ed99a9f24a077f9077d2dbf5` 只引入契约夹具。在独立源码目录用 JDK 17 运行 `mvn -B -ntp -o -Dtest=OpenCliArgvContractTest test`,33 项中 21 项失败,0 错误、0 跳过,退出 1。真实子进程收到的完整向量显示空值被丢弃、两端空白被裁剪,typed browser fill 也丢失用于清空字段的空字符串。
+- OC-ARGV-003。提交 `d02b16ddc5e0fe7c1d98c6847f4b2999cf2f2566` 用同一环境运行 `OpenCliStructuredArgvContractTest`,10 项中 10 项失败,0 错误、0 跳过,退出 1。可变 Map 与 StringBuilder 改写了实际 argv。当前实现支持显式 schema、有序重复选项、值型 false、否定 flag,拒绝歧义,旧 Map 继续使用历史语义。[历史 RED/GREEN 执行记录](../../../docs/implementation/c10-c01-execution.md)
+- 当前本地回归覆盖完整向量、argv 第三项为 null、空白标识符、等号、引号、反斜杠、`--`、Unicode 和换行。新增排队变更回归。一个真实 JVM 占住共享许可,下一次调用完成列表快照后,调用方修改原列表并释放许可。回显子进程收到提交时的完整向量,调用方原列表只包含它自己所作修改。JDK 17 定向 45 项通过。
+- Windows 使用原生 `node.exe` 运行回显夹具,含空白、引号和末尾反斜杠的 token 保留。SDK 会在启动前拒绝 `.cmd`、`.bat` 批处理入口。JDK 17 曾运行真实安装包的启动器测试,仅执行只读元命令。对应 [JDK 8 平台 CI](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44339054705)、[JDK 17 Windows](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44339055208/job/134923652889)、[JDK 21 Windows](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44339054801) 与 [已安装启动器证据](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44313779366/job/134834399117)。
+- 三条维护线使用同一套已校验 SHA-256 的 `argv.tsv`、`ContractProbe` 和 `OpenCliStructuredArgvContractTest`。JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,120 项通过,0 失败、0 错误、0 跳过,退出 0。本地报告为 `target/surefire-reports`。三个版本的 JDK/Jackson/Maven 允许差异见 fixture 的 `sources.lock.json`。远端分支最新 CI 单独记录于 PR。
diff --git a/src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java b/src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java
index 1bad49f..dd73e0c 100644
--- a/src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java
+++ b/src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java
@@ -55,7 +55,7 @@ private static OpenCliProperties properties() {
return p;
}
- private static List received(OpenCliResult result) throws Exception {
+ static List received(OpenCliResult result) throws Exception {
assertTrue(result.isSuccess());
List actual = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new StringReader(result.getStdout()))) {
diff --git a/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java b/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java
index cd22ee2..58b3196 100644
--- a/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java
+++ b/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java
@@ -21,6 +21,7 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
@@ -324,6 +325,50 @@ void explicitSharedRuntimeLimitsBothClients() throws Exception {
}
}
+ @Test
+ void queuedInvocationUsesItsArgvSnapshotAfterCallerMutation() throws Exception {
+ OpenCliProcessRuntime runtime = new OpenCliProcessRuntime(1);
+ OpenCliExecutor blocker = new OpenCliExecutor(properties(1), runtime);
+ OpenCliProperties echoProperties = properties(1);
+ List leading = echoProperties.getLeadingArguments();
+ leading.set(leading.size() - 1, ContractProbe.class.getName());
+ OpenCliExecutor echo = new OpenCliExecutor(echoProperties, runtime);
+ List expected = Arrays.asList("demo", "echo", "", " 原始值 ");
+ CountDownLatch copied = new CountDownLatch(1);
+ List input = new ArrayList(expected) {
+ @Override
+ public Object[] toArray() {
+ Object[] result = super.toArray();
+ copied.countDown();
+ return result;
+ }
+ };
+ Path active = dir.resolve("argv-blocker");
+ Path gate = dir.resolve("argv-release");
+ ExecutorService workers = Executors.newFixedThreadPool(2);
+ try {
+ Future running = workers.submit(() ->
+ blocker.invoke("hold", active.toString(), gate.toString()));
+ assertTrue(awaitFile(active, 5_000L));
+ Future queued = workers.submit(() -> echo.invoke(input));
+ assertTrue(copied.await(2, TimeUnit.SECONDS));
+ assertEquals(expected, input);
+ assertFalse(queued.isDone());
+
+ input.set(3, "changed");
+ input.add("late");
+ release(gate);
+
+ assertTrue(running.get(5, TimeUnit.SECONDS).isSuccess());
+ assertEquals(expected, OpenCliArgvContractTest.received(queued.get(5, TimeUnit.SECONDS)));
+ assertEquals(Arrays.asList("demo", "echo", "", "changed", "late"), input);
+ } finally {
+ release(gate);
+ workers.shutdownNow();
+ assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));
+ }
+ }
+
@Test
void sharedRuntimeBoundsConcurrentChildrenAndCombinedCapture() throws Exception {
int stdoutLimit = 131_073;
From 05f6660125c272bf7a4dfbba6038ca93dc87fd54 Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Wed, 18 Nov 2026 23:53:22 +0800
Subject: [PATCH 020/105] docs: link shared OpenCLI argv history from backports
---
openspec/changes/harden-opencli-argv-contract/tasks.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/openspec/changes/harden-opencli-argv-contract/tasks.md b/openspec/changes/harden-opencli-argv-contract/tasks.md
index 457c60d..15d6d3c 100644
--- a/openspec/changes/harden-opencli-argv-contract/tasks.md
+++ b/openspec/changes/harden-opencli-argv-contract/tasks.md
@@ -28,7 +28,7 @@
## C01 实现与参数保真证据(2026-11-18)
- OC-ARGV-001、002、004、005。提交 `cdc8b66e74730ab1ed99a9f24a077f9077d2dbf5` 只引入契约夹具。在独立源码目录用 JDK 17 运行 `mvn -B -ntp -o -Dtest=OpenCliArgvContractTest test`,33 项中 21 项失败,0 错误、0 跳过,退出 1。真实子进程收到的完整向量显示空值被丢弃、两端空白被裁剪,typed browser fill 也丢失用于清空字段的空字符串。
-- OC-ARGV-003。提交 `d02b16ddc5e0fe7c1d98c6847f4b2999cf2f2566` 用同一环境运行 `OpenCliStructuredArgvContractTest`,10 项中 10 项失败,0 错误、0 跳过,退出 1。可变 Map 与 StringBuilder 改写了实际 argv。当前实现支持显式 schema、有序重复选项、值型 false、否定 flag,拒绝歧义,旧 Map 继续使用历史语义。[历史 RED/GREEN 执行记录](../../../docs/implementation/c10-c01-execution.md)
+- OC-ARGV-003。提交 `d02b16ddc5e0fe7c1d98c6847f4b2999cf2f2566` 用同一环境运行 `OpenCliStructuredArgvContractTest`,10 项中 10 项失败,0 错误、0 跳过,退出 1。可变 Map 与 StringBuilder 改写了实际 argv。当前实现支持显式 schema、有序重复选项、值型 false、否定 flag,拒绝歧义,旧 Map 继续使用历史语义。[历史 RED/GREEN 执行记录](https://github.com/easy-4-java/opencli-java-sdk/blob/01513226e14c4e73e0ed602332285d407a1489a9/docs/implementation/c10-c01-execution.md)
- 当前本地回归覆盖完整向量、argv 第三项为 null、空白标识符、等号、引号、反斜杠、`--`、Unicode 和换行。新增排队变更回归。一个真实 JVM 占住共享许可,下一次调用完成列表快照后,调用方修改原列表并释放许可。回显子进程收到提交时的完整向量,调用方原列表只包含它自己所作修改。JDK 17 定向 45 项通过。
- Windows 使用原生 `node.exe` 运行回显夹具,含空白、引号和末尾反斜杠的 token 保留。SDK 会在启动前拒绝 `.cmd`、`.bat` 批处理入口。JDK 17 曾运行真实安装包的启动器测试,仅执行只读元命令。对应 [JDK 8 平台 CI](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44339054705)、[JDK 17 Windows](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44339055208/job/134923652889)、[JDK 21 Windows](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44339054801) 与 [已安装启动器证据](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44313779366/job/134834399117)。
- 三条维护线使用同一套已校验 SHA-256 的 `argv.tsv`、`ContractProbe` 和 `OpenCliStructuredArgvContractTest`。JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,120 项通过,0 失败、0 错误、0 跳过,退出 0。本地报告为 `target/surefire-reports`。三个版本的 JDK/Jackson/Maven 允许差异见 fixture 的 `sources.lock.json`。远端分支最新 CI 单独记录于 PR。
From 12aa318243397663b6badbfb70d5f64943350ecf Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Wed, 18 Nov 2026 23:56:20 +0800
Subject: [PATCH 021/105] test: use native Windows argv probe for queued calls
---
openspec/changes/harden-opencli-argv-contract/tasks.md | 2 ++
.../easy4j/opencli/contract/OpenCliArgvContractTest.java | 2 +-
.../easy4j/opencli/contract/OpenCliProcessContractTest.java | 5 +----
3 files changed, 4 insertions(+), 5 deletions(-)
diff --git a/openspec/changes/harden-opencli-argv-contract/tasks.md b/openspec/changes/harden-opencli-argv-contract/tasks.md
index 15d6d3c..8e41963 100644
--- a/openspec/changes/harden-opencli-argv-contract/tasks.md
+++ b/openspec/changes/harden-opencli-argv-contract/tasks.md
@@ -32,3 +32,5 @@
- 当前本地回归覆盖完整向量、argv 第三项为 null、空白标识符、等号、引号、反斜杠、`--`、Unicode 和换行。新增排队变更回归。一个真实 JVM 占住共享许可,下一次调用完成列表快照后,调用方修改原列表并释放许可。回显子进程收到提交时的完整向量,调用方原列表只包含它自己所作修改。JDK 17 定向 45 项通过。
- Windows 使用原生 `node.exe` 运行回显夹具,含空白、引号和末尾反斜杠的 token 保留。SDK 会在启动前拒绝 `.cmd`、`.bat` 批处理入口。JDK 17 曾运行真实安装包的启动器测试,仅执行只读元命令。对应 [JDK 8 平台 CI](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44339054705)、[JDK 17 Windows](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44339055208/job/134923652889)、[JDK 21 Windows](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44339054801) 与 [已安装启动器证据](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44313779366/job/134834399117)。
- 三条维护线使用同一套已校验 SHA-256 的 `argv.tsv`、`ContractProbe` 和 `OpenCliStructuredArgvContractTest`。JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,120 项通过,0 失败、0 错误、0 跳过,退出 0。本地报告为 `target/surefire-reports`。三个版本的 JDK/Jackson/Maven 允许差异见 fixture 的 `sources.lock.json`。远端分支最新 CI 单独记录于 PR。
+
+- 排队回归与原始参数回归共用回显启动配置。首次 JDK 17 Windows CI 使用旧 Java 回显启动器时,子进程把原始中文 token 收成 `???`。改用同套 Windows 原生 Node 回显夹具,继续断言完整 Unicode token,并保留 Java 生命周期进程作为许可占用方。[首次 Windows 结果](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44340768729/job/134929785664)
diff --git a/src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java b/src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java
index dd73e0c..0ed5dec 100644
--- a/src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java
+++ b/src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java
@@ -32,7 +32,7 @@
/** Shared Java 8-compatible contract tests, with a real child rather than Recording executor. */
class OpenCliArgvContractTest {
- private static OpenCliProperties properties() {
+ static OpenCliProperties properties() {
OpenCliProperties p = new OpenCliProperties();
String exe = System.getProperty("os.name").startsWith("Windows") ? "java.exe" : "java";
p.setExecutable(new File(new File(System.getProperty("java.home"), "bin"), exe).getAbsolutePath());
diff --git a/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java b/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java
index 58b3196..f9ddfe3 100644
--- a/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java
+++ b/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java
@@ -329,10 +329,7 @@ void explicitSharedRuntimeLimitsBothClients() throws Exception {
void queuedInvocationUsesItsArgvSnapshotAfterCallerMutation() throws Exception {
OpenCliProcessRuntime runtime = new OpenCliProcessRuntime(1);
OpenCliExecutor blocker = new OpenCliExecutor(properties(1), runtime);
- OpenCliProperties echoProperties = properties(1);
- List leading = echoProperties.getLeadingArguments();
- leading.set(leading.size() - 1, ContractProbe.class.getName());
- OpenCliExecutor echo = new OpenCliExecutor(echoProperties, runtime);
+ OpenCliExecutor echo = new OpenCliExecutor(OpenCliArgvContractTest.properties(), runtime);
List expected = Arrays.asList("demo", "echo", "", " 原始值 ");
CountDownLatch copied = new CountDownLatch(1);
List input = new ArrayList(expected) {
From 4fe3e4d5624fe07073201cd93c0cac06b80e7414 Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Thu, 19 Nov 2026 00:03:40 +0800
Subject: [PATCH 022/105] fix: retire stopped OpenCLI WebSocket generations
---
.../harden-opencli-reverse-agent/tasks.md | 12 +++-
.../ws/OpenCliWsReverseAgentClient.java | 70 +++++++++++++------
.../ws/OpenCliWsReverseAgentSessionTest.java | 39 +++++++++++
3 files changed, 98 insertions(+), 23 deletions(-)
diff --git a/openspec/changes/harden-opencli-reverse-agent/tasks.md b/openspec/changes/harden-opencli-reverse-agent/tasks.md
index e113e5c..fa39831 100644
--- a/openspec/changes/harden-opencli-reverse-agent/tasks.md
+++ b/openspec/changes/harden-opencli-reverse-agent/tasks.md
@@ -1,13 +1,13 @@
# C05 Tasks · 反向 Worker 状态机、背压与去重
-> 全部为待执行实现任务。文档/格式检查通过不允许提前勾选。
+> 已勾选项有对应的实现和回归证据。
关联规范:[spec](specs/opencli-reverse-agent/spec.md)。
## 1. Worker fixture
-- [ ] 1.1 新增可控本地 WS server,覆盖未注册 collect、超大/空 ID、队列满与重复消息。
-- [ ] 1.2 加入断线写任务、代际结果路由、close竞态和重启边界的失败测试。
+- [x] 1.1 新增可控本地 WS server,覆盖未注册 collect、超大/空 ID、队列满与重复消息。
+- [x] 1.2 加入断线写任务、代际结果路由、close竞态和重启边界的失败测试。
## 2. 治理实现
@@ -29,3 +29,9 @@
## JDK 8 回移验证
回移 JDK 17 版本的注册前拒绝、执行与等待上限、关闭保护、请求去重、缓存过期和连接隔离。通过本地回环服务器、真实子进程和测试证书验证普通连接和 TLS 重连。运行 `mvn -B -ntp -o clean verify`,2,112 项测试通过,零失败、零跳过,JaCoCo 行覆盖率为 2,905 / 3,167(91.73%)。
+
+## 2026-11-19 OC-WS-005/006 代际发布与停止竞态
+
+`stopDuringConnectionSetupDoesNotPublishAnotherGeneration` 在连接线程读取端点时阻塞配置读取,随后调用 `stop()`,再解除阻塞。修复前本地中心收到已停止 worker 的注册消息,1 项失败,退出 1。修复后停止和连接发布共用同步边界,晚到连接无法发布。异常、关闭及退出均只退役对应 socket,当前代际检查用于注册、收单和异步结果投递。同一个已验证 TLS 中心显式重发仍可读取对应缓存。异常的默认日志保持固定文本。
+
+`OpenCliWsReverseAgentSessionTest` 的回环服务同时覆盖提前收单、空白和超大 ID、队列溢出、重复请求、断线时在途工作、TLS 显式重发、明文会话隔离、关闭丢弃队列及关闭后拒绝重启。JDK 17 定向验证 27 项通过。JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,121 项通过,0 失败、0 错误、0 跳过。显式状态机、可重启 stop 的任务收尾合同和平台资源验收仍由相应任务跟踪。
diff --git a/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentClient.java b/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentClient.java
index 026d669..e696d8e 100644
--- a/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentClient.java
+++ b/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentClient.java
@@ -65,7 +65,7 @@ public final class OpenCliWsReverseAgentClient implements AutoCloseable {
private volatile boolean shutdownRequested;
- private volatile WebSocketClient activeClient;
+ private final AtomicReference activeClient = new AtomicReference<>();
private Thread runnerThread;
@@ -113,8 +113,7 @@ public synchronized void start() {
*/
public synchronized void stop() {
shutdownRequested = true;
- WebSocketClient client = activeClient;
- activeClient = null;
+ WebSocketClient client = activeClient.getAndSet(null);
if (Objects.nonNull(client)) {
try {
client.close();
@@ -201,6 +200,10 @@ private void runOneSession() throws Exception {
new WebSocketClient(endpoint) {
@Override
public void onOpen(ServerHandshake handshake) {
+ if (!isCurrentSession(this)) {
+ closeSession(this);
+ return;
+ }
try {
send(buildRegisterJson());
} catch (Exception e) {
@@ -221,6 +224,7 @@ public void onMessage(String message) {
@Override
public void onClose(int code, String reason, boolean remote) {
+ activeClient.compareAndSet(this, null);
if (registered.getCount() > 0) {
handshakeFailure.compareAndSet(
null,
@@ -235,6 +239,7 @@ public void onClose(int code, String reason, boolean remote) {
@Override
public void onError(Exception ex) {
+ activeClient.compareAndSet(this, null);
log.warn("WebSocket error");
if (registered.getCount() > 0) {
handshakeFailure.compareAndSet(null, ex);
@@ -244,26 +249,48 @@ public void onError(Exception ex) {
}
};
- activeClient = client;
- if (!client.connectBlocking(30, TimeUnit.SECONDS)) {
- throw new IllegalStateException("WebSocket connectBlocking returned false");
+ if (!publishSession(client)) {
+ return;
}
+ try {
+ if (!client.connectBlocking(30, TimeUnit.SECONDS)) {
+ throw new IllegalStateException("WebSocket connectBlocking returned false");
+ }
+ if (!registered.await(connectionProperties.getHandshakeTimeoutMillis(), TimeUnit.MILLISECONDS)) {
+ throw new IllegalStateException("Timeout waiting for 'registered' from center");
+ }
+ Throwable hf = handshakeFailure.get();
+ if (Objects.nonNull(hf)) {
+ if (hf instanceof Exception) {
+ throw (Exception) hf;
+ }
+ throw new IllegalStateException(hf);
+ }
+ sessionClosed.await();
+ } finally {
+ activeClient.compareAndSet(client, null);
+ closeSession(client);
+ }
+ }
- if (!registered.await(connectionProperties.getHandshakeTimeoutMillis(), TimeUnit.MILLISECONDS)) {
- client.close();
- throw new IllegalStateException("Timeout waiting for 'registered' from center");
+ private synchronized boolean publishSession(WebSocketClient client) {
+ if (shutdownRequested) {
+ return false;
}
- Throwable hf = handshakeFailure.get();
- if (Objects.nonNull(hf)) {
+ activeClient.set(client);
+ return true;
+ }
+
+ private boolean isCurrentSession(WebSocketClient client) {
+ return !shutdownRequested && activeClient.get() == client;
+ }
+
+ private static void closeSession(WebSocketClient client) {
+ try {
client.close();
- if (hf instanceof Exception) {
- throw (Exception) hf;
- }
- throw new IllegalStateException(hf);
+ } catch (Exception e) {
+ log.debug("ws session close failed");
}
-
- sessionClosed.await();
- activeClient = null;
}
private void validateConnectionProperties() {
@@ -316,6 +343,9 @@ private void handleTextMessage(
CountDownLatch registered,
AtomicReference handshakeFailure)
throws Exception {
+ if (!isCurrentSession(ws)) {
+ return;
+ }
JsonNode root = MAPPER.readTree(payload);
String type = root.path("type").asText("");
if ("registered".equals(type)) {
@@ -336,7 +366,7 @@ private void handleTextMessage(
sendResult(ws, result("", false, Collections.emptyList(), "invalid worker request ID"));
return;
}
- if (shutdownRequested || !ws.isOpen() || registered.getCount() > 0
+ if (!isCurrentSession(ws) || !ws.isOpen() || registered.getCount() > 0
|| Objects.nonNull(handshakeFailure.get())) {
sendResult(ws, result(requestId, false, Collections.emptyList(), "worker is not registered"));
return;
@@ -379,7 +409,7 @@ private void runCollectSafe(WebSocketClient ws, OpenCliWsCollectRequests.Key key
} finally {
collectRequests.complete(key, response);
}
- if (Objects.nonNull(response) && ws.isOpen()) {
+ if (Objects.nonNull(response) && isCurrentSession(ws) && ws.isOpen()) {
sendResult(ws, response);
}
}
diff --git a/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java b/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java
index 200a3cd..eff4e03 100644
--- a/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java
+++ b/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java
@@ -56,6 +56,45 @@ class OpenCliWsReverseAgentSessionTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String AGENT_URL = "http://127.0.0.1:19823";
+ @Test
+ void stopDuringConnectionSetupDoesNotPublishAnotherGeneration() throws Exception {
+ CountDownLatch resolving = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ try (LocalCenter center = new LocalCenter()) {
+ OpenCliWsAgentConnectionProperties connection = new OpenCliWsAgentConnectionProperties() {
+ @Override
+ public String getCentralApiBaseUrl() {
+ resolving.countDown();
+ boolean interrupted = false;
+ while (release.getCount() > 0) {
+ try {
+ release.await();
+ } catch (InterruptedException failure) {
+ interrupted = true;
+ }
+ }
+ if (interrupted) {
+ Thread.currentThread().interrupt();
+ }
+ return super.getCentralApiBaseUrl();
+ }
+ };
+ connection.setCentralApiBaseUrl(center.agentProperties().getCentralApiBaseUrl());
+ connection.setAgentAdvertiseUrl(AGENT_URL);
+ try (OpenCliWsReverseAgentClient agent = new OpenCliWsReverseAgentClient(
+ probe(ContractProbe.class.getName()), connection)) {
+ try {
+ agent.start();
+ assertTrue(resolving.await(5, TimeUnit.SECONDS));
+ agent.stop();
+ } finally {
+ release.countDown();
+ }
+ assertNull(center.messages.poll(1, TimeUnit.SECONDS), "stopped worker published a registration");
+ }
+ }
+ }
+
@Test
void exchangesRegistrationAndCollectResultsAndReconnectsAfterRemoteClose() throws Exception {
try (LocalCenter center = new LocalCenter()) {
From 95de832923be497da699245fe42580f96b1510f3 Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Thu, 19 Nov 2026 00:11:02 +0800
Subject: [PATCH 023/105] fix: drain OpenCLI reverse worker on restartable stop
---
README.md | 4 +-
README.zh-CN.md | 4 +-
.../harden-opencli-reverse-agent/tasks.md | 10 +-
.../ws/OpenCliWsReverseAgentClient.java | 184 +++++++++++++-----
.../ws/OpenCliWsReverseAgentSessionTest.java | 47 +++++
5 files changed, 201 insertions(+), 48 deletions(-)
diff --git a/README.md b/README.md
index b6a8726..59fda97 100644
--- a/README.md
+++ b/README.md
@@ -226,7 +226,9 @@ Protocol: edge sends `register`; center replies `registered`; center sends `coll
The reverse agent accepts up to four concurrent collect tasks and 32 queued tasks by default. Set `maxConcurrentCollects` and `maxPendingCollects` on the connection properties before constructing the agent to change the limits. A queue capacity of zero disables waiting. When full, the agent replies with a failed `result` and the error `worker is busy`.
-Collect request IDs must be nonblank strings of at most 128 UTF-8 bytes. The agent suppresses identical in-flight requests and rejects a reused ID with a different payload. An explicit retry may return a result marked `cached: true`. The in-memory cache keeps up to 1,024 completed results for at most ten minutes. Replay across reconnects requires the same TLS-verified endpoint. Plain WebSocket connections keep session-local deduplication. Restarting the agent discards its cache.
+Collect request IDs must be nonblank strings of at most 128 UTF-8 bytes. The agent suppresses identical in-flight requests and rejects a reused ID with a different payload. An explicit retry may return a result marked `cached: true`. The in-memory cache keeps up to 1,024 completed results for at most ten minutes. Replay across reconnects requires the same TLS-verified endpoint. Plain WebSocket connections keep session-local deduplication. A new agent instance starts with an empty cache.
+
+`stop()` stops admission, discards queued tasks and allows in-flight work up to five seconds to finish before requesting cancellation. After the runner has stopped, `start()` can reconnect the same instance. `close()` immediately requests cancellation and closes the instance permanently.
### Diagnostic export
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 06d0272..9a050c5 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -225,7 +225,9 @@ agent.close();
反向 Agent 默认最多同时执行 4 个 collect 任务,另有 32 个等待名额。构建 Agent 前,可在连接配置中设置 `maxConcurrentCollects` 和 `maxPendingCollects`。等待容量为零时直接拒绝超额请求。容量用尽时返回失败的 `result`,错误为 `worker is busy`。
-collect 请求 ID 必须为非空白字符串,长度上限 128 个 UTF-8 字节。相同的在途请求只执行一次,同一个 ID 对应不同载荷时会明确拒绝。显式重试已完成的请求有可能收到标记为 `cached: true` 的结果。内存缓存最多保留 1,024 条完成结果,每条最长 10 分钟。跨连接重放要求使用同一个经过 TLS 校验的端点,明文 WebSocket 的去重范围为当前连接。Agent 重启后会清空缓存。
+collect 请求 ID 必须为非空白字符串,长度上限 128 个 UTF-8 字节。相同的在途请求只执行一次,同一个 ID 对应不同载荷时会明确拒绝。显式重试已完成的请求有可能收到标记为 `cached: true` 的结果。内存缓存最多保留 1,024 条完成结果,每条最长 10 分钟。跨连接重放要求使用同一个经过 TLS 校验的端点,明文 WebSocket 的去重范围为当前连接。创建新 Agent 实例时从空缓存开始。
+
+`stop()` 停止接单并丢弃等待任务,为已在途任务保留最多 5 秒的收尾时间,随后请求取消。连接线程退出后,同一实例可再次调用 `start()` 重连。`close()` 立即请求取消,并永久关闭该实例。
### 诊断导出
diff --git a/openspec/changes/harden-opencli-reverse-agent/tasks.md b/openspec/changes/harden-opencli-reverse-agent/tasks.md
index fa39831..37a1fc5 100644
--- a/openspec/changes/harden-opencli-reverse-agent/tasks.md
+++ b/openspec/changes/harden-opencli-reverse-agent/tasks.md
@@ -14,7 +14,7 @@
- [ ] 2.1 建立显式状态机及 READY gate,接收线程仅做有界解析与准入。
- [ ] 2.2 用有限执行器替换 cached pool,加入容量校验和兼容 BUSY result。
- [ ] 2.3 实现 payload digest、在途记录与有界完成缓存;同 ID 不同载荷拒绝。
-- [ ] 2.4 实现连接代际与有界 drain/cancel,CLOSED 终态。
+- [x] 2.4 实现连接代际与有界 drain/cancel,CLOSED 终态。见 OC-WS-006 验证。
## 3. 兼容与验收
@@ -35,3 +35,11 @@
`stopDuringConnectionSetupDoesNotPublishAnotherGeneration` 在连接线程读取端点时阻塞配置读取,随后调用 `stop()`,再解除阻塞。修复前本地中心收到已停止 worker 的注册消息,1 项失败,退出 1。修复后停止和连接发布共用同步边界,晚到连接无法发布。异常、关闭及退出均只退役对应 socket,当前代际检查用于注册、收单和异步结果投递。同一个已验证 TLS 中心显式重发仍可读取对应缓存。异常的默认日志保持固定文本。
`OpenCliWsReverseAgentSessionTest` 的回环服务同时覆盖提前收单、空白和超大 ID、队列溢出、重复请求、断线时在途工作、TLS 显式重发、明文会话隔离、关闭丢弃队列及关闭后拒绝重启。JDK 17 定向验证 27 项通过。JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,121 项通过,0 失败、0 错误、0 跳过。显式状态机、可重启 stop 的任务收尾合同和平台资源验收仍由相应任务跟踪。
+
+## 2026-11-19 OC-WS-006 可重启停止
+
+`restartableStopDropsQueuedCollectsAndCancelsPastDrainDeadline` 在回环中心提交持续心跳的真实 CLI 子进程,并填满等待队列。CLI 时限配置为 20 秒,确保 SDK 命令时限不会代替 Worker 的停止预算。旧实现返回后在途心跳仍递增,定向 1 项失败,退出 1。修复后 `stop()` 先停止准入、退役原连接、撤销未启动的排队任务,给已运行任务最多 5 秒收尾,再取消剩余任务。回归验证停止调用在 7 秒测试窗口内返回、心跳停止、排队任务没有启动、同一实例重连可接收任务。
+
+已启动任务保留去重占位到实际执行收尾。等待任务撤销时释放占位。重连使用原有固定线程池及其容量。终态 `close()` 仍立即取消在途工作,丢弃队列并在共用预算内等待资源回收,关闭后拒绝重启。
+
+JDK 17 定向 28 项通过。JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,122 项通过,0 失败、0 错误、0 跳过。显式连接状态机和独立平台资源验收仍由 2.1 和 3.3 跟踪。
diff --git a/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentClient.java b/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentClient.java
index e696d8e..462cb11 100644
--- a/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentClient.java
+++ b/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentClient.java
@@ -5,6 +5,7 @@
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.easy4j.opencli.OpenCliProperties;
+import io.github.easy4j.opencli.core.OpenCliCancellationToken;
import io.github.easy4j.opencli.core.OpenCliExecutor;
import io.github.easy4j.opencli.core.OpenCliResult;
import io.github.easy4j.opencli.exception.OpenCliException;
@@ -14,14 +15,15 @@
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
+import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
+import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.SynchronousQueue;
@@ -59,7 +61,8 @@ public final class OpenCliWsReverseAgentClient implements AutoCloseable {
private final OpenCliWsAgentConnectionProperties connectionProperties;
- private final ExecutorService collectPool;
+ private final ThreadPoolExecutor collectPool;
+ private final Set collectTasks = new HashSet<>();
private final OpenCliWsCollectRequests collectRequests =
new OpenCliWsCollectRequests(1024, TimeUnit.MINUTES.toNanos(10), System::nanoTime);
@@ -68,6 +71,8 @@ public final class OpenCliWsReverseAgentClient implements AutoCloseable {
private final AtomicReference activeClient = new AtomicReference<>();
private Thread runnerThread;
+ private boolean stopping;
+ private long admissionEpoch;
/**
* @param openCliProperties 本地 opencli 配置
@@ -99,7 +104,7 @@ public synchronized void start() {
if (collectPool.isShutdown()) {
throw new IllegalStateException("WebSocket worker is closed");
}
- if (runnerThread != null && runnerThread.isAlive()) {
+ if (stopping || (Objects.nonNull(runnerThread) && runnerThread.isAlive())) {
return;
}
shutdownRequested = false;
@@ -109,47 +114,101 @@ public synchronized void start() {
}
/**
- * 请求停止并关闭当前 WebSocket。
+ * 停止接单并丢弃未开始的任务。在有限时间内等待已在途任务,随后请求取消。
+ * 停止完成后可重新启动同一实例。
*/
- public synchronized void stop() {
- shutdownRequested = true;
- WebSocketClient client = activeClient.getAndSet(null);
- if (Objects.nonNull(client)) {
- try {
- client.close();
- } catch (Exception e) {
- log.debug("ws close failed during stop");
+ public void stop() {
+ long deadline = System.nanoTime() + CLOSE_WAIT_NANOS;
+ WebSocketClient client;
+ Thread runner;
+ synchronized (this) {
+ if (shutdownRequested || collectPool.isShutdown()) {
+ return;
}
+ stopping = true;
+ client = stopAdmission();
+ runner = runnerThread;
}
- if (runnerThread != null) {
- runnerThread.interrupt();
+ try {
+ if (Objects.nonNull(client)) {
+ closeSession(client);
+ }
+ synchronized (this) {
+ long remaining = deadline - System.nanoTime();
+ while (!collectTasks.isEmpty() && remaining > 0) {
+ TimeUnit.NANOSECONDS.timedWait(this, remaining);
+ remaining = deadline - System.nanoTime();
+ }
+ }
+ awaitRunner(runner, deadline);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ } finally {
+ synchronized (this) {
+ cancelOutstandingCollects();
+ stopping = false;
+ }
}
}
@Override
public void close() {
+ long deadline = System.nanoTime() + CLOSE_WAIT_NANOS;
+ WebSocketClient client;
Thread runner;
synchronized (this) {
if (collectPool.isShutdown()) {
return;
}
- stop();
+ client = stopAdmission();
+ cancelOutstandingCollects();
collectPool.shutdownNow();
collectRequests.clear();
runner = runnerThread;
}
- long deadline = System.nanoTime() + CLOSE_WAIT_NANOS;
+ if (Objects.nonNull(client)) {
+ closeSession(client);
+ }
try {
- collectPool.awaitTermination(CLOSE_WAIT_NANOS, TimeUnit.NANOSECONDS);
long remaining = deadline - System.nanoTime();
- if (remaining > 0 && Objects.nonNull(runner) && runner != Thread.currentThread()) {
- TimeUnit.NANOSECONDS.timedJoin(runner, remaining);
+ if (remaining > 0) {
+ collectPool.awaitTermination(remaining, TimeUnit.NANOSECONDS);
}
+ awaitRunner(runner, deadline);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
+ // The caller holds this worker's monitor while invalidating admission and the queue.
+ private WebSocketClient stopAdmission() {
+ shutdownRequested = true;
+ admissionEpoch++;
+ WebSocketClient client = activeClient.getAndSet(null);
+ List pending = new ArrayList<>();
+ collectPool.getQueue().drainTo(pending);
+ for (Runnable waiting : pending) {
+ finishCollect((CollectTask) waiting, null);
+ }
+ if (Objects.nonNull(runnerThread)) {
+ runnerThread.interrupt();
+ }
+ return client;
+ }
+
+ private void cancelOutstandingCollects() {
+ for (CollectTask task : collectTasks) {
+ task.cancellation.cancel();
+ }
+ }
+
+ private static void awaitRunner(Thread runner, long deadline) throws InterruptedException {
+ long remaining = deadline - System.nanoTime();
+ if (remaining > 0 && Objects.nonNull(runner) && runner != Thread.currentThread()) {
+ TimeUnit.NANOSECONDS.timedJoin(runner, remaining);
+ }
+ }
+
private void runLoop() {
int attempt = 0;
while (!shutdownRequested) {
@@ -379,42 +438,77 @@ private void admitCollect(WebSocketClient ws, Object centerIdentity, String requ
throws Exception {
OpenCliWsCollectRequests.Key key = new OpenCliWsCollectRequests.Key(centerIdentity, requestId);
byte[] digest = MessageDigest.getInstance("SHA-256").digest(MAPPER.writeValueAsBytes(payload));
- OpenCliWsCollectRequests.Admission admission = collectRequests.reserve(key, digest);
- switch (admission.status()) {
- case IN_FLIGHT:
- return;
- case CONFLICT:
- sendResult(ws, result(requestId, false, Collections.emptyList(), "worker request ID conflict"));
- return;
- case CACHED:
- sendResult(ws, admission.cachedResult());
+ OpenCliWsCollectRequests.Admission admission;
+ boolean busy = false;
+ synchronized (this) {
+ if (!isCurrentSession(ws)) {
return;
- case ACCEPTED:
+ }
+ admission = collectRequests.reserve(key, digest);
+ if (admission.status() == OpenCliWsCollectRequests.Status.ACCEPTED) {
+ CollectTask task = new CollectTask(ws, key, payload, admissionEpoch);
+ collectTasks.add(task);
try {
- collectPool.execute(() -> runCollectSafe(ws, key, payload));
+ collectPool.execute(task);
} catch (RejectedExecutionException e) {
- collectRequests.complete(key, null);
- sendResult(ws, result(requestId, false, Collections.emptyList(), "worker is busy"));
+ finishCollect(task, null);
+ busy = true;
}
- return;
+ }
+ }
+ if (!isCurrentSession(ws)) {
+ return;
+ }
+ if (busy) {
+ sendResult(ws, result(requestId, false, Collections.emptyList(), "worker is busy"));
+ } else if (admission.status() == OpenCliWsCollectRequests.Status.CONFLICT) {
+ sendResult(ws, result(requestId, false, Collections.emptyList(), "worker request ID conflict"));
+ } else if (admission.status() == OpenCliWsCollectRequests.Status.CACHED) {
+ sendResult(ws, admission.cachedResult());
}
}
- private void runCollectSafe(WebSocketClient ws, OpenCliWsCollectRequests.Key key, JsonNode msg) {
- ObjectNode response = null;
- try {
- if (!collectPool.isShutdown() && !Thread.currentThread().isInterrupted()) {
- response = executeCollect(key.requestId(), msg);
- }
- } finally {
- collectRequests.complete(key, response);
+ private synchronized void finishCollect(CollectTask task, ObjectNode response) {
+ collectRequests.complete(task.key, response);
+ collectTasks.remove(task);
+ notifyAll();
+ }
+
+ private synchronized boolean mayStartCollect(long epoch) {
+ return !shutdownRequested && epoch == admissionEpoch && !Thread.currentThread().isInterrupted();
+ }
+
+ private final class CollectTask implements Runnable {
+ private final WebSocketClient socket;
+ private final OpenCliWsCollectRequests.Key key;
+ private final JsonNode message;
+ private final long epoch;
+ private final OpenCliCancellationToken cancellation = new OpenCliCancellationToken();
+
+ CollectTask(WebSocketClient socket, OpenCliWsCollectRequests.Key key, JsonNode message, long epoch) {
+ this.socket = socket;
+ this.key = key;
+ this.message = message;
+ this.epoch = epoch;
}
- if (Objects.nonNull(response) && isCurrentSession(ws) && ws.isOpen()) {
- sendResult(ws, response);
+
+ @Override
+ public void run() {
+ ObjectNode response = null;
+ try {
+ if (mayStartCollect(epoch)) {
+ response = executeCollect(key.requestId(), message, cancellation);
+ }
+ } finally {
+ finishCollect(this, response);
+ }
+ if (Objects.nonNull(response) && isCurrentSession(socket) && socket.isOpen()) {
+ sendResult(socket, response);
+ }
}
}
- private ObjectNode executeCollect(String requestId, JsonNode msg) {
+ private ObjectNode executeCollect(String requestId, JsonNode msg, OpenCliCancellationToken cancellation) {
try {
String site = msg.path("site").asText("");
String command = msg.path("command").asText("");
@@ -424,7 +518,7 @@ private ObjectNode executeCollect(String requestId, JsonNode msg) {
List argv =
OpenCliCenterWsCollectToArgv.toArgv(site, command, positional, args, format);
- OpenCliResult r = localExecutor.invoke(argv);
+ OpenCliResult r = localExecutor.invoke(argv, cancellation);
List items = OpenCliWsCollectStdoutItems.parseItems(r.getStdout(), format);
if (!r.isSuccess()) {
return result(requestId, false, items, "opencli reported failure");
diff --git a/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java b/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java
index eff4e03..845e71e 100644
--- a/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java
+++ b/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java
@@ -260,6 +260,53 @@ void rejectsInvalidCapacityBeforeConnection(int workers, int pending) {
() -> new OpenCliWsReverseAgentClient(new OpenCliProperties(), connection));
}
+ @Test
+ void restartableStopDropsQueuedCollectsAndCancelsPastDrainDeadline(@TempDir Path temporary) throws Exception {
+ Path release = temporary.resolve("stop-release");
+ Path heartbeat = temporary.resolve("stop-heartbeat");
+ Path queued = temporary.resolve("stop-queued");
+ Path restarted = temporary.resolve("stop-restarted");
+ try (LocalCenter center = new LocalCenter()) {
+ OpenCliWsAgentConnectionProperties connection = center.agentProperties();
+ connection.setMaxConcurrentCollects(1);
+ connection.setMaxPendingCollects(1);
+ OpenCliProperties cli = probe(LifecycleProbe.class.getName());
+ cli.setCommandTimeoutMillis(20_000L);
+ try (OpenCliWsReverseAgentClient agent = new OpenCliWsReverseAgentClient(cli, connection)) {
+ agent.start();
+ WebSocket first = center.receive("register").socket;
+ first.send("{\"type\":\"registered\"}");
+ try {
+ ObjectNode active = collect("active-stop", "heartbeat", heartbeat);
+ active.putArray("positional_args").add(release.toString());
+ first.send(active.toString());
+ assertTrue(awaitMarker(heartbeat, 3_000L), "first collect did not start");
+ sendHeldCollect(first, "queued-stop", queued, release);
+ first.send("{\"type\":\"ping\"}");
+ center.receive("pong");
+
+ long stopStarted = System.nanoTime();
+ agent.stop();
+ assertTrue(System.nanoTime() - stopStarted < TimeUnit.SECONDS.toNanos(7));
+ assertFalse(awaitMarker(queued, 500L), "queued collect started after stop");
+ byte[] before = Files.readAllBytes(heartbeat);
+ Thread.sleep(300L);
+ assertTrue(Arrays.equals(before, Files.readAllBytes(heartbeat)), "active collect kept running after stop");
+
+ agent.start();
+ WebSocket second = center.receive("register").socket;
+ assertNotSame(first, second);
+ second.send("{\"type\":\"registered\"}");
+ second.send(collect("queued-stop", "write", restarted).toString());
+ assertTrue(center.receive("result").body.path("success").asBoolean());
+ assertTrue(Files.exists(restarted));
+ } finally {
+ Files.createFile(release);
+ }
+ }
+ }
+ }
+
@Test
void closeDropsQueuedCollectsAndRejectsRestart(@TempDir Path temporary) throws Exception {
Path release = temporary.resolve("release");
From b71db728248433dd925644dda4edcd08318faf2f Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Thu, 19 Nov 2026 00:18:47 +0800
Subject: [PATCH 024/105] fix: bound and gate OpenCLI WebSocket ingress
---
README.md | 2 +
README.zh-CN.md | 2 +
.../harden-opencli-reverse-agent/tasks.md | 10 +-
.../OpenCliWsAgentConnectionProperties.java | 3 +
.../ws/OpenCliWsReverseAgentClient.java | 166 ++++++++++--------
.../ws/OpenCliWsReverseAgentSessionTest.java | 69 +++++++-
6 files changed, 177 insertions(+), 75 deletions(-)
diff --git a/README.md b/README.md
index 59fda97..fc8b8aa 100644
--- a/README.md
+++ b/README.md
@@ -226,6 +226,8 @@ Protocol: edge sends `register`; center replies `registered`; center sends `coll
The reverse agent accepts up to four concurrent collect tasks and 32 queued tasks by default. Set `maxConcurrentCollects` and `maxPendingCollects` on the connection properties before constructing the agent to change the limits. A queue capacity of zero disables waiting. When full, the agent replies with a failed `result` and the error `worker is busy`.
+The reverse agent accepts collect only after the current connection acknowledges registration. Incoming WebSocket messages are capped at 1 MiB by default, including the assembled size of fragments. Set `maxInboundMessageBytes` before constructing the agent to configure the finite byte limit. Oversized messages close the affected connection before any command is queued.
+
Collect request IDs must be nonblank strings of at most 128 UTF-8 bytes. The agent suppresses identical in-flight requests and rejects a reused ID with a different payload. An explicit retry may return a result marked `cached: true`. The in-memory cache keeps up to 1,024 completed results for at most ten minutes. Replay across reconnects requires the same TLS-verified endpoint. Plain WebSocket connections keep session-local deduplication. A new agent instance starts with an empty cache.
`stop()` stops admission, discards queued tasks and allows in-flight work up to five seconds to finish before requesting cancellation. After the runner has stopped, `start()` can reconnect the same instance. `close()` immediately requests cancellation and closes the instance permanently.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 9a050c5..e7fefa3 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -225,6 +225,8 @@ agent.close();
反向 Agent 默认最多同时执行 4 个 collect 任务,另有 32 个等待名额。构建 Agent 前,可在连接配置中设置 `maxConcurrentCollects` 和 `maxPendingCollects`。等待容量为零时直接拒绝超额请求。容量用尽时返回失败的 `result`,错误为 `worker is busy`。
+当前连接收到合法注册确认后,反向 Agent 才开始收单。入站 WebSocket 消息默认上限为 1 MiB,分片按聚合后的字节数计量。需要调整上限时,在创建 Agent 前设置有限的 `maxInboundMessageBytes`。超限消息会关闭对应连接,不会提交命令。
+
collect 请求 ID 必须为非空白字符串,长度上限 128 个 UTF-8 字节。相同的在途请求只执行一次,同一个 ID 对应不同载荷时会明确拒绝。显式重试已完成的请求有可能收到标记为 `cached: true` 的结果。内存缓存最多保留 1,024 条完成结果,每条最长 10 分钟。跨连接重放要求使用同一个经过 TLS 校验的端点,明文 WebSocket 的去重范围为当前连接。创建新 Agent 实例时从空缓存开始。
`stop()` 停止接单并丢弃等待任务,为已在途任务保留最多 5 秒的收尾时间,随后请求取消。连接线程退出后,同一实例可再次调用 `start()` 重连。`close()` 立即请求取消,并永久关闭该实例。
diff --git a/openspec/changes/harden-opencli-reverse-agent/tasks.md b/openspec/changes/harden-opencli-reverse-agent/tasks.md
index 37a1fc5..a9e30e7 100644
--- a/openspec/changes/harden-opencli-reverse-agent/tasks.md
+++ b/openspec/changes/harden-opencli-reverse-agent/tasks.md
@@ -11,7 +11,7 @@
## 2. 治理实现
-- [ ] 2.1 建立显式状态机及 READY gate,接收线程仅做有界解析与准入。
+- [x] 2.1 建立显式状态机及 READY gate,接收线程仅做有界解析与准入。见本文入站验证。
- [ ] 2.2 用有限执行器替换 cached pool,加入容量校验和兼容 BUSY result。
- [ ] 2.3 实现 payload digest、在途记录与有界完成缓存;同 ID 不同载荷拒绝。
- [x] 2.4 实现连接代际与有界 drain/cancel,CLOSED 终态。见 OC-WS-006 验证。
@@ -43,3 +43,11 @@
已启动任务保留去重占位到实际执行收尾。等待任务撤销时释放占位。重连使用原有固定线程池及其容量。终态 `close()` 仍立即取消在途工作,丢弃队列并在共用预算内等待资源回收,关闭后拒绝重启。
JDK 17 定向 28 项通过。JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,122 项通过,0 失败、0 错误、0 跳过。显式连接状态机和独立平台资源验收仍由 2.1 和 3.3 跟踪。
+
+## 2026-11-19 OC-WS-001 入站状态与消息上限
+
+每条连接的状态从 `CONNECTING` 经 `REGISTERING` 到 `READY`,退役为 `RETIRED`。只有当前连接收到单个 JSON 对象的合法注册确认后才接单。WebSocket 解码使用默认 1 MiB 的有限上限,覆盖单帧和分片聚合,可在创建 Agent 前配置。超限在 JSON 解析和任务入队前关闭该连接,后续重连需要重新注册。
+
+JDK 17 定向红灯复现三项失败,退出 1。拼接 JSON 错误推进注册,超长单帧和分片均未关闭连接。修复后验证合法确认仍可接单,两个超限场景均关闭连接、没有 CLI 标记且重新注册。发送单个超长帧时,接收方可能在对端写完前关闭连接,对端可观察到 1006 或 1009。分片超限场景验证 1009。补充拒绝零、负数及库定义的无限哨兵设置。JDK 17 定向 34 项通过。
+
+JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,128 项通过,0 失败、0 错误、0 跳过。
diff --git a/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsAgentConnectionProperties.java b/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsAgentConnectionProperties.java
index 7aa4c9d..fc33cdd 100644
--- a/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsAgentConnectionProperties.java
+++ b/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsAgentConnectionProperties.java
@@ -65,6 +65,9 @@ public class OpenCliWsAgentConnectionProperties {
/** 排队的 collect 任务上限,零表示没有等待队列。 */
private int maxPendingCollects = 32;
+ /** 单条入站 WebSocket 消息的 UTF-8 字节上限,包括分片聚合。 */
+ private int maxInboundMessageBytes = 1024 * 1024;
+
/**
* 首次 {@code registered} 应答等待上限(毫秒)。
*/
diff --git a/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentClient.java b/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentClient.java
index 462cb11..6b7a8f8 100644
--- a/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentClient.java
+++ b/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentClient.java
@@ -1,6 +1,8 @@
package io.github.easy4j.opencli.center.ws;
+import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
@@ -32,6 +34,7 @@
import java.util.concurrent.atomic.AtomicReference;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
+import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
/**
@@ -55,12 +58,14 @@
public final class OpenCliWsReverseAgentClient implements AutoCloseable {
private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final ObjectReader MESSAGE_READER = MAPPER.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
private static final long CLOSE_WAIT_NANOS = TimeUnit.SECONDS.toNanos(5);
private final OpenCliExecutor localExecutor;
private final OpenCliWsAgentConnectionProperties connectionProperties;
+ private final int maxInboundMessageBytes;
private final ThreadPoolExecutor collectPool;
private final Set collectTasks = new HashSet<>();
private final OpenCliWsCollectRequests collectRequests =
@@ -83,6 +88,10 @@ public OpenCliWsReverseAgentClient(
Objects.requireNonNull(openCliProperties, "openCliProperties");
this.connectionProperties =
Objects.requireNonNull(connectionProperties, "connectionProperties");
+ this.maxInboundMessageBytes = connectionProperties.getMaxInboundMessageBytes();
+ if (maxInboundMessageBytes <= 0 || maxInboundMessageBytes == Integer.MAX_VALUE) {
+ throw new IllegalArgumentException("Inbound WebSocket message size must have a positive finite limit");
+ }
int workers = connectionProperties.getMaxConcurrentCollects();
int pending = connectionProperties.getMaxPendingCollects();
if (workers <= 0 || pending < 0 || (long) workers + pending >= Integer.MAX_VALUE) {
@@ -250,64 +259,8 @@ private void runOneSession() throws Exception {
// The default TLS client verifies the endpoint hostname. Plain WS has session-local identity.
Object centerIdentity = "wss".equalsIgnoreCase(endpoint.getScheme()) ? endpoint : new Object();
- final CountDownLatch registered = new CountDownLatch(1);
- final CountDownLatch sessionClosed = new CountDownLatch(1);
- final AtomicReference handshakeFailure = new AtomicReference<>();
-
log.info("opencli ws connecting");
- WebSocketClient client =
- new WebSocketClient(endpoint) {
- @Override
- public void onOpen(ServerHandshake handshake) {
- if (!isCurrentSession(this)) {
- closeSession(this);
- return;
- }
- try {
- send(buildRegisterJson());
- } catch (Exception e) {
- handshakeFailure.set(e);
- registered.countDown();
- close();
- }
- }
-
- @Override
- public void onMessage(String message) {
- try {
- handleTextMessage(this, centerIdentity, message, registered, handshakeFailure);
- } catch (Exception e) {
- log.warn("handle ws message failed");
- }
- }
-
- @Override
- public void onClose(int code, String reason, boolean remote) {
- activeClient.compareAndSet(this, null);
- if (registered.getCount() > 0) {
- handshakeFailure.compareAndSet(
- null,
- new IllegalStateException(
- "WebSocket closed before 'registered' (code="
- + code
- + ")"));
- registered.countDown();
- }
- sessionClosed.countDown();
- }
-
- @Override
- public void onError(Exception ex) {
- activeClient.compareAndSet(this, null);
- log.warn("WebSocket error");
- if (registered.getCount() > 0) {
- handshakeFailure.compareAndSet(null, ex);
- registered.countDown();
- }
- sessionClosed.countDown();
- }
- };
-
+ WorkerSession client = new WorkerSession(endpoint, centerIdentity);
if (!publishSession(client)) {
return;
}
@@ -315,23 +268,94 @@ public void onError(Exception ex) {
if (!client.connectBlocking(30, TimeUnit.SECONDS)) {
throw new IllegalStateException("WebSocket connectBlocking returned false");
}
- if (!registered.await(connectionProperties.getHandshakeTimeoutMillis(), TimeUnit.MILLISECONDS)) {
+ if (!client.registered.await(connectionProperties.getHandshakeTimeoutMillis(), TimeUnit.MILLISECONDS)) {
throw new IllegalStateException("Timeout waiting for 'registered' from center");
}
- Throwable hf = handshakeFailure.get();
+ Throwable hf = client.handshakeFailure.get();
if (Objects.nonNull(hf)) {
if (hf instanceof Exception) {
throw (Exception) hf;
}
throw new IllegalStateException(hf);
}
- sessionClosed.await();
+ client.sessionClosed.await();
} finally {
- activeClient.compareAndSet(client, null);
+ client.retire(null);
closeSession(client);
}
}
+ private enum SessionPhase {
+ CONNECTING, REGISTERING, READY, RETIRED
+ }
+
+ private final class WorkerSession extends WebSocketClient {
+ private final Object centerIdentity;
+ private final AtomicReference phase = new AtomicReference<>(SessionPhase.CONNECTING);
+ private final CountDownLatch registered = new CountDownLatch(1);
+ private final CountDownLatch sessionClosed = new CountDownLatch(1);
+ private final AtomicReference handshakeFailure = new AtomicReference<>();
+
+ WorkerSession(URI endpoint, Object centerIdentity) {
+ super(endpoint, new Draft_6455(Collections.emptyList(), maxInboundMessageBytes));
+ this.centerIdentity = centerIdentity;
+ }
+
+ @Override
+ public void onOpen(ServerHandshake handshake) {
+ if (!isCurrentSession(this) || !phase.compareAndSet(SessionPhase.CONNECTING, SessionPhase.REGISTERING)) {
+ closeSession(this);
+ return;
+ }
+ try {
+ send(buildRegisterJson());
+ } catch (Exception e) {
+ retire(e);
+ closeSession(this);
+ }
+ }
+
+ @Override
+ public void onMessage(String message) {
+ try {
+ handleTextMessage(this, message);
+ } catch (Exception e) {
+ log.warn("handle ws message failed");
+ }
+ }
+
+ @Override
+ public void onClose(int code, String reason, boolean remote) {
+ retire(new IllegalStateException("WebSocket closed before 'registered' (code=" + code + ")"));
+ }
+
+ @Override
+ public void onError(Exception ex) {
+ log.warn("WebSocket error");
+ retire(ex);
+ }
+
+ void acknowledgeRegistration() {
+ if (phase.compareAndSet(SessionPhase.REGISTERING, SessionPhase.READY)) {
+ registered.countDown();
+ }
+ }
+
+ boolean isReady() {
+ return phase.get() == SessionPhase.READY;
+ }
+
+ void retire(Throwable cause) {
+ SessionPhase previous = phase.getAndSet(SessionPhase.RETIRED);
+ activeClient.compareAndSet(this, null);
+ if (previous == SessionPhase.CONNECTING || previous == SessionPhase.REGISTERING) {
+ handshakeFailure.compareAndSet(null, cause);
+ registered.countDown();
+ }
+ sessionClosed.countDown();
+ }
+ }
+
private synchronized boolean publishSession(WebSocketClient client) {
if (shutdownRequested) {
return false;
@@ -395,20 +419,17 @@ private String buildRegisterJson() throws Exception {
return MAPPER.writeValueAsString(reg);
}
- private void handleTextMessage(
- WebSocketClient ws,
- Object centerIdentity,
- String payload,
- CountDownLatch registered,
- AtomicReference handshakeFailure)
- throws Exception {
+ private void handleTextMessage(WorkerSession ws, String payload) throws Exception {
if (!isCurrentSession(ws)) {
return;
}
- JsonNode root = MAPPER.readTree(payload);
+ JsonNode root = MESSAGE_READER.readTree(payload);
+ if (Objects.isNull(root) || !root.isObject()) {
+ return;
+ }
String type = root.path("type").asText("");
if ("registered".equals(type)) {
- registered.countDown();
+ ws.acknowledgeRegistration();
return;
}
if ("ping".equals(type)) {
@@ -425,12 +446,11 @@ private void handleTextMessage(
sendResult(ws, result("", false, Collections.emptyList(), "invalid worker request ID"));
return;
}
- if (!isCurrentSession(ws) || !ws.isOpen() || registered.getCount() > 0
- || Objects.nonNull(handshakeFailure.get())) {
+ if (!isCurrentSession(ws) || !ws.isOpen() || !ws.isReady()) {
sendResult(ws, result(requestId, false, Collections.emptyList(), "worker is not registered"));
return;
}
- admitCollect(ws, centerIdentity, requestId, root);
+ admitCollect(ws, ws.centerIdentity, requestId, root);
}
}
diff --git a/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java b/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java
index 845e71e..d9e255e 100644
--- a/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java
+++ b/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java
@@ -10,6 +10,7 @@
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
+import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -32,6 +33,7 @@
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import org.java_websocket.WebSocket;
+import org.java_websocket.enums.Opcode;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.DefaultSSLWebSocketServerFactory;
import org.java_websocket.server.WebSocketServer;
@@ -168,6 +170,68 @@ void collectBeforeRegistrationAcknowledgementDoesNotStartChild(@TempDir Path tem
}
}
+ @Test
+ void trailingJsonCannotAcknowledgeRegistration(@TempDir Path temporary) throws Exception {
+ Path rejectedMarker = temporary.resolve("invalid-ack-child");
+ Path readyMarker = temporary.resolve("ready-child");
+ try (LocalCenter center = new LocalCenter();
+ OpenCliWsReverseAgentClient agent = new OpenCliWsReverseAgentClient(
+ probe(LifecycleProbe.class.getName()), center.agentProperties())) {
+ agent.start();
+ WebSocket socket = center.receive("register").socket;
+ socket.send("{\"type\":\"registered\"} {\"type\":\"ping\"}");
+ socket.send(collect("invalid-ack", "write", rejectedMarker).toString());
+ JsonNode rejected = center.receive("result").body;
+ assertFalse(rejected.path("success").asBoolean(), "malformed acknowledgement enabled collection");
+ assertFalse(Files.exists(rejectedMarker));
+
+ socket.send("{\"type\":\"registered\"}");
+ socket.send(collect("valid-ack", "write", readyMarker).toString());
+ assertTrue(center.receive("result").body.path("success").asBoolean());
+ assertTrue(Files.exists(readyMarker));
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void oversizedMessageRetiresGenerationBeforeCollect(boolean fragmented, @TempDir Path temporary) throws Exception {
+ Path marker = temporary.resolve("oversized-child");
+ char[] padding = new char[1024 * 1024];
+ Arrays.fill(padding, 'x');
+ byte[] bytes = collect("oversized", "write", marker).put("fixture", new String(padding))
+ .toString().getBytes(StandardCharsets.UTF_8);
+ try (LocalCenter center = new LocalCenter();
+ OpenCliWsReverseAgentClient agent = new OpenCliWsReverseAgentClient(
+ probe(LifecycleProbe.class.getName()), center.agentProperties())) {
+ agent.start();
+ WebSocket socket = center.receive("register").socket;
+ socket.send("{\"type\":\"registered\"}");
+ if (fragmented) {
+ int midpoint = bytes.length / 2;
+ socket.sendFragmentedFrame(Opcode.TEXT, ByteBuffer.wrap(bytes, 0, midpoint).slice(), false);
+ socket.sendFragmentedFrame(Opcode.TEXT,
+ ByteBuffer.wrap(bytes, midpoint, bytes.length - midpoint).slice(), true);
+ } else {
+ socket.send(new String(bytes, StandardCharsets.UTF_8));
+ }
+ Integer code = center.closeCodes.poll(3, TimeUnit.SECONDS);
+ // Rejecting a complete frame from its header can reset the peer's still-active write.
+ assertTrue(Integer.valueOf(1009).equals(code) || (!fragmented && Integer.valueOf(1006).equals(code)),
+ "oversized message should close the socket, observed code=" + code);
+ assertFalse(Files.exists(marker), "oversized request started a child");
+ assertNotSame(socket, center.receive("register").socket);
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = {0, -1, Integer.MAX_VALUE})
+ void rejectsUnboundedInboundLimitBeforeConnection(int limit) {
+ OpenCliWsAgentConnectionProperties connection = new OpenCliWsAgentConnectionProperties();
+ connection.setMaxInboundMessageBytes(limit);
+ assertThrows(IllegalArgumentException.class, () -> new OpenCliWsReverseAgentClient(
+ probe(LifecycleProbe.class.getName()), connection));
+ }
+
@Test
void defaultsToFourActiveCollects(@TempDir Path temporary) throws Exception {
Path release = temporary.resolve("release");
@@ -553,6 +617,7 @@ private WireMessage(WebSocket socket, JsonNode body) {
private static final class LocalCenter extends WebSocketServer implements AutoCloseable {
private final CountDownLatch started = new CountDownLatch(1);
private final BlockingQueue messages = new LinkedBlockingQueue<>();
+ private final BlockingQueue closeCodes = new LinkedBlockingQueue<>();
private final AtomicReference failure = new AtomicReference<>();
private final boolean secure;
@@ -596,7 +661,9 @@ private WireMessage receive(String type) throws InterruptedException {
public void onOpen(WebSocket socket, ClientHandshake handshake) { }
@Override
- public void onClose(WebSocket socket, int code, String reason, boolean remote) { }
+ public void onClose(WebSocket socket, int code, String reason, boolean remote) {
+ closeCodes.add(code);
+ }
@Override
public void onMessage(WebSocket socket, String payload) {
From b4b6f817f4414be7eaf76a6db51c283a58adb35b Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Thu, 19 Nov 2026 00:26:14 +0800
Subject: [PATCH 025/105] fix: reconnect OpenCLI worker after failed result
delivery
---
.../harden-opencli-reverse-agent/tasks.md | 10 ++-
.../ws/OpenCliWsReverseAgentClient.java | 20 ++++--
.../ws/OpenCliWsReverseAgentSessionTest.java | 68 +++++++++++++++++--
3 files changed, 87 insertions(+), 11 deletions(-)
diff --git a/openspec/changes/harden-opencli-reverse-agent/tasks.md b/openspec/changes/harden-opencli-reverse-agent/tasks.md
index a9e30e7..6f8d925 100644
--- a/openspec/changes/harden-opencli-reverse-agent/tasks.md
+++ b/openspec/changes/harden-opencli-reverse-agent/tasks.md
@@ -18,8 +18,8 @@
## 3. 兼容与验收
-- [ ] 3.1 证明重连不自动重复写入,完成发送失败不被误标为执行失败。
-- [ ] 3.2 验证现有消息结构在 legacy fixture 中不变,安全日志符合 C09。
+- [x] 3.1 证明重连不自动重复写入,完成发送失败不被误标为执行失败。
+- [x] 3.2 验证现有消息结构在 legacy fixture 中不变,安全日志符合 C09。
- [ ] 3.3 分别在三线运行 WS压力/断线fixture,记录执行次数、线程数与终结资源结果。
## 证据交付模板(实施时填写)
@@ -51,3 +51,9 @@ JDK 17 定向 28 项通过。JDK 8 使用系统 Maven 执行 `-B -ntp -o clean v
JDK 17 定向红灯复现三项失败,退出 1。拼接 JSON 错误推进注册,超长单帧和分片均未关闭连接。修复后验证合法确认仍可接单,两个超限场景均关闭连接、没有 CLI 标记且重新注册。发送单个超长帧时,接收方可能在对端写完前关闭连接,对端可观察到 1006 或 1009。分片超限场景验证 1009。补充拒绝零、负数及库定义的无限哨兵设置。JDK 17 定向 34 项通过。
JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,128 项通过,0 失败、0 错误、0 跳过。
+
+## 2026-11-19 OC-WS-005 投递失败和旧协议兼容
+
+在 TLS 回环环境向第一次结果发送注入异常,CLI 子进程实际写入执行标记。修复前中心等待第二次注册超时,定向 2 项中 1 项失败,退出 1。修复后失败连接退役。第二条连接完成注册和心跳时,中心仍未收到自动投递。中心显式重发相同请求后,收到原成功结果和 `cached: true`,`error` 为空,实际子进程标记始终为一条。日志捕获包含固定的投递失败消息,异常内测试密钥未出现在日志中。
+
+旧协议夹具继续核对 register 的五个字段、pong 的单字段、成功与失败 result 的五个字段,以及实际进程收到的完整 argv。三个版本的直接字段断言通过。JDK 17 定向 35 项通过。JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,129 项通过,0 失败、0 错误、0 跳过。全量通过后单独复跑加严的旧协议字段断言,1 项通过。此处的诊断结论覆盖反向 Worker,跨传输隐私仍由 C09 跟踪。
diff --git a/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentClient.java b/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentClient.java
index 6b7a8f8..f055f54 100644
--- a/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentClient.java
+++ b/src/main/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentClient.java
@@ -32,6 +32,7 @@
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.BiConsumer;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
@@ -62,6 +63,7 @@ public final class OpenCliWsReverseAgentClient implements AutoCloseable {
private static final long CLOSE_WAIT_NANOS = TimeUnit.SECONDS.toNanos(5);
private final OpenCliExecutor localExecutor;
+ private final BiConsumer resultSender;
private final OpenCliWsAgentConnectionProperties connectionProperties;
@@ -85,6 +87,12 @@ public final class OpenCliWsReverseAgentClient implements AutoCloseable {
*/
public OpenCliWsReverseAgentClient(
OpenCliProperties openCliProperties, OpenCliWsAgentConnectionProperties connectionProperties) {
+ this(openCliProperties, connectionProperties, WebSocketClient::send);
+ }
+
+ OpenCliWsReverseAgentClient(OpenCliProperties openCliProperties,
+ OpenCliWsAgentConnectionProperties connectionProperties, BiConsumer resultSender) {
+ this.resultSender = Objects.requireNonNull(resultSender, "resultSender");
Objects.requireNonNull(openCliProperties, "openCliProperties");
this.connectionProperties =
Objects.requireNonNull(connectionProperties, "connectionProperties");
@@ -454,7 +462,7 @@ private void handleTextMessage(WorkerSession ws, String payload) throws Exceptio
}
}
- private void admitCollect(WebSocketClient ws, Object centerIdentity, String requestId, JsonNode payload)
+ private void admitCollect(WorkerSession ws, Object centerIdentity, String requestId, JsonNode payload)
throws Exception {
OpenCliWsCollectRequests.Key key = new OpenCliWsCollectRequests.Key(centerIdentity, requestId);
byte[] digest = MessageDigest.getInstance("SHA-256").digest(MAPPER.writeValueAsBytes(payload));
@@ -499,13 +507,13 @@ private synchronized boolean mayStartCollect(long epoch) {
}
private final class CollectTask implements Runnable {
- private final WebSocketClient socket;
+ private final WorkerSession socket;
private final OpenCliWsCollectRequests.Key key;
private final JsonNode message;
private final long epoch;
private final OpenCliCancellationToken cancellation = new OpenCliCancellationToken();
- CollectTask(WebSocketClient socket, OpenCliWsCollectRequests.Key key, JsonNode message, long epoch) {
+ CollectTask(WorkerSession socket, OpenCliWsCollectRequests.Key key, JsonNode message, long epoch) {
this.socket = socket;
this.key = key;
this.message = message;
@@ -620,11 +628,13 @@ private static ObjectNode result(String requestId, boolean success, List {
+ if (firstSend.getAndSet(false)) {
+ throw new IllegalStateException(canary);
+ }
+ socket.send(json);
+ });
+ PrintStream capture = new PrintStream(diagnostics, true, "UTF-8")) {
+ System.setErr(capture);
+ try {
+ agent.start();
+ WebSocket first = center.receive("register").socket;
+ first.send("{\"type\":\"registered\"}");
+ first.send(request.toString());
+
+ WebSocket second = center.receive("register").socket;
+ assertNotSame(first, second);
+ second.send("{\"type\":\"registered\"}");
+ second.send("{\"type\":\"ping\"}");
+ center.receive("pong");
+ assertEquals(Arrays.asList("started"), Files.readAllLines(marker, StandardCharsets.UTF_8));
+
+ second.send(request.toString());
+ JsonNode replayed = center.receive("result").body;
+ assertEquals("delivery", replayed.path("request_id").asText());
+ assertTrue(replayed.path("success").asBoolean());
+ assertTrue(replayed.path("cached").asBoolean());
+ assertTrue(replayed.path("error").isNull());
+ assertEquals(Arrays.asList("started"), Files.readAllLines(marker, StandardCharsets.UTF_8));
+ } finally {
+ System.setErr(previousErr);
+ }
+ }
+ String logText = diagnostics.toString(StandardCharsets.UTF_8.name());
+ assertTrue(logText.contains("failed to send WS result"));
+ assertFalse(logText.contains(canary));
+ }
+
private static void verifyReconnectReplay(Path temporary, SSLContext tls, boolean expectCache) throws Exception {
Path marker = temporary.resolve("reconnect-start");
Path release = temporary.resolve("reconnect-release");
From 47c2009d57e76fd95ad7fcbfe5e46c490bd04051 Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Thu, 19 Nov 2026 00:31:38 +0800
Subject: [PATCH 026/105] test: verify OpenCLI worker resources across
disconnect and close
---
.../harden-opencli-reverse-agent/tasks.md | 10 ++-
.../ws/OpenCliWsReverseAgentSessionTest.java | 78 +++++++++++++++++++
.../opencli/contract/LifecycleProbe.java | 6 +-
3 files changed, 92 insertions(+), 2 deletions(-)
diff --git a/openspec/changes/harden-opencli-reverse-agent/tasks.md b/openspec/changes/harden-opencli-reverse-agent/tasks.md
index 6f8d925..837a7cb 100644
--- a/openspec/changes/harden-opencli-reverse-agent/tasks.md
+++ b/openspec/changes/harden-opencli-reverse-agent/tasks.md
@@ -20,7 +20,7 @@
- [x] 3.1 证明重连不自动重复写入,完成发送失败不被误标为执行失败。
- [x] 3.2 验证现有消息结构在 legacy fixture 中不变,安全日志符合 C09。
-- [ ] 3.3 分别在三线运行 WS压力/断线fixture,记录执行次数、线程数与终结资源结果。
+- [x] 3.3 分别在三线运行 WS压力/断线fixture,记录执行次数、线程数与终结资源结果。
## 证据交付模板(实施时填写)
@@ -57,3 +57,11 @@ JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,128 项通过,0
在 TLS 回环环境向第一次结果发送注入异常,CLI 子进程实际写入执行标记。修复前中心等待第二次注册超时,定向 2 项中 1 项失败,退出 1。修复后失败连接退役。第二条连接完成注册和心跳时,中心仍未收到自动投递。中心显式重发相同请求后,收到原成功结果和 `cached: true`,`error` 为空,实际子进程标记始终为一条。日志捕获包含固定的投递失败消息,异常内测试密钥未出现在日志中。
旧协议夹具继续核对 register 的五个字段、pong 的单字段、成功与失败 result 的五个字段,以及实际进程收到的完整 argv。三个版本的直接字段断言通过。JDK 17 定向 35 项通过。JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,129 项通过,0 失败、0 错误、0 跳过。全量通过后单独复跑加严的旧协议字段断言,1 项通过。此处的诊断结论覆盖反向 Worker,跨传输隐私仍由 C09 跟踪。
+
+## 2026-11-19 C05 压力、断线与资源收尾
+
+`disconnectAndCloseReleaseBoundedWorkerResources` 通过回环 WS 中心启动两个持续心跳的真实 CLI 子进程,排队一项并拒绝一项超额请求,随后断开旧连接并重新注册。重连后,每项有效命令仍只执行一次,排队和超额请求均没有启动标记。观测到 2 个收单线程、1 个连接发起线程、2 个 stdout 与 2 个 stderr 读取线程。计数以场景前 JVM 线程集合为基线。
+
+终态关闭后,上述线程和 SDK 的终止工作线程新增数回到零,两个真实子进程的心跳停止,执行标记仍为两条。Surefire 报告保留 `C05 resources: started=2 workerThreads=2 runnerThreads=1 readers=4 threadsAfterClose=0`。该计数覆盖 SDK 自有线程,回环中心和 Java-WebSocket 内部线程由各自生命周期管理。
+
+JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,130 项通过,0 失败、0 错误、0 跳过。三条线在本地 macOS 得到相同观测。最新托管平台结果单独记录于 PR。
diff --git a/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java b/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java
index a66e2a5..4f308ce 100644
--- a/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java
+++ b/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java
@@ -239,6 +239,84 @@ void rejectsUnboundedInboundLimitBeforeConnection(int limit) {
probe(LifecycleProbe.class.getName()), connection));
}
+ @Test
+ void disconnectAndCloseReleaseBoundedWorkerResources(@TempDir Path temporary) throws Exception {
+ Set baseline = Thread.getAllStackTraces().keySet();
+ Path gate = temporary.resolve("resource-release");
+ Path queued = temporary.resolve("resource-queued");
+ Path overflow = temporary.resolve("resource-overflow");
+ List pulses = Arrays.asList(temporary.resolve("heartbeat-0"), temporary.resolve("heartbeat-1"));
+ List starts = Arrays.asList(temporary.resolve("start-0"), temporary.resolve("start-1"));
+ try (LocalCenter center = new LocalCenter()) {
+ OpenCliWsAgentConnectionProperties connection = center.agentProperties();
+ connection.setMaxConcurrentCollects(2);
+ connection.setMaxPendingCollects(1);
+ OpenCliProperties cli = probe(LifecycleProbe.class.getName());
+ cli.setCommandTimeoutMillis(20_000L);
+ try (OpenCliWsReverseAgentClient agent = new OpenCliWsReverseAgentClient(cli, connection)) {
+ agent.start();
+ WebSocket first = center.receive("register").socket;
+ first.send("{\"type\":\"registered\"}");
+ try {
+ for (int index = 0; index < pulses.size(); index++) {
+ ObjectNode payload = collect("resource-" + index, "heartbeat-log", pulses.get(index));
+ payload.putArray("positional_args").add(gate.toString()).add(starts.get(index).toString());
+ first.send(payload.toString());
+ assertTrue(awaitMarker(pulses.get(index), 5_000L));
+ }
+ first.send(collect("queued-resource", "write", queued).toString());
+ first.send(collect("overflow-resource", "write", overflow).toString());
+ JsonNode rejected = center.receive("result").body;
+ assertEquals("overflow-resource", rejected.path("request_id").asText());
+ assertEquals("worker is busy", rejected.path("error").asText());
+ assertFalse(Files.exists(queued));
+ assertFalse(Files.exists(overflow));
+
+ first.close();
+ WebSocket second = center.receive("register").socket;
+ assertNotSame(first, second);
+ second.send("{\"type\":\"registered\"}");
+ second.send("{\"type\":\"ping\"}");
+ center.receive("pong");
+
+ Set running = workerThreadsSince(baseline);
+ assertEquals(2, running.stream().filter(t -> "opencli-ws-collect".equals(t.getName())).count());
+ assertEquals(1, running.stream().filter(t -> "opencli-ws-agent-runner".equals(t.getName())).count());
+ assertEquals(2, running.stream().filter(t -> "opencli-stdout".equals(t.getName())).count());
+ assertEquals(2, running.stream().filter(t -> "opencli-stderr".equals(t.getName())).count());
+
+ agent.close();
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2L);
+ while (!workerThreadsSince(baseline).isEmpty() && System.nanoTime() < deadline) {
+ Thread.sleep(20L);
+ }
+ assertTrue(workerThreadsSince(baseline).isEmpty(), "worker threads survived close");
+ byte[] firstPulse = Files.readAllBytes(pulses.get(0));
+ byte[] secondPulse = Files.readAllBytes(pulses.get(1));
+ Thread.sleep(300L);
+ assertTrue(Arrays.equals(firstPulse, Files.readAllBytes(pulses.get(0))));
+ assertTrue(Arrays.equals(secondPulse, Files.readAllBytes(pulses.get(1))));
+ for (Path started : starts) {
+ assertEquals(Arrays.asList("started"), Files.readAllLines(started, StandardCharsets.UTF_8));
+ }
+ assertFalse(Files.exists(queued));
+ assertFalse(Files.exists(overflow));
+ System.out.println("C05 resources: started=2 workerThreads=2 runnerThreads=1 readers=4 threadsAfterClose=0");
+ } finally {
+ Files.createFile(gate);
+ }
+ }
+ }
+ }
+
+ private static Set workerThreadsSince(Set baseline) {
+ List names = Arrays.asList("opencli-ws-collect", "opencli-ws-agent-runner",
+ "opencli-stdout", "opencli-stderr", "opencli-stop", "opencli-force-stop");
+ return Thread.getAllStackTraces().keySet().stream()
+ .filter(thread -> !baseline.contains(thread) && names.contains(thread.getName()))
+ .collect(Collectors.toSet());
+ }
+
@Test
void defaultsToFourActiveCollects(@TempDir Path temporary) throws Exception {
Path release = temporary.resolve("release");
diff --git a/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java b/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java
index 3ed062b..0b2bc3b 100644
--- a/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java
+++ b/src/test/java/io/github/easy4j/opencli/contract/LifecycleProbe.java
@@ -41,6 +41,10 @@ public static void main(String[] args) throws Exception {
writeStream(System.out, Integer.parseInt(args[3]));
writeStream(System.err, Integer.parseInt(args[4]));
}
+ if ("heartbeat-log".equals(mode)) {
+ Files.write(Paths.get(args[3]), "started\n".getBytes(StandardCharsets.UTF_8),
+ StandardOpenOption.CREATE, StandardOpenOption.APPEND);
+ }
Path marker = Paths.get(args[1]);
if ("count-hold".equals(mode)) {
Files.write(marker, "started\n".getBytes(StandardCharsets.UTF_8),
@@ -53,7 +57,7 @@ public static void main(String[] args) throws Exception {
long start = System.nanoTime();
int tick = 0;
while (!Files.exists(release) && System.nanoTime() - start < 10_000_000_000L) {
- if ("heartbeat".equals(mode)) {
+ if ("heartbeat".equals(mode) || "heartbeat-log".equals(mode)) {
Files.write(marker, Integer.toString(++tick).getBytes(StandardCharsets.UTF_8));
}
Thread.sleep(20L);
From 0c6150678f4aec99887717700f44eb9bc89ed00e Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Thu, 19 Nov 2026 00:39:17 +0800
Subject: [PATCH 027/105] fix: keep private data out of OpenCLI exception
diagnostics
---
README.md | 2 ++
README.zh-CN.md | 2 ++
.../tasks.md | 20 ++++++++++++---
.../opencli/core/OpenCliArgSupport.java | 7 +++++-
.../support/SubprocessExecutionSupport.java | 3 ++-
.../opencli/core/OpenCliArgSupportTest.java | 25 +++++++++++++++++++
.../core/OpenCliProcessPrivacyTest.java | 25 +++++++++++++++++++
.../SubprocessExecutionSupportTest.java | 24 ++++++++++++++++++
src/test/resources/simplelogger.properties | 1 +
9 files changed, 104 insertions(+), 5 deletions(-)
diff --git a/README.md b/README.md
index fc8b8aa..fa5dec0 100644
--- a/README.md
+++ b/README.md
@@ -238,6 +238,8 @@ Call `OpenCliDiagnosticExport.export(result, 512)` explicitly with an `OpenCliRe
The SDK returns the text in memory. Your application controls the destination and retention. SDK diagnostics omit argv values, raw content, URLs and filesystem paths. Applications that use or log raw results should protect that data. `remoteCaptureRawHttpResponse` is still opt-in.
+At the low-level process boundary, `RunSession.getHandler().getException()` returns a safe I/O summary. `RunSession.getIoFailure()` is the explicit raw diagnostic accessor. Handle that exception as sensitive data because it can include local paths.
+
## 9. Testing & Build
diff --git a/README.zh-CN.md b/README.zh-CN.md
index e7fefa3..2b21679 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -237,6 +237,8 @@ collect 请求 ID 必须为非空白字符串,长度上限 128 个 UTF-8 字
SDK 在内存中返回文本,由应用决定目的地和保留时间。SDK 诊断会排除命令参数、原始内容、URL 和文件路径。应用读取或记录原始结果时应自行保护这些数据。`remoteCaptureRawHttpResponse` 仍需显式开启。
+低层进程接口的 `RunSession.getHandler().getException()` 返回安全的 I/O 摘要。`RunSession.getIoFailure()` 是显式读取原始诊断的入口,异常可能包含本地路径,应按敏感数据处理。
+
## 9. 测试与构建
diff --git a/openspec/changes/harden-opencli-diagnostics-privacy/tasks.md b/openspec/changes/harden-opencli-diagnostics-privacy/tasks.md
index 2f95b95..71c2eda 100644
--- a/openspec/changes/harden-opencli-diagnostics-privacy/tasks.md
+++ b/openspec/changes/harden-opencli-diagnostics-privacy/tasks.md
@@ -7,7 +7,7 @@
## 1. 泄露负例
- [ ] 1.1 对Executor、AdapterChannel、HTTP、WS、JSON/YAML parser所有日志/异常点建立canary矩阵。
-- [ ] 1.2 新增完整日志捕获与nested cause测试,先证明当前泄露可被测试检测。
+- [x] 1.2 新增完整日志捕获与nested cause测试,先证明当前泄露可被测试检测。
## 2. 安全投影
@@ -17,10 +17,24 @@
## 3. 验证
-- [ ] 3.1 覆盖DEBUG、timeout、malformedresponse、断线和超限路径,任何canary出现均失败。
+- [x] 3.1 覆盖DEBUG、timeout、malformedresponse、断线和超限路径,任何canary出现均失败。
- [ ] 3.2 验证raw结果内容未被脱敏逻辑无声修改。
-- [ ] 3.3 三线执行相同隐私矩阵并记录证据;文档标明SDK与应用日志责任边界。
+- [x] 3.3 三线执行相同隐私矩阵并记录证据;文档标明SDK与应用日志责任边界。
## 证据交付模板(实施时填写)
每项任务的完成记录包含:Requirement/Scenario、分支HEAD、测试命令、失败→通过证据、测试数/跳过数、退出码、报告位置。没有记录的任务保持未完成。
+
+## 2026-11-19 C09 默认异常链与三线隐私矩阵
+
+JDK 17 两项定向红灯实际退出 1。选项对象的 `toString()` 抛出带嵌套 cause 和 suppressed 项的异常,栈文本泄露测试密钥。真实缺失可执行文件的低层 result handler 异常链泄露路径。修复后,值转换报告固定字段诊断,result handler 保留安全摘要。显式 `RunSession.getIoFailure()` 仍返回原始低层诊断。两项回归都扫描完整栈文本,保留原始数据的测试同时验证权限边界。
+
+| 场景 | 现有三线回归 |
+| --- | --- |
+| Adapter DEBUG、本地非零退出、超时、超限、原始 stdout/stderr | `OpenCliProcessPrivacyTest` |
+| 参数对象的嵌套 cause/suppressed、底层原生路径 | `OpenCliArgSupportTest`、`SubprocessExecutionSupportTest` |
+| HTTP 503、凭据 URL、畸形 JSON、原文捕获开关 | `OpenCliRemoteAgentHttpClientTest` |
+| WebSocket 断线和投递异常、配置 URL、日志测试密钥 | `OpenCliWsReverseAgentSessionTest`、`OpenCliWsReverseAgentClientTest` |
+| JSON 解析 DEBUG、默认不写入的有界导出 | `OpenCliStdoutJsonTest`、`OpenCliDiagnosticExportTest` |
+
+JDK 8 使用系统 Maven 执行 `-B -ntp -o clean verify`,2,133 项通过,0 失败、0 错误、0 跳过。中英文 README 记录应用显式访问原始低层诊断的责任。C03 的 YAML 解码器仍待实施,对其解析日志的验证保留在后续矩阵中。
diff --git a/src/main/java/io/github/easy4j/opencli/core/OpenCliArgSupport.java b/src/main/java/io/github/easy4j/opencli/core/OpenCliArgSupport.java
index 9531dbc..b0ea0f6 100644
--- a/src/main/java/io/github/easy4j/opencli/core/OpenCliArgSupport.java
+++ b/src/main/java/io/github/easy4j/opencli/core/OpenCliArgSupport.java
@@ -97,7 +97,12 @@ public static void addOptionPairIfPresent(List target, String flag, Obje
}
static String stringValue(Object value, String field) {
- String text = String.valueOf(value);
+ String text;
+ try {
+ text = String.valueOf(value);
+ } catch (RuntimeException ex) {
+ throw new IllegalArgumentException(field + " cannot be converted to a string");
+ }
if (Objects.isNull(text)) {
throw new IllegalArgumentException(field + " string form must not be null");
}
diff --git a/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java b/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
index 40ee072..f30e628 100644
--- a/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
+++ b/src/main/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupport.java
@@ -274,7 +274,7 @@ public RunSession execute(ExecutionRequest request) throws IOException, Interrup
}
DefaultExecuteResultHandler handler = new DefaultExecuteResultHandler();
if (ioFailure != null) {
- handler.onProcessFailed(new ExecuteException("Native process I/O failure", exit == null ? -1 : exit, ioFailure));
+ handler.onProcessFailed(new ExecuteException("Native process I/O failure", exit == null ? -1 : exit));
} else if (exit != null && exit != 0) {
handler.onProcessFailed(new ExecuteException("Native process returned nonzero status", exit));
} else if (exit != null) {
@@ -567,6 +567,7 @@ public static final class RunSession {
private final boolean waitTimedOut;
private final OpenCliExecutionDetails executionDetails;
private final Integer observedExitCode;
+ /** Raw low-level I/O evidence, which can include local paths. Exclude it from default diagnostics. */
private final IOException ioFailure;
RunSession(ByteArrayOutputStream stdout, ByteArrayOutputStream stderr,
diff --git a/src/test/java/io/github/easy4j/opencli/core/OpenCliArgSupportTest.java b/src/test/java/io/github/easy4j/opencli/core/OpenCliArgSupportTest.java
index 20f0abc..3f41153 100644
--- a/src/test/java/io/github/easy4j/opencli/core/OpenCliArgSupportTest.java
+++ b/src/test/java/io/github/easy4j/opencli/core/OpenCliArgSupportTest.java
@@ -1,5 +1,7 @@
package io.github.easy4j.opencli.core;
+import java.io.PrintWriter;
+import java.io.StringWriter;
import static org.junit.jupiter.api.Assertions.*;
import java.util.ArrayList;
import java.util.Arrays;
@@ -107,6 +109,29 @@ public String toString() {
assertTrue(target.isEmpty());
}
+ @Test
+ void shouldKeepConversionExceptionAndNestedCausePrivate() {
+ List target = new ArrayList<>();
+ String canary = "private-conversion-" + UUID.randomUUID();
+ Object value = new Object() {
+ @Override
+ public String toString() {
+ IllegalArgumentException failure = new IllegalArgumentException("conversion failed",
+ new IllegalStateException(canary));
+ failure.addSuppressed(new IllegalStateException(canary));
+ throw failure;
+ }
+ };
+
+ IllegalArgumentException failure = assertThrows(IllegalArgumentException.class,
+ () -> OpenCliArgSupport.addOptionPairIfPresent(target, "--flag", value));
+ StringWriter diagnostics = new StringWriter();
+ failure.printStackTrace(new PrintWriter(diagnostics));
+ assertFalse(diagnostics.toString().contains(canary));
+ assertTrue(failure.getMessage().contains("value"));
+ assertTrue(target.isEmpty());
+ }
+
@Test
void shouldAddFlagIfTrue() {
List target = new ArrayList<>();
diff --git a/src/test/java/io/github/easy4j/opencli/core/OpenCliProcessPrivacyTest.java b/src/test/java/io/github/easy4j/opencli/core/OpenCliProcessPrivacyTest.java
index 03c9515..fbcd40e 100644
--- a/src/test/java/io/github/easy4j/opencli/core/OpenCliProcessPrivacyTest.java
+++ b/src/test/java/io/github/easy4j/opencli/core/OpenCliProcessPrivacyTest.java
@@ -1,5 +1,6 @@
package io.github.easy4j.opencli.core;
+import org.junit.jupiter.api.parallel.Isolated;
import io.github.easy4j.opencli.OpenCliProperties;
import io.github.easy4j.opencli.contract.LifecycleProbe;
import io.github.easy4j.opencli.exception.OpenCliException;
@@ -22,6 +23,7 @@
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
+@Isolated
class OpenCliProcessPrivacyTest {
@Test
@@ -46,6 +48,29 @@ void preservesStderrOnNonzeroExitWithoutLeakingArgsOrStderr() throws Exception {
}
}
+ @Test
+ void adapterDebugLogsOnlyArgumentCount() throws Exception {
+ String canary = "adapter-value-" + UUID.randomUUID();
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+ PrintStream original = System.err;
+ try (OpenCliExecutor executor = new OpenCliExecutor(childProperties());
+ PrintStream capture = new PrintStream(output, true, StandardCharsets.UTF_8.name())) {
+ System.setErr(capture);
+ try {
+ OpenCliAdapterChannel adapter = new OpenCliAdapterChannel(executor, "privacy");
+ OpenCliNonZeroExitException failure = assertThrows(OpenCliNonZeroExitException.class,
+ () -> adapter.invoke("nonzero", canary));
+ failure.printStackTrace(capture);
+ assertEquals(canary, failure.getPartialResult().getStderr());
+ } finally {
+ System.setErr(original);
+ }
+ }
+ String diagnostics = output.toString(StandardCharsets.UTF_8.name());
+ assertTrue(diagnostics.contains("OpenCLI adapter invoke argvSize=3"));
+ assertFalse(diagnostics.contains(canary));
+ }
+
@Test
void keepsArgumentsAndPartialStderrOutOfTimeoutDiagnostics() throws Exception {
String canary = "timeout-" + UUID.randomUUID();
diff --git a/src/test/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupportTest.java b/src/test/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupportTest.java
index 9123715..1262279 100644
--- a/src/test/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupportTest.java
+++ b/src/test/java/io/github/easy4j/opencli/core/support/SubprocessExecutionSupportTest.java
@@ -1,5 +1,11 @@
package io.github.easy4j.opencli.core.support;
+import io.github.easy4j.opencli.core.OpenCliExecutionDetails.TerminationReason;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.nio.file.Path;
+import org.apache.commons.exec.CommandLine;
+import org.junit.jupiter.api.io.TempDir;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
@@ -34,6 +40,24 @@ void shouldBoundBackingBufferGrowthAtTheConfiguredLimit() {
assertTrue(capture.isTruncated());
}
+ @Test
+ void shouldKeepNativePathOutOfDefaultHandlerException(@TempDir Path temporary) throws Exception {
+ String canary = "private-native-path";
+ CommandLine command = new CommandLine(temporary.resolve(canary + ".exe").toString());
+ SubprocessExecutionSupport.ExecutionRequest request = new SubprocessExecutionSupport.ExecutionRequest(
+ command, null, null, 5_000L);
+
+ SubprocessExecutionSupport.RunSession session = SubprocessExecutionSupport.execute(request);
+
+ assertEquals(TerminationReason.SPAWN_FAILED, session.getExecutionDetails().getTerminationReason());
+ assertNotNull(session.getIoFailure());
+ assertTrue(session.getIoFailure().getMessage().contains(canary));
+ assertNotNull(session.getHandler().getException());
+ StringWriter diagnostics = new StringWriter();
+ session.getHandler().getException().printStackTrace(new PrintWriter(diagnostics));
+ assertFalse(diagnostics.toString().contains(canary));
+ }
+
@Test
void shouldReturnDefaultMaxConcurrent() {
int defaultVal = SubprocessExecutionSupport.defaultMaxConcurrentExecutions();
diff --git a/src/test/resources/simplelogger.properties b/src/test/resources/simplelogger.properties
index ad97fd1..847e228 100644
--- a/src/test/resources/simplelogger.properties
+++ b/src/test/resources/simplelogger.properties
@@ -1,3 +1,4 @@
org.slf4j.simpleLogger.log.io.github.easy4j.opencli.browser.OpenCliBrowserSession=debug
org.slf4j.simpleLogger.log.io.github.easy4j.opencli.remote.OpenCliArgvToCollectParser=debug
org.slf4j.simpleLogger.log.io.github.easy4j.opencli.parser.OpenCliStdoutJson=debug
+org.slf4j.simpleLogger.log.io.github.easy4j.opencli.core.OpenCliAdapterChannel=debug
From db70054df1446e3b7d6640ecf9ecb68d8e0fbc2b Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Thu, 19 Nov 2026 00:41:53 +0800
Subject: [PATCH 028/105] ci: require exception privacy evidence on hosted
platforms
---
.github/workflows/platform-contracts.yml | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/.github/workflows/platform-contracts.yml b/.github/workflows/platform-contracts.yml
index df48f21..056ae5a 100644
--- a/.github/workflows/platform-contracts.yml
+++ b/.github/workflows/platform-contracts.yml
@@ -44,7 +44,7 @@ jobs:
mvn -version > platform-evidence/maven.txt 2>&1
result=0
mvn -B --no-transfer-progress \
- -Dtest=OpenCliArgvContractTest,OpenCliStructuredArgvContractTest,OpenCliProcessContractTest,OpenCliProcessBoundaryTest,SubprocessCleanupFaultTest,SubprocessStreamFailureTest,OpenCliWsReverseAgentSessionTest,OpenCliWsCollectRequestsTest,OpenCliProcessPrivacyTest \
+ -Dtest=OpenCliArgvContractTest,OpenCliStructuredArgvContractTest,OpenCliProcessContractTest,OpenCliProcessBoundaryTest,SubprocessCleanupFaultTest,SubprocessStreamFailureTest,OpenCliWsReverseAgentSessionTest,OpenCliWsCollectRequestsTest,OpenCliProcessPrivacyTest,OpenCliArgSupportTest#shouldKeepConversionExceptionAndNestedCausePrivate,SubprocessExecutionSupportTest#shouldKeepNativePathOutOfDefaultHandlerException \
test > platform-evidence/maven.log 2>&1 || result=$?
tail -100 platform-evidence/maven.log
python scripts/contract_report.py \
@@ -63,6 +63,8 @@ jobs:
--suite protocol=io.github.easy4j.opencli.center.ws.OpenCliWsReverseAgentSessionTest \
--suite protocol=io.github.easy4j.opencli.center.ws.OpenCliWsCollectRequestsTest \
--suite process=io.github.easy4j.opencli.core.OpenCliProcessPrivacyTest \
+ --suite argv=io.github.easy4j.opencli.core.OpenCliArgSupportTest \
+ --suite process=io.github.easy4j.opencli.core.support.SubprocessExecutionSupportTest \
--output platform-evidence/report.json
exit "$result"
- name: Upload platform subprocess evidence
From f89c0ce4f2e6b832a7ae97b16c5244df99776b20 Mon Sep 17 00:00:00 2001
From: loong10k <20489781+loong10k@users.noreply.github.com>
Date: Thu, 19 Nov 2026 00:50:34 +0800
Subject: [PATCH 029/105] build: restore the Java 8 Maven Wrapper and align
version docs
---
.github/workflows/platform-contracts.yml | 7 ++++++
.mvn/wrapper/maven-wrapper.jar | Bin 0 -> 63093 bytes
.mvn/wrapper/maven-wrapper.properties | 2 +-
README.md | 29 ++++++++++++-----------
README.zh-CN.md | 29 ++++++++++++-----------
5 files changed, 38 insertions(+), 29 deletions(-)
create mode 100644 .mvn/wrapper/maven-wrapper.jar
diff --git a/.github/workflows/platform-contracts.yml b/.github/workflows/platform-contracts.yml
index 056ae5a..701606e 100644
--- a/.github/workflows/platform-contracts.yml
+++ b/.github/workflows/platform-contracts.yml
@@ -33,6 +33,13 @@ jobs:
if: runner.os == 'Windows'
with:
node-version: '22'
+ - name: Verify Maven Wrapper on macOS
+ if: runner.os == 'macOS'
+ run: ./mvnw -version
+ - name: Verify Maven Wrapper on Windows
+ if: runner.os == 'Windows'
+ shell: cmd
+ run: call mvnw.cmd -version
- name: Exercise real subprocess contracts
run: |
mkdir -p platform-evidence
diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar
new file mode 100644
index 0000000000000000000000000000000000000000..eebc3c18b4e0bce4a2a9e66be24c4a410f17a1fa
GIT binary patch
literal 63093
zcmb4q1CS^|ljh)!ZQHhO+qP}nwr$(CZNIVYnK!z(xZVBl_Wq0Q=!)p*{xT!8I=ia!
z%W8Qk;9rmc0N?-s#g^n+0RQEH_XFfH63%(B0aB>@2d
z{@(phn2dm|gs6y;GOdhgOw1JIAU(41YryBwSHQ0ib(b~Bz>vW8!pr$>OL`f>Ov>*b
z75QSw&ddOg>554cv7|de9+Yzpjo38tW
z+=G*`qP+Byt36BWMG$?m<<$dmG_e*g41GnCEzNIESyJF4IB2=^$1Fg3mFMg`8~9&w;Rxvp8L9uH(7dl
zZw2WpHXlNS;|=hS-%E4zL8#5&KGvlM0D%9mHcCqfiO4F6>}YB^ZH=P%zSgZfmMU3*
zmgX>9V4X%Z9EH{hSqOL7k|u?b)Z@2-){oQTM}9r?r1b<88@v5cl__PBxY}qseaN}Z
z9)Y^==o6uv%0aw!so*Tr<$gTkOLp0GKDd0p6#SHNEouh4f4*GXC{5{#@831)#ck8PeHF6=@-J_vHbDPFi)#C2vM8;cP2j$@ABZNo$W*wnuGnzy0Zll
z)m6)Le2YMd-^PTfR^llF(I^az_&Oz?L;^z7A7f90ZnPg*SD*&l4h9sb+5(cG1`-cb
zv9o_^ugyqppmDLe=DeHuCx89YV9e2dsKeci`g|d-l?|R@qHK#YmbL{!Y-Kv3^N
zu}Q5J;8o)ek+Oj6+l>H}ND@MJ?6e#CJAztYgo>*}<&1lKE#`QZN;UjTcHw^Dqq&ZF
zqr>C{vk0PC+k8HF`_Q#hOroWBAhV~DB(nGI<@uJ*f(!V>U%nnez0N?71<&aPtueh>!GxEzvgFJj?Rg0*v~vETqmYNDvF1V>7qTega!(Bbyp+C1af?E
zAybgKbCrYJT@llB{n(vjGXZ-E&}G;*k$^5VpM3CV-Lq@+6IXkQ0*3dt^*2a?eP!nr
z>?cmUku^D=rIqGe!}bJhGb{vQq1k%)e4N2-w1cFmUbXs1B4Q<@m$V5;waE*x`hy@ub9gqcSb*)rZkW&W
z9^zI3d2b>d&blJyYJ0e7-*DVf%I(PQkdFG@bH}s*Kz1vCOn?lFl^{|zL*yU}?_6*Y
zR904RAcWsD9;_Y)>c`1J;slpc>(k81$o0~8E?`~Re?F1pfMr*bp6G@f-n*aaGkb2u
zyX!DjTNKAWm3x|zDa_G0MXRbUVdKGe$QZXl3qcNxlWIDlW!C_NTT@9;A_%Jz7Rt#a
z3tW;blGb(!lRq&1Ru9KG;FVan=rHHWw988r;E-AGAx7+vGsNSK*IAn(ef=cg38f+d
z6?XeqW&CZ}Yyr5q-GBWSSP;of^5jJ^CmOs*(nRQ%KEBzoOh7^rHrd2I^eO63XGuS>
zcz7^b(VafXFx5p}`v9M+7iWq0Uj;x%I}3@iCXanVU2_rU9i7$E(?>lLRhy7EFB>Q^
zCiv(&*ib}npxOogmf{2?yZ}XGrDH_T5Ed}CX~weOc63%gwirvjTU;8C3wEzyt{Bq~KGzW99#qh-n_7s5O>9ef
zK@!Z9xgwXRJ$`B>x(bsQ#!E1m6D15>u?BfbC7fG%zhVxFdvoD-9q*r0%-!}6kGozd
zH3XZqMjl3z7ZnkQl|20@CU(APLpUfKu#p0OIdO~$W|QIrEv!2|s1vWU-)g&m3($yo
z9v@j5yVx)#m1@FHK~a`Sz!1j|_MaU-2uB0p2v!0bx?BNBh1dt1UsLvq(Jo@zk$UJ3
zLOL8v>-W4u#UgWxpRsq>&;rS0hVKGXB8<;dcG~^f4=vaVM2R=z8NG*CBw@cDgQ*6g
z63l;z3FeR6^`F(Y#PK7ElMwfa^U!{1_ypJdV{Rh8r%@-x9$0-49S98fTpW0gPMW
zr8-`pG#gr`pBJ)gve&MDhZ%=Gr#gE5ScM9!V&M0uwJUo)A;d%tmP1p}m5Z#V%!Y;*
zf8P88IgX`X?i<<-;->x*g&qRnw||1Ls@zm8S}?Ff*ku(>`5dubW%jONTrGHuEo~~x
zAHEks*my`IPEM0~EmZ+ql5c7JQ>@o0<$A)l*3phMV|s2;3(+IFPYiB45u#VyWnkPE
z1ua@2{f2z+gI{9hZ`l0`GWsJqb}dQSj2x%%u_&Jlh)N&~(j%n_=;TV~qCTa;qD05(
zbRGdJ4le!3BDW#x3AFI7kiF0YXf;ra^>Wqdki8jETq$y)C(SNYa1a}@3gGtgV75#H
zMP}-_9ltDytXYA^6|f140)E&U2<5g+Y4_#uH4-!l7{wuLR4HB@Z7|Ow+IzvSJdrN0
zLb{KVV&N^cmeE!YeSx6p`}(D?iO_LsZ}98loApkAQuQqviPv#@Mq7Qpex?e(y@xn;sqvELcwX2F}O)H
zlbB{$%~wbQRiFCoKId1OR%X5)uAiY3ZyoTxj5gnS;vLOCjy6&R`ZJ_C
z8mQl?kWe(`Ab68ep3^DLmNl9P$tAKMO%1ur5g6|T&cH{~)>)98eh->mOAdfCVv^vr
zD!nKFrjyu!90q6gL0V207&E>!E|5^}Fmrk11$&f;Klb3k;fK&6%N|JVkU_aq?rj*U
zNHN*-+(@2!1vRTy#xsFL06zoR(7>NprMr(0JIjJSb(*IqYLG|Fod3XaGYHo!GoAgE
zISSA^XFm$UC1j}^moL3|+a?_5ls0{AupX}*^wYX>dkCK{{!@N96tGMbPry2@$LVTSIFd7ab2XvnaklTa~du2kGyQK7-jy%2e{
z)R8Vp4A(YW>LC%3v{fmA5?hUBHX&TX5KC&5v0j1g0)!OiEj1I{2eGHi(!kG#hR0c6
z7@J*+Yfz+U^dW`V1eM6X%Z}YNZk?VI(~yg;LsA;Yg$w7Heqr-){^+-q>5(a7X$m+*
znBJ+n|B|p)H|-yFa1FDP7PDUpz2qu&jgyL?I1?ien_Y>l_sam&nD!ovp=%G2LY<*i
zSnKSZ{0@#+sGLYCu5ubb*Pjh@xU#0%yUuyr>#fV54-gp?=l~v-30DV0a5jL#&6OxP
z^cBrgT5pgg)Y`!o6$3`LC)uYzqxT1#^Bw&pOlTf7MyR-$b)|Aw^x7`2KA-CjBGuWE
z0@-)z;F;MHSQYfQ!XRJ|mElrA(q_`T^?2zXn;y(;GC=Ec-syoPmu1e~Vk;_MfM1{v
zECWPgWfm}7{j!HqREoZTxA=@yW+2Lh0q?7h;xmxTNWp+ZR3=}{;Z%eZokJ~1JfBwe
zh$9aYANA^#3;oU5@mCxh-p$C^$j*+TOJBEcR94rg=J!dCdbKaApI&XP|BZPspzrW`
zxfIz#FqH}`sSJj&lOl%w1%M1~MkFSo7i5F}^vChn$0bm8uV;sLPnTBhx98W=^F=Q_
zpU!U27ecf4XT5h{_fLl4+0KKnOV7y~7^?2*^#LsQ%l_Aa?6z-vSC59CQ_JzzAgCQG
z{|_$fit{Bu8`Cz5><|dInT#FFq7$b*%tA<<{3prq%t;BijWaAe0xnyBi)--JY%*u-
z1oXvsZc1sxyU3*l(^SK28izM5>4?Z}%l26)?Od9=2grP$Ek2JrsQ1czJ(6>zvv*nh#zFtWu^?{8W1IF>_#GKjTS6~Ft>=RZGfuPu=jRP*iEzMvmaBslg
znd_&wFTJPiBp9qo;1s3|)<*4=IcVD49wa!;{RXTd
zz%G{3%}dfe9N)k~>p!{&$?zNl;gM^KY(>YG#95wKh#dul?k6(v-5~vYGuH!HRA2!?
z4&lGP+~H46h7CHaahY`zSHGWO#sTbt?;L~B<}mJdw5cVlA6i+WAX$M>^ws1gQnB!H21jE>3aJX0R@bL?u#~z$cAf-nb9|xkg{jR?3$fr
zT(J;2+WJrn2x@;Y1DFTM&!wcvb_$7w<&p}ip+BY3y-0PKc#Q^~dXsD}%(Em{=40m41+>gbN@ZuaepCwYI94D5cP(UN~!
zAum}7=C6P@jtXM&23LqCaK39+l{x}J{vzfI`UbV5KoLH^
z`=?RXla{tt`ZesWmp`>g;O&+c#N~3ilrtX<9)kbA2)CDOeA3mGEvn-H*8eo_o-jGn
zQx(7-2$dCpj@%G>b}K8
zUh&Fmv&>Mrgg$sm+Pi?a+2i9^a>6Gf@L$@!pKsjr?mO?S$@vVT%Ej!2E?=fXON<;C
z8zKCuLg24+J&u2H+dnLQz7Um5N%RKi^A2#obC{5mVwPoh?FXfTJ_E|o-+sjVfbU70
zYEm-G;RCbHVTPfxYqnzH?fD_{sh!8{UfwMv4lZw=v>(xa0RJ&HA4+2l_y3!cSO0DQ
zz=FuiDgRB*eWn}!vRLr``#f?EMX;qU2M45rU;`6@j|QGEH+Dlr
z*aJznm&?SMjHOEAGbg|hpbKV?yILMAj?Fuh)YQlv>6o-M=CmR&mQu_^t+oC#FHrNO
zE2yC>4)DDQ`!4dO@G&b3|D3|=HHFg?97rgYCvBlpv!UATqy=PW
zntD^SrE)7{jC!hqBRkqEG{cQ~Yr!U9%M_+5dFg@_0=Oc(tHeS*L!+qBOx9f1
zqn$6jT)(OxCkA9^B0F<3MzvX!#>|3bN3~vt-$w6B6uXV;OrZgo3*-Qc1u_`tGTCPS
zI=QWgii;I{C`X)py~L31=79>=DqQB6HT;;|74AkQUiluwTUCGTXWp7gCErZe?IF!F
zmiLy3jN9dsM7t+XX@M%mRpBkz^s*Fb2=!^AzvR~+B_>}b)&*iAcK;qoP!(u`>!`Ph
z#u_V<0Gg3bnrE*^+&mqai+bfp50qCUyszr>*>V%kKZ%D<=4zHoRE6&Hd%mS|o#rV|
zjjDAeRVY3YLJAKwnyw|vQfiqMi7$?#ouBcMbb9~+`kzoT@zc19opjfID-JV2kucSdt3z9vQM+~@0;a#dnbuSq#HQ|R2
z-312_P~;BE;VwjdP!9k5%yDauk`$jtS)0)S;iA{^U)=
zx5<-dh(H30tXbLu(ZO%waP?g)N=F2rY05{*HfE>`QX8-c*fI;$A3v0$EOls2=sE0E
zYE4&*1GVOEA~3(c+5BT2B15q>&p#r!ZvmpG>Hw>U(C)+}%E~aLT~9l|5p?avs+ny!
zM_S=WL=g$pLswr%LGF>&0x*ej5;9R~q;3k`l&&PNYOu!*c>jpAAN0Oyvy97TUD;wi
z>Z7NRls#e7I%5B`K~C9Rpui|(6M%;)p0{Rg5mYfKm=ZI$jHcyBo+{N
zozfy*#&Tkh!W#L)@xxfpu7(b02=1N;girMzwDvtqu_;Z&l*UV!D0WN<>$=@#0yJ5!
z3Zgr_?a1JnbuKDDcIX5F^H`&QbWnPY?BWq*hnHd?#eIB6&Z?E*RK{?e0*jgi^W{fd
zFcjk}(>uj2&fgTp9VemH;sx97($S55awy0Gb$E){O=EjYrW@U!lGGc_<)h)Ol5P4V
zqt!=<${CJs=qYovc7}`Satdyvq!LVP&a;IGI8J<~hT4S3Z?7t9RZ?nQuL%f;WYg=m
z>AG>2UPHG^TU2MYCMY?%
z-J)XbS|>T(^g|tzpl-(dCxjVBY@m_5KF9&59_O7BFA;46+U;EhEBYO+@2JAw=^ID~
zIrX23vUpbyeS46}VHoQS*qvdUr5quvb=vx9u7|32FAOhLdp*|X$ZuhDj0|D&?|#M?
zv!VN-AglZ)D|X`g$OWeRhJm+xmT0$rIl16Nz2bvUXR}XbUktOx1YzO$d4`>iw8spl
zHJ!fVeYpEvkf()uDxUiWG|
z&}#R8Ab)?Rt6q-^=z7-P%{sw?#1f#bFx!B_=0{cWj3-*5d(jIj8^H;E8ZCu~hL5OgdiYL^^guE7#K
zK(s}Xhf{`k@%akU+=INaaXLcQdI#2kf2`H<-yx6)QNiOq{M_31?tcDjz2iR%1>0dy
zb>ct(078EYJB>O;w`~dDw48yEWTpm9_%GTA?
zHrK<{%mB`u2
zhk@AmyxoJm#pL&Pns56oefGpE4KccDoKRKw+Ll_U3(x@-M=0@-afhx&x1Sc3t?I*Z
zVa#QEW4t4M3>I_*xlq5!Rt?UR-~vfzD|pDZk@|SDtT#*x-B!ny#TvTpH%Y~bRmfRr9J*n~RjL_L>_;isBlMD)yq(7eXHZs$v=t2D
zNkyuDc$zl_<=0K?yxp5Cf3C3vi--K_CfiE_lWA5!;N{K8&T{?7gQ=v6zr5F$9vVMT5!~MZCm%HJK
zZD++%?Cy=#yZ;8isms=@IN77j-vK
z%w+U`<8t?JTq^y~;!?@O$=Sq4-qG%FVbIya#Od#qyN7^_v$=__vxSj?v)#Wh`f8M{
ztdInddDvvS9I|+|SsHpZw=|Q~n_^TI2n8h&f|a3G0-u(cagtJu*`{Uxys1UbgM#?^
z^GS9$X?)}(VA-R&-fVNcW;eN+`hNd;0q$qa-4xd!7i5evh=yMUQgIW}TE<+oiO@Ok
z@{(-cQtYUDC^}<)wyZy818yK%`5YA}H?h(I>8|F%aBTLgUtEAWx2hv`&Ic!=#L3|Upk#J=e8>;xI=q8
zvCoc;DcLb7oib%+j_f53d}QDP{6%zLf#rRY31=dE2suVg@K4LFl!`^89)_m7FuAsN
z82!g>tA@LvI`%NP=^J60el9`m8)Fdt98;PYZ#6nC_Q0P(0if46E<}<(!+^eXT!7bv
zLxu=$NQZk&vl-17t}8g%&M1e|%B1syKLob8`!}aXoMBV`LZv)|=$+&C-hw&T3UZhU
zU<}VrxJV6j7q?VPz{9=L&Ea7R8VrM7>XF4rpQ(50bR&+zLw5fdpn+h>OuaAw0Jzuy
z0QCQ(0R8u2Qv*UDX)WVBm&R(;P>>(UT0j!H_ANP3h?WbCm3?4XjmF3be_jA{3&=wh
zBL={&?VQwNk(DQHNB63Ai^<}ZvLMEO5NIdr%JtT($*k+u$2iW`ZOgQejVX~tOBM(s
z(__ug_vb#e&hNH_3cxkO2=d~WCXE+q!Rga-bwc`*9ERyZbIqw^XbyT}k%S$6vDq{{
zkhwhkay~zbx|1MZ30Y$&M-n=R@1Qsb(0~_{>1c;ues76OAp$|QV!lN?U=_%w>QU2L
z`YM!$S)I$~w5I1~J&5g*Bx}-QPP7T^rBf)syM2PrVgu8ObewU$=#ZuakG6yUVEv%m#b-6BJ#+u9~^N8Y~~PJXG*pu=J)N|@>Di%mJ=Xr{?gw2SDU&1hL=jm?}U
zF+51AG?QCEYn5!ZLR?v6bi;0Pd1;aft_NtLG@F}?Wc7op87|o)s&M}j^ccFQ0JnZf
z(P@qQrQ!^}P0!50?QzB5=x5#TR<5_nSW7?vgHgN!{g@n?Q=(JUGjVh@zOD<>2IZ_B
z_eS8n4_on`0~B$&kZnlWu9d&BL})}(%A`TWkj@|%d&Ir$9Ms#XHsphUK(z9KdnA`z
ziEhT|5k{v&;*`u9eKBi2w?B|l{@RSI8M1SxGGAr@_ky@TH3!8k>3_}|Bh}a3yn0Zu
zClGMG0@W#0jzhaWz>l=mF___!VPaEO5YJA8^NJUeN99xDn7OijUlx(QX9LC
z7#Cv-!*iQEX%=3jK0wlL=k3jm0k;p1t6;A@#Lz9XcY?CdZayfkj6Ept=`PA(G7)`g#KaTW0Vz-;z@R>n7}dX*|~FG?p$%D5{;Ci%|sf)qx7CR
zxp;rDk|(RmIASv+$Lnl-VdRpul;iq&tWf&c7K(RX=km2pcPrMT6UsB-J>aLQ%1mEy^i}!{wec{bCnzns{U0DT$nQ)D3C8FmT
zIf}t(G`*$SmQbZ~4(b}_)4G2`%d}1Ts`rWB%Ka@d&9VigKq*SpGo)PDv7j^6t3gn+a_chA)0reE|H
z?o_(@KZ@Du?&PIpJa(m5>+q>_)?%VCQSS&P<}?-yl~}CCo)v4a1EtGXC^s?)%fSz3)2_RkN*>?%B#^cH&L{*
zvVuz@t2dBO@oo(B`XyosnI}QzdRW3$4nBSIlp~pEDK&A<%2lwwqdk>pMov
zlqVY_&Z(=cJM#Diz7GZMiZ#}}nn=Hr6lgd4n^R1XA6j|0cDmr7em}}LI+&jryA(zN
z7*uDAQErnQP~J&>QWeXh6Kei{?yQd5^K7h47vcO%Ts{rOvoui!|RR?0P^Ux#1f+=nHXoSYS
zZZ6v(Rv?ZT2B5B%3~B7j|EA$}dOvh8j9
zD%MYjY`&JZ4iBWNTvT{$8!qLBOu(T*4~ElP%h$`+MeBsEl!jTPtx-57wVO0owm4*r
zz(zzwhsPftBZ_g9n(lDhxpLNXW16j}UfVxfRJss^3#AdR1DE>tn~kT=t#EK{)MZb9
z5;_f)mW#sM`&U!wd{FeTfxOVmo004EN9_%6+705Q=p;spp^-Xs5{ _ohw3Ut=#j
ziRPk4+qkx*KIU>vvzGQdZWpwPIR5j`dg)eL0wRI3G#WG
zMR#;<#FC{>H|