From bbae646e2b1d1a34aff78b31daedc0db5916d365 Mon Sep 17 00:00:00 2001 From: JackieTien97 Date: Sat, 5 Dec 2026 07:54:59 +0800 Subject: [PATCH 1/7] Fix LastFlushTimeMap degradation skipped during DataRegion recovery --- .../storageengine/dataregion/DataRegion.java | 21 ++++++++++++------- .../rescon/memory/TimePartitionInfo.java | 20 ++++++++++++++++++ .../rescon/memory/TimePartitionManager.java | 3 +++ .../memory/TimePartitionManagerTest.java | 19 +++++++++++++++++ 4 files changed, 56 insertions(+), 7 deletions(-) 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 8a1daab0d9eef..4e78ae2e7078a 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 @@ -829,7 +829,8 @@ private void recover() throws DataRegionException { latestPartitionId, false, Long.MAX_VALUE, - lastFlushTimeMap.getMemSize(latestPartitionId))); + lastFlushTimeMap.getMemSize(latestPartitionId), + this)); } } // wait until all unsealed TsFiles have been recovered @@ -1198,7 +1199,8 @@ private Callable asyncRecoverFilesInPartition( partitionId, false, Long.MAX_VALUE, - lastFlushTimeMap.getMemSize(partitionId))); + lastFlushTimeMap.getMemSize(partitionId), + this)); } for (TsFileResource tsFileResource : resourceList) { updatePartitionLastFlushTime(tsFileResource); @@ -1258,7 +1260,8 @@ private void syncRecoverFilesInPartition( partitionId, false, Long.MAX_VALUE, - lastFlushTimeMap.getMemSize(partitionId))); + lastFlushTimeMap.getMemSize(partitionId), + this)); } for (TsFileResource tsFileResource : resourceList) { if (!tsFileResource.isDeleted()) { @@ -1694,7 +1697,8 @@ private void initFlushTimeMap(long timePartitionId) { timePartitionId, true, Long.MAX_VALUE, - 0)); + 0, + this)); } } @@ -4798,7 +4802,8 @@ public void loadNewTsFile( timePartitionId, false, Long.MAX_VALUE, - lastFlushTimeMap.getMemSize(timePartitionId))); + lastFlushTimeMap.getMemSize(timePartitionId), + this)); } updateDeviceLastFlushTime(newTsFileResource); TimePartitionManager.getInstance() @@ -5364,7 +5369,8 @@ public void insert(InsertRowsOfOneDeviceNode insertRowsOfOneDeviceNode) timePartitionId, true, Long.MAX_VALUE, - 0)); + 0, + this)); } boolean isSequence = @@ -5489,7 +5495,8 @@ public void insert(InsertRowsNode insertRowsNode) timePartitionIds[i], true, Long.MAX_VALUE, - 0)); + 0, + this)); } areSequence[i] = config.isEnableSeparateData() diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionInfo.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionInfo.java index 9a25b6501a113..06f13a2662fea 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionInfo.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionInfo.java @@ -20,6 +20,9 @@ package org.apache.iotdb.db.storageengine.rescon.memory; import org.apache.iotdb.commons.consensus.DataRegionId; +import org.apache.iotdb.db.storageengine.dataregion.DataRegion; + +import java.lang.ref.WeakReference; /** Time partition info records necessary info of a time partition for a data region */ public class TimePartitionInfo { @@ -33,17 +36,34 @@ public class TimePartitionInfo { long memSize; + private final WeakReference dataRegionRef; + public TimePartitionInfo( DataRegionId dataRegionId, long partitionId, boolean isActive, long lastSystemFlushTime, long memsize) { + this(dataRegionId, partitionId, isActive, lastSystemFlushTime, memsize, null); + } + + public TimePartitionInfo( + DataRegionId dataRegionId, + long partitionId, + boolean isActive, + long lastSystemFlushTime, + long memsize, + DataRegion dataRegion) { this.dataRegionId = dataRegionId; this.partitionId = partitionId; this.isActive = isActive; this.lastSystemFlushTime = lastSystemFlushTime; this.memSize = memsize; + this.dataRegionRef = dataRegion == null ? null : new WeakReference<>(dataRegion); + } + + DataRegion getDataRegion() { + return dataRegionRef == null ? null : dataRegionRef.get(); } public int comparePriority(TimePartitionInfo timePartitionInfo) { diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java index 7e45bc1693317..6231be02a1cda 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java @@ -129,6 +129,9 @@ private void degradeLastFlushTime() { timePartitionInfoMemoryBlock.release(timePartitionInfo.memSize); DataRegion dataRegion = StorageEngine.getInstance().getDataRegion(timePartitionInfo.dataRegionId); + if (dataRegion == null) { + dataRegion = timePartitionInfo.getDataRegion(); + } if (dataRegion != null) { dataRegion.degradeFlushTimeMap(timePartitionInfo.partitionId); logger.info( diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java index 90eb10c7cfb72..baa58b12dca22 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java @@ -25,12 +25,14 @@ import org.apache.iotdb.db.conf.DataNodeMemoryConfig; import org.apache.iotdb.db.conf.IoTDBDescriptor; import org.apache.iotdb.db.exception.StorageEngineException; +import org.apache.iotdb.db.storageengine.dataregion.DataRegion; import org.apache.tsfile.exception.write.WriteProcessException; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.mockito.Mockito; import java.io.IOException; @@ -126,4 +128,21 @@ public void testCompareTimePartitionInfo() { new TimePartitionInfo(new DataRegionId(1), 0L, true, 101, 0); Assert.assertEquals(-1, timePartitionInfo.comparePriority(timePartitionInfo3)); } + + @Test + public void testDegradeBeforeStorageEngineRegistration() { + DataRegion mockDataRegion = Mockito.mock(DataRegion.class); + DataRegionId dataRegionId = new DataRegionId(999); + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(dataRegionId, 10L, false, Long.MAX_VALUE, 0, mockDataRegion)); + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(dataRegionId, 11L, false, Long.MAX_VALUE, 0, mockDataRegion)); + + timePartitionManager.updateAfterFlushing(dataRegionId, 10L, 100L, 60L, false); + timePartitionManager.updateAfterFlushing(dataRegionId, 11L, 101L, 60L, false); + + Mockito.verify(mockDataRegion, Mockito.times(1)).degradeFlushTimeMap(10L); + Assert.assertNull(timePartitionManager.getTimePartitionInfo(dataRegionId, 10L)); + Assert.assertNotNull(timePartitionManager.getTimePartitionInfo(dataRegionId, 11L)); + } } From 18d6d078ff891b7bf815e9372389f43219f048c9 Mon Sep 17 00:00:00 2001 From: JackieTien97 Date: Sat, 5 Dec 2026 09:21:47 +0800 Subject: [PATCH 2/7] Address review comments on LastFlushTimeMap degradation during recovery - HashLastFlushTimeMap: perform every mutation of an ILastFlushTime (and of its memory cost) inside partitionLatestFlushedTime.compute(partitionId, ...), so it is serialized with the degradation (computeIfPresent). This avoids ConcurrentModificationException and lost updates when another DataRegion's recovery thread degrades a partition that is still being recovered. - upgradeAndUpdateMultiDeviceFlushedTime: when the partition is already a PartitionLastFlushTime (recovered from FileTimeIndexCache or degraded), keep it degraded but merge the recovered maximum into it, instead of dropping it. - TimePartitionManager: prefer the DataRegion stored in TimePartitionInfo and only fall back to StorageEngine, so that a new region replacing an old one with the same id (snapshot load) is the one degraded; release/remove the entry only after a successful degradation; account the memory of an entry replaced by registerTimePartitionInfo. - Mark the TimePartitionInfo constructor without DataRegion as @TestOnly and make DataRegion#lastFlushTimeMap final. - Add tests for the lookup order, failed degradation, registration accounting, concurrent update/degrade, degradation on the real recovery path, and async recovery finishing after degradation. --- .../iotdb/db/i18n/StorageEngineMessages.java | 3 + .../iotdb/db/i18n/StorageEngineMessages.java | 2 + .../storageengine/dataregion/DataRegion.java | 8 +- .../dataregion/HashLastFlushTimeMap.java | 166 +++++++----- .../rescon/memory/TimePartitionInfo.java | 12 + .../rescon/memory/TimePartitionManager.java | 37 ++- .../dataregion/LastFlushTimeMapTest.java | 255 ++++++++++++++++++ .../memory/TimePartitionManagerTest.java | 81 ++++++ 8 files changed, 483 insertions(+), 81 deletions(-) diff --git a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java index 0015bf4a63f33..3656e74520da9 100644 --- a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java +++ b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java @@ -1533,6 +1533,9 @@ private StorageEngineMessages() {} public static final String STORAGE_LOG_DEGRADE_LASTFLUSHTIMEMAP_OF_OLD_TIMEPARTITIONINFO_MEM_SIZE_BED053EE = "[{}]degrade LastFlushTimeMap of old TimePartitionInfo-{}, mem size is {}, remaining mem " + "cost is {}"; + public static final String STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_TIMEPARTITIONINFO_KEEP_IT_REGISTERED_2B2924D0 = + "[{}]Failed to degrade LastFlushTimeMap of TimePartitionInfo-{}, keep it registered so " + + "that its memory is still accounted"; public static final String STORAGE_LOG_LIMIT_OF_ARRAY_DEQUE_SIZE_UPDATED_05DBA95E = "limit of {} array deque size updated: {} -> {}"; public static final String STORAGE_LOG_LIMITUPDATETHRESHOLD_OF_PRIMITIVEARRAYMANAGER_UPDATED_394801AE = diff --git a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java index 80c70ee05d745..0696f0d14c9e9 100644 --- a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java +++ b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java @@ -1452,6 +1452,8 @@ private StorageEngineMessages() {} "SG ({}) 已释放内存 (delta:{}),但系统仍处于拒绝状态 (totalSgMemCost:{})。"; public static final String STORAGE_LOG_DEGRADE_LASTFLUSHTIMEMAP_OF_OLD_TIMEPARTITIONINFO_MEM_SIZE_BED053EE = "[{}] 降级旧 TimePartitionInfo-{} 的 LastFlushTimeMap,内存大小为 {},剩余内存开销为 {}"; + public static final String STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_TIMEPARTITIONINFO_KEEP_IT_REGISTERED_2B2924D0 = + "[{}] 降级 TimePartitionInfo-{} 的 LastFlushTimeMap 失败,保留该分区的注册信息以继续统计其内存"; public static final String STORAGE_LOG_LIMIT_OF_ARRAY_DEQUE_SIZE_UPDATED_05DBA95E = "{} array deque 大小限制已更新:{} -> {}"; public static final String STORAGE_LOG_LIMITUPDATETHRESHOLD_OF_PRIMITIVEARRAYMANAGER_UPDATED_394801AE = 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 4e78ae2e7078a..3d51649187c8c 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 @@ -391,7 +391,7 @@ public class DataRegion implements IDataRegionForQuery { /** flush listeners. */ private List customFlushListeners = Collections.emptyList(); - private ILastFlushTimeMap lastFlushTimeMap; + private final ILastFlushTimeMap lastFlushTimeMap; /** * Record the insertWriteLock in SG is being hold by which method, it will be empty string if no @@ -465,6 +465,11 @@ public DataRegion( logger.error(StorageEngineMessages.CREATE_DB_SYSTEM_DIR_FAILED, dataRegionSysDir.getPath()); } + // Must be initialized before recover(): during recovery, `this` is published to + // TimePartitionManager through TimePartitionInfo (before this region is registered in + // StorageEngine), and other threads may call degradeFlushTimeMap() on it. TimePartitionManager + // synchronizes registration and degradation on the same monitor, and lastFlushTimeMap is final, + // so those threads always see a fully initialized map. lastFlushTimeMap = new HashLastFlushTimeMap(); upgradeModFileThreadPool = IoTDBThreadPoolFactory.newSingleThreadExecutor( @@ -524,6 +529,7 @@ public DataRegion(String databaseName, String dataRegionIdString) { this.dataRegionId = new DataRegionId(Integer.parseInt(this.dataRegionIdString)); this.dataRegionInfo = new DataRegionInfo(this); this.tsFileManager = new TsFileManager(databaseName, dataRegionIdString, ""); + this.lastFlushTimeMap = new HashLastFlushTimeMap(); this.partitionMaxFileVersions = new HashMap<>(); partitionMaxFileVersions.put(0L, 0L); upgradeModFileThreadPool = null; diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/HashLastFlushTimeMap.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/HashLastFlushTimeMap.java index 2452cfd011125..f2529d76ca165 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/HashLastFlushTimeMap.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/HashLastFlushTimeMap.java @@ -44,104 +44,118 @@ public class HashLastFlushTimeMap implements ILastFlushTimeMap { /** record memory cost of map for each partitionId */ private final Map memCostForEachPartition = new ConcurrentHashMap<>(); + /* + * Concurrency note: every mutation of an ILastFlushTime (and of the memory cost of its partition) + * is performed inside partitionLatestFlushedTime.compute(partitionId, ...). The degradation + * triggered by TimePartitionManager may run in another thread (e.g. the recovery thread of + * another DataRegion, or a flush thread that does not hold this region's write lock), and it + * replaces the ILastFlushTime inside computeIfPresent(partitionId, ...). Serializing both on the + * same key guarantees that the degradation never iterates a DeviceLastFlushTime that is being + * modified, and that no update is applied to a stale DeviceLastFlushTime after it was replaced. + */ + // For sync recover resource without fileTimeIndexCache and load @Override public void updateMultiDeviceFlushedTime( long timePartitionId, Map flushedTimeMap) { - ILastFlushTime flushTimeMapForPartition = - partitionLatestFlushedTime.computeIfAbsent( - timePartitionId, id -> new DeviceLastFlushTime()); - - long memIncr = 0L; - for (Map.Entry entry : flushedTimeMap.entrySet()) { - if (flushTimeMapForPartition.getLastFlushTime(entry.getKey()) == Long.MIN_VALUE) { - memIncr += HASHMAP_NODE_BASIC_SIZE + entry.getKey().ramBytesUsed(); - } - flushTimeMapForPartition.updateLastFlushTime(entry.getKey(), entry.getValue()); - } - long finalMemIncr = memIncr; - memCostForEachPartition.compute( - timePartitionId, (k1, v1) -> v1 == null ? finalMemIncr : v1 + finalMemIncr); + partitionLatestFlushedTime.compute( + timePartitionId, + (id, lastFlushTime) -> { + ILastFlushTime flushTimeMapForPartition = + lastFlushTime == null ? new DeviceLastFlushTime() : lastFlushTime; + // a degraded partition only keeps one long, so device entries cost no extra memory + boolean isDeviceLevel = flushTimeMapForPartition instanceof DeviceLastFlushTime; + long memIncr = 0L; + for (Map.Entry entry : flushedTimeMap.entrySet()) { + if (isDeviceLevel + && flushTimeMapForPartition.getLastFlushTime(entry.getKey()) == Long.MIN_VALUE) { + memIncr += HASHMAP_NODE_BASIC_SIZE + entry.getKey().ramBytesUsed(); + } + flushTimeMapForPartition.updateLastFlushTime(entry.getKey(), entry.getValue()); + } + memCostForEachPartition.merge(id, memIncr, Long::sum); + return flushTimeMapForPartition; + }); } // For async recover resource with fileTimeIndexCache @Override public void upgradeAndUpdateMultiDeviceFlushedTime( long timePartitionId, Map flushedTimeMap) { - ILastFlushTime flushTimeMapForPartition = - partitionLatestFlushedTime.computeIfAbsent( - timePartitionId, id -> new DeviceLastFlushTime()); - // upgrade DeviceLastFlushTime to PartitionLastFlushTime - if (flushTimeMapForPartition instanceof PartitionLastFlushTime) { - long maxFlushTime = flushTimeMapForPartition.getLastFlushTime(null); - ILastFlushTime newDeviceLastFlushTime = new DeviceLastFlushTime(); - long memIncr = 0; - for (Map.Entry entry : flushedTimeMap.entrySet()) { - memIncr += HASHMAP_NODE_BASIC_SIZE + entry.getKey().ramBytesUsed(); - newDeviceLastFlushTime.updateLastFlushTime(entry.getKey(), entry.getValue()); - maxFlushTime = Math.max(maxFlushTime, entry.getValue()); - } - long finalMemIncr = memIncr; - memCostForEachPartition.compute( - timePartitionId, (k1, v1) -> v1 == null ? finalMemIncr : v1 + finalMemIncr); - } else { - // go here when DeviceLastFlushTime was recovered by wal recovery - long memIncr = 0; - for (Map.Entry entry : flushedTimeMap.entrySet()) { - if (flushTimeMapForPartition.getLastFlushTime(entry.getKey()) == Long.MIN_VALUE) { - memIncr += HASHMAP_NODE_BASIC_SIZE + entry.getKey().ramBytesUsed(); - } - flushTimeMapForPartition.updateLastFlushTime(entry.getKey(), entry.getValue()); - } - long finalMemIncr = memIncr; - memCostForEachPartition.compute( - timePartitionId, (k1, v1) -> v1 == null ? finalMemIncr : v1 + finalMemIncr); - } + partitionLatestFlushedTime.compute( + timePartitionId, + (id, lastFlushTime) -> { + ILastFlushTime flushTimeMapForPartition = + lastFlushTime == null ? new DeviceLastFlushTime() : lastFlushTime; + if (flushTimeMapForPartition instanceof PartitionLastFlushTime) { + // The partition only keeps a partition-level flush time, either because it was + // recovered from the FileTimeIndexCache, or because TimePartitionManager has degraded + // it to release memory. Keep it degraded, but merge the recovered maximum into it so + // that the partition flush time is never lower than the real max end time. + for (long flushedTime : flushedTimeMap.values()) { + flushTimeMapForPartition.updateLastFlushTime(null, flushedTime); + } + } else { + // go here when DeviceLastFlushTime was recovered by wal recovery + long memIncr = 0; + for (Map.Entry entry : flushedTimeMap.entrySet()) { + if (flushTimeMapForPartition.getLastFlushTime(entry.getKey()) == Long.MIN_VALUE) { + memIncr += HASHMAP_NODE_BASIC_SIZE + entry.getKey().ramBytesUsed(); + } + flushTimeMapForPartition.updateLastFlushTime(entry.getKey(), entry.getValue()); + } + memCostForEachPartition.merge(id, memIncr, Long::sum); + } + return flushTimeMapForPartition; + }); } // For fileTimeIndexCache recovered before the async resource recover start @Override public void updatePartitionFlushedTime(long timePartitionId, long maxFlushedTime) { - ILastFlushTime flushTimeMapForPartition = - partitionLatestFlushedTime.computeIfAbsent( - timePartitionId, id -> new PartitionLastFlushTime(maxFlushedTime)); - - if (flushTimeMapForPartition instanceof PartitionLastFlushTime) { - long memIncr = Long.BYTES; - flushTimeMapForPartition.updateLastFlushTime(null, maxFlushedTime); - memCostForEachPartition.putIfAbsent(timePartitionId, memIncr); - } else { - // go here when DeviceLastFlushTime was recovered by wal recovery - DeviceLastFlushTime deviceLastFlushTime = (DeviceLastFlushTime) flushTimeMapForPartition; - Map flushedTimeMap = deviceLastFlushTime.getDeviceLastFlushTimeMap(); - for (Map.Entry entry : flushedTimeMap.entrySet()) { - flushTimeMapForPartition.updateLastFlushTime(entry.getKey(), entry.getValue()); - } - } + partitionLatestFlushedTime.compute( + timePartitionId, + (id, lastFlushTime) -> { + ILastFlushTime flushTimeMapForPartition = + lastFlushTime == null ? new PartitionLastFlushTime(maxFlushedTime) : lastFlushTime; + if (flushTimeMapForPartition instanceof PartitionLastFlushTime) { + flushTimeMapForPartition.updateLastFlushTime(null, maxFlushedTime); + memCostForEachPartition.putIfAbsent(id, (long) Long.BYTES); + } + // Otherwise the DeviceLastFlushTime was recovered by wal recovery or sync recovery, and + // the device flush times of these resources are merged into it by + // upgradeAndUpdateMultiDeviceFlushedTime after the async recovery. + return flushTimeMapForPartition; + }); } @Override public boolean checkAndCreateFlushedTimePartition( long timePartitionId, boolean usingDeviceFlushTime) { - if (!partitionLatestFlushedTime.containsKey(timePartitionId)) { - partitionLatestFlushedTime.put( - timePartitionId, - usingDeviceFlushTime - ? new DeviceLastFlushTime() - : new PartitionLastFlushTime(Long.MIN_VALUE)); - return false; - } - return true; + return partitionLatestFlushedTime.putIfAbsent( + timePartitionId, + usingDeviceFlushTime + ? new DeviceLastFlushTime() + : new PartitionLastFlushTime(Long.MIN_VALUE)) + != null; } // For insert @Override public void updateLatestFlushTime(long partitionId, Map updateMap) { - for (Map.Entry entry : updateMap.entrySet()) { - partitionLatestFlushedTime - .computeIfAbsent(partitionId, id -> new DeviceLastFlushTime()) - .updateLastFlushTime(entry.getKey(), entry.getValue()); + if (updateMap.isEmpty()) { + return; } + partitionLatestFlushedTime.compute( + partitionId, + (id, lastFlushTime) -> { + ILastFlushTime flushTimeMapForPartition = + lastFlushTime == null ? new DeviceLastFlushTime() : lastFlushTime; + for (Map.Entry entry : updateMap.entrySet()) { + flushTimeMapForPartition.updateLastFlushTime(entry.getKey(), entry.getValue()); + } + return flushTimeMapForPartition; + }); } @Override @@ -158,8 +172,12 @@ public void clearFlushedTime() { @Override public void degradeLastFlushTime(long partitionId) { partitionLatestFlushedTime.computeIfPresent( - partitionId, (id, lastFlushTime) -> lastFlushTime.degradeLastFlushTime()); - memCostForEachPartition.put(partitionId, (long) Long.BYTES); + partitionId, + (id, lastFlushTime) -> { + ILastFlushTime degradedLastFlushTime = lastFlushTime.degradeLastFlushTime(); + memCostForEachPartition.put(id, (long) Long.BYTES); + return degradedLastFlushTime; + }); } @Override diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionInfo.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionInfo.java index 06f13a2662fea..1fc6f19fb6fd6 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionInfo.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionInfo.java @@ -20,6 +20,7 @@ package org.apache.iotdb.db.storageengine.rescon.memory; import org.apache.iotdb.commons.consensus.DataRegionId; +import org.apache.iotdb.commons.utils.TestOnly; import org.apache.iotdb.db.storageengine.dataregion.DataRegion; import java.lang.ref.WeakReference; @@ -36,8 +37,19 @@ public class TimePartitionInfo { long memSize; + /** + * The DataRegion that owns this time partition. It is used to degrade the LastFlushTimeMap of the + * region when the region is not (or not yet) the one registered in StorageEngine, e.g. while the + * region is being constructed and recovered. A weak reference is used so that a region whose + * construction failed is not pinned in memory by TimePartitionManager. + */ private final WeakReference dataRegionRef; + /** + * Production code should always pass the owning DataRegion, otherwise the LastFlushTimeMap of a + * region that is not registered in StorageEngine cannot be degraded. + */ + @TestOnly public TimePartitionInfo( DataRegionId dataRegionId, long partitionId, diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java index 6231be02a1cda..f3afa7123d4e4 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java @@ -62,7 +62,16 @@ public void registerTimePartitionInfo(TimePartitionInfo timePartitionInfo) { timePartitionInfoMap.computeIfAbsent( timePartitionInfo.dataRegionId, k -> new TreeMap<>()); - timePartitionInfoMapForRegion.put(timePartitionInfo.partitionId, timePartitionInfo); + TimePartitionInfo previous = + timePartitionInfoMapForRegion.put(timePartitionInfo.partitionId, timePartitionInfo); + + // Account the memory of the registered partition, and release the memory of the entry it + // replaces (e.g. an entry of a replaced DataRegion with the same id), so that the memory + // block stays consistent with the memSize of the registered entries. + long memSizeDelta = timePartitionInfo.memSize - (previous == null ? 0 : previous.memSize); + if (memSizeDelta != 0) { + timePartitionInfoMemoryBlock.forceAllocateWithoutLimitation(memSizeDelta); + } // We need to ensure that the following method is called before // PipeInsertionDataNodeListener.listenToInsertNode. @@ -126,14 +135,30 @@ private void degradeLastFlushTime() { if (timePartitionInfo == null) { return; } - timePartitionInfoMemoryBlock.release(timePartitionInfo.memSize); - DataRegion dataRegion = - StorageEngine.getInstance().getDataRegion(timePartitionInfo.dataRegionId); + // Prefer the DataRegion that registered this entry. StorageEngine may not contain the + // region yet (it is still being constructed and recovered), or may still contain an old + // region with the same id (e.g. while a region is being replaced by snapshot loading). + DataRegion dataRegion = timePartitionInfo.getDataRegion(); if (dataRegion == null) { - dataRegion = timePartitionInfo.getDataRegion(); + dataRegion = StorageEngine.getInstance().getDataRegion(timePartitionInfo.dataRegionId); + } + if (dataRegion != null) { + try { + dataRegion.degradeFlushTimeMap(timePartitionInfo.partitionId); + } catch (RuntimeException e) { + // The LastFlushTimeMap is not degraded, so its memory is still occupied. Keep the entry + // and its memory accounting, it can be degraded again later. + logger.warn( + StorageEngineMessages + .STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_TIMEPARTITIONINFO_KEEP_IT_REGISTERED_2B2924D0, + timePartitionInfo.dataRegionId, + timePartitionInfo.partitionId, + e); + continue; + } } + timePartitionInfoMemoryBlock.release(timePartitionInfo.memSize); if (dataRegion != null) { - dataRegion.degradeFlushTimeMap(timePartitionInfo.partitionId); logger.info( StorageEngineMessages .STORAGE_LOG_DEGRADE_LASTFLUSHTIMEMAP_OF_OLD_TIMEPARTITIONINFO_MEM_SIZE_BED053EE, diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/LastFlushTimeMapTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/LastFlushTimeMapTest.java index 7f58ccdd22831..bc61ccb24ba43 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/LastFlushTimeMapTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/LastFlushTimeMapTest.java @@ -19,14 +19,18 @@ package org.apache.iotdb.db.storageengine.dataregion; +import org.apache.iotdb.commons.conf.IoTDBConstant; import org.apache.iotdb.commons.consensus.DataRegionId; import org.apache.iotdb.commons.exception.IllegalPathException; +import org.apache.iotdb.commons.utils.TimePartitionUtils; +import org.apache.iotdb.db.conf.IoTDBDescriptor; import org.apache.iotdb.db.exception.DataRegionException; import org.apache.iotdb.db.exception.WriteProcessException; import org.apache.iotdb.db.storageengine.StorageEngine; import org.apache.iotdb.db.storageengine.dataregion.compaction.schedule.CompactionTaskManager; import org.apache.iotdb.db.storageengine.dataregion.tsfile.TsFileResource; import org.apache.iotdb.db.storageengine.dataregion.tsfile.timeindex.ArrayDeviceTimeIndex; +import org.apache.iotdb.db.storageengine.rescon.memory.TimePartitionManager; import org.apache.iotdb.db.utils.EnvironmentUtils; import org.apache.iotdb.db.utils.constant.TestConstant; @@ -42,9 +46,21 @@ import java.io.File; import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.file.Files; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.Optional; +import java.util.concurrent.Callable; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; public class LastFlushTimeMapTest { @@ -266,4 +282,243 @@ public void testLastFlushedTimeWhenLargestTimestampInUnSeqSpace() dataRegion.getLastFlushTimeMap().degradeLastFlushTime(0); Assert.assertEquals(100, dataRegion.getLastFlushTimeMap().getFlushedTime(0, device)); } + + @Test + public void testUpgradeAfterDegradeKeepsPartitionMaximum() { + IDeviceID device = IDeviceID.Factory.DEFAULT_FACTORY.create("root.vehicle.d0"); + HashLastFlushTimeMap lastFlushTimeMap = new HashLastFlushTimeMap(); + lastFlushTimeMap.updateMultiDeviceFlushedTime(0, Collections.singletonMap(device, 100L)); + lastFlushTimeMap.degradeLastFlushTime(0); + Assert.assertEquals(Long.BYTES, lastFlushTimeMap.getMemSize(0)); + + // the async recovery finishes after the partition has been degraded + lastFlushTimeMap.upgradeAndUpdateMultiDeviceFlushedTime( + 0, Collections.singletonMap(device, 200L)); + + Assert.assertEquals(200L, lastFlushTimeMap.getFlushedTime(0, device)); + // still degraded + Assert.assertEquals(Long.BYTES, lastFlushTimeMap.getMemSize(0)); + IDeviceID otherDevice = IDeviceID.Factory.DEFAULT_FACTORY.create("root.vehicle.d1"); + Assert.assertEquals(200L, lastFlushTimeMap.getFlushedTime(0, otherDevice)); + } + + @Test + public void testConcurrentUpdateAndDegrade() throws InterruptedException { + final int partitionNum = 200; + final int deviceNum = 1000; + final HashLastFlushTimeMap lastFlushTimeMap = new HashLastFlushTimeMap(); + final IDeviceID[] devices = new IDeviceID[deviceNum]; + for (int i = 0; i < deviceNum; i++) { + devices[i] = IDeviceID.Factory.DEFAULT_FACTORY.create("root.vehicle.d" + i); + } + final AtomicLong updatingPartition = new AtomicLong(-1); + final AtomicBoolean finished = new AtomicBoolean(false); + final AtomicReference failure = new AtomicReference<>(); + + Thread updater = + new Thread( + () -> { + try { + for (int partition = 0; partition < partitionNum; partition++) { + updatingPartition.set(partition); + // update the devices one by one so that the degradation can interleave + for (int i = 0; i < deviceNum; i++) { + lastFlushTimeMap.updateMultiDeviceFlushedTime( + partition, Collections.singletonMap(devices[i], (long) i)); + } + Map batch = new HashMap<>(); + for (int i = 0; i < deviceNum; i++) { + batch.put(devices[i], (long) i); + } + lastFlushTimeMap.updateMultiDeviceFlushedTime(partition, batch); + } + } catch (Throwable t) { + failure.compareAndSet(null, t); + } finally { + finished.set(true); + } + }); + Thread degrader = + new Thread( + () -> { + try { + while (!finished.get()) { + long partition = updatingPartition.get(); + if (partition >= 0) { + lastFlushTimeMap.degradeLastFlushTime(partition); + } + } + } catch (Throwable t) { + failure.compareAndSet(null, t); + } + }); + updater.start(); + degrader.start(); + updater.join(60_000); + degrader.join(60_000); + + Assert.assertNull(failure.get()); + for (int partition = 0; partition < partitionNum; partition++) { + lastFlushTimeMap.degradeLastFlushTime(partition); + // no update is lost, so the degraded partition flush time is the max of all devices + Assert.assertEquals(deviceNum - 1L, lastFlushTimeMap.getFlushedTime(partition, devices[0])); + Assert.assertEquals(Long.BYTES, lastFlushTimeMap.getMemSize(partition)); + } + } + + @Test + public void testDegradeDuringRecovery() throws Exception { + IDeviceID device = IDeviceID.Factory.DEFAULT_FACTORY.create("root.vehicle.d0"); + long partitionInterval = TimePartitionUtils.getTimePartitionInterval(); + for (int partition = 0; partition < 3; partition++) { + insertAndClose(partition * partitionInterval + 100); + } + + long prevThreshold = getTimePartitionInfoMemoryThreshold(); + try { + // only allows one partition to keep its device level flush time + TimePartitionManager.getInstance().clear(); + TimePartitionManager.getInstance().setTimePartitionInfoMemoryThreshold(memSizeOfOneDevice()); + + // recover from disk, while the old region with the same id is still in StorageEngine + dataRegion = new DataRegionTest.DummyDataRegion(systemDir, storageGroup); + + ILastFlushTimeMap lastFlushTimeMap = dataRegion.getLastFlushTimeMap(); + // the early partitions of the recovering region are degraded + Assert.assertEquals(Long.BYTES, lastFlushTimeMap.getMemSize(0)); + Assert.assertEquals(Long.BYTES, lastFlushTimeMap.getMemSize(1)); + Assert.assertEquals(memSizeOfOneDevice(), lastFlushTimeMap.getMemSize(2)); + for (int partition = 0; partition < 3; partition++) { + Assert.assertEquals( + partition * partitionInterval + 100, + lastFlushTimeMap.getFlushedTime(partition, device)); + } + DataRegionId dataRegionId = new DataRegionId(0); + Assert.assertNull(TimePartitionManager.getInstance().getTimePartitionInfo(dataRegionId, 0)); + Assert.assertNull(TimePartitionManager.getInstance().getTimePartitionInfo(dataRegionId, 1)); + Assert.assertNotNull( + TimePartitionManager.getInstance().getTimePartitionInfo(dataRegionId, 2)); + } finally { + TimePartitionManager.getInstance().setTimePartitionInfoMemoryThreshold(prevThreshold); + TimePartitionManager.getInstance().clear(); + } + } + + @Test + public void testAsyncRecoveryAfterDegradeKeepsPartitionMaximum() throws Exception { + IDeviceID device = IDeviceID.Factory.DEFAULT_FACTORY.create("root.vehicle.d0"); + long partitionInterval = TimePartitionUtils.getTimePartitionInterval(); + TsFileResource seqResource = insertAndClose(100); + TsFileResource unseqResource = insertAndClose(200); + TsFileResource laterPartitionResource = insertAndClose(partitionInterval + 100); + Assert.assertEquals(0, seqResource.getTimePartition()); + Assert.assertEquals(0, unseqResource.getTimePartition()); + Assert.assertEquals(1, laterPartitionResource.getTimePartition()); + + // partition 0: a sequence file ends at 100 and an unsequence file ends at 200 + // partition 1: an unsequence file, recovered after partition 0 + moveToUnsequenceDir(unseqResource); + moveToUnsequenceDir(laterPartitionResource); + // only the unsequence file of partition 0 has a FileTimeIndexCache entry, so that it is + // recovered asynchronously + writeFileTimeIndexCache(unseqResource); + + long prevThreshold = getTimePartitionInfoMemoryThreshold(); + try { + TimePartitionManager.getInstance().clear(); + TimePartitionManager.getInstance().setTimePartitionInfoMemoryThreshold(memSizeOfOneDevice()); + + // recovering partition 1 degrades partition 0 before its async recovery task runs + dataRegion = new DataRegionTest.DummyDataRegion(systemDir, storageGroup); + Assert.assertEquals(Long.BYTES, dataRegion.getLastFlushTimeMap().getMemSize(0)); + Assert.assertEquals(100L, dataRegion.getLastFlushTimeMap().getFlushedTime(0, device)); + + List> asyncRecoverTasks = + new ArrayList<>(dataRegion.getAsyncTsFileResourceRecoverTaskList()); + Assert.assertFalse(asyncRecoverTasks.isEmpty()); + for (Callable task : asyncRecoverTasks) { + task.call(); + } + dataRegion.clearAsyncTsFileResourceRecoverTaskList(); + + Assert.assertEquals(200L, dataRegion.getLastFlushTimeMap().getFlushedTime(0, device)); + Assert.assertEquals(Long.BYTES, dataRegion.getLastFlushTimeMap().getMemSize(0)); + + // 150 is not larger than the max end time of partition 0, so it must be unsequence data + TSRecord record = new TSRecord("root.vehicle.d0", 150); + record.addTuple(DataPoint.getDataPoint(TSDataType.INT32, measurementId, "150")); + dataRegion.insert(DataRegionTest.buildInsertRowNodeByTSRecord(record)); + Assert.assertTrue(dataRegion.getWorkSequenceTsFileProcessors().isEmpty()); + Assert.assertEquals(1, dataRegion.getWorkUnsequenceTsFileProcessors().size()); + } finally { + TimePartitionManager.getInstance().setTimePartitionInfoMemoryThreshold(prevThreshold); + TimePartitionManager.getInstance().clear(); + } + } + + private TsFileResource insertAndClose(long time) + throws IllegalPathException, WriteProcessException { + TSRecord record = new TSRecord("root.vehicle.d0", time); + record.addTuple(DataPoint.getDataPoint(TSDataType.INT32, measurementId, String.valueOf(time))); + dataRegion.insert(DataRegionTest.buildInsertRowNodeByTSRecord(record)); + TsFileResource resource = + dataRegion.getWorkSequenceTsFileProcessors().iterator().next().getTsFileResource(); + dataRegion.syncCloseAllWorkingTsFileProcessors(); + return resource; + } + + private static long getTimePartitionInfoMemoryThreshold() { + return IoTDBDescriptor.getInstance() + .getMemoryConfig() + .getTimePartitionInfoMemoryManager() + .getTotalMemorySizeInBytes(); + } + + private static long memSizeOfOneDevice() { + HashLastFlushTimeMap lastFlushTimeMap = new HashLastFlushTimeMap(); + lastFlushTimeMap.updateMultiDeviceFlushedTime( + 0, + Collections.singletonMap(IDeviceID.Factory.DEFAULT_FACTORY.create("root.vehicle.d0"), 0L)); + return lastFlushTimeMap.getMemSize(0); + } + + private static void moveToUnsequenceDir(TsFileResource resource) throws IOException { + File tsFile = resource.getTsFile(); + File partitionDir = tsFile.getParentFile(); + File regionDir = partitionDir.getParentFile(); + File databaseDir = regionDir.getParentFile(); + File sequenceDir = databaseDir.getParentFile(); + Assert.assertEquals(IoTDBConstant.SEQUENCE_FOLDER_NAME, sequenceDir.getName()); + File targetDir = + new File( + new File( + new File( + new File(sequenceDir.getParentFile(), IoTDBConstant.UNSEQUENCE_FOLDER_NAME), + databaseDir.getName()), + regionDir.getName()), + partitionDir.getName()); + Assert.assertTrue(targetDir.isDirectory() || targetDir.mkdirs()); + Files.move(tsFile.toPath(), new File(targetDir, tsFile.getName()).toPath()); + File resourceFile = new File(tsFile.getPath() + TsFileResource.RESOURCE_SUFFIX); + Files.move(resourceFile.toPath(), new File(targetDir, resourceFile.getName()).toPath()); + } + + private void writeFileTimeIndexCache(TsFileResource... resources) throws IOException { + // the FileTimeIndexCache read by DataRegion#recover() + File cacheFile = new File(new File(systemDir, "0"), "FileTimeIndexCache_0"); + ByteBuffer buffer = + ByteBuffer.allocate(TsFileResource.getFileTimeIndexSerializedSize() * resources.length); + for (TsFileResource resource : resources) { + resource.serializeFileTimeIndexToByteBuffer(buffer); + } + buffer.flip(); + try (FileChannel channel = + FileChannel.open( + cacheFile.toPath(), + StandardOpenOption.CREATE, + StandardOpenOption.WRITE, + StandardOpenOption.TRUNCATE_EXISTING)) { + channel.write(buffer); + } + } } diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java index baa58b12dca22..1d5cadbc14e27 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java @@ -25,6 +25,7 @@ import org.apache.iotdb.db.conf.DataNodeMemoryConfig; import org.apache.iotdb.db.conf.IoTDBDescriptor; import org.apache.iotdb.db.exception.StorageEngineException; +import org.apache.iotdb.db.storageengine.StorageEngine; import org.apache.iotdb.db.storageengine.dataregion.DataRegion; import org.apache.tsfile.exception.write.WriteProcessException; @@ -142,7 +143,87 @@ public void testDegradeBeforeStorageEngineRegistration() { timePartitionManager.updateAfterFlushing(dataRegionId, 11L, 101L, 60L, false); Mockito.verify(mockDataRegion, Mockito.times(1)).degradeFlushTimeMap(10L); + Mockito.verify(mockDataRegion, Mockito.never()).degradeFlushTimeMap(11L); Assert.assertNull(timePartitionManager.getTimePartitionInfo(dataRegionId, 10L)); Assert.assertNotNull(timePartitionManager.getTimePartitionInfo(dataRegionId, 11L)); } + + @Test + public void testDegradePrefersRegisteredDataRegionOverStorageEngine() { + DataRegionId dataRegionId = new DataRegionId(999); + // e.g. the old region that is still in StorageEngine while a new region with the same id is + // being recovered for snapshot loading + DataRegion regionInStorageEngine = Mockito.mock(DataRegion.class); + Mockito.when(regionInStorageEngine.getDataRegionIdString()).thenReturn("999"); + DataRegion registeringRegion = Mockito.mock(DataRegion.class); + StorageEngine.getInstance().setDataRegion(dataRegionId, regionInStorageEngine); + try { + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(dataRegionId, 10L, false, Long.MAX_VALUE, 0, registeringRegion)); + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(dataRegionId, 11L, false, Long.MAX_VALUE, 0, registeringRegion)); + + timePartitionManager.updateAfterFlushing(dataRegionId, 10L, 100L, 60L, false); + timePartitionManager.updateAfterFlushing(dataRegionId, 11L, 101L, 60L, false); + + Mockito.verify(registeringRegion, Mockito.times(1)).degradeFlushTimeMap(10L); + Mockito.verify(registeringRegion, Mockito.never()).degradeFlushTimeMap(11L); + Mockito.verify(regionInStorageEngine, Mockito.never()).degradeFlushTimeMap(Mockito.anyLong()); + Assert.assertNull(timePartitionManager.getTimePartitionInfo(dataRegionId, 10L)); + Assert.assertNotNull(timePartitionManager.getTimePartitionInfo(dataRegionId, 11L)); + } finally { + StorageEngine.getInstance().reset(); + } + } + + @Test + public void testFailedDegradeKeepsTimePartitionInfoAndMemory() { + DataRegion failingDataRegion = Mockito.mock(DataRegion.class); + Mockito.doThrow(new IllegalStateException("mock degrade failure")) + .when(failingDataRegion) + .degradeFlushTimeMap(10L); + DataRegionId dataRegionId = new DataRegionId(999); + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(dataRegionId, 10L, false, Long.MAX_VALUE, 0, failingDataRegion)); + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(dataRegionId, 11L, false, Long.MAX_VALUE, 0, failingDataRegion)); + + timePartitionManager.updateAfterFlushing(dataRegionId, 10L, 100L, 60L, false); + timePartitionManager.updateAfterFlushing(dataRegionId, 11L, 101L, 60L, false); + + // partition 10 failed to degrade, so partition 11 is degraded instead + Mockito.verify(failingDataRegion, Mockito.times(1)).degradeFlushTimeMap(10L); + Mockito.verify(failingDataRegion, Mockito.times(1)).degradeFlushTimeMap(11L); + TimePartitionInfo keptInfo = timePartitionManager.getTimePartitionInfo(dataRegionId, 10L); + Assert.assertNotNull(keptInfo); + Assert.assertNull(timePartitionManager.getTimePartitionInfo(dataRegionId, 11L)); + // only the memory of the degraded partition is released + Assert.assertEquals( + keptInfo.memSize, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); + } + + @Test + public void testRegisterAccountsMemoryOfReplacedTimePartitionInfo() { + DataRegionId dataRegionId = new DataRegionId(999); + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(dataRegionId, 10L, false, Long.MAX_VALUE, 0)); + timePartitionManager.updateAfterFlushing(dataRegionId, 10L, 100L, 60L, false); + Assert.assertEquals( + 60L, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); + + // replaced by the entry of a new region with the same id, e.g. after snapshot loading + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(dataRegionId, 10L, false, Long.MAX_VALUE, 0)); + Assert.assertEquals( + 0L, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); + + // registered with a non-zero memory size + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(dataRegionId, 11L, false, Long.MAX_VALUE, Long.BYTES)); + Assert.assertEquals( + Long.BYTES, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); + timePartitionManager.removeTimePartitionInfo(dataRegionId); + Assert.assertEquals( + 0L, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); + } } From fe13f4c92120d366d080c5d8c9cd9ad02386d081 Mon Sep 17 00:00:00 2001 From: JackieTien97 Date: Sat, 5 Dec 2026 10:29:56 +0800 Subject: [PATCH 3/7] Keep replaced flush-time maps accounted and avoid allocation on partition hits - TimePartitionManager#registerTimePartitionInfo: when the replaced entry belongs to another DataRegion with the same id that is still alive (e.g. the old region kept in StorageEngine during snapshot loading), degrade its LastFlushTimeMap before releasing its accounting. If the degradation fails, keep the memory accounted. Entries re-registered by the same region, or whose region has been garbage collected, are released as before. - HashLastFlushTimeMap#checkAndCreateFlushedTimePartition: return early when the partition exists, and only construct the value and putIfAbsent on a miss, so that each insertion no longer allocates a DeviceLastFlushTime. --- .../iotdb/db/i18n/StorageEngineMessages.java | 3 + .../iotdb/db/i18n/StorageEngineMessages.java | 2 + .../dataregion/HashLastFlushTimeMap.java | 5 ++ .../rescon/memory/TimePartitionManager.java | 49 ++++++++++++-- .../dataregion/LastFlushTimeMapTest.java | 32 ++++++++++ .../memory/TimePartitionManagerTest.java | 64 +++++++++++++++++++ 6 files changed, 151 insertions(+), 4 deletions(-) diff --git a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java index 3656e74520da9..2935159cee378 100644 --- a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java +++ b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java @@ -1536,6 +1536,9 @@ private StorageEngineMessages() {} public static final String STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_TIMEPARTITIONINFO_KEEP_IT_REGISTERED_2B2924D0 = "[{}]Failed to degrade LastFlushTimeMap of TimePartitionInfo-{}, keep it registered so " + "that its memory is still accounted"; + public static final String STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_REPLACED_TIMEPARTITIONINFO_47B56998 = + "[{}]Failed to degrade LastFlushTimeMap of replaced TimePartitionInfo-{}, keep its memory " + + "accounted"; public static final String STORAGE_LOG_LIMIT_OF_ARRAY_DEQUE_SIZE_UPDATED_05DBA95E = "limit of {} array deque size updated: {} -> {}"; public static final String STORAGE_LOG_LIMITUPDATETHRESHOLD_OF_PRIMITIVEARRAYMANAGER_UPDATED_394801AE = diff --git a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java index 0696f0d14c9e9..8127ae67cebea 100644 --- a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java +++ b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java @@ -1454,6 +1454,8 @@ private StorageEngineMessages() {} "[{}] 降级旧 TimePartitionInfo-{} 的 LastFlushTimeMap,内存大小为 {},剩余内存开销为 {}"; public static final String STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_TIMEPARTITIONINFO_KEEP_IT_REGISTERED_2B2924D0 = "[{}] 降级 TimePartitionInfo-{} 的 LastFlushTimeMap 失败,保留该分区的注册信息以继续统计其内存"; + public static final String STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_REPLACED_TIMEPARTITIONINFO_47B56998 = + "[{}] 降级被替换的 TimePartitionInfo-{} 的 LastFlushTimeMap 失败,继续统计其内存"; public static final String STORAGE_LOG_LIMIT_OF_ARRAY_DEQUE_SIZE_UPDATED_05DBA95E = "{} array deque 大小限制已更新:{} -> {}"; public static final String STORAGE_LOG_LIMITUPDATETHRESHOLD_OF_PRIMITIVEARRAYMANAGER_UPDATED_394801AE = diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/HashLastFlushTimeMap.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/HashLastFlushTimeMap.java index f2529d76ca165..68769cd8a92b5 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/HashLastFlushTimeMap.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/HashLastFlushTimeMap.java @@ -132,6 +132,11 @@ public void updatePartitionFlushedTime(long timePartitionId, long maxFlushedTime @Override public boolean checkAndCreateFlushedTimePartition( long timePartitionId, boolean usingDeviceFlushTime) { + // fast path without allocation, this method is called for every insertion + if (partitionLatestFlushedTime.containsKey(timePartitionId)) { + return true; + } + // putIfAbsent keeps the creation atomic when several threads meet a new partition together return partitionLatestFlushedTime.putIfAbsent( timePartitionId, usingDeviceFlushTime diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java index f3afa7123d4e4..0250aee9193b2 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java @@ -65,10 +65,13 @@ public void registerTimePartitionInfo(TimePartitionInfo timePartitionInfo) { TimePartitionInfo previous = timePartitionInfoMapForRegion.put(timePartitionInfo.partitionId, timePartitionInfo); - // Account the memory of the registered partition, and release the memory of the entry it - // replaces (e.g. an entry of a replaced DataRegion with the same id), so that the memory - // block stays consistent with the memSize of the registered entries. - long memSizeDelta = timePartitionInfo.memSize - (previous == null ? 0 : previous.memSize); + // Account the memory of the registered partition. The memory of the replaced entry is only + // released when the LastFlushTimeMap it accounts for is gone or degraded. + long releasedMemSize = + previous != null && releaseReplacedTimePartitionInfo(previous, timePartitionInfo) + ? previous.memSize + : 0; + long memSizeDelta = timePartitionInfo.memSize - releasedMemSize; if (memSizeDelta != 0) { timePartitionInfoMemoryBlock.forceAllocateWithoutLimitation(memSizeDelta); } @@ -84,6 +87,44 @@ public void registerTimePartitionInfo(TimePartitionInfo timePartitionInfo) { } } + /** + * Called when {@code current} replaces {@code previous} in timePartitionInfoMap. + * + * @return whether the memory accounted by {@code previous} can be released + */ + private boolean releaseReplacedTimePartitionInfo( + TimePartitionInfo previous, TimePartitionInfo current) { + DataRegion previousDataRegion = previous.getDataRegion(); + if (previousDataRegion == null || previousDataRegion == current.getDataRegion()) { + // The same region registers the partition again, so the memory is accounted by the new + // entry; or the previous region has been garbage collected together with its map. + return true; + } + // The previous entry belongs to another region with the same id that is still alive, e.g. the + // old region kept in StorageEngine while its replacement is recovered for snapshot loading. + // Its LastFlushTimeMap is still on the heap and can no longer be found through + // timePartitionInfoMap, so degrade it now instead of only dropping its accounting. + try { + previousDataRegion.degradeFlushTimeMap(previous.partitionId); + } catch (RuntimeException e) { + logger.warn( + StorageEngineMessages + .STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_REPLACED_TIMEPARTITIONINFO_47B56998, + previous.dataRegionId, + previous.partitionId, + e); + return false; + } + logger.info( + StorageEngineMessages + .STORAGE_LOG_DEGRADE_LASTFLUSHTIMEMAP_OF_OLD_TIMEPARTITIONINFO_MEM_SIZE_BED053EE, + previous.dataRegionId, + previous.partitionId, + previous.memSize, + timePartitionInfoMemoryBlock.getUsedMemoryInBytes() - previous.memSize); + return true; + } + public void updateAfterFlushing( DataRegionId dataRegionId, long timePartitionId, diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/LastFlushTimeMapTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/LastFlushTimeMapTest.java index bc61ccb24ba43..bada0ceda2f94 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/LastFlushTimeMapTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/LastFlushTimeMapTest.java @@ -456,6 +456,38 @@ public void testAsyncRecoveryAfterDegradeKeepsPartitionMaximum() throws Exceptio } } + @Test + public void testReplacementRegionDegradesOldRegionMap() throws Exception { + for (int i = 0; i < 10; i++) { + TSRecord record = new TSRecord("root.vehicle.d" + i, 100); + record.addTuple(DataPoint.getDataPoint(TSDataType.INT32, measurementId, "100")); + dataRegion.insert(DataRegionTest.buildInsertRowNodeByTSRecord(record)); + } + dataRegion.syncCloseAllWorkingTsFileProcessors(); + IDeviceID device = IDeviceID.Factory.DEFAULT_FACTORY.create("root.vehicle.d0"); + + try { + TimePartitionManager.getInstance().clear(); + // the old region, recovered from disk and registered in StorageEngine + DataRegion oldRegion = new DataRegionTest.DummyDataRegion(systemDir, storageGroup); + StorageEngine.getInstance().setDataRegion(new DataRegionId(0), oldRegion); + long memSizeOfPartition = oldRegion.getLastFlushTimeMap().getMemSize(0); + Assert.assertTrue(memSizeOfPartition > Long.BYTES); + + // the replacement region (e.g. loaded from a snapshot) is recovered while the old region is + // still in StorageEngine + dataRegion = new DataRegionTest.DummyDataRegion(systemDir, storageGroup); + + // the old map is degraded instead of staying on the heap without being accounted + Assert.assertEquals(Long.BYTES, oldRegion.getLastFlushTimeMap().getMemSize(0)); + Assert.assertEquals(100L, oldRegion.getLastFlushTimeMap().getFlushedTime(0, device)); + Assert.assertEquals(memSizeOfPartition, dataRegion.getLastFlushTimeMap().getMemSize(0)); + Assert.assertEquals(100L, dataRegion.getLastFlushTimeMap().getFlushedTime(0, device)); + } finally { + TimePartitionManager.getInstance().clear(); + } + } + private TsFileResource insertAndClose(long time) throws IllegalPathException, WriteProcessException { TSRecord record = new TSRecord("root.vehicle.d0", time); diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java index 1d5cadbc14e27..16fe7d789d8b0 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java @@ -226,4 +226,68 @@ public void testRegisterAccountsMemoryOfReplacedTimePartitionInfo() { Assert.assertEquals( 0L, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); } + + @Test + public void testReplacedByAnotherRegionDegradesOldRegion() { + DataRegionId dataRegionId = new DataRegionId(999); + DataRegion oldRegion = Mockito.mock(DataRegion.class); + DataRegion newRegion = Mockito.mock(DataRegion.class); + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(dataRegionId, 10L, false, Long.MAX_VALUE, 0, oldRegion)); + timePartitionManager.updateAfterFlushing(dataRegionId, 10L, 100L, 60L, false); + + // the replacement region (e.g. loaded from a snapshot) registers the same partition while the + // old region is still alive + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(dataRegionId, 10L, false, Long.MAX_VALUE, 0, newRegion)); + // the old map is degraded together with releasing its accounting + Mockito.verify(oldRegion, Mockito.times(1)).degradeFlushTimeMap(10L); + Assert.assertEquals( + 0L, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); + + timePartitionManager.updateAfterFlushing(dataRegionId, 10L, 101L, 60L, false); + Assert.assertEquals( + 60L, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); + Mockito.verify(newRegion, Mockito.never()).degradeFlushTimeMap(Mockito.anyLong()); + } + + @Test + public void testReplacedRegionKeepsAccountedIfDegradeFails() { + DataRegionId dataRegionId = new DataRegionId(999); + DataRegion oldRegion = Mockito.mock(DataRegion.class); + Mockito.doThrow(new IllegalStateException("mock degrade failure")) + .when(oldRegion) + .degradeFlushTimeMap(10L); + DataRegion newRegion = Mockito.mock(DataRegion.class); + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(dataRegionId, 10L, false, Long.MAX_VALUE, 0, oldRegion)); + timePartitionManager.updateAfterFlushing(dataRegionId, 10L, 100L, 60L, false); + + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(dataRegionId, 10L, false, Long.MAX_VALUE, 0, newRegion)); + // the old map is still on the heap, so its memory stays accounted + Assert.assertEquals( + 60L, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); + + // over the threshold together with the old map, so the new map is degraded + timePartitionManager.updateAfterFlushing(dataRegionId, 10L, 101L, 60L, false); + Mockito.verify(newRegion, Mockito.times(1)).degradeFlushTimeMap(10L); + Assert.assertEquals( + 60L, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); + } + + @Test + public void testReRegisteredBySameRegionDoesNotDegrade() { + DataRegionId dataRegionId = new DataRegionId(999); + DataRegion dataRegion = Mockito.mock(DataRegion.class); + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(dataRegionId, 10L, false, Long.MAX_VALUE, 0, dataRegion)); + timePartitionManager.updateAfterFlushing(dataRegionId, 10L, 100L, 60L, false); + + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(dataRegionId, 10L, false, Long.MAX_VALUE, 60L, dataRegion)); + Mockito.verify(dataRegion, Mockito.never()).degradeFlushTimeMap(Mockito.anyLong()); + Assert.assertEquals( + 60L, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); + } } From b85116209731a69cd8829c30180f50b14df9e7cd Mon Sep 17 00:00:00 2001 From: JackieTien97 Date: Sat, 5 Dec 2026 10:58:35 +0800 Subject: [PATCH 4/7] Keep replaced TimePartitionInfo reachable until its memory can be released When registerTimePartitionInfo replaces an entry of another live region and fails to degrade its LastFlushTimeMap, the entry was overwritten in the partition map while its memory stayed charged, so it could never be degraded or released again. Keep such entries in TimePartitionManager#replacedTimePartitionInfos, still charged, and release each of them exactly once: - an eviction pass retries degrading them before the registered entries, and releases them once degraded; - they are released when their DataRegion has been garbage collected; - removeTimePartitionInfo releases the replaced entries of the region id. --- .../rescon/memory/TimePartitionManager.java | 97 +++++++++++++++--- .../memory/TimePartitionManagerTest.java | 99 +++++++++++++++++++ 2 files changed, 182 insertions(+), 14 deletions(-) diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java index 0250aee9193b2..2c4b66c7d0220 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java @@ -33,7 +33,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; import java.util.HashMap; +import java.util.Iterator; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.TreeMap; @@ -46,6 +49,14 @@ public class TimePartitionManager { IMemoryBlock timePartitionInfoMemoryBlock; + /** + * Entries replaced in timePartitionInfoMap whose LastFlushTimeMap is still alive because it + * failed to be degraded. Their memory is still accounted, and is released exactly once: after + * they are degraded by a later eviction, after their DataRegion is garbage collected, or when the + * data region id is removed. Guarded by timePartitionInfoMap. + */ + private final List replacedTimePartitionInfos = new ArrayList<>(); + private TimePartitionManager() { timePartitionInfoMap = new HashMap<>(); timePartitionInfoMemoryBlock = @@ -67,10 +78,15 @@ public void registerTimePartitionInfo(TimePartitionInfo timePartitionInfo) { // Account the memory of the registered partition. The memory of the replaced entry is only // released when the LastFlushTimeMap it accounts for is gone or degraded. - long releasedMemSize = - previous != null && releaseReplacedTimePartitionInfo(previous, timePartitionInfo) - ? previous.memSize - : 0; + long releasedMemSize = 0; + if (previous != null) { + if (canReleaseReplacedTimePartitionInfo(previous, timePartitionInfo)) { + releasedMemSize = previous.memSize; + } else { + // keep it charged, and keep it reachable so that it can be degraded or released later + replacedTimePartitionInfos.add(previous); + } + } long memSizeDelta = timePartitionInfo.memSize - releasedMemSize; if (memSizeDelta != 0) { timePartitionInfoMemoryBlock.forceAllocateWithoutLimitation(memSizeDelta); @@ -92,36 +108,53 @@ public void registerTimePartitionInfo(TimePartitionInfo timePartitionInfo) { * * @return whether the memory accounted by {@code previous} can be released */ - private boolean releaseReplacedTimePartitionInfo( + private boolean canReleaseReplacedTimePartitionInfo( TimePartitionInfo previous, TimePartitionInfo current) { DataRegion previousDataRegion = previous.getDataRegion(); - if (previousDataRegion == null || previousDataRegion == current.getDataRegion()) { + if (previousDataRegion != null && previousDataRegion == current.getDataRegion()) { // The same region registers the partition again, so the memory is accounted by the new - // entry; or the previous region has been garbage collected together with its map. + // entry. return true; } // The previous entry belongs to another region with the same id that is still alive, e.g. the // old region kept in StorageEngine while its replacement is recovered for snapshot loading. // Its LastFlushTimeMap is still on the heap and can no longer be found through // timePartitionInfoMap, so degrade it now instead of only dropping its accounting. + return degradeReplacedTimePartitionInfo(previous); + } + + /** + * Degrade the LastFlushTimeMap accounted by an entry that is no longer in timePartitionInfoMap. + * The fallback to StorageEngine is not used, because the region registered there is the one that + * replaced this entry. + * + * @return whether the memory accounted by the entry can be released, i.e. its LastFlushTimeMap is + * degraded or its DataRegion has been garbage collected + */ + private boolean degradeReplacedTimePartitionInfo(TimePartitionInfo replaced) { + DataRegion replacedDataRegion = replaced.getDataRegion(); + if (replacedDataRegion == null) { + // garbage collected together with its LastFlushTimeMap + return true; + } try { - previousDataRegion.degradeFlushTimeMap(previous.partitionId); + replacedDataRegion.degradeFlushTimeMap(replaced.partitionId); } catch (RuntimeException e) { logger.warn( StorageEngineMessages .STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_REPLACED_TIMEPARTITIONINFO_47B56998, - previous.dataRegionId, - previous.partitionId, + replaced.dataRegionId, + replaced.partitionId, e); return false; } logger.info( StorageEngineMessages .STORAGE_LOG_DEGRADE_LASTFLUSHTIMEMAP_OF_OLD_TIMEPARTITIONINFO_MEM_SIZE_BED053EE, - previous.dataRegionId, - previous.partitionId, - previous.memSize, - timePartitionInfoMemoryBlock.getUsedMemoryInBytes() - previous.memSize); + replaced.dataRegionId, + replaced.partitionId, + replaced.memSize, + timePartitionInfoMemoryBlock.getUsedMemoryInBytes() - replaced.memSize); return true; } @@ -142,6 +175,7 @@ public void updateAfterFlushing( memSize - timePartitionInfo.memSize); timePartitionInfo.memSize = memSize; timePartitionInfo.isActive = isActive; + releaseCollectedReplacedTimePartitionInfos(); if (timePartitionInfoMemoryBlock.getUsedMemoryInBytes() > timePartitionInfoMemoryBlock.getTotalMemorySizeInBytes()) { degradeLastFlushTime(); @@ -150,6 +184,18 @@ public void updateAfterFlushing( } } + /** Release the memory of the replaced entries whose DataRegion has been garbage collected. */ + private void releaseCollectedReplacedTimePartitionInfos() { + Iterator replacedIterator = replacedTimePartitionInfos.iterator(); + while (replacedIterator.hasNext()) { + TimePartitionInfo replaced = replacedIterator.next(); + if (replaced.getDataRegion() == null) { + timePartitionInfoMemoryBlock.release(replaced.memSize); + replacedIterator.remove(); + } + } + } + public void updateAfterOpeningTsFileProcessor(DataRegionId dataRegionId, long timePartitionId) { synchronized (timePartitionInfoMap) { TimePartitionInfo timePartitionInfo = @@ -165,6 +211,19 @@ public void updateAfterOpeningTsFileProcessor(DataRegionId dataRegionId, long ti private void degradeLastFlushTime() { TreeSet treeSet = new TreeSet<>(TimePartitionInfo::comparePriority); synchronized (timePartitionInfoMap) { + // Replaced entries first: they belong to regions that have been replaced, and are retried + // here because their previous degradation failed. + Iterator replacedIterator = replacedTimePartitionInfos.iterator(); + while (replacedIterator.hasNext() + && timePartitionInfoMemoryBlock.getUsedMemoryInBytes() + > timePartitionInfoMemoryBlock.getTotalMemorySizeInBytes()) { + TimePartitionInfo replaced = replacedIterator.next(); + if (degradeReplacedTimePartitionInfo(replaced)) { + timePartitionInfoMemoryBlock.release(replaced.memSize); + replacedIterator.remove(); + } + } + for (Map.Entry> entry : timePartitionInfoMap.entrySet()) { treeSet.addAll(entry.getValue().values()); @@ -226,6 +285,15 @@ public void removeTimePartitionInfo(DataRegionId dataRegionId) { } } } + // The data region id is removed, so the replaced entries of it are no longer accounted. + Iterator replacedIterator = replacedTimePartitionInfos.iterator(); + while (replacedIterator.hasNext()) { + TimePartitionInfo replaced = replacedIterator.next(); + if (replaced.dataRegionId.equals(dataRegionId)) { + timePartitionInfoMemoryBlock.release(replaced.memSize); + replacedIterator.remove(); + } + } } } @@ -245,6 +313,7 @@ public TimePartitionInfo getTimePartitionInfo(DataRegionId dataRegionId, long ti public void clear() { synchronized (timePartitionInfoMap) { timePartitionInfoMap.clear(); + replacedTimePartitionInfos.clear(); timePartitionInfoMemoryBlock.setUsedMemoryInBytes(0L); } } diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java index 16fe7d789d8b0..64aadf6b22a69 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java @@ -31,11 +31,14 @@ import org.apache.tsfile.exception.write.WriteProcessException; import org.junit.After; import org.junit.Assert; +import org.junit.Assume; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import java.io.IOException; +import java.lang.ref.WeakReference; +import java.util.concurrent.atomic.AtomicReference; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -274,6 +277,102 @@ public void testReplacedRegionKeepsAccountedIfDegradeFails() { Mockito.verify(newRegion, Mockito.times(1)).degradeFlushTimeMap(10L); Assert.assertEquals( 60L, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); + + // removing the region releases the charge of the replaced entry exactly once + timePartitionManager.removeTimePartitionInfo(dataRegionId); + Assert.assertEquals( + 0L, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); + + // an unrelated partition is not degraded because of the stale charge + DataRegionId unrelatedRegionId = new DataRegionId(1000); + DataRegion unrelatedRegion = Mockito.mock(DataRegion.class); + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(unrelatedRegionId, 0L, false, Long.MAX_VALUE, 0, unrelatedRegion)); + timePartitionManager.updateAfterFlushing(unrelatedRegionId, 0L, 102L, 60L, false); + Mockito.verify(unrelatedRegion, Mockito.never()).degradeFlushTimeMap(Mockito.anyLong()); + Assert.assertEquals( + 60L, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); + timePartitionManager.removeTimePartitionInfo(unrelatedRegionId); + Assert.assertEquals( + 0L, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); + } + + @Test + public void testReplacedRegionIsDegradedByLaterEviction() { + DataRegionId dataRegionId = new DataRegionId(999); + DataRegion oldRegion = Mockito.mock(DataRegion.class); + // fails only for the first time + Mockito.doThrow(new IllegalStateException("mock degrade failure")) + .doNothing() + .when(oldRegion) + .degradeFlushTimeMap(10L); + DataRegion newRegion = Mockito.mock(DataRegion.class); + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(dataRegionId, 10L, false, Long.MAX_VALUE, 0, oldRegion)); + timePartitionManager.updateAfterFlushing(dataRegionId, 10L, 100L, 60L, false); + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(dataRegionId, 10L, false, Long.MAX_VALUE, 0, newRegion)); + Assert.assertEquals( + 60L, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); + + // the next eviction retries the replaced entry before the registered entries + DataRegionId unrelatedRegionId = new DataRegionId(1000); + DataRegion unrelatedRegion = Mockito.mock(DataRegion.class); + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(unrelatedRegionId, 0L, false, Long.MAX_VALUE, 0, unrelatedRegion)); + timePartitionManager.updateAfterFlushing(unrelatedRegionId, 0L, 101L, 60L, false); + + Mockito.verify(oldRegion, Mockito.times(2)).degradeFlushTimeMap(10L); + Mockito.verify(unrelatedRegion, Mockito.never()).degradeFlushTimeMap(Mockito.anyLong()); + Mockito.verify(newRegion, Mockito.never()).degradeFlushTimeMap(Mockito.anyLong()); + Assert.assertEquals( + 60L, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); + + // released exactly once: removing the region only releases the registered entries + timePartitionManager.removeTimePartitionInfo(dataRegionId); + timePartitionManager.removeTimePartitionInfo(unrelatedRegionId); + Assert.assertEquals( + 0L, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); + } + + @Test + public void testReplacedRegionIsReleasedAfterCollected() throws Exception { + DataRegionId dataRegionId = new DataRegionId(999); + DataRegion newRegion = Mockito.mock(DataRegion.class); + AtomicReference> oldRegionRefHolder = new AtomicReference<>(); + // create and use the old region in another thread, so that no thread local of Mockito keeps + // a strong reference to it + Thread thread = + new Thread( + () -> { + DataRegion oldRegion = Mockito.mock(DataRegion.class); + Mockito.doThrow(new IllegalStateException("mock degrade failure")) + .when(oldRegion) + .degradeFlushTimeMap(10L); + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(dataRegionId, 10L, false, Long.MAX_VALUE, 0, oldRegion)); + timePartitionManager.updateAfterFlushing(dataRegionId, 10L, 100L, 60L, false); + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(dataRegionId, 10L, false, Long.MAX_VALUE, 0, newRegion)); + oldRegionRefHolder.set(new WeakReference<>(oldRegion)); + }); + thread.start(); + thread.join(); + WeakReference oldRegionRef = oldRegionRefHolder.get(); + Assert.assertEquals( + 60L, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); + + for (int i = 0; i < 100 && oldRegionRef.get() != null; i++) { + System.gc(); + Thread.sleep(50); + } + Assume.assumeTrue("the old region is not garbage collected", oldRegionRef.get() == null); + + // the charge of the collected region is released without degrading other partitions + timePartitionManager.updateAfterFlushing(dataRegionId, 10L, 101L, 30L, false); + Mockito.verify(newRegion, Mockito.never()).degradeFlushTimeMap(Mockito.anyLong()); + Assert.assertEquals( + 30L, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); } @Test From 994ad6bb5d9a0aa77fbbc278b23596fb13103212 Mon Sep 17 00:00:00 2001 From: JackieTien97 Date: Sat, 5 Dec 2026 18:13:03 +0800 Subject: [PATCH 5/7] Tie-break TimePartitionInfo priority by DataRegion to keep all eviction candidates comparePriority() only compared the active state, the partition id and the last flush time, so the TreeSet used by degradeLastFlushTime() treated entries of different DataRegions with the same partition id and flush time (common when regions are recovered in parallel within one millisecond) as one element and silently dropped the others, leaving the memory above the limit. Add the data region id as the final tie-breaker. Also split degradeLastFlushTime() into smaller methods without changing its behavior, and shorten two new i18n constant names to keep lines within 100 chars. --- .../iotdb/db/i18n/StorageEngineMessages.java | 4 +- .../iotdb/db/i18n/StorageEngineMessages.java | 4 +- .../rescon/memory/TimePartitionInfo.java | 9 +- .../rescon/memory/TimePartitionManager.java | 120 ++++++++++-------- .../memory/TimePartitionManagerTest.java | 37 ++++++ 5 files changed, 117 insertions(+), 57 deletions(-) diff --git a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java index 2935159cee378..33e0b11c4bdc2 100644 --- a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java +++ b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java @@ -1533,10 +1533,10 @@ private StorageEngineMessages() {} public static final String STORAGE_LOG_DEGRADE_LASTFLUSHTIMEMAP_OF_OLD_TIMEPARTITIONINFO_MEM_SIZE_BED053EE = "[{}]degrade LastFlushTimeMap of old TimePartitionInfo-{}, mem size is {}, remaining mem " + "cost is {}"; - public static final String STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_TIMEPARTITIONINFO_KEEP_IT_REGISTERED_2B2924D0 = + public static final String STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_2B2924D0 = "[{}]Failed to degrade LastFlushTimeMap of TimePartitionInfo-{}, keep it registered so " + "that its memory is still accounted"; - public static final String STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_REPLACED_TIMEPARTITIONINFO_47B56998 = + public static final String STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_REPLACED_47B56998 = "[{}]Failed to degrade LastFlushTimeMap of replaced TimePartitionInfo-{}, keep its memory " + "accounted"; public static final String STORAGE_LOG_LIMIT_OF_ARRAY_DEQUE_SIZE_UPDATED_05DBA95E = diff --git a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java index 8127ae67cebea..3b500fe1788cc 100644 --- a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java +++ b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java @@ -1452,9 +1452,9 @@ private StorageEngineMessages() {} "SG ({}) 已释放内存 (delta:{}),但系统仍处于拒绝状态 (totalSgMemCost:{})。"; public static final String STORAGE_LOG_DEGRADE_LASTFLUSHTIMEMAP_OF_OLD_TIMEPARTITIONINFO_MEM_SIZE_BED053EE = "[{}] 降级旧 TimePartitionInfo-{} 的 LastFlushTimeMap,内存大小为 {},剩余内存开销为 {}"; - public static final String STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_TIMEPARTITIONINFO_KEEP_IT_REGISTERED_2B2924D0 = + public static final String STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_2B2924D0 = "[{}] 降级 TimePartitionInfo-{} 的 LastFlushTimeMap 失败,保留该分区的注册信息以继续统计其内存"; - public static final String STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_REPLACED_TIMEPARTITIONINFO_47B56998 = + public static final String STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_REPLACED_47B56998 = "[{}] 降级被替换的 TimePartitionInfo-{} 的 LastFlushTimeMap 失败,继续统计其内存"; public static final String STORAGE_LOG_LIMIT_OF_ARRAY_DEQUE_SIZE_UPDATED_05DBA95E = "{} array deque 大小限制已更新:{} -> {}"; diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionInfo.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionInfo.java index 1fc6f19fb6fd6..381aed514aa6a 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionInfo.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionInfo.java @@ -87,6 +87,13 @@ public int comparePriority(TimePartitionInfo timePartitionInfo) { if (cmp != 0) { return cmp; } - return Long.compare(lastSystemFlushTime, timePartitionInfo.lastSystemFlushTime); + cmp = Long.compare(lastSystemFlushTime, timePartitionInfo.lastSystemFlushTime); + if (cmp != 0) { + return cmp; + } + // Entries of different DataRegions may share the partition id and the flush time (e.g. when + // several regions are recovered in parallel). Tie-break by the region so that sorted sets used + // for eviction keep all of them. + return Integer.compare(dataRegionId.getId(), timePartitionInfo.dataRegionId.getId()); } } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java index 2c4b66c7d0220..73edc78e7e97b 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java @@ -141,8 +141,7 @@ private boolean degradeReplacedTimePartitionInfo(TimePartitionInfo replaced) { replacedDataRegion.degradeFlushTimeMap(replaced.partitionId); } catch (RuntimeException e) { logger.warn( - StorageEngineMessages - .STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_REPLACED_TIMEPARTITIONINFO_47B56998, + StorageEngineMessages.STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_REPLACED_47B56998, replaced.dataRegionId, replaced.partitionId, e); @@ -209,71 +208,88 @@ public void updateAfterOpeningTsFileProcessor(DataRegionId dataRegionId, long ti } private void degradeLastFlushTime() { - TreeSet treeSet = new TreeSet<>(TimePartitionInfo::comparePriority); synchronized (timePartitionInfoMap) { // Replaced entries first: they belong to regions that have been replaced, and are retried // here because their previous degradation failed. - Iterator replacedIterator = replacedTimePartitionInfos.iterator(); - while (replacedIterator.hasNext() - && timePartitionInfoMemoryBlock.getUsedMemoryInBytes() - > timePartitionInfoMemoryBlock.getTotalMemorySizeInBytes()) { - TimePartitionInfo replaced = replacedIterator.next(); - if (degradeReplacedTimePartitionInfo(replaced)) { - timePartitionInfoMemoryBlock.release(replaced.memSize); - replacedIterator.remove(); - } - } + degradeReplacedTimePartitionInfos(); - for (Map.Entry> entry : - timePartitionInfoMap.entrySet()) { - treeSet.addAll(entry.getValue().values()); + TreeSet treeSet = new TreeSet<>(TimePartitionInfo::comparePriority); + for (Map timePartitionInfoMapForRegion : + timePartitionInfoMap.values()) { + treeSet.addAll(timePartitionInfoMapForRegion.values()); } - while (timePartitionInfoMemoryBlock.getUsedMemoryInBytes() - > timePartitionInfoMemoryBlock.getTotalMemorySizeInBytes()) { + while (isMemoryExceeded()) { TimePartitionInfo timePartitionInfo = treeSet.pollFirst(); if (timePartitionInfo == null) { return; } - // Prefer the DataRegion that registered this entry. StorageEngine may not contain the - // region yet (it is still being constructed and recovered), or may still contain an old - // region with the same id (e.g. while a region is being replaced by snapshot loading). - DataRegion dataRegion = timePartitionInfo.getDataRegion(); - if (dataRegion == null) { - dataRegion = StorageEngine.getInstance().getDataRegion(timePartitionInfo.dataRegionId); - } - if (dataRegion != null) { - try { - dataRegion.degradeFlushTimeMap(timePartitionInfo.partitionId); - } catch (RuntimeException e) { - // The LastFlushTimeMap is not degraded, so its memory is still occupied. Keep the entry - // and its memory accounting, it can be degraded again later. - logger.warn( - StorageEngineMessages - .STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_TIMEPARTITIONINFO_KEEP_IT_REGISTERED_2B2924D0, - timePartitionInfo.dataRegionId, - timePartitionInfo.partitionId, - e); - continue; - } - } - timePartitionInfoMemoryBlock.release(timePartitionInfo.memSize); - if (dataRegion != null) { - logger.info( - StorageEngineMessages - .STORAGE_LOG_DEGRADE_LASTFLUSHTIMEMAP_OF_OLD_TIMEPARTITIONINFO_MEM_SIZE_BED053EE, - timePartitionInfo.dataRegionId, - timePartitionInfo.partitionId, - timePartitionInfo.memSize, - timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); + if (degradeTimePartitionInfo(timePartitionInfo)) { + timePartitionInfoMap + .get(timePartitionInfo.dataRegionId) + .remove(timePartitionInfo.partitionId); } - timePartitionInfoMap - .get(timePartitionInfo.dataRegionId) - .remove(timePartitionInfo.partitionId); } } } + private boolean isMemoryExceeded() { + return timePartitionInfoMemoryBlock.getUsedMemoryInBytes() + > timePartitionInfoMemoryBlock.getTotalMemorySizeInBytes(); + } + + private void degradeReplacedTimePartitionInfos() { + Iterator replacedIterator = replacedTimePartitionInfos.iterator(); + while (replacedIterator.hasNext() && isMemoryExceeded()) { + TimePartitionInfo replaced = replacedIterator.next(); + if (degradeReplacedTimePartitionInfo(replaced)) { + timePartitionInfoMemoryBlock.release(replaced.memSize); + replacedIterator.remove(); + } + } + } + + /** + * Degrade the LastFlushTimeMap accounted by a registered entry, and release its memory if + * succeeded. + * + * @return whether the entry should be removed from timePartitionInfoMap + */ + private boolean degradeTimePartitionInfo(TimePartitionInfo timePartitionInfo) { + // Prefer the DataRegion that registered this entry. StorageEngine may not contain the + // region yet (it is still being constructed and recovered), or may still contain an old + // region with the same id (e.g. while a region is being replaced by snapshot loading). + DataRegion dataRegion = timePartitionInfo.getDataRegion(); + if (dataRegion == null) { + dataRegion = StorageEngine.getInstance().getDataRegion(timePartitionInfo.dataRegionId); + } + if (dataRegion != null) { + try { + dataRegion.degradeFlushTimeMap(timePartitionInfo.partitionId); + } catch (RuntimeException e) { + // The LastFlushTimeMap is not degraded, so its memory is still occupied. Keep the entry + // and its memory accounting, it can be degraded again later. + logger.warn( + StorageEngineMessages.STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_2B2924D0, + timePartitionInfo.dataRegionId, + timePartitionInfo.partitionId, + e); + return false; + } + } + timePartitionInfoMemoryBlock.release(timePartitionInfo.memSize); + if (dataRegion != null) { + logger.info( + StorageEngineMessages + .STORAGE_LOG_DEGRADE_LASTFLUSHTIMEMAP_OF_OLD_TIMEPARTITIONINFO_MEM_SIZE_BED053EE, + timePartitionInfo.dataRegionId, + timePartitionInfo.partitionId, + timePartitionInfo.memSize, + timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); + } + return true; + } + public void removeTimePartitionInfo(DataRegionId dataRegionId) { synchronized (timePartitionInfoMap) { Map timePartitionInfoMapForRegion = diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java index 64aadf6b22a69..4912ae7679baf 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java @@ -389,4 +389,41 @@ public void testReRegisteredBySameRegionDoesNotDegrade() { Assert.assertEquals( 60L, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); } + + @Test + public void testEqualPriorityAcrossDataRegions() { + DataRegionId firstId = new DataRegionId(1001); + DataRegionId secondId = new DataRegionId(1002); + DataRegion firstRegion = Mockito.mock(DataRegion.class); + DataRegion secondRegion = Mockito.mock(DataRegion.class); + + timePartitionManager.setTimePartitionInfoMemoryThreshold(1_000L); + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(firstId, 10L, false, Long.MAX_VALUE, 0L, firstRegion)); + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(secondId, 10L, false, Long.MAX_VALUE, 0L, secondRegion)); + // same partition id and the same flush time, e.g. recovered in parallel in one millisecond + timePartitionManager.updateAfterFlushing(firstId, 10L, 100L, 60L, false); + timePartitionManager.updateAfterFlushing(secondId, 10L, 100L, 60L, false); + + timePartitionManager.setTimePartitionInfoMemoryThreshold(50L); + timePartitionManager.updateAfterFlushing(firstId, 10L, 100L, 60L, false); + + Mockito.verify(firstRegion, Mockito.times(1)).degradeFlushTimeMap(10L); + Mockito.verify(secondRegion, Mockito.times(1)).degradeFlushTimeMap(10L); + Assert.assertEquals( + 0L, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); + Assert.assertNull(timePartitionManager.getTimePartitionInfo(firstId, 10L)); + Assert.assertNull(timePartitionManager.getTimePartitionInfo(secondId, 10L)); + } + + @Test + public void testComparePriorityTieBreaksByDataRegion() { + TimePartitionInfo first = new TimePartitionInfo(new DataRegionId(1), 10L, false, 100L, 0); + TimePartitionInfo second = new TimePartitionInfo(new DataRegionId(2), 10L, false, 100L, 0); + Assert.assertTrue(first.comparePriority(second) < 0); + Assert.assertTrue(second.comparePriority(first) > 0); + Assert.assertEquals( + 0, first.comparePriority(new TimePartitionInfo(new DataRegionId(1), 10L, false, 100L, 0))); + } } From 6be390dc327491699c61971891722de8ebe1ff65 Mon Sep 17 00:00:00 2001 From: JackieTien97 Date: Sun, 6 Dec 2026 10:33:59 +0800 Subject: [PATCH 6/7] Fix remaining recovery accounting, async-recovery races, GC owner sweep, and no-op degrade logs - HashLastFlushTimeMap#updatePartitionFlushedTime: degrade an existing DeviceLastFlushTime (e.g. from sync-recovered seq files in the same partition) to PartitionLastFlushTime, merge maxFlushedTime, and set memCostForEachPartition to Long.BYTES so concurrent writes arriving before async recovery finishes see the FileTimeIndexCache max and async recovery cannot grow DeviceLastFlushTime unaccounted. - PartitionLastFlushTime: make partitionLastFlushTime volatile for lock-free reads from insert threads during async recovery. - DataRegion#upgradeAndUpdateDeviceLastFlushTime: when the partition is already a PartitionLastFlushTime, merge resource.getTimeIndex().getMaxEndTime() in O(1) without allocating a per-device map; if a DeviceLastFlushTime still exists, take writeLock and call TimePartitionManager#updateAfterFlushing. - DataRegion#recover & recoverUnsealedTsFileCallBack: remove the redundant latestPartitionId re-registration (eliminating the stale-memSize TOCTOU race and un-eviction of degraded partitions), register/account WAL-recovered unsealed TsFiles, and pass 0 for newly created partitions in registerTimePartitionInfo. - TimePartitionInfo & TimePartitionManager: distinguish a cleared WeakReference from the @TestOnly null-owner constructor (never falling back to StorageEngine when dataRegionRef != null), and sweep collected entries from timePartitionInfoMap before evicting live partitions. - ILastFlushTimeMap / HashLastFlushTimeMap / DataRegion: return boolean from degradeLastFlushTime / degradeFlushTimeMap (fast-pathing absent or already degraded partitions) so TimePartitionManager skips redundant map writes and INFO log storms for already-degraded FileTimeIndexCache partitions. Also guard empty inputs in updateMultiDeviceFlushedTime, upgradeAndUpdateMultiDeviceFlushedTime, and releaseCollectedReplacedTimePartitionInfos. --- .../storageengine/dataregion/DataRegion.java | 134 ++++++----- .../dataregion/HashLastFlushTimeMap.java | 46 +++- .../dataregion/ILastFlushTimeMap.java | 10 +- .../dataregion/PartitionLastFlushTime.java | 4 +- .../rescon/memory/TimePartitionInfo.java | 8 + .../rescon/memory/TimePartitionManager.java | 83 ++++--- .../dataregion/LastFlushTimeMapTest.java | 209 +++++++++++++++++- .../memory/TimePartitionManagerTest.java | 82 ++++++- 8 files changed, 463 insertions(+), 113 deletions(-) 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 3d51649187c8c..bb35774efd87c 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 @@ -780,17 +780,6 @@ private void recover() throws DataRegionException { WALRecoverManager.getInstance().getAllDataRegionScannedLatch().countDown(); // recover sealed TsFiles if (!partitionTmpSeqTsFiles.isEmpty() || !partitionTmpUnseqTsFiles.isEmpty()) { - long latestPartitionId = Long.MIN_VALUE; - if (!partitionTmpSeqTsFiles.isEmpty()) { - latestPartitionId = - ((TreeMap>) partitionTmpSeqTsFiles).lastKey(); - } - if (!partitionTmpUnseqTsFiles.isEmpty()) { - latestPartitionId = - Math.max( - latestPartitionId, - ((TreeMap>) partitionTmpUnseqTsFiles).lastKey()); - } File logFile = SystemFileFactory.INSTANCE.getFile(dataRegionSysDir, "FileTimeIndexCache_0"); Map fileTimeIndexMap = new HashMap<>(); if (logFile.exists()) { @@ -827,17 +816,6 @@ private void recover() throws DataRegionException { asyncTsFileResourceRecoverTaskList.add(asyncRecoverTask); } } - if (config.isEnableSeparateData()) { - TimePartitionManager.getInstance() - .registerTimePartitionInfo( - new TimePartitionInfo( - new DataRegionId(Integer.parseInt(dataRegionIdString)), - latestPartitionId, - false, - Long.MAX_VALUE, - lastFlushTimeMap.getMemSize(latestPartitionId), - this)); - } } // wait until all unsealed TsFiles have been recovered for (WALRecoverListener recoverListener : recoverListeners) { @@ -911,10 +889,40 @@ protected void updateDeviceLastFlushTime(TsFileResource resource) { } } + private void updateAndRegisterDeviceLastFlushTime(TsFileResource resource) { + if (!config.isEnableSeparateData()) { + return; + } + long timePartitionId = resource.getTimePartition(); + if (!lastFlushTimeMap.checkAndCreateFlushedTimePartition(timePartitionId, true)) { + TimePartitionManager.getInstance() + .registerTimePartitionInfo( + new TimePartitionInfo(dataRegionId, timePartitionId, false, Long.MAX_VALUE, 0, this)); + } + updateDeviceLastFlushTime(resource); + TimePartitionManager.getInstance() + .updateAfterFlushing( + dataRegionId, + timePartitionId, + System.currentTimeMillis(), + lastFlushTimeMap.getMemSize(timePartitionId), + false); + } + protected void upgradeAndUpdateDeviceLastFlushTime( long timePartitionId, List resources) { + if (!config.isEnableSeparateData()) { + return; + } + if (lastFlushTimeMap.isPartitionLastFlushTime(timePartitionId)) { + updatePartitionMaxEndTime(timePartitionId, resources); + return; + } Map endTimeMap = new HashMap<>(); for (TsFileResource resource : resources) { + if (resource.isDeleted()) { + continue; + } for (IDeviceID deviceId : resource.getDevices()) { // checked above //noinspection OptionalGetWithoutIsPresent @@ -922,8 +930,33 @@ protected void upgradeAndUpdateDeviceLastFlushTime( endTimeMap.merge(deviceId, endTime, Math::max); } } - if (config.isEnableSeparateData()) { + if (endTimeMap.isEmpty()) { + return; + } + writeLock("upgradeAndUpdateDeviceLastFlushTime"); + try { lastFlushTimeMap.upgradeAndUpdateMultiDeviceFlushedTime(timePartitionId, endTimeMap); + TimePartitionManager.getInstance() + .updateAfterFlushing( + dataRegionId, + timePartitionId, + System.currentTimeMillis(), + lastFlushTimeMap.getMemSize(timePartitionId), + workSequenceTsFileProcessors.get(timePartitionId) != null); + } finally { + writeUnlock(); + } + } + + private void updatePartitionMaxEndTime(long timePartitionId, List resources) { + long maxEndTime = Long.MIN_VALUE; + for (TsFileResource resource : resources) { + if (!resource.isDeleted() && resource.getTimeIndex() != null) { + maxEndTime = Math.max(maxEndTime, resource.getTimeIndex().getMaxEndTime()); + } + } + if (maxEndTime != Long.MIN_VALUE) { + lastFlushTimeMap.updatePartitionFlushedTime(timePartitionId, maxEndTime); } } @@ -1083,16 +1116,16 @@ private void recoverUnsealedTsFileCallBack(UnsealedTsFileRecoverPerformer recove tsFileResource.remove(); return; } - updateDeviceLastFlushTime(tsFileResource); + updateAndRegisterDeviceLastFlushTime(tsFileResource); tsFileResourceManager.registerSealedTsFileResource(tsFileResource); FileMetrics.getInstance().addTsFile(tsFileResource); } else { // the last file is not closed, continue writing to it RestorableTsFileIOWriter writer = recoverPerformer.getWriter(); long timePartitionId = tsFileResource.getTimePartition(); + initFlushTimeMap(timePartitionId); TimePartitionManager.getInstance() - .updateAfterOpeningTsFileProcessor( - new DataRegionId(Integer.parseInt(dataRegionIdString)), timePartitionId); + .updateAfterOpeningTsFileProcessor(dataRegionId, timePartitionId); TsFileProcessor tsFileProcessor = new TsFileProcessor( dataRegionIdString, @@ -1200,20 +1233,14 @@ private Callable asyncRecoverFilesInPartition( if (!lastFlushTimeMap.checkAndCreateFlushedTimePartition(partitionId, false)) { TimePartitionManager.getInstance() .registerTimePartitionInfo( - new TimePartitionInfo( - new DataRegionId(Integer.parseInt(dataRegionIdString)), - partitionId, - false, - Long.MAX_VALUE, - lastFlushTimeMap.getMemSize(partitionId), - this)); + new TimePartitionInfo(dataRegionId, partitionId, false, Long.MAX_VALUE, 0, this)); } for (TsFileResource tsFileResource : resourceList) { updatePartitionLastFlushTime(tsFileResource); } TimePartitionManager.getInstance() .updateAfterFlushing( - new DataRegionId(Integer.parseInt(dataRegionIdString)), + dataRegionId, partitionId, System.currentTimeMillis(), lastFlushTimeMap.getMemSize(partitionId), @@ -1261,13 +1288,7 @@ private void syncRecoverFilesInPartition( if (!lastFlushTimeMap.checkAndCreateFlushedTimePartition(partitionId, true)) { TimePartitionManager.getInstance() .registerTimePartitionInfo( - new TimePartitionInfo( - new DataRegionId(Integer.parseInt(dataRegionIdString)), - partitionId, - false, - Long.MAX_VALUE, - lastFlushTimeMap.getMemSize(partitionId), - this)); + new TimePartitionInfo(dataRegionId, partitionId, false, Long.MAX_VALUE, 0, this)); } for (TsFileResource tsFileResource : resourceList) { if (!tsFileResource.isDeleted()) { @@ -1276,7 +1297,7 @@ private void syncRecoverFilesInPartition( } TimePartitionManager.getInstance() .updateAfterFlushing( - new DataRegionId(Integer.parseInt(dataRegionIdString)), + dataRegionId, partitionId, System.currentTimeMillis(), lastFlushTimeMap.getMemSize(partitionId), @@ -4796,30 +4817,7 @@ public void loadNewTsFile( FileMetrics.getInstance().addTsFile(newTsFileResource); - if (config.isEnableSeparateData()) { - final DataRegionId dataRegionId = - new DataRegionId(Integer.parseInt(this.dataRegionIdString)); - final long timePartitionId = newTsFileResource.getTimePartition(); - if (!lastFlushTimeMap.checkAndCreateFlushedTimePartition(timePartitionId, true)) { - TimePartitionManager.getInstance() - .registerTimePartitionInfo( - new TimePartitionInfo( - dataRegionId, - timePartitionId, - false, - Long.MAX_VALUE, - lastFlushTimeMap.getMemSize(timePartitionId), - this)); - } - updateDeviceLastFlushTime(newTsFileResource); - TimePartitionManager.getInstance() - .updateAfterFlushing( - dataRegionId, - timePartitionId, - System.currentTimeMillis(), - lastFlushTimeMap.getMemSize(timePartitionId), - false); - } + updateAndRegisterDeviceLastFlushTime(newTsFileResource); onTsFileLoaded(newTsFileResource, isFromConsensus, lastValues, lastReader); if (isGeneratedByPipe) { @@ -5849,8 +5847,8 @@ private void releaseDirectBufferMemory() { } /* Be careful, the thread that calls this method may not hold the write lock!!*/ - public void degradeFlushTimeMap(long timePartitionId) { - lastFlushTimeMap.degradeLastFlushTime(timePartitionId); + public boolean degradeFlushTimeMap(long timePartitionId) { + return lastFlushTimeMap.degradeLastFlushTime(timePartitionId); } public ResidentSeriesCounter getResidentSeriesCounter() { diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/HashLastFlushTimeMap.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/HashLastFlushTimeMap.java index 68769cd8a92b5..804a7d68dd798 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/HashLastFlushTimeMap.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/HashLastFlushTimeMap.java @@ -58,6 +58,9 @@ public class HashLastFlushTimeMap implements ILastFlushTimeMap { @Override public void updateMultiDeviceFlushedTime( long timePartitionId, Map flushedTimeMap) { + if (flushedTimeMap.isEmpty()) { + return; + } partitionLatestFlushedTime.compute( timePartitionId, (id, lastFlushTime) -> { @@ -82,6 +85,9 @@ public void updateMultiDeviceFlushedTime( @Override public void upgradeAndUpdateMultiDeviceFlushedTime( long timePartitionId, Map flushedTimeMap) { + if (flushedTimeMap.isEmpty()) { + return; + } partitionLatestFlushedTime.compute( timePartitionId, (id, lastFlushTime) -> { @@ -116,16 +122,18 @@ public void updatePartitionFlushedTime(long timePartitionId, long maxFlushedTime partitionLatestFlushedTime.compute( timePartitionId, (id, lastFlushTime) -> { - ILastFlushTime flushTimeMapForPartition = - lastFlushTime == null ? new PartitionLastFlushTime(maxFlushedTime) : lastFlushTime; - if (flushTimeMapForPartition instanceof PartitionLastFlushTime) { - flushTimeMapForPartition.updateLastFlushTime(null, maxFlushedTime); - memCostForEachPartition.putIfAbsent(id, (long) Long.BYTES); - } - // Otherwise the DeviceLastFlushTime was recovered by wal recovery or sync recovery, and - // the device flush times of these resources are merged into it by - // upgradeAndUpdateMultiDeviceFlushedTime after the async recovery. - return flushTimeMapForPartition; + // If the partition already holds a DeviceLastFlushTime (e.g. from sync-recovered seq + // files in the same partition), degrade it to PartitionLastFlushTime and merge + // maxFlushedTime. Per-device end times of async-recovered files are unknown until their + // .resource files are read, so keeping a DeviceLastFlushTime without maxFlushedTime + // would misroute concurrent writes arriving before async recovery finishes. + ILastFlushTime partitionLastFlushTime = + lastFlushTime == null + ? new PartitionLastFlushTime(maxFlushedTime) + : lastFlushTime.degradeLastFlushTime(); + partitionLastFlushTime.updateLastFlushTime(null, maxFlushedTime); + memCostForEachPartition.put(id, (long) Long.BYTES); + return partitionLastFlushTime; }); } @@ -168,6 +176,11 @@ public long getFlushedTime(long timePartitionId, IDeviceID deviceId) { return partitionLatestFlushedTime.get(timePartitionId).getLastFlushTime(deviceId); } + @Override + public boolean isPartitionLastFlushTime(long timePartitionId) { + return partitionLatestFlushedTime.get(timePartitionId) instanceof PartitionLastFlushTime; + } + @Override public void clearFlushedTime() { partitionLatestFlushedTime.clear(); @@ -175,14 +188,25 @@ public void clearFlushedTime() { } @Override - public void degradeLastFlushTime(long partitionId) { + public boolean degradeLastFlushTime(long partitionId) { + // Fast path: absent or already degraded, avoid taking the bin lock and rewriting + // memCostForEachPartition under TimePartitionManager's global monitor. + if (!(partitionLatestFlushedTime.get(partitionId) instanceof DeviceLastFlushTime)) { + return false; + } + boolean[] degraded = {false}; partitionLatestFlushedTime.computeIfPresent( partitionId, (id, lastFlushTime) -> { + if (!(lastFlushTime instanceof DeviceLastFlushTime)) { + return lastFlushTime; + } ILastFlushTime degradedLastFlushTime = lastFlushTime.degradeLastFlushTime(); memCostForEachPartition.put(id, (long) Long.BYTES); + degraded[0] = true; return degradedLastFlushTime; }); + return degraded[0]; } @Override diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/ILastFlushTimeMap.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/ILastFlushTimeMap.java index b5947afbe89ee..31ec14c9d9256 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/ILastFlushTimeMap.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/ILastFlushTimeMap.java @@ -47,6 +47,8 @@ void upgradeAndUpdateMultiDeviceFlushedTime( // region read long getFlushedTime(long timePartitionId, IDeviceID deviceId); + boolean isPartitionLastFlushTime(long timePartitionId); + // endregion // region clear @@ -54,7 +56,13 @@ void upgradeAndUpdateMultiDeviceFlushedTime( // endregion - void degradeLastFlushTime(long partitionId); + /** + * Degrade the partition's flush time from device-level to partition-level. + * + * @return {@code true} if a device-level flush time map was actually degraded to partition-level, + * {@code false} if the partition was absent or already partition-level. + */ + boolean degradeLastFlushTime(long partitionId); long getMemSize(long partitionId); } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/PartitionLastFlushTime.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/PartitionLastFlushTime.java index a5976861441e7..45809abb910d8 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/PartitionLastFlushTime.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/PartitionLastFlushTime.java @@ -23,7 +23,9 @@ public class PartitionLastFlushTime implements ILastFlushTime { - private long partitionLastFlushTime; + // Updated inside HashLastFlushTimeMap's per-partition compute(), but read lock-free via + // getLastFlushTime() from insert threads while async recovery may merge a larger max end time. + private volatile long partitionLastFlushTime; public PartitionLastFlushTime(long initPartitionLastFlushTime) { this.partitionLastFlushTime = initPartitionLastFlushTime; diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionInfo.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionInfo.java index 381aed514aa6a..4b42cb10c5370 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionInfo.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionInfo.java @@ -78,6 +78,14 @@ DataRegion getDataRegion() { return dataRegionRef == null ? null : dataRegionRef.get(); } + boolean hasDataRegionRef() { + return dataRegionRef != null; + } + + boolean isDataRegionCollected() { + return dataRegionRef != null && dataRegionRef.get() == null; + } + public int comparePriority(TimePartitionInfo timePartitionInfo) { int cmp = Boolean.compare(isActive, timePartitionInfo.isActive); if (cmp != 0) { diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java index 73edc78e7e97b..650b27c97f17a 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManager.java @@ -111,9 +111,10 @@ public void registerTimePartitionInfo(TimePartitionInfo timePartitionInfo) { private boolean canReleaseReplacedTimePartitionInfo( TimePartitionInfo previous, TimePartitionInfo current) { DataRegion previousDataRegion = previous.getDataRegion(); - if (previousDataRegion != null && previousDataRegion == current.getDataRegion()) { - // The same region registers the partition again, so the memory is accounted by the new - // entry. + if (previousDataRegion == null || previousDataRegion == current.getDataRegion()) { + // Either the same region registers the partition again (its memory is accounted by the new + // entry), or the previous entry has no live region reference (garbage collected together + // with its map, or registered via the @TestOnly constructor without a region). return true; } // The previous entry belongs to another region with the same id that is still alive, e.g. the @@ -137,8 +138,9 @@ private boolean degradeReplacedTimePartitionInfo(TimePartitionInfo replaced) { // garbage collected together with its LastFlushTimeMap return true; } + boolean degraded; try { - replacedDataRegion.degradeFlushTimeMap(replaced.partitionId); + degraded = replacedDataRegion.degradeFlushTimeMap(replaced.partitionId); } catch (RuntimeException e) { logger.warn( StorageEngineMessages.STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_REPLACED_47B56998, @@ -147,13 +149,15 @@ private boolean degradeReplacedTimePartitionInfo(TimePartitionInfo replaced) { e); return false; } - logger.info( - StorageEngineMessages - .STORAGE_LOG_DEGRADE_LASTFLUSHTIMEMAP_OF_OLD_TIMEPARTITIONINFO_MEM_SIZE_BED053EE, - replaced.dataRegionId, - replaced.partitionId, - replaced.memSize, - timePartitionInfoMemoryBlock.getUsedMemoryInBytes() - replaced.memSize); + if (degraded) { + logger.info( + StorageEngineMessages + .STORAGE_LOG_DEGRADE_LASTFLUSHTIMEMAP_OF_OLD_TIMEPARTITIONINFO_MEM_SIZE_BED053EE, + replaced.dataRegionId, + replaced.partitionId, + replaced.memSize, + timePartitionInfoMemoryBlock.getUsedMemoryInBytes() - replaced.memSize); + } return true; } @@ -175,8 +179,7 @@ public void updateAfterFlushing( timePartitionInfo.memSize = memSize; timePartitionInfo.isActive = isActive; releaseCollectedReplacedTimePartitionInfos(); - if (timePartitionInfoMemoryBlock.getUsedMemoryInBytes() - > timePartitionInfoMemoryBlock.getTotalMemorySizeInBytes()) { + if (isMemoryExceeded()) { degradeLastFlushTime(); } } @@ -185,6 +188,9 @@ public void updateAfterFlushing( /** Release the memory of the replaced entries whose DataRegion has been garbage collected. */ private void releaseCollectedReplacedTimePartitionInfos() { + if (replacedTimePartitionInfos.isEmpty()) { + return; + } Iterator replacedIterator = replacedTimePartitionInfos.iterator(); while (replacedIterator.hasNext()) { TimePartitionInfo replaced = replacedIterator.next(); @@ -212,12 +218,12 @@ private void degradeLastFlushTime() { // Replaced entries first: they belong to regions that have been replaced, and are retried // here because their previous degradation failed. degradeReplacedTimePartitionInfos(); + if (!isMemoryExceeded()) { + return; + } TreeSet treeSet = new TreeSet<>(TimePartitionInfo::comparePriority); - for (Map timePartitionInfoMapForRegion : - timePartitionInfoMap.values()) { - treeSet.addAll(timePartitionInfoMapForRegion.values()); - } + collectLiveTimePartitionInfosAndReleaseCollected(treeSet); while (isMemoryExceeded()) { TimePartitionInfo timePartitionInfo = treeSet.pollFirst(); @@ -233,6 +239,29 @@ private void degradeLastFlushTime() { } } + private void collectLiveTimePartitionInfosAndReleaseCollected( + TreeSet livePartitionInfos) { + Iterator>> regionIterator = + timePartitionInfoMap.entrySet().iterator(); + while (regionIterator.hasNext()) { + Map timePartitionInfoMapForRegion = regionIterator.next().getValue(); + Iterator partitionIterator = + timePartitionInfoMapForRegion.values().iterator(); + while (partitionIterator.hasNext()) { + TimePartitionInfo info = partitionIterator.next(); + if (info.isDataRegionCollected()) { + timePartitionInfoMemoryBlock.release(info.memSize); + partitionIterator.remove(); + } else { + livePartitionInfos.add(info); + } + } + if (timePartitionInfoMapForRegion.isEmpty()) { + regionIterator.remove(); + } + } + } + private boolean isMemoryExceeded() { return timePartitionInfoMemoryBlock.getUsedMemoryInBytes() > timePartitionInfoMemoryBlock.getTotalMemorySizeInBytes(); @@ -256,16 +285,18 @@ private void degradeReplacedTimePartitionInfos() { * @return whether the entry should be removed from timePartitionInfoMap */ private boolean degradeTimePartitionInfo(TimePartitionInfo timePartitionInfo) { - // Prefer the DataRegion that registered this entry. StorageEngine may not contain the - // region yet (it is still being constructed and recovered), or may still contain an old - // region with the same id (e.g. while a region is being replaced by snapshot loading). - DataRegion dataRegion = timePartitionInfo.getDataRegion(); - if (dataRegion == null) { - dataRegion = StorageEngine.getInstance().getDataRegion(timePartitionInfo.dataRegionId); - } + // When the entry holds a WeakReference to its owning DataRegion, never fall back to + // StorageEngine if the reference has been cleared: that owner was garbage collected together + // with its map, and StorageEngine may now hold a different replacement region with the same + // DataRegionId. + DataRegion dataRegion = + timePartitionInfo.hasDataRegionRef() + ? timePartitionInfo.getDataRegion() + : StorageEngine.getInstance().getDataRegion(timePartitionInfo.dataRegionId); + boolean degraded = false; if (dataRegion != null) { try { - dataRegion.degradeFlushTimeMap(timePartitionInfo.partitionId); + degraded = dataRegion.degradeFlushTimeMap(timePartitionInfo.partitionId); } catch (RuntimeException e) { // The LastFlushTimeMap is not degraded, so its memory is still occupied. Keep the entry // and its memory accounting, it can be degraded again later. @@ -278,7 +309,7 @@ private boolean degradeTimePartitionInfo(TimePartitionInfo timePartitionInfo) { } } timePartitionInfoMemoryBlock.release(timePartitionInfo.memSize); - if (dataRegion != null) { + if (degraded) { logger.info( StorageEngineMessages .STORAGE_LOG_DEGRADE_LASTFLUSHTIMEMAP_OF_OLD_TIMEPARTITIONINFO_MEM_SIZE_BED053EE, diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/LastFlushTimeMapTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/LastFlushTimeMapTest.java index bada0ceda2f94..c9ae3fc089e35 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/LastFlushTimeMapTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/LastFlushTimeMapTest.java @@ -19,6 +19,7 @@ package org.apache.iotdb.db.storageengine.dataregion; +import org.apache.iotdb.commons.concurrent.ExceptionalCountDownLatch; import org.apache.iotdb.commons.conf.IoTDBConstant; import org.apache.iotdb.commons.consensus.DataRegionId; import org.apache.iotdb.commons.exception.IllegalPathException; @@ -30,6 +31,9 @@ import org.apache.iotdb.db.storageengine.dataregion.compaction.schedule.CompactionTaskManager; import org.apache.iotdb.db.storageengine.dataregion.tsfile.TsFileResource; import org.apache.iotdb.db.storageengine.dataregion.tsfile.timeindex.ArrayDeviceTimeIndex; +import org.apache.iotdb.db.storageengine.dataregion.tsfile.timeindex.FileTimeIndex; +import org.apache.iotdb.db.storageengine.dataregion.wal.recover.WALRecoverManager; +import org.apache.iotdb.db.storageengine.rescon.memory.TimePartitionInfo; import org.apache.iotdb.db.storageengine.rescon.memory.TimePartitionManager; import org.apache.iotdb.db.utils.EnvironmentUtils; import org.apache.iotdb.db.utils.constant.TestConstant; @@ -428,10 +432,19 @@ public void testAsyncRecoveryAfterDegradeKeepsPartitionMaximum() throws Exceptio TimePartitionManager.getInstance().clear(); TimePartitionManager.getInstance().setTimePartitionInfoMemoryThreshold(memSizeOfOneDevice()); - // recovering partition 1 degrades partition 0 before its async recovery task runs + // recovering partition 0's async unseq file degrades partition 0's DeviceLastFlushTime and + // merges the FileTimeIndexCache max (200) immediately, before async recovery runs dataRegion = new DataRegionTest.DummyDataRegion(systemDir, storageGroup); Assert.assertEquals(Long.BYTES, dataRegion.getLastFlushTimeMap().getMemSize(0)); - Assert.assertEquals(100L, dataRegion.getLastFlushTimeMap().getFlushedTime(0, device)); + Assert.assertEquals(200L, dataRegion.getLastFlushTimeMap().getFlushedTime(0, device)); + + // Even before async recovery completes, 150 must be routed to an unsequence writer + TSRecord earlyRecord = new TSRecord("root.vehicle.d0", 150); + earlyRecord.addTuple(DataPoint.getDataPoint(TSDataType.INT32, measurementId, "150")); + dataRegion.insert(DataRegionTest.buildInsertRowNodeByTSRecord(earlyRecord)); + Assert.assertTrue(dataRegion.getWorkSequenceTsFileProcessors().isEmpty()); + Assert.assertEquals(1, dataRegion.getWorkUnsequenceTsFileProcessors().size()); + dataRegion.syncCloseAllWorkingTsFileProcessors(); List> asyncRecoverTasks = new ArrayList<>(dataRegion.getAsyncTsFileResourceRecoverTaskList()); @@ -444,9 +457,9 @@ public void testAsyncRecoveryAfterDegradeKeepsPartitionMaximum() throws Exceptio Assert.assertEquals(200L, dataRegion.getLastFlushTimeMap().getFlushedTime(0, device)); Assert.assertEquals(Long.BYTES, dataRegion.getLastFlushTimeMap().getMemSize(0)); - // 150 is not larger than the max end time of partition 0, so it must be unsequence data - TSRecord record = new TSRecord("root.vehicle.d0", 150); - record.addTuple(DataPoint.getDataPoint(TSDataType.INT32, measurementId, "150")); + // After async recovery completes, 160 is still not larger than 200 -> unsequence writer + TSRecord record = new TSRecord("root.vehicle.d0", 160); + record.addTuple(DataPoint.getDataPoint(TSDataType.INT32, measurementId, "160")); dataRegion.insert(DataRegionTest.buildInsertRowNodeByTSRecord(record)); Assert.assertTrue(dataRegion.getWorkSequenceTsFileProcessors().isEmpty()); Assert.assertEquals(1, dataRegion.getWorkUnsequenceTsFileProcessors().size()); @@ -456,6 +469,185 @@ public void testAsyncRecoveryAfterDegradeKeepsPartitionMaximum() throws Exceptio } } + @Test + public void testUpdatePartitionFlushedTimeDegradesExistingDeviceMapWithoutEviction() + throws Exception { + IDeviceID device0 = IDeviceID.Factory.DEFAULT_FACTORY.create("root.vehicle.d0"); + insertAndClose(100); + + // Build an unsequence file with 10 devices ending at 200 in the same partition 0 + for (int i = 0; i < 10; i++) { + TSRecord record = new TSRecord("root.vehicle.d" + i, 200); + record.addTuple(DataPoint.getDataPoint(TSDataType.INT32, measurementId, "200")); + dataRegion.insert(DataRegionTest.buildInsertRowNodeByTSRecord(record)); + } + TsFileResource unseqResource = + dataRegion.getWorkSequenceTsFileProcessors().iterator().next().getTsFileResource(); + dataRegion.syncCloseAllWorkingTsFileProcessors(); + moveToUnsequenceDir(unseqResource); + // Only the unseq file is in FileTimeIndexCache (sync seq + async unseq in partition 0) + writeFileTimeIndexCache(unseqResource); + + long prevThreshold = getTimePartitionInfoMemoryThreshold(); + try { + TimePartitionManager.getInstance().clear(); + // Large budget so TimePartitionManager does not evict partition 0 during recover() + TimePartitionManager.getInstance() + .setTimePartitionInfoMemoryThreshold(100 * memSizeOfOneDevice()); + + dataRegion = new DataRegionTest.DummyDataRegion(systemDir, storageGroup); + // Partition 0's DeviceLastFlushTime was degraded to PartitionLastFlushTime(200) + Assert.assertEquals(Long.BYTES, dataRegion.getLastFlushTimeMap().getMemSize(0)); + Assert.assertEquals(200L, dataRegion.getLastFlushTimeMap().getFlushedTime(0, device0)); + Assert.assertEquals(Long.BYTES, getTimePartitionInfoUsedMemory()); + TimePartitionInfo info = + TimePartitionManager.getInstance().getTimePartitionInfo(new DataRegionId(0), 0L); + Assert.assertNotNull(info); + + // Run async recovery: partition 0 stays degraded at Long.BYTES without unaccounted growth + List> asyncRecoverTasks = + new ArrayList<>(dataRegion.getAsyncTsFileResourceRecoverTaskList()); + Assert.assertFalse(asyncRecoverTasks.isEmpty()); + for (Callable task : asyncRecoverTasks) { + task.call(); + } + dataRegion.clearAsyncTsFileResourceRecoverTaskList(); + + Assert.assertEquals(Long.BYTES, dataRegion.getLastFlushTimeMap().getMemSize(0)); + Assert.assertEquals(200L, dataRegion.getLastFlushTimeMap().getFlushedTime(0, device0)); + Assert.assertEquals(Long.BYTES, getTimePartitionInfoUsedMemory()); + } finally { + TimePartitionManager.getInstance().setTimePartitionInfoMemoryThreshold(prevThreshold); + TimePartitionManager.getInstance().clear(); + } + } + + @Test + public void testUpgradeOnPartitionLastFlushTimeUsesTimeIndexWithoutDeviceScan() { + IDeviceID device = IDeviceID.Factory.DEFAULT_FACTORY.create("root.vehicle.d0"); + TsFileResource resource = Mockito.mock(TsFileResource.class); + Mockito.when(resource.getTimeIndex()).thenReturn(new FileTimeIndex(10L, 250L)); + + dataRegion.getLastFlushTimeMap().clearFlushedTime(); + dataRegion.getLastFlushTimeMap().updatePartitionFlushedTime(0, 100L); + Assert.assertTrue(dataRegion.getLastFlushTimeMap().isPartitionLastFlushTime(0)); + + dataRegion.upgradeAndUpdateDeviceLastFlushTime(0, Collections.singletonList(resource)); + + Assert.assertEquals(250L, dataRegion.getLastFlushTimeMap().getFlushedTime(0, device)); + Assert.assertEquals(Long.BYTES, dataRegion.getLastFlushTimeMap().getMemSize(0)); + Mockito.verify(resource, Mockito.never()).getDevices(); + } + + @Test + public void testDegradeLastFlushTimeReturnsBoolean() { + IDeviceID device = IDeviceID.Factory.DEFAULT_FACTORY.create("root.vehicle.d0"); + HashLastFlushTimeMap map = new HashLastFlushTimeMap(); + + // Absent partition -> false + Assert.assertFalse(map.degradeLastFlushTime(99)); + + // Empty update is a no-op + map.updateMultiDeviceFlushedTime(2, Collections.emptyMap()); + Assert.assertEquals(0, map.getMemSize(2)); + Assert.assertFalse(map.degradeLastFlushTime(2)); + + // DeviceLastFlushTime -> true once, false thereafter + map.updateMultiDeviceFlushedTime(0, Collections.singletonMap(device, 100L)); + Assert.assertFalse(map.isPartitionLastFlushTime(0)); + Assert.assertTrue(map.degradeLastFlushTime(0)); + Assert.assertTrue(map.isPartitionLastFlushTime(0)); + Assert.assertEquals(Long.BYTES, map.getMemSize(0)); + Assert.assertFalse(map.degradeLastFlushTime(0)); + + // PartitionLastFlushTime from updatePartitionFlushedTime -> false + map.updatePartitionFlushedTime(1, 200L); + Assert.assertTrue(map.isPartitionLastFlushTime(1)); + Assert.assertFalse(map.degradeLastFlushTime(1)); + } + + @Test + public void testUnsealedTsFileRecoveryRegistersAndDegradesPartitions() throws Exception { + IDeviceID device = IDeviceID.Factory.DEFAULT_FACTORY.create("root.vehicle.d0"); + long partitionInterval = TimePartitionUtils.getTimePartitionInterval(); + TsFileResource resource0 = insertAndClose(100); + TsFileResource resource1 = insertAndClose(partitionInterval + 100); + + // Delete both .resource files so both partitions only have unsealed TsFiles + File resourceFile0 = new File(resource0.getTsFilePath() + TsFileResource.RESOURCE_SUFFIX); + File resourceFile1 = new File(resource1.getTsFilePath() + TsFileResource.RESOURCE_SUFFIX); + Assert.assertTrue(resourceFile0.delete()); + Assert.assertTrue(resourceFile1.delete()); + + long prevThreshold = getTimePartitionInfoMemoryThreshold(); + AtomicReference walRecoverFailure = new AtomicReference<>(); + try { + TimePartitionManager.getInstance().clear(); + TimePartitionManager.getInstance().setTimePartitionInfoMemoryThreshold(memSizeOfOneDevice()); + WALRecoverManager.getInstance().clear(); + WALRecoverManager.getInstance() + .setAllDataRegionScannedLatch(new ExceptionalCountDownLatch(1)); + + Thread walRecoverThread = + new Thread( + () -> { + try { + WALRecoverManager.getInstance().recover(); + } catch (Throwable t) { + walRecoverFailure.set(t); + } + }); + walRecoverThread.start(); + dataRegion = new DataRegionTest.DummyDataRegion(systemDir, storageGroup); + walRecoverThread.join(60_000); + Assert.assertNull(walRecoverFailure.get()); + + ILastFlushTimeMap lastFlushTimeMap = dataRegion.getLastFlushTimeMap(); + // Partition 0 (only unsealed TsFile) was registered, accounted, and degraded when partition 1 + // exceeded the 1-device budget + Assert.assertEquals(Long.BYTES, lastFlushTimeMap.getMemSize(0)); + Assert.assertEquals(100L, lastFlushTimeMap.getFlushedTime(0, device)); + Assert.assertEquals(memSizeOfOneDevice(), lastFlushTimeMap.getMemSize(1)); + Assert.assertEquals(partitionInterval + 100, lastFlushTimeMap.getFlushedTime(1, device)); + + DataRegionId dataRegionId = new DataRegionId(0); + Assert.assertNull(TimePartitionManager.getInstance().getTimePartitionInfo(dataRegionId, 0)); + Assert.assertNotNull( + TimePartitionManager.getInstance().getTimePartitionInfo(dataRegionId, 1)); + Assert.assertEquals(memSizeOfOneDevice(), getTimePartitionInfoUsedMemory()); + } finally { + WALRecoverManager.getInstance().clear(); + TimePartitionManager.getInstance().setTimePartitionInfoMemoryThreshold(prevThreshold); + TimePartitionManager.getInstance().clear(); + } + } + + @Test + public void testSingleOversizedPartitionStaysDegradedAfterRecovery() throws Exception { + IDeviceID device = IDeviceID.Factory.DEFAULT_FACTORY.create("root.vehicle.d0"); + insertAndClose(100); + + long prevThreshold = getTimePartitionInfoMemoryThreshold(); + try { + TimePartitionManager.getInstance().clear(); + // Even a single partition exceeds the budget, so it is degraded during recover() + TimePartitionManager.getInstance() + .setTimePartitionInfoMemoryThreshold(memSizeOfOneDevice() - 1); + + dataRegion = new DataRegionTest.DummyDataRegion(systemDir, storageGroup); + + Assert.assertEquals(Long.BYTES, dataRegion.getLastFlushTimeMap().getMemSize(0)); + Assert.assertEquals(100L, dataRegion.getLastFlushTimeMap().getFlushedTime(0, device)); + // Must not be re-registered after degradation + Assert.assertNull( + TimePartitionManager.getInstance().getTimePartitionInfo(new DataRegionId(0), 0)); + Assert.assertEquals(0L, getTimePartitionInfoUsedMemory()); + } finally { + TimePartitionManager.getInstance().setTimePartitionInfoMemoryThreshold(prevThreshold); + TimePartitionManager.getInstance().clear(); + } + } + @Test public void testReplacementRegionDegradesOldRegionMap() throws Exception { for (int i = 0; i < 10; i++) { @@ -506,6 +698,13 @@ private static long getTimePartitionInfoMemoryThreshold() { .getTotalMemorySizeInBytes(); } + private static long getTimePartitionInfoUsedMemory() { + return IoTDBDescriptor.getInstance() + .getMemoryConfig() + .getTimePartitionInfoMemoryManager() + .getUsedMemorySizeInBytes(); + } + private static long memSizeOfOneDevice() { HashLastFlushTimeMap lastFlushTimeMap = new HashLastFlushTimeMap(); lastFlushTimeMap.updateMultiDeviceFlushedTime( diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java index 4912ae7679baf..65e53017c7ef1 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/TimePartitionManagerTest.java @@ -303,7 +303,7 @@ public void testReplacedRegionIsDegradedByLaterEviction() { DataRegion oldRegion = Mockito.mock(DataRegion.class); // fails only for the first time Mockito.doThrow(new IllegalStateException("mock degrade failure")) - .doNothing() + .doReturn(true) .when(oldRegion) .degradeFlushTimeMap(10L); DataRegion newRegion = Mockito.mock(DataRegion.class); @@ -426,4 +426,84 @@ public void testComparePriorityTieBreaksByDataRegion() { Assert.assertEquals( 0, first.comparePriority(new TimePartitionInfo(new DataRegionId(1), 10L, false, 100L, 0))); } + + @Test + public void testCollectedOwnerInMapReleasedWithoutEvictingLiveOrFallingBackToStorageEngine() + throws Exception { + DataRegionId oldRegionId = new DataRegionId(1001); + DataRegionId liveRegionId = new DataRegionId(1002); + DataRegion replacementInStorageEngine = Mockito.mock(DataRegion.class); + Mockito.when(replacementInStorageEngine.getDataRegionIdString()).thenReturn("1001"); + DataRegion liveRegion = Mockito.mock(DataRegion.class); + + timePartitionManager.setTimePartitionInfoMemoryThreshold(350L); + StorageEngine.getInstance().setDataRegion(oldRegionId, replacementInStorageEngine); + try { + AtomicReference> oldOwnerRefHolder = new AtomicReference<>(); + Thread thread = + new Thread( + () -> { + DataRegion oldOwner = Mockito.mock(DataRegion.class); + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(oldRegionId, 100L, false, Long.MAX_VALUE, 0L, oldOwner)); + timePartitionManager.updateAfterFlushing(oldRegionId, 100L, 100L, 240L, false); + oldOwnerRefHolder.set(new WeakReference<>(oldOwner)); + }); + thread.start(); + thread.join(); + WeakReference oldOwnerRef = oldOwnerRefHolder.get(); + + for (int i = 0; i < 100 && oldOwnerRef.get() != null; i++) { + System.gc(); + Thread.sleep(50); + } + Assume.assumeTrue("the old owner region is not garbage collected", oldOwnerRef.get() == null); + + // Partition 50 < 100 would be ordered before the collected entry if it were not swept first, + // and live usage (200) is within the 350-byte budget. + timePartitionManager.registerTimePartitionInfo( + new TimePartitionInfo(liveRegionId, 50L, false, Long.MAX_VALUE, 0L, liveRegion)); + timePartitionManager.updateAfterFlushing(liveRegionId, 50L, 101L, 200L, false); + + Mockito.verify(replacementInStorageEngine, Mockito.never()) + .degradeFlushTimeMap(Mockito.anyLong()); + Mockito.verify(liveRegion, Mockito.never()).degradeFlushTimeMap(Mockito.anyLong()); + Assert.assertNull(timePartitionManager.getTimePartitionInfo(oldRegionId, 100L)); + Assert.assertNotNull(timePartitionManager.getTimePartitionInfo(liveRegionId, 50L)); + Assert.assertEquals( + 200L, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes()); + } finally { + StorageEngine.getInstance().reset(); + } + } + + @Test + public void testLegacyNullDataRegionRefFallsBackToStorageEngine() { + DataRegionId dataRegionId = new DataRegionId(1003); + DataRegion regionInStorageEngine = Mockito.mock(DataRegion.class); + Mockito.when(regionInStorageEngine.getDataRegionIdString()).thenReturn("1003"); + Mockito.when(regionInStorageEngine.degradeFlushTimeMap(10L)).thenReturn(true); + StorageEngine.getInstance().setDataRegion(dataRegionId, regionInStorageEngine); + try { + // Uses the @TestOnly 5-arg constructor (dataRegionRef == null) + TimePartitionInfo info10 = + new TimePartitionInfo(dataRegionId, 10L, false, Long.MAX_VALUE, 0L); + TimePartitionInfo info11 = + new TimePartitionInfo(dataRegionId, 11L, false, Long.MAX_VALUE, 0L); + Assert.assertFalse(info10.hasDataRegionRef()); + Assert.assertFalse(info10.isDataRegionCollected()); + timePartitionManager.registerTimePartitionInfo(info10); + timePartitionManager.registerTimePartitionInfo(info11); + + timePartitionManager.updateAfterFlushing(dataRegionId, 10L, 100L, 60L, false); + timePartitionManager.updateAfterFlushing(dataRegionId, 11L, 101L, 60L, false); + + Mockito.verify(regionInStorageEngine, Mockito.times(1)).degradeFlushTimeMap(10L); + Mockito.verify(regionInStorageEngine, Mockito.never()).degradeFlushTimeMap(11L); + Assert.assertNull(timePartitionManager.getTimePartitionInfo(dataRegionId, 10L)); + Assert.assertNotNull(timePartitionManager.getTimePartitionInfo(dataRegionId, 11L)); + } finally { + StorageEngine.getInstance().reset(); + } + } } From 329d7bc88d22b20030170519cd36c2eb5220b241 Mon Sep 17 00:00:00 2001 From: JackieTien97 Date: Sun, 6 Dec 2026 12:10:57 +0800 Subject: [PATCH 7/7] Fix SonarCloud issues in PartitionLastFlushTime and HashLastFlushTimeMap - PartitionLastFlushTime: rename field partitionLastFlushTime -> lastFlushTime (java:S1700) and update it atomically via AtomicLongFieldUpdater CAS instead of a non-atomic read-modify-write on a volatile long (java:S3078), keeping zero extra heap allocation per partition. - HashLastFlushTimeMap: deduplicate updateMultiDeviceFlushedTime and upgradeAndUpdateMultiDeviceFlushedTime via mergeMultiDeviceFlushedTime and updateDeviceLastFlushTimeAndMemCost helpers to reduce Cognitive Complexity below Sonar's 15 limit (java:S3776). --- .../dataregion/HashLastFlushTimeMap.java | 55 ++++++++----------- .../dataregion/PartitionLastFlushTime.java | 25 ++++++--- 2 files changed, 41 insertions(+), 39 deletions(-) diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/HashLastFlushTimeMap.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/HashLastFlushTimeMap.java index 804a7d68dd798..b8f8ac0364c61 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/HashLastFlushTimeMap.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/HashLastFlushTimeMap.java @@ -58,33 +58,18 @@ public class HashLastFlushTimeMap implements ILastFlushTimeMap { @Override public void updateMultiDeviceFlushedTime( long timePartitionId, Map flushedTimeMap) { - if (flushedTimeMap.isEmpty()) { - return; - } - partitionLatestFlushedTime.compute( - timePartitionId, - (id, lastFlushTime) -> { - ILastFlushTime flushTimeMapForPartition = - lastFlushTime == null ? new DeviceLastFlushTime() : lastFlushTime; - // a degraded partition only keeps one long, so device entries cost no extra memory - boolean isDeviceLevel = flushTimeMapForPartition instanceof DeviceLastFlushTime; - long memIncr = 0L; - for (Map.Entry entry : flushedTimeMap.entrySet()) { - if (isDeviceLevel - && flushTimeMapForPartition.getLastFlushTime(entry.getKey()) == Long.MIN_VALUE) { - memIncr += HASHMAP_NODE_BASIC_SIZE + entry.getKey().ramBytesUsed(); - } - flushTimeMapForPartition.updateLastFlushTime(entry.getKey(), entry.getValue()); - } - memCostForEachPartition.merge(id, memIncr, Long::sum); - return flushTimeMapForPartition; - }); + mergeMultiDeviceFlushedTime(timePartitionId, flushedTimeMap); } // For async recover resource with fileTimeIndexCache @Override public void upgradeAndUpdateMultiDeviceFlushedTime( long timePartitionId, Map flushedTimeMap) { + mergeMultiDeviceFlushedTime(timePartitionId, flushedTimeMap); + } + + private void mergeMultiDeviceFlushedTime( + long timePartitionId, Map flushedTimeMap) { if (flushedTimeMap.isEmpty()) { return; } @@ -96,26 +81,32 @@ public void upgradeAndUpdateMultiDeviceFlushedTime( if (flushTimeMapForPartition instanceof PartitionLastFlushTime) { // The partition only keeps a partition-level flush time, either because it was // recovered from the FileTimeIndexCache, or because TimePartitionManager has degraded - // it to release memory. Keep it degraded, but merge the recovered maximum into it so - // that the partition flush time is never lower than the real max end time. + // it to release memory. Keep it degraded (costing no extra memory), and merge the + // maximum flush time so it is never lower than the real max end time. for (long flushedTime : flushedTimeMap.values()) { flushTimeMapForPartition.updateLastFlushTime(null, flushedTime); } } else { - // go here when DeviceLastFlushTime was recovered by wal recovery - long memIncr = 0; - for (Map.Entry entry : flushedTimeMap.entrySet()) { - if (flushTimeMapForPartition.getLastFlushTime(entry.getKey()) == Long.MIN_VALUE) { - memIncr += HASHMAP_NODE_BASIC_SIZE + entry.getKey().ramBytesUsed(); - } - flushTimeMapForPartition.updateLastFlushTime(entry.getKey(), entry.getValue()); - } - memCostForEachPartition.merge(id, memIncr, Long::sum); + updateDeviceLastFlushTimeAndMemCost(id, flushTimeMapForPartition, flushedTimeMap); } return flushTimeMapForPartition; }); } + private void updateDeviceLastFlushTimeAndMemCost( + long timePartitionId, + ILastFlushTime flushTimeMapForPartition, + Map flushedTimeMap) { + long memIncr = 0L; + for (Map.Entry entry : flushedTimeMap.entrySet()) { + if (flushTimeMapForPartition.getLastFlushTime(entry.getKey()) == Long.MIN_VALUE) { + memIncr += HASHMAP_NODE_BASIC_SIZE + entry.getKey().ramBytesUsed(); + } + flushTimeMapForPartition.updateLastFlushTime(entry.getKey(), entry.getValue()); + } + memCostForEachPartition.merge(timePartitionId, memIncr, Long::sum); + } + // For fileTimeIndexCache recovered before the async resource recover start @Override public void updatePartitionFlushedTime(long timePartitionId, long maxFlushedTime) { diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/PartitionLastFlushTime.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/PartitionLastFlushTime.java index 45809abb910d8..b7ba0249b3e59 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/PartitionLastFlushTime.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/PartitionLastFlushTime.java @@ -21,24 +21,35 @@ import org.apache.tsfile.file.metadata.IDeviceID; +import java.util.concurrent.atomic.AtomicLongFieldUpdater; + public class PartitionLastFlushTime implements ILastFlushTime { - // Updated inside HashLastFlushTimeMap's per-partition compute(), but read lock-free via - // getLastFlushTime() from insert threads while async recovery may merge a larger max end time. - private volatile long partitionLastFlushTime; + private static final AtomicLongFieldUpdater LAST_FLUSH_TIME_UPDATER = + AtomicLongFieldUpdater.newUpdater(PartitionLastFlushTime.class, "lastFlushTime"); + + // Updated atomically via LAST_FLUSH_TIME_UPDATER and read lock-free via getLastFlushTime() from + // insert threads while async recovery may merge a larger max end time. + private volatile long lastFlushTime; - public PartitionLastFlushTime(long initPartitionLastFlushTime) { - this.partitionLastFlushTime = initPartitionLastFlushTime; + public PartitionLastFlushTime(long initLastFlushTime) { + this.lastFlushTime = initLastFlushTime; } @Override public long getLastFlushTime(IDeviceID device) { - return partitionLastFlushTime; + return lastFlushTime; } @Override public void updateLastFlushTime(IDeviceID device, long time) { - partitionLastFlushTime = Math.max(partitionLastFlushTime, time); + long current; + do { + current = lastFlushTime; + if (time <= current) { + return; + } + } while (!LAST_FLUSH_TIME_UPDATER.compareAndSet(this, current, time)); } @Override