This is an automated email from the ASF dual-hosted git repository.
jt2594838 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iotdb.git
The following commit(s) were added to refs/heads/master by this push:
new d3163c00b37 Fix table schema resolution during pre-delete refresh
(#19467)
d3163c00b37 is described below
commit d3163c00b37710a843e79df5c2c68e3d94da9b70
Author: Caideyipi <[email protected]>
AuthorDate: Tue Dec 1 16:04:13 2026 +0800
Fix table schema resolution during pre-delete refresh (#19467)
---
.../schema/IoTDBTableSchemaFlushVisibilityIT.java | 143 ++++++++++
.../iotdb/db/i18n/StorageEngineMessages.java | 5 +
.../iotdb/db/i18n/StorageEngineMessages.java | 5 +
.../dataregion/DataExecutionVisitor.java | 12 +
.../db/schemaengine/table/DataNodeTableCache.java | 36 ++-
.../db/storageengine/dataregion/DataRegion.java | 248 +++++++++++------
.../dataregion/memtable/TsFileProcessor.java | 31 ++-
.../dataregion/DataExecutionVisitorTest.java | 109 ++++++++
.../schemaengine/table/DataNodeTableCacheTest.java | 137 +++++++++-
.../dataregion/DataRegionSchemaResolutionTest.java | 294 +++++++++++++++++++++
.../dataregion/memtable/TsFileProcessorTest.java | 42 ++-
...FileTableSchemaRegistrationPerformanceTest.java | 2 +-
12 files changed, 964 insertions(+), 100 deletions(-)
diff --git
a/integration-test/src/test/java/org/apache/iotdb/relational/it/schema/IoTDBTableSchemaFlushVisibilityIT.java
b/integration-test/src/test/java/org/apache/iotdb/relational/it/schema/IoTDBTableSchemaFlushVisibilityIT.java
new file mode 100644
index 00000000000..267a0ab62f6
--- /dev/null
+++
b/integration-test/src/test/java/org/apache/iotdb/relational/it/schema/IoTDBTableSchemaFlushVisibilityIT.java
@@ -0,0 +1,143 @@
+/*
+ * 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.relational.it.schema;
+
+import org.apache.iotdb.consensus.ConsensusFactory;
+import org.apache.iotdb.it.env.EnvFactory;
+import org.apache.iotdb.it.framework.IoTDBTestRunner;
+import org.apache.iotdb.itbase.category.TableClusterIT;
+
+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.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+import static org.apache.iotdb.itbase.env.BaseEnv.TABLE_SQL_DIALECT;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+@RunWith(IoTDBTestRunner.class)
+@Category(TableClusterIT.class)
+public class IoTDBTableSchemaFlushVisibilityIT {
+
+ private static final String DATABASE = "table_schema_flush_visibility";
+ private static final String TABLE = DATABASE + ".sensor";
+
+ @BeforeClass
+ public static void setUpClass() throws SQLException {
+ EnvFactory.getEnv()
+ .getConfig()
+ .getCommonConfig()
+ .setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
+
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
+ .setDataRegionConsensusProtocolClass(ConsensusFactory.IOT_CONSENSUS)
+ .setSchemaReplicationFactor(3)
+ .setDataReplicationFactor(3);
+ EnvFactory.getEnv().initClusterEnvironment(1, 3);
+ }
+
+ @AfterClass
+ public static void tearDownClass() {
+ EnvFactory.getEnv().cleanClusterEnvironment();
+ }
+
+ @Test
+ public void testHistoricalRowsSurviveRepeatedAlterAndFlush() throws
SQLException {
+ try (Connection connection =
EnvFactory.getEnv().getConnection(TABLE_SQL_DIALECT);
+ Statement statement = connection.createStatement()) {
+ statement.execute("CREATE DATABASE " + DATABASE);
+ statement.execute(
+ "CREATE TABLE "
+ + TABLE
+ + " (device_id STRING TAG, location STRING ATTRIBUTE, s0 INT32
FIELD)");
+ statement.execute(
+ "INSERT INTO "
+ + TABLE
+ + " (time, device_id, location, s0) VALUES (1, 'device_1',
'Beijing', 1)");
+ statement.execute("FLUSH");
+
+ statement.execute("ALTER TABLE " + TABLE + " ADD COLUMN tag2 STRING
TAG");
+ statement.execute(
+ "INSERT INTO "
+ + TABLE
+ + " (time, device_id, location, s0, tag2) "
+ + "VALUES (2, 'device_2', 'Shanghai', 2, 'tag_2')");
+ statement.execute("FLUSH");
+
+ statement.execute("ALTER TABLE " + TABLE + " ADD COLUMN f2 INT32 FIELD");
+ statement.execute(
+ "INSERT INTO "
+ + TABLE
+ + " (time, device_id, location, s0, f2) "
+ + "VALUES (211, 'device_1', 'Shanghai', 10, 33)");
+ statement.execute("FLUSH");
+
+ statement.execute("ALTER TABLE " + TABLE + " ADD COLUMN a2 STRING
ATTRIBUTE");
+ statement.execute(
+ "INSERT INTO "
+ + TABLE
+ + " (time, device_id, s0, a2) VALUES (411, 'device_1', 40, 'a2
attr')");
+ statement.execute("FLUSH");
+
+ try (ResultSet resultSet =
+ statement.executeQuery(
+ "SELECT time, device_id, location, a2, s0, tag2, f2 FROM "
+ + TABLE
+ + " ORDER BY time, device_id")) {
+ assertRow(resultSet, 1, "device_1", "Shanghai", "a2 attr", 1, null,
null);
+ assertRow(resultSet, 2, "device_2", "Shanghai", null, 2, "tag_2",
null);
+ assertRow(resultSet, 211, "device_1", "Shanghai", "a2 attr", 10, null,
33);
+ assertRow(resultSet, 411, "device_1", "Shanghai", "a2 attr", 40, null,
null);
+ assertFalse(resultSet.next());
+ }
+ }
+ }
+
+ private void assertRow(
+ final ResultSet resultSet,
+ final long expectedTime,
+ final String expectedDevice,
+ final String expectedLocation,
+ final String expectedA2,
+ final int expectedValue,
+ final String expectedTag,
+ final Integer expectedF2)
+ throws SQLException {
+ assertTrue("Missing row at time " + expectedTime, resultSet.next());
+ assertEquals(expectedTime, resultSet.getLong("time"));
+ assertEquals(expectedDevice, resultSet.getString("device_id"));
+ assertEquals(expectedLocation, resultSet.getString("location"));
+ assertEquals(expectedA2, resultSet.getString("a2"));
+ assertEquals(expectedValue, resultSet.getInt("s0"));
+ assertEquals(expectedTag, resultSet.getString("tag2"));
+ if (expectedF2 == null) {
+ assertNull(resultSet.getObject("f2"));
+ } else {
+ assertEquals(expectedF2, resultSet.getObject("f2"));
+ }
+ }
+}
diff --git
a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java
b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java
index ef3db3ca28f..0015bf4a63f 100644
---
a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java
+++
b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java
@@ -943,6 +943,11 @@ public final class StorageEngineMessages {
"Fail to recover unsealed TsFile {}, skip it.";
public static final String
STORAGE_LOG_REMOTE_REQUEST_CONFIG_NODE_FAILED_THAT_JUDGMENT_IF_TABLE_25FE3602 =
"Remote request config node failed that judgment if table is exist,
occur exception. {}";
+ public static final String
EXCEPTION_FAILED_TO_DESCRIBE_TABLE_ARG_ARG_FROM_CONFIGNODE_BFBC7FBC =
+ "Failed to describe table %s.%s from ConfigNode";
+ public static final String
+
EXCEPTION_FAILED_TO_OBTAIN_A_STABLE_TABLE_SCHEMA_FOR_TSFILE_REGISTRATION_24F0C44B
=
+ "Failed to obtain a stable table schema for TsFile registration";
public static final String
STORAGE_LOG_DUE_TSTABLE_IS_NULL_TABLE_SCHEMA_CAN_T_BE_GOT_LEADER_NODE_C3EF524D =
"Due tsTable is null, table schema can't be got, leader node occur
special situation need to "
+ "resolve.";
diff --git
a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java
b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java
index d67165c837a..80c70ee05d7 100644
---
a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java
+++
b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java
@@ -918,6 +918,11 @@ public final class StorageEngineMessages {
"无法恢复 unsealed TsFile {},跳过该文件。";
public static final String
STORAGE_LOG_REMOTE_REQUEST_CONFIG_NODE_FAILED_THAT_JUDGMENT_IF_TABLE_25FE3602 =
"向 ConfigNode 远程请求判断表是否存在失败,发生异常:{}";
+ public static final String
EXCEPTION_FAILED_TO_DESCRIBE_TABLE_ARG_ARG_FROM_CONFIGNODE_BFBC7FBC =
+ "从 ConfigNode 获取表 %s.%s 的描述失败";
+ public static final String
+
EXCEPTION_FAILED_TO_OBTAIN_A_STABLE_TABLE_SCHEMA_FOR_TSFILE_REGISTRATION_24F0C44B
=
+ "无法为 TsFile 注册获取稳定的表 schema";
public static final String
STORAGE_LOG_DUE_TSTABLE_IS_NULL_TABLE_SCHEMA_CAN_T_BE_GOT_LEADER_NODE_C3EF524D =
"由于 tsTable 为 null,无法获取表 schema,leader 节点发生特殊情况,需要处理。";
public static final String
STORAGE_LOG_DISK_SPACE_IS_INSUFFICIENT_WHEN_CREATING_TSFILE_PROCESSOR_4032BAF0 =
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/consensus/statemachine/dataregion/DataExecutionVisitor.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/consensus/statemachine/dataregion/DataExecutionVisitor.java
index 7b3e883bb35..b1fd9153dca 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/consensus/statemachine/dataregion/DataExecutionVisitor.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/consensus/statemachine/dataregion/DataExecutionVisitor.java
@@ -153,6 +153,9 @@ public class DataExecutionVisitor implements
PlanVisitor<TSStatus, DataRegion> {
} catch (WriteProcessException e) {
LOGGER.error(DataNodeMiscMessages.ERROR_EXECUTING_PLAN_NODE, node, e);
return RpcUtils.getStatus(e.getErrorCode(), e.getMessage());
+ } catch (SemanticException | TableLostRuntimeException e) {
+ LOGGER.error(DataNodeMiscMessages.ERROR_EXECUTING_PLAN_NODE_CAUSED,
node, e.getMessage());
+ return RpcUtils.getStatus(e.getErrorCode(), e.getMessage());
} catch (MetadataLeaseFencedException e) {
return RpcUtils.getStatus(e.getErrorCode(), e.getMessage());
}
@@ -198,6 +201,9 @@ public class DataExecutionVisitor implements
PlanVisitor<TSStatus, DataRegion> {
}
}
return firstStatus;
+ } catch (final SemanticException | TableLostRuntimeException e) {
+ LOGGER.error(DataNodeMiscMessages.ERROR_EXECUTING_PLAN_NODE_CAUSED,
node, e.getMessage());
+ return RpcUtils.getStatus(e.getErrorCode(), e.getMessage());
} catch (final MetadataLeaseFencedException e) {
return RpcUtils.getStatus(e.getErrorCode(), e.getMessage());
}
@@ -273,6 +279,9 @@ public class DataExecutionVisitor implements
PlanVisitor<TSStatus, DataRegion> {
}
}
return firstStatus;
+ } catch (SemanticException | TableLostRuntimeException e) {
+ LOGGER.error(DataNodeMiscMessages.ERROR_EXECUTING_PLAN_NODE_CAUSED,
node, e.getMessage());
+ return RpcUtils.getStatus(e.getErrorCode(), e.getMessage());
} catch (MetadataLeaseFencedException e) {
return RpcUtils.getStatus(e.getErrorCode(), e.getMessage());
}
@@ -312,6 +321,9 @@ public class DataExecutionVisitor implements
PlanVisitor<TSStatus, DataRegion> {
}
}
return firstStatus;
+ } catch (SemanticException | TableLostRuntimeException e) {
+ LOGGER.error(DataNodeMiscMessages.ERROR_EXECUTING_PLAN_NODE_CAUSED,
node, e.getMessage());
+ return RpcUtils.getStatus(e.getErrorCode(), e.getMessage());
} catch (MetadataLeaseFencedException e) {
return RpcUtils.getStatus(e.getErrorCode(), e.getMessage());
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/table/DataNodeTableCache.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/table/DataNodeTableCache.java
index 1f10cb7f4b5..db813a9d840 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/table/DataNodeTableCache.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/table/DataNodeTableCache.java
@@ -97,6 +97,8 @@ public class DataNodeTableCache implements ITableCache {
private final Map<String, Map<String, Pair<TsTable, Long>>> specialStatusMap
=
new ConcurrentHashMap<>();
+ private final AtomicLong specialStatusVersion = new AtomicLong();
+
private final ReentrantReadWriteLock readWriteLock = new
ReentrantReadWriteLock();
private final Semaphore fetchTableSemaphore =
new Semaphore(
@@ -148,7 +150,7 @@ public class DataNodeTableCache implements ITableCache {
.collect(
Collectors.toMap(
TsTable::getTableName,
- table -> new Pair<>(table, 0L),
+ table -> new Pair<>(table,
specialStatusVersion.incrementAndGet()),
(v1, v2) -> v2,
ConcurrentHashMap::new))));
treeToTableViewCache.init(collectInitialViews(usingMap));
@@ -208,16 +210,17 @@ public class DataNodeTableCache implements ITableCache {
readWriteLock.writeLock().lock();
try {
failIfMetadataLeaseFenced(LeaseFencedRetryPolicy.RETRY_UNTIL_SUCCESS);
+ final TsTable previousTable = getTableFromSpecialStatusMap(database,
table.getTableName());
specialStatusMap
.computeIfAbsent(database, k -> new ConcurrentHashMap<>())
.compute(
table.getTableName(),
(k, v) -> {
if (Objects.isNull(v)) {
- return new Pair<>(table, 0L);
+ return new Pair<>(table,
specialStatusVersion.incrementAndGet());
} else {
v.setLeft(table);
- v.setRight(v.getRight() + 1);
+ v.setRight(specialStatusVersion.incrementAndGet());
return v;
}
});
@@ -231,6 +234,9 @@ public class DataNodeTableCache implements ITableCache {
if (databaseTableMap.containsKey(database)) {
databaseTableMap.get(database).remove(table.getTableName());
}
+ if (!(previousTable instanceof PreDeleteTsTable)) {
+ instanceVersion.incrementAndGet();
+ }
}
// If rename table
@@ -242,10 +248,10 @@ public class DataNodeTableCache implements ITableCache {
oldName,
(k, v) -> {
if (Objects.isNull(v)) {
- return new Pair<>(oldTable, 0L);
+ return new Pair<>(oldTable,
specialStatusVersion.incrementAndGet());
} else {
v.setLeft(oldTable);
- v.setRight(v.getRight() + 1);
+ v.setRight(specialStatusVersion.incrementAndGet());
return v;
}
});
@@ -535,7 +541,10 @@ public class DataNodeTableCache implements ITableCache {
if (Objects.isNull(getTableFromCache(database, newName))) {
specialStatusMap
.computeIfAbsent(database, k -> new ConcurrentHashMap<>())
- .put(newName, new Pair<>(new NonCommittableTsTable(newName), 0L));
+ .put(
+ newName,
+ new Pair<>(
+ new NonCommittableTsTable(newName),
specialStatusVersion.incrementAndGet()));
}
instanceVersion.incrementAndGet();
}
@@ -599,7 +608,7 @@ public class DataNodeTableCache implements ITableCache {
copyTable.removeColumnSchema(columnName);
tableVersionPair.setLeft(copyTable);
}
- tableVersionPair.setRight(tableVersionPair.getRight() + 1);
+ tableVersionPair.setRight(specialStatusVersion.incrementAndGet());
}
instanceVersion.incrementAndGet();
} finally {
@@ -674,7 +683,8 @@ public class DataNodeTableCache implements ITableCache {
if (tableStatusRef.get() == TableNodeStatus.USING) {
updateUsingTable(fetchedTables, specialStatusMap,
leaseFencedRetryPolicy);
} else {
- updateDeleteTable(fetchedTables, database, tableName,
leaseFencedRetryPolicy);
+ updateDeleteTable(
+ fetchedTables, specialStatusMap, database, tableName,
leaseFencedRetryPolicy);
}
}
final TsTable table = getTableInCache(database, tableName,
leaseFencedRetryPolicy);
@@ -824,6 +834,7 @@ public class DataNodeTableCache implements ITableCache {
/** fetch the pre delete table to update */
private void updateDeleteTable(
Map<String, Map<String, TsTable>> fetchedTables,
+ Map<String, Map<String, Long>> previousVersions,
String targetDatabase,
final String targetTable,
final LeaseFencedRetryPolicy leaseFencedRetryPolicy) {
@@ -850,6 +861,12 @@ public class DataNodeTableCache implements ITableCache {
|| !(existingPair.getLeft() instanceof PreDeleteTsTable)) {
continue;
}
+ final Map<String, Long> previousDatabaseVersions =
previousVersions.get(currentDatabase);
+ if (Objects.isNull(previousDatabaseVersions)
+ || !Objects.equals(
+ existingPair.getRight(),
previousDatabaseVersions.get(currentTableName))) {
+ continue;
+ }
final TsTable fetchedTable = tableEntry.getValue();
// case 1. the table is still in the pre delete status, do not update
@@ -880,6 +897,9 @@ public class DataNodeTableCache implements ITableCache {
if (isUpdated) {
instanceVersion.incrementAndGet();
}
+ if (getTableFromSpecialStatusMap(targetDatabase, targetTable) instanceof
PreDeleteTsTable) {
+ targetTableIsStillDeleting = true;
+ }
if (targetTableIsStillDeleting) {
throw new SemanticException(
String.format(
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/DataRegion.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/DataRegion.java
index 13ccb870e48..600e6ba5a68 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/DataRegion.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/DataRegion.java
@@ -32,7 +32,9 @@ import org.apache.iotdb.commons.consensus.DataRegionId;
import org.apache.iotdb.commons.consensus.index.ProgressIndex;
import org.apache.iotdb.commons.exception.DiskSpaceInsufficientException;
import org.apache.iotdb.commons.exception.MetadataException;
+import org.apache.iotdb.commons.exception.MetadataLeaseFencedException;
import
org.apache.iotdb.commons.exception.MetadataLeaseFencedException.LeaseFencedRetryPolicy;
+import org.apache.iotdb.commons.exception.SemanticException;
import org.apache.iotdb.commons.external.caffeine.cache.Cache;
import org.apache.iotdb.commons.external.caffeine.cache.Caffeine;
import org.apache.iotdb.commons.file.SystemFileFactory;
@@ -372,6 +374,8 @@ public class DataRegion implements IDataRegionForQuery {
+ 2 * Long.BYTES))
.build();
+ private static final int TABLE_SCHEMA_RESOLUTION_MAX_ATTEMPTS = 3;
+
/** database info for mem control. */
private final DataRegionInfo dataRegionInfo;
@@ -1731,8 +1735,14 @@ public class DataRegion implements IDataRegionForQuery {
}
try {
- // register TableSchema (and maybe more) for table insertion
registerToTsFile(insertTabletNode, tsFileProcessor);
+ } catch (SemanticException | TableLostRuntimeException e) {
+ markInsertTabletRangesFailed(
+ rangeList, results, RpcUtils.getStatus(e.getErrorCode(),
e.getMessage()));
+ return false;
+ }
+
+ try {
tsFileProcessor.insertTablet(insertTabletNode, rangeList, results,
noFailure, infoForMetrics);
} catch (DataTypeInconsistentException e) {
// flush all MemTables so that the new type can be inserted into a new
MemTable
@@ -1843,68 +1853,141 @@ public class DataRegion implements IDataRegionForQuery
{
return tsFileProcessor;
}
+ TableSchema resolveTableSchemaForTsFileWrite(
+ final String database,
+ final String tableName,
+ final ITableCache tableCache,
+ final boolean generatedByRemoteConsensusLeader) {
+ for (int attempt = 0; attempt < TABLE_SCHEMA_RESOLUTION_MAX_ATTEMPTS;
attempt++) {
+ TsTable tsTable =
+ tableCache.getTable(
+ database, tableName, false,
LeaseFencedRetryPolicy.RETRY_UNTIL_SUCCESS);
+ if (tsTable == null) {
+ final TableSchema schema;
+ try {
+ schema =
+ fetchTableSchemaFromConfigNode(database, tableName,
generatedByRemoteConsensusLeader);
+ } catch (SemanticException | TableLostRuntimeException e) {
+ if (tableCache.getTableInCache(database, tableName) != null) {
+ continue;
+ }
+ throw e;
+ }
+ tsTable = tableCache.getTableInCache(database, tableName);
+ if (tsTable == null) {
+ return schema;
+ }
+ }
+
+ final Pair<Long, Long> tableVersion = tsTable.getInstanceVersion();
+ final TableSchema schema = resolveSchemaFromCache(database, tableName,
tsTable);
+ if (schema != null
+ && tableVersion.equals(tsTable.getInstanceVersion())
+ && tsTable == tableCache.getTableInCache(database, tableName)) {
+ return schema;
+ }
+ }
+
+ throw new MetadataLeaseFencedException(
+ StorageEngineMessages
+
.EXCEPTION_FAILED_TO_OBTAIN_A_STABLE_TABLE_SCHEMA_FOR_TSFILE_REGISTRATION_24F0C44B,
+ LeaseFencedRetryPolicy.RETRY_UNTIL_SUCCESS);
+ }
+
+ TableSchema resolveSchemaFromCache(
+ final String database, final String tableName, final TsTable tsTable) {
+ for (int attempt = 0; attempt < TABLE_SCHEMA_RESOLUTION_MAX_ATTEMPTS;
attempt++) {
+ final Pair<Long, Long> currentVersion = tsTable.getInstanceVersion();
+ final TableSchema cachedSchema = getTableSchemaFromCache(database,
tableName, currentVersion);
+ if (cachedSchema != null) {
+ if (currentVersion.equals(tsTable.getInstanceVersion())) {
+ return cachedSchema;
+ }
+ continue;
+ }
+
+ final TableSchema schema =
TsFileTableSchemaUtil.toTsFileTableSchemaNoAttribute(tsTable);
+ if (!currentVersion.equals(tsTable.getInstanceVersion())) {
+ continue;
+ }
+ cacheTableSchema(database, tableName, currentVersion, schema);
+ if (currentVersion.equals(tsTable.getInstanceVersion())) {
+ return schema;
+ }
+ }
+ return null;
+ }
+
+ TableSchema fetchTableSchemaFromConfigNode(
+ final String database,
+ final String tableName,
+ final boolean generatedByRemoteConsensusLeader) {
+ try (ConfigNodeClient client =
+
ConfigNodeClientManager.getInstance().borrowClient(ConfigNodeInfo.CONFIG_REGION_ID))
{
+ final TDescTableResp resp = client.describeTable(database, tableName,
false);
+ return tableSchemaFromConfigNodeResponse(
+ database, tableName, resp, generatedByRemoteConsensusLeader);
+ } catch (TException | ClientManagerException e) {
+ logger.error(
+ StorageEngineMessages
+
.STORAGE_LOG_REMOTE_REQUEST_CONFIG_NODE_FAILED_THAT_JUDGMENT_IF_TABLE_25FE3602,
+ e.getMessage(),
+ e);
+ throw new SemanticException(e,
TSStatusCode.INTERNAL_SERVER_ERROR.getStatusCode());
+ }
+ }
+
+ TableSchema tableSchemaFromConfigNodeResponse(
+ final String database, final String tableName, final TDescTableResp
resp) {
+ return tableSchemaFromConfigNodeResponse(database, tableName, resp, true);
+ }
+
+ TableSchema tableSchemaFromConfigNodeResponse(
+ final String database,
+ final String tableName,
+ final TDescTableResp resp,
+ final boolean generatedByRemoteConsensusLeader) {
+ if (resp == null || resp.getStatus() == null) {
+ throw new SemanticException(
+ String.format(
+ StorageEngineMessages
+
.EXCEPTION_FAILED_TO_DESCRIBE_TABLE_ARG_ARG_FROM_CONFIGNODE_BFBC7FBC,
+ database,
+ tableName),
+ TSStatusCode.INTERNAL_SERVER_ERROR.getStatusCode());
+ }
+ if (resp.getStatus().getCode() !=
TSStatusCode.SUCCESS_STATUS.getStatusCode()) {
+ if (resp.getStatus().getCode() ==
TSStatusCode.TABLE_NOT_EXISTS.getStatusCode()) {
+ if (generatedByRemoteConsensusLeader) {
+ CommonMetadataUtils.throwTableNotExistsException(database,
tableName);
+ }
+ throw new TableLostRuntimeException(database, tableName);
+ }
+ throw new SemanticException(resp.getStatus().getMessage(),
resp.getStatus().getCode());
+ }
+ if (resp.getTableInfo() == null) {
+ throw new SemanticException(
+ String.format(
+ StorageEngineMessages
+
.EXCEPTION_FAILED_TO_DESCRIBE_TABLE_ARG_ARG_FROM_CONFIGNODE_BFBC7FBC,
+ database,
+ tableName),
+ TSStatusCode.INTERNAL_SERVER_ERROR.getStatusCode());
+ }
+ return TsFileTableSchemaUtil.tsTableBufferToTableSchemaNoAttribute(
+ ByteBuffer.wrap(resp.getTableInfo()));
+ }
+
private void registerToTsFile(InsertNode node, TsFileProcessor
tsFileProcessor) {
final String tableName = node.getTableName();
if (tableName != null) {
final ITableCache tableCache = DataNodeTableCache.getInstance();
tsFileProcessor.registerToTsFile(
tableName,
- tableCache.getInstanceVersion(),
- t -> {
- final String database = getDatabaseName();
-
- TsTable tsTable =
- tableCache.getTable(database, t, false,
LeaseFencedRetryPolicy.RETRY_UNTIL_SUCCESS);
- if (tsTable == null) {
- // There is a high probability that the leader node has been
executed and is currently
- // located in the follower node.
- if (node.isGeneratedByRemoteConsensusLeader()) {
- // If current node is follower, after request config node and
get the answer that
- // table is exist or not, then tell leader node when table is
not exist.
- TDescTableResp resp;
- try (ConfigNodeClient client =
- ConfigNodeClientManager.getInstance()
- .borrowClient(ConfigNodeInfo.CONFIG_REGION_ID)) {
- resp = client.describeTable(getDatabaseName(), tableName,
false);
- if (resp == null || resp.tableInfo == null) {
-
CommonMetadataUtils.throwTableNotExistsException(getDatabaseName(), tableName);
- }
- // For table schema from ConfigNode, we cannot get version
info,
- // so we don't cache it to avoid version mismatch
- final TableSchema schema =
-
TsFileTableSchemaUtil.tsTableBufferToTableSchemaNoAttribute(
- ByteBuffer.wrap(resp.getTableInfo()));
- return schema;
- } catch (TException | ClientManagerException e) {
- logger.error(
- StorageEngineMessages
-
.STORAGE_LOG_REMOTE_REQUEST_CONFIG_NODE_FAILED_THAT_JUDGMENT_IF_TABLE_25FE3602,
- e.getMessage(),
- e);
-
CommonMetadataUtils.throwTableNotExistsException(getDatabaseName(), tableName);
- return null; // unreachable, throwTableNotExistsException
always throws
- }
- } else {
- // Here may be invoked by leader node, the table is very
unexpected not exist in the
- // DataNodeTableCache
- logger.error(
- StorageEngineMessages
-
.STORAGE_LOG_DUE_TSTABLE_IS_NULL_TABLE_SCHEMA_CAN_T_BE_GOT_LEADER_NODE_C3EF524D);
- throw new TableLostRuntimeException(getDatabaseName(),
tableName);
- }
- }
-
- final Pair<Long, Long> currentVersion =
tsTable.getInstanceVersion();
- final TableSchema cachedSchema = getTableSchemaFromCache(database,
t, currentVersion);
- if (cachedSchema != null) {
- return cachedSchema;
- }
-
- final TableSchema schema =
- TsFileTableSchemaUtil.toTsFileTableSchemaNoAttribute(tsTable);
- cacheTableSchema(database, t, currentVersion, schema);
- return schema;
- });
+ tableCache::getInstanceVersion,
+ t ->
+ resolveTableSchemaForTsFileWrite(
+ getDatabaseName(), t, tableCache,
node.isGeneratedByRemoteConsensusLeader()));
}
}
@@ -1988,7 +2071,8 @@ public class DataRegion implements IDataRegionForQuery {
}
}
} catch (WriteProcessException e) {
- recordInsertRowsFailure(insertRowsNode, subInsertRowsNode, e);
+ recordInsertRowsFailure(
+ insertRowsNode.getResults(), subInsertRowsNode, e.getErrorCode(),
e.getMessage());
}
}
return executedInsertRowNodeList;
@@ -1998,8 +2082,14 @@ public class DataRegion implements IDataRegionForQuery {
TsFileProcessor tsFileProcessor, InsertRowsNode subInsertRowsNode,
long[] infoForMetrics)
throws WriteProcessException {
try {
- // register TableSchema (and maybe more) for table insertion
registerToTsFile(subInsertRowsNode, tsFileProcessor);
+ } catch (SemanticException | TableLostRuntimeException e) {
+ final InsertRowsExecutionResult executionResult = new
InsertRowsExecutionResult();
+ executionResult.recordFailure(subInsertRowsNode, e.getErrorCode(),
e.getMessage());
+ return executionResult;
+ }
+
+ try {
tsFileProcessor.insertRows(subInsertRowsNode, infoForMetrics);
InsertRowsExecutionResult executionResult = new
InsertRowsExecutionResult();
executionResult.recordSuccess(tsFileProcessor, subInsertRowsNode);
@@ -2119,6 +2209,11 @@ public class DataRegion implements IDataRegionForQuery {
subInsertRowsNode.isLastFragment() && --remainingRetriedFragments ==
0);
try {
registerToTsFile(retriedInsertRowsNode, retriedProcessor);
+ } catch (SemanticException | TableLostRuntimeException e) {
+ executionResult.recordFailure(retriedInsertRowsNode, e.getErrorCode(),
e.getMessage());
+ continue;
+ }
+ try {
retriedProcessor.insertRows(retriedInsertRowsNode, infoForMetrics);
executionResult.recordSuccess(retriedProcessor, retriedInsertRowsNode);
} catch (WriteProcessException e) {
@@ -2141,8 +2236,12 @@ public class DataRegion implements IDataRegionForQuery {
private void recordFailure(
final InsertRowsNode insertRowsNode, final WriteProcessException
exception) {
- final TSStatus failureStatus =
- RpcUtils.getStatus(exception.getErrorCode(), exception.getMessage());
+ recordFailure(insertRowsNode, exception.getErrorCode(),
exception.getMessage());
+ }
+
+ private void recordFailure(
+ final InsertRowsNode insertRowsNode, final int errorCode, final String
errorMessage) {
+ final TSStatus failureStatus = RpcUtils.getStatus(errorCode,
errorMessage);
for (final int failedIndex : insertRowsNode.getInsertRowNodeIndexList())
{
failedResults.put(failedIndex, failureStatus);
}
@@ -2155,24 +2254,13 @@ public class DataRegion implements IDataRegionForQuery {
}
private void recordInsertRowsFailure(
- final InsertRowsNode sourceInsertRowsNode,
- final InsertRowsNode failedInsertRowsNode,
- final WriteProcessException exception) {
- final TSStatus failureStatus =
- RpcUtils.getStatus(exception.getErrorCode(), exception.getMessage());
- for (Integer failedIndex :
failedInsertRowsNode.getInsertRowNodeIndexList()) {
- sourceInsertRowsNode.getResults().put(failedIndex, failureStatus);
- }
- }
-
- private void recordInsertRowsFailure(
- final InsertRowsOfOneDeviceNode sourceInsertRowsNode,
+ final Map<Integer, TSStatus> results,
final InsertRowsNode failedInsertRowsNode,
- final WriteProcessException exception) {
- final TSStatus failureStatus =
- RpcUtils.getStatus(exception.getErrorCode(), exception.getMessage());
+ final int errorCode,
+ final String errorMessage) {
+ final TSStatus failureStatus = RpcUtils.getStatus(errorCode, errorMessage);
for (Integer failedIndex :
failedInsertRowsNode.getInsertRowNodeIndexList()) {
- sourceInsertRowsNode.getResults().put(failedIndex, failureStatus);
+ results.put(failedIndex, failureStatus);
}
}
@@ -5326,7 +5414,11 @@ public class DataRegion implements IDataRegionForQuery {
}
}
} catch (WriteProcessException e) {
- recordInsertRowsFailure(insertRowsOfOneDeviceNode,
subInsertRowsNode, e);
+ recordInsertRowsFailure(
+ insertRowsOfOneDeviceNode.getResults(),
+ subInsertRowsNode,
+ e.getErrorCode(),
+ e.getMessage());
}
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/memtable/TsFileProcessor.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/memtable/TsFileProcessor.java
index 206623354e5..39abedba289 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/memtable/TsFileProcessor.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/memtable/TsFileProcessor.java
@@ -26,6 +26,8 @@ import org.apache.iotdb.commons.conf.CommonDescriptor;
import org.apache.iotdb.commons.exception.IllegalPathException;
import org.apache.iotdb.commons.exception.IoTDBRuntimeException;
import org.apache.iotdb.commons.exception.MetadataException;
+import org.apache.iotdb.commons.exception.MetadataLeaseFencedException;
+import
org.apache.iotdb.commons.exception.MetadataLeaseFencedException.LeaseFencedRetryPolicy;
import org.apache.iotdb.commons.path.AlignedPath;
import org.apache.iotdb.commons.path.IFullPath;
import org.apache.iotdb.commons.schema.table.column.TsTableColumnCategory;
@@ -126,6 +128,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Function;
+import java.util.function.LongSupplier;
import static
org.apache.iotdb.calc.metric.QueryExecutionMetricSet.GET_QUERY_RESOURCE_FROM_MEM;
import static
org.apache.iotdb.db.queryengine.metric.QueryResourceMetricSet.FLUSHING_MEMTABLE;
@@ -134,6 +137,8 @@ import static
org.apache.iotdb.db.queryengine.metric.QueryResourceMetricSet.WORK
@SuppressWarnings("java:S1135") // ignore todos
public class TsFileProcessor {
+ private static final int TABLE_SCHEMA_REGISTRATION_MAX_ATTEMPTS = 3;
+
/** Logger fot this class. */
private static final Logger logger =
LoggerFactory.getLogger(TsFileProcessor.class);
@@ -2880,15 +2885,33 @@ public class TsFileProcessor {
}
public void registerToTsFile(
- String tableName, long tableCacheVersion, Function<String, TableSchema>
tableSchemaFunction) {
+ String tableName,
+ LongSupplier tableCacheVersionSupplier,
+ Function<String, TableSchema> tableSchemaFunction) {
registeredTableSchemaVersions.compute(
tableName,
(name, registeredVersion) -> {
- if (registeredVersion != null && registeredVersion ==
tableCacheVersion) {
+ final long currentVersion = tableCacheVersionSupplier.getAsLong();
+ if (registeredVersion != null
+ && registeredVersion == currentVersion
+ && currentVersion == tableCacheVersionSupplier.getAsLong()) {
return registeredVersion;
}
- getWriter().getSchema().getTableSchemaMap().put(name,
tableSchemaFunction.apply(name));
- return tableCacheVersion;
+ for (int attempt = 0; attempt <
TABLE_SCHEMA_REGISTRATION_MAX_ATTEMPTS; attempt++) {
+ final long tableCacheVersion =
tableCacheVersionSupplier.getAsLong();
+ final TableSchema tableSchema = tableSchemaFunction.apply(name);
+ if (tableCacheVersion != tableCacheVersionSupplier.getAsLong()) {
+ continue;
+ }
+ getWriter().getSchema().getTableSchemaMap().put(name, tableSchema);
+ if (tableCacheVersion == tableCacheVersionSupplier.getAsLong()) {
+ return tableCacheVersion;
+ }
+ }
+ throw new MetadataLeaseFencedException(
+ StorageEngineMessages
+
.EXCEPTION_FAILED_TO_OBTAIN_A_STABLE_TABLE_SCHEMA_FOR_TSFILE_REGISTRATION_24F0C44B,
+ LeaseFencedRetryPolicy.RETRY_UNTIL_SUCCESS);
});
}
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/consensus/statemachine/dataregion/DataExecutionVisitorTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/consensus/statemachine/dataregion/DataExecutionVisitorTest.java
index 60fcf8878a4..0abe7a85f33 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/consensus/statemachine/dataregion/DataExecutionVisitorTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/consensus/statemachine/dataregion/DataExecutionVisitorTest.java
@@ -27,8 +27,11 @@ import org.apache.iotdb.commons.path.PartialPath;
import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.PlanNodeId;
import org.apache.iotdb.db.exception.runtime.TableLostRuntimeException;
import
org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.DeleteDataNode;
+import
org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.InsertMultiTabletsNode;
import
org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.InsertRowNode;
import
org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.InsertRowsNode;
+import
org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.InsertRowsOfOneDeviceNode;
+import
org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.InsertTabletNode;
import
org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.RelationalDeleteDataNode;
import org.apache.iotdb.db.storageengine.dataregion.DataRegion;
import org.apache.iotdb.rpc.TSStatusCode;
@@ -78,6 +81,112 @@ public class DataExecutionVisitorTest {
new TableLostRuntimeException("test_db", "test_table"));
}
+ @Test
+ public void testInsertRowSemanticFailureReturnsStatus() throws Exception {
+ assertInsertRowFailureReturnsStatus(new SemanticException("injected write
failure"));
+ }
+
+ @Test
+ public void testInsertRowTableLostFailureReturnsStatus() throws Exception {
+ assertInsertRowFailureReturnsStatus(new
TableLostRuntimeException("test_db", "test_table"));
+ }
+
+ @Test
+ public void testInsertTabletSemanticFailureReturnsStatus() throws Exception {
+ assertInsertTabletFailureReturnsStatus(new SemanticException("injected
write failure"));
+ }
+
+ @Test
+ public void testInsertTabletTableLostFailureReturnsStatus() throws Exception
{
+ assertInsertTabletFailureReturnsStatus(new
TableLostRuntimeException("test_db", "test_table"));
+ }
+
+ @Test
+ public void testInsertMultiTabletsSemanticFailureReturnsStatus() throws
Exception {
+ assertInsertMultiTabletsFailureReturnsStatus(new
SemanticException("injected write failure"));
+ }
+
+ @Test
+ public void testInsertMultiTabletsTableLostFailureReturnsStatus() throws
Exception {
+ assertInsertMultiTabletsFailureReturnsStatus(
+ new TableLostRuntimeException("test_db", "test_table"));
+ }
+
+ @Test
+ public void testInsertRowsOfOneDeviceSemanticFailureReturnsStatus() throws
Exception {
+ assertInsertRowsOfOneDeviceFailureReturnsStatus(
+ new SemanticException("injected write failure"));
+ }
+
+ @Test
+ public void testInsertRowsOfOneDeviceTableLostFailureReturnsStatus() throws
Exception {
+ assertInsertRowsOfOneDeviceFailureReturnsStatus(
+ new TableLostRuntimeException("test_db", "test_table"));
+ }
+
+ private void assertInsertRowFailureReturnsStatus(final IoTDBRuntimeException
failure)
+ throws Exception {
+ final DataRegion dataRegion = Mockito.mock(DataRegion.class);
+ Mockito.doThrow(failure).when(dataRegion).insert(any(InsertRowNode.class));
+ final InsertRowNode insertRowNode =
+ new InsertRowNode(
+ new PlanNodeId("write-log-test"),
+ new PartialPath("root.sg.device"),
+ false,
+ new String[] {"s1"},
+ new TSDataType[] {TSDataType.INT64},
+ 1L,
+ new Object[] {1L},
+ false);
+
+ final TSStatus status = new
DataExecutionVisitor().visitInsertRow(insertRowNode, dataRegion);
+
+ Assert.assertEquals(failure.getErrorCode(), status.getCode());
+ Assert.assertEquals(failure.getMessage(), status.getMessage());
+ }
+
+ private void assertInsertTabletFailureReturnsStatus(final
IoTDBRuntimeException failure)
+ throws Exception {
+ final DataRegion dataRegion = Mockito.mock(DataRegion.class);
+
Mockito.doThrow(failure).when(dataRegion).insertTablet(any(InsertTabletNode.class));
+ final InsertTabletNode insertTabletNode = new InsertTabletNode(new
PlanNodeId("tablet-test"));
+
+ final TSStatus status =
+ new DataExecutionVisitor().visitInsertTablet(insertTabletNode,
dataRegion);
+
+ Assert.assertEquals(failure.getErrorCode(), status.getCode());
+ Assert.assertEquals(failure.getMessage(), status.getMessage());
+ }
+
+ private void assertInsertMultiTabletsFailureReturnsStatus(final
IoTDBRuntimeException failure)
+ throws Exception {
+ final DataRegion dataRegion = Mockito.mock(DataRegion.class);
+
Mockito.doThrow(failure).when(dataRegion).insertTablets(any(InsertMultiTabletsNode.class));
+ final InsertMultiTabletsNode insertMultiTabletsNode =
+ new InsertMultiTabletsNode(new PlanNodeId("multi-tablets-test"));
+
+ final TSStatus status =
+ new
DataExecutionVisitor().visitInsertMultiTablets(insertMultiTabletsNode,
dataRegion);
+
+ Assert.assertEquals(failure.getErrorCode(), status.getCode());
+ Assert.assertEquals(failure.getMessage(), status.getMessage());
+ }
+
+ private void assertInsertRowsOfOneDeviceFailureReturnsStatus(final
IoTDBRuntimeException failure)
+ throws Exception {
+ final DataRegion dataRegion = Mockito.mock(DataRegion.class);
+
Mockito.doThrow(failure).when(dataRegion).insert(any(InsertRowsOfOneDeviceNode.class));
+ final InsertRowsOfOneDeviceNode insertRowsOfOneDeviceNode =
+ new InsertRowsOfOneDeviceNode(new PlanNodeId("rows-one-device-test"));
+
+ final TSStatus status =
+ new DataExecutionVisitor()
+ .visitInsertRowsOfOneDevice(insertRowsOfOneDeviceNode, dataRegion);
+
+ Assert.assertEquals(failure.getErrorCode(), status.getCode());
+ Assert.assertEquals(failure.getMessage(), status.getMessage());
+ }
+
private void assertInsertRowsFailureWithoutStackTrace(final
IoTDBRuntimeException failure)
throws Exception {
final DataRegion dataRegion = Mockito.mock(DataRegion.class);
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/schemaengine/table/DataNodeTableCacheTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/schemaengine/table/DataNodeTableCacheTest.java
index 18ee416d2e8..04c8998a3fc 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/schemaengine/table/DataNodeTableCacheTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/schemaengine/table/DataNodeTableCacheTest.java
@@ -72,6 +72,29 @@ public class DataNodeTableCacheTest {
}
}
+ @Test
+ public void preDeleteInvalidatesTableSchemaVersionOnlyOnce() {
+ final ITableCache cache = DataNodeTableCache.getInstance();
+ cache.invalid(TABLE_CACHE_TEST_DATABASE);
+ try {
+ cache.preUpdateTable(TABLE_CACHE_TEST_DATABASE, createTable(TABLE_NAME),
null);
+ cache.commitUpdateTable(TABLE_CACHE_TEST_DATABASE, TABLE_NAME, null,
null);
+ final long versionBeforePreDelete = cache.getInstanceVersion();
+
+ cache.preUpdateTable(TABLE_CACHE_TEST_DATABASE, new
PreDeleteTsTable(TABLE_NAME), null);
+ final long versionAfterPreDelete = cache.getInstanceVersion();
+
+ Assert.assertTrue(versionAfterPreDelete > versionBeforePreDelete);
+ Assert.assertNull(cache.getTableInCache(TABLE_CACHE_TEST_DATABASE,
TABLE_NAME));
+
+ cache.preUpdateTable(TABLE_CACHE_TEST_DATABASE, new
PreDeleteTsTable(TABLE_NAME), null);
+
+ Assert.assertEquals(versionAfterPreDelete, cache.getInstanceVersion());
+ } finally {
+ cache.invalid(TABLE_CACHE_TEST_DATABASE);
+ }
+ }
+
@Test
public void interruptedFetchDoesNotLeakSemaphorePermit() throws Exception {
final ITableCache cache = DataNodeTableCache.getInstance();
@@ -198,6 +221,89 @@ public class DataNodeTableCacheTest {
}
}
+ @Test
+ public void fetchingMissingPreDeleteEntryReportsDedicatedStatusCode() throws
Exception {
+ final ITableCache cache = DataNodeTableCache.getInstance();
+ cache.invalid(DATABASE);
+ try {
+ cache.preUpdateTable(DATABASE, createTable(TABLE_NAME), null);
+ cache.commitUpdateTable(DATABASE, TABLE_NAME, null, null);
+ cache.preUpdateTable(DATABASE, new PreDeleteTsTable(TABLE_NAME), null);
+
+ final InvocationTargetException thrown =
+ Assert.assertThrows(
+ InvocationTargetException.class,
+ () -> updateDeleteTable(cache, Collections.emptyMap(),
TABLE_NAME));
+
+ final SemanticException cause = (SemanticException) thrown.getCause();
+ Assert.assertEquals(TSStatusCode.TABLE_IN_PRE_DELETE.getStatusCode(),
cause.getErrorCode());
+ Assert.assertNull(cache.getTableInCache(DATABASE, TABLE_NAME));
+ Assert.assertTrue(
+ getSpecialStatusTable(cache, DATABASE, TABLE_NAME) instanceof
PreDeleteTsTable);
+ } finally {
+ cache.invalid(DATABASE);
+ }
+ }
+
+ @Test
+ public void stalePreDeleteFetchDoesNotClearUpdatedPreDeleteMarker() throws
Exception {
+ final ITableCache cache = DataNodeTableCache.getInstance();
+ cache.invalid(DATABASE);
+ try {
+ cache.preUpdateTable(DATABASE, createTable(TABLE_NAME), null);
+ cache.commitUpdateTable(DATABASE, TABLE_NAME, null, null);
+ cache.preUpdateTable(DATABASE, new PreDeleteTsTable(TABLE_NAME), null);
+ final Map<String, Map<String, Long>> previousVersions =
+ getSpecialStatusVersions(cache, DATABASE, TABLE_NAME);
+
+ cache.preUpdateTable(DATABASE, new PreDeleteTsTable(TABLE_NAME), null);
+
+ final Map<String, Map<String, TsTable>> fetchedTables = new HashMap<>();
+ fetchedTables.put(DATABASE, Collections.singletonMap(TABLE_NAME,
createTable(TABLE_NAME)));
+ final InvocationTargetException thrown =
+ Assert.assertThrows(
+ InvocationTargetException.class,
+ () -> updateDeleteTable(cache, fetchedTables, TABLE_NAME,
previousVersions));
+
+ final SemanticException cause = (SemanticException) thrown.getCause();
+ Assert.assertEquals(TSStatusCode.TABLE_IN_PRE_DELETE.getStatusCode(),
cause.getErrorCode());
+ Assert.assertNull(cache.getTableInCache(DATABASE, TABLE_NAME));
+ Assert.assertTrue(
+ getSpecialStatusTable(cache, DATABASE, TABLE_NAME) instanceof
PreDeleteTsTable);
+ } finally {
+ cache.invalid(DATABASE);
+ }
+ }
+
+ @Test
+ public void stalePreDeleteFetchDoesNotClearMarkerAfterCacheReset() throws
Exception {
+ final ITableCache cache = DataNodeTableCache.getInstance();
+ cache.invalid(DATABASE);
+ try {
+ cache.preUpdateTable(DATABASE, new PreDeleteTsTable(TABLE_NAME), null);
+ final Map<String, Map<String, Long>> previousVersions =
+ getSpecialStatusVersions(cache, DATABASE, TABLE_NAME);
+
+ cache.invalid(DATABASE);
+ cache.preUpdateTable(DATABASE, new PreDeleteTsTable(TABLE_NAME), null);
+
+ final Map<String, Map<String, TsTable>> fetchedTables = new HashMap<>();
+ fetchedTables.put(DATABASE, Collections.singletonMap(TABLE_NAME,
createTable(TABLE_NAME)));
+ final InvocationTargetException thrown =
+ Assert.assertThrows(
+ InvocationTargetException.class,
+ () -> updateDeleteTable(cache, fetchedTables, TABLE_NAME,
previousVersions));
+
+ final SemanticException cause = (SemanticException) thrown.getCause();
+ Assert.assertEquals(TSStatusCode.TABLE_IN_PRE_DELETE.getStatusCode(),
cause.getErrorCode());
+ Assert.assertNull(cache.getTableInCache(DATABASE, TABLE_NAME));
+ Assert.assertTrue(
+ getSpecialStatusTable(cache, DATABASE, TABLE_NAME) instanceof
PreDeleteTsTable);
+ } finally {
+ cache.invalid(DATABASE);
+ }
+ }
+
/**
* The pre-delete branch lives in the private {@code updateDeleteTable},
which is only reachable
* through a ConfigNode fetch, so invoke it directly.
@@ -207,16 +313,32 @@ public class DataNodeTableCacheTest {
final Map<String, Map<String, TsTable>> fetchedTables,
final String tableName)
throws Exception {
+ updateDeleteTable(
+ cache, fetchedTables, tableName, getSpecialStatusVersions(cache,
DATABASE, tableName));
+ }
+
+ private static void updateDeleteTable(
+ final ITableCache cache,
+ final Map<String, Map<String, TsTable>> fetchedTables,
+ final String tableName,
+ final Map<String, Map<String, Long>> previousVersions)
+ throws Exception {
final Method method =
DataNodeTableCache.class.getDeclaredMethod(
"updateDeleteTable",
Map.class,
+ Map.class,
String.class,
String.class,
LeaseFencedRetryPolicy.class);
method.setAccessible(true);
method.invoke(
- cache, fetchedTables, DATABASE, tableName,
LeaseFencedRetryPolicy.RETRY_UNTIL_SUCCESS);
+ cache,
+ fetchedTables,
+ previousVersions,
+ DATABASE,
+ tableName,
+ LeaseFencedRetryPolicy.RETRY_UNTIL_SUCCESS);
}
/** The old name must be gone, and the new name left as a placeholder to be
re-fetched. */
@@ -245,6 +367,19 @@ public class DataNodeTableCacheTest {
return Objects.isNull(tablePair) ? null : tablePair.getLeft();
}
+ @SuppressWarnings("unchecked")
+ private static Map<String, Map<String, Long>> getSpecialStatusVersions(
+ final ITableCache cache, final String database, final String tableName)
throws Exception {
+ final Field field =
DataNodeTableCache.class.getDeclaredField("specialStatusMap");
+ field.setAccessible(true);
+ final Map<String, Map<String, Pair<TsTable, Long>>> specialStatusMap =
+ (Map<String, Map<String, Pair<TsTable, Long>>>) field.get(cache);
+ final String unqualifiedDatabase =
PathUtils.unQualifyDatabaseName(database);
+ final Pair<TsTable, Long> tablePair =
specialStatusMap.get(unqualifiedDatabase).get(tableName);
+ return Collections.singletonMap(
+ unqualifiedDatabase, Collections.singletonMap(tableName,
tablePair.getRight()));
+ }
+
private Semaphore getFetchTableSemaphore(final ITableCache cache) throws
Exception {
final Field field =
DataNodeTableCache.class.getDeclaredField("fetchTableSemaphore");
field.setAccessible(true);
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/DataRegionSchemaResolutionTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/DataRegionSchemaResolutionTest.java
new file mode 100644
index 00000000000..e3172326d70
--- /dev/null
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/DataRegionSchemaResolutionTest.java
@@ -0,0 +1,294 @@
+/*
+ * 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.storageengine.dataregion;
+
+import org.apache.iotdb.common.rpc.thrift.TSStatus;
+import org.apache.iotdb.commons.exception.MetadataLeaseFencedException;
+import
org.apache.iotdb.commons.exception.MetadataLeaseFencedException.LeaseFencedRetryPolicy;
+import org.apache.iotdb.commons.exception.SemanticException;
+import org.apache.iotdb.commons.schema.table.TsTable;
+import org.apache.iotdb.commons.schema.table.column.FieldColumnSchema;
+import org.apache.iotdb.confignode.rpc.thrift.TDescTableResp;
+import org.apache.iotdb.db.exception.runtime.TableLostRuntimeException;
+import org.apache.iotdb.db.schemaengine.table.ITableCache;
+import org.apache.iotdb.rpc.TSStatusCode;
+
+import org.apache.tsfile.enums.TSDataType;
+import org.apache.tsfile.file.metadata.TableSchema;
+import org.apache.tsfile.utils.Pair;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class DataRegionSchemaResolutionTest {
+
+ @Test
+ public void testCacheMissFetchesSchemaFromConfigNode() {
+ final String database = "schema_resolution_db";
+ final String tableName = "schema_resolution_table";
+ final DataRegion dataRegion = Mockito.mock(DataRegion.class,
Mockito.CALLS_REAL_METHODS);
+ final ITableCache tableCache = Mockito.mock(ITableCache.class);
+ final TableSchema fetchedSchema = Mockito.mock(TableSchema.class);
+ when(tableCache.getTable(anyString(), anyString(), anyBoolean(),
any())).thenReturn(null);
+ doReturn(fetchedSchema)
+ .when(dataRegion)
+ .fetchTableSchemaFromConfigNode(database, tableName, false);
+
+ final TableSchema schema =
+ dataRegion.resolveTableSchemaForTsFileWrite(database, tableName,
tableCache, false);
+
+ Assert.assertSame(fetchedSchema, schema);
+ verify(tableCache)
+ .getTable(database, tableName, false,
LeaseFencedRetryPolicy.RETRY_UNTIL_SUCCESS);
+ verify(dataRegion).fetchTableSchemaFromConfigNode(database, tableName,
false);
+ }
+
+ @Test
+ public void testCacheMissDoesNotRetryWhenGlobalCacheVersionChanges() {
+ final String database = "schema_resolution_db";
+ final String tableName = "schema_resolution_table";
+ final DataRegion dataRegion = Mockito.mock(DataRegion.class,
Mockito.CALLS_REAL_METHODS);
+ final ITableCache tableCache = Mockito.mock(ITableCache.class);
+ final TableSchema fetchedSchema = Mockito.mock(TableSchema.class);
+ when(tableCache.getTable(anyString(), anyString(), anyBoolean(),
any())).thenReturn(null);
+ when(tableCache.getInstanceVersion()).thenReturn(0L, 1L);
+ when(tableCache.getTableInCache(database, tableName)).thenReturn(null);
+ doReturn(fetchedSchema)
+ .when(dataRegion)
+ .fetchTableSchemaFromConfigNode(database, tableName, false);
+
+ final TableSchema schema =
+ dataRegion.resolveTableSchemaForTsFileWrite(database, tableName,
tableCache, false);
+
+ Assert.assertSame(fetchedSchema, schema);
+ verify(dataRegion).fetchTableSchemaFromConfigNode(database, tableName,
false);
+ verify(tableCache, Mockito.never()).getInstanceVersion();
+ }
+
+ @Test
+ public void
testCacheMissPreservesConfigNodeErrorWhenGlobalCacheVersionChanges() {
+ final String database = "schema_resolution_db";
+ final String tableName = "schema_resolution_table";
+ final DataRegion dataRegion = Mockito.mock(DataRegion.class,
Mockito.CALLS_REAL_METHODS);
+ final ITableCache tableCache = Mockito.mock(ITableCache.class);
+ final SemanticException failure = new SemanticException("ConfigNode
unavailable");
+
+ when(tableCache.getTable(anyString(), anyString(), anyBoolean(),
any())).thenReturn(null);
+ when(tableCache.getInstanceVersion()).thenReturn(0L, 1L);
+ when(tableCache.getTableInCache(database, tableName)).thenReturn(null);
+ Mockito.doThrow(failure)
+ .when(dataRegion)
+ .fetchTableSchemaFromConfigNode(database, tableName, false);
+
+ try {
+ dataRegion.resolveTableSchemaForTsFileWrite(database, tableName,
tableCache, false);
+ Assert.fail("Expected the ConfigNode error to be preserved");
+ } catch (SemanticException e) {
+ Assert.assertSame(failure, e);
+ }
+ verify(dataRegion).fetchTableSchemaFromConfigNode(database, tableName,
false);
+ }
+
+ @Test
+ public void testReplacedTableUsesUpdatedCachedSchema() {
+ final String database = "schema_resolution_db";
+ final String tableName = "schema_resolution_table";
+ final DataRegion dataRegion = Mockito.mock(DataRegion.class,
Mockito.CALLS_REAL_METHODS);
+ final ITableCache tableCache = Mockito.mock(ITableCache.class);
+ final TsTable staleTable = Mockito.mock(TsTable.class);
+ final TsTable updatedTable = Mockito.mock(TsTable.class);
+ final TableSchema staleSchema = Mockito.mock(TableSchema.class);
+ final TableSchema updatedSchema = Mockito.mock(TableSchema.class);
+ final AtomicInteger tableLookups = new AtomicInteger();
+
+ Mockito.doAnswer(invocation -> tableLookups.getAndIncrement() == 0 ?
staleTable : updatedTable)
+ .when(tableCache)
+ .getTable(anyString(), anyString(), anyBoolean(), any());
+ when(tableCache.getTableInCache(database,
tableName)).thenReturn(updatedTable);
+ when(staleTable.getInstanceVersion()).thenReturn(new Pair<>(1L, 1L));
+ when(updatedTable.getInstanceVersion()).thenReturn(new Pair<>(1L, 1L));
+ doReturn(staleSchema).when(dataRegion).resolveSchemaFromCache(database,
tableName, staleTable);
+ doReturn(updatedSchema)
+ .when(dataRegion)
+ .resolveSchemaFromCache(database, tableName, updatedTable);
+
+ final TableSchema schema =
+ dataRegion.resolveTableSchemaForTsFileWrite(database, tableName,
tableCache, false);
+
+ Assert.assertSame(updatedSchema, schema);
+ verify(dataRegion).resolveSchemaFromCache(database, tableName, staleTable);
+ verify(dataRegion).resolveSchemaFromCache(database, tableName,
updatedTable);
+ verify(dataRegion,
Mockito.never()).fetchTableSchemaFromConfigNode(database, tableName, false);
+ }
+
+ @Test
+ public void testCacheMissUsesTableInstalledWhileConfigNodeFetchFails() {
+ final String database = "schema_resolution_db";
+ final String tableName = "schema_resolution_table";
+ final DataRegion dataRegion = Mockito.mock(DataRegion.class,
Mockito.CALLS_REAL_METHODS);
+ final ITableCache tableCache = Mockito.mock(ITableCache.class);
+ final TsTable updatedTable = Mockito.mock(TsTable.class);
+ final TableSchema updatedSchema = Mockito.mock(TableSchema.class);
+ final AtomicInteger tableLookups = new AtomicInteger();
+
+ Mockito.doAnswer(invocation -> tableLookups.getAndIncrement() == 0 ? null
: updatedTable)
+ .when(tableCache)
+ .getTable(anyString(), anyString(), anyBoolean(), any());
+ when(tableCache.getTableInCache(database,
tableName)).thenReturn(updatedTable);
+ when(updatedTable.getInstanceVersion()).thenReturn(new Pair<>(1L, 1L));
+ doReturn(updatedSchema)
+ .when(dataRegion)
+ .resolveSchemaFromCache(database, tableName, updatedTable);
+ Mockito.doThrow(new SemanticException("ConfigNode unavailable"))
+ .when(dataRegion)
+ .fetchTableSchemaFromConfigNode(database, tableName, false);
+
+ final TableSchema schema =
+ dataRegion.resolveTableSchemaForTsFileWrite(database, tableName,
tableCache, false);
+
+ Assert.assertSame(updatedSchema, schema);
+ verify(dataRegion).fetchTableSchemaFromConfigNode(database, tableName,
false);
+ }
+
+ @Test
+ public void testSchemaCacheHitIsInvalidatedWhenTableVersionChanges() {
+ final String database = "schema_resolution_cache_db";
+ final String tableName = "schema_resolution_cache_table";
+ final DataRegion dataRegion = Mockito.mock(DataRegion.class,
Mockito.CALLS_REAL_METHODS);
+ final TsTable tsTable = new TsTable(tableName);
+ tsTable.addColumnSchema(new FieldColumnSchema("field_1",
TSDataType.INT32));
+
+ final TableSchema originalSchema =
+ dataRegion.resolveSchemaFromCache(database, tableName, tsTable);
+ Assert.assertSame(
+ originalSchema, dataRegion.resolveSchemaFromCache(database, tableName,
tsTable));
+
+ tsTable.addColumnSchema(new FieldColumnSchema("field_2",
TSDataType.INT64));
+ final TableSchema updatedSchema =
+ dataRegion.resolveSchemaFromCache(database, tableName, tsTable);
+
+ Assert.assertNotSame(originalSchema, updatedSchema);
+ Assert.assertEquals(2, updatedSchema.getColumnTypes().size());
+ }
+
+ @Test
+ public void testRepeatedSchemaVersionChangesAreBoundedAndRetried() {
+ final String database = "schema_resolution_unstable_db";
+ final String tableName = "schema_resolution_unstable_table";
+ final DataRegion dataRegion = Mockito.mock(DataRegion.class,
Mockito.CALLS_REAL_METHODS);
+ final ITableCache tableCache = Mockito.mock(ITableCache.class);
+ final TsTable tsTable = Mockito.mock(TsTable.class);
+ final AtomicLong version = new AtomicLong();
+
+ when(tableCache.getTable(anyString(), anyString(), anyBoolean(),
any())).thenReturn(tsTable);
+ when(tableCache.getTableInCache(database, tableName)).thenReturn(tsTable);
+ when(tsTable.getInstanceVersion())
+ .thenAnswer(invocation -> new Pair<>(1L, version.getAndIncrement()));
+ when(tsTable.getTableName()).thenReturn(tableName);
+
when(tsTable.getColumnList()).thenReturn(java.util.Collections.emptyList());
+
+ try {
+ dataRegion.resolveTableSchemaForTsFileWrite(database, tableName,
tableCache, false);
+ Assert.fail("Expected a retry when the table schema keeps changing");
+ } catch (MetadataLeaseFencedException e) {
+ Assert.assertEquals(
+ TSStatusCode.METADATA_LEASE_FENCED_RETRY_REQUIRED.getStatusCode(),
e.getErrorCode());
+ }
+ verify(tableCache, Mockito.times(3))
+ .getTable(database, tableName, false,
LeaseFencedRetryPolicy.RETRY_UNTIL_SUCCESS);
+ verify(tsTable, Mockito.times(9)).getColumnList();
+ }
+
+ @Test
+ public void testConfigNodeErrorStatusIsNotReportedAsMissingTable() {
+ final String database = "schema_resolution_db";
+ final String tableName = "schema_resolution_table";
+ final DataRegion dataRegion = Mockito.mock(DataRegion.class,
Mockito.CALLS_REAL_METHODS);
+ final TDescTableResp response =
+ new TDescTableResp(
+ new TSStatus(TSStatusCode.EXECUTE_STATEMENT_ERROR.getStatusCode())
+ .setMessage("ConfigNode schema read failed"));
+
+ try {
+ dataRegion.tableSchemaFromConfigNodeResponse(database, tableName,
response);
+ Assert.fail("Expected the ConfigNode error status to be preserved");
+ } catch (SemanticException e) {
+
Assert.assertEquals(TSStatusCode.EXECUTE_STATEMENT_ERROR.getStatusCode(),
e.getErrorCode());
+ Assert.assertEquals("ConfigNode schema read failed", e.getMessage());
+ }
+ }
+
+ @Test
+ public void testMissingTableRemainsSemanticError() {
+ final String database = "schema_resolution_db";
+ final String tableName = "schema_resolution_table";
+ final DataRegion dataRegion = Mockito.mock(DataRegion.class,
Mockito.CALLS_REAL_METHODS);
+ final TDescTableResp response =
+ new TDescTableResp(new
TSStatus(TSStatusCode.TABLE_NOT_EXISTS.getStatusCode()));
+
+ try {
+ dataRegion.tableSchemaFromConfigNodeResponse(database, tableName,
response);
+ Assert.fail("Expected a missing-table error");
+ } catch (SemanticException e) {
+ Assert.assertEquals(TSStatusCode.SEMANTIC_ERROR.getStatusCode(),
e.getErrorCode());
+ }
+ }
+
+ @Test
+ public void testMissingTableRemainsTableLostForLocalWrite() {
+ final String database = "schema_resolution_db";
+ final String tableName = "schema_resolution_table";
+ final DataRegion dataRegion = Mockito.mock(DataRegion.class,
Mockito.CALLS_REAL_METHODS);
+ final TDescTableResp response =
+ new TDescTableResp(new
TSStatus(TSStatusCode.TABLE_NOT_EXISTS.getStatusCode()));
+
+ try {
+ dataRegion.tableSchemaFromConfigNodeResponse(database, tableName,
response, false);
+ Assert.fail("Expected a table-lost error");
+ } catch (TableLostRuntimeException e) {
+ Assert.assertEquals(TSStatusCode.TABLE_IS_LOST.getStatusCode(),
e.getErrorCode());
+ }
+ }
+
+ @Test
+ public void
testSuccessfulResponseWithoutTableInfoIsNotReportedAsMissingTable() {
+ final String database = "schema_resolution_db";
+ final String tableName = "schema_resolution_table";
+ final DataRegion dataRegion = Mockito.mock(DataRegion.class,
Mockito.CALLS_REAL_METHODS);
+ final TDescTableResp response =
+ new TDescTableResp(new
TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode()));
+
+ try {
+ dataRegion.tableSchemaFromConfigNodeResponse(database, tableName,
response);
+ Assert.fail("Expected an invalid ConfigNode response error");
+ } catch (SemanticException e) {
+ Assert.assertEquals(TSStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(),
e.getErrorCode());
+ }
+ }
+}
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/memtable/TsFileProcessorTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/memtable/TsFileProcessorTest.java
index 116782cdff7..e057d3fa4a3 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/memtable/TsFileProcessorTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/memtable/TsFileProcessorTest.java
@@ -112,6 +112,7 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
import static junit.framework.TestCase.assertTrue;
import static
org.apache.iotdb.db.storageengine.dataregion.DataRegionTest.buildInsertRowNodeByTSRecord;
@@ -184,26 +185,50 @@ public class TsFileProcessorTest {
final AtomicInteger supplierCalls = new AtomicInteger();
final AtomicInteger secondTableSupplierCalls = new AtomicInteger();
+ final AtomicLong tableCacheVersion = new AtomicLong(1);
final TableSchema firstSchema = new TableSchema("table1");
final TableSchema updatedSchema = new TableSchema("table1");
final TableSchema secondTableSchema = new TableSchema("table2");
processor.registerToTsFile(
"table1",
- 1,
- tableName -> supplierCalls.incrementAndGet() == 1 ? firstSchema :
updatedSchema);
+ tableCacheVersion::get,
+ tableName -> {
+ if (supplierCalls.incrementAndGet() == 1) {
+ tableCacheVersion.incrementAndGet();
+ return firstSchema;
+ }
+ return updatedSchema;
+ });
processor.registerToTsFile(
"table1",
- 1,
+ tableCacheVersion::get,
tableName -> supplierCalls.incrementAndGet() == 1 ? firstSchema :
updatedSchema);
- Assert.assertEquals(1, supplierCalls.get());
+ Assert.assertEquals(2, supplierCalls.get());
+ Assert.assertSame(
+ updatedSchema,
processor.getWriter().getSchema().getTableSchemaMap().get("table1"));
+
+ final AtomicInteger registrationVersionReads = new AtomicInteger();
+ final AtomicInteger racingSchemaCalls = new AtomicInteger();
+ final AtomicLong racingCacheVersion = new AtomicLong(10);
+ final TableSchema staleSchema = new TableSchema("race_table");
+ final TableSchema currentSchema = new TableSchema("race_table");
+ processor.registerToTsFile(
+ "race_table",
+ () ->
+ registrationVersionReads.incrementAndGet() == 4
+ ? racingCacheVersion.incrementAndGet()
+ : racingCacheVersion.get(),
+ tableName -> racingSchemaCalls.incrementAndGet() == 1 ? staleSchema :
currentSchema);
+
+ Assert.assertEquals(2, racingSchemaCalls.get());
Assert.assertSame(
- firstSchema,
processor.getWriter().getSchema().getTableSchemaMap().get("table1"));
+ currentSchema,
processor.getWriter().getSchema().getTableSchemaMap().get("race_table"));
processor.registerToTsFile(
"table2",
- 1,
+ tableCacheVersion::get,
tableName -> {
secondTableSupplierCalls.incrementAndGet();
return secondTableSchema;
@@ -213,12 +238,13 @@ public class TsFileProcessorTest {
Assert.assertSame(
secondTableSchema,
processor.getWriter().getSchema().getTableSchemaMap().get("table2"));
+ tableCacheVersion.incrementAndGet();
processor.registerToTsFile(
"table1",
- 2,
+ tableCacheVersion::get,
tableName -> supplierCalls.incrementAndGet() == 1 ? firstSchema :
updatedSchema);
- Assert.assertEquals(2, supplierCalls.get());
+ Assert.assertEquals(3, supplierCalls.get());
Assert.assertSame(
updatedSchema,
processor.getWriter().getSchema().getTableSchemaMap().get("table1"));
}
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/memtable/TsFileTableSchemaRegistrationPerformanceTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/memtable/TsFileTableSchemaRegistrationPerformanceTest.java
index ad4b2dc84af..c6aa0663063 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/memtable/TsFileTableSchemaRegistrationPerformanceTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/memtable/TsFileTableSchemaRegistrationPerformanceTest.java
@@ -191,7 +191,7 @@ public class TsFileTableSchemaRegistrationPerformanceTest {
private static void cachedRegister(
TsFileProcessor processor, Function<String, TableSchema>
tableSchemaFunction) {
- processor.registerToTsFile("cached_table", 1, tableSchemaFunction);
+ processor.registerToTsFile("cached_table", () -> 1L, tableSchemaFunction);
benchmarkBlackhole =
processor.getWriter().getSchema().getTableSchemaMap().size();
}