From c444ba24befb939713d475ec92af398e4b058497 Mon Sep 17 00:00:00 2001 From: 761417898 <761417898@qq.com> Date: Wed, 18 Nov 2026 11:59:13 +0800 Subject: [PATCH 1/6] Add staged test insertion APIs for Java tree and table sessions --- .../session/it/IoTDBStagedTestInsertIT.java | 311 ++++++++++++++++++ .../org/apache/iotdb/isession/ISession.java | 51 +++ .../apache/iotdb/isession/ITableSession.java | 29 ++ .../iotdb/session/i18n/SessionMessages.java | 12 + .../iotdb/session/i18n/SessionMessages.java | 12 + .../org/apache/iotdb/session/Session.java | 143 ++++++++ .../iotdb/session/SessionConnection.java | 36 ++ .../apache/iotdb/session/TableSession.java | 7 + .../session/pool/TableSessionWrapper.java | 14 + .../iotdb/session/SessionConnectionTest.java | 49 +++ .../iotdb/session/TableSessionTest.java | 51 +++ .../session/pool/TableSessionWrapperTest.java | 102 ++++++ .../iotdb/db/i18n/DataNodeMiscMessages.java | 3 + .../iotdb/db/i18n/DataNodeQueryMessages.java | 21 ++ .../iotdb/db/i18n/DataNodeMiscMessages.java | 3 + .../iotdb/db/i18n/DataNodeQueryMessages.java | 21 ++ .../thrift/impl/ClientRPCServiceImpl.java | 115 +++++++ .../impl/DataNodeInternalRPCServiceImpl.java | 6 + .../queryengine/common/MPPQueryContext.java | 19 ++ .../db/queryengine/plan/Coordinator.java | 124 +++++++ .../plan/analyze/AnalyzeVisitor.java | 28 +- .../plan/analyze/ClusterPartitionFetcher.java | 34 ++ .../schema/AutoCreateSchemaExecutor.java | 3 + .../execution/TestInsertPlanValidator.java | 80 +++++ .../analyzer/StatementAnalyzer.java | 5 +- .../fetcher/TableDeviceSchemaValidator.java | 3 + .../fetcher/TableHeaderSchemaValidator.java | 4 + .../TestInsertPlanValidatorTest.java | 81 +++++ .../thrift-datanode/rpc-changelist.md | 7 + .../src/main/thrift/client.thrift | 37 +++ .../src/main/thrift/datanode.thrift | 3 + 31 files changed, 1406 insertions(+), 8 deletions(-) create mode 100644 integration-test/src/test/java/org/apache/iotdb/session/it/IoTDBStagedTestInsertIT.java create mode 100644 iotdb-client/session/src/test/java/org/apache/iotdb/session/TableSessionTest.java create mode 100644 iotdb-client/session/src/test/java/org/apache/iotdb/session/pool/TableSessionWrapperTest.java create mode 100644 iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/TestInsertPlanValidator.java create mode 100644 iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/execution/TestInsertPlanValidatorTest.java diff --git a/integration-test/src/test/java/org/apache/iotdb/session/it/IoTDBStagedTestInsertIT.java b/integration-test/src/test/java/org/apache/iotdb/session/it/IoTDBStagedTestInsertIT.java new file mode 100644 index 0000000000000..12d56ad51f695 --- /dev/null +++ b/integration-test/src/test/java/org/apache/iotdb/session/it/IoTDBStagedTestInsertIT.java @@ -0,0 +1,311 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iotdb.session.it; + +import org.apache.iotdb.isession.ISession; +import org.apache.iotdb.isession.ITableSession; +import org.apache.iotdb.isession.SessionDataSet; +import org.apache.iotdb.isession.pool.ITableSessionPool; +import org.apache.iotdb.it.env.EnvFactory; +import org.apache.iotdb.it.env.cluster.node.DataNodeWrapper; +import org.apache.iotdb.it.framework.IoTDBTestRunner; +import org.apache.iotdb.itbase.category.ClusterIT; +import org.apache.iotdb.itbase.category.LocalStandaloneIT; +import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; +import org.apache.iotdb.session.TableSessionBuilder; +import org.apache.iotdb.session.pool.TableSessionPoolBuilder; + +import org.apache.tsfile.enums.ColumnCategory; +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.write.record.Tablet; +import org.apache.tsfile.write.schema.MeasurementSchema; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; + +import java.util.Arrays; +import java.util.Collections; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +@RunWith(IoTDBTestRunner.class) +@Category({LocalStandaloneIT.class, ClusterIT.class}) +public class IoTDBStagedTestInsertIT { + @BeforeClass + public static void setUp() throws Exception { + EnvFactory.getEnv().initClusterEnvironment(); + } + + @AfterClass + public static void tearDown() throws Exception { + EnvFactory.getEnv().cleanClusterEnvironment(); + } + + @Test + public void testStagesAndPayloadsLeaveDataUnchanged() throws Exception { + try (ISession session = EnvFactory.getEnv().getSessionConnection()) { + session.executeNonQueryStatement( + "CREATE TIMESERIES root.staged.d.`a.b` WITH DATATYPE=DOUBLE, ENCODING=PLAIN"); + session.executeNonQueryStatement("INSERT INTO root.staged.d(time, `a.b`) VALUES(1, 1)"); + for (TestInsertStage stage : TestInsertStage.values()) { + session.executeNonQueryStatement("CLEAR CACHE"); + session.testInsertRecord( + "root.staged.d", + 2, + Collections.singletonList("`a.b`"), + Collections.singletonList(TSDataType.DOUBLE), + Collections.singletonList(2.0), + stage); + session.testInsertRecord( + "root.staged.d", + 2, + Collections.singletonList("`a.b`"), + Collections.singletonList("2"), + stage); + session.testInsertRecords( + Collections.singletonList("root.staged.d"), + Collections.singletonList(2L), + Collections.singletonList(Collections.singletonList("`a.b`")), + Collections.singletonList(Collections.singletonList(TSDataType.DOUBLE)), + Collections.singletonList(Collections.singletonList(2.0)), + stage); + session.testInsertRecords( + Collections.singletonList("root.staged.d"), + Collections.singletonList(2L), + Collections.singletonList(Collections.singletonList("`a.b`")), + Collections.singletonList(Collections.singletonList("2")), + stage); + Tablet tablet = + new Tablet( + "root.staged.d", + Collections.singletonList(new MeasurementSchema("`a.b`", TSDataType.DOUBLE))); + tablet.addTimestamp(0, 2); + tablet.addValue("`a.b`", 0, 2.0); + session.testInsertTablet(tablet, stage); + session.testInsertTablets(Collections.singletonMap("root.staged.d", tablet), stage); + } + try (SessionDataSet data = + session.executeQueryStatement("SELECT count(`a.b`) FROM root.staged.d")) { + assertEquals(1, data.next().getFields().get(0).getLongV()); + } + session.executeNonQueryStatement( + "CREATE TIMESERIES root.staged_other.d.s WITH DATATYPE=INT64, ENCODING=PLAIN"); + session.executeNonQueryStatement("INSERT INTO root.staged_other.d(time,s) VALUES(1,1)"); + // Each ingress node tests the same multi-region request, exercising local and remote + // reception. + for (DataNodeWrapper node : EnvFactory.getEnv().getDataNodeWrapperList()) { + try (ISession ingress = + EnvFactory.getEnv() + .getSessionConnection(Collections.singletonList(node.getIpAndPortString()))) { + ingress.testInsertRecords( + Arrays.asList("root.staged.d", "root.staged_other.d"), + Arrays.asList(2L, 2L), + Arrays.asList(Collections.singletonList("`a.b`"), Collections.singletonList("s")), + Arrays.asList(Collections.singletonList("2"), Collections.singletonList("2")), + TestInsertStage.UNTIL_WRITE_TARGET_RECEIVED); + } + } + try (SessionDataSet data = + session.executeQueryStatement("SELECT count(s) FROM root.staged_other.d")) { + assertEquals(1, data.next().getFields().get(0).getLongV()); + } + try (SessionDataSet data = + session.executeQueryStatement("SELECT count(`a.b`) FROM root.staged.d")) { + assertEquals(1, data.next().getFields().get(0).getLongV()); + } + // A normal insertion after the tests proves schema locks/resources were released. + session.executeNonQueryStatement("INSERT INTO root.staged.d(time, `a.b`) VALUES(2, 2)"); + try (SessionDataSet data = + session.executeQueryStatement("SELECT count(`a.b`) FROM root.staged.d")) { + assertEquals(2, data.next().getFields().get(0).getLongV()); + } + } + } + + @Test + public void testMissingMetadataAndPartitionAreNotCreated() throws Exception { + try (ISession session = EnvFactory.getEnv().getSessionConnection()) { + session.testInsertRecord( + "root.staged_missing.d", + 1, + Collections.singletonList("s"), + Collections.singletonList("1")); + session.testInsertRecord( + "root.staged_missing.d", + 1, + Collections.singletonList("s"), + Collections.singletonList("1"), + TestInsertStage.UNTIL_DECODED); + assertThrows( + StatementExecutionException.class, + () -> + session.testInsertRecord( + "root.staged_missing.d", + 1, + Collections.singletonList("s"), + Collections.singletonList("1"), + TestInsertStage.UNTIL_ANALYZED)); + try (SessionDataSet data = + session.executeQueryStatement("SHOW DATABASES root.staged_missing")) { + assertFalse(data.hasNext()); + } + session.executeNonQueryStatement( + "CREATE TIMESERIES root.staged_empty.d.s WITH DATATYPE=INT64, ENCODING=PLAIN"); + assertThrows( + StatementExecutionException.class, + () -> + session.testInsertRecord( + "root.staged_empty.d", + 1, + Collections.singletonList("s"), + Collections.singletonList("1"), + TestInsertStage.UNTIL_PLANNED)); + session.executeNonQueryStatement("INSERT INTO root.staged_empty.d(time,s) VALUES(1,1)"); + session.testInsertRecord( + "root.staged_empty.d", + 2, + Collections.singletonList("s"), + Collections.singletonList("2"), + TestInsertStage.UNTIL_WRITE_TARGET_RECEIVED); + try (SessionDataSet data = + session.executeQueryStatement("SELECT count(s) FROM root.staged_empty.d")) { + assertEquals(1, data.next().getFields().get(0).getLongV()); + } + } + } + + @Test + public void testTemplateIsNotActivatedOrExtended() throws Exception { + try (ISession session = EnvFactory.getEnv().getSessionConnection()) { + session.executeNonQueryStatement( + "CREATE SCHEMA TEMPLATE staged_template (s INT64 ENCODING=PLAIN)"); + session.executeNonQueryStatement("CREATE DATABASE root.staged_template"); + session.executeNonQueryStatement( + "SET SCHEMA TEMPLATE staged_template TO root.staged_template"); + assertThrows( + StatementExecutionException.class, + () -> + session.testInsertRecord( + "root.staged_template.d", + 1, + Collections.singletonList("s"), + Collections.singletonList("1"), + TestInsertStage.UNTIL_ANALYZED)); + assertTrue(session.showPathsTemplateUsingOn("staged_template").isEmpty()); + session.executeNonQueryStatement("INSERT INTO root.staged_template.d(time,s) VALUES(1,1)"); + assertThrows( + StatementExecutionException.class, + () -> + session.testInsertRecord( + "root.staged_template.d", + 2, + Collections.singletonList("extra"), + Collections.singletonList("1"), + TestInsertStage.UNTIL_ANALYZED)); + try (SessionDataSet data = + session.executeQueryStatement("SHOW TIMESERIES root.staged_template.d.extra")) { + assertFalse(data.hasNext()); + } + session.testInsertRecord( + "root.staged_template.d", + 2, + Collections.singletonList("s"), + Collections.singletonList("2"), + TestInsertStage.UNTIL_WRITE_TARGET_RECEIVED); + } + } + + @Test + public void testTableDeviceAndAttributeRemainUnchanged() throws Exception { + try (ITableSession session = + new TableSessionBuilder() + .nodeUrls( + Collections.singletonList( + EnvFactory.getEnv().getIP() + ":" + EnvFactory.getEnv().getPort())) + .build()) { + session.executeNonQueryStatement("CREATE DATABASE staged_table"); + session.executeNonQueryStatement("USE staged_table"); + session.executeNonQueryStatement( + "CREATE TABLE t(id STRING TAG, attr STRING ATTRIBUTE, v INT64 FIELD)"); + session.executeNonQueryStatement("INSERT INTO t(time,id,attr,v) VALUES(1,'d','original',1)"); + session.testInsert(tableTablet("d", "original")); + for (TestInsertStage stage : TestInsertStage.values()) { + session.testInsert(tableTablet("d", "original"), stage); + } + try (ITableSessionPool pool = + new TableSessionPoolBuilder() + .nodeUrls( + Collections.singletonList( + EnvFactory.getEnv().getIP() + ":" + EnvFactory.getEnv().getPort())) + .database("staged_table") + .maxSize(1) + .build()) { + try (ITableSession borrowed = pool.getSession()) { + borrowed.testInsert(tableTablet("d", "original")); + for (TestInsertStage stage : TestInsertStage.values()) { + borrowed.testInsert(tableTablet("d", "original"), stage); + } + assertThrows( + StatementExecutionException.class, + () -> + borrowed.testInsert(tableTablet("d", "changed"), TestInsertStage.UNTIL_ANALYZED)); + } + // A statement error leaves the connection usable and returns it to the pool on close. + try (ITableSession borrowed = pool.getSession(); + SessionDataSet data = borrowed.executeQueryStatement("SELECT count(*) FROM t")) { + assertEquals(1, data.next().getFields().get(0).getLongV()); + } + } + + assertThrows( + StatementExecutionException.class, + () -> + session.testInsert( + tableTablet("missing", "original"), TestInsertStage.UNTIL_ANALYZED)); + assertThrows( + StatementExecutionException.class, + () -> session.testInsert(tableTablet("d", "changed"), TestInsertStage.UNTIL_ANALYZED)); + try (SessionDataSet data = session.executeQueryStatement("SELECT id,attr,v FROM t")) { + assertTrue(data.hasNext()); + assertEquals("original", data.next().getFields().get(1).getStringValue()); + assertFalse(data.hasNext()); + } + } + } + + private Tablet tableTablet(String device, String attribute) { + Tablet tablet = + new Tablet( + "t", + Arrays.asList("id", "attr", "v"), + Arrays.asList(TSDataType.STRING, TSDataType.STRING, TSDataType.INT64), + Arrays.asList(ColumnCategory.TAG, ColumnCategory.ATTRIBUTE, ColumnCategory.FIELD)); + tablet.addTimestamp(0, 2); + tablet.addValue("id", 0, device); + tablet.addValue("attr", 0, attribute); + tablet.addValue("v", 0, 2L); + return tablet; + } +} diff --git a/iotdb-client/isession/src/main/java/org/apache/iotdb/isession/ISession.java b/iotdb-client/isession/src/main/java/org/apache/iotdb/isession/ISession.java index 70d4266d6c889..2c793f2b35882 100644 --- a/iotdb-client/isession/src/main/java/org/apache/iotdb/isession/ISession.java +++ b/iotdb-client/isession/src/main/java/org/apache/iotdb/isession/ISession.java @@ -29,6 +29,7 @@ import org.apache.iotdb.rpc.StatementExecutionException; import org.apache.iotdb.service.rpc.thrift.TSBackupConfigurationResp; import org.apache.iotdb.service.rpc.thrift.TSConnectionInfoResp; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; import org.apache.thrift.TException; import org.apache.tsfile.enums.TSDataType; @@ -570,4 +571,54 @@ default boolean isEnableCacheLeader() { */ @Deprecated default void setEnableCacheLeader(boolean enableCacheLeader) {} + + /** + * Tests insertion up to the requested stage without writing data or changing metadata. Analysis + * and later stages require existing schema and data partitions. + */ + void testInsertTablet(Tablet tablet, TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException; + + void testInsertTablet(Tablet tablet, boolean sorted, TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException; + + void testInsertTablets(Map tablets, TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException; + + void testInsertTablets(Map tablets, boolean sorted, TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException; + + void testInsertRecords( + List deviceIds, + List times, + List> measurementsList, + List> valuesList, + TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException; + + void testInsertRecords( + List deviceIds, + List times, + List> measurementsList, + List> typesList, + List> valuesList, + TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException; + + void testInsertRecord( + String deviceId, + long time, + List measurements, + List values, + TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException; + + void testInsertRecord( + String deviceId, + long time, + List measurements, + List types, + List values, + TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException; } diff --git a/iotdb-client/isession/src/main/java/org/apache/iotdb/isession/ITableSession.java b/iotdb-client/isession/src/main/java/org/apache/iotdb/isession/ITableSession.java index 75a37f8384719..e69155693170d 100644 --- a/iotdb-client/isession/src/main/java/org/apache/iotdb/isession/ITableSession.java +++ b/iotdb-client/isession/src/main/java/org/apache/iotdb/isession/ITableSession.java @@ -21,6 +21,7 @@ import org.apache.iotdb.rpc.IoTDBConnectionException; import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; import org.apache.tsfile.write.record.Tablet; @@ -46,6 +47,34 @@ public interface ITableSession extends AutoCloseable { */ void insert(Tablet tablet) throws StatementExecutionException, IoTDBConnectionException; + /** + * Tests receiving a table-model tablet without inserting data or changing metadata. + * + * @param tablet the tablet to test + * @throws StatementExecutionException if the server rejects the request or does not support + * staged tests + * @throws IoTDBConnectionException if the connection fails + */ + default void testInsert(Tablet tablet) + throws StatementExecutionException, IoTDBConnectionException { + testInsert(tablet, TestInsertStage.UNTIL_RPC_PROCESSED); + } + + /** + * Tests a table-model tablet up to the requested stage, without inserting data or changing + * metadata. Analysis and later stages require existing schema, devices and data partitions, and + * must not require attribute updates. A successful return acknowledges completion of the + * requested stage. Unsupported servers fail rather than falling back to a normal insertion. + * + * @param tablet the tablet to test + * @param stage the inclusive completion boundary + * @throws StatementExecutionException if a stage fails or the server does not support staged + * tests + * @throws IoTDBConnectionException if the connection fails + */ + void testInsert(Tablet tablet, TestInsertStage stage) + throws StatementExecutionException, IoTDBConnectionException; + /** * Executes a non-query SQL statement, such as a DDL or DML command. * diff --git a/iotdb-client/session/src/main/i18n/en/org/apache/iotdb/session/i18n/SessionMessages.java b/iotdb-client/session/src/main/i18n/en/org/apache/iotdb/session/i18n/SessionMessages.java index 280a8414d6e8e..6f49c371dc3c1 100644 --- a/iotdb-client/session/src/main/i18n/en/org/apache/iotdb/session/i18n/SessionMessages.java +++ b/iotdb-client/session/src/main/i18n/en/org/apache/iotdb/session/i18n/SessionMessages.java @@ -21,6 +21,18 @@ public final class SessionMessages { + public static final String EXCEPTION_SERVER_DID_NOT_ACKNOWLEDGE_THE_REQUESTED_TEST_INSERTION_STAGE_41067D1C = + "Server did not acknowledge the requested test insertion stage"; + + public static final String MESSAGE_SERVER_DOES_NOT_SUPPORT_STAGED_TEST_INSERTION_0127CF25 = + "Server does not support staged test insertion"; + + public static final String EXCEPTION_TEST_INSERTION_HAS_NO_NON_NULL_VALUES_40F5D116 = + "Test insertion has no non-null values"; + + public static final String EXCEPTION_STAGE_9A8C2B9D = + "stage"; + public static final String EXCEPTION_INTERNAL_NODE_SUPPLIER_MUST_NOT_BE_NULL_C5CAF392 = "Internal node supplier must not be null"; diff --git a/iotdb-client/session/src/main/i18n/zh/org/apache/iotdb/session/i18n/SessionMessages.java b/iotdb-client/session/src/main/i18n/zh/org/apache/iotdb/session/i18n/SessionMessages.java index cee0512a23a05..7ce3ef704260e 100644 --- a/iotdb-client/session/src/main/i18n/zh/org/apache/iotdb/session/i18n/SessionMessages.java +++ b/iotdb-client/session/src/main/i18n/zh/org/apache/iotdb/session/i18n/SessionMessages.java @@ -21,6 +21,18 @@ public final class SessionMessages { + public static final String EXCEPTION_SERVER_DID_NOT_ACKNOWLEDGE_THE_REQUESTED_TEST_INSERTION_STAGE_41067D1C = + "服务端未确认完成请求的测试写入阶段"; + + public static final String MESSAGE_SERVER_DOES_NOT_SUPPORT_STAGED_TEST_INSERTION_0127CF25 = + "服务端不支持分阶段测试写入"; + + public static final String EXCEPTION_TEST_INSERTION_HAS_NO_NON_NULL_VALUES_40F5D116 = + "测试写入没有非空值"; + + public static final String EXCEPTION_STAGE_9A8C2B9D = + "stage"; + public static final String EXCEPTION_INTERNAL_NODE_SUPPLIER_MUST_NOT_BE_NULL_C5CAF392 = "内部节点 supplier 不能为空"; diff --git a/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java b/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java index d8bcce5e13def..02fbb80521602 100644 --- a/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java +++ b/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java @@ -56,7 +56,9 @@ import org.apache.iotdb.service.rpc.thrift.TSQueryTemplateReq; import org.apache.iotdb.service.rpc.thrift.TSQueryTemplateResp; import org.apache.iotdb.service.rpc.thrift.TSSetSchemaTemplateReq; +import org.apache.iotdb.service.rpc.thrift.TSTestInsertReq; import org.apache.iotdb.service.rpc.thrift.TSUnsetSchemaTemplateReq; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; import org.apache.iotdb.session.i18n.SessionMessages; import org.apache.iotdb.session.rpccompress.TabletEncoder; import org.apache.iotdb.session.template.MeasurementNode; @@ -2899,6 +2901,20 @@ private void insertTabletInternal(Tablet tablet, TSInsertTabletReq request) } } + /** + * Tests a table-model tablet without writing data or changing metadata. Analysis and later stages + * require existing schema, devices and partitions, and must not require attribute updates. + */ + public void testInsertRelationalTablet(Tablet tablet, TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException { + Objects.requireNonNull(stage, SessionMessages.EXCEPTION_STAGE_9A8C2B9D); + TSInsertTabletReq request = genTSInsertTabletReq(tablet, false, false); + request.setWriteToTable(true); + request.setColumnCategories(toEnumOrdinalsAsBytes(tablet.getColumnTypes())); + getDefaultSessionConnection() + .testInsert(new TSTestInsertReq(0, stage.getValue()).setTablet(request)); + } + /** * insert a relational Tablet. Note: This method is for internal use only, we do not guarantee * compatibility with subsequent versions. @@ -3719,6 +3735,133 @@ public void testInsertRecord( getDefaultSessionConnection().testInsertRecord(request); } + /** Test insertion up to the requested stage without writing data or metadata. */ + @Override + public void testInsertTablet(Tablet tablet, TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException { + testInsertTablet(tablet, false, stage); + } + + /** Test insertion up to the requested stage without writing data or metadata. */ + @Override + public void testInsertTablet(Tablet tablet, boolean sorted, TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException { + Objects.requireNonNull(stage, SessionMessages.EXCEPTION_STAGE_9A8C2B9D); + TSInsertTabletReq request = genTSInsertTabletReq(tablet, sorted, false); + getDefaultSessionConnection() + .testInsert(new TSTestInsertReq(0, stage.getValue()).setTablet(request)); + } + + /** Test insertion up to the requested stage without writing data or metadata. */ + @Override + public void testInsertTablets(Map tablets, TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException { + testInsertTablets(tablets, false, stage); + } + + /** Test insertion up to the requested stage without writing data or metadata. */ + @Override + public void testInsertTablets(Map tablets, boolean sorted, TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException { + Objects.requireNonNull(stage, SessionMessages.EXCEPTION_STAGE_9A8C2B9D); + TSInsertTabletsReq request = + genTSInsertTabletsReq(new ArrayList<>(tablets.values()), sorted, false); + getDefaultSessionConnection() + .testInsert(new TSTestInsertReq(0, stage.getValue()).setTablets(request)); + } + + /** Test insertion up to the requested stage without writing data or metadata. */ + @Override + public void testInsertRecords( + List deviceIds, + List times, + List> measurementsList, + List> valuesList, + TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException { + Objects.requireNonNull(stage, SessionMessages.EXCEPTION_STAGE_9A8C2B9D); + TSInsertStringRecordsReq request; + try { + request = + filterAndGenTSInsertStringRecordsReq( + deviceIds, times, measurementsList, valuesList, false); + } catch (NoValidValueException e) { + throw new StatementExecutionException( + SessionMessages.EXCEPTION_TEST_INSERTION_HAS_NO_NON_NULL_VALUES_40F5D116); + } + + getDefaultSessionConnection() + .testInsert(new TSTestInsertReq(0, stage.getValue()).setStringRecords(request)); + } + + /** Test insertion up to the requested stage without writing data or metadata. */ + @Override + public void testInsertRecords( + List deviceIds, + List times, + List> measurementsList, + List> typesList, + List> valuesList, + TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException { + Objects.requireNonNull(stage, SessionMessages.EXCEPTION_STAGE_9A8C2B9D); + TSInsertRecordsReq request; + try { + request = + filterAndGenTSInsertRecordsReq( + deviceIds, times, measurementsList, typesList, valuesList, false); + } catch (NoValidValueException e) { + throw new StatementExecutionException( + SessionMessages.EXCEPTION_TEST_INSERTION_HAS_NO_NON_NULL_VALUES_40F5D116); + } + + getDefaultSessionConnection() + .testInsert(new TSTestInsertReq(0, stage.getValue()).setRecords(request)); + } + + /** Test insertion up to the requested stage without writing data or metadata. */ + @Override + public void testInsertRecord( + String deviceId, + long time, + List measurements, + List values, + TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException { + Objects.requireNonNull(stage, SessionMessages.EXCEPTION_STAGE_9A8C2B9D); + TSInsertStringRecordReq request; + try { + request = filterAndGenTSInsertStringRecordReq(deviceId, time, measurements, values, false); + } catch (NoValidValueException e) { + throw new StatementExecutionException( + SessionMessages.EXCEPTION_TEST_INSERTION_HAS_NO_NON_NULL_VALUES_40F5D116); + } + getDefaultSessionConnection() + .testInsert(new TSTestInsertReq(0, stage.getValue()).setStringRecord(request)); + } + + /** Test insertion up to the requested stage without writing data or metadata. */ + @Override + public void testInsertRecord( + String deviceId, + long time, + List measurements, + List types, + List values, + TestInsertStage stage) + throws IoTDBConnectionException, StatementExecutionException { + Objects.requireNonNull(stage, SessionMessages.EXCEPTION_STAGE_9A8C2B9D); + TSInsertRecordReq request; + try { + request = filterAndGenTSInsertRecordReq(deviceId, time, measurements, types, values, false); + } catch (NoValidValueException e) { + throw new StatementExecutionException( + SessionMessages.EXCEPTION_TEST_INSERTION_HAS_NO_NON_NULL_VALUES_40F5D116); + } + getDefaultSessionConnection() + .testInsert(new TSTestInsertReq(0, stage.getValue()).setRecord(request)); + } + /** * delete a timeseries, including data and schema * diff --git a/iotdb-client/session/src/main/java/org/apache/iotdb/session/SessionConnection.java b/iotdb-client/session/src/main/java/org/apache/iotdb/session/SessionConnection.java index ca8862cf1c989..3e7b2b354db0b 100644 --- a/iotdb-client/session/src/main/java/org/apache/iotdb/session/SessionConnection.java +++ b/iotdb-client/session/src/main/java/org/apache/iotdb/session/SessionConnection.java @@ -67,10 +67,13 @@ import org.apache.iotdb.service.rpc.thrift.TSRawDataQueryReq; import org.apache.iotdb.service.rpc.thrift.TSSetSchemaTemplateReq; import org.apache.iotdb.service.rpc.thrift.TSSetTimeZoneReq; +import org.apache.iotdb.service.rpc.thrift.TSTestInsertReq; +import org.apache.iotdb.service.rpc.thrift.TSTestInsertResp; import org.apache.iotdb.service.rpc.thrift.TSUnsetSchemaTemplateReq; import org.apache.iotdb.session.i18n.SessionMessages; import org.apache.iotdb.session.util.SessionUtils; +import org.apache.thrift.TApplicationException; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TCompactProtocol; @@ -1072,6 +1075,39 @@ private TSStatus deleteDataInternal(TSDeleteDataReq request) throws TException { return client.deleteData(request); } + protected void testInsert(TSTestInsertReq request) + throws IoTDBConnectionException, StatementExecutionException { + RetryResult result = + callWithRetryAndReconnect( + () -> { + request.setSessionId(sessionId); + try { + return client.testInsert(request); + } catch (TApplicationException e) { + if (e.getType() != TApplicationException.UNKNOWN_METHOD) { + throw e; + } + return new TSTestInsertResp( + new TSStatus(TSStatusCode.EXECUTE_STATEMENT_ERROR.getStatusCode()) + .setMessage( + SessionMessages + .MESSAGE_SERVER_DOES_NOT_SUPPORT_STAGED_TEST_INSERTION_0127CF25), + 0); + } + }, + TSTestInsertResp::getStatus); + if (result.getException() != null) { + throw new IoTDBConnectionException(result.getException()); + } + TSTestInsertResp response = result.getResult(); + RpcUtils.verifySuccess(response.getStatus()); + if (response.getCompletedStage() != request.getStage()) { + throw new StatementExecutionException( + SessionMessages + .EXCEPTION_SERVER_DID_NOT_ACKNOWLEDGE_THE_REQUESTED_TEST_INSERTION_STAGE_41067D1C); + } + } + protected void testInsertRecord(TSInsertStringRecordReq request) throws IoTDBConnectionException, StatementExecutionException { final TSStatus status = diff --git a/iotdb-client/session/src/main/java/org/apache/iotdb/session/TableSession.java b/iotdb-client/session/src/main/java/org/apache/iotdb/session/TableSession.java index 059fdea346948..e0b5dd20b9e94 100644 --- a/iotdb-client/session/src/main/java/org/apache/iotdb/session/TableSession.java +++ b/iotdb-client/session/src/main/java/org/apache/iotdb/session/TableSession.java @@ -23,6 +23,7 @@ import org.apache.iotdb.isession.SessionDataSet; import org.apache.iotdb.rpc.IoTDBConnectionException; import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; import org.apache.tsfile.write.record.Tablet; @@ -34,6 +35,12 @@ public class TableSession implements ITableSession { this.session = session; } + @Override + public void testInsert(Tablet tablet, TestInsertStage stage) + throws StatementExecutionException, IoTDBConnectionException { + session.testInsertRelationalTablet(tablet, stage); + } + @Override public void insert(Tablet tablet) throws StatementExecutionException, IoTDBConnectionException { session.insertRelationalTablet(tablet); diff --git a/iotdb-client/session/src/main/java/org/apache/iotdb/session/pool/TableSessionWrapper.java b/iotdb-client/session/src/main/java/org/apache/iotdb/session/pool/TableSessionWrapper.java index 38b927e386780..5ee529c252b33 100644 --- a/iotdb-client/session/src/main/java/org/apache/iotdb/session/pool/TableSessionWrapper.java +++ b/iotdb-client/session/src/main/java/org/apache/iotdb/session/pool/TableSessionWrapper.java @@ -23,6 +23,7 @@ import org.apache.iotdb.isession.SessionDataSet; import org.apache.iotdb.rpc.IoTDBConnectionException; import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; import org.apache.iotdb.session.Session; import org.apache.iotdb.session.i18n.SessionMessages; @@ -56,6 +57,19 @@ protected TableSessionWrapper(Session session, SessionPool sessionPool) { this.closed = new AtomicBoolean(false); } + @Override + public synchronized void testInsert(Tablet tablet, TestInsertStage stage) + throws StatementExecutionException, IoTDBConnectionException { + try { + session.testInsertRelationalTablet(tablet, stage); + } catch (IoTDBConnectionException e) { + sessionPool.cleanSessionAndMayThrowConnectionException(session); + closed.set(true); + session = null; + throw e; + } + } + @Override public synchronized void insert(Tablet tablet) throws StatementExecutionException, IoTDBConnectionException { diff --git a/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java b/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java index 9faa0c6efb6a2..43d7ffa4679db 100644 --- a/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java +++ b/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionConnectionTest.java @@ -53,8 +53,13 @@ import org.apache.iotdb.service.rpc.thrift.TSQueryTemplateReq; import org.apache.iotdb.service.rpc.thrift.TSQueryTemplateResp; import org.apache.iotdb.service.rpc.thrift.TSSetSchemaTemplateReq; +import org.apache.iotdb.service.rpc.thrift.TSTestInsertReq; +import org.apache.iotdb.service.rpc.thrift.TSTestInsertResp; import org.apache.iotdb.service.rpc.thrift.TSUnsetSchemaTemplateReq; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; +import org.apache.iotdb.session.i18n.SessionMessages; +import org.apache.thrift.TApplicationException; import org.apache.thrift.TException; import org.apache.thrift.transport.TTransport; import org.junit.After; @@ -82,6 +87,50 @@ public class SessionConnectionTest { @Mock private Session session; + @Test + public void testOldServerRejectsStagedInsertionWithoutFallback() throws Exception { + Mockito.when(client.testInsert(any())) + .thenThrow(new TApplicationException(TApplicationException.UNKNOWN_METHOD, "testInsert")); + StatementExecutionException error = + Assert.assertThrows( + StatementExecutionException.class, + () -> + sessionConnection.testInsert( + new TSTestInsertReq(0, TestInsertStage.UNTIL_PLANNED.getValue()))); + Assert.assertTrue( + error + .getMessage() + .contains( + SessionMessages.MESSAGE_SERVER_DOES_NOT_SUPPORT_STAGED_TEST_INSERTION_0127CF25)); + Mockito.verify(client, Mockito.times(1)).testInsert(any()); + Mockito.verify(client, Mockito.never()).insertTablet(any()); + Mockito.verify(client, Mockito.never()).testInsertTablet(any()); + } + + @Test + public void testStagedInsertionAcknowledgement() throws Exception { + TSTestInsertReq request = new TSTestInsertReq(0, TestInsertStage.UNTIL_PLANNED.getValue()); + Mockito.when(client.testInsert(any())) + .thenReturn( + new TSTestInsertResp( + new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode()), request.getStage())); + sessionConnection.testInsert(request); + Mockito.verify(client).testInsert(request); + Mockito.verify(client, Mockito.never()).insertTablet(any()); + Mockito.when(client.testInsert(any())) + .thenReturn( + new TSTestInsertResp( + new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode()), + TestInsertStage.UNTIL_DECODED.getValue())); + Assert.assertThrows( + StatementExecutionException.class, () -> sessionConnection.testInsert(request)); + Mockito.when(client.testInsert(any())) + .thenReturn( + new TSTestInsertResp(new TSStatus(TSStatusCode.METADATA_ERROR.getStatusCode()), 0)); + Assert.assertThrows( + StatementExecutionException.class, () -> sessionConnection.testInsert(request)); + } + @Before public void setUp() throws IoTDBConnectionException, StatementExecutionException, TException { MockitoAnnotations.initMocks(this); diff --git a/iotdb-client/session/src/test/java/org/apache/iotdb/session/TableSessionTest.java b/iotdb-client/session/src/test/java/org/apache/iotdb/session/TableSessionTest.java new file mode 100644 index 0000000000000..45dc27b0266a5 --- /dev/null +++ b/iotdb-client/session/src/test/java/org/apache/iotdb/session/TableSessionTest.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.session; + +import org.apache.iotdb.isession.ITableSession; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; + +import org.apache.tsfile.write.record.Tablet; +import org.junit.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +public class TableSessionTest { + @Test + public void testInsertionStagesUseOnlyTheTableTestRpc() throws Exception { + Session delegate = mock(Session.class); + Tablet tablet = mock(Tablet.class); + try (ITableSession session = new TableSession(delegate)) { + session.testInsert(tablet); + for (TestInsertStage stage : TestInsertStage.values()) { + session.testInsert(tablet, stage); + } + } + for (TestInsertStage stage : TestInsertStage.values()) { + verify(delegate, times(stage == TestInsertStage.UNTIL_RPC_PROCESSED ? 2 : 1)) + .testInsertRelationalTablet(tablet, stage); + } + verify(delegate, never()).insertRelationalTablet(tablet); + verify(delegate).close(); + } +} diff --git a/iotdb-client/session/src/test/java/org/apache/iotdb/session/pool/TableSessionWrapperTest.java b/iotdb-client/session/src/test/java/org/apache/iotdb/session/pool/TableSessionWrapperTest.java new file mode 100644 index 0000000000000..6a128febb27c0 --- /dev/null +++ b/iotdb-client/session/src/test/java/org/apache/iotdb/session/pool/TableSessionWrapperTest.java @@ -0,0 +1,102 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.session.pool; + +import org.apache.iotdb.isession.ITableSession; +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; +import org.apache.iotdb.session.Session; + +import org.apache.tsfile.write.record.Tablet; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +public class TableSessionWrapperTest { + @Test + public void testDefaultAndExplicitStagesReturnConnectionOnlyOnce() throws Exception { + Session delegate = mock(Session.class); + SessionPool pool = mock(SessionPool.class); + Tablet tablet = mock(Tablet.class); + ITableSession session = new TableSessionWrapper(delegate, pool); + session.testInsert(tablet); + session.testInsert(tablet, TestInsertStage.UNTIL_PLANNED); + session.close(); + session.close(); + verify(delegate).testInsertRelationalTablet(tablet, TestInsertStage.UNTIL_RPC_PROCESSED); + verify(delegate).testInsertRelationalTablet(tablet, TestInsertStage.UNTIL_PLANNED); + verify(delegate, never()).insertRelationalTablet(any()); + verify(pool).putBack(delegate); + verify(pool, never()).cleanSessionAndMayThrowConnectionException(any()); + } + + @Test + public void testConnectionFailureDiscardsSessionWithoutMaskingTheErrorOnClose() throws Exception { + Session delegate = mock(Session.class); + SessionPool pool = mock(SessionPool.class); + Tablet tablet = mock(Tablet.class); + IoTDBConnectionException failure = new IoTDBConnectionException("disconnected"); + doThrow(failure) + .when(delegate) + .testInsertRelationalTablet(tablet, TestInsertStage.UNTIL_PLANNED); + IoTDBConnectionException actual = + assertThrows( + IoTDBConnectionException.class, + () -> { + try (ITableSession session = new TableSessionWrapper(delegate, pool)) { + session.testInsert(tablet, TestInsertStage.UNTIL_PLANNED); + } + }); + assertSame(failure, actual); + assertEquals(0, actual.getSuppressed().length); + verify(pool).cleanSessionAndMayThrowConnectionException(delegate); + verify(pool, never()).putBack(any()); + } + + @Test + public void testStatementFailurePreservesConnectionForReuse() throws Exception { + Session delegate = mock(Session.class); + SessionPool pool = mock(SessionPool.class); + Tablet tablet = mock(Tablet.class); + StatementExecutionException failure = new StatementExecutionException("missing partition"); + doThrow(failure) + .when(delegate) + .testInsertRelationalTablet(tablet, TestInsertStage.UNTIL_ANALYZED); + try (ITableSession session = new TableSessionWrapper(delegate, pool)) { + assertSame( + failure, + assertThrows( + StatementExecutionException.class, + () -> session.testInsert(tablet, TestInsertStage.UNTIL_ANALYZED))); + session.testInsert(tablet); + } + verify(delegate).testInsertRelationalTablet(tablet, TestInsertStage.UNTIL_RPC_PROCESSED); + verify(pool, never()).cleanSessionAndMayThrowConnectionException(any()); + verify(pool).putBack(delegate); + } +} diff --git a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java index 963e9deceaa59..45982b1df23d9 100644 --- a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java +++ b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java @@ -21,6 +21,9 @@ /** Compile-time i18n constants for DataNode misc subsystems (English). */ public final class DataNodeMiscMessages { + + public static final String MESSAGE_TEST_INSERTION_REQUIRES_A_KNOWN_STAGE_AND_EXACTLY_ONE_INSERTION_PAYLOAD_B0F3D171 = + "Test insertion requires a known stage and exactly one insertion payload"; public static final String LOG_FAILED_TO_AUTHORIZE_CQ_ARG_FOR_USER_ARG_ARG_B436A81F = "Failed to authorize CQ {} for user {}: {}"; diff --git a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java index 378a6381dcc99..aae3fe5332091 100644 --- a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java +++ b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java @@ -20,6 +20,27 @@ package org.apache.iotdb.db.i18n; public final class DataNodeQueryMessages { + + public static final String EXCEPTION_TEST_INSERTION_REQUIRES_AN_EXISTING_DATA_PARTITION_FOR_ARG_AT_ARG_A5AABFF2 = + "Test insertion requires an existing data partition for %s at %s"; + + public static final String EXCEPTION_INVALID_TEST_INSERTION_ACKNOWLEDGEMENT_FROM_ARG_E2F722A6 = + "Invalid test insertion acknowledgement from %s"; + + public static final String MESSAGE_TEST_INSERTION_TARGET_REGION_DOES_NOT_EXIST_A4645EC1 = + "Test insertion target region does not exist"; + + public static final String MESSAGE_TEST_INSERTION_ACCEPTS_ONLY_INSERTION_PLANS_TARGETING_DATA_REGIONS_319E02A6 = + "Test insertion accepts only insertion plans targeting data regions"; + + public static final String EXCEPTION_TEST_INSERTION_REQUIRES_AN_EXISTING_DATABASE_FOR_EVERY_DEVICE_22548137 = + "Test insertion requires an existing database for every device"; + + public static final String EXCEPTION_TEST_INSERTION_HAS_NO_EXECUTABLE_INSERTION_PLAN_803B3A76 = + "Test insertion has no executable insertion plan"; + + public static final String EXCEPTION_TEST_INSERTION_REQUIRES_EXISTING_SCHEMA_DEVICES_AND_ATTRIBUTES_METADATA_CHANGES_ARE_NOT_ALLOWED_8CF4EF1B = + "Test insertion requires existing schema, devices and attributes; metadata changes are not allowed"; public static final String EXCEPTION_QUERY_ATTEMPT_ARG_IS_CLOSED_12143E89 = "Query attempt %s is closed."; public static final String EXCEPTION_QUERY_ATTEMPT_ARG_ADMISSION_EXPIRED_DEADLINE_ARG_NS_NOW_ARG_NS_16A9846C = "Query attempt %s admission expired: deadline=%d ns, now=%d ns."; public static final String EXCEPTION_INVALID_QUERY_ADMISSION_ISSUER_FOR_ATTEMPT_ARG_9D1C4E9C = "Invalid query admission issuer for attempt %s."; diff --git a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java index 334010c873919..f9fa679af8e65 100644 --- a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java +++ b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java @@ -21,6 +21,9 @@ /** 编译时国际化常量 - DataNode 杂项子系统(中文)。 */ public final class DataNodeMiscMessages { + + public static final String MESSAGE_TEST_INSERTION_REQUIRES_A_KNOWN_STAGE_AND_EXACTLY_ONE_INSERTION_PAYLOAD_B0F3D171 = + "测试写入需要有效阶段且只能包含一个写入载荷"; public static final String LOG_FAILED_TO_AUTHORIZE_CQ_ARG_FOR_USER_ARG_ARG_B436A81F = "CQ {} 的用户 {} 鉴权失败:{}"; diff --git a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java index 02cf8edc0a469..51f73cc750486 100644 --- a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java +++ b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java @@ -20,6 +20,27 @@ package org.apache.iotdb.db.i18n; public final class DataNodeQueryMessages { + + public static final String EXCEPTION_TEST_INSERTION_REQUIRES_AN_EXISTING_DATA_PARTITION_FOR_ARG_AT_ARG_A5AABFF2 = + "测试写入要求设备 %s 在时间 %s 的数据分区已存在"; + + public static final String EXCEPTION_INVALID_TEST_INSERTION_ACKNOWLEDGEMENT_FROM_ARG_E2F722A6 = + "来自 %s 的测试写入确认无效"; + + public static final String MESSAGE_TEST_INSERTION_TARGET_REGION_DOES_NOT_EXIST_A4645EC1 = + "测试写入的目标 Region 不存在"; + + public static final String MESSAGE_TEST_INSERTION_ACCEPTS_ONLY_INSERTION_PLANS_TARGETING_DATA_REGIONS_319E02A6 = + "测试写入仅接受以 DataRegion 为目标的写入计划"; + + public static final String EXCEPTION_TEST_INSERTION_REQUIRES_AN_EXISTING_DATABASE_FOR_EVERY_DEVICE_22548137 = + "测试写入要求每个设备所属的数据库已存在"; + + public static final String EXCEPTION_TEST_INSERTION_HAS_NO_EXECUTABLE_INSERTION_PLAN_803B3A76 = + "测试写入没有可执行的写入计划"; + + public static final String EXCEPTION_TEST_INSERTION_REQUIRES_EXISTING_SCHEMA_DEVICES_AND_ATTRIBUTES_METADATA_CHANGES_ARE_NOT_ALLOWED_8CF4EF1B = + "测试写入要求 schema、设备和属性已存在;不允许修改元数据"; public static final String EXCEPTION_QUERY_ATTEMPT_ARG_IS_CLOSED_12143E89 = "查询执行轮次 %s 已关闭。"; public static final String EXCEPTION_QUERY_ATTEMPT_ARG_ADMISSION_EXPIRED_DEADLINE_ARG_NS_NOW_ARG_NS_16A9846C = "查询执行轮次 %s 的接收凭证已过期:截止时间=%d ns,当前时间=%d ns。"; public static final String EXCEPTION_INVALID_QUERY_ADMISSION_ISSUER_FOR_ATTEMPT_ARG_9D1C4E9C = "查询执行轮次 %s 的接收凭证签发节点进程不匹配。"; diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java index e6eedc4b636a9..2f8761c557f82 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java @@ -110,6 +110,7 @@ import org.apache.iotdb.db.queryengine.plan.statement.StatementType; import org.apache.iotdb.db.queryengine.plan.statement.component.Ordering; import org.apache.iotdb.db.queryengine.plan.statement.crud.DeleteDataStatement; +import org.apache.iotdb.db.queryengine.plan.statement.crud.InsertBaseStatement; import org.apache.iotdb.db.queryengine.plan.statement.crud.InsertMultiTabletsStatement; import org.apache.iotdb.db.queryengine.plan.statement.crud.InsertRowStatement; import org.apache.iotdb.db.queryengine.plan.statement.crud.InsertRowsOfOneDeviceStatement; @@ -200,9 +201,12 @@ import org.apache.iotdb.service.rpc.thrift.TSRawDataQueryReq; import org.apache.iotdb.service.rpc.thrift.TSSetSchemaTemplateReq; import org.apache.iotdb.service.rpc.thrift.TSSetTimeZoneReq; +import org.apache.iotdb.service.rpc.thrift.TSTestInsertReq; +import org.apache.iotdb.service.rpc.thrift.TSTestInsertResp; import org.apache.iotdb.service.rpc.thrift.TSUnsetSchemaTemplateReq; import org.apache.iotdb.service.rpc.thrift.TSyncIdentityInfo; import org.apache.iotdb.service.rpc.thrift.TSyncTransportMetaInfo; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; import io.airlift.units.Duration; import org.apache.thrift.TException; @@ -2943,6 +2947,117 @@ public TSStatus testInsertTablet(TSInsertTabletReq req) { return RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS); } + @Override + public TSTestInsertResp testInsert(TSTestInsertReq req) { + try { + IClientSession session = SESSION_MANAGER.getCurrSessionAndUpdateIdleTime(); + if (!SESSION_MANAGER.checkLogin(session)) { + return new TSTestInsertResp(getNotLoggedInStatus(), 0); + } + TestInsertStage stage = TestInsertStage.findByValue(req.getStage()); + int payloads = + (req.isSetTablet() ? 1 : 0) + + (req.isSetTablets() ? 1 : 0) + + (req.isSetRecord() ? 1 : 0) + + (req.isSetStringRecord() ? 1 : 0) + + (req.isSetRecords() ? 1 : 0) + + (req.isSetRecordsOfOneDevice() ? 1 : 0) + + (req.isSetStringRecords() ? 1 : 0); + if (stage == null || payloads != 1) { + return new TSTestInsertResp( + RpcUtils.getStatus( + TSStatusCode.ILLEGAL_PARAMETER, + DataNodeMiscMessages + .MESSAGE_TEST_INSERTION_REQUIRES_A_KNOWN_STAGE_AND_EXACTLY_ONE_INSERTION_PAYLOAD_B0F3D171), + 0); + } + if (stage == TestInsertStage.UNTIL_RPC_PROCESSED) { + return new TSTestInsertResp( + RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS), req.getStage()); + } + InsertBaseStatement statement; + if (req.isSetTablet()) { + if (!req.getTablet().isWriteToTable()) { + req.getTablet() + .setMeasurements( + PathUtils.checkIsLegalSingleMeasurementsAndUpdate( + req.getTablet().getMeasurements())); + } + statement = StatementGenerator.createStatement(req.getTablet()); + } else if (req.isSetTablets()) { + req.getTablets() + .setMeasurementsList( + PathUtils.checkIsLegalSingleMeasurementListsAndUpdate( + req.getTablets().getMeasurementsList())); + statement = StatementGenerator.createStatement(req.getTablets()); + } else if (req.isSetRecord()) { + if (!req.getRecord().isIsWriteToTable()) { + req.getRecord() + .setMeasurements( + PathUtils.checkIsLegalSingleMeasurementsAndUpdate( + req.getRecord().getMeasurements())); + } + statement = StatementGenerator.createStatement(req.getRecord()); + } else if (req.isSetStringRecord()) { + req.getStringRecord() + .setMeasurements( + PathUtils.checkIsLegalSingleMeasurementsAndUpdate( + req.getStringRecord().getMeasurements())); + statement = StatementGenerator.createStatement(req.getStringRecord()); + } else if (req.isSetRecords()) { + req.getRecords() + .setMeasurementsList( + PathUtils.checkIsLegalSingleMeasurementListsAndUpdate( + req.getRecords().getMeasurementsList())); + statement = StatementGenerator.createStatement(req.getRecords()); + } else if (req.isSetRecordsOfOneDevice()) { + req.getRecordsOfOneDevice() + .setMeasurementsList( + PathUtils.checkIsLegalSingleMeasurementListsAndUpdate( + req.getRecordsOfOneDevice().getMeasurementsList())); + statement = StatementGenerator.createStatement(req.getRecordsOfOneDevice()); + } else { + req.getStringRecords() + .setMeasurementsList( + PathUtils.checkIsLegalSingleMeasurementListsAndUpdate( + req.getStringRecords().getMeasurementsList())); + statement = StatementGenerator.createStatement(req.getStringRecords()); + } + if (stage == TestInsertStage.UNTIL_DECODED) { + return new TSTestInsertResp( + RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS), req.getStage()); + } + if (!statement.isWriteToTable()) { + TSStatus permission = + AuthorityChecker.checkAuthority( + statement, + new TreeAccessCheckContext( + session.getUserId(), session.getUsername(), session.getClientAddress())); + if (permission.getCode() != TSStatusCode.SUCCESS_STATUS.getStatusCode()) { + return new TSTestInsertResp(permission, 0); + } + } + TSStatus status = + COORDINATOR.testInsert( + statement, + stage, + SESSION_MANAGER.requestQueryId(), + SESSION_MANAGER.getSessionInfo(session), + relationSqlParser, + metadata, + partitionFetcher, + schemaFetcher); + return new TSTestInsertResp( + status, + status.getCode() == TSStatusCode.SUCCESS_STATUS.getStatusCode() ? req.getStage() : 0); + } catch (Exception e) { + return new TSTestInsertResp( + onQueryException(e, "testInsert", TSStatusCode.EXECUTE_STATEMENT_ERROR), 0); + } finally { + SESSION_MANAGER.updateIdleTime(); + } + } + @Override public TSStatus testInsertTablets(TSInsertTabletsReq req) { LOGGER.debug(DataNodeMiscMessages.TEST_INSERT_BATCH_RECEIVE); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/DataNodeInternalRPCServiceImpl.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/DataNodeInternalRPCServiceImpl.java index 1069eb2b7b7fd..f538bf4183d5f 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/DataNodeInternalRPCServiceImpl.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/DataNodeInternalRPCServiceImpl.java @@ -154,6 +154,7 @@ import org.apache.iotdb.db.queryengine.plan.analyze.schema.ISchemaFetcher; import org.apache.iotdb.db.queryengine.plan.execution.ExecutionResult; import org.apache.iotdb.db.queryengine.plan.execution.IQueryExecution; +import org.apache.iotdb.db.queryengine.plan.execution.TestInsertPlanValidator; import org.apache.iotdb.db.queryengine.plan.expression.Expression; import org.apache.iotdb.db.queryengine.plan.expression.binary.GreaterEqualExpression; import org.apache.iotdb.db.queryengine.plan.expression.binary.LessThanExpression; @@ -605,6 +606,11 @@ public TSendFragmentInstanceResp sendFragmentInstance(final TSendFragmentInstanc } } + @Override + public TSendBatchPlanNodeResp testInsertPlanNodes(TSendBatchPlanNodeReq req) { + return TestInsertPlanValidator.validate(req); + } + @Override public TSendBatchPlanNodeResp sendBatchPlanNode(TSendBatchPlanNodeReq req) { List responses = diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/common/MPPQueryContext.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/common/MPPQueryContext.java index e2b84a0960b61..4972fe8015fa2 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/common/MPPQueryContext.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/common/MPPQueryContext.java @@ -27,6 +27,7 @@ import org.apache.iotdb.commons.audit.AuditLogOperation; import org.apache.iotdb.commons.audit.IAuditEntity; import org.apache.iotdb.commons.auth.entity.PrivilegeType; +import org.apache.iotdb.commons.exception.SemanticException; import org.apache.iotdb.commons.queryengine.common.SessionInfo; import org.apache.iotdb.commons.queryengine.plan.relational.analyzer.NodeRef; import org.apache.iotdb.commons.queryengine.plan.relational.metadata.ColumnSchema; @@ -209,6 +210,24 @@ public enum ExplainType { ConcurrentHashMap.newKeySet(); private final AtomicInteger externalTsFileQueryResourceIndex = new AtomicInteger(); + private boolean testInsert; + + public boolean isTestInsert() { + return testInsert; + } + + public void setTestInsert(boolean testInsert) { + this.testInsert = testInsert; + } + + public void checkSchemaModificationAllowed() { + if (testInsert) { + throw new SemanticException( + DataNodeQueryMessages + .EXCEPTION_TEST_INSERTION_REQUIRES_EXISTING_SCHEMA_DEVICES_AND_ATTRIBUTES_METADATA_CHANGES_ARE_NOT_ALLOWED_8CF4EF1B); + } + } + @TestOnly public MPPQueryContext(QueryId queryId) { this.queryId = queryId; diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/Coordinator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/Coordinator.java index 32ea59c26c20d..565ce8c24fb79 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/Coordinator.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/Coordinator.java @@ -20,6 +20,7 @@ package org.apache.iotdb.db.queryengine.plan; import org.apache.iotdb.common.rpc.thrift.TEndPoint; +import org.apache.iotdb.common.rpc.thrift.TSStatus; import org.apache.iotdb.commons.client.ClientPoolFactory; import org.apache.iotdb.commons.client.IClientManager; import org.apache.iotdb.commons.client.async.AsyncDataNodeInternalServiceClient; @@ -57,17 +58,23 @@ import org.apache.iotdb.db.queryengine.common.QueryId; import org.apache.iotdb.db.queryengine.execution.QueryIdGenerator; import org.apache.iotdb.db.queryengine.execution.QueryState; +import org.apache.iotdb.db.queryengine.plan.analyze.IAnalysis; import org.apache.iotdb.db.queryengine.plan.analyze.IPartitionFetcher; import org.apache.iotdb.db.queryengine.plan.analyze.lock.DataNodeSchemaLockManager; import org.apache.iotdb.db.queryengine.plan.analyze.schema.ISchemaFetcher; import org.apache.iotdb.db.queryengine.plan.execution.ExecutionResult; import org.apache.iotdb.db.queryengine.plan.execution.IQueryExecution; import org.apache.iotdb.db.queryengine.plan.execution.QueryExecution; +import org.apache.iotdb.db.queryengine.plan.execution.TestInsertPlanValidator; import org.apache.iotdb.db.queryengine.plan.execution.config.ConfigExecution; import org.apache.iotdb.db.queryengine.plan.execution.config.TableConfigTaskVisitor; import org.apache.iotdb.db.queryengine.plan.execution.config.TreeConfigTaskVisitor; +import org.apache.iotdb.db.queryengine.plan.planner.IPlanner; import org.apache.iotdb.db.queryengine.plan.planner.LocalExecutionPlanner; import org.apache.iotdb.db.queryengine.plan.planner.TreeModelPlanner; +import org.apache.iotdb.db.queryengine.plan.planner.plan.DistributedQueryPlan; +import org.apache.iotdb.db.queryengine.plan.planner.plan.FragmentInstance; +import org.apache.iotdb.db.queryengine.plan.planner.plan.LogicalQueryPlan; import org.apache.iotdb.db.queryengine.plan.relational.metadata.Metadata; import org.apache.iotdb.db.queryengine.plan.relational.planner.PlannerContext; import org.apache.iotdb.db.queryengine.plan.relational.planner.TableModelPlanner; @@ -159,10 +166,18 @@ import org.apache.iotdb.db.queryengine.plan.relational.sql.rewrite.StatementRewriteFactory; import org.apache.iotdb.db.queryengine.plan.statement.IConfigStatement; import org.apache.iotdb.db.queryengine.plan.statement.Statement; +import org.apache.iotdb.db.queryengine.plan.statement.crud.InsertBaseStatement; import org.apache.iotdb.db.queryengine.plan.statement.metadata.pipe.ShowPipeMemoryStatement; import org.apache.iotdb.db.queryengine.plan.statement.pipe.PipeEnrichedStatement; import org.apache.iotdb.db.queryengine.udf.InternalQueryExecutor; import org.apache.iotdb.db.utils.SetThreadName; +import org.apache.iotdb.mpp.rpc.thrift.TPlanNode; +import org.apache.iotdb.mpp.rpc.thrift.TSendBatchPlanNodeReq; +import org.apache.iotdb.mpp.rpc.thrift.TSendBatchPlanNodeResp; +import org.apache.iotdb.mpp.rpc.thrift.TSendSinglePlanNodeReq; +import org.apache.iotdb.rpc.RpcUtils; +import org.apache.iotdb.rpc.TSStatusCode; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; import org.apache.thrift.TBase; import org.apache.tsfile.utils.Accountable; @@ -283,6 +298,115 @@ public class Coordinator { } } + /** Analyze and plan an insertion without scheduling any writes. */ + public TSStatus testInsert( + InsertBaseStatement statement, + TestInsertStage stage, + long queryId, + SessionInfo session, + SqlParser sqlParser, + Metadata metadata, + IPartitionFetcher partitionFetcher, + ISchemaFetcher schemaFetcher) + throws Exception { + MPPQueryContext context = + new MPPQueryContext( + "", + queryIdGenerator.createNextQueryId(), + queryId, + session, + DataNodeEndPoints.LOCAL_HOST_DATA_BLOCK_ENDPOINT, + DataNodeEndPoints.LOCAL_HOST_INTERNAL_ENDPOINT); + context.setTestInsert(true); + context.setStartTime(System.currentTimeMillis()); + context.setTimeOut(CONFIG.getQueryTimeoutThreshold()); + try { + IPlanner planner = + statement.isWriteToTable() + ? new TableModelPlanner( + statement.toRelationalStatement(context), + sqlParser, + metadata, + scheduledExecutor, + SYNC_INTERNAL_SERVICE_CLIENT_MANAGER, + ASYNC_INTERNAL_SERVICE_CLIENT_MANAGER, + statementRewrite, + logicalPlanOptimizers, + distributionPlanOptimizers, + AuthorityChecker.getAccessControl(), + dataNodeLocationSupplier, + Collections.emptyList(), + Collections.emptyMap(), + typeManager) + : new TreeModelPlanner( + statement, + executor, + scheduledExecutor, + partitionFetcher, + schemaFetcher, + SYNC_INTERNAL_SERVICE_CLIENT_MANAGER, + ASYNC_INTERNAL_SERVICE_CLIENT_MANAGER); + IAnalysis analysis = planner.analyze(context); + if (analysis.isFailed()) { + return analysis.getFailStatus(); + } + context.checkTimeOut(); + if (stage == TestInsertStage.UNTIL_ANALYZED) { + return RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS); + } + if (analysis.isFinishQueryAfterAnalyze()) { + throw new SemanticException( + DataNodeQueryMessages + .EXCEPTION_TEST_INSERTION_HAS_NO_EXECUTABLE_INSERTION_PLAN_803B3A76); + } + context.checkTimeOut(); + LogicalQueryPlan logicalPlan = planner.doLogicalPlan(analysis, context); + if (analysis.isFailed()) { + return analysis.getFailStatus(); + } + DistributedQueryPlan plan = planner.doDistributionPlan(analysis, logicalPlan, context); + context.reserveMemoryForFrontEndImmediately(); + if (stage == TestInsertStage.UNTIL_WRITE_TARGET_RECEIVED) { + for (FragmentInstance instance : plan.getInstances()) { + context.checkTimeOut(); + TSendBatchPlanNodeReq request = + new TSendBatchPlanNodeReq( + Collections.singletonList( + new TSendSinglePlanNodeReq( + new TPlanNode( + instance.getFragment().getPlanNodeTree().serializeToByteBuffer()), + instance.getRegionReplicaSet().getRegionId()))); + TEndPoint endpoint = instance.getHostDataNode().getInternalEndPoint(); + TSendBatchPlanNodeResp response; + if (DataNodeEndPoints.LOCAL_HOST_INTERNAL_ENDPOINT.equals(endpoint)) { + response = TestInsertPlanValidator.validate(request); + } else { + try (SyncDataNodeInternalServiceClient client = + SYNC_INTERNAL_SERVICE_CLIENT_MANAGER.borrowClient(endpoint)) { + response = client.testInsertPlanNodes(request); + } + } + if (response.getResponsesSize() != 1) { + throw new SemanticException( + String.format( + DataNodeQueryMessages + .EXCEPTION_INVALID_TEST_INSERTION_ACKNOWLEDGEMENT_FROM_ARG_E2F722A6, + endpoint)); + } + if (!response.getResponses().get(0).isAccepted()) { + return response.getResponses().get(0).getStatus(); + } + RpcUtils.verifySuccess(response.getResponses().get(0).getStatus()); + } + } + context.checkTimeOut(); + return RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS); + } finally { + context.releaseAllMemoryReservedForFrontEnd(); + DataNodeSchemaLockManager.getInstance().releaseReadLock(context); + } + } + private Coordinator() { this.queryExecutionMap = new ConcurrentHashMap<>(); this.typeManager = new InternalTypeManager(); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/AnalyzeVisitor.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/AnalyzeVisitor.java index c40c3e57f985a..ff3a474bbfe0c 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/AnalyzeVisitor.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/AnalyzeVisitor.java @@ -2911,7 +2911,9 @@ public Analysis visitInsertTablet( context, insertTabletStatement, () -> SchemaValidator.validate(schemaFetcher, insertTabletStatement, context), - partitionFetcher::getOrCreateDataPartition, + context.isTestInsert() + ? ClusterPartitionFetcher.getInstance()::getDataPartitionForTestInsert + : partitionFetcher::getOrCreateDataPartition, AnalyzeUtils::computeTreeDataPartitionParams, analysis, true); @@ -2946,13 +2948,17 @@ public Analysis visitInsertRow(InsertRowStatement insertRowStatement, MPPQueryCo analysis, Collections.singletonList(dataPartitionQueryParam), context.getSession().getUserName(), - partitionFetcher::getOrCreateDataPartition); + context.isTestInsert() + ? ClusterPartitionFetcher.getInstance()::getDataPartitionForTestInsert + : partitionFetcher::getOrCreateDataPartition); } else { AnalyzeUtils.analyzeDataPartition( analysis, AnalyzeUtils.computeTreeDataPartitionParams(realInsertStatement, context), context.getSession().getUserName(), - partitionFetcher::getOrCreateDataPartition); + context.isTestInsert() + ? ClusterPartitionFetcher.getInstance()::getDataPartitionForTestInsert + : partitionFetcher::getOrCreateDataPartition); } return analysis; } @@ -2978,7 +2984,9 @@ public Analysis visitInsertRows( analysis, AnalyzeUtils.computeTreeDataPartitionParams(realInsertRowsStatement, context), context.getSession().getUserName(), - partitionFetcher::getOrCreateDataPartition); + context.isTestInsert() + ? ClusterPartitionFetcher.getInstance()::getDataPartitionForTestInsert + : partitionFetcher::getOrCreateDataPartition); return analysis; } @@ -3004,7 +3012,9 @@ public Analysis visitInsertMultiTablets( analysis, AnalyzeUtils.computeTreeDataPartitionParams(realStatement, context), context.getSession().getUserName(), - partitionFetcher::getOrCreateDataPartition); + context.isTestInsert() + ? ClusterPartitionFetcher.getInstance()::getDataPartitionForTestInsert + : partitionFetcher::getOrCreateDataPartition); return analysis; } @@ -3036,13 +3046,17 @@ public Analysis visitInsertRowsOfOneDevice( analysis, Collections.singletonList(dataPartitionQueryParam), context.getSession().getUserName(), - partitionFetcher::getOrCreateDataPartition); + context.isTestInsert() + ? ClusterPartitionFetcher.getInstance()::getDataPartitionForTestInsert + : partitionFetcher::getOrCreateDataPartition); } else { AnalyzeUtils.analyzeDataPartition( analysis, AnalyzeUtils.computeTreeDataPartitionParams(realInsertStatement, context), context.getSession().getUserName(), - partitionFetcher::getOrCreateDataPartition); + context.isTestInsert() + ? ClusterPartitionFetcher.getInstance()::getDataPartitionForTestInsert + : partitionFetcher::getOrCreateDataPartition); } return analysis; } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/ClusterPartitionFetcher.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/ClusterPartitionFetcher.java index 824e3a4fbe08d..f52af26da7e6a 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/ClusterPartitionFetcher.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/ClusterPartitionFetcher.java @@ -27,6 +27,7 @@ import org.apache.iotdb.commons.client.exception.ClientManagerException; import org.apache.iotdb.commons.consensus.ConfigRegionId; import org.apache.iotdb.commons.exception.IoTDBRuntimeException; +import org.apache.iotdb.commons.exception.SemanticException; import org.apache.iotdb.commons.partition.DataPartition; import org.apache.iotdb.commons.partition.DataPartitionQueryParam; import org.apache.iotdb.commons.partition.SchemaNodeManagementPartition; @@ -316,6 +317,39 @@ public DataPartition getOrCreateDataPartition( return dataPartition; } + public DataPartition getDataPartitionForTestInsert( + final List params, final String userName) { + final Map> byDatabase = + splitDataPartitionQueryParam(params, false, userName); + if (byDatabase.values().stream().mapToInt(List::size).sum() != params.size()) { + throw new SemanticException( + DataNodeQueryMessages + .EXCEPTION_TEST_INSERTION_REQUIRES_AN_EXISTING_DATABASE_FOR_EVERY_DEVICE_22548137); + } + final DataPartition partition = getDataPartition(byDatabase); + for (Map.Entry> entry : byDatabase.entrySet()) { + for (DataPartitionQueryParam param : entry.getValue()) { + final Map> slots = + partition + .getDataPartitionMap() + .getOrDefault(entry.getKey(), Collections.emptyMap()) + .getOrDefault( + partition.calculateDeviceGroupId(param.getDeviceID()), Collections.emptyMap()); + for (TTimePartitionSlot slot : param.getTimePartitionSlotList()) { + if (!slots.containsKey(slot) || slots.get(slot).isEmpty()) { + throw new SemanticException( + String.format( + DataNodeQueryMessages + .EXCEPTION_TEST_INSERTION_REQUIRES_AN_EXISTING_DATA_PARTITION_FOR_ARG_AT_ARG_A5AABFF2, + param.getDeviceID(), + slot.getStartTime())); + } + } + } + } + return partition; + } + @Override public DataPartition getOrCreateDataPartition( final List dataPartitionQueryParams, final String userName) { diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/schema/AutoCreateSchemaExecutor.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/schema/AutoCreateSchemaExecutor.java index 2c5836c96c8f6..c5c68baa6f267 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/schema/AutoCreateSchemaExecutor.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/schema/AutoCreateSchemaExecutor.java @@ -84,6 +84,9 @@ class AutoCreateSchemaExecutor { } private ExecutionResult executeStatement(Statement statement, MPPQueryContext context) { + if (context != null) { + context.checkSchemaModificationAllowed(); + } return coordinator.executeForTreeModel( statement, diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/TestInsertPlanValidator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/TestInsertPlanValidator.java new file mode 100644 index 0000000000000..15b0f7c7bdb45 --- /dev/null +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/TestInsertPlanValidator.java @@ -0,0 +1,80 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.db.queryengine.plan.execution; + +import org.apache.iotdb.common.rpc.thrift.TConsensusGroupType; +import org.apache.iotdb.common.rpc.thrift.TSStatus; +import org.apache.iotdb.commons.consensus.ConsensusGroupId; +import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.PlanNode; +import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.PlanNodeType; +import org.apache.iotdb.db.i18n.DataNodeQueryMessages; +import org.apache.iotdb.db.protocol.thrift.impl.DataNodeRegionManager; +import org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.InsertNode; +import org.apache.iotdb.mpp.rpc.thrift.TSendBatchPlanNodeReq; +import org.apache.iotdb.mpp.rpc.thrift.TSendBatchPlanNodeResp; +import org.apache.iotdb.mpp.rpc.thrift.TSendSinglePlanNodeReq; +import org.apache.iotdb.mpp.rpc.thrift.TSendSinglePlanNodeResp; +import org.apache.iotdb.rpc.RpcUtils; +import org.apache.iotdb.rpc.TSStatusCode; + +import java.util.ArrayList; +import java.util.List; + +/** Checks reception and routing only; never invokes triggers, consensus or storage writes. */ +public class TestInsertPlanValidator { + private TestInsertPlanValidator() {} + + public static TSendBatchPlanNodeResp validate(TSendBatchPlanNodeReq request) { + List responses = new ArrayList<>(); + for (TSendSinglePlanNodeReq item : request.getRequests()) { + TSStatus status; + try { + PlanNode node = PlanNodeType.deserialize(item.getPlanNode().bufferForBody()); + if (!(node instanceof InsertNode) + || item.getConsensusGroupId().getType() != TConsensusGroupType.DataRegion) { + status = + RpcUtils.getStatus( + TSStatusCode.EXECUTE_STATEMENT_ERROR, + DataNodeQueryMessages + .MESSAGE_TEST_INSERTION_ACCEPTS_ONLY_INSERTION_PLANS_TARGETING_DATA_REGIONS_319E02A6); + } else if (DataNodeRegionManager.getInstance() + .getRegionLock( + ConsensusGroupId.Factory.createFromTConsensusGroupId( + item.getConsensusGroupId())) + == null) { + status = + RpcUtils.getStatus( + TSStatusCode.NO_AVAILABLE_REGION_GROUP, + DataNodeQueryMessages + .MESSAGE_TEST_INSERTION_TARGET_REGION_DOES_NOT_EXIST_A4645EC1); + } else { + status = RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS); + } + } catch (RuntimeException e) { + status = RpcUtils.getStatus(TSStatusCode.EXECUTE_STATEMENT_ERROR, e.getMessage()); + } + TSendSinglePlanNodeResp response = new TSendSinglePlanNodeResp(); + response.setStatus(status); + response.setAccepted(status.getCode() == TSStatusCode.SUCCESS_STATUS.getStatusCode()); + responses.add(response); + } + return new TSendBatchPlanNodeResp(responses); + } +} diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java index 6d06b3b535106..579dd5bf76f97 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java @@ -136,6 +136,7 @@ import org.apache.iotdb.db.queryengine.execution.warnings.IoTDBWarning; import org.apache.iotdb.db.queryengine.execution.warnings.WarningCollector; import org.apache.iotdb.db.queryengine.plan.analyze.AnalyzeUtils; +import org.apache.iotdb.db.queryengine.plan.analyze.ClusterPartitionFetcher; import org.apache.iotdb.db.queryengine.plan.analyze.QueryType; import org.apache.iotdb.db.queryengine.plan.analyze.load.LoadTsFileAnalyzer; import org.apache.iotdb.db.queryengine.plan.analyze.lock.DataNodeSchemaLockManager; @@ -1403,7 +1404,9 @@ private Scope visitInsert(WrappedInsertStatement insert, Optional scope) context, innerInsert, () -> SchemaValidator.validate(metadata, insert, context, accessControl), - metadata::getOrCreateDataPartition, + context.isTestInsert() + ? ClusterPartitionFetcher.getInstance()::getDataPartitionForTestInsert + : metadata::getOrCreateDataPartition, AnalyzeUtils::computeTableDataPartitionParams, analysis, false); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceSchemaValidator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceSchemaValidator.java index 7133c7ff2f924..49cdbe3530340 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceSchemaValidator.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceSchemaValidator.java @@ -250,6 +250,9 @@ private void autoCreateOrUpdateDeviceSchema( final List inputDeviceIdList, final List attributeKeyList, final List intPutAttributeValueList) { + if (context != null) { + context.checkSchemaModificationAllowed(); + } final int size = previousValidateResult.missingDeviceIndexList.size() + previousValidateResult.attributeUpdateDeviceIndexList.size(); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableHeaderSchemaValidator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableHeaderSchemaValidator.java index 797085491206c..e7ad120e13604 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableHeaderSchemaValidator.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableHeaderSchemaValidator.java @@ -546,6 +546,7 @@ private void autoCreateTableFromMeasurementInfo( final MPPQueryContext context, final String database, final InsertNodeMeasurementInfo measurementInfo) { + context.checkSchemaModificationAllowed(); DataNodeSchemaLockManager.getInstance().releaseReadLock(context); final TsTable tsTable = toTsTable(measurementInfo); AuthorityChecker.getAccessControl() @@ -578,6 +579,7 @@ private void autoCreateColumnsFromMeasurements( final InsertNodeMeasurementInfo measurementInfo, final List missingIndices, final MPPQueryContext context) { + context.checkSchemaModificationAllowed(); DataNodeSchemaLockManager.getInstance().releaseReadLock(context); AuthorityChecker.getAccessControl() .checkCanAlterTable( @@ -635,6 +637,7 @@ private void autoCreateColumnsFromMeasurements( private void autoCreateTable( final MPPQueryContext context, final String database, final TableSchema tableSchema) { + context.checkSchemaModificationAllowed(); // Release to avoid deadlock DataNodeSchemaLockManager.getInstance().releaseReadLock(context); final TsTable tsTable = new TsTable(tableSchema.getTableName()); @@ -843,6 +846,7 @@ private void autoCreateColumn( final String tableName, final List inputColumnList, final MPPQueryContext context) { + context.checkSchemaModificationAllowed(); DataNodeSchemaLockManager.getInstance().releaseReadLock(context); AuthorityChecker.getAccessControl() .checkCanAlterTable( diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/execution/TestInsertPlanValidatorTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/execution/TestInsertPlanValidatorTest.java new file mode 100644 index 0000000000000..294b095cd50b4 --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/execution/TestInsertPlanValidatorTest.java @@ -0,0 +1,81 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.db.queryengine.plan.execution; + +import org.apache.iotdb.common.rpc.thrift.TConsensusGroupId; +import org.apache.iotdb.common.rpc.thrift.TConsensusGroupType; +import org.apache.iotdb.commons.path.PartialPath; +import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.PlanNodeId; +import org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.InsertRowNode; +import org.apache.iotdb.mpp.rpc.thrift.TPlanNode; +import org.apache.iotdb.mpp.rpc.thrift.TSendBatchPlanNodeReq; +import org.apache.iotdb.mpp.rpc.thrift.TSendBatchPlanNodeResp; +import org.apache.iotdb.mpp.rpc.thrift.TSendSinglePlanNodeReq; +import org.apache.iotdb.rpc.TSStatusCode; + +import org.apache.tsfile.enums.TSDataType; +import org.junit.Test; + +import java.nio.ByteBuffer; +import java.util.Arrays; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +public class TestInsertPlanValidatorTest { + @Test + public void testBatchReportsMissingRegionWrongRegionAndMalformedPlan() throws Exception { + InsertRowNode row = + new InsertRowNode( + new PlanNodeId("test"), + new PartialPath("root.test.d"), + false, + new String[] {"s"}, + new TSDataType[] {TSDataType.INT64}, + 1, + new Object[] {1L}, + false); + TSendBatchPlanNodeResp response = + TestInsertPlanValidator.validate( + new TSendBatchPlanNodeReq( + Arrays.asList( + new TSendSinglePlanNodeReq( + new TPlanNode(row.serializeToByteBuffer()), + new TConsensusGroupId(TConsensusGroupType.DataRegion, Integer.MAX_VALUE)), + new TSendSinglePlanNodeReq( + new TPlanNode(row.serializeToByteBuffer()), + new TConsensusGroupId(TConsensusGroupType.SchemaRegion, Integer.MAX_VALUE)), + new TSendSinglePlanNodeReq( + new TPlanNode(ByteBuffer.allocate(0)), + new TConsensusGroupId( + TConsensusGroupType.DataRegion, Integer.MAX_VALUE))))); + assertEquals(3, response.getResponsesSize()); + response.getResponses().forEach(result -> assertFalse(result.isAccepted())); + assertEquals( + TSStatusCode.NO_AVAILABLE_REGION_GROUP.getStatusCode(), + response.getResponses().get(0).getStatus().getCode()); + assertEquals( + TSStatusCode.EXECUTE_STATEMENT_ERROR.getStatusCode(), + response.getResponses().get(1).getStatus().getCode()); + assertEquals( + TSStatusCode.EXECUTE_STATEMENT_ERROR.getStatusCode(), + response.getResponses().get(2).getStatus().getCode()); + } +} diff --git a/iotdb-protocol/thrift-datanode/rpc-changelist.md b/iotdb-protocol/thrift-datanode/rpc-changelist.md index 1efeb28c80ef7..8011e218df2dc 100644 --- a/iotdb-protocol/thrift-datanode/rpc-changelist.md +++ b/iotdb-protocol/thrift-datanode/rpc-changelist.md @@ -19,6 +19,13 @@ --> +# 2.0.x staged test insertion + +Staged test insertion: added `testInsert(TSTestInsertReq)` with an explicit completed-stage +acknowledgement, and internal `testInsertPlanNodes` for execution-free target checks. +Existing `testInsertXXX` RPCs retain their behavior. New RPCs require upgraded servers; +unsupported methods must fail rather than fall back to a normal insertion. + # 0.12.x -> 0.13.x Last Updated on 2022.1.17 by Xin Zhao. diff --git a/iotdb-protocol/thrift-datanode/src/main/thrift/client.thrift b/iotdb-protocol/thrift-datanode/src/main/thrift/client.thrift index 7ff12ceb02154..40597260cec46 100644 --- a/iotdb-protocol/thrift-datanode/src/main/thrift/client.thrift +++ b/iotdb-protocol/thrift-datanode/src/main/thrift/client.thrift @@ -564,6 +564,41 @@ struct TSConnectionInfoResp { 1: required list connectionInfoList } +// Staged test insertion never writes data or changes metadata. +// Analysis and later stages require pre-existing metadata and data partitions. +enum TestInsertStage { + // Login, stage and payload-count checks have passed; no Statement has been decoded. + UNTIL_RPC_PROCESSED = 1, + // The insertion payload has been decoded into a Statement. + UNTIL_DECODED = 2, + // Read-only analysis has completed. + UNTIL_ANALYZED = 3, + // Logical and distributed plans have been generated. + UNTIL_PLANNED = 4, + // All plan targets have deserialized the plan and checked its type and target region existence. + // No triggers, consensus or storage writes have been invoked. + UNTIL_WRITE_TARGET_RECEIVED = 5 +} + +// Exactly one payload must be supplied. Separate RPC prevents old servers silently ignoring stages. +struct TSTestInsertReq { + 1: required i64 sessionId + 2: required i32 stage + 3: optional TSInsertTabletReq tablet + 4: optional TSInsertTabletsReq tablets + 5: optional TSInsertRecordReq record + 6: optional TSInsertStringRecordReq stringRecord + 7: optional TSInsertRecordsReq records + 8: optional TSInsertRecordsOfOneDeviceReq recordsOfOneDevice + 9: optional TSInsertStringRecordsReq stringRecords +} + +struct TSTestInsertResp { + 1: required common.TSStatus status + // Zero on failure; otherwise the requested stage has completed. + 2: required i32 completedStage +} + service IClientRPCService { TSExecuteStatementResp executeQueryStatementV2(1:TSExecuteStatementReq req); @@ -645,6 +680,8 @@ service IClientRPCService { common.TSStatus insertStringRecords(1:TSInsertStringRecordsReq req); + TSTestInsertResp testInsert(1:TSTestInsertReq req); + common.TSStatus testInsertTablet(1:TSInsertTabletReq req); common.TSStatus testInsertTablets(1:TSInsertTabletsReq req); diff --git a/iotdb-protocol/thrift-datanode/src/main/thrift/datanode.thrift b/iotdb-protocol/thrift-datanode/src/main/thrift/datanode.thrift index 795fb2deb9d02..0137bbbff3328 100644 --- a/iotdb-protocol/thrift-datanode/src/main/thrift/datanode.thrift +++ b/iotdb-protocol/thrift-datanode/src/main/thrift/datanode.thrift @@ -970,6 +970,9 @@ service IDataNodeRPCService { */ TSendBatchPlanNodeResp sendBatchPlanNode(TSendBatchPlanNodeReq req); + // Deserialize and validate insertion plans without executing them. + TSendBatchPlanNodeResp testInsertPlanNodes(TSendBatchPlanNodeReq req); + TFragmentInstanceInfoResp fetchFragmentInstanceInfo(TFetchFragmentInstanceInfoReq req); TCancelResp cancelQuery(TCancelQueryReq req); From 05bd3fd89140f63d8f64fc55fcb98215fba35247 Mon Sep 17 00:00:00 2001 From: 761417898 <761417898@qq.com> Date: Wed, 18 Nov 2026 12:28:52 +0800 Subject: [PATCH 2/6] Remove target-validator unit test and RPC changelog entry --- .../TestInsertPlanValidatorTest.java | 81 ------------------- .../thrift-datanode/rpc-changelist.md | 7 -- 2 files changed, 88 deletions(-) delete mode 100644 iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/execution/TestInsertPlanValidatorTest.java diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/execution/TestInsertPlanValidatorTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/execution/TestInsertPlanValidatorTest.java deleted file mode 100644 index 294b095cd50b4..0000000000000 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/execution/TestInsertPlanValidatorTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.iotdb.db.queryengine.plan.execution; - -import org.apache.iotdb.common.rpc.thrift.TConsensusGroupId; -import org.apache.iotdb.common.rpc.thrift.TConsensusGroupType; -import org.apache.iotdb.commons.path.PartialPath; -import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.PlanNodeId; -import org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.InsertRowNode; -import org.apache.iotdb.mpp.rpc.thrift.TPlanNode; -import org.apache.iotdb.mpp.rpc.thrift.TSendBatchPlanNodeReq; -import org.apache.iotdb.mpp.rpc.thrift.TSendBatchPlanNodeResp; -import org.apache.iotdb.mpp.rpc.thrift.TSendSinglePlanNodeReq; -import org.apache.iotdb.rpc.TSStatusCode; - -import org.apache.tsfile.enums.TSDataType; -import org.junit.Test; - -import java.nio.ByteBuffer; -import java.util.Arrays; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - -public class TestInsertPlanValidatorTest { - @Test - public void testBatchReportsMissingRegionWrongRegionAndMalformedPlan() throws Exception { - InsertRowNode row = - new InsertRowNode( - new PlanNodeId("test"), - new PartialPath("root.test.d"), - false, - new String[] {"s"}, - new TSDataType[] {TSDataType.INT64}, - 1, - new Object[] {1L}, - false); - TSendBatchPlanNodeResp response = - TestInsertPlanValidator.validate( - new TSendBatchPlanNodeReq( - Arrays.asList( - new TSendSinglePlanNodeReq( - new TPlanNode(row.serializeToByteBuffer()), - new TConsensusGroupId(TConsensusGroupType.DataRegion, Integer.MAX_VALUE)), - new TSendSinglePlanNodeReq( - new TPlanNode(row.serializeToByteBuffer()), - new TConsensusGroupId(TConsensusGroupType.SchemaRegion, Integer.MAX_VALUE)), - new TSendSinglePlanNodeReq( - new TPlanNode(ByteBuffer.allocate(0)), - new TConsensusGroupId( - TConsensusGroupType.DataRegion, Integer.MAX_VALUE))))); - assertEquals(3, response.getResponsesSize()); - response.getResponses().forEach(result -> assertFalse(result.isAccepted())); - assertEquals( - TSStatusCode.NO_AVAILABLE_REGION_GROUP.getStatusCode(), - response.getResponses().get(0).getStatus().getCode()); - assertEquals( - TSStatusCode.EXECUTE_STATEMENT_ERROR.getStatusCode(), - response.getResponses().get(1).getStatus().getCode()); - assertEquals( - TSStatusCode.EXECUTE_STATEMENT_ERROR.getStatusCode(), - response.getResponses().get(2).getStatus().getCode()); - } -} diff --git a/iotdb-protocol/thrift-datanode/rpc-changelist.md b/iotdb-protocol/thrift-datanode/rpc-changelist.md index 8011e218df2dc..1efeb28c80ef7 100644 --- a/iotdb-protocol/thrift-datanode/rpc-changelist.md +++ b/iotdb-protocol/thrift-datanode/rpc-changelist.md @@ -19,13 +19,6 @@ --> -# 2.0.x staged test insertion - -Staged test insertion: added `testInsert(TSTestInsertReq)` with an explicit completed-stage -acknowledgement, and internal `testInsertPlanNodes` for execution-free target checks. -Existing `testInsertXXX` RPCs retain their behavior. New RPCs require upgraded servers; -unsupported methods must fail rather than fall back to a normal insertion. - # 0.12.x -> 0.13.x Last Updated on 2022.1.17 by Xin Zhao. From 7c301370555a8d74598a3ce93a15517b10d216a0 Mon Sep 17 00:00:00 2001 From: 761417898 <761417898@qq.com> Date: Wed, 18 Nov 2026 12:44:04 +0800 Subject: [PATCH 3/6] Separate staged test insertion decoding from RPC control flow --- .../thrift/impl/ClientRPCServiceImpl.java | 122 ++++++++++-------- 1 file changed, 65 insertions(+), 57 deletions(-) diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java index 2f8761c557f82..7b3b0bc6231fe 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java @@ -19,6 +19,7 @@ package org.apache.iotdb.db.protocol.thrift.impl; +import org.apache.iotdb.calc.exception.QueryProcessException; import org.apache.iotdb.common.rpc.thrift.TAggregationType; import org.apache.iotdb.common.rpc.thrift.TEndPoint; import org.apache.iotdb.common.rpc.thrift.TRegionReplicaSet; @@ -36,6 +37,7 @@ import org.apache.iotdb.commons.conf.IoTDBConstant; import org.apache.iotdb.commons.exception.IllegalPathException; import org.apache.iotdb.commons.exception.IoTDBException; +import org.apache.iotdb.commons.exception.MetadataException; import org.apache.iotdb.commons.i18n.PipeMessages; import org.apache.iotdb.commons.partition.DataPartition; import org.apache.iotdb.commons.partition.DataPartitionQueryParam; @@ -2955,15 +2957,7 @@ public TSTestInsertResp testInsert(TSTestInsertReq req) { return new TSTestInsertResp(getNotLoggedInStatus(), 0); } TestInsertStage stage = TestInsertStage.findByValue(req.getStage()); - int payloads = - (req.isSetTablet() ? 1 : 0) - + (req.isSetTablets() ? 1 : 0) - + (req.isSetRecord() ? 1 : 0) - + (req.isSetStringRecord() ? 1 : 0) - + (req.isSetRecords() ? 1 : 0) - + (req.isSetRecordsOfOneDevice() ? 1 : 0) - + (req.isSetStringRecords() ? 1 : 0); - if (stage == null || payloads != 1) { + if (stage == null || !hasExactlyOneInsertPayload(req)) { return new TSTestInsertResp( RpcUtils.getStatus( TSStatusCode.ILLEGAL_PARAMETER, @@ -2975,54 +2969,7 @@ public TSTestInsertResp testInsert(TSTestInsertReq req) { return new TSTestInsertResp( RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS), req.getStage()); } - InsertBaseStatement statement; - if (req.isSetTablet()) { - if (!req.getTablet().isWriteToTable()) { - req.getTablet() - .setMeasurements( - PathUtils.checkIsLegalSingleMeasurementsAndUpdate( - req.getTablet().getMeasurements())); - } - statement = StatementGenerator.createStatement(req.getTablet()); - } else if (req.isSetTablets()) { - req.getTablets() - .setMeasurementsList( - PathUtils.checkIsLegalSingleMeasurementListsAndUpdate( - req.getTablets().getMeasurementsList())); - statement = StatementGenerator.createStatement(req.getTablets()); - } else if (req.isSetRecord()) { - if (!req.getRecord().isIsWriteToTable()) { - req.getRecord() - .setMeasurements( - PathUtils.checkIsLegalSingleMeasurementsAndUpdate( - req.getRecord().getMeasurements())); - } - statement = StatementGenerator.createStatement(req.getRecord()); - } else if (req.isSetStringRecord()) { - req.getStringRecord() - .setMeasurements( - PathUtils.checkIsLegalSingleMeasurementsAndUpdate( - req.getStringRecord().getMeasurements())); - statement = StatementGenerator.createStatement(req.getStringRecord()); - } else if (req.isSetRecords()) { - req.getRecords() - .setMeasurementsList( - PathUtils.checkIsLegalSingleMeasurementListsAndUpdate( - req.getRecords().getMeasurementsList())); - statement = StatementGenerator.createStatement(req.getRecords()); - } else if (req.isSetRecordsOfOneDevice()) { - req.getRecordsOfOneDevice() - .setMeasurementsList( - PathUtils.checkIsLegalSingleMeasurementListsAndUpdate( - req.getRecordsOfOneDevice().getMeasurementsList())); - statement = StatementGenerator.createStatement(req.getRecordsOfOneDevice()); - } else { - req.getStringRecords() - .setMeasurementsList( - PathUtils.checkIsLegalSingleMeasurementListsAndUpdate( - req.getStringRecords().getMeasurementsList())); - statement = StatementGenerator.createStatement(req.getStringRecords()); - } + InsertBaseStatement statement = decodeTestInsert(req); if (stage == TestInsertStage.UNTIL_DECODED) { return new TSTestInsertResp( RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS), req.getStage()); @@ -3058,6 +3005,67 @@ public TSTestInsertResp testInsert(TSTestInsertReq req) { } } + private static boolean hasExactlyOneInsertPayload(TSTestInsertReq req) { + int payloadCount = + (req.isSetTablet() ? 1 : 0) + + (req.isSetTablets() ? 1 : 0) + + (req.isSetRecord() ? 1 : 0) + + (req.isSetStringRecord() ? 1 : 0) + + (req.isSetRecords() ? 1 : 0) + + (req.isSetRecordsOfOneDevice() ? 1 : 0) + + (req.isSetStringRecords() ? 1 : 0); + return payloadCount == 1; + } + + private static InsertBaseStatement decodeTestInsert(TSTestInsertReq req) + throws MetadataException, QueryProcessException { + if (req.isSetTablet()) { + TSInsertTabletReq tablet = req.getTablet(); + if (!tablet.isWriteToTable()) { + tablet.setMeasurements( + PathUtils.checkIsLegalSingleMeasurementsAndUpdate(tablet.getMeasurements())); + } + return StatementGenerator.createStatement(tablet); + } + if (req.isSetTablets()) { + TSInsertTabletsReq tablets = req.getTablets(); + tablets.setMeasurementsList( + PathUtils.checkIsLegalSingleMeasurementListsAndUpdate(tablets.getMeasurementsList())); + return StatementGenerator.createStatement(tablets); + } + if (req.isSetRecord()) { + TSInsertRecordReq record = req.getRecord(); + if (!record.isIsWriteToTable()) { + record.setMeasurements( + PathUtils.checkIsLegalSingleMeasurementsAndUpdate(record.getMeasurements())); + } + return StatementGenerator.createStatement(record); + } + if (req.isSetStringRecord()) { + TSInsertStringRecordReq record = req.getStringRecord(); + record.setMeasurements( + PathUtils.checkIsLegalSingleMeasurementsAndUpdate(record.getMeasurements())); + return StatementGenerator.createStatement(record); + } + if (req.isSetRecords()) { + TSInsertRecordsReq records = req.getRecords(); + records.setMeasurementsList( + PathUtils.checkIsLegalSingleMeasurementListsAndUpdate(records.getMeasurementsList())); + return StatementGenerator.createStatement(records); + } + if (req.isSetRecordsOfOneDevice()) { + TSInsertRecordsOfOneDeviceReq records = req.getRecordsOfOneDevice(); + records.setMeasurementsList( + PathUtils.checkIsLegalSingleMeasurementListsAndUpdate(records.getMeasurementsList())); + return StatementGenerator.createStatement(records); + } + // The caller has verified that exactly one payload is set. + TSInsertStringRecordsReq records = req.getStringRecords(); + records.setMeasurementsList( + PathUtils.checkIsLegalSingleMeasurementListsAndUpdate(records.getMeasurementsList())); + return StatementGenerator.createStatement(records); + } + @Override public TSStatus testInsertTablets(TSInsertTabletsReq req) { LOGGER.debug(DataNodeMiscMessages.TEST_INSERT_BATCH_RECEIVE); From eb0c06d69ffe6743dafd4a3c34978fca3cf4f754 Mon Sep 17 00:00:00 2001 From: 761417898 <761417898@qq.com> Date: Wed, 18 Nov 2026 14:57:16 +0800 Subject: [PATCH 4/6] Handle filtered-empty tablets in staged test insertion --- .../org/apache/iotdb/session/Session.java | 13 +++- .../org/apache/iotdb/session/SessionTest.java | 75 +++++++++++++++++++ 2 files changed, 87 insertions(+), 1 deletion(-) diff --git a/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java b/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java index 02fbb80521602..54f58500ed211 100644 --- a/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java +++ b/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java @@ -2909,8 +2909,11 @@ public void testInsertRelationalTablet(Tablet tablet, TestInsertStage stage) throws IoTDBConnectionException, StatementExecutionException { Objects.requireNonNull(stage, SessionMessages.EXCEPTION_STAGE_9A8C2B9D); TSInsertTabletReq request = genTSInsertTabletReq(tablet, false, false); + if (request == null) { + throw new StatementExecutionException( + SessionMessages.EXCEPTION_TEST_INSERTION_HAS_NO_NON_NULL_VALUES_40F5D116); + } request.setWriteToTable(true); - request.setColumnCategories(toEnumOrdinalsAsBytes(tablet.getColumnTypes())); getDefaultSessionConnection() .testInsert(new TSTestInsertReq(0, stage.getValue()).setTablet(request)); } @@ -3748,6 +3751,10 @@ public void testInsertTablet(Tablet tablet, boolean sorted, TestInsertStage stag throws IoTDBConnectionException, StatementExecutionException { Objects.requireNonNull(stage, SessionMessages.EXCEPTION_STAGE_9A8C2B9D); TSInsertTabletReq request = genTSInsertTabletReq(tablet, sorted, false); + if (request == null) { + throw new StatementExecutionException( + SessionMessages.EXCEPTION_TEST_INSERTION_HAS_NO_NON_NULL_VALUES_40F5D116); + } getDefaultSessionConnection() .testInsert(new TSTestInsertReq(0, stage.getValue()).setTablet(request)); } @@ -3766,6 +3773,10 @@ public void testInsertTablets(Map tablets, boolean sorted, TestI Objects.requireNonNull(stage, SessionMessages.EXCEPTION_STAGE_9A8C2B9D); TSInsertTabletsReq request = genTSInsertTabletsReq(new ArrayList<>(tablets.values()), sorted, false); + if (request == null) { + throw new StatementExecutionException( + SessionMessages.EXCEPTION_TEST_INSERTION_HAS_NO_NON_NULL_VALUES_40F5D116); + } getDefaultSessionConnection() .testInsert(new TSTestInsertReq(0, stage.getValue()).setTablets(request)); } diff --git a/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionTest.java b/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionTest.java index 2c93d04cb077b..72879241844e5 100644 --- a/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionTest.java +++ b/iotdb-client/session/src/test/java/org/apache/iotdb/session/SessionTest.java @@ -28,8 +28,12 @@ import org.apache.iotdb.rpc.IoTDBConnectionException; import org.apache.iotdb.rpc.StatementExecutionException; import org.apache.iotdb.service.rpc.thrift.TSQueryTemplateResp; +import org.apache.iotdb.service.rpc.thrift.TSTestInsertReq; +import org.apache.iotdb.service.rpc.thrift.TestInsertStage; +import org.apache.iotdb.session.i18n.SessionMessages; import org.apache.tsfile.common.conf.TSFileConfig; +import org.apache.tsfile.enums.ColumnCategory; import org.apache.tsfile.enums.TSDataType; import org.apache.tsfile.file.metadata.enums.CompressionType; import org.apache.tsfile.file.metadata.enums.TSEncoding; @@ -42,6 +46,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; @@ -887,6 +892,76 @@ public void testSetSchemaTemplateException() session.setSchemaTemplate("template1", "prefixPath"); } + @Test + public void testStagedTabletsRejectFilteredEmptyRequests() throws Exception { + Tablet tableTablet = + new Tablet( + "t", + Collections.singletonList("v"), + Collections.singletonList(TSDataType.INT64), + Collections.singletonList(ColumnCategory.FIELD)); + tableTablet.addTimestamp(0, 1); + tableTablet.addValue("v", 0, null); + Tablet treeTablet = + new Tablet( + "root.sg.d", Collections.singletonList(new MeasurementSchema("v", TSDataType.INT64))); + treeTablet.addTimestamp(0, 1); + treeTablet.addValue("v", 0, null); + TableSession tableSession = new TableSession((Session) session); + String expectedMessage = + SessionMessages.EXCEPTION_TEST_INSERTION_HAS_NO_NON_NULL_VALUES_40F5D116; + assertEquals( + expectedMessage, + Assert.assertThrows( + StatementExecutionException.class, () -> tableSession.testInsert(tableTablet)) + .getMessage()); + for (TestInsertStage stage : TestInsertStage.values()) { + assertEquals( + expectedMessage, + Assert.assertThrows( + StatementExecutionException.class, + () -> tableSession.testInsert(tableTablet, stage)) + .getMessage()); + assertEquals( + expectedMessage, + Assert.assertThrows( + StatementExecutionException.class, + () -> session.testInsertTablet(treeTablet, stage)) + .getMessage()); + assertEquals( + expectedMessage, + Assert.assertThrows( + StatementExecutionException.class, + () -> + session.testInsertTablets( + Collections.singletonMap("root.sg.d", treeTablet), stage)) + .getMessage()); + } + Mockito.verifyZeroInteractions(sessionConnection); + } + + @Test + public void testStagedTableTabletKeepsFilteredColumnCategories() throws Exception { + Tablet tablet = + new Tablet( + "t", + Arrays.asList("id", "empty", "value"), + Arrays.asList(TSDataType.STRING, TSDataType.INT64, TSDataType.INT64), + Arrays.asList(ColumnCategory.TAG, ColumnCategory.FIELD, ColumnCategory.FIELD)); + tablet.addTimestamp(0, 1); + tablet.addValue("id", 0, "d"); + tablet.addValue("empty", 0, null); + tablet.addValue("value", 0, 1L); + new TableSession((Session) session).testInsert(tablet, TestInsertStage.UNTIL_DECODED); + ArgumentCaptor request = ArgumentCaptor.forClass(TSTestInsertReq.class); + Mockito.verify(sessionConnection).testInsert(request.capture()); + Assert.assertTrue(request.getValue().getTablet().isWriteToTable()); + assertEquals(Arrays.asList("id", "value"), request.getValue().getTablet().getMeasurements()); + assertEquals( + Arrays.asList((byte) ColumnCategory.TAG.ordinal(), (byte) ColumnCategory.FIELD.ordinal()), + request.getValue().getTablet().getColumnCategories()); + } + @Test public void testInsertTablet() throws IoTDBConnectionException, StatementExecutionException { List schemas = new ArrayList<>(); From 8cbcf91cf0e4beb719032d38d846308d28c1cec9 Mon Sep 17 00:00:00 2001 From: 761417898 <761417898@qq.com> Date: Wed, 18 Nov 2026 19:08:20 +0800 Subject: [PATCH 5/6] Clarify the null test insertion stage diagnostic --- .../iotdb/session/i18n/SessionMessages.java | 4 ++-- .../iotdb/session/i18n/SessionMessages.java | 4 ++-- .../org/apache/iotdb/session/Session.java | 21 ++++++++++++------- 3 files changed, 18 insertions(+), 11 deletions(-) diff --git a/iotdb-client/session/src/main/i18n/en/org/apache/iotdb/session/i18n/SessionMessages.java b/iotdb-client/session/src/main/i18n/en/org/apache/iotdb/session/i18n/SessionMessages.java index 6f49c371dc3c1..7d06874fa8904 100644 --- a/iotdb-client/session/src/main/i18n/en/org/apache/iotdb/session/i18n/SessionMessages.java +++ b/iotdb-client/session/src/main/i18n/en/org/apache/iotdb/session/i18n/SessionMessages.java @@ -30,8 +30,8 @@ public final class SessionMessages { public static final String EXCEPTION_TEST_INSERTION_HAS_NO_NON_NULL_VALUES_40F5D116 = "Test insertion has no non-null values"; - public static final String EXCEPTION_STAGE_9A8C2B9D = - "stage"; + public static final String EXCEPTION_TEST_INSERTION_STAGE_MUST_NOT_BE_NULL_EC9D4E51 = + "Test insertion stage must not be null"; public static final String EXCEPTION_INTERNAL_NODE_SUPPLIER_MUST_NOT_BE_NULL_C5CAF392 = "Internal node supplier must not be null"; diff --git a/iotdb-client/session/src/main/i18n/zh/org/apache/iotdb/session/i18n/SessionMessages.java b/iotdb-client/session/src/main/i18n/zh/org/apache/iotdb/session/i18n/SessionMessages.java index 7ce3ef704260e..b88f7a9410eac 100644 --- a/iotdb-client/session/src/main/i18n/zh/org/apache/iotdb/session/i18n/SessionMessages.java +++ b/iotdb-client/session/src/main/i18n/zh/org/apache/iotdb/session/i18n/SessionMessages.java @@ -30,8 +30,8 @@ public final class SessionMessages { public static final String EXCEPTION_TEST_INSERTION_HAS_NO_NON_NULL_VALUES_40F5D116 = "测试写入没有非空值"; - public static final String EXCEPTION_STAGE_9A8C2B9D = - "stage"; + public static final String EXCEPTION_TEST_INSERTION_STAGE_MUST_NOT_BE_NULL_EC9D4E51 = + "测试写入阶段不能为空"; public static final String EXCEPTION_INTERNAL_NODE_SUPPLIER_MUST_NOT_BE_NULL_C5CAF392 = "内部节点 supplier 不能为空"; diff --git a/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java b/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java index 54f58500ed211..2f2a31742b35f 100644 --- a/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java +++ b/iotdb-client/session/src/main/java/org/apache/iotdb/session/Session.java @@ -2907,7 +2907,8 @@ private void insertTabletInternal(Tablet tablet, TSInsertTabletReq request) */ public void testInsertRelationalTablet(Tablet tablet, TestInsertStage stage) throws IoTDBConnectionException, StatementExecutionException { - Objects.requireNonNull(stage, SessionMessages.EXCEPTION_STAGE_9A8C2B9D); + Objects.requireNonNull( + stage, SessionMessages.EXCEPTION_TEST_INSERTION_STAGE_MUST_NOT_BE_NULL_EC9D4E51); TSInsertTabletReq request = genTSInsertTabletReq(tablet, false, false); if (request == null) { throw new StatementExecutionException( @@ -3749,7 +3750,8 @@ public void testInsertTablet(Tablet tablet, TestInsertStage stage) @Override public void testInsertTablet(Tablet tablet, boolean sorted, TestInsertStage stage) throws IoTDBConnectionException, StatementExecutionException { - Objects.requireNonNull(stage, SessionMessages.EXCEPTION_STAGE_9A8C2B9D); + Objects.requireNonNull( + stage, SessionMessages.EXCEPTION_TEST_INSERTION_STAGE_MUST_NOT_BE_NULL_EC9D4E51); TSInsertTabletReq request = genTSInsertTabletReq(tablet, sorted, false); if (request == null) { throw new StatementExecutionException( @@ -3770,7 +3772,8 @@ public void testInsertTablets(Map tablets, TestInsertStage stage @Override public void testInsertTablets(Map tablets, boolean sorted, TestInsertStage stage) throws IoTDBConnectionException, StatementExecutionException { - Objects.requireNonNull(stage, SessionMessages.EXCEPTION_STAGE_9A8C2B9D); + Objects.requireNonNull( + stage, SessionMessages.EXCEPTION_TEST_INSERTION_STAGE_MUST_NOT_BE_NULL_EC9D4E51); TSInsertTabletsReq request = genTSInsertTabletsReq(new ArrayList<>(tablets.values()), sorted, false); if (request == null) { @@ -3790,7 +3793,8 @@ public void testInsertRecords( List> valuesList, TestInsertStage stage) throws IoTDBConnectionException, StatementExecutionException { - Objects.requireNonNull(stage, SessionMessages.EXCEPTION_STAGE_9A8C2B9D); + Objects.requireNonNull( + stage, SessionMessages.EXCEPTION_TEST_INSERTION_STAGE_MUST_NOT_BE_NULL_EC9D4E51); TSInsertStringRecordsReq request; try { request = @@ -3815,7 +3819,8 @@ public void testInsertRecords( List> valuesList, TestInsertStage stage) throws IoTDBConnectionException, StatementExecutionException { - Objects.requireNonNull(stage, SessionMessages.EXCEPTION_STAGE_9A8C2B9D); + Objects.requireNonNull( + stage, SessionMessages.EXCEPTION_TEST_INSERTION_STAGE_MUST_NOT_BE_NULL_EC9D4E51); TSInsertRecordsReq request; try { request = @@ -3839,7 +3844,8 @@ public void testInsertRecord( List values, TestInsertStage stage) throws IoTDBConnectionException, StatementExecutionException { - Objects.requireNonNull(stage, SessionMessages.EXCEPTION_STAGE_9A8C2B9D); + Objects.requireNonNull( + stage, SessionMessages.EXCEPTION_TEST_INSERTION_STAGE_MUST_NOT_BE_NULL_EC9D4E51); TSInsertStringRecordReq request; try { request = filterAndGenTSInsertStringRecordReq(deviceId, time, measurements, values, false); @@ -3861,7 +3867,8 @@ public void testInsertRecord( List values, TestInsertStage stage) throws IoTDBConnectionException, StatementExecutionException { - Objects.requireNonNull(stage, SessionMessages.EXCEPTION_STAGE_9A8C2B9D); + Objects.requireNonNull( + stage, SessionMessages.EXCEPTION_TEST_INSERTION_STAGE_MUST_NOT_BE_NULL_EC9D4E51); TSInsertRecordReq request; try { request = filterAndGenTSInsertRecordReq(deviceId, time, measurements, types, values, false); From b8cc373b59c4e3385796e6c2880bd9c871c90822 Mon Sep 17 00:00:00 2001 From: 761417898 <761417898@qq.com> Date: Fri, 4 Dec 2026 10:09:45 +0800 Subject: [PATCH 6/6] Acknowledge empty staged test insertions after decoding --- .../iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java index c30454a233908..bb64b45333da9 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/ClientRPCServiceImpl.java @@ -3157,7 +3157,7 @@ public TSTestInsertResp testInsert(TSTestInsertReq req) { RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS), req.getStage()); } InsertBaseStatement statement = decodeTestInsert(req); - if (stage == TestInsertStage.UNTIL_DECODED) { + if (stage == TestInsertStage.UNTIL_DECODED || statement.isEmpty()) { return new TSTestInsertResp( RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS), req.getStage()); }