This is an automated email from the ASF dual-hosted git repository.

JackieTien97 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iotdb.git


The following commit(s) were added to refs/heads/master by this push:
     new 3d643e7c296 Fix heap accounting for sealed TsFile resources
3d643e7c296 is described below

commit 3d643e7c29678993303883556cf960a5b7708430
Author: Jackie Tien <[email protected]>
AuthorDate: Fri Nov 27 09:02:41 2026 +0800

    Fix heap accounting for sealed TsFile resources
---
 .../iotdb/db/i18n/StorageEngineMessages.java       |   2 -
 .../iotdb/db/i18n/StorageEngineMessages.java       |   2 -
 .../plan/relational/sql/ast/LoadTsFile.java        |  29 +-
 .../db/storageengine/dataregion/DataRegion.java    |  23 +-
 .../schedule/CompactionScheduleContext.java        |  23 +-
 .../dataregion/modification/ModificationFile.java  |  28 +-
 .../dataregion/tsfile/TsFileResource.java          | 294 +++++++++++-----
 .../tsfile/timeindex/ArrayDeviceTimeIndex.java     |  46 ++-
 .../dataregion/tsfile/timeindex/FileTimeIndex.java |  15 +-
 .../dataregion/tsfile/timeindex/ITimeIndex.java    |  10 -
 .../rescon/memory/TsFileResourceManager.java       | 306 +++++++++++++---
 .../java/org/apache/iotdb/db/utils/MemUtils.java   |  39 ++
 .../relational/sql/AstMemoryEstimatorTest.java     |  28 ++
 .../storageengine/dataregion/DataRegionTest.java   |   4 +
 .../dataregion/tsfile/TsFileResourceTest.java      |  31 ++
 .../rescon/memory/ResourceManagerTest.java         | 391 ++++++++++++++++++++-
 .../org/apache/iotdb/db/utils/MemUtilsTest.java    |  31 ++
 17 files changed, 1068 insertions(+), 234 deletions(-)

diff --git 
a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java
 
b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java
index e40a54c0c12..ef3db3ca28f 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
@@ -675,8 +675,6 @@ public final class StorageEngineMessages {
   public static final String FAILED_TO_CREATE_TSFILE_DIR_AFTER_RETRIES = 
"Failed to create tsfile directory after retries";
   public static final String FAILED_TO_CREATE_DIR_AFTER_RETRIES = "Failed to 
create directory after retries";
   public static final String TSFILE_NAME_FORMAT_INCORRECT = "tsfile file name 
format is incorrect:";
-  public static final String WRONG_TIME_INDEX_TYPE_LOG = "Wrong timeIndex type 
{}";
-  public static final String WRONG_TIME_INDEX_TYPE = "Wrong timeIndex type ";
   public static final String ERROR_RECORD_FILE_TIME_INDEX_CACHE = "Meet error 
when record FileTimeIndexCache: {}";
   public static final String ERROR_RECORD_FILE_TIME_INDEX_CACHE_NO_DETAIL = 
"Meet error when record FileTimeIndexCache";
   public static final String ERROR_COMPACT_FILE_TIME_INDEX_CACHE = "Meet error 
when compact FileTimeIndexCache: {}";
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 532b664dab4..d67165c837a 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
@@ -656,8 +656,6 @@ public final class StorageEngineMessages {
   public static final String FAILED_TO_CREATE_TSFILE_DIR_AFTER_RETRIES = 
"重试后仍无法创建 TsFile 目录";
   public static final String FAILED_TO_CREATE_DIR_AFTER_RETRIES = "重试后仍无法创建目录";
   public static final String TSFILE_NAME_FORMAT_INCORRECT = "TsFile 文件名格式不正确: 
";
-  public static final String WRONG_TIME_INDEX_TYPE_LOG = "错误的 timeIndex 类型 {}";
-  public static final String WRONG_TIME_INDEX_TYPE = "错误的 timeIndex 类型 ";
   public static final String ERROR_RECORD_FILE_TIME_INDEX_CACHE = "记录 
FileTimeIndexCache 时遇到错误: {}";
   public static final String ERROR_RECORD_FILE_TIME_INDEX_CACHE_NO_DETAIL = 
"记录 FileTimeIndexCache 时遇到错误";
   public static final String ERROR_COMPACT_FILE_TIME_INDEX_CACHE = "压缩 
FileTimeIndexCache 时遇到错误: {}";
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/LoadTsFile.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/LoadTsFile.java
index ae448f554f6..d0a3e0e2ec4 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/LoadTsFile.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/LoadTsFile.java
@@ -30,6 +30,7 @@ import org.apache.iotdb.db.i18n.DataNodeQueryMessages;
 import org.apache.iotdb.db.queryengine.plan.statement.crud.LoadTsFileStatement;
 import org.apache.iotdb.db.storageengine.dataregion.tsfile.TsFileResource;
 import org.apache.iotdb.db.storageengine.load.config.LoadTsFileConfigurator;
+import org.apache.iotdb.db.utils.MemUtils;
 
 import org.apache.tsfile.utils.RamUsageEstimator;
 
@@ -49,9 +50,6 @@ public class LoadTsFile extends Statement {
   private static final long INSTANCE_SIZE =
       RamUsageEstimator.shallowSizeOfInstance(LoadTsFile.class);
 
-  private static final long FILE_INSTANCE_SIZE =
-      RamUsageEstimator.shallowSizeOfInstance(File.class);
-
   private String filePath;
 
   private int databaseLevel; // For loading to tree-model only
@@ -389,14 +387,6 @@ public class LoadTsFile extends Statement {
     size += RamUsageEstimator.sizeOf(filePath);
     size += RamUsageEstimator.sizeOf(database);
     size += RamUsageEstimator.sizeOfMap(loadAttributes);
-    if (tsFiles != null) {
-      size += RamUsageEstimator.shallowSizeOf(tsFiles);
-      for (File file : tsFiles) {
-        if (file != null) {
-          size += FILE_INSTANCE_SIZE;
-        }
-      }
-    }
     if (resources != null) {
       size += RamUsageEstimator.shallowSizeOf(resources);
       for (TsFileResource resource : resources) {
@@ -405,8 +395,25 @@ public class LoadTsFile extends Statement {
         }
       }
     }
+    size += estimateUnsharedTsFilesSize();
     size += 
AstMemoryEstimationHelper.getEstimatedSizeOfLongList(writePointCountList);
     size += RamUsageEstimator.shallowSizeOf(isTableModel);
     return size;
   }
+
+  private long estimateUnsharedTsFilesSize() {
+    if (tsFiles == null) {
+      return 0;
+    }
+    long size = RamUsageEstimator.shallowSizeOf(tsFiles);
+    for (int i = 0; i < tsFiles.size(); i++) {
+      File file = tsFiles.get(i);
+      // Analysis appends one resource (possibly null) for each processed 
file, in order.
+      TsFileResource resource = resources != null && i < resources.size() ? 
resources.get(i) : null;
+      if (resource == null || resource.getTsFile() != file) {
+        size += MemUtils.getFileRamBytes(file);
+      }
+    }
+    return size;
+  }
 }
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 f47090a76ff..13ccb870e48 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
@@ -4627,12 +4627,14 @@ public class DataRegion implements IDataRegionForQuery {
               newTsFileResource.getTsFile().getName()));
     }
 
+    final Map<IDeviceID, List<Pair<String, TimeValuePair>>> lastValues =
+        newTsFileResource.getLastValues();
     TsFileLastReader lastReader = null;
     LastCacheLoadStrategy lastCacheLoadStrategy = 
config.getLastCacheLoadStrategy();
     if (!isFromConsensus
         && (lastCacheLoadStrategy == LastCacheLoadStrategy.UPDATE
             || lastCacheLoadStrategy == LastCacheLoadStrategy.UPDATE_NO_BLOB)
-        && newTsFileResource.getLastValues() == null) {
+        && lastValues == null) {
       try {
         // init reader outside of lock to boost performance
         lastReader =
@@ -4716,7 +4718,7 @@ public class DataRegion implements IDataRegionForQuery {
                 false);
       }
 
-      onTsFileLoaded(newTsFileResource, isFromConsensus, lastReader);
+      onTsFileLoaded(newTsFileResource, isFromConsensus, lastValues, 
lastReader);
       if (isGeneratedByPipe) {
         logger.debug(StorageEngineMessages.TSFILE_LOADED_IN_UNSEQ_LIST, 
newFileName);
       } else {
@@ -4745,12 +4747,15 @@ public class DataRegion implements IDataRegionForQuery {
   }
 
   private void onTsFileLoaded(
-      TsFileResource newTsFileResource, boolean isFromConsensus, 
TsFileLastReader lastReader) {
+      TsFileResource newTsFileResource,
+      boolean isFromConsensus,
+      Map<IDeviceID, List<Pair<String, TimeValuePair>>> lastValues,
+      TsFileLastReader lastReader) {
     if (CommonDescriptor.getInstance().getConfig().isLastCacheEnable() && 
!isFromConsensus) {
       switch (config.getLastCacheLoadStrategy()) {
         case UPDATE:
         case UPDATE_NO_BLOB:
-          updateLastCache(newTsFileResource, lastReader);
+          updateLastCache(lastValues, lastReader);
           break;
         case CLEAN_ALL:
           // The inner cache is shared by TreeDeviceSchemaCacheManager and
@@ -4785,11 +4790,10 @@ public class DataRegion implements IDataRegionForQuery {
   }
 
   @SuppressWarnings("java:S112")
-  private void updateLastCache(TsFileResource newTsFileResource, 
TsFileLastReader lastReader) {
+  private void updateLastCache(
+      Map<IDeviceID, List<Pair<String, TimeValuePair>>> lastValues, 
TsFileLastReader lastReader) {
     boolean isTableModel = isTableModelDatabase(databaseName);
 
-    Map<IDeviceID, List<Pair<String, TimeValuePair>>> lastValues =
-        newTsFileResource.getLastValues();
     if (lastValues != null) {
       for (Entry<IDeviceID, List<Pair<String, TimeValuePair>>> entry : 
lastValues.entrySet()) {
         IDeviceID deviceID = entry.getKey();
@@ -4806,7 +4810,6 @@ public class DataRegion implements IDataRegionForQuery {
                   databaseName, deviceID, measurements, timeValuePairs, false, 
null);
         }
       }
-      newTsFileResource.setLastValues(null);
       return;
     }
 
@@ -4874,6 +4877,7 @@ public class DataRegion implements IDataRegionForQuery {
     tsFileResource.setFile(targetFile);
     if (tsFileManager.contains(tsFileResource, false)) {
       logger.warn(StorageEngineMessages.FILE_ALREADY_LOADED_IN_UNSEQ_LIST, 
tsFileResource);
+      tsFileResource.setLastValues(null);
       return false;
     }
 
@@ -4974,6 +4978,9 @@ public class DataRegion implements IDataRegionForQuery {
       }
     }
 
+    // The file is published. Only loadNewTsFile needs the last values from 
this point on.
+    tsFileResource.setLastValues(null);
+
     // Only published mods belong in FileMetrics. Also replace any cached 
source-side handle.
     
tsFileResource.setExclusiveModFile(ModificationFile.getExclusiveMods(tsFileResource));
 
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/compaction/schedule/CompactionScheduleContext.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/compaction/schedule/CompactionScheduleContext.java
index 6f0f7872789..14b72d99083 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/compaction/schedule/CompactionScheduleContext.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/compaction/schedule/CompactionScheduleContext.java
@@ -54,9 +54,12 @@ public class CompactionScheduleContext {
   private int fullyDirtyFileNum = 0;
 
   private int partiallyDirtyFileNum = 0;
+
   // end region
 
-  private final Map<TsFileResource, ArrayDeviceTimeIndex> 
partitionFileDeviceInfoCache;
+  private record CachedDeviceTimeIndex(ArrayDeviceTimeIndex index, long bytes) 
{}
+
+  private final Map<TsFileResource, CachedDeviceTimeIndex> 
partitionFileDeviceInfoCache;
   private final Map<IDeviceID, IDeviceID> deviceIdCache;
   private long cachedDeviceInfoSize = 0;
 
@@ -89,15 +92,21 @@ public class CompactionScheduleContext {
 
   public void addResourceDeviceTimeIndex(
       TsFileResource tsFileResource, ArrayDeviceTimeIndex deviceTimeIndex) {
-    partitionFileDeviceInfoCache.put(tsFileResource, deviceTimeIndex);
-    long deviceTimeIndexSize =
-        
tsFileResource.getDeviceTimeIndexRamSize().orElse(deviceTimeIndex.calculateRamSize());
-    cachedDeviceInfoSize += deviceTimeIndexSize;
-    
CompactionMetrics.getInstance().addSelectionCachedDeviceTimeIndexSize(deviceTimeIndexSize);
+    CachedDeviceTimeIndex previous = 
partitionFileDeviceInfoCache.get(tsFileResource);
+    if (previous != null && previous.index() == deviceTimeIndex) {
+      return;
+    }
+    long bytes = tsFileResource.getDeviceTimeIndexRamSize(deviceTimeIndex);
+    partitionFileDeviceInfoCache.put(
+        tsFileResource, new CachedDeviceTimeIndex(deviceTimeIndex, bytes));
+    long delta = bytes - (previous == null ? 0 : previous.bytes());
+    cachedDeviceInfoSize += delta;
+    
CompactionMetrics.getInstance().addSelectionCachedDeviceTimeIndexSize(delta);
   }
 
   public ArrayDeviceTimeIndex getResourceDeviceInfo(TsFileResource resource) {
-    return partitionFileDeviceInfoCache.get(resource);
+    CachedDeviceTimeIndex cached = partitionFileDeviceInfoCache.get(resource);
+    return cached == null ? null : cached.index();
   }
 
   public void clearTimePartitionDeviceInfoCache() {
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/modification/ModificationFile.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/modification/ModificationFile.java
index 5ef17e9c01b..25fbb4c3b8b 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/modification/ModificationFile.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/modification/ModificationFile.java
@@ -28,7 +28,10 @@ import 
org.apache.iotdb.db.storageengine.dataregion.modification.v1.Deletion;
 import 
org.apache.iotdb.db.storageengine.dataregion.modification.v1.Modification;
 import 
org.apache.iotdb.db.storageengine.dataregion.modification.v1.ModificationFileV1;
 import org.apache.iotdb.db.storageengine.dataregion.tsfile.TsFileResource;
+import org.apache.iotdb.db.utils.MemUtils;
 
+import org.apache.tsfile.utils.Accountable;
+import org.apache.tsfile.utils.RamUsageEstimator;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -51,6 +54,7 @@ import java.util.Map;
 import java.util.Map.Entry;
 import java.util.NoSuchElementException;
 import java.util.Set;
+import java.util.concurrent.locks.AbstractQueuedSynchronizer;
 import java.util.concurrent.locks.ReentrantReadWriteLock;
 import java.util.stream.Collectors;
 
@@ -59,7 +63,23 @@ import static java.nio.file.StandardOpenOption.CREATE;
 import static org.apache.iotdb.db.utils.ModificationUtils.sortAndMerge;
 import static org.apache.tsfile.common.constant.TsFileConstant.TSFILE_SUFFIX;
 
-public class ModificationFile implements AutoCloseable {
+public class ModificationFile implements AutoCloseable, Accountable {
+
+  // The read/write synchronizer adds three references and the first reader's 
hold count to
+  // its AQS state. It also owns a ThreadLocal for read holds.
+  private static final long LOCK_SYNC_SIZE =
+      RamUsageEstimator.alignObjectSize(
+              
RamUsageEstimator.shallowSizeOfInstance(AbstractQueuedSynchronizer.class)
+                  + 3L * RamUsageEstimator.NUM_BYTES_OBJECT_REF
+                  + Integer.BYTES)
+          + RamUsageEstimator.shallowSizeOfInstance(ThreadLocal.class);
+
+  private static final long INSTANCE_SIZE =
+      RamUsageEstimator.shallowSizeOfInstance(ModificationFile.class)
+          + 
RamUsageEstimator.shallowSizeOfInstance(ReentrantReadWriteLock.class)
+          + 
RamUsageEstimator.shallowSizeOfInstance(ReentrantReadWriteLock.ReadLock.class)
+          + 
RamUsageEstimator.shallowSizeOfInstance(ReentrantReadWriteLock.WriteLock.class)
+          + LOCK_SYNC_SIZE;
 
   public static final String FILE_SUFFIX = ".mods2";
   public static final String COMPACTION_FILE_SUFFIX = ".compaction.mods2";
@@ -92,6 +112,12 @@ public class ModificationFile implements AutoCloseable {
     }
   }
 
+  /** Long-lived handle and lock. Open streams and cascaded files have 
separate lifetimes. */
+  @Override
+  public long ramBytesUsed() {
+    return INSTANCE_SIZE + MemUtils.getFileRamBytes(file);
+  }
+
   public void writeLock() {
     this.lock.writeLock().lock();
   }
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/tsfile/TsFileResource.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/tsfile/TsFileResource.java
index 72c7022e5b5..e110c096504 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/tsfile/TsFileResource.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/tsfile/TsFileResource.java
@@ -48,8 +48,9 @@ import 
org.apache.iotdb.db.storageengine.dataregion.tsfile.timeindex.ArrayDevice
 import 
org.apache.iotdb.db.storageengine.dataregion.tsfile.timeindex.FileTimeIndex;
 import 
org.apache.iotdb.db.storageengine.dataregion.tsfile.timeindex.ITimeIndex;
 import 
org.apache.iotdb.db.storageengine.dataregion.tsfile.timeindex.PlainDeviceTimeIndex;
-import 
org.apache.iotdb.db.storageengine.dataregion.tsfile.timeindex.TimeIndexLevel;
 import org.apache.iotdb.db.storageengine.rescon.disk.TierManager;
+import 
org.apache.iotdb.db.storageengine.rescon.memory.TsFileResourceManager.Registration;
+import org.apache.iotdb.db.utils.MemUtils;
 
 import 
org.apache.ratis.thirdparty.com.google.common.util.concurrent.RateLimiter;
 import org.apache.tsfile.file.metadata.IChunkMetadata;
@@ -95,6 +96,7 @@ import java.util.concurrent.Future;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
 
 import static org.apache.iotdb.commons.conf.IoTDBConstant.FILE_NAME_SEPARATOR;
 import static org.apache.tsfile.common.constant.TsFileConstant.TSFILE_SUFFIX;
@@ -104,8 +106,14 @@ public class TsFileResource implements PersistentResource, 
Cloneable {
 
   private static final long INSTANCE_SIZE =
       RamUsageEstimator.shallowSizeOfInstance(TsFileResource.class)
-          + RamUsageEstimator.shallowSizeOfInstance(TsFileRepairStatus.class)
+          + RamUsageEstimator.shallowSizeOfInstance(TsFileLock.class)
+          + 3L * RamUsageEstimator.shallowSizeOfInstance(AtomicReference.class)
+          + RamUsageEstimator.shallowSizeOfInstance(AtomicBoolean.class)
           + TsFileID.SHALLOW_SIZE;
+  private static final long TIER_SIZE =
+      RamUsageEstimator.shallowSizeOfInstance(AtomicInteger.class);
+  private static final AtomicReferenceFieldUpdater<TsFileResource, ITimeIndex> 
TIME_INDEX_UPDATER =
+      AtomicReferenceFieldUpdater.newUpdater(TsFileResource.class, 
ITimeIndex.class, "timeIndex");
 
   private static final Logger LOGGER = 
LoggerFactory.getLogger(TsFileResource.class);
 
@@ -113,8 +121,9 @@ public class TsFileResource implements PersistentResource, 
Cloneable {
 
   private static final IoTDBConfig CONFIG = 
IoTDBDescriptor.getInstance().getConfig();
 
-  /** this tsfile */
-  private File file;
+  /** Publishing a new File also publishes its immutable path. */
+  @SuppressWarnings("java:S3077")
+  private volatile File file;
 
   public static final String RESOURCE_SUFFIX = ".resource";
   public static final String TEMP_SUFFIX = ".temp";
@@ -133,9 +142,13 @@ public class TsFileResource implements PersistentResource, 
Cloneable {
 
   private final AtomicReference<Boolean> isEmpty = new AtomicReference<>();
 
-  private Future<ModificationFile> exclusiveModFileFuture;
-  // this future suggest when the async recovery ends
-  private CompletableFuture<String> sharedModFilePathFuture;
+  // The resource monitor protects the handle/future pair, including when 
cloning the resource.
+  @SuppressWarnings("java:S3077")
+  private volatile Future<ModificationFile> exclusiveModFileFuture;
+
+  // The future signals completion of asynchronous shared-mod recovery.
+  @SuppressWarnings("java:S3077")
+  private volatile CompletableFuture<String> sharedModFilePathFuture;
 
   private ModFileManagement modFileManagement;
 
@@ -174,7 +187,9 @@ public class TsFileResource implements PersistentResource, 
Cloneable {
 
   private TsFileID tsFileID;
 
-  private long deviceTimeIndexRamSize;
+  // The manager monitor protects the mutable fields of the published 
registration.
+  @SuppressWarnings("java:S3077")
+  private volatile Registration memoryRegistration;
 
   private AtomicInteger tierLevel;
 
@@ -213,7 +228,13 @@ public class TsFileResource implements PersistentResource, 
Cloneable {
   private InsertionCompactionCandidateStatus 
insertionCompactionCandidateStatus =
       InsertionCompactionCandidateStatus.NOT_CHECKED;
 
-  private Map<IDeviceID, List<Pair<String, TimeValuePair>>> lastValues;
+  /**
+   * Temporary last values collected within LOAD's cache budget. LOAD keeps 
them locally for its
+   * last-cache update and clears this field before registering the sealed 
file. The resource's
+   * resident memory estimate therefore excludes the map.
+   */
+  @SuppressWarnings("java:S3077")
+  private volatile Map<IDeviceID, List<Pair<String, TimeValuePair>>> 
lastValues;
 
   @TestOnly
   public TsFileResource() {
@@ -348,10 +369,12 @@ public class TsFileResource implements 
PersistentResource, Cloneable {
         // ends with ".mods2" means it is a new version resource file
         if (modFilePath != null && 
modFilePath.endsWith(ModificationFile.FILE_SUFFIX)) {
           sharedModFileOffset = ReadWriteIOUtils.readLong(inputStream);
-          if (sharedModFilePathFuture != null) {
-            sharedModFilePathFuture.complete(modFilePath);
-          } else {
+          // A writer may hold the resource monitor while waiting for 
shared-mod recovery.
+          final CompletableFuture<String> recovery = sharedModFilePathFuture;
+          if (recovery == null) {
             sharedModFilePathFuture = 
CompletableFuture.completedFuture(modFilePath);
+          } else {
+            recovery.complete(modFilePath);
           }
         }
       }
@@ -371,6 +394,8 @@ public class TsFileResource implements PersistentResource, 
Cloneable {
             break;
         }
       }
+    } finally {
+      updateMemoryCostIfRegistered(true);
     }
   }
 
@@ -394,12 +419,16 @@ public class TsFileResource implements 
PersistentResource, Cloneable {
     buffer.putLong(timeIndex.getMaxEndTime());
   }
 
+  // Writers build device times before registering the sealed resource. 
Updating registered files
+  // device by device would remeasure the entire index for each mutation.
   public void updateStartTime(IDeviceID device, long time) {
     timeIndex.updateStartTime(device, time);
+    updateMemoryCostIfRegistered(true);
   }
 
   public void updateEndTime(IDeviceID device, long time) {
     timeIndex.updateEndTime(device, time);
+    updateMemoryCostIfRegistered(true);
   }
 
   public boolean resourceFileExists() {
@@ -524,10 +553,11 @@ public class TsFileResource implements 
PersistentResource, Cloneable {
     if (sharedModFile != null) {
       return sharedModFile;
     }
-    if (sharedModFilePathFuture != null) {
+    final CompletableFuture<String> recovery = sharedModFilePathFuture;
+    if (recovery != null) {
       try {
         if (modFileManagement != null) {
-          sharedModFile = 
modFileManagement.recover(sharedModFilePathFuture.get(), this);
+          sharedModFile = modFileManagement.recover(recovery.get(), this);
         }
       } catch (InterruptedException e) {
         Thread.currentThread().interrupt();
@@ -540,62 +570,75 @@ public class TsFileResource implements 
PersistentResource, Cloneable {
 
   @SuppressWarnings("java:S2886")
   public ModificationFile getExclusiveModFile() {
-    if (exclusiveModFile != null) {
-      return exclusiveModFile;
+    ModificationFile current = exclusiveModFile;
+    if (current != null) {
+      return current;
     }
 
     synchronized (this) {
-      if (exclusiveModFile == null) {
-        if (exclusiveModFileFuture != null) {
-          try {
-            exclusiveModFile = exclusiveModFileFuture.get();
-          } catch (InterruptedException e) {
-            Thread.currentThread().interrupt();
-            LOGGER.warn(StorageEngineMessages.UPGRADING_MOD_FILE_INTERRUPTED, 
e);
-            exclusiveModFile = ModificationFile.getExclusiveMods(this);
-          } catch (ExecutionException e) {
-            LOGGER.warn(StorageEngineMessages.CANNOT_UPGRADE_MOD_FILE, e);
-            exclusiveModFile = ModificationFile.getExclusiveMods(this);
-          }
-        } else {
-          exclusiveModFile = ModificationFile.getExclusiveMods(this);
+      current = exclusiveModFile;
+      if (current != null) {
+        return current;
+      }
+      if (exclusiveModFileFuture != null) {
+        try {
+          current = exclusiveModFileFuture.get();
+        } catch (InterruptedException e) {
+          Thread.currentThread().interrupt();
+          LOGGER.warn(StorageEngineMessages.UPGRADING_MOD_FILE_INTERRUPTED, e);
+          current = ModificationFile.getExclusiveMods(this);
+        } catch (ExecutionException e) {
+          LOGGER.warn(StorageEngineMessages.CANNOT_UPGRADE_MOD_FILE, e);
+          current = ModificationFile.getExclusiveMods(this);
         }
+      } else {
+        current = ModificationFile.getExclusiveMods(this);
       }
+      exclusiveModFile = current;
+      exclusiveModFileFuture = null;
     }
-    return exclusiveModFile;
+    updateMemoryCostIfRegistered();
+    return current;
   }
 
   public ModificationFile getCompactionModFile() {
-    if (compactionModFile == null) {
-      synchronized (this) {
-        if (compactionModFile == null) {
-          compactionModFile = ModificationFile.getCompactionMods(this);
-        }
+    ModificationFile current = compactionModFile;
+    if (current != null) {
+      return current;
+    }
+    synchronized (this) {
+      current = compactionModFile;
+      if (current != null) {
+        return current;
       }
+      current = ModificationFile.getCompactionMods(this);
+      compactionModFile = current;
     }
-    return compactionModFile;
+    updateMemoryCostIfRegistered();
+    return current;
   }
 
   public void removeCompactionModFile() throws IOException {
     if (compactionModFileExists() && !useSharedModFile) {
       getCompactionModFile().remove();
     }
-    compactionModFile = null;
+    setCompactionModFile(null);
   }
 
   @TestOnly
-  public void resetModFile() throws IOException {
+  public synchronized void resetModFile() throws IOException {
     if (exclusiveModFile != null) {
-      synchronized (this) {
-        exclusiveModFile.close();
-        exclusiveModFile = null;
-      }
+      exclusiveModFile.close();
     }
+    exclusiveModFile = null;
+    exclusiveModFileFuture = null;
+    updateMemoryCostIfRegistered();
   }
 
   public void setFile(File file) {
-    this.file = file;
     this.tsFileID = new TsFileID(file.getAbsolutePath());
+    this.file = file;
+    updateMemoryCostIfRegistered();
   }
 
   public File getTsFile() {
@@ -794,6 +837,7 @@ public class TsFileResource implements PersistentResource, 
Cloneable {
     pathToReadOnlyMemChunkMap = null;
     pathToTimeSeriesMetadataMap = null;
     timeIndex.close();
+    updateMemoryCostIfRegistered(true);
   }
 
   public TsFileProcessor getProcessor() {
@@ -885,7 +929,7 @@ public class TsFileResource implements PersistentResource, 
Cloneable {
     // Note that pipe can safely handle the case that the time index does not 
exist
     isEmpty();
     if (getStatus() != TsFileResourceStatus.UNCLOSED) {
-      degradeTimeIndex();
+      replaceDeviceTimeIndexWithFileTimeIndex();
     }
     forceMarkDeleted();
     try {
@@ -1164,36 +1208,87 @@ public class TsFileResource implements 
PersistentResource, Cloneable {
     return timeIndex.isSpanMultiTimePartitions();
   }
 
-  public void setExclusiveModFile(ModificationFile exclusiveModFile) {
-    synchronized (this) {
-      this.exclusiveModFile = exclusiveModFile;
-    }
+  public synchronized void setExclusiveModFile(ModificationFile 
exclusiveModFile) {
+    this.exclusiveModFile = exclusiveModFile;
+    exclusiveModFileFuture = null;
+    updateMemoryCostIfRegistered();
   }
 
-  /**
-   * @return resource map size
-   */
+  /** Estimated resident metadata of the file, excluding shared managers and 
query snapshot data. */
   public long calculateRamSize() {
-    final ProgressIndex progressIndex = maxProgressIndex.get();
-    if (timeIndex.getTimeIndexType() == ITimeIndex.FILE_TIME_INDEX_TYPE) {
-      return INSTANCE_SIZE
-          + timeIndex.calculateRamSize()
-          + (Objects.nonNull(progressIndex) ? progressIndex.ramBytesUsed() : 
0);
+    ITimeIndex index = timeIndex;
+    return calculateMetadataRamSize() + (index == null ? 0 : 
index.calculateRamSize());
+  }
+
+  /** The part that remains resident after a device index is replaced. */
+  public long calculateMetadataRamSize() {
+    final ProgressIndex progress = maxProgressIndex.get();
+    final ModificationFile exclusive = exclusiveModFile;
+    final ModificationFile compaction = compactionModFile;
+    long size =
+        INSTANCE_SIZE
+            + (tierLevel == null ? 0 : TIER_SIZE)
+            + MemUtils.getFileRamBytes(file)
+            + (progress == null || progress == MinimumProgressIndex.INSTANCE
+                ? 0
+                : progress.ramBytesUsed())
+            + (exclusive == null ? 0 : exclusive.ramBytesUsed())
+            + (compaction == null || compaction == exclusive ? 0 : 
compaction.ramBytesUsed());
+    final Future<ModificationFile> upgrade = exclusiveModFileFuture;
+    final CompletableFuture<String> recovery = sharedModFilePathFuture;
+    if (upgrade != null) {
+      size += RamUsageEstimator.shallowSizeOf(upgrade);
+    }
+    if (recovery != null) {
+      size += RamUsageEstimator.shallowSizeOf(recovery);
     }
-    if (deviceTimeIndexRamSize == 0) {
-      deviceTimeIndexRamSize = timeIndex.calculateRamSize();
+    if (originTsFileResource == null) {
+      // LOAD and asynchronous recovery can mark the file sealed without 
calling close().
+      if (pathToChunkMetadataListMap != null) {
+        size += RamUsageEstimator.SHALLOW_SIZE_OF_HASHMAP;
+      }
+      if (pathToReadOnlyMemChunkMap != null) {
+        size += RamUsageEstimator.SHALLOW_SIZE_OF_HASHMAP;
+      }
+      if (pathToTimeSeriesMetadataMap != null) {
+        size += RamUsageEstimator.SHALLOW_SIZE_OF_CONCURRENT_HASHMAP;
+      }
     }
-    return INSTANCE_SIZE
-        + deviceTimeIndexRamSize
-        + (Objects.nonNull(progressIndex) ? progressIndex.ramBytesUsed() : 0);
+    return size;
   }
 
-  // used for compaction
+  /** A rebuilt device index must be measured by its owner when the resident 
index is file-level. */
+  @TestOnly
   public Optional<Long> getDeviceTimeIndexRamSize() {
-    if (!this.isClosed()) {
-      return Optional.empty();
+    ITimeIndex index = timeIndex;
+    return isClosed() && index instanceof ArrayDeviceTimeIndex
+        ? Optional.of(getDeviceTimeIndexRamSize((ArrayDeviceTimeIndex) index))
+        : Optional.empty();
+  }
+
+  /** Uses the registration's measurement only for the exact index the caller 
holds. */
+  public long getDeviceTimeIndexRamSize(ArrayDeviceTimeIndex index) {
+    Registration registration = memoryRegistration;
+    return registration == null ? index.calculateRamSize() : 
registration.getIndexRamSize(index);
+  }
+
+  public Registration getMemoryRegistration() {
+    return memoryRegistration;
+  }
+
+  public void setMemoryRegistration(Registration registration) {
+    memoryRegistration = registration;
+  }
+
+  private void updateMemoryCostIfRegistered() {
+    updateMemoryCostIfRegistered(false);
+  }
+
+  private void updateMemoryCostIfRegistered(boolean indexChanged) {
+    Registration registration = memoryRegistration;
+    if (registration != null) {
+      registration.refresh(indexChanged);
     }
-    return Optional.of(deviceTimeIndexRamSize);
   }
 
   public long getMaxPlanIndex() {
@@ -1273,6 +1368,7 @@ public class TsFileResource implements 
PersistentResource, Cloneable {
 
   public void setTimeIndex(ITimeIndex timeIndex) {
     this.timeIndex = timeIndex;
+    updateMemoryCostIfRegistered(true);
   }
 
   /**
@@ -1376,11 +1472,6 @@ public class TsFileResource implements 
PersistentResource, Cloneable {
     return isRecordedByMetric.compareAndSet(true, false);
   }
 
-  public int compareIndexDegradePriority(TsFileResource tsFileResource) {
-    int cmp = timeIndex.compareDegradePriority(tsFileResource.timeIndex);
-    return cmp == 0 ? 
file.getAbsolutePath().compareTo(tsFileResource.file.getAbsolutePath()) : cmp;
-  }
-
   public byte getTimeIndexType() {
     return timeIndex.getTimeIndexType();
   }
@@ -1389,34 +1480,39 @@ public class TsFileResource implements 
PersistentResource, Cloneable {
   public void setTimeIndexType(byte type) {
     switch (type) {
       case ITimeIndex.ARRAY_DEVICE_TIME_INDEX_TYPE:
-        this.timeIndex = new ArrayDeviceTimeIndex();
+        setTimeIndex(new ArrayDeviceTimeIndex());
         break;
       case ITimeIndex.FILE_TIME_INDEX_TYPE:
-        this.timeIndex = new FileTimeIndex();
+        setTimeIndex(new FileTimeIndex());
         break;
       case ITimeIndex.PLAIN_DEVICE_TIME_INDEX_TYPE:
-        this.timeIndex = new PlainDeviceTimeIndex();
+        setTimeIndex(new PlainDeviceTimeIndex());
         break;
       default:
         throw new UnsupportedOperationException();
     }
   }
 
-  /** the DeviceTimeIndex degrade to FileTimeIndex and release memory */
+  /** Degrades the index and scans the detached index to measure the size 
difference. */
+  @TestOnly
   public long degradeTimeIndex() {
-    TimeIndexLevel timeIndexLevel = TimeIndexLevel.valueOf(getTimeIndexType());
-    // if current timeIndex is FileTimeIndex, no need to degrade
-    if (timeIndexLevel == TimeIndexLevel.FILE_TIME_INDEX) {
-      return 0;
+    ITimeIndex previous = replaceDeviceTimeIndexWithFileTimeIndex();
+    return previous == null ? 0 : previous.calculateRamSize() - 
FileTimeIndex.INSTANCE_SIZE;
+  }
+
+  /** Drops the device index without scanning it. The caller may measure the 
previous index. */
+  public ITimeIndex replaceDeviceTimeIndexWithFileTimeIndex() {
+    ITimeIndex current = timeIndex;
+    while (current != null && current.getTimeIndexType() != 
ITimeIndex.FILE_TIME_INDEX_TYPE) {
+      FileTimeIndex replacement =
+          new FileTimeIndex(current.getMinStartTime(), 
current.getMaxEndTime());
+      if (TIME_INDEX_UPDATER.compareAndSet(this, current, replacement)) {
+        updateMemoryCostIfRegistered(true);
+        return current;
+      }
+      current = timeIndex;
     }
-    // get the minimum startTime
-    long startTime = timeIndex.getMinStartTime();
-    // get the maximum endTime
-    long endTime = timeIndex.getMaxEndTime();
-    // replace the DeviceTimeIndex with FileTimeIndex
-    timeIndex = new FileTimeIndex(startTime, endTime);
-    // deviceTimeIndexRamSize has already been calculated before
-    return deviceTimeIndexRamSize - timeIndex.calculateRamSize();
+    return null;
   }
 
   public void deleteRemovedDeviceAndUpdateEndTime(Map<IDeviceID, Long> 
lastTimeForEachDevice) {
@@ -1431,12 +1527,14 @@ public class TsFileResource implements 
PersistentResource, Cloneable {
               });
     }
     timeIndex = newTimeIndex;
+    updateMemoryCostIfRegistered(true);
   }
 
   public void updateEndTime(Map<IDeviceID, Long> lastTimeForEachDevice) {
     for (Map.Entry<IDeviceID, Long> entry : lastTimeForEachDevice.entrySet()) {
       timeIndex.updateEndTime(entry.getKey(), entry.getValue());
     }
+    updateMemoryCostIfRegistered(true);
   }
 
   /**
@@ -1455,6 +1553,7 @@ public class TsFileResource implements 
PersistentResource, Cloneable {
       maxProgressIndex.updateAndGet(
           index -> 
index.updateToMinimumEqualOrIsAfterProgressIndex(progressIndex));
     }
+    updateMemoryCostIfRegistered();
   }
 
   public void setProgressIndex(ProgressIndex progressIndex) {
@@ -1463,6 +1562,7 @@ public class TsFileResource implements 
PersistentResource, Cloneable {
     }
 
     maxProgressIndex.set(progressIndex);
+    updateMemoryCostIfRegistered();
   }
 
   @Override
@@ -1596,8 +1696,8 @@ public class TsFileResource implements 
PersistentResource, Cloneable {
   }
 
   /** Unpublished LOAD installations defer metrics until their data file is 
published. */
-  public void upgradeModFile(ExecutorService upgradeModFileThreadPool, boolean 
updateModMetrics)
-      throws IOException {
+  public synchronized void upgradeModFile(
+      ExecutorService upgradeModFileThreadPool, boolean updateModMetrics) 
throws IOException {
     ModificationFileV1 oldModFile = ModificationFileV1.getNormalMods(this);
     if (!oldModFile.exists()) {
       return;
@@ -1606,9 +1706,10 @@ public class TsFileResource implements 
PersistentResource, Cloneable {
     if (upgradeModFileThreadPool != null) {
       exclusiveModFileFuture =
           upgradeModFileThreadPool.submit(() -> doUpgradeModFile(oldModFile, 
updateModMetrics));
+      exclusiveModFile = null;
+      updateMemoryCostIfRegistered();
     } else {
-      exclusiveModFileFuture =
-          CompletableFuture.completedFuture(doUpgradeModFile(oldModFile, 
updateModMetrics));
+      setExclusiveModFile(doUpgradeModFile(oldModFile, updateModMetrics));
     }
   }
 
@@ -1641,6 +1742,7 @@ public class TsFileResource implements 
PersistentResource, Cloneable {
 
   public void setSharedModFilePathFuture(CompletableFuture<String> 
sharedModFilePathFuture) {
     this.sharedModFilePathFuture = sharedModFilePathFuture;
+    updateMemoryCostIfRegistered();
   }
 
   public boolean isUseSharedModFile() {
@@ -1657,6 +1759,7 @@ public class TsFileResource implements 
PersistentResource, Cloneable {
 
   public void setCompactionModFile(ModificationFile compactionModFile) {
     this.compactionModFile = compactionModFile;
+    updateMemoryCostIfRegistered();
   }
 
   public Map<IDeviceID, List<Pair<String, TimeValuePair>>> getLastValues() {
@@ -1667,7 +1770,7 @@ public class TsFileResource implements 
PersistentResource, Cloneable {
     this.lastValues = lastValues;
   }
 
-  public TsFileResource shallowClone() {
+  public synchronized TsFileResource shallowClone() {
     TsFileResource cloned = new TsFileResource();
     cloned.file = this.file;
     cloned.timeIndex = this.timeIndex;
@@ -1684,7 +1787,6 @@ public class TsFileResource implements 
PersistentResource, Cloneable {
     cloned.isRecordedByMetric = this.isRecordedByMetric;
     cloned.tsFileRepairStatus = this.tsFileRepairStatus;
     cloned.settleTsFileCallBack = this.settleTsFileCallBack;
-    cloned.deviceTimeIndexRamSize = this.deviceTimeIndexRamSize;
     cloned.tsFileSize = this.tsFileSize;
     cloned.processor = this.processor;
     cloned.originTsFileResource = this.originTsFileResource;
@@ -1705,7 +1807,9 @@ public class TsFileResource implements 
PersistentResource, Cloneable {
     return cloned;
   }
 
-  public TsFileResource shallowCloneForNative() throws 
CloneNotSupportedException {
-    return (TsFileResource) clone();
+  public synchronized TsFileResource shallowCloneForNative() throws 
CloneNotSupportedException {
+    TsFileResource cloned = (TsFileResource) clone();
+    cloned.memoryRegistration = null;
+    return cloned;
   }
 }
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/tsfile/timeindex/ArrayDeviceTimeIndex.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/tsfile/timeindex/ArrayDeviceTimeIndex.java
index 4ce25b0121c..ff7e862b3f6 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/tsfile/timeindex/ArrayDeviceTimeIndex.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/tsfile/timeindex/ArrayDeviceTimeIndex.java
@@ -23,7 +23,6 @@ import 
org.apache.iotdb.commons.exception.IllegalPathException;
 import org.apache.iotdb.commons.path.PartialPath;
 import org.apache.iotdb.commons.utils.TimePartitionUtils;
 import org.apache.iotdb.db.exception.load.PartitionViolationException;
-import org.apache.iotdb.db.i18n.StorageEngineMessages;
 import org.apache.iotdb.db.storageengine.dataregion.tsfile.TsFileResource;
 import org.apache.iotdb.db.utils.CommonUtils;
 
@@ -35,8 +34,6 @@ import org.apache.tsfile.utils.FilePathUtils;
 import org.apache.tsfile.utils.Pair;
 import org.apache.tsfile.utils.RamUsageEstimator;
 import org.apache.tsfile.utils.ReadWriteIOUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
 import java.io.IOException;
 import java.io.InputStream;
@@ -54,7 +51,13 @@ public class ArrayDeviceTimeIndex implements ITimeIndex {
   private static final long INSTANCE_SIZE =
       RamUsageEstimator.shallowSizeOfInstance(ArrayDeviceTimeIndex.class);
 
-  private static final Logger logger = 
LoggerFactory.getLogger(ArrayDeviceTimeIndex.class);
+  private static final long INTEGER_SIZE = 
RamUsageEstimator.shallowSizeOfInstance(Integer.class);
+  // Both ConcurrentHashMap.Node and HashMap.Node hold a hash and three 
references.
+  private static final long MAP_NODE_SIZE =
+      RamUsageEstimator.alignObjectSize(
+          RamUsageEstimator.NUM_BYTES_OBJECT_HEADER
+              + Integer.BYTES
+              + 3L * RamUsageEstimator.NUM_BYTES_OBJECT_REF);
 
   public static final int INIT_ARRAY_SIZE = 64;
 
@@ -235,9 +238,27 @@ public class ArrayDeviceTimeIndex implements ITimeIndex {
 
   @Override
   public long calculateRamSize() {
+    int count = deviceToIndex.size();
+    long deviceIdBytes = 0;
+    for (IDeviceID device : deviceToIndex.keySet()) {
+      deviceIdBytes += device.ramBytesUsed();
+    }
+    // Capacity is an estimate: map implementations do not expose their 
backing array.
+    // ConcurrentHashMap grows at the threshold; HashMap grows on the next 
insertion.
+    boolean concurrent = deviceToIndex instanceof ConcurrentHashMap;
+    long requiredSlots = (4L * count - (concurrent ? 0 : 1)) / 3;
+    long buckets =
+        count == 0 ? 0 : Math.min(1L << 30, Math.max(16L, 
Long.highestOneBit(requiredSlots) << 1));
+    long tableSize = buckets == 0 ? 0 : 
RamUsageEstimator.sizeOfObjectArray((int) buckets);
     return INSTANCE_SIZE
-        + RamUsageEstimator.sizeOfMap(
-            deviceToIndex, 
RamUsageEstimator.shallowSizeOfInstance(Integer.class))
+        + (concurrent
+            ? RamUsageEstimator.SHALLOW_SIZE_OF_CONCURRENT_HASHMAP
+            : RamUsageEstimator.SHALLOW_SIZE_OF_HASHMAP)
+        + tableSize
+        + count * MAP_NODE_SIZE
+        + deviceIdBytes
+        // Indices are contiguous from zero. Integer.valueOf shares at least 
the first 128.
+        + Math.max(0, count - 128) * INTEGER_SIZE
         + RamUsageEstimator.sizeOf(startTimes)
         + RamUsageEstimator.sizeOf(endTimes);
   }
@@ -417,19 +438,6 @@ public class ArrayDeviceTimeIndex implements ITimeIndex {
     return maxEndTime;
   }
 
-  @Override
-  public int compareDegradePriority(ITimeIndex timeIndex) {
-    if (timeIndex instanceof ArrayDeviceTimeIndex) {
-      return Long.compare(getMinStartTime(), timeIndex.getMinStartTime());
-    } else if (timeIndex instanceof FileTimeIndex) {
-      return -1;
-    } else {
-      logger.error(StorageEngineMessages.WRONG_TIME_INDEX_TYPE_LOG, 
timeIndex.getClass().getName());
-      throw new RuntimeException(
-          StorageEngineMessages.WRONG_TIME_INDEX_TYPE + 
timeIndex.getClass().getName());
-    }
-  }
-
   @Override
   public boolean definitelyNotContains(IDeviceID device) {
     return !deviceToIndex.containsKey(device);
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/tsfile/timeindex/FileTimeIndex.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/tsfile/timeindex/FileTimeIndex.java
index 7c28839cc16..ac0eb308840 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/tsfile/timeindex/FileTimeIndex.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/tsfile/timeindex/FileTimeIndex.java
@@ -48,7 +48,7 @@ import java.util.Set;
 
 public class FileTimeIndex implements ITimeIndex {
 
-  private static final long INSTANCE_SIZE =
+  public static final long INSTANCE_SIZE =
       RamUsageEstimator.shallowSizeOfInstance(FileTimeIndex.class);
 
   private static final Logger logger = 
LoggerFactory.getLogger(FileTimeIndex.class);
@@ -280,19 +280,6 @@ public class FileTimeIndex implements ITimeIndex {
     return true;
   }
 
-  @Override
-  public int compareDegradePriority(ITimeIndex timeIndex) {
-    if (timeIndex instanceof ArrayDeviceTimeIndex) {
-      return 1;
-    } else if (timeIndex instanceof FileTimeIndex) {
-      return Long.compare(startTime, timeIndex.getMinStartTime());
-    } else {
-      logger.error(StorageEngineMessages.WRONG_TIME_INDEX_TYPE_LOG, 
timeIndex.getClass().getName());
-      throw new RuntimeException(
-          StorageEngineMessages.WRONG_TIME_INDEX_TYPE + 
timeIndex.getClass().getName());
-    }
-  }
-
   @Override
   public boolean definitelyNotContains(IDeviceID device) {
     return false;
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/tsfile/timeindex/ITimeIndex.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/tsfile/timeindex/ITimeIndex.java
index e943b91201e..7510c478819 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/tsfile/timeindex/ITimeIndex.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/tsfile/timeindex/ITimeIndex.java
@@ -193,16 +193,6 @@ public interface ITimeIndex {
    */
   long getMaxEndTime();
 
-  /**
-   * compare the priority of two ITimeIndex
-   *
-   * @param timeIndex another timeIndex
-   * @return value is less than 0 if the priority of this timeIndex is higher 
than the argument,
-   *     value is equal to 0 if the priority of this timeIndex is equal to the 
argument, value is
-   *     larger than 0 if the priority of this timeIndex is less than the 
argument
-   */
-  int compareDegradePriority(ITimeIndex timeIndex);
-
   /**
    * Whether this TsFile definitely not contains this device, if ture, it must 
not contain this
    * device, if false, it may or may not contain this device Notice: using 
method be CAREFULLY and
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TsFileResourceManager.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TsFileResourceManager.java
index 3221185db55..231fd1df6ac 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TsFileResourceManager.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/rescon/memory/TsFileResourceManager.java
@@ -26,11 +26,17 @@ import org.apache.iotdb.db.conf.DataNodeMemoryConfig;
 import org.apache.iotdb.db.conf.IoTDBDescriptor;
 import org.apache.iotdb.db.i18n.StorageEngineMessages;
 import org.apache.iotdb.db.storageengine.dataregion.tsfile.TsFileResource;
-import 
org.apache.iotdb.db.storageengine.dataregion.tsfile.timeindex.TimeIndexLevel;
+import 
org.apache.iotdb.db.storageengine.dataregion.tsfile.timeindex.ArrayDeviceTimeIndex;
+import 
org.apache.iotdb.db.storageengine.dataregion.tsfile.timeindex.ITimeIndex;
+import org.apache.iotdb.db.utils.MemUtils;
 
+import org.apache.tsfile.utils.RamUsageEstimator;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import java.io.File;
+import java.util.HashMap;
+import java.util.Map;
 import java.util.TreeSet;
 
 public class TsFileResourceManager {
@@ -42,12 +48,78 @@ public class TsFileResourceManager {
   /** The memory block of time index */
   private final IMemoryBlock memoryBlock;
 
-  /** store the sealed TsFileResource, sorted by priority of TimeIndex */
-  private final TreeSet<TsFileResource> sealedTsFileResources =
-      new TreeSet<>(TsFileResource::compareIndexDegradePriority);
+  // Registration, its priority-tree node, and the path map's node and 
amortized bucket slots.
+  static final long REGISTRATION_RAM_BYTES =
+      RamUsageEstimator.shallowSizeOfInstance(Registration.class)
+          + RamUsageEstimator.alignObjectSize(
+              RamUsageEstimator.NUM_BYTES_OBJECT_HEADER
+                  + 5L * RamUsageEstimator.NUM_BYTES_OBJECT_REF
+                  + Byte.BYTES)
+          + RamUsageEstimator.SHALLOW_SIZE_OF_HASHMAP_ENTRY
+          + 2L * RamUsageEstimator.NUM_BYTES_OBJECT_REF;
 
-  // degraded time index number
-  private long degradedTimeIndexNum = 0;
+  private final Map<String, Registration> registrationsByPath = new 
HashMap<>();
+  private final TreeSet<Registration> sealedTsFileResources =
+      new TreeSet<>(Registration::comparePriority);
+  private long degradedTimeIndexNum;
+  private boolean degrading;
+
+  /**
+   * After publication the manager monitor protects the priority key, measured 
index and charged
+   * bytes.
+   */
+  public static final class Registration {
+    private final TsFileResource resource;
+    private File file;
+    private String path;
+    private long startTime;
+    private ITimeIndex index;
+    private long indexBytes;
+    private long bytes;
+
+    private Registration(TsFileResource resource, File file, String path) {
+      this.resource = resource;
+      this.file = file;
+      this.path = path;
+      index = resource.getTimeIndex();
+      startTime = index == null ? Long.MAX_VALUE : index.getMinStartTime();
+    }
+
+    private boolean hasFileIndex() {
+      return index != null && index.getTimeIndexType() == 
ITimeIndex.FILE_TIME_INDEX_TYPE;
+    }
+
+    private boolean canDegrade() {
+      return index != null && !hasFileIndex();
+    }
+
+    private int comparePriority(Registration other) {
+      int cmp = Boolean.compare(other.canDegrade(), canDegrade());
+      if (cmp == 0) {
+        cmp = Long.compare(startTime, other.startTime);
+      }
+      return cmp == 0 ? path.compareTo(other.path) : cmp;
+    }
+
+    public long getIndexRamSize(ITimeIndex candidate) {
+      synchronized (TsFileResourceManager.getInstance()) {
+        if (candidate == index) {
+          return indexBytes;
+        }
+      }
+      // A compaction may own a rebuilt index or still hold the index from 
before degradation.
+      return candidate.calculateRamSize();
+    }
+
+    public void refresh(boolean indexChanged) {
+      TsFileResourceManager.getInstance().refresh(this, indexChanged);
+    }
+
+    private void detach() {
+      resource.setMemoryRegistration(null);
+      index = null;
+    }
+  }
 
   private TsFileResourceManager() {
     memoryBlock =
@@ -61,82 +133,204 @@ public class TsFileResourceManager {
     this.memoryBlock.setTotalMemorySizeInBytes(timeIndexMemoryThreshold);
   }
 
-  public long getPriorityQueueSize() {
+  public synchronized long getPriorityQueueSize() {
     return sealedTsFileResources.size();
   }
 
-  /**
-   * add the closed TsFileResource into priorityQueue and increase memory cost 
of timeIndex, once
-   * memory cost is larger than threshold, degradation is triggered.
-   */
-  public synchronized void registerSealedTsFileResource(TsFileResource 
tsFileResource) {
-    if (!sealedTsFileResources.contains(tsFileResource)) {
-      sealedTsFileResources.add(tsFileResource);
-      
memoryBlock.forceAllocateWithoutLimitation(tsFileResource.calculateRamSize());
-      chooseTsFileResourceToDegrade();
+  // Device IDs are appended to a live index, and close() can trim its time 
arrays in place.
+  private record DeviceIndexShape(
+      ArrayDeviceTimeIndex index, int deviceCount, int startCapacity, int 
endCapacity) {
+    private DeviceIndexShape(ArrayDeviceTimeIndex index) {
+      this(
+          index,
+          index.getDeviceToIndex().size(),
+          index.getStartTimes().length,
+          index.getEndTimes().length);
     }
-  }
 
-  /** delete the TsFileResource in PriorityQueue when the source file is 
deleted */
-  public synchronized void removeTsFileResource(TsFileResource tsFileResource) 
{
-    if (sealedTsFileResources.contains(tsFileResource)) {
-      sealedTsFileResources.remove(tsFileResource);
-      if (TimeIndexLevel.valueOf(tsFileResource.getTimeIndexType())
-          == TimeIndexLevel.FILE_TIME_INDEX) {
-        memoryBlock.release(tsFileResource.calculateRamSize());
-        degradedTimeIndexNum--;
-      } else {
-        memoryBlock.release(tsFileResource.calculateRamSize());
-      }
+    private boolean changed() {
+      return deviceCount != index.getDeviceToIndex().size()
+          || startCapacity != index.getStartTimes().length
+          || endCapacity != index.getEndTimes().length;
     }
   }
 
-  public void forceDegradeTsFileResource(TsFileResource resource) {
-    if (TimeIndexLevel.valueOf(resource.getTimeIndexType()) == 
TimeIndexLevel.FILE_TIME_INDEX) {
+  public void registerSealedTsFileResource(TsFileResource resource) {
+    if (resource.getMemoryRegistration() != null) {
       return;
     }
-    logger.debug(StorageEngineMessages.FORCE_DEGRADE_TSFILE_RESOURCE, 
resource.getTsFilePath());
+    Registration entry;
     synchronized (this) {
-      if (!sealedTsFileResources.remove(resource)) {
-        resource.degradeTimeIndex();
+      File file = resource.getTsFile();
+      String path = file.getAbsolutePath();
+      if (registrationsByPath.containsKey(path)) {
         return;
       }
-      long memoryReduce = resource.degradeTimeIndex();
+      entry = new Registration(resource, file, path);
+    }
+
+    // Measure device IDs while the entry is private, outside the monitor 
shared with queries.
+    DeviceIndexShape shape =
+        entry.index instanceof ArrayDeviceTimeIndex deviceIndex
+            ? new DeviceIndexShape(deviceIndex)
+            : null;
+    entry.indexBytes = entry.index == null ? 0 : 
entry.index.calculateRamSize();
+    publishRegistration(entry, shape);
+  }
+
+  private synchronized void publishRegistration(Registration entry, 
DeviceIndexShape shape) {
+    TsFileResource resource = entry.resource;
+    if (resource.getMemoryRegistration() != null) {
+      return;
+    }
+    File file = resource.getTsFile();
+    if (entry.file != file) {
+      entry.file = file;
+      entry.path = file.getAbsolutePath();
+    }
+    if (registrationsByPath.putIfAbsent(entry.path, entry) != null) {
+      return;
+    }
+    sealedTsFileResources.add(entry);
+    if (entry.hasFileIndex()) {
+      degradedTimeIndexNum++;
+    }
+    // Publish before validating the sample so subsequent mutations deliver 
their own refresh.
+    resource.setMemoryRegistration(entry);
+    boolean charged = false;
+    try {
+      // refresh also remeasures if the resource now holds a different index 
object.
+      refresh(entry, shape != null && shape.changed());
+      charged = true;
+    } finally {
+      if (!charged) {
+        removeRegistration(entry);
+      }
+    }
+  }
+
+  public synchronized void removeTsFileResource(TsFileResource resource) {
+    Registration entry = resource.getMemoryRegistration();
+    if (entry == null) {
+      // Compaction recovery may only know the path, with an empty or 
different time index.
+      File file = resource.getTsFile();
+      entry = file == null ? null : 
registrationsByPath.get(file.getAbsolutePath());
+    }
+    if (entry != null) {
+      removeRegistration(entry);
+    }
+  }
+
+  private void removeRegistration(Registration entry) {
+    if (registrationsByPath.remove(entry.path, entry)) {
+      sealedTsFileResources.remove(entry);
+      if (entry.hasFileIndex()) {
+        degradedTimeIndexNum--;
+      }
+      entry.detach();
+      memoryBlock.release(entry.bytes);
+    }
+  }
+
+  private boolean updatePriority(Registration entry, ITimeIndex index, long 
startTime, File file) {
+    String path = entry.path;
+    if (file != entry.file) {
+      path = file.getAbsolutePath();
+      Registration owner = registrationsByPath.get(path);
+      if (owner != null && owner != entry) {
+        // As on registration, keep the existing owner when two resources name 
the same file.
+        removeRegistration(entry);
+        return false;
+      }
+      registrationsByPath.remove(entry.path);
+      registrationsByPath.put(path, entry);
+    }
+    sealedTsFileResources.remove(entry);
+    if (entry.hasFileIndex()) {
+      degradedTimeIndexNum--;
+    }
+    entry.file = file;
+    entry.path = path;
+    entry.startTime = startTime;
+    entry.index = index;
+    if (entry.hasFileIndex()) {
       degradedTimeIndexNum++;
-      releaseTimeIndexMemCost(memoryReduce);
-      sealedTsFileResources.add(resource);
     }
+    sealedTsFileResources.add(entry);
+    return true;
+  }
+
+  private synchronized void refresh(Registration entry, boolean indexChanged) {
+    TsFileResource resource = entry.resource;
+    if (resource.getMemoryRegistration() != entry) {
+      return;
+    }
+    ITimeIndex index = resource.getTimeIndex();
+    long startTime = index == null ? Long.MAX_VALUE : index.getMinStartTime();
+    File file = resource.getTsFile();
+    boolean replaced = index != entry.index;
+    // A metadata callback can observe an index swap before the swapping 
thread takes this monitor.
+    long indexBytes = entry.indexBytes;
+    if (replaced || indexChanged) {
+      indexBytes = index == null ? 0 : index.calculateRamSize();
+    }
+    if ((replaced || startTime != entry.startTime || file != entry.file)
+        && !updatePriority(entry, index, startTime, file)) {
+      return;
+    }
+    entry.indexBytes = indexBytes;
+    // A relative File retains its own path string in addition to the map's 
absolute key.
+    long pathBytes = file.isAbsolute() ? 0 : 
MemUtils.getFilePathRamBytes(entry.path);
+    long bytes =
+        REGISTRATION_RAM_BYTES + pathBytes + 
resource.calculateMetadataRamSize() + indexBytes;
+    long delta = bytes - entry.bytes;
+    entry.bytes = bytes;
+    adjustMemoryUsage(delta);
   }
 
-  /** once degradation is triggered, the total memory for timeIndex should 
reduce */
-  private void releaseTimeIndexMemCost(long memCost) {
-    memoryBlock.release(memCost);
+  private void adjustMemoryUsage(long delta) {
+    if (delta > 0) {
+      memoryBlock.forceAllocateWithoutLimitation(delta);
+      if (!degrading
+          && memoryBlock.getUsedMemoryInBytes() > 
memoryBlock.getTotalMemorySizeInBytes()) {
+        degrading = true;
+        try {
+          chooseTsFileResourceToDegrade();
+        } finally {
+          degrading = false;
+        }
+      }
+    } else if (delta < 0) {
+      memoryBlock.release(-delta);
+    }
+  }
+
+  public void forceDegradeTsFileResource(TsFileResource resource) {
+    if (resource.replaceDeviceTimeIndexWithFileTimeIndex() != null) {
+      logger.debug(StorageEngineMessages.FORCE_DEGRADE_TSFILE_RESOURCE, 
resource.getTsFilePath());
+    }
   }
 
-  /**
-   * choose the top TsFileResource in priorityQueue to degrade until the 
memory is smaller than
-   * threshold.
-   */
   private void chooseTsFileResourceToDegrade() {
     while (memoryBlock.getUsedMemoryInBytes() > 
memoryBlock.getTotalMemorySizeInBytes()) {
-      TsFileResource tsFileResource = sealedTsFileResources.pollFirst();
-      if (tsFileResource == null
-          || TimeIndexLevel.valueOf(tsFileResource.getTimeIndexType())
-              == TimeIndexLevel.FILE_TIME_INDEX) {
+      Registration entry = sealedTsFileResources.first();
+      if (!entry.canDegrade()) {
         
logger.debug(StorageEngineMessages.CANNOT_DEGRADE_TIME_INDEX_ALL_FILE_LEVEL);
-        sealedTsFileResources.add(tsFileResource);
         return;
       }
-      long memoryReduce = tsFileResource.degradeTimeIndex();
-      logger.debug(StorageEngineMessages.DEGRADE_TSFILE_RESOURCE, 
tsFileResource.getTsFilePath());
-      degradedTimeIndexNum++;
-      releaseTimeIndexMemCost(memoryReduce);
-      // add the polled tsFileResource to the priority queue
-      sealedTsFileResources.add(tsFileResource);
+      if (entry.resource.getMemoryRegistration() != entry) {
+        // Its degradation callback cannot release this entry's charge.
+        return;
+      }
+      logger.debug(StorageEngineMessages.DEGRADE_TSFILE_RESOURCE, entry.file);
+      if (entry.resource.replaceDeviceTimeIndexWithFileTimeIndex() == null) {
+        // Another thread has already swapped the index and is waiting to 
publish its size.
+        refresh(entry, true);
+      }
     }
   }
 
-  public long getDegradedTimeIndexNum() {
+  public synchronized long getDegradedTimeIndexNum() {
     return degradedTimeIndexNum;
   }
 
@@ -151,6 +345,8 @@ public class TsFileResourceManager {
   /** function for clearing TsFileManager */
   @TestOnly
   public synchronized void clear() {
+    registrationsByPath.values().forEach(Registration::detach);
+    registrationsByPath.clear();
     this.sealedTsFileResources.clear();
     this.memoryBlock.setUsedMemoryInBytes(0);
     this.degradedTimeIndexNum = 0;
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/MemUtils.java 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/MemUtils.java
index b724c4d3c6f..1187d3d495b 100644
--- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/MemUtils.java
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/MemUtils.java
@@ -26,6 +26,7 @@ import org.apache.iotdb.db.i18n.DataNodeMiscMessages;
 import 
org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.InsertTabletNode;
 import org.apache.iotdb.rpc.TSStatusCode;
 
+import com.sun.management.HotSpotDiagnosticMXBean;
 import org.apache.tsfile.common.conf.TSFileConfig;
 import org.apache.tsfile.enums.TSDataType;
 import org.apache.tsfile.utils.Binary;
@@ -41,11 +42,49 @@ import 
org.apache.tsfile.write.record.datapoint.StringDataPoint;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import java.io.File;
+import java.lang.management.ManagementFactory;
 import java.util.List;
 
 // Notice : methods in this class may not be accurate.
 public class MemUtils {
 
+  private static final long FILE_INSTANCE_SIZE =
+      RamUsageEstimator.shallowSizeOfInstance(File.class);
+
+  private static final long STRING_INSTANCE_SIZE =
+      RamUsageEstimator.shallowSizeOfInstance(String.class);
+  private static final boolean COMPACT_STRINGS = usesCompactStrings();
+
+  private static boolean usesCompactStrings() {
+    try {
+      HotSpotDiagnosticMXBean vm =
+          ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
+      return vm != null && 
Boolean.parseBoolean(vm.getVMOption("CompactStrings").getValue());
+    } catch (RuntimeException | NoClassDefFoundError unavailable) {
+      // The two-byte estimate also works on VMs that do not expose the 
HotSpot option.
+      return false;
+    }
+  }
+
+  /** Heap occupied by a file path string and its backing array. */
+  public static long getFilePathRamBytes(String path) {
+    if (path == null || !COMPACT_STRINGS) {
+      return RamUsageEstimator.sizeOf(path);
+    }
+    for (int i = 0; i < path.length(); i++) {
+      if (path.charAt(i) > 0xff) {
+        return RamUsageEstimator.sizeOf(path);
+      }
+    }
+    return STRING_INSTANCE_SIZE + 
RamUsageEstimator.sizeOfByteArray(path.length());
+  }
+
+  /** Heap occupied by a file handle and its stored path. */
+  public static long getFileRamBytes(File file) {
+    return file == null ? 0 : FILE_INSTANCE_SIZE + 
getFilePathRamBytes(file.getPath());
+  }
+
   private static final Logger LOGGER = LoggerFactory.getLogger(MemUtils.class);
 
   private MemUtils() {}
diff --git 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/sql/AstMemoryEstimatorTest.java
 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/sql/AstMemoryEstimatorTest.java
index cbac0f40d23..3cbd3fa2981 100644
--- 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/sql/AstMemoryEstimatorTest.java
+++ 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/sql/AstMemoryEstimatorTest.java
@@ -40,17 +40,25 @@ import 
org.apache.iotdb.db.queryengine.plan.relational.metadata.TableMetadataImp
 import org.apache.iotdb.db.queryengine.plan.relational.planner.PlannerContext;
 import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.InsertRows;
 import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.InsertValues;
+import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.LoadTsFile;
 import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.Prepare;
 import org.apache.iotdb.db.queryengine.plan.relational.sql.parser.SqlParser;
 import org.apache.iotdb.db.queryengine.plan.statement.crud.InsertRowStatement;
 import org.apache.iotdb.db.schemaengine.table.DataNodeTableCache;
 import org.apache.iotdb.db.schemaengine.table.ITableCache;
+import org.apache.iotdb.db.storageengine.dataregion.tsfile.TsFileResource;
+import org.apache.iotdb.db.utils.MemUtils;
 
 import org.apache.tsfile.enums.TSDataType;
 import org.junit.Before;
 import org.junit.Test;
 
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.time.ZoneId;
+import java.util.Collections;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotSame;
@@ -1074,4 +1082,24 @@ public class AstMemoryEstimatorTest {
     long memorySize = estimateMemorySize(statement);
     assertTrue("Memory size should be positive", memorySize > 0);
   }
+
+  @Test
+  public void testLoadRamSizeCountsSharedFileOnce() throws IOException {
+    Path input = Files.createTempFile("load-ram-", ".tsfile");
+    try {
+      LoadTsFile load = LoadTsFile.createUnchecked(null, input.toString(), 
Collections.emptyMap());
+      File file = load.getTsFiles().get(0);
+      load.addTsFileResource(null);
+      long filesOnly = load.ramBytesUsed();
+      TsFileResource resource = new TsFileResource(file);
+      load.getResources().set(0, resource);
+      assertEquals(
+          filesOnly + resource.calculateRamSize() - 
MemUtils.getFileRamBytes(file),
+          load.ramBytesUsed());
+      resource.setFile(new File(file.getParentFile(), "0-2-0-0.tsfile"));
+      assertEquals(filesOnly + resource.calculateRamSize(), 
load.ramBytesUsed());
+    } finally {
+      Files.deleteIfExists(input);
+    }
+  }
 }
diff --git 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/DataRegionTest.java
 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/DataRegionTest.java
index 2fae4dee1a4..ae69e590c26 100644
--- 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/DataRegionTest.java
+++ 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/DataRegionTest.java
@@ -274,6 +274,7 @@ public class DataRegionTest {
         resource.setStatus(TsFileResourceStatus.NORMAL);
         resource.updateStartTime(device, 1);
         resource.updateEndTime(device, 3);
+        resource.setLastValues(Collections.emptyMap());
         resource.serialize();
         final File sourceMods =
             modsVersion == 1
@@ -405,7 +406,10 @@ public class DataRegionTest {
             resource.setFile(source);
           }
         }
+        // Failed publication leaves the LOAD input available for the retry.
+        Assert.assertNotNull(resource.getLastValues());
         dataRegion.loadNewTsFile(resource, deleteOrigin, false, true, 
Optional.empty());
+        Assert.assertNull(resource.getLastValues());
         final File installed = resource.getTsFile();
         Assert.assertArrayEquals(data, Files.readAllBytes(installed.toPath()));
         Assert.assertTrue(new File(installed + 
TsFileResource.RESOURCE_SUFFIX).isFile());
diff --git 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/tsfile/TsFileResourceTest.java
 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/tsfile/TsFileResourceTest.java
index f0149f799c1..59bdf10a4fa 100644
--- 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/tsfile/TsFileResourceTest.java
+++ 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/tsfile/TsFileResourceTest.java
@@ -192,6 +192,7 @@ public class TsFileResourceTest {
 
     // upgrade asynchronously
     ExecutorService threadPool = Executors.newSingleThreadExecutor();
+    long metadataBeforeUpgrade = tsFileResource.calculateMetadataRamSize();
     tsFileResource.upgradeModFile(threadPool);
 
     // entries should be upgraded
@@ -212,6 +213,9 @@ public class TsFileResourceTest {
       fail("Mod file upgrade takes too long");
     }
 
+    assertEquals(
+        metadataBeforeUpgrade + 
tsFileResource.getExclusiveModFile().ramBytesUsed(),
+        tsFileResource.calculateMetadataRamSize());
     // writable after upgrade
     try (ModificationFile modFileForWrite = 
tsFileResource.getModFileForWrite()) {
       TreeDeletionEntry newDeletionEntry =
@@ -237,7 +241,15 @@ public class TsFileResourceTest {
     }
 
     // upgrade synchronously
+    long metadataBeforeUpgrade = tsFileResource.calculateMetadataRamSize();
     tsFileResource.upgradeModFile(null);
+    // Local LOAD publishes its own handle after converting a legacy mods file.
+    ModificationFile published =
+        new ModificationFile(ModificationFile.getExclusiveMods(file), false);
+    tsFileResource.setExclusiveModFile(published);
+    assertEquals(
+        metadataBeforeUpgrade + published.ramBytesUsed(),
+        tsFileResource.calculateMetadataRamSize());
 
     // entries should be upgraded
     List<TreeDeletionEntry> newDeletionEntriesExpected =
@@ -262,6 +274,25 @@ public class TsFileResourceTest {
     assertEquals(newDeletionEntriesExpected, 
tsFileResource.getAllModEntries());
   }
 
+  @Test
+  public void testResetCompletedModUpgradeBeforeFirstRead() throws Exception {
+    try (ModificationFileV1 legacy = 
ModificationFileV1.getNormalMods(tsFileResource)) {
+      legacy.write(new Deletion(new MeasurementPath("root.db1.d1.s1"), 0, 
100));
+    }
+    long beforeUpgrade = tsFileResource.calculateMetadataRamSize();
+    ExecutorService pool = Executors.newSingleThreadExecutor();
+    try {
+      tsFileResource.upgradeModFile(pool);
+      pool.shutdown();
+      assertTrue(pool.awaitTermination(10, TimeUnit.SECONDS));
+      tsFileResource.resetModFile();
+      assertEquals(beforeUpgrade, tsFileResource.calculateMetadataRamSize());
+      assertEquals(1, tsFileResource.getAllModEntries().size());
+    } finally {
+      pool.shutdownNow();
+    }
+  }
+
   @Test
   public void testUpgradeModFileAsyncDirectlyWrite()
       throws IllegalPathException, IOException, InterruptedException {
diff --git 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/ResourceManagerTest.java
 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/ResourceManagerTest.java
index 4236cbcd576..de0193fd11e 100644
--- 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/ResourceManagerTest.java
+++ 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/rescon/memory/ResourceManagerTest.java
@@ -20,6 +20,7 @@
 package org.apache.iotdb.db.storageengine.rescon.memory;
 
 import org.apache.iotdb.commons.conf.IoTDBConstant;
+import org.apache.iotdb.commons.consensus.index.impl.SimpleProgressIndex;
 import org.apache.iotdb.commons.exception.MetadataException;
 import org.apache.iotdb.db.conf.DataNodeMemoryConfig;
 import org.apache.iotdb.db.conf.IoTDBConfig;
@@ -28,12 +29,16 @@ import org.apache.iotdb.db.exception.StorageEngineException;
 import org.apache.iotdb.db.storageengine.buffer.BloomFilterCache;
 import org.apache.iotdb.db.storageengine.buffer.ChunkCache;
 import org.apache.iotdb.db.storageengine.buffer.TimeSeriesMetadataCache;
+import 
org.apache.iotdb.db.storageengine.dataregion.compaction.schedule.CompactionScheduleContext;
 import 
org.apache.iotdb.db.storageengine.dataregion.read.control.FileReaderManager;
 import org.apache.iotdb.db.storageengine.dataregion.tsfile.TsFileResource;
 import 
org.apache.iotdb.db.storageengine.dataregion.tsfile.TsFileResourceStatus;
+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.tsfile.timeindex.ITimeIndex;
 import 
org.apache.iotdb.db.storageengine.dataregion.tsfile.timeindex.TimeIndexLevel;
 import org.apache.iotdb.db.utils.EnvironmentUtils;
+import org.apache.iotdb.db.utils.MemUtils;
 import org.apache.iotdb.db.utils.constant.TestConstant;
 
 import org.apache.tsfile.enums.TSDataType;
@@ -42,12 +47,16 @@ import org.apache.tsfile.file.metadata.IDeviceID;
 import org.apache.tsfile.file.metadata.enums.CompressionType;
 import org.apache.tsfile.file.metadata.enums.TSEncoding;
 import org.apache.tsfile.fileSystem.FSFactoryProducer;
+import org.apache.tsfile.read.TimeValuePair;
 import org.apache.tsfile.read.common.Path;
+import org.apache.tsfile.utils.Pair;
+import org.apache.tsfile.utils.TsPrimitiveType;
 import org.apache.tsfile.write.TsFileWriter;
 import org.apache.tsfile.write.record.TSRecord;
 import org.apache.tsfile.write.record.datapoint.DataPoint;
 import org.apache.tsfile.write.schema.IMeasurementSchema;
 import org.apache.tsfile.write.schema.MeasurementSchema;
+import org.awaitility.Awaitility;
 import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
@@ -56,10 +65,25 @@ import org.junit.Test;
 import java.io.File;
 import java.io.IOException;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
 
 import static org.apache.iotdb.commons.conf.IoTDBConstant.PATH_SEPARATOR;
+import static 
org.apache.iotdb.db.storageengine.rescon.memory.TsFileResourceManager.REGISTRATION_RAM_BYTES;
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.clearInvocations;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
 
 public class ResourceManagerTest {
 
@@ -246,7 +270,7 @@ public class ResourceManagerTest {
         TimeIndexLevel.ARRAY_DEVICE_TIME_INDEX,
         TimeIndexLevel.valueOf(tsFileResource.getTimeIndexType()));
     long previousRamSize = tsFileResource.calculateRamSize();
-    long curTimeIndexMemoryThreshold = 4291;
+    long curTimeIndexMemoryThreshold = registeredSize(tsFileResource);
     
tsFileResourceManager.setTimeIndexMemoryThreshold(curTimeIndexMemoryThreshold);
     tsFileResourceManager.registerSealedTsFileResource(tsFileResource);
     assertEquals(0, previousRamSize - tsFileResource.calculateRamSize());
@@ -302,7 +326,7 @@ public class ResourceManagerTest {
         TimeIndexLevel.valueOf(tsFileResource2.getTimeIndexType()));
 
     long curTimeIndexMemoryThreshold =
-        degradedResource1.calculateRamSize() + 
tsFileResource2.calculateRamSize();
+        registeredSize(degradedResource1) + registeredSize(tsFileResource2);
     
tsFileResourceManager.setTimeIndexMemoryThreshold(curTimeIndexMemoryThreshold);
     tsFileResourceManager.registerSealedTsFileResource(tsFileResource1);
     assertEquals(
@@ -340,7 +364,7 @@ public class ResourceManagerTest {
           TimeIndexLevel.valueOf(tsFileResource.getTimeIndexType()));
       prepareFile(tsFileResource, i * ptNum, ptNum, 0);
       tsFileResource.degradeTimeIndex();
-      curTimeIndexMemoryThreshold += tsFileResource.calculateRamSize();
+      curTimeIndexMemoryThreshold += registeredSize(tsFileResource);
     }
     for (int i = 8; i < seqFileNum; i++) {
       File file =
@@ -361,7 +385,7 @@ public class ResourceManagerTest {
           TimeIndexLevel.ARRAY_DEVICE_TIME_INDEX,
           TimeIndexLevel.valueOf(tsFileResource.getTimeIndexType()));
       prepareFile(tsFileResource, i * ptNum, ptNum, 0);
-      curTimeIndexMemoryThreshold += tsFileResource.calculateRamSize();
+      curTimeIndexMemoryThreshold += registeredSize(tsFileResource);
     }
 
     for (int i = 0; i < seqFileNum; i++) {
@@ -457,15 +481,362 @@ public class ResourceManagerTest {
         TimeIndexLevel.ARRAY_DEVICE_TIME_INDEX,
         TimeIndexLevel.valueOf(tsFileResource.getTimeIndexType()));
     tsFileResourceManager.registerSealedTsFileResource(tsFileResource);
-    long resourceRamSizeBeforeDegrade = tsFileResource.calculateRamSize();
-    Assert.assertEquals(
-        resourceRamSizeBeforeDegrade, 
tsFileResourceManager.getTotalTimeIndexMemCost());
+    long chargeBeforeDegrade = registeredSize(tsFileResource);
+    Assert.assertEquals(chargeBeforeDegrade, 
tsFileResourceManager.getTotalTimeIndexMemCost());
     
TsFileResourceManager.getInstance().forceDegradeTsFileResource(tsFileResource);
     Assert.assertEquals(
-        tsFileResource.calculateRamSize(), 
tsFileResourceManager.getTotalTimeIndexMemCost());
-    Assert.assertTrue(
-        resourceRamSizeBeforeDegrade > 
tsFileResourceManager.getTotalTimeIndexMemCost());
+        registeredSize(tsFileResource), 
tsFileResourceManager.getTotalTimeIndexMemCost());
+    Assert.assertTrue(chargeBeforeDegrade > 
tsFileResourceManager.getTotalTimeIndexMemCost());
     Assert.assertTrue(tsFileResource.getTimeIndexType() == 
ITimeIndex.FILE_TIME_INDEX_TYPE);
     Assert.assertEquals(1, tsFileResourceManager.getDegradedTimeIndexNum());
   }
+
+  @Test
+  public void testResidentMetadataAndIndexSizeChanges() throws IOException {
+    File file = new File("target/0-1-0-0.tsfile");
+    TsFileResource resource = new TsFileResource(file);
+    long before = resource.calculateRamSize();
+    IDeviceID device = 
IDeviceID.Factory.DEFAULT_FACTORY.create("root.test.newDevice");
+    resource.updateStartTime(device, 1);
+    assertTrue(resource.calculateRamSize() > before);
+
+    resource.close();
+    long sealed = resource.calculateRamSize();
+    long indexSize = resource.getTimeIndex().calculateRamSize();
+    assertEquals(Long.valueOf(indexSize), 
resource.getDeviceTimeIndexRamSize().get());
+    long expectedRelease = indexSize - new FileTimeIndex().calculateRamSize();
+    // A freshly sealed resource can also be degraded before any size 
calculation.
+    TsFileResource unmeasured = new TsFileResource(file);
+    unmeasured.updateStartTime(device, 1);
+    unmeasured.close();
+    assertEquals(expectedRelease, unmeasured.degradeTimeIndex());
+    assertEquals(expectedRelease, resource.degradeTimeIndex());
+    assertEquals(sealed - expectedRelease, resource.calculateRamSize());
+    assertEquals(0, resource.degradeTimeIndex());
+    Assert.assertFalse(resource.getDeviceTimeIndexRamSize().isPresent());
+
+    long base = resource.calculateRamSize();
+    File longerPath = new File("target/longer/directory/0-1-0-0.tsfile");
+    resource.setFile(longerPath);
+    assertEquals(
+        base + MemUtils.getFileRamBytes(longerPath) - 
MemUtils.getFileRamBytes(file),
+        resource.calculateRamSize());
+    long beforeMods = resource.calculateRamSize();
+    long modSize = resource.getExclusiveModFile().ramBytesUsed();
+    assertEquals(beforeMods + modSize, resource.calculateRamSize());
+    resource.resetModFile();
+    assertEquals(beforeMods, resource.calculateRamSize());
+  }
+
+  @Test
+  public void testRegisteredBytesFollowMetadataAndIndexChanges() throws 
Exception {
+    tsFileResourceManager.setTimeIndexMemoryThreshold(Long.MAX_VALUE);
+    TsFileResource remaining = new TsFileResource(new 
File("target/0-1-0-0.tsfile"));
+    remaining.close();
+    tsFileResourceManager.registerSealedTsFileResource(remaining);
+    long baseline = tsFileResourceManager.getTotalTimeIndexMemCost();
+    TsFileResource resource = new TsFileResource(new 
File("target/0-2-0-0.tsfile"));
+    resource.close();
+    resource.setTimeIndex(new ArrayDeviceTimeIndex());
+    tsFileResourceManager.registerSealedTsFileResource(resource);
+    tsFileResourceManager.registerSealedTsFileResource(resource);
+    long originalCharge = registeredSize(resource);
+    assertEquals(baseline + originalCharge, 
tsFileResourceManager.getTotalTimeIndexMemCost());
+    
resource.updateStartTime(IDeviceID.Factory.DEFAULT_FACTORY.create("root.test.later"),
 7);
+    resource.setProgressIndex(new SimpleProgressIndex(1, 1));
+    resource.getExclusiveModFile();
+    long changedCharge = registeredSize(resource);
+    assertTrue(changedCharge > originalCharge);
+    assertEquals(baseline + changedCharge, 
tsFileResourceManager.getTotalTimeIndexMemCost());
+
+    resource.degradeTimeIndex();
+    assertEquals(1, tsFileResourceManager.getDegradedTimeIndexNum());
+    assertEquals(
+        baseline + registeredSize(resource), 
tsFileResourceManager.getTotalTimeIndexMemCost());
+    TsFileResource clone = resource.shallowCloneForNative();
+    Assert.assertNull(clone.getMemoryRegistration());
+    clone.getCompactionModFile();
+    assertEquals(
+        baseline + registeredSize(resource), 
tsFileResourceManager.getTotalTimeIndexMemCost());
+    resource.setTimeIndex(new ArrayDeviceTimeIndex());
+    assertEquals(0, tsFileResourceManager.getDegradedTimeIndexNum());
+    assertEquals(
+        baseline + registeredSize(resource), 
tsFileResourceManager.getTotalTimeIndexMemCost());
+    tsFileResourceManager.removeTsFileResource(resource);
+    tsFileResourceManager.removeTsFileResource(resource);
+    assertEquals(baseline, tsFileResourceManager.getTotalTimeIndexMemCost());
+    assertEquals(0, tsFileResourceManager.getDegradedTimeIndexNum());
+    tsFileResourceManager.removeTsFileResource(remaining);
+    assertEquals(0, tsFileResourceManager.getTotalTimeIndexMemCost());
+  }
+
+  @Test
+  public void testLoadLastValuesExcludedFromResourceBudget() throws 
IOException {
+    TsFileResource resource = spy(new TsFileResource(new 
File("target/0-3-0-0.tsfile")));
+    resource.setTimeIndex(new ArrayDeviceTimeIndex());
+    resource.close();
+    long budget = registeredSize(resource);
+    tsFileResourceManager.setTimeIndexMemoryThreshold(budget);
+
+    resource.setLastValues(
+        Collections.singletonMap(
+            IDeviceID.Factory.DEFAULT_FACTORY.create("root.test.d"),
+            Collections.singletonList(
+                new Pair<>("s1", new TimeValuePair(1, new 
TsPrimitiveType.TsInt(42))))));
+    assertEquals(budget, registeredSize(resource));
+    tsFileResourceManager.registerSealedTsFileResource(resource);
+    assertEquals(budget, tsFileResourceManager.getTotalTimeIndexMemCost());
+    assertEquals(0, tsFileResourceManager.getDegradedTimeIndexNum());
+
+    clearInvocations(resource);
+    resource.setLastValues(null);
+    verify(resource, never()).calculateMetadataRamSize();
+    assertEquals(budget, tsFileResourceManager.getTotalTimeIndexMemCost());
+    tsFileResourceManager.removeTsFileResource(resource);
+    assertEquals(0, tsFileResourceManager.getTotalTimeIndexMemCost());
+  }
+
+  private static long registeredSize(TsFileResource resource) {
+    File file = resource.getTsFile();
+    return resource.calculateRamSize()
+        + REGISTRATION_RAM_BYTES
+        + (file.isAbsolute() ? 0 : 
MemUtils.getFilePathRamBytes(file.getAbsolutePath()));
+  }
+
+  @Test
+  public void testRecoveryUsesFileIdentityAcrossIndexLevelsAndRenames() throws 
IOException {
+    tsFileResourceManager.setTimeIndexMemoryThreshold(Long.MAX_VALUE);
+    File file = new File("target/0-11-0-0.tsfile");
+    TsFileResource original = new TsFileResource(file);
+    
original.updateStartTime(IDeviceID.Factory.DEFAULT_FACTORY.create("root.test.d1"),
 7);
+    original.close();
+    tsFileResourceManager.registerSealedTsFileResource(original);
+    TsFileResource recovered = new TsFileResource(file.getAbsoluteFile());
+    long charge = tsFileResourceManager.getTotalTimeIndexMemCost();
+    tsFileResourceManager.registerSealedTsFileResource(recovered);
+    assertEquals(1, tsFileResourceManager.getPriorityQueueSize());
+    assertEquals(charge, tsFileResourceManager.getTotalTimeIndexMemCost());
+
+    tsFileResourceManager.forceDegradeTsFileResource(original);
+    charge = tsFileResourceManager.getTotalTimeIndexMemCost();
+    tsFileResourceManager.registerSealedTsFileResource(recovered);
+    assertEquals(charge, tsFileResourceManager.getTotalTimeIndexMemCost());
+    File newFile = new File("target/0-12-0-0.tsfile").getAbsoluteFile();
+    original.setFile(newFile);
+    assertEquals(registeredSize(original), 
tsFileResourceManager.getTotalTimeIndexMemCost());
+    tsFileResourceManager.registerSealedTsFileResource(recovered);
+    assertEquals(2, tsFileResourceManager.getPriorityQueueSize());
+    // Moving onto an already registered path leaves one charge for the 
existing owner.
+    recovered.setFile(newFile);
+    Assert.assertNull(recovered.getMemoryRegistration());
+    assertEquals(registeredSize(original), 
tsFileResourceManager.getTotalTimeIndexMemCost());
+    tsFileResourceManager.removeTsFileResource(new TsFileResource(file));
+    assertEquals(1, tsFileResourceManager.getPriorityQueueSize());
+    tsFileResourceManager.removeTsFileResource(new TsFileResource(newFile));
+    assertEquals(0, tsFileResourceManager.getPriorityQueueSize());
+    assertEquals(0, tsFileResourceManager.getDegradedTimeIndexNum());
+    assertEquals(0, tsFileResourceManager.getTotalTimeIndexMemCost());
+    Assert.assertNull(original.getMemoryRegistration());
+  }
+
+  @Test
+  public void testMetadataRefreshObservesPendingIndexSwap() throws Exception {
+    tsFileResourceManager.setTimeIndexMemoryThreshold(Long.MAX_VALUE);
+    TsFileResource first = new TsFileResource(new 
File("target/0-21-0-0.tsfile"));
+    TsFileResource second = new TsFileResource(new 
File("target/0-22-0-0.tsfile"));
+    for (int i = 0; i < 16; i++) {
+      
first.updateStartTime(IDeviceID.Factory.DEFAULT_FACTORY.create("root.test.d" + 
i), 1);
+    }
+    
second.updateStartTime(IDeviceID.Factory.DEFAULT_FACTORY.create("root.test.other"),
 2);
+    first.close();
+    second.close();
+    tsFileResourceManager.registerSealedTsFileResource(first);
+    tsFileResourceManager.registerSealedTsFileResource(second);
+    tsFileResourceManager.setTimeIndexMemoryThreshold(
+        tsFileResourceManager.getTotalTimeIndexMemCost());
+    ExecutorService pool = Executors.newSingleThreadExecutor();
+    try {
+      Future<Long> degradation;
+      synchronized (tsFileResourceManager) {
+        // Hold the manager monitor between the index CAS and its accounting 
callback.
+        degradation = pool.submit(first::degradeTimeIndex);
+        Awaitility.await()
+            .atMost(10, TimeUnit.SECONDS)
+            .until(() -> first.getTimeIndex() instanceof FileTimeIndex);
+        first.getExclusiveModFile();
+        assertTrue(second.getTimeIndex() instanceof ArrayDeviceTimeIndex);
+        assertEquals(1, tsFileResourceManager.getDegradedTimeIndexNum());
+      }
+      assertTrue(degradation.get(10, TimeUnit.SECONDS) > 0);
+    } finally {
+      pool.shutdownNow();
+    }
+  }
+
+  @Test
+  public void testSelectionUsesMeasuredSizeOnlyForTheSameIndex() throws 
IOException {
+    tsFileResourceManager.setTimeIndexMemoryThreshold(Long.MAX_VALUE);
+    TsFileResource resource = new TsFileResource(new 
File("target/0-31-0-0.tsfile"));
+    ArrayDeviceTimeIndex resident = spy(new ArrayDeviceTimeIndex());
+    resource.setTimeIndex(resident);
+    resource.close();
+    tsFileResourceManager.registerSealedTsFileResource(resource);
+    CompactionScheduleContext context = new CompactionScheduleContext();
+    ArrayDeviceTimeIndex rebuilt = spy(new ArrayDeviceTimeIndex());
+    try {
+      assertTrue(resource.getDeviceTimeIndexRamSize().isPresent());
+      context.addResourceDeviceTimeIndex(resource, resident);
+      context.clearTimePartitionDeviceInfoCache();
+      context.addResourceDeviceTimeIndex(resource, resident);
+      tsFileResourceManager.forceDegradeTsFileResource(resource);
+      context.addResourceDeviceTimeIndex(resource, rebuilt);
+      context.addResourceDeviceTimeIndex(resource, rebuilt);
+      verify(resident, times(1)).calculateRamSize();
+      verify(rebuilt, times(1)).calculateRamSize();
+      Assert.assertSame(rebuilt, context.getResourceDeviceInfo(resource));
+      tsFileResourceManager.removeTsFileResource(resource);
+      context.clearTimePartitionDeviceInfoCache();
+      context.addResourceDeviceTimeIndex(resource, resident);
+      verify(resident, times(2)).calculateRamSize();
+    } finally {
+      context.clearTimePartitionDeviceInfoCache();
+    }
+  }
+
+  @Test
+  public void testNullTimeIndex() {
+    TsFileResource empty = new TsFileResource();
+    Assert.assertNull(empty.replaceDeviceTimeIndexWithFileTimeIndex());
+    assertEquals(0, empty.degradeTimeIndex());
+
+    TsFileResource registered = new TsFileResource(new 
File("target/0-41-0-0.tsfile"));
+    registered.setTimeIndex(new FileTimeIndex());
+    tsFileResourceManager.registerSealedTsFileResource(registered);
+    registered.setTimeIndex(null);
+    assertEquals(0, registered.degradeTimeIndex());
+    assertEquals(0, tsFileResourceManager.getDegradedTimeIndexNum());
+    assertEquals(registeredSize(registered), 
tsFileResourceManager.getTotalTimeIndexMemCost());
+  }
+
+  @Test
+  public void testFirstModsHandlesProceedDuringAnotherRegistrationScan() 
throws Exception {
+    tsFileResourceManager.setTimeIndexMemoryThreshold(Long.MAX_VALUE);
+    TsFileResource queried = spy(new TsFileResource(new 
File("target/0-51-0-0.tsfile")));
+    queried.close();
+    tsFileResourceManager.registerSealedTsFileResource(queried);
+    doAnswer(
+            call -> {
+              Assert.assertFalse(
+                  "mods accounting held the resource monitor", 
Thread.holdsLock(queried));
+              return call.callRealMethod();
+            })
+        .when(queried)
+        .calculateMetadataRamSize();
+
+    TsFileResource registering = new TsFileResource(new 
File("target/0-52-0-0.tsfile"));
+    ArrayDeviceTimeIndex original = spy(new ArrayDeviceTimeIndex());
+    registering.setTimeIndex(original);
+    registering.close();
+    CountDownLatch measured = new CountDownLatch(1);
+    CountDownLatch resume = new CountDownLatch(1);
+    doAnswer(
+            call -> {
+              long bytes = (long) call.callRealMethod();
+              measured.countDown();
+              assertTrue(resume.await(20, TimeUnit.SECONDS));
+              return bytes;
+            })
+        .when(original)
+        .calculateRamSize();
+
+    ExecutorService pool = Executors.newFixedThreadPool(2);
+    try {
+      Future<?> registration =
+          pool.submit(() -> 
tsFileResourceManager.registerSealedTsFileResource(registering));
+      assertTrue(measured.await(10, TimeUnit.SECONDS));
+      Future<?> handles =
+          pool.submit(
+              () -> {
+                Assert.assertNotNull(queried.getExclusiveModFile());
+                Assert.assertNotNull(queried.getCompactionModFile());
+              });
+      handles.get(10, TimeUnit.SECONDS);
+      registering.setTimeIndex(new FileTimeIndex(1, 2));
+      resume.countDown();
+      registration.get(10, TimeUnit.SECONDS);
+      assertEquals(1, tsFileResourceManager.getDegradedTimeIndexNum());
+      assertEquals(
+          registeredSize(queried) + registeredSize(registering),
+          tsFileResourceManager.getTotalTimeIndexMemCost());
+    } finally {
+      resume.countDown();
+      pool.shutdownNow();
+      assertTrue(pool.awaitTermination(10, TimeUnit.SECONDS));
+    }
+  }
+
+  @Test
+  public void testRegistrationRemeasuresResizedDeviceIndex() {
+    tsFileResourceManager.setTimeIndexMemoryThreshold(Long.MAX_VALUE);
+    TsFileResource resource = new TsFileResource(new 
File("target/0-53-0-0.tsfile"));
+    ArrayDeviceTimeIndex index = spy(new ArrayDeviceTimeIndex());
+    resource.setTimeIndex(index);
+    
resource.updateStartTime(IDeviceID.Factory.DEFAULT_FACTORY.create("root.test.d"),
 1);
+    resource.setStatus(TsFileResourceStatus.NORMAL);
+    doAnswer(
+            call -> {
+              long bytes = (long) call.callRealMethod();
+              // Trim both arrays without changing the index identity or 
device count.
+              index.close();
+              return bytes;
+            })
+        .doCallRealMethod()
+        .when(index)
+        .calculateRamSize();
+    tsFileResourceManager.registerSealedTsFileResource(resource);
+    assertEquals(registeredSize(resource), 
tsFileResourceManager.getTotalTimeIndexMemCost());
+  }
+
+  @Test
+  public void testRegistrationRechecksFileOwnershipAfterMeasurement() {
+    tsFileResourceManager.setTimeIndexMemoryThreshold(Long.MAX_VALUE);
+    File target = new File("target/0-55-0-0.tsfile");
+    TsFileResource owner = new TsFileResource(target.getAbsoluteFile());
+    TsFileResource moving = new TsFileResource(new 
File("target/0-54-0-0.tsfile"));
+    ArrayDeviceTimeIndex index = spy(new ArrayDeviceTimeIndex());
+    moving.setTimeIndex(index);
+    doAnswer(
+            call -> {
+              long bytes = (long) call.callRealMethod();
+              moving.setFile(target);
+              tsFileResourceManager.registerSealedTsFileResource(owner);
+              return bytes;
+            })
+        .when(index)
+        .calculateRamSize();
+
+    tsFileResourceManager.registerSealedTsFileResource(moving);
+    Assert.assertNull(moving.getMemoryRegistration());
+    assertEquals(1, tsFileResourceManager.getPriorityQueueSize());
+    assertEquals(registeredSize(owner), 
tsFileResourceManager.getTotalTimeIndexMemCost());
+  }
+
+  @Test
+  public void testBudgetDegradationStopsOnDetachedRegistration() {
+    tsFileResourceManager.setTimeIndexMemoryThreshold(Long.MAX_VALUE);
+    TsFileResource orphan = spy(new TsFileResource(new 
File("target/0-61-0-0.tsfile")));
+    tsFileResourceManager.registerSealedTsFileResource(orphan);
+    orphan.setMemoryRegistration(null);
+    // Fail immediately if the manager attempts a swap whose callback cannot 
release this charge.
+    doThrow(new AssertionError("attempted to degrade a detached registration"))
+        .when(orphan)
+        .replaceDeviceTimeIndexWithFileTimeIndex();
+    tsFileResourceManager.setTimeIndexMemoryThreshold(0);
+    TsFileResource other = new TsFileResource(new 
File("target/0-62-0-0.tsfile"));
+    tsFileResourceManager.registerSealedTsFileResource(other);
+    verify(orphan, never()).replaceDeviceTimeIndexWithFileTimeIndex();
+    tsFileResourceManager.removeTsFileResource(orphan);
+    tsFileResourceManager.removeTsFileResource(other);
+    assertEquals(0, tsFileResourceManager.getTotalTimeIndexMemCost());
+  }
 }
diff --git 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/MemUtilsTest.java 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/MemUtilsTest.java
index 9bdbba74c09..9b6eb588b11 100644
--- 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/MemUtilsTest.java
+++ 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/MemUtilsTest.java
@@ -29,6 +29,7 @@ import org.apache.tsfile.enums.TSDataType;
 import org.apache.tsfile.file.metadata.IDeviceID;
 import org.apache.tsfile.utils.Binary;
 import org.apache.tsfile.utils.BytesUtils;
+import org.apache.tsfile.utils.RamUsageEstimator;
 import org.apache.tsfile.write.record.TSRecord;
 import org.apache.tsfile.write.record.datapoint.BooleanDataPoint;
 import org.apache.tsfile.write.record.datapoint.DataPoint;
@@ -39,13 +40,43 @@ import 
org.apache.tsfile.write.record.datapoint.LongDataPoint;
 import org.apache.tsfile.write.record.datapoint.StringDataPoint;
 import org.apache.tsfile.write.schema.MeasurementSchema;
 import org.junit.Assert;
+import org.junit.Assume;
 import org.junit.Test;
 
+import javax.management.ObjectName;
+
+import java.io.File;
+import java.lang.management.ManagementFactory;
+import java.lang.reflect.Field;
 import java.util.ArrayList;
 import java.util.List;
 
 public class MemUtilsTest {
 
+  @Test
+  public void testFilePathRamBytes() throws Exception {
+    Assert.assertEquals(0, MemUtils.getFilePathRamBytes(null));
+    Assume.assumeTrue(
+        ManagementFactory.getPlatformMBeanServer()
+            .isRegistered(new 
ObjectName("com.sun.management:type=HotSpotDiagnostic")));
+    Field storage = String.class.getDeclaredField("value");
+    Assume.assumeTrue(storage.trySetAccessible());
+    for (String path :
+        new String[] {
+          "target/data/0123456789.tsfile",
+          "target/café/données.tsfile",
+          "target/数据/0123456789.tsfile"
+        }) {
+      long bytes =
+          RamUsageEstimator.shallowSizeOf(path)
+              + RamUsageEstimator.shallowSizeOf(storage.get(path));
+      Assert.assertEquals(bytes, MemUtils.getFilePathRamBytes(path));
+      File file = new File(path);
+      Assert.assertEquals(
+          RamUsageEstimator.shallowSizeOf(file) + bytes, 
MemUtils.getFileRamBytes(file));
+    }
+  }
+
   @Test
   public void getRecordSizeTest() {
     Assert.assertEquals(12, MemUtils.getRecordSize(TSDataType.INT32, 10, 
true));

Reply via email to