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 0015bf4a63f3..2935159cee37 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,12 @@ 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_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 80c70ee05d74..8127ae67cebe 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,10 @@ 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_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/DataRegion.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/DataRegion.java index 8a1daab0d9ee..3d51649187c8 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; @@ -829,7 +835,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 +1205,8 @@ private Callable asyncRecoverFilesInPartition( partitionId, false, Long.MAX_VALUE, - lastFlushTimeMap.getMemSize(partitionId))); + lastFlushTimeMap.getMemSize(partitionId), + this)); } for (TsFileResource tsFileResource : resourceList) { updatePartitionLastFlushTime(tsFileResource); @@ -1258,7 +1266,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 +1703,8 @@ private void initFlushTimeMap(long timePartitionId) { timePartitionId, true, Long.MAX_VALUE, - 0)); + 0, + this)); } } @@ -4798,7 +4808,8 @@ public void loadNewTsFile( timePartitionId, false, Long.MAX_VALUE, - lastFlushTimeMap.getMemSize(timePartitionId))); + lastFlushTimeMap.getMemSize(timePartitionId), + this)); } updateDeviceLastFlushTime(newTsFileResource); TimePartitionManager.getInstance() @@ -5364,7 +5375,8 @@ public void insert(InsertRowsOfOneDeviceNode insertRowsOfOneDeviceNode) timePartitionId, true, Long.MAX_VALUE, - 0)); + 0, + this)); } boolean isSequence = @@ -5489,7 +5501,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/dataregion/HashLastFlushTimeMap.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/HashLastFlushTimeMap.java index 2452cfd01112..68769cd8a92b 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,123 @@ 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; + // fast path without allocation, this method is called for every insertion + if (partitionLatestFlushedTime.containsKey(timePartitionId)) { + return true; } - return true; + // putIfAbsent keeps the creation atomic when several threads meet a new partition together + 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 +177,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 9a25b6501a11..1fc6f19fb6fd 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,10 @@ 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; /** Time partition info records necessary info of a time partition for a data region */ public class TimePartitionInfo { @@ -33,17 +37,45 @@ 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, 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 7e45bc169331..2c4b66c7d022 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 = @@ -62,7 +73,24 @@ 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. The memory of the replaced entry is only + // released when the LastFlushTimeMap it accounts for is gone or degraded. + 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); + } // We need to ensure that the following method is called before // PipeInsertionDataNodeListener.listenToInsertNode. @@ -75,6 +103,61 @@ 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 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. + 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 { + replacedDataRegion.degradeFlushTimeMap(replaced.partitionId); + } catch (RuntimeException e) { + logger.warn( + StorageEngineMessages + .STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_REPLACED_TIMEPARTITIONINFO_47B56998, + replaced.dataRegionId, + replaced.partitionId, + 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); + return true; + } + public void updateAfterFlushing( DataRegionId dataRegionId, long timePartitionId, @@ -92,6 +175,7 @@ public void updateAfterFlushing( memSize - timePartitionInfo.memSize); timePartitionInfo.memSize = memSize; timePartitionInfo.isActive = isActive; + releaseCollectedReplacedTimePartitionInfos(); if (timePartitionInfoMemoryBlock.getUsedMemoryInBytes() > timePartitionInfoMemoryBlock.getTotalMemorySizeInBytes()) { degradeLastFlushTime(); @@ -100,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 = @@ -115,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()); @@ -126,11 +235,30 @@ private void degradeLastFlushTime() { 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); - DataRegion dataRegion = - StorageEngine.getInstance().getDataRegion(timePartitionInfo.dataRegionId); if (dataRegion != null) { - dataRegion.degradeFlushTimeMap(timePartitionInfo.partitionId); logger.info( StorageEngineMessages .STORAGE_LOG_DEGRADE_LASTFLUSHTIMEMAP_OF_OLD_TIMEPARTITIONINFO_MEM_SIZE_BED053EE, @@ -157,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(); + } + } } } @@ -176,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/dataregion/LastFlushTimeMapTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/LastFlushTimeMapTest.java index 7f58ccdd2283..bada0ceda2f9 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,275 @@ 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(); + } + } + + @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); + 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 90eb10c7cfb7..64aadf6b22a6 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,14 +25,20 @@ 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; 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; @@ -126,4 +132,261 @@ 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); + 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()); + } + + @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()); + + // 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 + 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()); + } }