This is an automated email from the ASF dual-hosted git repository.
JackieTien97 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iotdb.git
The following commit(s) were added to refs/heads/master by this push:
new 92229158db8 Use per-thread JDBC connections in AINode concurrent
forecast IT
92229158db8 is described below
commit 92229158db8a5b45cb95bb5e7b8e35ac012afeac
Author: Jackie Tien <[email protected]>
AuthorDate: Mon Nov 23 17:29:09 2026 +0800
Use per-thread JDBC connections in AINode concurrent forecast IT
---
.../cluster/env/IntegrationTestEnvMessages.java | 24 +
.../cluster/env/IntegrationTestEnvMessages.java | 24 +
.../iotdb/it/env/cluster/env/AbstractEnv.java | 77 ++-
.../iotdb/it/env/cluster/node/AINodeWrapper.java | 327 +++++++++++--
.../iotdb/it/env/remote/env/RemoteServerEnv.java | 16 +-
.../java/org/apache/iotdb/itbase/env/BaseEnv.java | 20 +
.../iotdb/ainode/it/AINodeSharedClusterIT.java | 204 +++++++-
.../apache/iotdb/ainode/utils/AINodeTestUtils.java | 523 ++++++++++++++++++---
iotdb-core/ainode/iotdb/ainode/core/rpc/service.py | 24 +-
9 files changed, 1118 insertions(+), 121 deletions(-)
diff --git
a/integration-test/src/main/i18n/en/org/apache/iotdb/it/env/cluster/env/IntegrationTestEnvMessages.java
b/integration-test/src/main/i18n/en/org/apache/iotdb/it/env/cluster/env/IntegrationTestEnvMessages.java
index b7a7c51d86c..b42798bd731 100644
---
a/integration-test/src/main/i18n/en/org/apache/iotdb/it/env/cluster/env/IntegrationTestEnvMessages.java
+++
b/integration-test/src/main/i18n/en/org/apache/iotdb/it/env/cluster/env/IntegrationTestEnvMessages.java
@@ -32,4 +32,28 @@ public final class IntegrationTestEnvMessages {
public static final String
EXCEPTION_FAILED_TO_GET_CONNECTION_TO_CONFIGNODE_ARG_DF03F50F =
"Failed to get connection to ConfigNode %s";
+
+ public static final String
+
LOG_NODE_ARG_S_STOP_SCRIPT_DID_NOT_EXIT_WITHIN_ARG_MS_KILLING_STOP_SCRIPT_9393F866
=
+ "Node {}'s stop script did not exit within {} ms, killing stop
script";
+
+ public static final String
LOG_NODE_ARG_S_STOP_SCRIPT_EXITED_WITH_CODE_ARG_E5C267CF =
+ "Node {}'s stop script exited with code {}";
+
+ public static final String
+
LOG_FAILED_TO_RUN_STOP_SCRIPT_FOR_NODE_ARG_FALLING_BACK_TO_DIRECT_PROCESS_TERMINATION_13E3FD59
=
+ "Failed to run stop script for node {}, falling back to direct
process termination";
+
+ public static final String
+
LOG_NODE_ARG_DID_NOT_EXIT_WITHIN_ARG_MS_FORCIBLY_TERMINATING_PROCESS_TREE_65FA74DB
=
+ "Node {} did not exit within {} ms, forcibly terminating process
tree";
+
+ public static final String
LOG_FAILED_TO_CONFIRM_EXIT_OF_NODE_ARG_SURVIVING_PIDS_ARG_CBF3E211 =
+ "Failed to confirm exit of node {} (surviving PIDs: {})";
+
+ public static final String LOG_IN_TEST_ARG_ARG_STOPPED_57DB922B = "In test
{} {} stopped.";
+
+ public static final String
+
LOG_NODE_ARG_IS_STILL_ALIVE_AFTER_STOPFORCIBLY_SKIPPING_DIRECTORY_CLEANUP_AND_LOCK_FILE_REMOVAL_55F75817
=
+ "Node {} is still alive after stopForcibly; skipping directory
cleanup and lock file removal";
}
diff --git
a/integration-test/src/main/i18n/zh/org/apache/iotdb/it/env/cluster/env/IntegrationTestEnvMessages.java
b/integration-test/src/main/i18n/zh/org/apache/iotdb/it/env/cluster/env/IntegrationTestEnvMessages.java
index 5909e594dfe..06e508b1859 100644
---
a/integration-test/src/main/i18n/zh/org/apache/iotdb/it/env/cluster/env/IntegrationTestEnvMessages.java
+++
b/integration-test/src/main/i18n/zh/org/apache/iotdb/it/env/cluster/env/IntegrationTestEnvMessages.java
@@ -32,4 +32,28 @@ public final class IntegrationTestEnvMessages {
public static final String
EXCEPTION_FAILED_TO_GET_CONNECTION_TO_CONFIGNODE_ARG_DF03F50F =
"无法连接 ConfigNode %s";
+
+ public static final String
+
LOG_NODE_ARG_S_STOP_SCRIPT_DID_NOT_EXIT_WITHIN_ARG_MS_KILLING_STOP_SCRIPT_9393F866
=
+ "节点 {} 的停止脚本在 {} ms 内未退出,正在强制终止停止脚本";
+
+ public static final String
LOG_NODE_ARG_S_STOP_SCRIPT_EXITED_WITH_CODE_ARG_E5C267CF =
+ "节点 {} 的停止脚本退出,退出码为 {}";
+
+ public static final String
+
LOG_FAILED_TO_RUN_STOP_SCRIPT_FOR_NODE_ARG_FALLING_BACK_TO_DIRECT_PROCESS_TERMINATION_13E3FD59
=
+ "执行节点 {} 的停止脚本失败,回退到直接终止进程";
+
+ public static final String
+
LOG_NODE_ARG_DID_NOT_EXIT_WITHIN_ARG_MS_FORCIBLY_TERMINATING_PROCESS_TREE_65FA74DB
=
+ "节点 {} 在 {} ms 内未退出,正在强制终止进程树";
+
+ public static final String
LOG_FAILED_TO_CONFIRM_EXIT_OF_NODE_ARG_SURVIVING_PIDS_ARG_CBF3E211 =
+ "无法确认节点 {} 已退出(仍在运行的 PID:{})";
+
+ public static final String LOG_IN_TEST_ARG_ARG_STOPPED_57DB922B = "在测试 {}
中,{} 已停止。";
+
+ public static final String
+
LOG_NODE_ARG_IS_STILL_ALIVE_AFTER_STOPFORCIBLY_SKIPPING_DIRECTORY_CLEANUP_AND_LOCK_FILE_REMOVAL_55F75817
=
+ "节点 {} 在 stopForcibly 后仍在运行,跳过目录清理和锁文件删除";
}
diff --git
a/integration-test/src/main/java/org/apache/iotdb/it/env/cluster/env/AbstractEnv.java
b/integration-test/src/main/java/org/apache/iotdb/it/env/cluster/env/AbstractEnv.java
index da90c669994..818ea4a6866 100644
---
a/integration-test/src/main/java/org/apache/iotdb/it/env/cluster/env/AbstractEnv.java
+++
b/integration-test/src/main/java/org/apache/iotdb/it/env/cluster/env/AbstractEnv.java
@@ -697,6 +697,13 @@ public abstract class AbstractEnv implements BaseEnv {
nodeWrapper -> logger.info("You can find logs at {}",
nodeWrapper.getLogDirPath()));
for (final AbstractNodeWrapper nodeWrapper : allNodeWrappers) {
nodeWrapper.stopForcibly();
+ if (nodeWrapper.isAlive()) {
+ logger.error(
+ IntegrationTestEnvMessages
+
.LOG_NODE_ARG_IS_STILL_ALIVE_AFTER_STOPFORCIBLY_SKIPPING_DIRECTORY_CLEANUP_AND_LOCK_FILE_REMOVAL_55F75817,
+ nodeWrapper.getId());
+ continue;
+ }
nodeWrapper.destroyDir();
final String lockPath = EnvUtils.getLockFilePath(nodeWrapper.getPort());
try {
@@ -888,12 +895,24 @@ public abstract class AbstractEnv implements BaseEnv {
final String password,
final String sqlDialect)
throws SQLException {
+ return getConnection(version, username, password, sqlDialect,
NODE_NETWORK_TIMEOUT_MS);
+ }
+
+ @Override
+ public Connection getConnection(
+ final Constant.Version version,
+ final String username,
+ final String password,
+ final String sqlDialect,
+ final int networkTimeoutMs)
+ throws SQLException {
return System.getProperty("ReadAndVerifyWithMultiNode",
"true").equalsIgnoreCase("true")
? new ClusterTestConnection(
- getWriteConnection(version, username, password, sqlDialect),
- getReadConnections(version, username, password, sqlDialect),
+ getWriteConnection(version, username, password, sqlDialect,
networkTimeoutMs),
+ getReadConnections(version, username, password, sqlDialect,
networkTimeoutMs),
this)
- : getWriteConnection(version, username, password,
sqlDialect).getUnderlyingConnection();
+ : getWriteConnection(version, username, password, sqlDialect,
networkTimeoutMs)
+ .getUnderlyingConnection();
}
@Override
@@ -1053,8 +1072,18 @@ public abstract class AbstractEnv implements BaseEnv {
protected NodeConnection getWriteConnection(
Constant.Version version, String username, String password, String
sqlDialect)
throws SQLException {
+ return getWriteConnection(version, username, password, sqlDialect,
NODE_NETWORK_TIMEOUT_MS);
+ }
+
+ protected NodeConnection getWriteConnection(
+ Constant.Version version,
+ String username,
+ String password,
+ String sqlDialect,
+ int networkTimeoutMs)
+ throws SQLException {
return getWriteConnectionFromDataNodeList(
- this.dataNodeWrapperList, version, username, password, sqlDialect);
+ this.dataNodeWrapperList, version, username, password, sqlDialect,
networkTimeoutMs);
}
protected NodeConnection getWriteConnectionWithSpecifiedDataNode(
@@ -1064,13 +1093,25 @@ public abstract class AbstractEnv implements BaseEnv {
final String password,
final String sqlDialect)
throws SQLException {
+ return getWriteConnectionWithSpecifiedDataNode(
+ dataNode, version, username, password, sqlDialect,
NODE_NETWORK_TIMEOUT_MS);
+ }
+
+ protected NodeConnection getWriteConnectionWithSpecifiedDataNode(
+ final DataNodeWrapper dataNode,
+ final Constant.Version version,
+ final String username,
+ final String password,
+ final String sqlDialect,
+ final int networkTimeoutMs)
+ throws SQLException {
final String endpoint =
UrlUtils.formatTEndPointIpv4AndIpv6Url(dataNode.getIp(),
dataNode.getPort());
final Connection writeConnection =
DriverManager.getConnection(
Config.IOTDB_URL_PREFIX
+ endpoint
- + getParam(version, NODE_NETWORK_TIMEOUT_MS, ZERO_TIME_ZONE),
+ + getParam(version, networkTimeoutMs, ZERO_TIME_ZONE),
constructConnectionProperties(username, password, sqlDialect));
return new NodeConnection(
endpoint,
@@ -1086,13 +1127,25 @@ public abstract class AbstractEnv implements BaseEnv {
final String password,
final String sqlDialect)
throws SQLException {
+ return getWriteConnectionFromDataNodeList(
+ dataNodeList, version, username, password, sqlDialect,
NODE_NETWORK_TIMEOUT_MS);
+ }
+
+ protected NodeConnection getWriteConnectionFromDataNodeList(
+ final List<DataNodeWrapper> dataNodeList,
+ final Constant.Version version,
+ final String username,
+ final String password,
+ final String sqlDialect,
+ final int networkTimeoutMs)
+ throws SQLException {
final List<DataNodeWrapper> dataNodeWrapperListCopy = new
ArrayList<>(dataNodeList);
Collections.shuffle(dataNodeWrapperListCopy);
SQLException lastException = null;
for (final DataNodeWrapper dataNode : dataNodeWrapperListCopy) {
try {
return getWriteConnectionWithSpecifiedDataNode(
- dataNode, version, username, password, sqlDialect);
+ dataNode, version, username, password, sqlDialect,
networkTimeoutMs);
} catch (final SQLException e) {
lastException = e;
}
@@ -1109,6 +1162,16 @@ public abstract class AbstractEnv implements BaseEnv {
final String password,
final String sqlDialect)
throws SQLException {
+ return getReadConnections(version, username, password, sqlDialect,
NODE_NETWORK_TIMEOUT_MS);
+ }
+
+ protected List<NodeConnection> getReadConnections(
+ final Constant.Version version,
+ final String username,
+ final String password,
+ final String sqlDialect,
+ final int networkTimeoutMs)
+ throws SQLException {
final List<String> endpoints = new ArrayList<>();
final ParallelRequestDelegate<NodeConnection> readConnRequestDelegate =
new ParallelRequestDelegate<>(endpoints, NODE_START_TIMEOUT, this);
@@ -1127,7 +1190,7 @@ public abstract class AbstractEnv implements BaseEnv {
DriverManager.getConnection(
Config.IOTDB_URL_PREFIX
+ endpoint
- + getParam(version, NODE_NETWORK_TIMEOUT_MS,
ZERO_TIME_ZONE),
+ + getParam(version, networkTimeoutMs,
ZERO_TIME_ZONE),
constructConnectionProperties(username,
password, sqlDialect))));
});
return readConnRequestDelegate.requestAll();
diff --git
a/integration-test/src/main/java/org/apache/iotdb/it/env/cluster/node/AINodeWrapper.java
b/integration-test/src/main/java/org/apache/iotdb/it/env/cluster/node/AINodeWrapper.java
index 91faeae8eee..611894cc69b 100644
---
a/integration-test/src/main/java/org/apache/iotdb/it/env/cluster/node/AINodeWrapper.java
+++
b/integration-test/src/main/java/org/apache/iotdb/it/env/cluster/node/AINodeWrapper.java
@@ -20,6 +20,7 @@
package org.apache.iotdb.it.env.cluster.node;
import org.apache.iotdb.it.env.cluster.config.MppJVMConfig;
+import org.apache.iotdb.it.env.cluster.env.IntegrationTestEnvMessages;
import org.apache.iotdb.it.framework.IoTDBTestLogger;
import org.apache.tsfile.external.commons.io.file.PathUtils;
@@ -36,9 +37,16 @@ import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
import static org.apache.iotdb.it.env.cluster.ClusterConstant.AI_NODE_NAME;
@@ -64,6 +72,14 @@ public class AINodeWrapper extends AbstractNodeWrapper {
public static final String BUILT_IN_MODEL_PATH =
"data/ainode/models/builtin";
public static final String CACHE_BUILT_IN_MODEL_PATH = "/data/ainode/models";
+ private static final long GRACEFUL_STOP_TIMEOUT_MILLIS =
TimeUnit.SECONDS.toMillis(20);
+ private static final long FORCE_STOP_TIMEOUT_MILLIS =
TimeUnit.SECONDS.toMillis(10);
+ private static final long STOP_SCRIPT_TIMEOUT_MILLIS =
TimeUnit.SECONDS.toMillis(5);
+ private static final long FORCE_STOP_SCRIPT_TIMEOUT_MILLIS =
TimeUnit.SECONDS.toMillis(5);
+ private static final long PROCESS_EXIT_POLL_INTERVAL_MILLIS = 100L;
+
+ private final Set<ProcessHandle> survivingProcessHandles =
ConcurrentHashMap.newKeySet();
+
private void replaceAttribute(String[] keys, String[] values, String
filePath) {
Properties props = new Properties();
try (FileInputStream in = new FileInputStream(filePath)) {
@@ -190,6 +206,7 @@ public class AINodeWrapper extends AbstractNodeWrapper {
new ProcessBuilder(startCommand)
.redirectOutput(ProcessBuilder.Redirect.appendTo(stdoutFile))
.redirectError(ProcessBuilder.Redirect.appendTo(stdoutFile));
+ this.survivingProcessHandles.clear();
this.instance = processBuilder.start();
logger.info("In test {} {} started.", getTestLogDirName(), getId());
} catch (Exception e) {
@@ -199,44 +216,300 @@ public class AINodeWrapper extends AbstractNodeWrapper {
@Override
public void stop() {
- if (this.instance == null) {
+ stop(GRACEFUL_STOP_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
+ }
+
+ @Override
+ public void stop(final long timeout, final TimeUnit unit) {
+ stopAndConfirmExit(unit.toMillis(timeout), FORCE_STOP_TIMEOUT_MILLIS);
+ }
+
+ @Override
+ public void stopForcibly() {
+ stop();
+ }
+
+ @Override
+ public boolean isAlive() {
+ if (super.isAlive()) {
+ return true;
+ }
+ return survivingProcessHandles.stream().anyMatch(ProcessHandle::isAlive);
+ }
+
+ public List<Long> getSurvivingPids() {
+ Set<Long> pids = new LinkedHashSet<>();
+ Process process = this.instance;
+ if (process != null && process.isAlive()) {
+ pids.add(process.pid());
+ }
+ for (ProcessHandle handle : survivingProcessHandles) {
+ if (handle.isAlive()) {
+ pids.add(handle.pid());
+ }
+ }
+ return new ArrayList<>(pids);
+ }
+
+ protected boolean stopAndConfirmExit(
+ final long graceTimeoutMillis, final long forceTimeoutMillis) {
+ final Process process = this.instance;
+ if (process == null && survivingProcessHandles.isEmpty()) {
+ return true;
+ }
+
+ final Set<ProcessHandle> trackedHandles = new
LinkedHashSet<>(survivingProcessHandles);
+ refreshTrackedHandles(process, trackedHandles);
+ if (!hasAliveProcesses(process, trackedHandles)) {
+ survivingProcessHandles.clear();
+ logger.info(
+ IntegrationTestEnvMessages.LOG_IN_TEST_ARG_ARG_STOPPED_57DB922B,
+ getTestLogDirName(),
+ getId());
+ return true;
+ }
+
+ final AtomicBoolean interruptedFlag = new
AtomicBoolean(Thread.interrupted());
+ try {
+ final long normalizedGraceMillis = Math.max(0L, graceTimeoutMillis);
+ final long graceDeadlineNanos =
+ System.nanoTime() +
TimeUnit.MILLISECONDS.toNanos(normalizedGraceMillis);
+
+ if (normalizedGraceMillis > 0L) {
+ final long stopScriptTimeoutMillis =
+ Math.min(remainingMillis(graceDeadlineNanos),
STOP_SCRIPT_TIMEOUT_MILLIS);
+ runStopScript(stopScriptTimeoutMillis, interruptedFlag);
+ refreshTrackedHandles(process, trackedHandles);
+
+ if (process != null && process.isAlive()) {
+ process.destroy();
+ }
+ final Set<ProcessHandle> gracefullySignalled = new HashSet<>();
+ while (hasAliveProcesses(process, trackedHandles)) {
+ final long remainingGraceMillis =
remainingMillis(graceDeadlineNanos);
+ if (remainingGraceMillis <= 0L) {
+ break;
+ }
+ refreshTrackedHandles(process, trackedHandles);
+ if (process == null || !process.isAlive()) {
+ for (ProcessHandle handle : trackedHandles) {
+ if (handle.isAlive() && gracefullySignalled.add(handle)) {
+ handle.destroy();
+ }
+ }
+ }
+ waitForAnyProgress(
+ process,
+ trackedHandles,
+ Math.min(PROCESS_EXIT_POLL_INTERVAL_MILLIS,
remainingGraceMillis),
+ interruptedFlag);
+ }
+ }
+
+ refreshTrackedHandles(process, trackedHandles);
+ if (hasAliveProcesses(process, trackedHandles)) {
+ logger.warn(
+ IntegrationTestEnvMessages
+
.LOG_NODE_ARG_DID_NOT_EXIT_WITHIN_ARG_MS_FORCIBLY_TERMINATING_PROCESS_TREE_65FA74DB,
+ getId(),
+ normalizedGraceMillis);
+ final Set<ProcessHandle> forciblySignalled = new HashSet<>();
+ if (process != null && process.isAlive()) {
+ process.destroyForcibly();
+ forciblySignalled.add(process.toHandle());
+ }
+ for (ProcessHandle handle : new ArrayList<>(trackedHandles)) {
+ if (handle.isAlive() && forciblySignalled.add(handle)) {
+ handle.destroyForcibly();
+ }
+ }
+
+ final long forceDeadlineNanos =
+ System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(Math.max(0L,
forceTimeoutMillis));
+ while (hasAliveProcesses(process, trackedHandles)) {
+ final long remainingForceMillis =
remainingMillis(forceDeadlineNanos);
+ if (remainingForceMillis <= 0L) {
+ break;
+ }
+ refreshTrackedHandles(process, trackedHandles);
+ for (ProcessHandle handle : new ArrayList<>(trackedHandles)) {
+ if (handle.isAlive() && forciblySignalled.add(handle)) {
+ handle.destroyForcibly();
+ }
+ }
+ waitForAnyProgress(
+ process,
+ trackedHandles,
+ Math.min(PROCESS_EXIT_POLL_INTERVAL_MILLIS,
remainingForceMillis),
+ interruptedFlag);
+ }
+ }
+
+ refreshTrackedHandles(process, trackedHandles);
+ final Set<ProcessHandle> stillAlive = new LinkedHashSet<>();
+ if (process != null && process.isAlive()) {
+ stillAlive.add(process.toHandle());
+ }
+ for (ProcessHandle handle : trackedHandles) {
+ if (handle.isAlive()) {
+ stillAlive.add(handle);
+ }
+ }
+ survivingProcessHandles.addAll(stillAlive);
+ survivingProcessHandles.retainAll(stillAlive);
+
+ if (stillAlive.isEmpty() && (process == null || !process.isAlive())) {
+ logger.info(
+ IntegrationTestEnvMessages.LOG_IN_TEST_ARG_ARG_STOPPED_57DB922B,
+ getTestLogDirName(),
+ getId());
+ return true;
+ }
+
+ logger.error(
+ IntegrationTestEnvMessages
+
.LOG_FAILED_TO_CONFIRM_EXIT_OF_NODE_ARG_SURVIVING_PIDS_ARG_CBF3E211,
+ getId(),
+ getSurvivingPids());
+ return false;
+ } finally {
+ if (interruptedFlag.get()) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
+
+ private void runStopScript(final long timeoutMillis, final AtomicBoolean
interruptedFlag) {
+ if (timeoutMillis <= 0L) {
return;
}
+ final File stdoutFile = new File(getLogPath());
+ final File parentDir = stdoutFile.getParentFile();
+ if (parentDir != null && !parentDir.exists()) {
+ parentDir.mkdirs();
+ }
+ final String filePrefix = getNodePath();
+ final List<String> stopCommand = new ArrayList<>();
+ stopCommand.add(SHELL_COMMAND);
+ stopCommand.add(filePrefix + File.separator + SCRIPT_PATH + File.separator
+ STOP_SCRIPT_FILE);
+ final ProcessBuilder processBuilder =
+ new ProcessBuilder(stopCommand)
+ .redirectOutput(ProcessBuilder.Redirect.appendTo(stdoutFile))
+ .redirectError(ProcessBuilder.Redirect.appendTo(stdoutFile));
try {
- // stop AINode
- File stdoutFile = new File(getLogPath());
- String filePrefix = getNodePath();
- List<String> stopCommand = new ArrayList<>();
- stopCommand.add(SHELL_COMMAND);
- stopCommand.add(
- filePrefix + File.separator + SCRIPT_PATH + File.separator +
STOP_SCRIPT_FILE);
- ProcessBuilder processBuilder =
- new ProcessBuilder(stopCommand)
- .redirectOutput(ProcessBuilder.Redirect.appendTo(stdoutFile))
- .redirectError(ProcessBuilder.Redirect.appendTo(stdoutFile));
- Process stopProcess = processBuilder.inheritIO().start();
- if (!stopProcess.waitFor(20, TimeUnit.SECONDS)) {
- logger.warn("Node {} does not exit within 20s, killing it", getId());
- if (!this.instance.destroyForcibly().waitFor(10, TimeUnit.SECONDS)) {
- logger.error("Cannot forcibly stop node {}", getId());
+ final Process stopProcess = processBuilder.start();
+ if (!waitForProcessUninterruptibly(stopProcess, timeoutMillis,
interruptedFlag)) {
+ logger.warn(
+ IntegrationTestEnvMessages
+
.LOG_NODE_ARG_S_STOP_SCRIPT_DID_NOT_EXIT_WITHIN_ARG_MS_KILLING_STOP_SCRIPT_9393F866,
+ getId(),
+ timeoutMillis);
+ try (Stream<ProcessHandle> descendants =
stopProcess.toHandle().descendants()) {
+ descendants.forEach(ProcessHandle::destroyForcibly);
}
+ stopProcess.destroyForcibly();
+ waitForProcessUninterruptibly(
+ stopProcess, FORCE_STOP_SCRIPT_TIMEOUT_MILLIS, interruptedFlag);
+ return;
}
- int exitCode = stopProcess.exitValue();
+ final int exitCode = stopProcess.exitValue();
if (exitCode != 0) {
- logger.warn("Node {}'s stop script exited with code {}", getId(),
exitCode);
+ logger.warn(
+
IntegrationTestEnvMessages.LOG_NODE_ARG_S_STOP_SCRIPT_EXITED_WITH_CODE_ARG_E5C267CF,
+ getId(),
+ exitCode);
}
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- logger.error("Waiting node to shutdown error.", e);
} catch (IOException e) {
- logger.error("Waiting node to shutdown error.", e);
+ logger.warn(
+ IntegrationTestEnvMessages
+
.LOG_FAILED_TO_RUN_STOP_SCRIPT_FOR_NODE_ARG_FALLING_BACK_TO_DIRECT_PROCESS_TERMINATION_13E3FD59,
+ getId(),
+ e);
}
- logger.info("In test {} {} stopped.", getTestLogDirName(), getId());
}
- @Override
- public void stopForcibly() {
- this.stop();
+ private static void refreshTrackedHandles(
+ final Process process, final Set<ProcessHandle> trackedHandles) {
+ if (process != null) {
+ trackedHandles.add(process.toHandle());
+ }
+ for (ProcessHandle handle : new ArrayList<>(trackedHandles)) {
+ if (handle.isAlive()) {
+ try (Stream<ProcessHandle> descendants = handle.descendants()) {
+ descendants.forEach(trackedHandles::add);
+ }
+ }
+ }
+ }
+
+ private static boolean hasAliveProcesses(
+ final Process process, final Set<ProcessHandle> trackedHandles) {
+ if (process != null && process.isAlive()) {
+ return true;
+ }
+ for (ProcessHandle handle : trackedHandles) {
+ if (handle.isAlive()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static void waitForAnyProgress(
+ final Process process,
+ final Set<ProcessHandle> trackedHandles,
+ final long waitMillis,
+ final AtomicBoolean interruptedFlag) {
+ if (waitMillis <= 0L) {
+ return;
+ }
+ try {
+ if (process != null && process.isAlive()) {
+ process.waitFor(waitMillis, TimeUnit.MILLISECONDS);
+ return;
+ }
+ for (ProcessHandle handle : trackedHandles) {
+ if (handle.isAlive()) {
+ try {
+ handle.onExit().get(waitMillis, TimeUnit.MILLISECONDS);
+ } catch (TimeoutException | ExecutionException ignored) {
+ // Re-checked by caller loop.
+ }
+ return;
+ }
+ }
+ } catch (InterruptedException e) {
+ interruptedFlag.set(true);
+ }
+ }
+
+ private static boolean waitForProcessUninterruptibly(
+ final Process process, final long timeoutMillis, final AtomicBoolean
interruptedFlag) {
+ final long deadlineNanos =
+ System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(Math.max(0L,
timeoutMillis));
+ while (process.isAlive()) {
+ final long remaining = remainingMillis(deadlineNanos);
+ if (remaining <= 0L) {
+ return !process.isAlive();
+ }
+ try {
+ if (process.waitFor(remaining, TimeUnit.MILLISECONDS)) {
+ return true;
+ }
+ } catch (InterruptedException e) {
+ interruptedFlag.set(true);
+ }
+ }
+ return true;
+ }
+
+ private static long remainingMillis(final long deadlineNanos) {
+ final long remainingNanos = deadlineNanos - System.nanoTime();
+ if (remainingNanos <= 0L) {
+ return 0L;
+ }
+ final long oneMilliNanos = TimeUnit.MILLISECONDS.toNanos(1);
+ return (remainingNanos + oneMilliNanos - 1) / oneMilliNanos;
}
@Override
diff --git
a/integration-test/src/main/java/org/apache/iotdb/it/env/remote/env/RemoteServerEnv.java
b/integration-test/src/main/java/org/apache/iotdb/it/env/remote/env/RemoteServerEnv.java
index 3790c37dcea..cc092d00d72 100644
---
a/integration-test/src/main/java/org/apache/iotdb/it/env/remote/env/RemoteServerEnv.java
+++
b/integration-test/src/main/java/org/apache/iotdb/it/env/remote/env/RemoteServerEnv.java
@@ -169,9 +169,22 @@ public class RemoteServerEnv implements BaseEnv {
public Connection getConnection(
Constant.Version version, String username, String password, String
sqlDialect)
throws SQLException {
+ return getConnection(version, username, password, sqlDialect, 0);
+ }
+
+ @Override
+ public Connection getConnection(
+ Constant.Version version,
+ String username,
+ String password,
+ String sqlDialect,
+ int networkTimeoutMs)
+ throws SQLException {
Connection connection;
try {
Class.forName(Config.JDBC_DRIVER_NAME);
+ String timeoutParam =
+ networkTimeoutMs > 0 ? "&" + Config.NETWORK_TIMEOUT + "=" +
networkTimeoutMs : "";
connection =
DriverManager.getConnection(
Config.IOTDB_URL_PREFIX
@@ -179,7 +192,8 @@ public class RemoteServerEnv implements BaseEnv {
+ "?"
+ VERSION
+ "="
- + version.toString(),
+ + version.toString()
+ + timeoutParam,
BaseEnv.constructProperties(this.user, this.password,
sqlDialect));
} catch (ClassNotFoundException e) {
e.printStackTrace();
diff --git
a/integration-test/src/main/java/org/apache/iotdb/itbase/env/BaseEnv.java
b/integration-test/src/main/java/org/apache/iotdb/itbase/env/BaseEnv.java
index fb2196943e4..1e20d2152b3 100644
--- a/integration-test/src/main/java/org/apache/iotdb/itbase/env/BaseEnv.java
+++ b/integration-test/src/main/java/org/apache/iotdb/itbase/env/BaseEnv.java
@@ -147,6 +147,16 @@ public interface BaseEnv {
version, SessionConfig.DEFAULT_USER, SessionConfig.DEFAULT_PASSWORD,
sqlDialect);
}
+ default Connection getConnection(
+ Constant.Version version, String sqlDialect, int networkTimeoutMs)
throws SQLException {
+ return getConnection(
+ version,
+ SessionConfig.DEFAULT_USER,
+ SessionConfig.DEFAULT_PASSWORD,
+ sqlDialect,
+ networkTimeoutMs);
+ }
+
default Connection getConnection(Constant.Version version, String username,
String password)
throws SQLException {
return getConnection(version, username, password, TREE_SQL_DIALECT);
@@ -156,6 +166,16 @@ public interface BaseEnv {
Constant.Version version, String username, String password, String
sqlDialect)
throws SQLException;
+ default Connection getConnection(
+ Constant.Version version,
+ String username,
+ String password,
+ String sqlDialect,
+ int networkTimeoutMs)
+ throws SQLException {
+ return getConnection(version, username, password, sqlDialect);
+ }
+
Connection getConnection(
DataNodeWrapper dataNodeWrapper, String username, String password,
String sqlDialect)
throws SQLException;
diff --git
a/integration-test/src/test/java/org/apache/iotdb/ainode/it/AINodeSharedClusterIT.java
b/integration-test/src/test/java/org/apache/iotdb/ainode/it/AINodeSharedClusterIT.java
index cbd0f62f16e..1e7bfad1765 100644
---
a/integration-test/src/test/java/org/apache/iotdb/ainode/it/AINodeSharedClusterIT.java
+++
b/integration-test/src/test/java/org/apache/iotdb/ainode/it/AINodeSharedClusterIT.java
@@ -22,6 +22,8 @@ package org.apache.iotdb.ainode.it;
import org.apache.iotdb.ainode.utils.AINodeTestUtils;
import org.apache.iotdb.ainode.utils.AINodeTestUtils.FakeModelInfo;
import org.apache.iotdb.it.env.EnvFactory;
+import org.apache.iotdb.it.env.cluster.node.AINodeWrapper;
+import org.apache.iotdb.it.env.cluster.node.AbstractNodeWrapper;
import org.apache.iotdb.it.framework.IoTDBTestRunner;
import org.apache.iotdb.itbase.category.AIClusterIT;
import org.apache.iotdb.itbase.env.BaseEnv;
@@ -43,7 +45,9 @@ import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
+import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
@@ -57,6 +61,7 @@ import static
org.apache.iotdb.ainode.utils.AINodeTestUtils.checkModelNotOnSpeci
import static
org.apache.iotdb.ainode.utils.AINodeTestUtils.checkModelOnSpecifiedDevice;
import static
org.apache.iotdb.ainode.utils.AINodeTestUtils.concurrentInference;
import static org.apache.iotdb.ainode.utils.AINodeTestUtils.errorTest;
+import static
org.apache.iotdb.ainode.utils.AINodeTestUtils.hasSurvivingInferenceWorkers;
import static org.apache.iotdb.ainode.utils.AINodeTestUtils.prepareDataInTable;
import static org.apache.iotdb.ainode.utils.AINodeTestUtils.prepareDataInTree;
import static org.junit.Assert.assertEquals;
@@ -530,30 +535,189 @@ public class AINodeSharedClusterIT {
}
}
+ @FunctionalInterface
+ interface ConcurrentForecastAction {
+ void run() throws SQLException, InterruptedException;
+ }
+
+ @FunctionalInterface
+ interface ModelUnloadAction {
+ void unload(
+ Statement statement,
+ String modelId,
+ String devices,
+ boolean loadCompleted,
+ long loadSubmittedNanos)
+ throws SQLException;
+ }
+
+ @FunctionalInterface
+ interface ClusterResetAction {
+ void reset() throws SQLException;
+ }
+
private void concurrentGPUForecastTest(FakeModelInfo modelInfo, String
devices)
throws SQLException, InterruptedException {
final int forecastLength = 512;
- try (Connection connection =
EnvFactory.getEnv().getConnection(BaseEnv.TABLE_SQL_DIALECT);
+ final String forecastSQL =
+ String.format(CONCURRENT_FORECAST_SQL_TEMPLATE,
modelInfo.getModelId(), forecastLength);
+ final int threadCnt = 10;
+ // PR CI keeps a concurrency smoke check; nightly/daily can dial this up
if regressions
+ // appear.
+ final int loop = 10;
+ runConcurrentForecastWithModelCleanup(
+ () -> EnvFactory.getEnv().getConnection(BaseEnv.TABLE_SQL_DIALECT),
+ modelInfo.getModelId(),
+ devices,
+ statement -> checkModelOnSpecifiedDevice(statement,
modelInfo.getModelId(), devices),
+ () -> {
+ long startTime = System.currentTimeMillis();
+ concurrentInference(
+ BaseEnv.TABLE_SQL_DIALECT, forecastSQL, threadCnt, loop,
forecastLength);
+ long endTime = System.currentTimeMillis();
+ LOGGER.info(
+ String.format(
+ "Model %s concurrent inference %d reqs (%d threads, %d
loops) in GPU takes time: %dms",
+ modelInfo.getModelId(), threadCnt * loop, threadCnt, loop,
endTime - startTime));
+ },
+ AINodeTestUtils::unloadSubmittedModel,
+ AINodeSharedClusterIT::resetSharedCluster);
+ }
+
+ @FunctionalInterface
+ interface ConnectionOpener {
+ Connection open() throws SQLException;
+ }
+
+ @FunctionalInterface
+ interface ReadinessChecker {
+ void check(Statement statement) throws SQLException, InterruptedException;
+ }
+
+ static void runConcurrentForecastWithModelCleanup(
+ ConnectionOpener controlConnectionOpener,
+ String modelId,
+ String devices,
+ ReadinessChecker readinessChecker,
+ ConcurrentForecastAction inferenceAction,
+ ModelUnloadAction unloadAction,
+ ClusterResetAction resetAction)
+ throws SQLException, InterruptedException {
+ boolean resetClusterRequired = false;
+ Throwable primaryFailure = null;
+ try (Connection connection = controlConnectionOpener.open();
Statement statement = connection.createStatement()) {
- final String forecastSQL =
- String.format(CONCURRENT_FORECAST_SQL_TEMPLATE,
modelInfo.getModelId(), forecastLength);
- final int threadCnt = 10;
- // PR CI keeps a concurrency smoke check; nightly/daily can dial this up
if regressions
- // appear.
- final int loop = 10;
- statement.execute(
- String.format("LOAD MODEL %s TO DEVICES '%s'",
modelInfo.getModelId(), devices));
- checkModelOnSpecifiedDevice(statement, modelInfo.getModelId(), devices);
- long startTime = System.currentTimeMillis();
- concurrentInference(statement, forecastSQL, threadCnt, loop,
forecastLength);
- long endTime = System.currentTimeMillis();
- LOGGER.info(
- String.format(
- "Model %s concurrent inference %d reqs (%d threads, %d loops) in
GPU takes time: %dms",
- modelInfo.getModelId(), threadCnt * loop, threadCnt, loop,
endTime - startTime));
- statement.execute(
- String.format("UNLOAD MODEL %s FROM DEVICES '%s'",
modelInfo.getModelId(), devices));
- checkModelNotOnSpecifiedDevice(statement, modelInfo.getModelId(),
devices);
+ boolean loadSubmitted = false;
+ boolean loadCompleted = false;
+ boolean workersTerminated = true;
+ long loadSubmittedNanos = 0L;
+ try {
+ loadSubmittedNanos = System.nanoTime();
+ statement.execute(String.format("LOAD MODEL %s TO DEVICES '%s'",
modelId, devices));
+ loadSubmitted = true;
+ readinessChecker.check(statement);
+ loadCompleted = true;
+ workersTerminated = false;
+ try {
+ inferenceAction.run();
+ workersTerminated = true;
+ } catch (Throwable t) {
+ workersTerminated = !hasSurvivingInferenceWorkers(t);
+ throw t;
+ }
+ } catch (Throwable t) {
+ primaryFailure = t;
+ throw t;
+ } finally {
+ if (loadSubmitted) {
+ if (!workersTerminated) {
+ // Do not unload the model while inference workers are still
alive; reset the shared
+ // cluster fixture after closing the control connection.
+ resetClusterRequired = true;
+ } else {
+ try {
+ unloadAction.unload(statement, modelId, devices, loadCompleted,
loadSubmittedNanos);
+ } catch (Throwable cleanupError) {
+ resetClusterRequired = true;
+ if (primaryFailure != null) {
+ primaryFailure.addSuppressed(cleanupError);
+ } else {
+ primaryFailure = cleanupError;
+ throw cleanupError;
+ }
+ }
+ }
+ }
+ }
+ } catch (Throwable t) {
+ if (primaryFailure == null) {
+ primaryFailure = t;
+ }
+ throw t;
+ } finally {
+ if (resetClusterRequired) {
+ try {
+ resetAction.reset();
+ } catch (Throwable resetError) {
+ if (primaryFailure != null) {
+ primaryFailure.addSuppressed(resetError);
+ } else {
+ throw resetError;
+ }
+ }
+ }
+ }
+ }
+
+ @FunctionalInterface
+ interface ClusterReinitAction {
+ void reinit() throws SQLException;
+ }
+
+ private static void resetSharedCluster() throws SQLException {
+ resetSharedCluster(
+ EnvFactory.getEnv(),
+ () -> {
+ EnvFactory.getEnv().initClusterEnvironment(1, 1);
+ prepareDataInTree();
+ prepareDataInTable();
+ prepareDataForConcurrentForecast();
+ });
+ }
+
+ static void resetSharedCluster(BaseEnv env, ClusterReinitAction reinitAction)
+ throws SQLException {
+ LOGGER.warn(
+ "Resetting shared AINode test cluster after unresolved model or worker
cleanup failure.");
+ boolean interrupted = Thread.interrupted();
+ try {
+ List<AbstractNodeWrapper> previousNodes = env.getNodeWrapperList();
+ List<AbstractNodeWrapper> previousNodesSnapshot =
+ previousNodes == null ? Collections.emptyList() : new
ArrayList<>(previousNodes);
+ env.cleanClusterEnvironment();
+ List<String> survivingNodes = new ArrayList<>();
+ for (AbstractNodeWrapper node : previousNodesSnapshot) {
+ if (node != null && node.isAlive()) {
+ if (node instanceof AINodeWrapper) {
+ survivingNodes.add(
+ node.getId() + "(pids=" + ((AINodeWrapper)
node).getSurvivingPids() + ")");
+ } else {
+ Process instance = node.getInstance();
+ survivingNodes.add(
+ node.getId() + "(pid=" + (instance != null ? instance.pid() :
-1L) + ")");
+ }
+ }
+ }
+ if (!survivingNodes.isEmpty()) {
+ throw new IllegalStateException(
+ "Failed to confirm exit of previous cluster node(s) before
starting replacement cluster: "
+ + String.join(", ", survivingNodes));
+ }
+ reinitAction.reinit();
+ } finally {
+ if (interrupted) {
+ Thread.currentThread().interrupt();
+ }
}
}
diff --git
a/integration-test/src/test/java/org/apache/iotdb/ainode/utils/AINodeTestUtils.java
b/integration-test/src/test/java/org/apache/iotdb/ainode/utils/AINodeTestUtils.java
index 8f5567c7c9c..6bea065582f 100644
---
a/integration-test/src/test/java/org/apache/iotdb/ainode/utils/AINodeTestUtils.java
+++
b/integration-test/src/test/java/org/apache/iotdb/ainode/utils/AINodeTestUtils.java
@@ -21,9 +21,9 @@ package org.apache.iotdb.ainode.utils;
import org.apache.iotdb.it.env.EnvFactory;
import org.apache.iotdb.itbase.env.BaseEnv;
+import org.apache.iotdb.jdbc.Constant;
import com.google.common.collect.ImmutableSet;
-import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -33,13 +33,18 @@ import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.AbstractMap;
+import java.util.ArrayList;
import java.util.Collections;
+import java.util.HashMap;
import java.util.HashSet;
+import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -97,6 +102,53 @@ public class AINodeTestUtils {
private static final Logger LOGGER =
LoggerFactory.getLogger(AINodeTestUtils.class);
+ private static final long CONCURRENT_INFERENCE_TIMEOUT_MILLIS =
TimeUnit.MINUTES.toMillis(10);
+ private static final int CONCURRENT_INFERENCE_QUERY_TIMEOUT_SECONDS = 60;
+ // Give worker connections a finite socket timeout above the server query
timeout so a hung
+ // response cannot block reads indefinitely; keep drain > 4x network timeout
to cover the initial
+ // RPC plus IoTDBConnection.reconnect()'s 3 retry attempts.
+ private static final int CONCURRENT_INFERENCE_NETWORK_TIMEOUT_MILLIS =
+ (int)
TimeUnit.SECONDS.toMillis(CONCURRENT_INFERENCE_QUERY_TIMEOUT_SECONDS + 10L);
+ private static final long CONCURRENT_INFERENCE_WORKER_DRAIN_TIMEOUT_MILLIS =
+ TimeUnit.SECONDS.toMillis(300);
+ private static final long MODEL_STATUS_POLL_INTERVAL_MILLIS =
TimeUnit.SECONDS.toMillis(3);
+ private static final long MODEL_LOAD_SETTLE_TIMEOUT_MILLIS =
TimeUnit.SECONDS.toMillis(600);
+ private static final long MODEL_UNLOAD_TIMEOUT_MILLIS =
TimeUnit.SECONDS.toMillis(150);
+
+ @FunctionalInterface
+ interface ConnectionSupplier {
+ Connection get() throws SQLException;
+ }
+
+ public static final class SurvivingInferenceWorkersException extends
IllegalStateException {
+
+ private final List<String> survivingWorkers;
+
+ SurvivingInferenceWorkersException(List<String> survivingWorkers) {
+ super("Inference workers still alive after cancellation drain timeout: "
+ survivingWorkers);
+ this.survivingWorkers = Collections.unmodifiableList(new
ArrayList<>(survivingWorkers));
+ }
+
+ public List<String> getSurvivingWorkers() {
+ return survivingWorkers;
+ }
+ }
+
+ public static boolean hasSurvivingInferenceWorkers(Throwable throwable) {
+ if (throwable == null) {
+ return false;
+ }
+ if (throwable instanceof SurvivingInferenceWorkersException) {
+ return true;
+ }
+ for (Throwable suppressed : throwable.getSuppressed()) {
+ if (hasSurvivingInferenceWorkers(suppressed)) {
+ return true;
+ }
+ }
+ return hasSurvivingInferenceWorkers(throwable.getCause());
+ }
+
public static void checkHeader(ResultSetMetaData resultSetMetaData, String
title)
throws SQLException {
String[] headers = title.split(",");
@@ -114,50 +166,219 @@ public class AINodeTestUtils {
}
public static void concurrentInference(
- Statement statement, String sql, int threadCnt, int loop, int
expectedOutputLength)
+ String sqlDialect, String sql, int threadCnt, int loop, int
expectedOutputLength)
+ throws InterruptedException {
+ // Use the Version + networkTimeoutMs overload so profiles with
+ // ReadAndVerifyWithMultiNode=false (such as AIClusterIT) return direct
IoTDBConnections
+ // (avoiding the 5-thread cap in RequestThreadPool) with bounded socket
reads.
+ concurrentInference(
+ () ->
+ EnvFactory.getEnv()
+ .getConnection(
+ Constant.Version.V_1_0,
+ sqlDialect,
+ CONCURRENT_INFERENCE_NETWORK_TIMEOUT_MILLIS),
+ sql,
+ threadCnt,
+ loop,
+ expectedOutputLength,
+ CONCURRENT_INFERENCE_TIMEOUT_MILLIS,
+ CONCURRENT_INFERENCE_QUERY_TIMEOUT_SECONDS,
+ CONCURRENT_INFERENCE_WORKER_DRAIN_TIMEOUT_MILLIS);
+ }
+
+ static void concurrentInference(
+ ConnectionSupplier connectionSupplier,
+ String sql,
+ int threadCnt,
+ int loop,
+ int expectedOutputLength,
+ long overallTimeoutMillis,
+ int perQueryTimeoutSeconds,
+ long workerDrainTimeoutMillis)
throws InterruptedException {
- AtomicBoolean allPass = new AtomicBoolean(true);
+ AtomicBoolean cancelled = new AtomicBoolean(false);
+ AtomicInteger completedRequests = new AtomicInteger(0);
+ AtomicReference<Throwable> firstFailure = new AtomicReference<>();
+ int boundedPerQueryTimeoutSeconds = Math.max(1, perQueryTimeoutSeconds);
+ long deadlineNanos = System.nanoTime() +
TimeUnit.MILLISECONDS.toNanos(overallTimeoutMillis);
Thread[] threads = new Thread[threadCnt];
for (int i = 0; i < threadCnt; i++) {
threads[i] =
new Thread(
() -> {
- try {
+ if (cancelled.get() || Thread.currentThread().isInterrupted())
{
+ return;
+ }
+ // JDBC Statements cannot be shared concurrently because
executing a new query
+ // closes any previously open ResultSet on that Statement.
+ try (Connection connection = connectionSupplier.get();
+ Statement statement = connection.createStatement()) {
for (int j = 0; j < loop; j++) {
+ if (cancelled.get() ||
Thread.currentThread().isInterrupted()) {
+ return;
+ }
+ long remainingNanos = deadlineNanos - System.nanoTime();
+ if (remainingNanos <= 0L) {
+ if (!cancelled.get()) {
+ firstFailure.compareAndSet(
+ null,
+ new AssertionError(
+ "Concurrent inference deadline exceeded before
completing all loops for SQL: "
+ + sql));
+ }
+ return;
+ }
+ long remainingSecondsCeil = (remainingNanos - 1L) /
1_000_000_000L + 1L;
+ int queryTimeoutSeconds =
+ (int) Math.min(boundedPerQueryTimeoutSeconds,
remainingSecondsCeil);
+ statement.setQueryTimeout(queryTimeoutSeconds);
try (ResultSet resultSet = statement.executeQuery(sql)) {
int outputCnt = 0;
- while (resultSet.next()) {
+ while (!cancelled.get()
+ && !Thread.currentThread().isInterrupted()
+ && resultSet.next()) {
outputCnt++;
}
+ if (cancelled.get() ||
Thread.currentThread().isInterrupted()) {
+ return;
+ }
if (expectedOutputLength != outputCnt) {
- allPass.set(false);
- fail(
- "Output count mismatch for SQL: "
- + sql
- + ". Expected: "
- + expectedOutputLength
- + ", but got: "
- + outputCnt);
+ AssertionError error =
+ new AssertionError(
+ "Output count mismatch for SQL: "
+ + sql
+ + ". Expected: "
+ + expectedOutputLength
+ + ", but got: "
+ + outputCnt);
+ firstFailure.compareAndSet(null, error);
+ LOGGER.error("Concurrent inference output mismatch",
error);
+ return;
}
- } catch (SQLException e) {
- allPass.set(false);
- fail(e.getMessage());
+ completedRequests.incrementAndGet();
}
}
- } catch (Exception e) {
- allPass.set(false);
- fail(e.getMessage());
+ } catch (Throwable t) {
+ if (!cancelled.get()) {
+ firstFailure.compareAndSet(null, t);
+ LOGGER.error("Concurrent inference failed for SQL: {}",
sql, t);
+ } else {
+ LOGGER.debug(
+ "Concurrent inference worker stopped after
cancellation for SQL: {}",
+ sql,
+ t);
+ }
}
- });
+ },
+ "ainode-concurrent-inference-" + i);
threads[i].start();
}
+
+ List<String> timedOutThreads = new ArrayList<>();
+ try {
+ for (Thread thread : threads) {
+ long remainingNanos = deadlineNanos - System.nanoTime();
+ if (remainingNanos > 0L) {
+ thread.join(Math.max(1L,
TimeUnit.NANOSECONDS.toMillis(remainingNanos)));
+ }
+ if (thread.isAlive()) {
+ timedOutThreads.add(thread.getName());
+ }
+ }
+ } catch (InterruptedException e) {
+ cancelled.set(true);
+ interruptAll(threads);
+ List<String> survivingThreads =
+ drainWorkersUninterruptibly(threads, workerDrainTimeoutMillis);
+ Throwable failure = firstFailure.get();
+ if (failure != null) {
+ e.addSuppressed(failure);
+ }
+ if (!survivingThreads.isEmpty()) {
+ e.addSuppressed(new
SurvivingInferenceWorkersException(survivingThreads));
+ }
+ throw e;
+ }
+
+ if (!timedOutThreads.isEmpty()) {
+ cancelled.set(true);
+ interruptAll(threads);
+ List<String> survivingThreads =
+ drainWorkersUninterruptibly(threads, workerDrainTimeoutMillis);
+ StringBuilder message =
+ new StringBuilder("Thread timeout after ")
+ .append(overallTimeoutMillis)
+ .append(" ms: ")
+ .append(timedOutThreads);
+ if (!survivingThreads.isEmpty()) {
+ message.append("; still alive after drain timeout:
").append(survivingThreads);
+ }
+ Throwable failure = firstFailure.get();
+ AssertionError timeoutError;
+ if (failure != null) {
+ message.append("; first worker failure:
").append(failure.getMessage());
+ timeoutError = new AssertionError(message.toString(), failure);
+ } else {
+ timeoutError = new AssertionError(message.toString());
+ }
+ if (!survivingThreads.isEmpty()) {
+ timeoutError.addSuppressed(new
SurvivingInferenceWorkersException(survivingThreads));
+ }
+ throw timeoutError;
+ }
+
+ Throwable failure = firstFailure.get();
+ if (failure != null) {
+ throw new AssertionError("Concurrent inference failed: " +
failure.getMessage(), failure);
+ }
+ assertEquals(
+ "Completed concurrent inference request count mismatch for SQL: " +
sql,
+ threadCnt * loop,
+ completedRequests.get());
+ }
+
+ private static void interruptAll(Thread[] threads) {
+ for (Thread thread : threads) {
+ if (thread != null) {
+ thread.interrupt();
+ }
+ }
+ }
+
+ private static List<String> drainWorkersUninterruptibly(
+ Thread[] threads, long drainTimeoutMillis) {
+ long drainDeadlineNanos = System.nanoTime() +
TimeUnit.MILLISECONDS.toNanos(drainTimeoutMillis);
+ boolean interrupted = false;
+ try {
+ for (Thread thread : threads) {
+ if (thread == null) {
+ continue;
+ }
+ while (thread.isAlive()) {
+ long remainingNanos = drainDeadlineNanos - System.nanoTime();
+ if (remainingNanos <= 0L) {
+ break;
+ }
+ try {
+ thread.join(Math.max(1L,
TimeUnit.NANOSECONDS.toMillis(remainingNanos)));
+ } catch (InterruptedException e) {
+ interrupted = true;
+ }
+ }
+ }
+ } finally {
+ if (interrupted) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ List<String> survivingThreads = new ArrayList<>();
for (Thread thread : threads) {
- thread.join(TimeUnit.MINUTES.toMillis(10));
- if (thread.isAlive()) {
- fail("Thread timeout after 10 minutes");
+ if (thread != null && thread.isAlive()) {
+ survivingThreads.add(thread.getName());
}
}
- Assert.assertTrue(allPass.get());
+ return survivingThreads;
}
public static void checkModelOnSpecifiedDevice(Statement statement, String
modelId, String device)
@@ -166,23 +387,18 @@ public class AINodeTestUtils {
LOGGER.info("Checking model: {} on target devices: {}", modelId,
targetDevices);
for (int retry = 0; retry < 200; retry++) {
Set<String> foundDevices = new HashSet<>();
- try (final ResultSet resultSet =
- statement.executeQuery(String.format("SHOW LOADED MODELS '%s'",
device))) {
- while (resultSet.next()) {
- String deviceId = resultSet.getString("DeviceId");
- String loadedModelId = resultSet.getString("ModelId");
- int count = resultSet.getInt("Count(instances)");
- LOGGER.info("Model {} found in device {}, count {}", loadedModelId,
deviceId, count);
- if (loadedModelId.equals(modelId) &&
targetDevices.contains(deviceId) && count > 0) {
- foundDevices.add(deviceId);
- LOGGER.info("Model {} is loaded to device {}", modelId, deviceId);
- }
- }
- if (foundDevices.containsAll(targetDevices)) {
- LOGGER.info("Model {} is loaded to devices {}, start testing",
modelId, targetDevices);
- return;
+ Map<String, Integer> deviceCounts =
+ queryModelDeviceCounts(statement, modelId, device, targetDevices);
+ for (Map.Entry<String, Integer> entry : deviceCounts.entrySet()) {
+ if (entry.getValue() > 0) {
+ foundDevices.add(entry.getKey());
+ LOGGER.info("Model {} is loaded to device {}", modelId,
entry.getKey());
}
}
+ if (foundDevices.containsAll(targetDevices)) {
+ LOGGER.info("Model {} is loaded to devices {}, start testing",
modelId, targetDevices);
+ return;
+ }
TimeUnit.SECONDS.sleep(3);
}
fail("Model " + modelId + " is not loaded on device " + device);
@@ -194,29 +410,224 @@ public class AINodeTestUtils {
Set<String> targetDevices = ImmutableSet.copyOf(device.split(","));
LOGGER.info("Checking model: {} not on target devices: {}", modelId,
targetDevices);
for (int retry = 0; retry < 50; retry++) {
- Set<String> foundDevices = new HashSet<>();
- try (final ResultSet resultSet =
- statement.executeQuery(String.format("SHOW LOADED MODELS '%s'",
device))) {
- while (resultSet.next()) {
- String deviceId = resultSet.getString("DeviceId");
- String loadedModelId = resultSet.getString("ModelId");
- int count = resultSet.getInt("Count(instances)");
- LOGGER.info("Model {} found in device {}, count {}", loadedModelId,
deviceId, count);
- if (loadedModelId.equals(modelId) &&
targetDevices.contains(deviceId) && count > 0) {
- foundDevices.add(deviceId);
- LOGGER.info("Model {} is loaded to device {}", modelId, device);
- }
- }
- if (foundDevices.isEmpty()) {
- LOGGER.info("Model {} is unloaded from devices {}.", modelId,
targetDevices);
- return;
- }
+ Map<String, Integer> deviceCounts =
+ queryModelDeviceCounts(statement, modelId, device, targetDevices);
+ if (deviceCounts.isEmpty()) {
+ LOGGER.info("Model {} is unloaded from devices {}.", modelId,
targetDevices);
+ return;
}
+ LOGGER.info("Model {} is still present on devices {}", modelId,
deviceCounts);
TimeUnit.SECONDS.sleep(3);
}
fail("Model " + modelId + " is still loaded on device " + device);
}
+ public static void unloadSubmittedModel(
+ Statement statement,
+ String modelId,
+ String device,
+ boolean loadCompleted,
+ long loadSubmittedNanos)
+ throws SQLException {
+ unloadSubmittedModel(
+ statement,
+ modelId,
+ device,
+ loadCompleted,
+ loadSubmittedNanos,
+ MODEL_STATUS_POLL_INTERVAL_MILLIS,
+ MODEL_LOAD_SETTLE_TIMEOUT_MILLIS,
+ MODEL_UNLOAD_TIMEOUT_MILLIS);
+ }
+
+ static void unloadSubmittedModel(
+ Statement statement,
+ String modelId,
+ String device,
+ boolean loadCompleted,
+ long loadSubmittedNanos,
+ long pollIntervalMillis,
+ long loadSettleTimeoutMillis,
+ long unloadTimeoutMillis)
+ throws SQLException {
+ Set<String> targetDevices = ImmutableSet.copyOf(device.split(","));
+ AtomicBoolean interrupted = new AtomicBoolean(Thread.interrupted());
+ try {
+ if (!loadCompleted) {
+ // LOAD MODEL returns as soon as the task is queued in AINode's
PoolController. If we
+ // issue UNLOAD MODEL before any device registers a pool, AINode skips
queuing an unload
+ // and the later load would leave the model resident for subsequent
tests. Wait for the
+ // submitted load to complete or settle before unloading; if it
remains unresolved with no
+ // running pool at the deadline, fail cleanup so the caller resets the
shared cluster.
+ waitForSubmittedModelLoadToSettle(
+ statement,
+ modelId,
+ device,
+ targetDevices,
+ loadSubmittedNanos,
+ pollIntervalMillis,
+ loadSettleTimeoutMillis,
+ interrupted);
+ }
+ statement.execute(String.format("UNLOAD MODEL %s FROM DEVICES '%s'",
modelId, device));
+ waitForModelRemoval(
+ statement,
+ modelId,
+ device,
+ targetDevices,
+ pollIntervalMillis,
+ unloadTimeoutMillis,
+ interrupted);
+ } finally {
+ if (interrupted.get()) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
+
+ private static void waitForSubmittedModelLoadToSettle(
+ Statement statement,
+ String modelId,
+ String device,
+ Set<String> targetDevices,
+ long loadSubmittedNanos,
+ long pollIntervalMillis,
+ long loadSettleTimeoutMillis,
+ AtomicBoolean interrupted)
+ throws SQLException {
+ long settleDeadlineNanos =
+ loadSubmittedNanos +
TimeUnit.MILLISECONDS.toNanos(loadSettleTimeoutMillis);
+ Set<String> everRegisteredDevices = new HashSet<>();
+ while (true) {
+ Map<String, Integer> deviceCounts =
+ queryModelDeviceCounts(statement, modelId, device, targetDevices);
+ everRegisteredDevices.addAll(deviceCounts.keySet());
+ Set<String> runningDevices = new HashSet<>();
+ boolean hasInitializingDevice = false;
+ for (Map.Entry<String, Integer> entry : deviceCounts.entrySet()) {
+ if (entry.getValue() > 0) {
+ runningDevices.add(entry.getKey());
+ } else {
+ hasInitializingDevice = true;
+ }
+ }
+ if (runningDevices.containsAll(targetDevices)) {
+ LOGGER.info(
+ "Submitted load of model {} completed on devices {} before cleanup
unload.",
+ modelId,
+ targetDevices);
+ return;
+ }
+ if (everRegisteredDevices.containsAll(targetDevices) &&
!hasInitializingDevice) {
+ LOGGER.info(
+ "Submitted load of model {} settled on devices {} (running={})
before cleanup unload.",
+ modelId,
+ targetDevices,
+ runningDevices);
+ return;
+ }
+ long remainingNanos = settleDeadlineNanos - System.nanoTime();
+ if (remainingNanos <= 0L) {
+ if (runningDevices.isEmpty()) {
+ Set<String> unobservedDevices = new HashSet<>(targetDevices);
+ unobservedDevices.removeAll(everRegisteredDevices);
+ fail(
+ "Submitted load of model "
+ + modelId
+ + " on devices "
+ + device
+ + " remained unresolved after "
+ + loadSettleTimeoutMillis
+ + " ms (current="
+ + deviceCounts
+ + ", unobserved="
+ + unobservedDevices
+ + "); UNLOAD MODEL cannot guarantee cleanup without a
running pool.");
+ }
+ LOGGER.warn(
+ "Timed out waiting for submitted load of model {} on devices {} to
settle (current={}); queuing unload for registered pools.",
+ modelId,
+ targetDevices,
+ deviceCounts);
+ return;
+ }
+ long sleepMillis =
+ Math.min(pollIntervalMillis, Math.max(1L,
TimeUnit.NANOSECONDS.toMillis(remainingNanos)));
+ if (sleepUninterruptibly(sleepMillis)) {
+ interrupted.set(true);
+ }
+ }
+ }
+
+ private static void waitForModelRemoval(
+ Statement statement,
+ String modelId,
+ String device,
+ Set<String> targetDevices,
+ long pollIntervalMillis,
+ long unloadTimeoutMillis,
+ AtomicBoolean interrupted)
+ throws SQLException {
+ long unloadDeadlineNanos =
+ System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(unloadTimeoutMillis);
+ while (true) {
+ Map<String, Integer> deviceCounts =
+ queryModelDeviceCounts(statement, modelId, device, targetDevices);
+ if (deviceCounts.isEmpty()) {
+ LOGGER.info("Model {} is unloaded from devices {}.", modelId,
targetDevices);
+ return;
+ }
+ long remainingNanos = unloadDeadlineNanos - System.nanoTime();
+ if (remainingNanos <= 0L) {
+ fail("Model " + modelId + " is still loaded on device " + device + ":
" + deviceCounts);
+ }
+ long sleepMillis =
+ Math.min(pollIntervalMillis, Math.max(1L,
TimeUnit.NANOSECONDS.toMillis(remainingNanos)));
+ if (sleepUninterruptibly(sleepMillis)) {
+ interrupted.set(true);
+ }
+ }
+ }
+
+ private static Map<String, Integer> queryModelDeviceCounts(
+ Statement statement, String modelId, String device, Set<String>
targetDevices)
+ throws SQLException {
+ Map<String, Integer> deviceCounts = new HashMap<>();
+ try (final ResultSet resultSet =
+ statement.executeQuery(String.format("SHOW LOADED MODELS '%s'",
device))) {
+ while (resultSet.next()) {
+ String deviceId = resultSet.getString("DeviceId");
+ String loadedModelId = resultSet.getString("ModelId");
+ int count = resultSet.getInt("Count(instances)");
+ LOGGER.info("Model {} found in device {}, count {}", loadedModelId,
deviceId, count);
+ if (loadedModelId.equals(modelId) && targetDevices.contains(deviceId))
{
+ deviceCounts.put(deviceId, count);
+ }
+ }
+ }
+ return deviceCounts;
+ }
+
+ private static boolean sleepUninterruptibly(long millis) {
+ if (millis <= 0L) {
+ return false;
+ }
+ boolean interrupted = false;
+ long endNanos = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(millis);
+ while (true) {
+ long remainingNanos = endNanos - System.nanoTime();
+ if (remainingNanos <= 0L) {
+ return interrupted;
+ }
+ try {
+ TimeUnit.NANOSECONDS.sleep(remainingNanos);
+ return interrupted;
+ } catch (InterruptedException e) {
+ interrupted = true;
+ }
+ }
+ }
+
private static final String[] WRITE_SQL_IN_TREE =
new String[] {
"CREATE DATABASE root.AI",
diff --git a/iotdb-core/ainode/iotdb/ainode/core/rpc/service.py
b/iotdb-core/ainode/iotdb/ainode/core/rpc/service.py
index 3f47b7e976e..2420af20184 100644
--- a/iotdb-core/ainode/iotdb/ainode/core/rpc/service.py
+++ b/iotdb-core/ainode/iotdb/ainode/core/rpc/service.py
@@ -30,7 +30,7 @@ from iotdb.thrift.ainode import IAINodeRPCService
logger = Logger()
-class AINodeThreadPoolServer(TServer.TThreadPoolServer):
+class AINodeThreadPoolServer(TServer.TThreadedServer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._stop_event = threading.Event()
@@ -38,14 +38,8 @@ class AINodeThreadPoolServer(TServer.TThreadPoolServer):
def serve(self) -> None:
self._stop_event.clear()
logger.info("The RPC service thread pool of IoTDB-AINode begins to
serve...")
- """Start a fixed number of worker threads and put client into a
queue"""
- for i in range(self.threads):
- try:
- t = threading.Thread(target=self.serveThread,
daemon=self.daemon)
- t.start()
- except Exception as x:
- logger.error(x)
- # Pump the socket for clients
+ # Pump the socket for clients and spawn a dedicated thread per
connection so
+ # persistent pooled clients from DataNode/ConfigNode cannot starve
concurrent RPCs.
self.serverTransport.listen()
handle = getattr(self.serverTransport, "handle", None)
if handle is not None and hasattr(handle, "settimeout"):
@@ -56,7 +50,17 @@ class AINodeThreadPoolServer(TServer.TThreadPoolServer):
client = self.serverTransport.accept()
if not client:
continue
- self.clients.put(client)
+ if self._stop_event.is_set():
+ client.close()
+ break
+ t = threading.Thread(
+ target=self.handle, args=(client,), daemon=self.daemon
+ )
+ try:
+ t.start()
+ except Exception:
+ client.close()
+ raise
except socket.timeout:
continue
except Exception as x: