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..33e0b11c4bdc 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_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_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..3b500fe1788c 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_2B2924D0 = + "[{}] 降级 TimePartitionInfo-{} 的 LastFlushTimeMap 失败,保留该分区的注册信息以继续统计其内存"; + 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 大小限制已更新:{} -> {}"; 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..bb35774efd87 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; @@ -774,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()) { @@ -821,16 +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))); - } } // wait until all unsealed TsFiles have been recovered for (WALRecoverListener recoverListener : recoverListeners) { @@ -904,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 @@ -915,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); } } @@ -1076,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, @@ -1193,19 +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))); + 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), @@ -1253,12 +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))); + new TimePartitionInfo(dataRegionId, partitionId, false, Long.MAX_VALUE, 0, this)); } for (TsFileResource tsFileResource : resourceList) { if (!tsFileResource.isDeleted()) { @@ -1267,7 +1297,7 @@ private void syncRecoverFilesInPartition( } TimePartitionManager.getInstance() .updateAfterFlushing( - new DataRegionId(Integer.parseInt(dataRegionIdString)), + dataRegionId, partitionId, System.currentTimeMillis(), lastFlushTimeMap.getMemSize(partitionId), @@ -1694,7 +1724,8 @@ private void initFlushTimeMap(long timePartitionId) { timePartitionId, true, Long.MAX_VALUE, - 0)); + 0, + this)); } } @@ -4786,29 +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))); - } - updateDeviceLastFlushTime(newTsFileResource); - TimePartitionManager.getInstance() - .updateAfterFlushing( - dataRegionId, - timePartitionId, - System.currentTimeMillis(), - lastFlushTimeMap.getMemSize(timePartitionId), - false); - } + updateAndRegisterDeviceLastFlushTime(newTsFileResource); onTsFileLoaded(newTsFileResource, isFromConsensus, lastValues, lastReader); if (isGeneratedByPipe) { @@ -5364,7 +5373,8 @@ public void insert(InsertRowsOfOneDeviceNode insertRowsOfOneDeviceNode) timePartitionId, true, Long.MAX_VALUE, - 0)); + 0, + this)); } boolean isSequence = @@ -5489,7 +5499,8 @@ public void insert(InsertRowsNode insertRowsNode) timePartitionIds[i], true, Long.MAX_VALUE, - 0)); + 0, + this)); } areSequence[i] = config.isEnableSeparateData() @@ -5836,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 2452cfd01112..b8f8ac0364c6 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,122 @@ 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); + mergeMultiDeviceFlushedTime(timePartitionId, flushedTimeMap); } // 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()) { + mergeMultiDeviceFlushedTime(timePartitionId, flushedTimeMap); + } + + private void mergeMultiDeviceFlushedTime( + long timePartitionId, Map flushedTimeMap) { + if (flushedTimeMap.isEmpty()) { + return; + } + 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 (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 { + 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(); - 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); + 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) { - 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) -> { + // 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; + }); } @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 @@ -149,6 +167,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(); @@ -156,10 +179,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) -> lastFlushTime.degradeLastFlushTime()); - memCostForEachPartition.put(partitionId, (long) Long.BYTES); + 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 b5947afbe89e..31ec14c9d925 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 a5976861441e..b7ba0249b3e5 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,22 +21,35 @@ import org.apache.tsfile.file.metadata.IDeviceID; +import java.util.concurrent.atomic.AtomicLongFieldUpdater; + public class PartitionLastFlushTime implements ILastFlushTime { - private 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 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..4b42cb10c537 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,53 @@ 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(); + } + + boolean hasDataRegionRef() { + return dataRegionRef != null; + } + + boolean isDataRegionCollected() { + return dataRegionRef != null && dataRegionRef.get() == null; } public int comparePriority(TimePartitionInfo timePartitionInfo) { @@ -55,6 +95,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 7e45bc169331..650b27c97f17 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,64 @@ 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()) { + // 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 + // 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; + } + boolean degraded; + try { + degraded = replacedDataRegion.degradeFlushTimeMap(replaced.partitionId); + } catch (RuntimeException e) { + logger.warn( + StorageEngineMessages.STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_REPLACED_47B56998, + replaced.dataRegionId, + replaced.partitionId, + e); + return false; + } + 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; + } + public void updateAfterFlushing( DataRegionId dataRegionId, long timePartitionId, @@ -92,14 +178,29 @@ public void updateAfterFlushing( memSize - timePartitionInfo.memSize); timePartitionInfo.memSize = memSize; timePartitionInfo.isActive = isActive; - if (timePartitionInfoMemoryBlock.getUsedMemoryInBytes() - > timePartitionInfoMemoryBlock.getTotalMemorySizeInBytes()) { + releaseCollectedReplacedTimePartitionInfos(); + if (isMemoryExceeded()) { degradeLastFlushTime(); } } } } + /** 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(); + if (replaced.getDataRegion() == null) { + timePartitionInfoMemoryBlock.release(replaced.memSize); + replacedIterator.remove(); + } + } + } + public void updateAfterOpeningTsFileProcessor(DataRegionId dataRegionId, long timePartitionId) { synchronized (timePartitionInfoMap) { TimePartitionInfo timePartitionInfo = @@ -113,39 +214,113 @@ public void updateAfterOpeningTsFileProcessor(DataRegionId dataRegionId, long ti } private void degradeLastFlushTime() { - TreeSet treeSet = new TreeSet<>(TimePartitionInfo::comparePriority); synchronized (timePartitionInfoMap) { - for (Map.Entry> entry : - timePartitionInfoMap.entrySet()) { - treeSet.addAll(entry.getValue().values()); + // Replaced entries first: they belong to regions that have been replaced, and are retried + // here because their previous degradation failed. + degradeReplacedTimePartitionInfos(); + if (!isMemoryExceeded()) { + return; } - while (timePartitionInfoMemoryBlock.getUsedMemoryInBytes() - > timePartitionInfoMemoryBlock.getTotalMemorySizeInBytes()) { + TreeSet treeSet = new TreeSet<>(TimePartitionInfo::comparePriority); + collectLiveTimePartitionInfosAndReleaseCollected(treeSet); + + while (isMemoryExceeded()) { TimePartitionInfo timePartitionInfo = treeSet.pollFirst(); if (timePartitionInfo == null) { return; } - 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, - 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 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(); + } + + 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) { + // 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 { + 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. + logger.warn( + StorageEngineMessages.STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_2B2924D0, + timePartitionInfo.dataRegionId, + timePartitionInfo.partitionId, + e); + return false; + } + } + timePartitionInfoMemoryBlock.release(timePartitionInfo.memSize); + if (degraded) { + 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 = @@ -157,6 +332,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 +360,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..c9ae3fc089e3 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,22 @@ 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; +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.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; @@ -42,9 +50,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 +286,470 @@ 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 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(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()); + 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)); + + // 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()); + } finally { + TimePartitionManager.getInstance().setTimePartitionInfoMemoryThreshold(prevThreshold); + TimePartitionManager.getInstance().clear(); + } + } + + @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++) { + 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 getTimePartitionInfoUsedMemory() { + return IoTDBDescriptor.getInstance() + .getMemoryConfig() + .getTimePartitionInfoMemoryManager() + .getUsedMemorySizeInBytes(); + } + + 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..65e53017c7ef 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,378 @@ 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")) + .doReturn(true) + .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()); + } + + @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))); + } + + @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(); + } + } }