This is an automated email from the ASF dual-hosted git repository.
JackieTien97 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iotdb.git
The following commit(s) were added to refs/heads/master by this push:
new c01bd84324d Prevent stale device schema cache after concurrent LAST
queries and deletion
c01bd84324d is described below
commit c01bd84324dd3f6c0c77323d783cb5cffcd2ea1f
Author: alpass163 <[email protected]>
AuthorDate: Thu Dec 3 20:16:43 2026 +0800
Prevent stale device schema cache after concurrent LAST queries and deletion
---
.../iotdb/confignode/i18n/ProcedureMessages.java | 44 +++-
.../iotdb/confignode/i18n/ProcedureMessages.java | 42 +++-
.../persistence/schema/ClusterSchemaInfo.java | 12 +-
.../persistence/schema/TemplateTable.java | 2 +-
.../schema/AlterEncodingCompressorProcedure.java | 8 +-
.../impl/schema/DeactivateTemplateProcedure.java | 43 +++-
.../impl/schema/DeleteTimeSeriesProcedure.java | 43 +++-
.../impl/schema/table/DeleteDevicesProcedure.java | 48 ++++-
.../impl/schema/table/DropTableProcedure.java | 36 +++-
.../state/schema/DeactivateTemplateState.java | 3 +-
.../procedure/state/schema/DeleteDevicesState.java | 3 +-
.../state/schema/DeleteTimeSeriesState.java | 3 +-
.../procedure/state/schema/DropTableState.java | 3 +-
.../impl/DataNodeInternalRPCServiceImpl.java | 10 +-
.../thrift/impl/DataNodeRegionManager.java | 19 +-
.../execution/fragment/DataNodeQueryContext.java | 49 ++++-
.../fragment/FragmentInstanceContext.java | 5 +
.../last/AbstractUpdateLastCacheOperator.java | 8 +-
.../relational/LastQueryAggTableScanOperator.java | 9 +-
.../planner/DataNodeTableOperatorGenerator.java | 53 +++--
.../plan/planner/OperatorTreeGenerator.java | 51 +++--
.../planner/plan/node/write/InsertRowNode.java | 2 +-
.../planner/plan/node/write/InsertTabletNode.java | 7 +-
.../fetcher/cache/TableAttributeSchema.java | 12 +-
.../fetcher/cache/TableDeviceCacheEntry.java | 66 ++----
.../fetcher/cache/TableDeviceLastCache.java | 162 +++++++++++----
.../fetcher/cache/TableDeviceSchemaCache.java | 224 ++++++++++++---------
.../fetcher/cache/TreeDeviceNormalSchema.java | 25 ---
.../cache/TreeDeviceSchemaCacheManager.java | 61 +++---
.../db/storageengine/dataregion/DataRegion.java | 8 +-
.../cache/TreeDeviceSchemaCacheManagerTest.java | 8 +-
.../fragment/DataNodeQueryContextTest.java | 63 ++++++
.../plan/planner/LastQueryCacheTest.java | 28 +--
.../cache/TableDeviceLastCachePerformanceTest.java | 2 +-
.../fetcher/cache/TableDeviceLastCacheTest.java | 118 ++++++++++-
.../fetcher/cache/TableDeviceSchemaCacheTest.java | 16 +-
.../src/main/thrift/datanode.thrift | 1 +
37 files changed, 881 insertions(+), 416 deletions(-)
diff --git
a/iotdb-core/confignode/src/main/i18n/en/org/apache/iotdb/confignode/i18n/ProcedureMessages.java
b/iotdb-core/confignode/src/main/i18n/en/org/apache/iotdb/confignode/i18n/ProcedureMessages.java
index e6903a40c93..3efe1860fd2 100644
---
a/iotdb-core/confignode/src/main/i18n/en/org/apache/iotdb/confignode/i18n/ProcedureMessages.java
+++
b/iotdb-core/confignode/src/main/i18n/en/org/apache/iotdb/confignode/i18n/ProcedureMessages.java
@@ -431,16 +431,28 @@ public final class ProcedureMessages {
"Failed to init CQ {} because such cq already exists";
public static final String FAILED_TO_INVALIDATE_COLUMN_S_CACHE_OF_TABLE =
"Failed to invalidate {} column {}'s cache of table {}.{}";
- public static final String
FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_DEVICES_IN_TABLE =
- "Failed to invalidate schemaEngine cache of devices in table {}.{}";
- public static final String FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_TABLE =
- "Failed to invalidate schemaEngine cache of table {}.{}";
+ public static final String
+ FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_DEVICES_IN_TABLE_FIRST_TIME =
+ "Failed to invalidate schemaEngine cache of devices in table {}.{}
for the first time";
+ public static final String
+ FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_DEVICES_IN_TABLE_SECOND_TIME =
+ "Failed to invalidate schemaEngine cache of devices in table {}.{}
for the second time";
+ public static final String
FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_TABLE_FIRST_TIME =
+ "Failed to invalidate schemaEngine cache of table {}.{} for the first
time";
+ public static final String
FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_TABLE_SECOND_TIME =
+ "Failed to invalidate schemaEngine cache of table {}.{} for the second
time";
public static final String
FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_TIMESERIES =
"Failed to invalidate schemaEngine cache of timeSeries {}";
+ public static final String
FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_TIMESERIES_FIRST_TIME =
+ "Failed to invalidate schemaEngine cache of timeSeries {} for the first
time";
+ public static final String
FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_TIMESERIES_SECOND_TIME =
+ "Failed to invalidate schemaEngine cache of timeSeries {} for the second
time";
public static final String FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_VIEW =
"Failed to invalidate schemaengine cache of view {}";
- public static final String
FAILED_TO_INVALIDATE_SCHEMA_CACHE_OF_TEMPLATE_TIMESERIES =
- "Failed to invalidate schema cache of template timeSeries {}";
+ public static final String
FAILED_TO_INVALIDATE_SCHEMA_CACHE_OF_TEMPLATE_TIMESERIES_FIRST_TIME =
+ "Failed to invalidate schema cache of template timeSeries {} for the
first time";
+ public static final String
FAILED_TO_INVALIDATE_SCHEMA_CACHE_OF_TEMPLATE_TIMESERIES_SECOND_TIME =
+ "Failed to invalidate schema cache of template timeSeries {} for the
second time";
public static final String
FAILED_TO_INVALIDATE_TEMPLATE_CACHE_OF_TEMPLATE_SET_ON =
"Failed to invalidate template cache of template {} set on {}";
public static final String
FAILED_TO_PRE_RELEASE_FOR_TABLE_TO_DATANODE_FAILURE_RESULTS =
@@ -573,13 +585,25 @@ public final class ProcedureMessages {
"[%s] for %s.%s failed when [%s] because failed to execute in all
replicaset of %s %s. Failure nodes: %s";
public static final String
FOR_FAILED_WHEN_CONSTRUCT_BLACK_LIST_FOR_TABLE_BECAUSE_FAILED =
"[%s] for %s.%s failed when construct black list for table because
failed to execute in all replicaset of %s %s. Failures: %s";
- public static final String INVALIDATE_CACHE_OF_DEVICES_IN =
- "Invalidate cache of devices in {}.{}";
+ public static final String INVALIDATE_CACHE_OF_DEVICES_IN_FIRST_TIME =
+ "Invalidate cache of devices in {}.{} for the first time";
+ public static final String INVALIDATE_CACHE_OF_DEVICES_IN_SECOND_TIME =
+ "Invalidate cache of devices in {}.{} for the second time";
public static final String INVALIDATE_CACHE_OF_TEMPLATE_SET_ON =
"Invalidate cache of template {} set on {}";
- public static final String INVALIDATE_CACHE_OF_TEMPLATE_TIMESERIES =
- "Invalidate cache of template timeSeries {}";
+ public static final String
INVALIDATE_CACHE_OF_TEMPLATE_TIMESERIES_FIRST_TIME =
+ "Invalidate cache of template timeSeries {} for the first time";
+ public static final String
INVALIDATE_CACHE_OF_TEMPLATE_TIMESERIES_SECOND_TIME =
+ "Invalidate cache of template timeSeries {} for the second time";
+ public static final String INVALIDATE_CACHE_OF_TABLE_FIRST_TIME =
+ "Invalidate cache of table {}.{} for the first time";
+ public static final String INVALIDATE_CACHE_OF_TABLE_SECOND_TIME =
+ "Invalidate cache of table {}.{} for the second time";
public static final String INVALIDATE_CACHE_OF_TIMESERIES = "Invalidate
cache of timeSeries {}";
+ public static final String INVALIDATE_CACHE_OF_TIMESERIES_FIRST_TIME =
+ "Invalidate cache of timeSeries {} for the first time";
+ public static final String INVALIDATE_CACHE_OF_TIMESERIES_SECOND_TIME =
+ "Invalidate cache of timeSeries {} for the second time";
public static final String INVALIDATE_CACHE_OF_VIEW = "Invalidate cache of
view {}";
public static final String INVALIDATE_COLUMN_CACHE_FAILED_FOR_TABLE =
"Invalidate column %s cache failed for table %s.%s";
diff --git
a/iotdb-core/confignode/src/main/i18n/zh/org/apache/iotdb/confignode/i18n/ProcedureMessages.java
b/iotdb-core/confignode/src/main/i18n/zh/org/apache/iotdb/confignode/i18n/ProcedureMessages.java
index d329cf3d899..b2edac203bd 100644
---
a/iotdb-core/confignode/src/main/i18n/zh/org/apache/iotdb/confignode/i18n/ProcedureMessages.java
+++
b/iotdb-core/confignode/src/main/i18n/zh/org/apache/iotdb/confignode/i18n/ProcedureMessages.java
@@ -416,16 +416,28 @@ public final class ProcedureMessages {
"初始化 CQ {} 失败,原因:该 CQ 已存在";
public static final String FAILED_TO_INVALIDATE_COLUMN_S_CACHE_OF_TABLE =
"使表 {}.{} 的 {} 列 {} 缓存失效失败";
- public static final String
FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_DEVICES_IN_TABLE =
- "使表 {}.{} 中设备的 schemaEngine 缓存失效失败";
- public static final String FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_TABLE =
- "使表 {}.{} 的 schemaEngine 缓存失效失败";
+ public static final String
+ FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_DEVICES_IN_TABLE_FIRST_TIME =
+ "使表 {}.{} 中设备的 schemaEngine 缓存第一次失效失败";
+ public static final String
+ FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_DEVICES_IN_TABLE_SECOND_TIME =
+ "使表 {}.{} 中设备的 schemaEngine 缓存第二次失效失败";
+ public static final String
FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_TABLE_FIRST_TIME =
+ "使表 {}.{} 的 schemaEngine 缓存第一次失效失败";
+ public static final String
FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_TABLE_SECOND_TIME =
+ "使表 {}.{} 的 schemaEngine 缓存第二次失效失败";
public static final String
FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_TIMESERIES =
"使时间序列 {} 的 schemaEngine 缓存失效失败";
+ public static final String
FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_TIMESERIES_FIRST_TIME =
+ "使时间序列 {} 第一次的 schemaEngine 缓存失效失败";
+ public static final String
FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_TIMESERIES_SECOND_TIME =
+ "使时间序列 {} 第二次的 schemaEngine 缓存失效失败";
public static final String FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_VIEW =
"使视图 {} 的 schemaengine 缓存失效失败";
- public static final String
FAILED_TO_INVALIDATE_SCHEMA_CACHE_OF_TEMPLATE_TIMESERIES =
- "使模板时间序列 {} 的 schema 缓存失效失败";
+ public static final String
FAILED_TO_INVALIDATE_SCHEMA_CACHE_OF_TEMPLATE_TIMESERIES_FIRST_TIME =
+ "使模板时间序列 {} 的 schema 缓存第一次失效失败";
+ public static final String
FAILED_TO_INVALIDATE_SCHEMA_CACHE_OF_TEMPLATE_TIMESERIES_SECOND_TIME =
+ "使模板时间序列 {} 的 schema 缓存第二次失效失败";
public static final String
FAILED_TO_INVALIDATE_TEMPLATE_CACHE_OF_TEMPLATE_SET_ON =
"使模板 {}(设置在 {} 上)的模板缓存失效失败";
public static final String
FAILED_TO_PRE_RELEASE_FOR_TABLE_TO_DATANODE_FAILURE_RESULTS =
@@ -549,10 +561,24 @@ public final class ProcedureMessages {
"[%s] 对 %s.%s 失败,当 [%s] 时,原因:在所有 replicaset(%s %s)中执行失败。失败节点:%s";
public static final String
FOR_FAILED_WHEN_CONSTRUCT_BLACK_LIST_FOR_TABLE_BECAUSE_FAILED =
"[%s] 对 %s.%s 失败,当为表构建黑名单时,原因:在所有 replicaset(%s %s)中执行失败。失败信息:%s";
- public static final String INVALIDATE_CACHE_OF_DEVICES_IN = "使 {}.{}
中设备的缓存失效";
+ public static final String INVALIDATE_CACHE_OF_DEVICES_IN_FIRST_TIME =
+ "使 {}.{} 中设备的缓存第一次失效";
+ public static final String INVALIDATE_CACHE_OF_DEVICES_IN_SECOND_TIME =
+ "使 {}.{} 中设备的缓存第二次失效";
public static final String INVALIDATE_CACHE_OF_TEMPLATE_SET_ON = "使模板 {}(设置在
{} 上)的缓存失效";
- public static final String INVALIDATE_CACHE_OF_TEMPLATE_TIMESERIES =
"使模板时间序列 {} 的缓存失效";
+ public static final String
INVALIDATE_CACHE_OF_TEMPLATE_TIMESERIES_FIRST_TIME =
+ "使模板时间序列 {} 的缓存第一次失效";
+ public static final String
INVALIDATE_CACHE_OF_TEMPLATE_TIMESERIES_SECOND_TIME =
+ "使模板时间序列 {} 的缓存第二次失效";
+ public static final String INVALIDATE_CACHE_OF_TABLE_FIRST_TIME =
+ "使表 {}.{} 的缓存第一次失效";
+ public static final String INVALIDATE_CACHE_OF_TABLE_SECOND_TIME =
+ "使表 {}.{} 的缓存第二次失效";
public static final String INVALIDATE_CACHE_OF_TIMESERIES = "使时间序列 {} 的缓存失效";
+ public static final String INVALIDATE_CACHE_OF_TIMESERIES_FIRST_TIME =
+ "使时间序列 {} 第一次的缓存失效";
+ public static final String INVALIDATE_CACHE_OF_TIMESERIES_SECOND_TIME =
+ "使时间序列 {} 第二次的缓存失效";
public static final String INVALIDATE_CACHE_OF_VIEW = "使视图 {} 的缓存失效";
public static final String INVALIDATE_COLUMN_CACHE_FAILED_FOR_TABLE = "使表
%s.%s 的列 %s 缓存失效失败";
public static final String INVALIDATE_SCHEMAENGINE_CACHE_FAILED = "使
SchemaEngine 缓存失效失败";
diff --git
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/persistence/schema/ClusterSchemaInfo.java
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/persistence/schema/ClusterSchemaInfo.java
index 43b0712d3da..770bb684648 100644
---
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/persistence/schema/ClusterSchemaInfo.java
+++
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/persistence/schema/ClusterSchemaInfo.java
@@ -919,7 +919,7 @@ public class ClusterSchemaInfo implements SnapshotProcessor
{
result.setTemplateList(list);
result.setStatus(RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS));
} catch (MetadataException e) {
- LOGGER.error(e.getMessage(), e);
+ LOGGER.warn(e.getMessage());
result.setStatus(RpcUtils.getStatus(e.getErrorCode(), e.getMessage()));
}
return result;
@@ -948,7 +948,7 @@ public class ClusterSchemaInfo implements SnapshotProcessor
{
Collections.singletonList(
templateTable.getTemplate(checkTemplateSettablePlan.getName())));
} catch (final MetadataException e) {
- LOGGER.error(e.getMessage(), e);
+ LOGGER.warn(e.getMessage());
resp.setStatus(RpcUtils.getStatus(e.getErrorCode(), e.getMessage()));
}
@@ -1141,7 +1141,7 @@ public class ClusterSchemaInfo implements
SnapshotProcessor {
resp.setPatternTemplateMap(result);
return resp;
} catch (MetadataException e) {
- LOGGER.error(e.getMessage(), e);
+ LOGGER.warn(e.getMessage());
resp.setStatus(RpcUtils.getStatus(e.getErrorCode(), e.getMessage()));
}
return resp;
@@ -1152,7 +1152,7 @@ public class ClusterSchemaInfo implements
SnapshotProcessor {
treeModelMTree.preUnsetTemplate(plan.getTemplateId(), plan.getPath());
return StatusUtils.OK;
} catch (MetadataException e) {
- LOGGER.error(e.getMessage(), e);
+ LOGGER.warn(e.getMessage());
return RpcUtils.getStatus(e.getErrorCode(), e.getMessage());
}
}
@@ -1162,7 +1162,7 @@ public class ClusterSchemaInfo implements
SnapshotProcessor {
treeModelMTree.rollbackUnsetTemplate(plan.getTemplateId(),
plan.getPath());
return StatusUtils.OK;
} catch (MetadataException e) {
- LOGGER.error(e.getMessage(), e);
+ LOGGER.warn(e.getMessage());
return RpcUtils.getStatus(e.getErrorCode(), e.getMessage());
}
}
@@ -1172,7 +1172,7 @@ public class ClusterSchemaInfo implements
SnapshotProcessor {
treeModelMTree.unsetTemplate(plan.getTemplateId(), plan.getPath());
return StatusUtils.OK;
} catch (MetadataException e) {
- LOGGER.error(e.getMessage(), e);
+ LOGGER.warn(e.getMessage());
return RpcUtils.getStatus(e.getErrorCode(), e.getMessage());
}
}
diff --git
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/persistence/schema/TemplateTable.java
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/persistence/schema/TemplateTable.java
index 45b8264c40f..25028eff69b 100644
---
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/persistence/schema/TemplateTable.java
+++
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/persistence/schema/TemplateTable.java
@@ -132,7 +132,7 @@ public class TemplateTable {
try {
Template temp = this.templateMap.remove(templateName);
if (temp == null) {
- LOGGER.error(ConfigNodeMessages.UNDEFINED_TEMPLATE, templateName);
+ LOGGER.warn(ConfigNodeMessages.UNDEFINED_TEMPLATE, templateName);
throw new UndefinedTemplateException(templateName);
}
templateIdMap.remove(temp.getId());
diff --git
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/AlterEncodingCompressorProcedure.java
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/AlterEncodingCompressorProcedure.java
index f168f6dd683..312e8580a1e 100644
---
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/AlterEncodingCompressorProcedure.java
+++
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/AlterEncodingCompressorProcedure.java
@@ -133,7 +133,13 @@ public class AlterEncodingCompressorProcedure
break;
case CLEAR_CACHE:
LOGGER.info(ProcedureMessages.INVALIDATE_CACHE_OF_TIMESERIES,
requestMessage);
- invalidateCache(env, patternTreeBytes, requestMessage,
this::setFailure, false);
+ invalidateCache(
+ env,
+ patternTreeBytes,
+ requestMessage,
+ this::setFailure,
+ false,
+
ProcedureMessages.FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_TIMESERIES);
collectPayload4Pipe(env);
return Flow.NO_MORE_STATE;
default:
diff --git
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/DeactivateTemplateProcedure.java
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/DeactivateTemplateProcedure.java
index ec114b556ed..94f849f37f8 100644
---
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/DeactivateTemplateProcedure.java
+++
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/DeactivateTemplateProcedure.java
@@ -116,13 +116,30 @@ public class DeactivateTemplateProcedure
return Flow.NO_MORE_STATE;
}
case CLEAN_DATANODE_SCHEMA_CACHE:
-
LOGGER.info(ProcedureMessages.INVALIDATE_CACHE_OF_TEMPLATE_TIMESERIES,
requestMessage);
- invalidateCache(env);
+ LOGGER.info(
+
ProcedureMessages.INVALIDATE_CACHE_OF_TEMPLATE_TIMESERIES_FIRST_TIME,
requestMessage);
+ if (invalidateCache(
+ env,
+ ProcedureMessages
+
.FAILED_TO_INVALIDATE_SCHEMA_CACHE_OF_TEMPLATE_TIMESERIES_FIRST_TIME)) {
+ setNextState(DeactivateTemplateState.DELETE_DATA);
+ }
break;
case DELETE_DATA:
LOGGER.info(ProcedureMessages.DELETE_DATA_OF_TEMPLATE_TIMESERIES,
requestMessage);
deleteData(env);
break;
+ case DOUBLE_CLEAN_DATANODE_SCHEMA_CACHE:
+ LOGGER.info(
+
ProcedureMessages.INVALIDATE_CACHE_OF_TEMPLATE_TIMESERIES_SECOND_TIME,
+ requestMessage);
+ if (invalidateCache(
+ env,
+ ProcedureMessages
+
.FAILED_TO_INVALIDATE_SCHEMA_CACHE_OF_TEMPLATE_TIMESERIES_SECOND_TIME)) {
+ setNextState(DeactivateTemplateState.DEACTIVATE_TEMPLATE);
+ }
+ break;
case DEACTIVATE_TEMPLATE:
LOGGER.info(ProcedureMessages.DEACTIVATE_TEMPLATE_OF,
requestMessage);
deactivateTemplate(env);
@@ -180,7 +197,7 @@ public class DeactivateTemplateProcedure
return preDeletedNum;
}
- private void invalidateCache(final ConfigNodeProcedureEnv env) {
+ private boolean invalidateCache(final ConfigNodeProcedureEnv env, final
String failureMessage) {
// if no target timeseries, return directly
if (!timeSeriesPatternTree.isEmpty()) {
Map<Integer, TDataNodeLocation> dataNodeLocationMap =
@@ -196,18 +213,15 @@ public class DeactivateTemplateProcedure
for (TSStatus status : statusMap.values()) {
// all dataNodes must clear the related schema cache
if (status.getCode() != TSStatusCode.SUCCESS_STATUS.getStatusCode()) {
- LOGGER.error(
-
ProcedureMessages.FAILED_TO_INVALIDATE_SCHEMA_CACHE_OF_TEMPLATE_TIMESERIES,
- requestMessage);
+ LOGGER.error(failureMessage, requestMessage);
setFailure(
new ProcedureException(
new
MetadataException(ProcedureMessages.INVALIDATE_SCHEMA_CACHE_FAILED)));
- return;
+ return false;
}
}
}
-
- setNextState(DeactivateTemplateState.DELETE_DATA);
+ return true;
}
private void deleteData(final ConfigNodeProcedureEnv env) {
@@ -228,7 +242,7 @@ public class DeactivateTemplateProcedure
new ArrayList<>(consensusGroupIdList),
timeSeriesPatternTreeBytes)));
deleteDataTask.execute();
}
- setNextState(DeactivateTemplateState.DEACTIVATE_TEMPLATE);
+ setNextState(DeactivateTemplateState.DOUBLE_CLEAN_DATANODE_SCHEMA_CACHE);
}
private void deactivateTemplate(ConfigNodeProcedureEnv env) {
@@ -285,7 +299,14 @@ public class DeactivateTemplateProcedure
@Override
protected boolean isRollbackSupported(DeactivateTemplateState
deactivateTemplateState) {
- return true;
+ switch (deactivateTemplateState) {
+ case CONSTRUCT_BLACK_LIST:
+ case CLEAN_DATANODE_SCHEMA_CACHE:
+ case DELETE_DATA:
+ return true;
+ default:
+ return false;
+ }
}
@Override
diff --git
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/DeleteTimeSeriesProcedure.java
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/DeleteTimeSeriesProcedure.java
index 7df0cf22d47..0cdbb1b5c4e 100644
---
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/DeleteTimeSeriesProcedure.java
+++
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/DeleteTimeSeriesProcedure.java
@@ -150,14 +150,31 @@ public class DeleteTimeSeriesProcedure
return Flow.NO_MORE_STATE;
}
case CLEAN_DATANODE_SCHEMA_CACHE:
- LOGGER.info(ProcedureMessages.INVALIDATE_CACHE_OF_TIMESERIES,
requestMessage);
- invalidateCache(env, patternTreeBytes, requestMessage,
this::setFailure, true);
+
LOGGER.info(ProcedureMessages.INVALIDATE_CACHE_OF_TIMESERIES_FIRST_TIME,
requestMessage);
+ invalidateCache(
+ env,
+ patternTreeBytes,
+ requestMessage,
+ this::setFailure,
+ true,
+
ProcedureMessages.FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_TIMESERIES_FIRST_TIME);
setNextState(DeleteTimeSeriesState.DELETE_DATA);
break;
case DELETE_DATA:
LOGGER.info(ProcedureMessages.DELETE_DATA_OF_TIMESERIES,
requestMessage);
deleteData(env);
break;
+ case DOUBLE_CLEAN_DATANODE_SCHEMA_CACHE:
+
LOGGER.info(ProcedureMessages.INVALIDATE_CACHE_OF_TIMESERIES_SECOND_TIME,
requestMessage);
+ invalidateCache(
+ env,
+ patternTreeBytes,
+ requestMessage,
+ this::setFailure,
+ true,
+
ProcedureMessages.FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_TIMESERIES_SECOND_TIME);
+ setNextState(DeleteTimeSeriesState.DELETE_TIMESERIES_SCHEMA);
+ break;
case DELETE_TIMESERIES_SCHEMA:
LOGGER.info(ProcedureMessages.DELETE_TIMESERIES_SCHEMAENGINE_OF,
requestMessage);
deleteTimeSeriesSchema(env);
@@ -327,7 +344,8 @@ public class DeleteTimeSeriesProcedure
final ByteBuffer patternTreeBytes,
final String requestMessage,
final Consumer<ProcedureException> setFailure,
- final boolean needLock) {
+ final boolean needLock,
+ final String failureMessage) {
// Proceed once every unreachable DataNode is provably self-fenced (it
fails closed on its
// schema cache and resyncs on recovery, so it cannot serve the
to-be-deleted/altered series),
// instead of hard-failing on the first unreachable DataNode. This runs
before the physical
@@ -335,8 +353,7 @@ public class DeleteTimeSeriesProcedure
if (!SchemaUtils.invalidateMatchedSchemaCache(
env.getConfigManager(), patternTreeBytes, needLock)) {
// All dataNodes must clear the related schemaEngine cache
- LOGGER.warn(
-
ProcedureMessages.FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_TIMESERIES,
requestMessage);
+ LOGGER.warn(failureMessage, requestMessage);
setFailure.accept(
new ProcedureException(
new
MetadataException(ProcedureMessages.INVALIDATE_SCHEMAENGINE_CACHE_FAILED)));
@@ -346,7 +363,7 @@ public class DeleteTimeSeriesProcedure
private void deleteData(final ConfigNodeProcedureEnv env) {
if (isAllLogicalView) {
modProgress.finishWithoutModFiles();
- setNextState(DeleteTimeSeriesState.DELETE_TIMESERIES_SCHEMA);
+ setNextState(DeleteTimeSeriesState.DOUBLE_CLEAN_DATANODE_SCHEMA_CACHE);
return;
}
@@ -356,7 +373,7 @@ public class DeleteTimeSeriesProcedure
// Target timeSeries has no data
if (relatedDataRegionGroup.isEmpty()) {
modProgress.finishWithoutModFiles();
- setNextState(DeleteTimeSeriesState.DELETE_TIMESERIES_SCHEMA);
+ setNextState(DeleteTimeSeriesState.DOUBLE_CLEAN_DATANODE_SCHEMA_CACHE);
return;
}
@@ -382,7 +399,7 @@ public class DeleteTimeSeriesProcedure
modProgress.finish(
() -> {
if (!isFailed()) {
- setNextState(DeleteTimeSeriesState.DELETE_TIMESERIES_SCHEMA);
+
setNextState(DeleteTimeSeriesState.DOUBLE_CLEAN_DATANODE_SCHEMA_CACHE);
}
});
}
@@ -457,7 +474,15 @@ public class DeleteTimeSeriesProcedure
@Override
protected boolean isRollbackSupported(final DeleteTimeSeriesState
deleteTimeSeriesState) {
- return true;
+ switch (deleteTimeSeriesState) {
+ case PREPARE_DELETE:
+ case CONSTRUCT_BLACK_LIST:
+ case CLEAN_DATANODE_SCHEMA_CACHE:
+ case DELETE_DATA:
+ return true;
+ default:
+ return false;
+ }
}
@Override
diff --git
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/table/DeleteDevicesProcedure.java
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/table/DeleteDevicesProcedure.java
index 3a547bc9f36..153a29250fd 100644
---
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/table/DeleteDevicesProcedure.java
+++
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/table/DeleteDevicesProcedure.java
@@ -67,6 +67,7 @@ import static
org.apache.iotdb.confignode.procedure.state.schema.DeleteDevicesSt
import static
org.apache.iotdb.confignode.procedure.state.schema.DeleteDevicesState.CONSTRUCT_BLACK_LIST;
import static
org.apache.iotdb.confignode.procedure.state.schema.DeleteDevicesState.DELETE_DATA;
import static
org.apache.iotdb.confignode.procedure.state.schema.DeleteDevicesState.DELETE_DEVICE_SCHEMA;
+import static
org.apache.iotdb.confignode.procedure.state.schema.DeleteDevicesState.DOUBLE_CLEAN_DATANODE_SCHEMA_CACHE;
import static org.apache.iotdb.rpc.TSStatusCode.TABLE_NOT_EXISTS;
public class DeleteDevicesProcedure extends
AbstractAlterOrDropTableProcedure<DeleteDevicesState> {
@@ -119,13 +120,29 @@ public class DeleteDevicesProcedure extends
AbstractAlterOrDropTableProcedure<De
return Flow.NO_MORE_STATE;
}
case CLEAN_DATANODE_SCHEMA_CACHE:
- LOGGER.info(ProcedureMessages.INVALIDATE_CACHE_OF_DEVICES_IN,
database, tableName);
- invalidateCache(env);
+ LOGGER.info(
+ ProcedureMessages.INVALIDATE_CACHE_OF_DEVICES_IN_FIRST_TIME,
database, tableName);
+ if (invalidateCache(
+ env,
+ ProcedureMessages
+
.FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_DEVICES_IN_TABLE_FIRST_TIME)) {
+ setNextState(DELETE_DATA);
+ }
break;
case DELETE_DATA:
LOGGER.info(ProcedureMessages.DELETE_DATA_OF_DEVICES_IN, database,
tableName);
deleteData(env);
break;
+ case DOUBLE_CLEAN_DATANODE_SCHEMA_CACHE:
+ LOGGER.info(
+ ProcedureMessages.INVALIDATE_CACHE_OF_DEVICES_IN_SECOND_TIME,
database, tableName);
+ if (invalidateCache(
+ env,
+ ProcedureMessages
+
.FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_DEVICES_IN_TABLE_SECOND_TIME)) {
+ setNextState(DELETE_DEVICE_SCHEMA);
+ }
+ break;
case DELETE_DEVICE_SCHEMA:
LOGGER.info(ProcedureMessages.DELETE_DEVICES_IN_IN_SCHEMAENGINE,
database, tableName);
deleteDeviceSchema(env);
@@ -223,7 +240,7 @@ public class DeleteDevicesProcedure extends
AbstractAlterOrDropTableProcedure<De
: 0;
}
- private void invalidateCache(final ConfigNodeProcedureEnv env) {
+ private boolean invalidateCache(final ConfigNodeProcedureEnv env, final
String failureMessage) {
TTableDeviceInvalidateCacheReq req =
new TTableDeviceInvalidateCacheReq(database, tableName,
ByteBuffer.wrap(patternBytes));
boolean proceeded =
@@ -231,17 +248,13 @@ public class DeleteDevicesProcedure extends
AbstractAlterOrDropTableProcedure<De
.propagate(targets -> broadCastInvalidateCache(req, targets));
if (!proceeded) {
- LOGGER.warn(
-
ProcedureMessages.FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_DEVICES_IN_TABLE,
- database,
- tableName);
+ LOGGER.warn(failureMessage, database, tableName);
setFailure(
new ProcedureException(
new
MetadataException(ProcedureMessages.INVALIDATE_SCHEMAENGINE_CACHE_FAILED)));
- return;
+ return false;
}
-
- setNextState(DELETE_DATA);
+ return true;
}
private Map<Integer, TSStatus> broadCastInvalidateCache(
@@ -267,7 +280,7 @@ public class DeleteDevicesProcedure extends
AbstractAlterOrDropTableProcedure<De
new TTableDeviceDeletionWithPatternOrModReq(
consensusGroupIdList, tableName,
ByteBuffer.wrap(modBytes)))
.execute();
- setNextState(DELETE_DEVICE_SCHEMA);
+ setNextState(DOUBLE_CLEAN_DATANODE_SCHEMA_CACHE);
}
private void deleteDeviceSchema(final ConfigNodeProcedureEnv env) {
@@ -322,6 +335,19 @@ public class DeleteDevicesProcedure extends
AbstractAlterOrDropTableProcedure<De
}
}
+ @Override
+ protected boolean isRollbackSupported(final DeleteDevicesState
deleteDevicesState) {
+ switch (deleteDevicesState) {
+ case CHECK_TABLE_EXISTENCE:
+ case CONSTRUCT_BLACK_LIST:
+ case CLEAN_DATANODE_SCHEMA_CACHE:
+ case DELETE_DATA:
+ return true;
+ default:
+ return false;
+ }
+ }
+
public long getDeletedDevicesNum() {
return deletedDevicesNum;
}
diff --git
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/table/DropTableProcedure.java
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/table/DropTableProcedure.java
index 236804c0989..51a8d55e12c 100644
---
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/table/DropTableProcedure.java
+++
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/table/DropTableProcedure.java
@@ -139,6 +139,15 @@ public class DropTableProcedure extends
AbstractAlterOrDropTableProcedure<DropTa
tableName);
deleteSchema(env);
break;
+ case DOUBLE_CLEAN_DATANODE_SCHEMA_CACHE:
+ LOGGER.info(ProcedureMessages.INVALIDATE_CACHE_OF_TABLE_SECOND_TIME,
database, tableName);
+ if (invalidateTableCache(
+ env,
+
ProcedureMessages.FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_TABLE_SECOND_TIME,
+ false)) {
+ setNextState(DropTableState.DROP_TABLE);
+ }
+ break;
case DROP_TABLE:
LOGGER.info(ProcedureMessages.DROPPING_TABLE_ON_CONFIGNODE,
database, tableName);
dropTable(env);
@@ -184,21 +193,34 @@ public class DropTableProcedure extends
AbstractAlterOrDropTableProcedure<DropTa
}
private void preDelete(final ConfigNodeProcedureEnv env) {
- TInvalidateTableCacheReq req = new TInvalidateTableCacheReq(database,
tableName);
+ LOGGER.info(ProcedureMessages.INVALIDATE_CACHE_OF_TABLE_FIRST_TIME,
database, tableName);
+ if (!invalidateTableCache(
+ env,
ProcedureMessages.FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_TABLE_FIRST_TIME,
true)) {
+ return;
+ }
+ setNextState(
+ this instanceof DropViewProcedure ? DropTableState.DROP_TABLE :
DropTableState.DELETE_DATA);
+ }
+
+ private boolean invalidateTableCache(
+ final ConfigNodeProcedureEnv env,
+ final String failureMessage,
+ final boolean cleanDataNodeTableCache) {
+ TInvalidateTableCacheReq req =
+ new TInvalidateTableCacheReq(database, tableName)
+ .setCleanDataNodeTableCache(cleanDataNodeTableCache);
final boolean proceeded =
new
ClusterCachePropagator(SchemaUtils.filterFencedDataNode(env.getConfigManager()))
.propagate(targets -> broadCastInvalidateCache(req, targets));
if (!proceeded) {
- LOGGER.warn(
- ProcedureMessages.FAILED_TO_INVALIDATE_SCHEMAENGINE_CACHE_OF_TABLE,
database, tableName);
+ LOGGER.warn(failureMessage, database, tableName);
setFailure(
new ProcedureException(
new
MetadataException(ProcedureMessages.INVALIDATE_SCHEMAENGINE_CACHE_FAILED)));
- return;
+ return false;
}
- setNextState(
- this instanceof DropViewProcedure ? DropTableState.DROP_TABLE :
DropTableState.DELETE_DATA);
+ return true;
}
private Map<Integer, TSStatus> broadCastInvalidateCache(
@@ -256,7 +278,7 @@ public class DropTableProcedure extends
AbstractAlterOrDropTableProcedure<DropTa
.execute();
}
- setNextState(DropTableState.DROP_TABLE);
+ setNextState(DropTableState.DOUBLE_CLEAN_DATANODE_SCHEMA_CACHE);
}
private void dropTable(final ConfigNodeProcedureEnv env) {
diff --git
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/state/schema/DeactivateTemplateState.java
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/state/schema/DeactivateTemplateState.java
index 3abbb2e266c..690ed501d5a 100644
---
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/state/schema/DeactivateTemplateState.java
+++
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/state/schema/DeactivateTemplateState.java
@@ -23,5 +23,6 @@ public enum DeactivateTemplateState {
CONSTRUCT_BLACK_LIST,
CLEAN_DATANODE_SCHEMA_CACHE,
DELETE_DATA,
- DEACTIVATE_TEMPLATE
+ DEACTIVATE_TEMPLATE,
+ DOUBLE_CLEAN_DATANODE_SCHEMA_CACHE
}
diff --git
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/state/schema/DeleteDevicesState.java
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/state/schema/DeleteDevicesState.java
index 974a2fdfb54..ddec0bd4fe4 100644
---
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/state/schema/DeleteDevicesState.java
+++
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/state/schema/DeleteDevicesState.java
@@ -24,5 +24,6 @@ public enum DeleteDevicesState {
CONSTRUCT_BLACK_LIST,
CLEAN_DATANODE_SCHEMA_CACHE,
DELETE_DATA,
- DELETE_DEVICE_SCHEMA
+ DELETE_DEVICE_SCHEMA,
+ DOUBLE_CLEAN_DATANODE_SCHEMA_CACHE
}
diff --git
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/state/schema/DeleteTimeSeriesState.java
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/state/schema/DeleteTimeSeriesState.java
index 879a709eab2..26495951d1e 100644
---
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/state/schema/DeleteTimeSeriesState.java
+++
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/state/schema/DeleteTimeSeriesState.java
@@ -26,5 +26,6 @@ public enum DeleteTimeSeriesState {
DELETE_TIMESERIES_SCHEMA,
PREPARE_DELETE,
DELETE_DATABASES,
- RECREATE_DATABASES
+ RECREATE_DATABASES,
+ DOUBLE_CLEAN_DATANODE_SCHEMA_CACHE
}
diff --git
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/state/schema/DropTableState.java
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/state/schema/DropTableState.java
index 804e02344ac..2c9650c8164 100644
---
a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/state/schema/DropTableState.java
+++
b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/state/schema/DropTableState.java
@@ -25,5 +25,6 @@ public enum DropTableState {
DELETE_DATA,
DELETE_DEVICES,
DROP_TABLE,
- COMMIT_DELETE
+ COMMIT_DELETE,
+ DOUBLE_CLEAN_DATANODE_SCHEMA_CACHE
}
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 20c6800ab67..6fa0af6c7cf 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
@@ -2010,9 +2010,13 @@ public class DataNodeInternalRPCServiceImpl implements
IDataNodeRPCService.Iface
DataNodeSchemaLockManager.getInstance()
.takeWriteLock(SchemaLockType.VALIDATE_VS_DELETION_TABLE);
try {
- TableDeviceSchemaCache.getInstance()
- .invalidateAndPreDelete(
- PathUtils.unQualifyDatabaseName(req.getDatabase()),
req.getTableName());
+ final String database =
PathUtils.unQualifyDatabaseName(req.getDatabase());
+ if (req.isSetCleanDataNodeTableCache() &&
!req.isCleanDataNodeTableCache()) {
+ TableDeviceSchemaCache.getInstance()
+ .invalidate(database, req.getTableName(), Collections.emptyList());
+ } else {
+ TableDeviceSchemaCache.getInstance().invalidateAndPreDelete(database,
req.getTableName());
+ }
return StatusUtils.OK;
} finally {
DataNodeSchemaLockManager.getInstance()
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/DataNodeRegionManager.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/DataNodeRegionManager.java
index 357044efe5c..0ed4fc1525c 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/DataNodeRegionManager.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/DataNodeRegionManager.java
@@ -39,6 +39,7 @@ import org.apache.iotdb.db.exception.DataRegionException;
import org.apache.iotdb.db.i18n.DataNodeMiscMessages;
import org.apache.iotdb.db.pipe.agent.PipeDataNodeAgent;
import org.apache.iotdb.db.pipe.source.schemaregion.SchemaRegionListeningQueue;
+import
org.apache.iotdb.db.queryengine.plan.relational.metadata.fetcher.cache.TreeDeviceSchemaCacheManager;
import org.apache.iotdb.db.schemaengine.SchemaEngine;
import org.apache.iotdb.db.storageengine.StorageEngine;
import org.apache.iotdb.rpc.RpcUtils;
@@ -209,11 +210,21 @@ public class DataNodeRegionManager {
}
public TSStatus deleteDataRegion(DataRegionId dataRegionId) {
- TSStatus status = storageEngine.deleteDataRegion(dataRegionId);
- if (status.getCode() == TSStatusCode.SUCCESS_STATUS.getStatusCode()) {
- dataRegionLockMap.remove(dataRegionId);
+ try {
+ TSStatus status = storageEngine.deleteDataRegion(dataRegionId);
+ if (status.getCode() == TSStatusCode.SUCCESS_STATUS.getStatusCode()) {
+ dataRegionLockMap.remove(dataRegionId);
+ }
+ return status;
+ } finally {
+ final TreeDeviceSchemaCacheManager cacheManager =
TreeDeviceSchemaCacheManager.getInstance();
+ cacheManager.takeWriteLock();
+ try {
+ cacheManager.cleanUp();
+ } finally {
+ cacheManager.releaseWriteLock();
+ }
}
- return status;
}
public TSStatus deleteSchemaRegion(SchemaRegionId schemaRegionId) {
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/fragment/DataNodeQueryContext.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/fragment/DataNodeQueryContext.java
index 6f6b9c4517e..3c44cbb577d 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/fragment/DataNodeQueryContext.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/fragment/DataNodeQueryContext.java
@@ -30,16 +30,21 @@ import
org.apache.iotdb.db.protocol.client.ConfigNodeClientManager;
import org.apache.iotdb.db.protocol.client.ConfigNodeInfo;
import org.apache.iotdb.db.queryengine.plan.relational.metadata.DeviceEntry;
import
org.apache.iotdb.db.queryengine.plan.relational.metadata.fetcher.cache.TableDeviceSchemaCache;
+import
org.apache.iotdb.db.queryengine.plan.relational.metadata.fetcher.cache.TableId;
import org.apache.thrift.TException;
+import org.apache.tsfile.file.metadata.IDeviceID;
import org.apache.tsfile.read.TimeValuePair;
import org.apache.tsfile.utils.Pair;
+import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
@@ -66,6 +71,12 @@ public class DataNodeQueryContext {
private static final TableDeviceSchemaCache TABLE_DEVICE_SCHEMA_CACHE =
TableDeviceSchemaCache.getInstance();
+ // Devices whose last cache is declared by this query attempt, shared by its
fragment instances.
+ // database is null for the tree model.
+ private final Map<TableId, Set<IDeviceID>> declaredDevices = new HashMap<>();
+ private final Object declaredDevicesLock = new Object();
+ private boolean lastCacheInvalidationStarted = false;
+
// Used for TableModel information table_disk_usage scan
@GuardedBy("lock")
private Map<String, List<TTableInfo>> databaseTableInfoMap;
@@ -99,6 +110,35 @@ public class DataNodeQueryContext {
this.deviceCountAndMeasurementValues = new HashMap<>();
}
+ /** Register a device whose last cache is declared by this query attempt. */
+ public void registerDeviceAndDeclareLastCache(
+ final @Nullable String database, final IDeviceID deviceID, final
Runnable declaration) {
+ final TableId tableId = new TableId(database, deviceID.getTableName());
+ synchronized (declaredDevicesLock) {
+ if (lastCacheInvalidationStarted) {
+ return;
+ }
+ declaredDevices.computeIfAbsent(tableId, ignored -> new
HashSet<>()).add(deviceID);
+ declaration.run();
+ }
+ }
+
+ public void invalidateDeclaredLastCaches() {
+ synchronized (declaredDevicesLock) {
+ lastCacheInvalidationStarted = true;
+ if (!declaredDevices.isEmpty()) {
+ TABLE_DEVICE_SCHEMA_CACHE.invalidateDeviceEntries(declaredDevices);
+ declaredDevices.clear();
+ }
+ }
+ }
+
+ public boolean isLastCacheInvalidationStarted() {
+ synchronized (declaredDevicesLock) {
+ return lastCacheInvalidationStarted;
+ }
+ }
+
public boolean unCached(PartialPath path) {
return uncachedPathToSeriesScanInfo.containsKey(path);
}
@@ -161,15 +201,20 @@ public class DataNodeQueryContext {
/** Update the last cache when device count decrease to zero. */
public void updateLastCache(QualifiedObjectName tableName, DeviceEntry
deviceEntry) {
+ if (isLastCacheInvalidationStarted()) {
+ return;
+ }
Map<String, TimeValuePair> values =
deviceCountAndMeasurementValues.get(tableName).get(deviceEntry).getRight();
// if a device hits cache each time, the values recorded in context will
be null
if (values != null) {
- TABLE_DEVICE_SCHEMA_CACHE.updateLastCacheFromQuery(
+ TABLE_DEVICE_SCHEMA_CACHE.putBackLastCache(
tableName.getDatabaseName(),
deviceEntry.getDeviceID(),
values.keySet().toArray(new String[0]),
- values.values().toArray(new TimeValuePair[0]));
+ null,
+ values.values().toArray(new TimeValuePair[0]),
+ true);
}
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/fragment/FragmentInstanceContext.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/fragment/FragmentInstanceContext.java
index b3d4bb7675e..f97c0a6259b 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/fragment/FragmentInstanceContext.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/fragment/FragmentInstanceContext.java
@@ -532,6 +532,11 @@ public class FragmentInstanceContext extends QueryContext {
private void updateStatsIfDone(FragmentInstanceState newState) {
if (newState.isDone()) {
+ if (newState.isFailed() && dataNodeQueryContext != null) {
+ // A LAST query that declared last-cache entries may have thrown
before putting back a
+ // valid value. Drop the whole entries of the devices declared by this
query attempt.
+ dataNodeQueryContext.invalidateDeclaredLastCaches();
+ }
long now = System.currentTimeMillis();
// before setting the end times, make sure a start has been recorded
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/process/last/AbstractUpdateLastCacheOperator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/process/last/AbstractUpdateLastCacheOperator.java
index a7a6141cd79..9fd277ed6e4 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/process/last/AbstractUpdateLastCacheOperator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/process/last/AbstractUpdateLastCacheOperator.java
@@ -106,7 +106,7 @@ public abstract class AbstractUpdateLastCacheOperator
implements ProcessOperator
protected void mayUpdateLastCache(
final long time, final @Nullable TsPrimitiveType value, final
MeasurementPath fullPath) {
- if (!needUpdateCache) {
+ if (!needUpdateCache ||
dataNodeQueryContext.isLastCacheInvalidationStarted()) {
return;
}
try {
@@ -120,7 +120,7 @@ public abstract class AbstractUpdateLastCacheOperator
implements ProcessOperator
}
if (!deviceInMultiRegion) {
- lastCache.updateLastCacheIfExists(
+ lastCache.updateLastCacheForLastQuery(
getDatabaseName(),
fullPath.getIDeviceID(),
new String[] {fullPath.getMeasurement()},
@@ -129,7 +129,6 @@ public abstract class AbstractUpdateLastCacheOperator
implements ProcessOperator
? new TimeValuePair(time, value)
: needUpdateNullEntry ?
TableDeviceLastCache.PLACEHOLDER_EMPTY_COLUMN : null
},
- fullPath.isUnderAlignedEntity(),
new IMeasurementSchema[] {fullPath.getMeasurementSchema()});
return;
}
@@ -144,12 +143,11 @@ public abstract class AbstractUpdateLastCacheOperator
implements ProcessOperator
}
if (seriesScanInfo.left.decrementAndGet() == 0) {
- lastCache.updateLastCacheIfExists(
+ lastCache.updateLastCacheForLastQuery(
getDatabaseName(),
fullPath.getIDeviceID(),
new String[] {fullPath.getMeasurement()},
new TimeValuePair[] {seriesScanInfo.right},
- fullPath.isUnderAlignedEntity(),
new IMeasurementSchema[] {fullPath.getMeasurementSchema()});
}
} finally {
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/LastQueryAggTableScanOperator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/LastQueryAggTableScanOperator.java
index a602586b050..76d8ef55435 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/LastQueryAggTableScanOperator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/LastQueryAggTableScanOperator.java
@@ -689,17 +689,22 @@ public class LastQueryAggTableScanOperator extends
AbstractAggTableScanOperator
private void checkIfUpdated(
List<String> updateMeasurementList, List<TimeValuePair>
updateTimeValuePairList) {
+ if (dataNodeQueryContext.isLastCacheInvalidationStarted()) {
+ return;
+ }
if (!updateMeasurementList.isEmpty()) {
currentDeviceEntry = deviceEntries.get(currentDeviceIndex);
boolean deviceInMultiRegion =
deviceCountMap != null &&
deviceCountMap.containsKey(currentDeviceEntry);
if (!deviceInMultiRegion) {
- TABLE_DEVICE_SCHEMA_CACHE.updateLastCacheFromQuery(
+ TABLE_DEVICE_SCHEMA_CACHE.putBackLastCache(
dbName,
currentDeviceEntry.getDeviceID(),
updateMeasurementList.toArray(new String[0]),
- updateTimeValuePairList.toArray(new TimeValuePair[0]));
+ null,
+ updateTimeValuePairList.toArray(new TimeValuePair[0]),
+ true);
return;
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/DataNodeTableOperatorGenerator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/DataNodeTableOperatorGenerator.java
index d5bcbc92a81..7c6c2d2234e 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/DataNodeTableOperatorGenerator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/DataNodeTableOperatorGenerator.java
@@ -70,6 +70,7 @@ import
org.apache.iotdb.db.queryengine.execution.exchange.sink.DownStreamChannel
import org.apache.iotdb.db.queryengine.execution.exchange.sink.ISinkHandle;
import
org.apache.iotdb.db.queryengine.execution.exchange.sink.ShuffleSinkHandle;
import org.apache.iotdb.db.queryengine.execution.exchange.source.ISourceHandle;
+import org.apache.iotdb.db.queryengine.execution.fragment.DataNodeQueryContext;
import
org.apache.iotdb.db.queryengine.execution.fragment.FragmentInstanceManager;
import org.apache.iotdb.db.queryengine.execution.operator.EmptyDataOperator;
import
org.apache.iotdb.db.queryengine.execution.operator.ExplainAnalyzeOperator;
@@ -1952,12 +1953,22 @@ public class DataNodeTableOperatorGenerator
for (int j = 1; j < updateColumns.length; j++) {
updateColumns[j] = parameter.getMeasurementColumnNames().get(j
- 1);
}
- TableDeviceSchemaCache.getInstance()
- .initOrInvalidateLastCache(
- node.getQualifiedObjectName().getDatabaseName(),
- deviceEntry.getDeviceID(),
- updateColumns,
- false);
+ final String databaseName =
node.getQualifiedObjectName().getDatabaseName();
+ final DataNodeQueryContext queryContext =
context.dataNodeQueryContext;
+ if (TableDeviceSchemaCache.getInstance()
+ .isLastCacheEnabled(databaseName,
deviceEntry.getDeviceID().getTableName())) {
+ final Runnable declaration =
+ () ->
+ TableDeviceSchemaCache.getInstance()
+ .declareLastCache(
+ databaseName, deviceEntry.getDeviceID(),
updateColumns, true);
+ if (queryContext == null) {
+ declaration.run();
+ } else {
+ queryContext.registerDeviceAndDeclareLastCache(
+ databaseName, deviceEntry.getDeviceID(), declaration);
+ }
+ }
} else {
hitCachesIndexes.add(i);
lastRowCacheResults.add(lastByResult.get());
@@ -2046,14 +2057,28 @@ public class DataNodeTableOperatorGenerator
unCachedDeviceEntries.add(deviceEntry);
addUncachedDeviceToContext(node, context, deviceEntry);
- TableDeviceSchemaCache.getInstance()
- .initOrInvalidateLastCache(
- node.getQualifiedObjectName().getDatabaseName(),
- deviceEntry.getDeviceID(),
- needInitTime || node.getGroupingKeys().isEmpty()
- ? targetColumns
- : Arrays.copyOfRange(targetColumns, 0,
targetColumns.length - 1),
- false);
+ final String databaseName =
node.getQualifiedObjectName().getDatabaseName();
+ final DataNodeQueryContext queryContext =
context.dataNodeQueryContext;
+ if (TableDeviceSchemaCache.getInstance()
+ .isLastCacheEnabled(databaseName,
deviceEntry.getDeviceID().getTableName())) {
+ final Runnable declaration =
+ () ->
+ TableDeviceSchemaCache.getInstance()
+ .declareLastCache(
+ databaseName,
+ deviceEntry.getDeviceID(),
+ needInitTime ||
node.getGroupingKeys().isEmpty()
+ ? targetColumns
+ : Arrays.copyOfRange(
+ targetColumns, 0, targetColumns.length
- 1),
+ true);
+ if (queryContext == null) {
+ declaration.run();
+ } else {
+ queryContext.registerDeviceAndDeclareLastCache(
+ databaseName, deviceEntry.getDeviceID(), declaration);
+ }
+ }
} else {
hitCachesIndexes.add(i);
lastValuesCacheResults.add(lastResult);
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/OperatorTreeGenerator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/OperatorTreeGenerator.java
index 265c3bac1ce..7433d579685 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/OperatorTreeGenerator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/OperatorTreeGenerator.java
@@ -70,6 +70,7 @@ import
org.apache.iotdb.db.queryengine.execution.exchange.sink.ISinkHandle;
import
org.apache.iotdb.db.queryengine.execution.exchange.sink.LocalSinkChannel;
import
org.apache.iotdb.db.queryengine.execution.exchange.sink.ShuffleSinkHandle;
import org.apache.iotdb.db.queryengine.execution.exchange.source.ISourceHandle;
+import org.apache.iotdb.db.queryengine.execution.fragment.DataNodeQueryContext;
import
org.apache.iotdb.db.queryengine.execution.fragment.FragmentInstanceManager;
import org.apache.iotdb.db.queryengine.execution.operator.AggregationUtil;
import
org.apache.iotdb.db.queryengine.execution.operator.ExplainAnalyzeOperator;
@@ -2740,12 +2741,22 @@ public class OperatorTreeGenerator implements
PlanVisitor<Operator, LocalExecuti
final boolean isNeedUpdateLastCache = context.isNeedUpdateLastCache();
if (isNeedUpdateLastCache) {
- TreeDeviceSchemaCacheManager.getInstance()
- .declareLastCache(
- ((DataDriverContext) operatorContext.getDriverContext())
- .getDataRegion()
- .getDatabaseName(),
- fullPath);
+ final String databaseName =
+ ((DataDriverContext) operatorContext.getDriverContext())
+ .getDataRegion()
+ .getDatabaseName();
+ final DataNodeQueryContext queryContext = context.dataNodeQueryContext;
+ if
(TreeDeviceSchemaCacheManager.getInstance().isLastCacheEnabled(databaseName)) {
+ final Runnable declaration =
+ () ->
+
TreeDeviceSchemaCacheManager.getInstance().declareLastCache(databaseName,
fullPath);
+ if (queryContext == null) {
+ declaration.run();
+ } else {
+ queryContext.registerDeviceAndDeclareLastCache(
+ null, fullPath.getIDeviceID(), declaration);
+ }
+ }
}
return Objects.isNull(node.getOutputPaths())
@@ -2795,14 +2806,26 @@ public class OperatorTreeGenerator implements
PlanVisitor<Operator, LocalExecuti
.getDataRegion()
.getDatabaseName();
- for (int i = 0; i < size; ++i) {
- TreeDeviceSchemaCacheManager.getInstance()
- .declareLastCache(
- databaseName,
- new MeasurementPath(
-
devicePath.concatNode(unCachedPath.getMeasurementList().get(i)),
- unCachedPath.getSchemaList().get(i),
- true));
+ final DataNodeQueryContext queryContext = context.dataNodeQueryContext;
+ if
(TreeDeviceSchemaCacheManager.getInstance().isLastCacheEnabled(databaseName)) {
+ final Runnable declaration =
+ () -> {
+ for (int i = 0; i < size; ++i) {
+ TreeDeviceSchemaCacheManager.getInstance()
+ .declareLastCache(
+ databaseName,
+ new MeasurementPath(
+
devicePath.concatNode(unCachedPath.getMeasurementList().get(i)),
+ unCachedPath.getSchemaList().get(i),
+ true));
+ }
+ };
+ if (queryContext == null) {
+ declaration.run();
+ } else {
+ queryContext.registerDeviceAndDeclareLastCache(
+ null, devicePath.getIDeviceID(), declaration);
+ }
}
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/write/InsertRowNode.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/write/InsertRowNode.java
index 1230400e310..1d209091f64 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/write/InsertRowNode.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/write/InsertRowNode.java
@@ -926,7 +926,7 @@ public class InsertRowNode extends InsertNode implements
WALEntryValue, LastCach
public void updateLastCache(String databaseName) {
TreeDeviceSchemaCacheManager.getInstance()
.updateLastCacheIfExists(
- databaseName, getDeviceID(), measurements, this, isAligned,
measurementSchemas);
+ databaseName, getDeviceID(), measurements, this,
measurementSchemas);
}
@Override
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/write/InsertTabletNode.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/write/InsertTabletNode.java
index bd197ce6168..fcf83b9af4b 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/write/InsertTabletNode.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/write/InsertTabletNode.java
@@ -1401,12 +1401,7 @@ public class InsertTabletNode extends InsertNode
implements WALEntryValue {
}
TreeDeviceSchemaCacheManager.getInstance()
.updateLastCacheIfExists(
- databaseName,
- getDeviceID(),
- measurements,
- timeValuePairs,
- isAligned,
- measurementSchemas);
+ databaseName, getDeviceID(), measurements, timeValuePairs,
measurementSchemas);
}
@Override
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableAttributeSchema.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableAttributeSchema.java
index a033c0405d5..d245bda6054 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableAttributeSchema.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableAttributeSchema.java
@@ -61,11 +61,13 @@ public class TableAttributeSchema implements IDeviceSchema {
? newValueSize -
UpdateDetailContainer.sizeOf(previousValue)
: RamUsageEstimator.HASHTABLE_RAM_BYTES_PER_ENTRY +
newValueSize));
} else {
- attributeMap.remove(k);
- diff.addAndGet(
- (int)
- (-RamUsageEstimator.HASHTABLE_RAM_BYTES_PER_ENTRY
- - UpdateDetailContainer.sizeOf(v)));
+ final Binary previousValue = attributeMap.remove(k);
+ if (Objects.nonNull(previousValue)) {
+ diff.addAndGet(
+ (int)
+ (-RamUsageEstimator.HASHTABLE_RAM_BYTES_PER_ENTRY
+ - UpdateDetailContainer.sizeOf(previousValue)));
+ }
}
});
// Typically the "update" and "invalidate" won't be concurrently called
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceCacheEntry.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceCacheEntry.java
index c7f67307a70..d79288318ae 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceCacheEntry.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceCacheEntry.java
@@ -131,33 +131,6 @@ public class TableDeviceCacheEntry {
}
}
- int setMeasurementSchema(
- final String database,
- final boolean isAligned,
- final String[] measurements,
- final IMeasurementSchema[] schemas) {
- if (schemas == null) {
- return 0;
- }
- // Safe here because tree schema is invalidated by the whole entry
- IDeviceSchema schema = deviceSchema.get();
- int result = 0;
- if (schema == null) {
- final TreeDeviceNormalSchema newSchema = new
TreeDeviceNormalSchema(database, isAligned);
- if (deviceSchema.compareAndSet(null, newSchema)) {
- schema = newSchema;
- result = TreeDeviceNormalSchema.INSTANCE_SIZE;
- } else {
- schema = deviceSchema.get();
- }
- }
- if (!(schema instanceof TreeDeviceNormalSchema)) {
- return 0;
- }
- result += ((TreeDeviceNormalSchema) schema).update(measurements, schemas);
- return deviceSchema.get() == schema ? result : 0;
- }
-
IDeviceSchema getDeviceSchema() {
return deviceSchema.get();
}
@@ -180,7 +153,7 @@ public class TableDeviceCacheEntry {
final String database,
final String tableName,
final String[] measurements,
- final boolean isInvalidate,
+ final boolean invalidateLastCacheValue,
final boolean isTableModel) {
int result =
lastCache.compareAndSet(null, new TableDeviceLastCache(isTableModel))
@@ -189,16 +162,12 @@ public class TableDeviceCacheEntry {
final TableDeviceLastCache cache = lastCache.get();
result +=
Objects.nonNull(cache)
- ? cache.initOrInvalidate(database, tableName, measurements,
isInvalidate)
+ ? cache.initOrInvalidateLastCache(
+ database, tableName, measurements, invalidateLastCacheValue)
: 0;
return Objects.nonNull(lastCache.get()) ? result : 0;
}
- int tryUpdateLastCache(
- final String[] measurements, final TimeValuePair[] timeValuePairs,
boolean invalidateNull) {
- return tryUpdateLastCache(measurements, null, timeValuePairs,
invalidateNull);
- }
-
int tryUpdateLastCache(
final String[] measurements,
final @Nullable IMeasurementSchema[] measurementSchemas,
@@ -212,35 +181,28 @@ public class TableDeviceCacheEntry {
return Objects.nonNull(lastCache.get()) ? result : 0;
}
- int tryUpdateLastCache(
+ int updateOrDeleteLastCache(
final String[] measurements,
- final @Nullable IMeasurementSchema[] measurementSchemas,
- final LastCacheUpdateSource updateSource) {
+ final IMeasurementSchema[] measurementSchemas,
+ final TimeValuePair[] timeValuePairs) {
final TableDeviceLastCache cache = lastCache.get();
final int result =
Objects.nonNull(cache)
- ? cache.tryUpdate(measurements, measurementSchemas, updateSource)
+ ? cache.updateOrDelete(measurements, measurementSchemas,
timeValuePairs)
: 0;
return Objects.nonNull(lastCache.get()) ? result : 0;
}
- int tryUpdateLastCacheFromQuery(
- final String[] measurements, final TimeValuePair[] timeValuePairs) {
- final TableDeviceLastCache cache = lastCache.get();
- final int result =
- Objects.nonNull(cache) ? cache.tryUpdateFromQuery(measurements,
timeValuePairs) : 0;
- return Objects.nonNull(lastCache.get()) ? result : 0;
- }
-
- int tryUpdateLastCache(final String[] measurements, final TimeValuePair[]
timeValuePairs) {
- return tryUpdateLastCache(measurements, timeValuePairs, false);
- }
-
int tryUpdateLastCache(
final String[] measurements,
final @Nullable IMeasurementSchema[] measurementSchemas,
- final TimeValuePair[] timeValuePairs) {
- return tryUpdateLastCache(measurements, measurementSchemas,
timeValuePairs, false);
+ final LastCacheUpdateSource updateSource) {
+ final TableDeviceLastCache cache = lastCache.get();
+ final int result =
+ Objects.nonNull(cache)
+ ? cache.tryUpdate(measurements, measurementSchemas, updateSource)
+ : 0;
+ return Objects.nonNull(lastCache.get()) ? result : 0;
}
int invalidateLastCache(final String measurement) {
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceLastCache.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceLastCache.java
index f36c200207d..861a65e42db 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceLastCache.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceLastCache.java
@@ -45,7 +45,7 @@ import java.util.concurrent.atomic.AtomicLong;
public class TableDeviceLastCache {
static final int INSTANCE_SIZE =
(int) RamUsageEstimator.shallowSizeOfInstance(TableDeviceLastCache.class)
- + (int)
RamUsageEstimator.shallowSizeOfInstance(ConcurrentHashMap.class);
+ + 2 * (int)
RamUsageEstimator.shallowSizeOfInstance(ConcurrentHashMap.class);
private static final int LONG_INSTANCE_SIZE =
(int) RamUsageEstimator.shallowSizeOfInstance(Long.class);
@@ -75,6 +75,8 @@ public class TableDeviceLastCache {
// Time is seen as "" as a measurement
private final ConcurrentMap<String, TimeValuePair> measurement2CachedLastMap
=
new ConcurrentHashMap<>();
+ // measurement -> an aligned last-row time at which this measurement is
known to be null.
+ // It advances only when a later aligned row observes null, and is removed
once a value covers it.
private final ConcurrentMap<String, Long>
measurement2CachedLastKnownNullTimeMap =
new ConcurrentHashMap<>();
private final boolean isTableModel;
@@ -83,11 +85,17 @@ public class TableDeviceLastCache {
this.isTableModel = isTableModel;
}
- int initOrInvalidate(
+ /**
+ * @param invalidateLastCacheValue true means that invalidate(delete) the
last value in
+ * measurement2CachedLastMap, false means that init the last value, just
put on a
+ * PLACEHOLDER_NO_CACHE, if it has been init(the last value exists) then
do not need init
+ * again
+ */
+ int initOrInvalidateLastCache(
final String database,
final String tableName,
final String[] measurements,
- final boolean isInvalidate) {
+ final boolean invalidateLastCacheValue) {
final AtomicInteger diff = new AtomicInteger(0);
for (final String measurement : measurements) {
@@ -101,25 +109,27 @@ public class TableDeviceLastCache {
if (Objects.isNull(finalMeasurement)) {
continue;
}
- if (isInvalidate &&
measurement2CachedLastKnownNullTimeMap.remove(finalMeasurement) != null) {
+ if (invalidateLastCacheValue
+ && measurement2CachedLastKnownNullTimeMap.remove(finalMeasurement)
!= null) {
diff.addAndGet(-getKnownNullTimeEntrySize());
}
- final TimeValuePair newPair = isInvalidate ? null : PLACEHOLDER_NO_CACHE;
measurement2CachedLastMap.compute(
finalMeasurement,
(measurementKey, tvPair) -> {
- if (Objects.isNull(newPair)) {
- diff.addAndGet(
- -((isTableModel ? 0 : (int)
RamUsageEstimator.sizeOf(finalMeasurement))
- + getTvPairEntrySize(tvPair)));
+ if (invalidateLastCacheValue) {
+ if (Objects.nonNull(tvPair)) {
+ diff.addAndGet(
+ -((isTableModel ? 0 : (int)
RamUsageEstimator.sizeOf(finalMeasurement))
+ + getTvPairEntrySize(tvPair)));
+ }
return null;
}
if (Objects.isNull(tvPair)) {
diff.addAndGet(
(isTableModel ? 0 : (int)
RamUsageEstimator.sizeOf(finalMeasurement))
- + getTvPairEntrySize(newPair));
- return newPair;
+ + getTvPairEntrySize(PLACEHOLDER_NO_CACHE));
+ return PLACEHOLDER_NO_CACHE;
}
return tvPair;
});
@@ -147,13 +157,6 @@ public class TableDeviceLastCache {
return tryUpdate(measurements, measurementSchemas, timeValuePairs,
invalidateNull, true);
}
- int tryUpdateFromQuery(
- final @Nonnull String[] measurements, final @Nonnull TimeValuePair[]
timeValuePairs) {
- // A FIELD's last non-NULL value can be older than the device's latest
row. Queries must
- // provide an explicit time entry when they can establish the actual
last-row time.
- return tryUpdate(measurements, null, timeValuePairs, false, false);
- }
-
private int tryUpdate(
final @Nonnull String[] measurements,
final @Nullable IMeasurementSchema[] measurementSchemas,
@@ -185,15 +188,107 @@ public class TableDeviceLastCache {
if (isKnownNullAtAlignedTime(measurement, timeValuePair)) {
diff += tryUpdateKnownNullTime(measurement,
timeValuePair.getTimestamp());
} else {
- diff += tryUpdateCachedLast(measurement, timeValuePair);
+ diff +=
+ tryUpdateCachedLast(
+ measurement, measurement2CachedLastMap.get(measurement),
timeValuePair);
}
}
if (updateLastTimeFromMeasurements) {
- tryUpdateLastTime(lastTime);
+ diff += updateTimeColumnAndGetDiff(lastTime);
+ }
+ return diff;
+ }
+
+ int updateOrDelete(
+ final String[] measurements,
+ final IMeasurementSchema[] measurementSchemas,
+ final TimeValuePair[] timeValuePairs) {
+ int diff = 0;
+ for (int i = 0; i < measurements.length; ++i) {
+ String measurement = getRawMeasurement(measurements, measurementSchemas,
i);
+ if (Objects.isNull(measurement)) {
+ continue;
+ }
+ TimeValuePair timeValuePair = timeValuePairs[i];
+ if (Objects.isNull(timeValuePair)) {
+ continue;
+ }
+
+ // scan and get the null, cache it, or delete entry if it has the valid
value
+ if (timeValuePair == PLACEHOLDER_EMPTY_COLUMN) {
+ diff += cacheNullValueOrDeleteValue(measurement);
+ continue;
+ }
+
+ TimeValuePair cachedPair = measurement2CachedLastMap.get(measurement);
+ if (Objects.isNull(cachedPair)) {
+ // The declared entry has been cleared.
+ continue;
+ }
+
+ // scan and get the non-null value
+ if (cachedPair == PLACEHOLDER_EMPTY_COLUMN) {
+ // Another LAST query already cached all-null after this scan; drop
the entry instead of
+ // letting a possibly stale result (value or known-null time)
overwrite the null.
+ diff += deleteCachedValue(measurement, cachedPair);
+ continue;
+ }
+ if (isTableModel && isKnownNullAtAlignedTime(measurement,
timeValuePair)) {
+ diff += tryUpdateKnownNullTime(measurement,
timeValuePair.getTimestamp());
+ continue;
+ }
+ if (cachedPair.getTimestamp() > timeValuePair.getTimestamp()) {
+ // A newer value is already cached.
+ continue;
+ }
+ diff += tryUpdateCachedLast(measurement, cachedPair, timeValuePair);
+ }
+
+ return diff;
+ }
+
+ private int cacheNullValueOrDeleteValue(final String measurement) {
+ TimeValuePair cachedPair = measurement2CachedLastMap.get(measurement);
+ if (Objects.isNull(cachedPair) || cachedPair == PLACEHOLDER_EMPTY_COLUMN) {
+ return 0;
+ }
+ if (cachedPair == PLACEHOLDER_NO_CACHE) {
+ if (measurement2CachedLastMap.replace(measurement, cachedPair,
PLACEHOLDER_EMPTY_COLUMN)
+ && isTableModel) {
+ // A known-null time recorded before the all-null result is superseded
by it.
+ return removeKnownNullTime(measurement);
+ }
+ return 0;
+ }
+ // The cached value may have been inserted after this query scanned the
data.
+ return deleteCachedValue(measurement, cachedPair);
+ }
+
+ private int deleteCachedValue(final String measurement, final TimeValuePair
cachedPair) {
+ if (!measurement2CachedLastMap.remove(measurement, cachedPair)) {
+ return 0;
+ }
+ int diff =
+ -((isTableModel ? 0 : (int) RamUsageEstimator.sizeOf(measurement))
+ + getTvPairEntrySize(cachedPair));
+ if (isTableModel) {
+ diff += removeKnownNullTime(measurement);
}
return diff;
}
+ private int updateTimeColumnAndGetDiff(long lastTime) {
+ TimeValuePair cachedPair = measurement2CachedLastMap.get("");
+ while (Objects.nonNull(cachedPair) && cachedPair.getTimestamp() <
lastTime) {
+ TimeValuePair newPair = new TimeValuePair(lastTime,
PLACEHOLDER_NO_VALUE);
+ if (measurement2CachedLastMap.replace("", cachedPair, newPair)) {
+ return getDiffSize(cachedPair, newPair);
+ }
+ cachedPair = measurement2CachedLastMap.get("");
+ }
+ return 0;
+ }
+
int tryUpdate(
final @Nonnull String[] measurements,
final @Nullable IMeasurementSchema[] measurementSchemas,
@@ -210,7 +305,7 @@ public class TableDeviceLastCache {
diff += tryUpdateCachedLast(measurement, updateSource, i);
}
if (hasValue) {
- tryUpdateLastTime(updateSource.getLastCacheTimestamp());
+ diff += updateTimeColumnAndGetDiff(updateSource.getLastCacheTimestamp());
}
return diff;
}
@@ -226,10 +321,6 @@ public class TableDeviceLastCache {
return Objects.nonNull(newPair) ? tryUpdateCachedLast(measurement,
cachedPair, newPair) : 0;
}
- private int tryUpdateCachedLast(final String measurement, final
TimeValuePair newPair) {
- return tryUpdateCachedLast(measurement,
measurement2CachedLastMap.get(measurement), newPair);
- }
-
private int tryUpdateCachedLast(
final String measurement, TimeValuePair cachedPair, final TimeValuePair
newPair) {
while (Objects.nonNull(cachedPair) && cachedPair.getTimestamp() <=
newPair.getTimestamp()) {
@@ -242,23 +333,6 @@ public class TableDeviceLastCache {
return 0;
}
- private void tryUpdateLastTime(final long lastTime) {
- if (lastTime == Long.MIN_VALUE) {
- return;
- }
- TimeValuePair cachedPair = measurement2CachedLastMap.get("");
- if (Objects.isNull(cachedPair) || cachedPair.getTimestamp() >= lastTime) {
- return;
- }
- final TimeValuePair newPair = new TimeValuePair(lastTime,
PLACEHOLDER_NO_VALUE);
- while (Objects.nonNull(cachedPair) && cachedPair.getTimestamp() <
lastTime) {
- if (measurement2CachedLastMap.replace("", cachedPair, newPair)) {
- return;
- }
- cachedPair = measurement2CachedLastMap.get("");
- }
- }
-
@Nullable
private static String getRawMeasurement(
final @Nonnull String[] measurements,
@@ -300,7 +374,9 @@ public class TableDeviceLastCache {
"",
(s, timeValuePair) -> {
if (timeValuePair.getTimestamp() <= Math.max(time.get(),
knownNullTime.get())) {
- diff.addAndGet((int) RamUsageEstimator.sizeOf(s) +
getTvPairEntrySize(timeValuePair));
+ diff.addAndGet(
+ (isTableModel ? 0 : (int) RamUsageEstimator.sizeOf(s))
+ + getTvPairEntrySize(timeValuePair));
return null;
}
return timeValuePair;
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCache.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCache.java
index 01f106bac9d..e01c7e30517 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCache.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCache.java
@@ -38,6 +38,7 @@ import
org.apache.iotdb.db.queryengine.common.schematree.DeviceSchemaInfo;
import
org.apache.iotdb.db.queryengine.plan.analyze.cache.schema.dualkeycache.IDualKeyCache;
import
org.apache.iotdb.db.queryengine.plan.analyze.cache.schema.dualkeycache.impl.DualKeyCacheBuilder;
import
org.apache.iotdb.db.queryengine.plan.analyze.cache.schema.dualkeycache.impl.DualKeyCachePolicy;
+import org.apache.iotdb.db.schemaengine.lease.MetadataLeaseManager;
import org.apache.iotdb.db.schemaengine.schemaregion.SchemaRegion;
import org.apache.iotdb.db.schemaengine.table.DataNodeTableCache;
import org.apache.iotdb.rpc.subscription.annotation.TableModel;
@@ -64,6 +65,7 @@ import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalLong;
+import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Predicate;
@@ -177,6 +179,9 @@ public class TableDeviceSchemaCache {
final String database, final IDeviceID deviceId, final Map<String,
Binary> attributeMap) {
readWriteLock.readLock().lock();
try {
+ if (isDataNodeFenced()) {
+ return;
+ }
// Avoid stale table
if (Objects.isNull(
DataNodeTableCache.getInstance().getTable(database,
deviceId.getTableName(), false))) {
@@ -195,6 +200,9 @@ public class TableDeviceSchemaCache {
public void updateAttributes(
final String database, final IDeviceID deviceId, final Map<String,
Binary> attributeMap) {
+ if (isDataNodeFenced()) {
+ return;
+ }
dualKeyCache.update(
new TableId(database, deviceId.getTableName()),
deviceId,
@@ -227,62 +235,73 @@ public class TableDeviceSchemaCache {
/////////////////////////////// Last Cache ///////////////////////////////
/**
- * Update the last cache on query or data recover.
- *
- * <p>Note: The query shall put the cache twice:
- *
- * <p>- First time put the {@link TimeValuePair} array as {@code null}
before the query accesses
- * data. It does not indicate that the measurements are all {@code null}s,
just to allow the
- * writing to update the cache, then avoid that the query put a stale value
to cache and break the
- * consistency. WARNING: The writing may temporarily put a stale value in
cache if a stale value
- * is written, but it won't affect the eventual consistency.
+ * Whether the last cache of the given table shall be maintained, i.e.
whether {@link
+ * #declareLastCache} would touch the cache. The result is only advisory:
the table may be dropped
+ * between this check and {@link #declareLastCache}.
+ */
+ public boolean isLastCacheEnabled(final String database, final String
tableName) {
+ final TsTable table = DataNodeTableCache.getInstance().getTable(database,
tableName, false);
+ return Objects.nonNull(table) && table.getCachedNeedLastCache();
+ }
+
+ /**
+ * Declare the last cache of the fetched measurements before a LAST and LAST
BY query accesses
+ * data.
*
- * <p>- Second time put the calculated {@link TimeValuePair}s, and use {@link
- * #updateLastCacheIfExists(String, IDeviceID, String[], TimeValuePair[])}.
The input {@link
- * TimeValuePair}s shall never be or contain {@code null}. If a measurement
is with all {@code
- * null}s, its {@link TimeValuePair} shall be {@link
- * TableDeviceLastCache#PLACEHOLDER_EMPTY_COLUMN}; if it is known to be
{@code null} at a concrete
- * last-row time, preserve that time and use {@link
TableDeviceLastCache#PLACEHOLDER_NO_VALUE} as
- * the value. For time column, the input measurement shall be "", and the
value shall be {@link
- * TableDeviceLastCache#PLACEHOLDER_NO_VALUE}. If the time column is not
explicitly specified, the
- * device's last time won't be updated because we cannot guarantee the
completeness of the
- * existing measurements in cache.
+ * <p>The entry is created if absent, and the measurements without a cached
last value get a
+ * placeholder. It does not indicate that the measurements are all {@code
null}s, just to allow
+ * the writing to update the cache, then avoid that the query puts a stale
value to cache and
+ * breaks the consistency.
*
- * <p>If the query has ended abnormally, it shall call this to invalidate
the entry it has pushed
- * in the first time, to avoid the stale writing damaging the eventual
consistency. The input
- * {@link TimeValuePair}s shall be all {@code null}s in this case.
+ * <p>Only the last cache is touched here: the device schema shall never be
set by a LAST query,
+ * otherwise a query analyzed before a deletion may restore a stale schema
into this cache.
*
- * @param database the device's database, without "root"
+ * @param database the device's database, without "root" in table model
* @param deviceId {@link IDeviceID}
- * @param measurements the fetched measurements
- * @param isInvalidate whether to init or invalidate the cache
+ * @param measurements the fetched measurements, "" for the time column
+ * @param isTableModel whether the device belongs to the table model, which
decides the first key
+ * of the cache and whether the measurement names are interned
*/
- public void initOrInvalidateLastCache(
+ public void declareLastCache(
final String database,
final IDeviceID deviceId,
final String[] measurements,
- final boolean isInvalidate) {
+ final boolean isTableModel) {
readWriteLock.readLock().lock();
try {
+ if (isDataNodeFenced()) {
+ return;
+ }
+ if (!isTableModel) {
+ declareLastCacheInternal(database, deviceId, measurements, false);
+ return;
+ }
+
// Avoid stale table
- final TsTable table =
- DataNodeTableCache.getInstance().getTable(database,
deviceId.getTableName(), false);
- if (Objects.isNull(table) ||
Boolean.FALSE.equals(table.getCachedNeedLastCache())) {
+ if (!isLastCacheEnabled(database, deviceId.getTableName())) {
return;
}
- dualKeyCache.update(
- new TableId(database, deviceId.getTableName()),
- deviceId,
- new TableDeviceCacheEntry(),
- entry ->
- entry.initOrInvalidateLastCache(
- database, deviceId.getTableName(), measurements,
isInvalidate, true),
- !isInvalidate);
+ declareLastCacheInternal(database, deviceId, measurements, true);
} finally {
readWriteLock.readLock().unlock();
}
}
+ private void declareLastCacheInternal(
+ final String database,
+ final IDeviceID deviceId,
+ final String[] measurements,
+ final boolean isTableModel) {
+ dualKeyCache.update(
+ new TableId(isTableModel ? database : null, deviceId.getTableName()),
+ deviceId,
+ new TableDeviceCacheEntry(),
+ entry ->
+ entry.initOrInvalidateLastCache(
+ database, deviceId.getTableName(), measurements, false,
isTableModel),
+ true);
+ }
+
/**
* Update the last cache in writing or the second push of last cache query.
If a measurement is
* with all {@code null}s or is a tag/attribute column, its {@link
TimeValuePair}[] shall be
@@ -322,6 +341,9 @@ public class TableDeviceSchemaCache {
final @Nullable IMeasurementSchema[] measurementSchemas,
final TimeValuePair[] timeValuePairs,
boolean invalidateNull) {
+ if (isDataNodeFenced()) {
+ return;
+ }
dualKeyCache.update(
new TableId(database, deviceId.getTableName()),
deviceId,
@@ -338,6 +360,9 @@ public class TableDeviceSchemaCache {
final String[] measurements,
final @Nullable IMeasurementSchema[] measurementSchemas,
final LastCacheUpdateSource updateSource) {
+ if (isDataNodeFenced()) {
+ return;
+ }
dualKeyCache.update(
new TableId(database, deviceId.getTableName()),
deviceId,
@@ -346,20 +371,6 @@ public class TableDeviceSchemaCache {
false);
}
- /** Update query results without inferring the device's last-row time from
FIELD timestamps. */
- public void updateLastCacheFromQuery(
- final String database,
- final IDeviceID deviceId,
- final String[] measurements,
- final TimeValuePair[] timeValuePairs) {
- dualKeyCache.update(
- new TableId(database, deviceId.getTableName()),
- deviceId,
- null,
- entry -> entry.tryUpdateLastCacheFromQuery(measurements,
timeValuePairs),
- false);
- }
-
/**
* Update the last cache in writing or the second push of last cache query.
If a measurement is
* with all {@code null}s or is a tag/attribute column, its {@link
TimeValuePair}[] shall be
@@ -396,14 +407,11 @@ public class TableDeviceSchemaCache {
}
/**
- * Get the last {@link TimeValuePair}s of given measurements, the
measurements shall never be
- * "time". If you want to get the last of "time", use "" to represent.
+ * Get the last values of the given measurements.
*
- * @param database the device's database, without "root", {@code null} for
tree model
- * @param deviceId {@link IDeviceID}
- * @param measurements the measurements to get
- * @return {@code null} iff cache miss, {@link
TableDeviceLastCache#PLACEHOLDER_EMPTY_COLUMN} iff
- * cache hit but the measurement has no values at all, and the result
value otherwise.
+ * @return {@code null} iff the device entry is absent; otherwise one
element per measurement,
+ * {@code null} for a cache miss, {@link
TableDeviceLastCache#PLACEHOLDER_EMPTY_COLUMN} for a
+ * measurement with no values, and the cached value otherwise.
*/
public TimeValuePair[] getLastEntries(
final @Nullable String database, final IDeviceID deviceId, final
String[] measurements) {
@@ -472,6 +480,9 @@ public class TableDeviceSchemaCache {
/////////////////////////////// Tree model ///////////////////////////////
public void putDeviceSchema(final String database, final DeviceSchemaInfo
deviceSchemaInfo) {
+ if (isDataNodeFenced()) {
+ return;
+ }
final PartialPath devicePath = deviceSchemaInfo.getDevicePath();
final IDeviceID deviceID = devicePath.getIDeviceID();
final String previousDatabase =
treeModelDatabasePool.putIfAbsent(database, database);
@@ -498,55 +509,81 @@ public class TableDeviceSchemaCache {
return Objects.nonNull(entry) ? entry.getDeviceSchema() : null;
}
+ /**
+ * Remove the whole TableDeviceCacheEntry of the devices, including their
device schemas,
+ * attributes and last caches, under a single acquisition of the cache write
lock. Used when a
+ * LAST query ends abnormally after declaring the caches.
+ */
+ public void invalidateDeviceEntries(final Map<TableId, Set<IDeviceID>>
tableIdToDeviceIDs) {
+ readWriteLock.writeLock().lock();
+ try {
+ tableIdToDeviceIDs.forEach(
+ (tableId, deviceIDs) ->
+ deviceIDs.forEach(deviceID -> dualKeyCache.invalidate(tableId,
deviceID)));
+ } finally {
+ readWriteLock.writeLock().unlock();
+ }
+ }
+
void updateLastCache(
- final String database,
final IDeviceID deviceID,
final String[] measurements,
- final @Nullable TimeValuePair[] timeValuePairs,
- final boolean isAligned,
- final IMeasurementSchema[] measurementSchemas,
- final boolean initOrInvalidate) {
- final String previousDatabase =
treeModelDatabasePool.putIfAbsent(database, database);
- final String database2Use = Objects.nonNull(previousDatabase) ?
previousDatabase : database;
-
+ final TimeValuePair[] timeValuePairs,
+ final IMeasurementSchema[] measurementSchemas) {
+ if (isDataNodeFenced()) {
+ return;
+ }
dualKeyCache.update(
new TableId(null, deviceID.getTableName()),
deviceID,
- Objects.isNull(timeValuePairs) ? new TableDeviceCacheEntry() : null,
- initOrInvalidate
- ? entry ->
- entry.setMeasurementSchema(
- database2Use, isAligned, measurements,
measurementSchemas)
- + entry.initOrInvalidateLastCache(
- database,
- deviceID.getTableName(),
- measurements,
- Objects.nonNull(timeValuePairs),
- false)
- : entry ->
- entry.setMeasurementSchema(
- database2Use, isAligned, measurements,
measurementSchemas)
- + entry.tryUpdateLastCache(measurements,
measurementSchemas, timeValuePairs),
- Objects.isNull(timeValuePairs));
+ null,
+ entry -> entry.tryUpdateLastCache(measurements, measurementSchemas,
timeValuePairs, false),
+ false);
}
- void updateLastCache(
+ /**
+ * Put back the last values calculated by a LAST / LAST_BY query into the
last cache.
+ *
+ * <p>Only the last cache is touched here: the device schema shall never be
set by a LAST query.
+ *
+ * <p>Only an existing entry is updated: if the entry declared before the
query has been cleaned
+ * by a deletion, the value is skipped. An all-null result caches {@link
+ * TableDeviceLastCache#PLACEHOLDER_EMPTY_COLUMN} on the placeholder, or
removes the cached value
+ * if a concrete value has been cached. A concrete value arriving while the
entry already holds an
+ * all-null result is dropped instead of overwriting it, so the put-back
order of concurrent LAST
+ * queries does not matter.
+ */
+ public void putBackLastCache(
final String database,
+ final IDeviceID deviceId,
+ final String[] measurements,
+ final @Nullable IMeasurementSchema[] measurementSchemas,
+ final TimeValuePair[] timeValuePairs,
+ final boolean isTableModel) {
+ if (isDataNodeFenced()) {
+ return;
+ }
+ dualKeyCache.update(
+ new TableId(isTableModel ? database : null, deviceId.getTableName()),
+ deviceId,
+ null,
+ entry -> entry.updateOrDeleteLastCache(measurements,
measurementSchemas, timeValuePairs),
+ false);
+ }
+
+ void updateLastCache(
final IDeviceID deviceID,
final String[] measurements,
final LastCacheUpdateSource updateSource,
- final boolean isAligned,
final IMeasurementSchema[] measurementSchemas) {
- final String previousDatabase =
treeModelDatabasePool.putIfAbsent(database, database);
- final String database2Use = Objects.nonNull(previousDatabase) ?
previousDatabase : database;
-
+ if (isDataNodeFenced()) {
+ return;
+ }
dualKeyCache.update(
new TableId(null, deviceID.getTableName()),
deviceID,
null,
- entry ->
- entry.setMeasurementSchema(database2Use, isAligned, measurements,
measurementSchemas)
- + entry.tryUpdateLastCache(measurements, measurementSchemas,
updateSource),
+ entry -> entry.tryUpdateLastCache(measurements, measurementSchemas,
updateSource),
false);
}
@@ -555,6 +592,11 @@ public class TableDeviceSchemaCache {
return dualKeyCache.batchApply(inputMap,
TableDeviceCacheEntry::updateInputMap);
}
+ /** A fenced DataNode must not write schema or last-cache data until the
lease recovers. */
+ protected boolean isDataNodeFenced() {
+ return MetadataLeaseManager.getInstance().isFenced();
+ }
+
// WARNING: This is not guaranteed to affect table model's cache
void invalidateLastCache(final PartialPath devicePath, final String
measurement) {
final ToIntFunction<TableDeviceCacheEntry> updateFunction =
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TreeDeviceNormalSchema.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TreeDeviceNormalSchema.java
index b9337974a67..1df359a7317 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TreeDeviceNormalSchema.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TreeDeviceNormalSchema.java
@@ -57,31 +57,6 @@ public class TreeDeviceNormalSchema implements IDeviceSchema
{
return measurementMap.get(measurement);
}
- public int update(final String[] measurements, final IMeasurementSchema[]
schemas) {
- int diff = 0;
- if (schemas == null) {
- return diff;
- }
-
- final int length = measurements.length;
-
- for (int i = 0; i < length; ++i) {
- final String inputMeasurement = measurements[i];
- if (Objects.isNull(inputMeasurement)) {
- continue;
- }
- final IMeasurementSchema schema = i < schemas.length ? schemas[i] : null;
- final String measurement =
- Objects.nonNull(schema) ? schema.getMeasurementName() :
inputMeasurement;
- // Skip this to avoid instance creation/gc for writing performance
- if (schema == null || measurementMap.containsKey(measurement)) {
- continue;
- }
- diff += putEntry(measurement, schema, null);
- }
- return diff;
- }
-
public int update(final List<IMeasurementSchemaInfo> schemaInfoList) {
return schemaInfoList.stream()
.mapToInt(
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TreeDeviceSchemaCacheManager.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TreeDeviceSchemaCacheManager.java
index 0f0f92ef0ff..f6d9b593955 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TreeDeviceSchemaCacheManager.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TreeDeviceSchemaCacheManager.java
@@ -350,14 +350,13 @@ public class TreeDeviceSchemaCacheManager {
final IDeviceID deviceID,
final String[] measurements,
final @Nonnull TimeValuePair[] timeValuePairs,
- final boolean isAligned,
final IMeasurementSchema[] measurementSchemas) {
if (!ClusterPartitionFetcher.getInstance().needLastCache(database)) {
return;
}
tableDeviceSchemaCache.updateLastCache(
- database, deviceID, measurements, timeValuePairs, isAligned,
measurementSchemas, false);
+ deviceID, measurements, timeValuePairs, measurementSchemas);
}
public void updateLastCacheIfExists(
@@ -365,10 +364,18 @@ public class TreeDeviceSchemaCacheManager {
final IDeviceID deviceID,
final String[] measurements,
final LastCacheUpdateSource updateSource,
- final boolean isAligned,
final IMeasurementSchema[] measurementSchemas) {
+ if (!ClusterPartitionFetcher.getInstance().needLastCache(database)) {
+ return;
+ }
+
tableDeviceSchemaCache.updateLastCache(
- database, deviceID, measurements, updateSource, isAligned,
measurementSchemas);
+ deviceID, measurements, updateSource, measurementSchemas);
+ }
+
+ /** Whether the last cache of the given database shall be maintained. */
+ public boolean isLastCacheEnabled(final String database) {
+ return ClusterPartitionFetcher.getInstance().needLastCache(database);
}
/**
@@ -381,49 +388,35 @@ public class TreeDeviceSchemaCacheManager {
* consistency. WARNING: The writing may temporarily put a stale value in
cache if a stale value
* is written, but it won't affect the eventual consistency.
*
- * <p>- Second time put the calculated {@link TimeValuePair}, and use {@link
- * #updateLastCacheIfExists(String, IDeviceID, String[], TimeValuePair[],
boolean,
- * IMeasurementSchema[])}. The input {@link TimeValuePair} shall never be or
contain {@code null},
- * if the measurement is with all {@code null}s, its {@link TimeValuePair}
shall be {@link
- * TableDeviceLastCache#PLACEHOLDER_EMPTY_COLUMN}. This method is not
supposed to update time
- * column.
+ * <p>Second time the query would put back the value in the cache
*
* @param database the device's database, WITH "root"
* @param measurementPath the fetched {@link MeasurementPath}
*/
public void declareLastCache(final String database, final MeasurementPath
measurementPath) {
- if (!ClusterPartitionFetcher.getInstance().needLastCache(database)) {
+ if (!isLastCacheEnabled(database)) {
return;
}
- tableDeviceSchemaCache.updateLastCache(
+ tableDeviceSchemaCache.declareLastCache(
database,
measurementPath.getIDeviceID(),
new String[] {measurementPath.getMeasurement()},
- null,
- measurementPath.isUnderAlignedEntity(),
- new IMeasurementSchema[] {measurementPath.getMeasurementSchema()},
- true);
+ false);
}
- /**
- * Update the {@link TableDeviceLastCache} on query in tree model.
- *
- * <p>If the query has ended abnormally, it shall call this to invalidate
the entry it has pushed
- * in the first time, to avoid the stale writing damaging the eventual
consistency.
- *
- * @param database the device's database, WITH "root"
- * @param measurementPath the fetched {@link MeasurementPath}
- */
- public void invalidateLastCache(final String database, final MeasurementPath
measurementPath) {
- tableDeviceSchemaCache.updateLastCache(
- database,
- measurementPath.getIDeviceID(),
- new String[] {measurementPath.getMeasurement()},
- new TimeValuePair[] {null},
- measurementPath.isUnderAlignedEntity(),
- new IMeasurementSchema[] {measurementPath.getMeasurementSchema()},
- true);
+ public void updateLastCacheForLastQuery(
+ final String database,
+ final IDeviceID deviceID,
+ final String[] measurements,
+ final TimeValuePair[] timeValuePairs,
+ final IMeasurementSchema[] measurementSchemas) {
+ if (!ClusterPartitionFetcher.getInstance().needLastCache(database)) {
+ return;
+ }
+
+ tableDeviceSchemaCache.putBackLastCache(
+ database, deviceID, measurements, measurementSchemas, timeValuePairs,
false);
}
public void invalidate(final List<MeasurementPath> partialPathList) {
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 84551fbb835..8a1daab0d9e 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
@@ -4896,10 +4896,8 @@ public class DataRegion implements IDataRegionForQuery {
TableDeviceSchemaCache.getInstance()
.updateLastCacheIfExists(databaseName, deviceID, measurements,
timeValuePairs);
} else {
- // we do not update schema here, so aligned is not relevant
TreeDeviceSchemaCacheManager.getInstance()
- .updateLastCacheIfExists(
- databaseName, deviceID, measurements, timeValuePairs, false,
null);
+ .updateLastCacheIfExists(databaseName, deviceID, measurements,
timeValuePairs, null);
}
}
return;
@@ -4916,10 +4914,8 @@ public class DataRegion implements IDataRegionForQuery {
TableDeviceSchemaCache.getInstance()
.updateLastCacheIfExists(databaseName, deviceID, measurements,
timeValuePairs);
} else {
- // we do not update schema here, so aligned is not relevant
TreeDeviceSchemaCacheManager.getInstance()
- .updateLastCacheIfExists(
- databaseName, deviceID, measurements, timeValuePairs, false,
null);
+ .updateLastCacheIfExists(databaseName, deviceID, measurements,
timeValuePairs, null);
}
}
} else {
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/metadata/cache/TreeDeviceSchemaCacheManagerTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/metadata/cache/TreeDeviceSchemaCacheManagerTest.java
index 59cdf620561..2b18ee01401 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/metadata/cache/TreeDeviceSchemaCacheManagerTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/metadata/cache/TreeDeviceSchemaCacheManagerTest.java
@@ -217,10 +217,9 @@ public class TreeDeviceSchemaCacheManagerTest {
new TimeValuePair[] {
new TimeValuePair(2, new TsPrimitiveType.TsInt(2)),
},
- false,
new MeasurementSchema[] {s1});
treeDeviceSchemaCacheManager.invalidateLastCache(
- database, new MeasurementPath(device.concatNode("s1"), s1));
+ new MeasurementPath(device.concatNode("s1"), s1));
// "s2" shall be null since the "null" timeValuePair has not been put
treeDeviceSchemaCacheManager.updateLastCacheIfExists(
@@ -229,7 +228,6 @@ public class TreeDeviceSchemaCacheManagerTest {
StringArrayDeviceID.splitDeviceIdString(device.getNodes())),
new String[] {"s2"},
new TimeValuePair[] {tv1},
- false,
new MeasurementSchema[] {s2});
treeDeviceSchemaCacheManager.updateLastCacheIfExists(
@@ -238,7 +236,6 @@ public class TreeDeviceSchemaCacheManagerTest {
StringArrayDeviceID.splitDeviceIdString(device.getNodes())),
new String[] {"s3"},
new TimeValuePair[] {tv1},
- false,
new MeasurementSchema[] {s3});
Assert.assertNull(
@@ -260,7 +257,6 @@ public class TreeDeviceSchemaCacheManagerTest {
new TimeValuePair(2, new TsPrimitiveType.TsInt(2)),
new TimeValuePair(2, new TsPrimitiveType.TsInt(2))
},
- false,
measurementSchemas);
Assert.assertNull(
@@ -293,7 +289,6 @@ public class TreeDeviceSchemaCacheManagerTest {
StringArrayDeviceID.splitDeviceIdString(device.getNodes())),
new String[] {"s1"},
new TimeValuePair[] {tv1},
- false,
new MeasurementSchema[] {s1});
Assert.assertEquals(tv1,
treeDeviceSchemaCacheManager.getLastCache(measurementPath));
@@ -398,7 +393,6 @@ public class TreeDeviceSchemaCacheManagerTest {
StringArrayDeviceID.splitDeviceIdString(devicePath.getNodes())),
new String[] {path.getMeasurement()},
new TimeValuePair[] {timeValuePair},
- false,
new MeasurementSchema[] {schema});
}
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/fragment/DataNodeQueryContextTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/fragment/DataNodeQueryContextTest.java
new file mode 100644
index 00000000000..894a14398dd
--- /dev/null
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/fragment/DataNodeQueryContextTest.java
@@ -0,0 +1,63 @@
+/*
+ * 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.execution.fragment;
+
+import
org.apache.iotdb.db.queryengine.plan.relational.metadata.fetcher.cache.TableDeviceSchemaCache;
+import
org.apache.iotdb.db.queryengine.plan.relational.metadata.fetcher.cache.TableId;
+import org.apache.iotdb.db.schemaengine.lease.MetadataLeaseManager;
+
+import org.apache.tsfile.file.metadata.IDeviceID;
+import org.apache.tsfile.file.metadata.StringArrayDeviceID;
+import org.apache.tsfile.read.TimeValuePair;
+import org.apache.tsfile.utils.TsPrimitiveType;
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.util.Collections;
+
+public class DataNodeQueryContextTest {
+
+ @Test
+ public void testInvalidateDeclaredLastCachesOnFailure() {
+ MetadataLeaseManager.getInstance().recoveryLeaseForTest(true);
+ final TableDeviceSchemaCache cache = TableDeviceSchemaCache.getInstance();
+ final IDeviceID device = new
StringArrayDeviceID("root.__query_context_test_db.d1");
+ final String database = "root.__query_context_test_db";
+ final TimeValuePair value = new TimeValuePair(10L, new
TsPrimitiveType.TsInt(10));
+ final DataNodeQueryContext context = new DataNodeQueryContext();
+
+ try {
+ cache.declareLastCache(database, device, new String[] {"s1"}, false);
+ cache.putBackLastCache(
+ database, device, new String[] {"s1"}, null, new TimeValuePair[]
{value}, false);
+ Assert.assertEquals(value, cache.getLastEntry(null, device, "s1"));
+
+ context.registerDeviceAndDeclareLastCache(null, device, () -> {});
+ context.invalidateDeclaredLastCaches();
+
+ Assert.assertTrue(context.isLastCacheInvalidationStarted());
+ Assert.assertNull(cache.getLastEntry(null, device, "s1"));
+ } finally {
+ cache.invalidateDeviceEntries(
+ Collections.singletonMap(
+ new TableId(null, device.getTableName()),
Collections.singleton(device)));
+ }
+ }
+}
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/planner/LastQueryCacheTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/planner/LastQueryCacheTest.java
index 486bdb63ea0..09f5663c7b6 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/planner/LastQueryCacheTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/planner/LastQueryCacheTest.java
@@ -76,7 +76,6 @@ public class LastQueryCacheTest {
private static final String DATABASE = "root.last_query_cache";
private final boolean aligned;
private final Filter timeFilter;
- private final boolean updateSchema;
private final boolean updateNullEntry;
private final TreeDeviceSchemaCacheManager cache =
TreeDeviceSchemaCacheManager.getInstance();
private MeasurementPath path;
@@ -85,21 +84,19 @@ public class LastQueryCacheTest {
@Parameterized.Parameters(name = "aligned={0}, filter={1}")
public static Collection<Object[]> parameters() {
return Arrays.asList(
- new Object[] {false, null, true, true},
- new Object[] {true, null, true, true},
- new Object[] {false, TimeFilterApi.gt(10), true, false},
- new Object[] {true, TimeFilterApi.gt(10), true, false},
- new Object[] {false, TimeFilterApi.gtEq(10), true, false},
- new Object[] {true, TimeFilterApi.gtEq(10), true, false},
- new Object[] {false, TimeFilterApi.lt(10), false, false},
- new Object[] {true, TimeFilterApi.lt(10), false, false});
+ new Object[] {false, null, true},
+ new Object[] {true, null, true},
+ new Object[] {false, TimeFilterApi.gt(10), false},
+ new Object[] {true, TimeFilterApi.gt(10), false},
+ new Object[] {false, TimeFilterApi.gtEq(10), false},
+ new Object[] {true, TimeFilterApi.gtEq(10), false},
+ new Object[] {false, TimeFilterApi.lt(10), false},
+ new Object[] {true, TimeFilterApi.lt(10), false});
}
- public LastQueryCacheTest(
- boolean aligned, Filter timeFilter, boolean updateSchema, boolean
updateNullEntry) {
+ public LastQueryCacheTest(boolean aligned, Filter timeFilter, boolean
updateNullEntry) {
this.aligned = aligned;
this.timeFilter = timeFilter;
- this.updateSchema = updateSchema;
this.updateNullEntry = updateNullEntry;
}
@@ -155,11 +152,8 @@ public class LastQueryCacheTest {
when(dataRegion.getDatabaseName()).thenReturn(DATABASE);
LocalExecutionPlanContext context = createContext(dataRegion);
try (Operator operator = createOperator(context)) {
- if (updateSchema) {
- assertEquals(DATABASE,
cache.getMatchedNormalSchema(path).getBelongedDatabase(path));
- } else {
- assertTrue(cache.getMatchedNormalSchema(path).isEmpty());
- }
+ // LAST planning must not populate the device schema cache.
+ assertTrue(cache.getMatchedNormalSchema(path).isEmpty());
consumeEmptyResult(operator, context);
if (updateNullEntry) {
assertEquals(TableDeviceLastCache.PLACEHOLDER_EMPTY_COLUMN,
cache.getLastCache(path));
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceLastCachePerformanceTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceLastCachePerformanceTest.java
index d88169999d3..2755252e316 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceLastCachePerformanceTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceLastCachePerformanceTest.java
@@ -137,7 +137,7 @@ public class TableDeviceLastCachePerformanceTest {
}
final TableDeviceLastCache cache = new TableDeviceLastCache(false);
- cache.initOrInvalidate(null, null, cachedMeasurements, false);
+ cache.initOrInvalidateLastCache(null, null, cachedMeasurements, false);
return new Scenario(
cache,
measurements,
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceLastCacheTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceLastCacheTest.java
index 3270e60157b..c3e8e009886 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceLastCacheTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceLastCacheTest.java
@@ -19,10 +19,20 @@
package org.apache.iotdb.db.queryengine.plan.relational.metadata.fetcher.cache;
+import org.apache.iotdb.commons.schema.table.TsTable;
+import org.apache.iotdb.commons.schema.table.column.FieldColumnSchema;
+import org.apache.iotdb.commons.schema.table.column.TimeColumnSchema;
+import org.apache.iotdb.db.schemaengine.table.DataNodeTableCache;
+
+import org.apache.tsfile.enums.TSDataType;
+import org.apache.tsfile.file.metadata.enums.CompressionType;
+import org.apache.tsfile.file.metadata.enums.TSEncoding;
import org.apache.tsfile.read.TimeValuePair;
import org.apache.tsfile.utils.Pair;
import org.apache.tsfile.utils.TsPrimitiveType;
+import org.junit.AfterClass;
import org.junit.Assert;
+import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Collections;
@@ -32,20 +42,39 @@ import java.util.concurrent.atomic.AtomicInteger;
public class TableDeviceLastCacheTest {
+ private static final String DATABASE = "sg_last_cache_test";
+ private static final String TABLE = "t_last_cache_test";
+
+ @BeforeClass
+ public static void prepareTableCache() {
+ final TsTable table = new TsTable(TABLE);
+ table.addColumnSchema(new TimeColumnSchema("time", TSDataType.INT64));
+ table.addColumnSchema(
+ new FieldColumnSchema("s1", TSDataType.INT32, TSEncoding.RLE,
CompressionType.GZIP));
+ DataNodeTableCache.getInstance().preUpdateTable(DATABASE, table, null);
+ DataNodeTableCache.getInstance().commitUpdateTable(DATABASE, TABLE, null,
null);
+ }
+
+ @AfterClass
+ public static void clearTableCache() {
+ DataNodeTableCache.getInstance().invalid(DATABASE);
+ }
+
@Test
public void testQueryFieldTimesDoNotInitializeAlignedTime() {
- final TableDeviceLastCache cache = new TableDeviceLastCache(false);
- cache.initOrInvalidate(null, null, new String[] {"", "s1"}, false);
+ final TableDeviceLastCache cache = new TableDeviceLastCache(true);
+ cache.initOrInvalidateLastCache(DATABASE, TABLE, new String[] {"", "s1"},
false);
final TimeValuePair historicalValue = new TimeValuePair(2L, new
TsPrimitiveType.TsInt(20));
- cache.tryUpdateFromQuery(new String[] {"s1"}, new TimeValuePair[]
{historicalValue});
+ cache.updateOrDelete(new String[] {"s1"}, null, new TimeValuePair[]
{historicalValue});
Assert.assertEquals(historicalValue, cache.getTimeValuePair("s1"));
Assert.assertNull(cache.getTimeValuePair(""));
Assert.assertFalse(cache.getLastRow("",
Collections.singletonList("s1")).isPresent());
- cache.tryUpdateFromQuery(
+ cache.updateOrDelete(
new String[] {"", "s1"},
+ null,
new TimeValuePair[] {
new TimeValuePair(7L, TableDeviceLastCache.PLACEHOLDER_NO_VALUE),
new TimeValuePair(7L, TableDeviceLastCache.PLACEHOLDER_NO_VALUE)
@@ -60,7 +89,7 @@ public class TableDeviceLastCacheTest {
new TsPrimitiveType[] {TableDeviceLastCache.PLACEHOLDER_NO_VALUE},
result.get().getRight());
final TimeValuePair newerFieldValue = new TimeValuePair(8L, new
TsPrimitiveType.TsInt(80));
- cache.tryUpdateFromQuery(new String[] {"s1"}, new TimeValuePair[]
{newerFieldValue});
+ cache.updateOrDelete(new String[] {"s1"}, null, new TimeValuePair[]
{newerFieldValue});
Assert.assertEquals(newerFieldValue, cache.getTimeValuePair("s1"));
Assert.assertEquals(7L, cache.getTimeValuePair("").getTimestamp());
}
@@ -68,7 +97,7 @@ public class TableDeviceLastCacheTest {
@Test
public void testLazyUpdateOnlyComposesCachedMeasurements() {
final TableDeviceLastCache cache = new TableDeviceLastCache(false);
- cache.initOrInvalidate(null, null, new String[] {"s1"}, false);
+ cache.initOrInvalidateLastCache(null, null, new String[] {"s1"}, false);
final AtomicInteger composedValueCount = new AtomicInteger();
cache.tryUpdate(
@@ -102,7 +131,7 @@ public class TableDeviceLastCacheTest {
public void testKnownNullTimePreservesHistoricalValueAndClearsOnNewerValue()
{
final TableDeviceLastCache cache = new TableDeviceLastCache(false);
- cache.initOrInvalidate(null, null, new String[] {"", "s1"}, false);
+ cache.initOrInvalidateLastCache(null, null, new String[] {"", "s1"},
false);
final TimeValuePair historicalValue = new TimeValuePair(1L, new
TsPrimitiveType.TsInt(1));
cache.tryUpdate(
@@ -133,11 +162,84 @@ public class TableDeviceLastCacheTest {
new TsPrimitiveType[] {new TsPrimitiveType.TsInt(3)},
result.get().getRight());
}
+ @Test
+ public void testLastQueryAllNullDeletesCachedValue() {
+ final TableDeviceLastCache cache = new TableDeviceLastCache(false);
+ cache.initOrInvalidateLastCache(null, null, new String[] {"s1"}, false);
+ final TimeValuePair value = new TimeValuePair(10L, new
TsPrimitiveType.TsInt(10));
+
+ cache.updateOrDelete(new String[] {"s1"}, null, new TimeValuePair[]
{value});
+ Assert.assertEquals(value, cache.getTimeValuePair("s1"));
+
+ final int diff =
+ cache.updateOrDelete(
+ new String[] {"s1"},
+ null,
+ new TimeValuePair[]
{TableDeviceLastCache.PLACEHOLDER_EMPTY_COLUMN});
+ Assert.assertNull(cache.getTimeValuePair("s1"));
+ Assert.assertTrue(diff < 0);
+ }
+
+ @Test
+ public void testLastQueryValueDoesNotOverwriteCachedAllNull() {
+ final TableDeviceLastCache cache = new TableDeviceLastCache(false);
+ cache.initOrInvalidateLastCache(null, null, new String[] {"s1"}, false);
+
+ cache.updateOrDelete(
+ new String[] {"s1"},
+ null,
+ new TimeValuePair[] {TableDeviceLastCache.PLACEHOLDER_EMPTY_COLUMN});
+ Assert.assertSame(TableDeviceLastCache.PLACEHOLDER_EMPTY_COLUMN,
cache.getTimeValuePair("s1"));
+
+ final int diff =
+ cache.updateOrDelete(
+ new String[] {"s1"},
+ null,
+ new TimeValuePair[] {new TimeValuePair(10L, new
TsPrimitiveType.TsInt(10))});
+ Assert.assertNull(cache.getTimeValuePair("s1"));
+ Assert.assertTrue(diff < 0);
+ }
+
+ @Test
+ public void testLastQueryValueBackfillsDeclaredPlaceholder() {
+ final TableDeviceLastCache cache = new TableDeviceLastCache(false);
+ cache.initOrInvalidateLastCache(null, null, new String[] {"s1"}, false);
+ final TimeValuePair value = new TimeValuePair(10L, new
TsPrimitiveType.TsInt(10));
+
+ cache.updateOrDelete(new String[] {"s1"}, null, new TimeValuePair[]
{value});
+
+ Assert.assertEquals(value, cache.getTimeValuePair("s1"));
+ Assert.assertNull(cache.getTimeValuePair(""));
+ }
+
+ @Test
+ public void testLastQuerySkipsClearedEntry() {
+ final TableDeviceLastCache cache = new TableDeviceLastCache(false);
+ cache.initOrInvalidateLastCache(null, null, new String[] {"s1"}, false);
+ cache.invalidate("s1");
+
+ cache.updateOrDelete(
+ new String[] {"s1"},
+ null,
+ new TimeValuePair[] {new TimeValuePair(10L, new
TsPrimitiveType.TsInt(10))});
+
+ Assert.assertNull(cache.getTimeValuePair("s1"));
+ }
+
+ @Test
+ public void testInvalidateAbsentMeasurementDoesNotSubtractSize() {
+ final TableDeviceLastCache cache = new TableDeviceLastCache(false);
+
+ final int diff = cache.initOrInvalidateLastCache(null, null, new String[]
{"s1"}, true);
+
+ Assert.assertEquals(0, diff);
+ }
+
@Test
public void testInvalidateMeasurementClearsKnownNullTimeAndAlignedTime() {
final TableDeviceLastCache cache = new TableDeviceLastCache(false);
- cache.initOrInvalidate(null, null, new String[] {"", "s1"}, false);
+ cache.initOrInvalidateLastCache(null, null, new String[] {"", "s1"},
false);
cache.tryUpdate(
new String[] {"", "s1"},
new TimeValuePair[] {
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCacheTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCacheTest.java
index bab5d624fe4..9b53a0e34fe 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCacheTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCacheTest.java
@@ -409,8 +409,8 @@ public class TableDeviceSchemaCacheTest {
cache.getLastEntry(database1, convertTagValuesToDeviceID(table1,
device0), "s3"));
// Test null hit measurements
- cache.initOrInvalidateLastCache(
- database1, convertTagValuesToDeviceID(table1, device0), new String[]
{"s4"}, false);
+ cache.declareLastCache(
+ database1, convertTagValuesToDeviceID(table1, device0), new String[]
{"s4"}, true);
// Miss if the "null" time value pair is not in cache, meaning that the
// entry is evicted
@@ -473,8 +473,8 @@ public class TableDeviceSchemaCacheTest {
},
result.get().getRight());
- cache.initOrInvalidateLastCache(
- database1, convertTagValuesToDeviceID(table1, device0), new String[]
{"s5"}, false);
+ cache.declareLastCache(
+ database1, convertTagValuesToDeviceID(table1, device0), new String[]
{"s5"}, true);
result =
cache.getLastRow(
@@ -787,13 +787,13 @@ public class TableDeviceSchemaCacheTest {
final IDeviceID disabledDevice =
convertTagValuesToDeviceID(tableNeedLastCacheDisabled, device0);
- cache.initOrInvalidateLastCache(database1, disabledDevice, measurements,
false);
+ cache.declareLastCache(database1, disabledDevice, measurements, true);
cache.updateLastCacheIfExists(database1, disabledDevice, measurements,
values);
Assert.assertNull(cache.getLastEntry(database1, disabledDevice,
measurement1));
final IDeviceID enabledDevice = convertTagValuesToDeviceID(table1,
device0);
- cache.initOrInvalidateLastCache(database1, enabledDevice, measurements,
false);
+ cache.declareLastCache(database1, enabledDevice, measurements, true);
cache.updateLastCacheIfExists(database1, enabledDevice, measurements,
values);
Assert.assertEquals(values[0], cache.getLastEntry(database1,
enabledDevice, measurement1));
@@ -805,8 +805,8 @@ public class TableDeviceSchemaCacheTest {
final IDeviceID deviceID,
final String[] measurement,
final TimeValuePair[] data) {
- cache.initOrInvalidateLastCache(database, deviceID, measurement, false);
- cache.updateLastCacheIfExists(database, deviceID, measurement, data);
+ cache.declareLastCache(database, deviceID, measurement, true);
+ cache.putBackLastCache(database, deviceID, measurement, null, data, true);
}
@Test
diff --git a/iotdb-protocol/thrift-datanode/src/main/thrift/datanode.thrift
b/iotdb-protocol/thrift-datanode/src/main/thrift/datanode.thrift
index 97416bf3309..0edeb533532 100644
--- a/iotdb-protocol/thrift-datanode/src/main/thrift/datanode.thrift
+++ b/iotdb-protocol/thrift-datanode/src/main/thrift/datanode.thrift
@@ -384,6 +384,7 @@ struct TUpdateTree2TableView{
struct TInvalidateTableCacheReq {
1: required string database
2: required string tableName
+ 3: optional bool cleanDataNodeTableCache
}
struct TInvalidateColumnCacheReq {