Skip to content

Fix LastFlushTimeMap degradation skipped during DataRegion recovery - #19545

Open
JackieTien97 wants to merge 5 commits into
masterfrom
ty/fix-recovery-last-flush-time-degrade
Open

JackieTien97 wants to merge 5 commits into
masterfrom
ty/fix-recovery-last-flush-time-degrade

Conversation

@JackieTien97

@JackieTien97 JackieTien97 commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Problem

During DataRegion construction/recovery (StorageEngine.buildNewDataRegion() -> new DataRegion(...) -> recover()), the DataRegion instance has not yet been inserted into StorageEngine.dataRegionMap.

When syncRecoverFilesInPartition() (or asyncRecoverFilesInPartition()) registers time partitions in TimePartitionManager and calls updateAfterFlushing(...), if timePartitionInfoMemoryBlock exceeds its memory threshold, TimePartitionManager.degradeLastFlushTime() executes:

  1. timePartitionInfoMemoryBlock.release(timePartitionInfo.memSize);
  2. DataRegion dataRegion = StorageEngine.getInstance().getDataRegion(timePartitionInfo.dataRegionId); — returns null during DataRegion construction!
  3. if (dataRegion != null) { dataRegion.degradeFlushTimeMap(timePartitionInfo.partitionId); ... } — skipped!
  4. timePartitionInfoMap.get(timePartitionInfo.dataRegionId).remove(timePartitionInfo.partitionId); — permanently removes the partition from tracking so it can never be degraded later either.

As a result, every recovered time partition leaks its full DeviceLastFlushTime map on the JVM heap during recovery. On memory-constrained deployments (e.g., 256 MB heap with 30,000 devices across many weekly time partitions), this causes an OOM crash during startup recovery.

Solution

  • Store a WeakReference<DataRegion> in TimePartitionInfo and pass this from every DataRegion call site. The weak reference means a region whose construction failed is not pinned in memory. The constructor without a region is now @TestOnly.
  • In TimePartitionManager.degradeLastFlushTime(), use the region stored in TimePartitionInfo first and only fall back to StorageEngine.getDataRegion(id). During snapshot load, the old region with the same id is still in StorageEngine while the new region recovers, so this order makes sure the new region is the one degraded.
  • Release and remove a TimePartitionInfo only after degradeFlushTimeMap succeeds. If it fails, keep the entry and its memory accounting so it can be degraded later. When registerTimePartitionInfo replaces an entry owned by another region that is still alive (the old region during snapshot load), it degrades that region's map before releasing its accounting.
  • Since recovering regions can now be degraded by other threads (data regions recover in parallel), HashLastFlushTimeMap runs every mutation of an ILastFlushTime and its memory cost inside partitionLatestFlushedTime.compute(partitionId, ...). This serializes mutations with the degradation's computeIfPresent, so there is no ConcurrentModificationException and no lost update to a replaced DeviceLastFlushTime.
  • When async recovery finishes on a partition that is already a PartitionLastFlushTime (recovered from FileTimeIndexCache or degraded), upgradeAndUpdateMultiDeviceFlushedTime now merges the recovered maximum into it instead of dropping it, and the partition stays degraded.

Verification

  • spotless:check, checkstyle:check, and a zh-locale compile pass. TimePartitionManagerTest (10), LastFlushTimeMapTest (11) and DataRegionTest (60) pass.
  • New tests: lookup order (unit test, and real recovery while the old region with the same id is still in StorageEngine), failed degradation, registration accounting, concurrent update/degrade, degradation on the real recovery path, replacing a region that is still alive (snapshot load), and async recovery finishing after degradation (inserting 150 after a restart where the seq file ends at 100 and the unseq file ends at 200 now goes to an unsequence file). Each new test fails without the change it covers.
  • Verified on a 256 MB heap Edge node recovering 469 TsFiles across 157 weekly time partitions (30,000 devices). Before this fix it ran out of memory at 73/469 TsFiles. With the fix, each partition degrades cleanly during recovery and all 469/469 TsFiles recover without OOM.

@codecov

codecov Bot commented Dec 5, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.36842% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 51.08%. Comparing base (c4e0c8b) to head (994ad6b).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
...storageengine/dataregion/HashLastFlushTimeMap.java 94.54% 3 Missing ⚠️
.../iotdb/db/storageengine/dataregion/DataRegion.java 80.00% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master   #19545      +/-   ##
============================================
+ Coverage     50.99%   51.08%   +0.09%     
  Complexity      145      145              
============================================
  Files          5797     5797              
  Lines        430347   430522     +175     
  Branches      57344    57390      +46     
============================================
+ Hits         219459   219945     +486     
+ Misses       210888   210577     -311     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@JackieTien97 JackieTien97 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The root-cause analysis is correct: release(memSize) + skipped degradeFlushTimeMap + permanent remove means the memory block believes the memory is freed while the DeviceLastFlushTime maps stay on the heap forever. Using a WeakReference to avoid pinning a half-constructed DataRegion also makes sense.

However, I think two issues should be addressed before merging (details inline):

  1. New concurrency exposure during parallel recovery. Data regions are recovered in parallel (StorageEngine.asyncRecover -> cachedThreadPool). Before this PR, a recovering region's partitions were never touched by other threads. With this PR, region A's recovery thread can degrade region B's partition while B is still populating its DeviceLastFlushTime (a plain HashMap). This may cause a ConcurrentModificationException (leaving TimePartitionManager accounting inconsistent and failing A's recovery) or lost updates (an under-estimated partition flush time, which can cause overlapping sequence files).
  2. Lookup order defeats the fix on the snapshot-load path. In StorageEngine.setDataRegionForSnapshotLoad, the old region with the same id is still in dataRegionMap while the new region is being constructed and recovered, so StorageEngine.getDataRegion(id) returns the old region and the new region's map is still never degraded.

Minor / out of scope (could be separate issues):

  • Leaking this from the constructor is safe here because lastFlushTimeMap is assigned before recover() and both registration and degradation synchronize on timePartitionInfoMap. A short comment, or making lastFlushTimeMap final (it is assigned only once), would make this explicit.
  • Pre-existing: HashLastFlushTimeMap.upgradeAndUpdateMultiDeviceFlushedTime builds newDeviceLastFlushTime in the PartitionLastFlushTime branch but never puts it back into partitionLatestFlushedTime (it only increases memCostForEachPartition), so the async-recovery "upgrade" is effectively a no-op.
  • Pre-existing: partitions are registered with memSize = lastFlushTimeMap.getMemSize(..), but that amount is never allocated in timePartitionInfoMemoryBlock (only the delta in updateAfterFlushing is), so the accounting can drift.

Long.MAX_VALUE,
lastFlushTimeMap.getMemSize(partitionId)));
lastFlushTimeMap.getMemSize(partitionId),
this));

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concurrency concern introduced by making recovering regions degradable.

Here the partition is registered (with memSize = 0) before the loop below populates its DeviceLastFlushTime (a plain HashMap). Data regions are recovered in parallel, so with this change the following interleaving becomes possible:

thread B (recovering region B, partition P)   thread A (recovering region A)
register(P, memSize=0, this)
updateMultiDeviceFlushedTime(P, ...)
  D.merge(dev_i, t) ... looping ...           updateAfterFlushing -> over threshold
                                              degradeLastFlushTime()
                                                picks B's P (inactive, small partitionId)
                                                B.degradeFlushTimeMap(P)
                                                  D.degradeLastFlushTime() iterates D.values()

Possible outcomes:

  • ConcurrentModificationException thrown in thread A. recover() only catches IOException, so A's region recovery fails, and TimePartitionManager is left with release() done but the entry not removed.
  • Lost updates: B keeps writing into the stale D after computeIfPresent has swapped in a PartitionLastFlushTime. The degraded partition flush time is then lower than the real max end time, so later writes in (degraded, real] may be classified as sequence, which can produce overlapping seq files.

In-progress partitions (memSize 0, small partitionId) are actually the first candidates in comparePriority, and degrading them frees nothing, so this window is easy to hit in exactly the memory-pressure scenario this PR targets. A single-region Edge setup does not exercise it.

Suggestions:

  • (a) Minimal: register only after the map is fully populated, so a partition never becomes a degradation candidate while this thread is still mutating it:
    boolean existed = lastFlushTimeMap.checkAndCreateFlushedTimePartition(partitionId, true);
    for (TsFileResource r : resourceList) {
      if (!r.isDeleted()) {
        updateDeviceLastFlushTime(r);
      }
    }
    if (!existed) {
      TimePartitionManager.getInstance()
          .registerTimePartitionInfo(
              new TimePartitionInfo(dataRegionId, partitionId, false, Long.MAX_VALUE, 0, this));
    }
    TimePartitionManager.getInstance()
        .updateAfterFlushing(
            dataRegionId, partitionId, System.currentTimeMillis(),
            lastFlushTimeMap.getMemSize(partitionId), false);
    Note that this does not cover recoverUnsealedTsFileCallBack -> updateDeviceLastFlushTime, or the DeviceLastFlushTime branch of upgradeAndUpdateMultiDeviceFlushedTime in the async tasks, which mutate already-registered partitions.
  • (b) More robust: in HashLastFlushTimeMap, perform every mutation of an ILastFlushTime inside partitionLatestFlushedTime.compute(partitionId, ...), so it is serialized per partition with degradeLastFlushTime's computeIfPresent. This would also close the pre-existing runtime race noted on degradeFlushTimeMap ("may not hold the write lock").

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 18d6d07 with option (b): every mutation of an ILastFlushTime in HashLastFlushTimeMap (updateMultiDeviceFlushedTime, upgradeAndUpdateMultiDeviceFlushedTime, updatePartitionFlushedTime, updateLatestFlushTime) and its memory-cost update now run inside partitionLatestFlushedTime.compute(partitionId, ...). degradeLastFlushTime runs inside computeIfPresent and resets the memory cost there too. Degradation can no longer iterate a DeviceLastFlushTime that is being modified, and no update goes into a stale DeviceLastFlushTime after it is replaced. Later updates go into the PartitionLastFlushTime and are merged by max. This also covers recoverUnsealedTsFileCallBack and the async upgrade path, plus the runtime "may not hold the write lock" race. checkAndCreateFlushedTimePartition now uses putIfAbsent. Also, a degraded partition no longer gains phantom memory cost from later device updates. New test: LastFlushTimeMapTest#testConcurrentUpdateAndDegrade, which fails on the previous commit with ConcurrentModificationException.

Comment on lines +132 to +134
if (dataRegion == null) {
dataRegion = timePartitionInfo.getDataRegion();
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd suggest preferring the reference stored in TimePartitionInfo and only falling back to StorageEngine when it is null:

DataRegion dataRegion = timePartitionInfo.getDataRegion();
if (dataRegion == null) {
  dataRegion = StorageEngine.getInstance().getDataRegion(timePartitionInfo.dataRegionId);
}

Reason: in StorageEngine.setDataRegionForSnapshotLoad, the old region with the same DataRegionId stays in dataRegionMap while newRegionSupplier.get() constructs and recovers the new region, and the old region's TimePartitionInfos are not removed (deleteFolder does not call removeTimePartitionInfo). The new region's register replaces those entries, but when one of them is picked here, StorageEngine.getDataRegion(id) returns the old region. The old region gets degraded instead, and the new region's map is never degraded. That is the same leak this PR fixes, only on the snapshot-load / region-migration path.

The stored reference always points to the region that actually owns the entry. If it points to a replaced region that is still alive, degrading it is harmless.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: degradeLastFlushTime() now uses timePartitionInfo.getDataRegion() first and only falls back to StorageEngine.getDataRegion(id) when it is null. Tests: TimePartitionManagerTest#testDegradePrefersRegisteredDataRegionOverStorageEngine, and LastFlushTimeMapTest#testDegradeDuringRecovery, which rebuilds the region on the real recovery path while the old region with the same id is still in StorageEngine.

dataRegion = timePartitionInfo.getDataRegion();
}
if (dataRegion != null) {
dataRegion.degradeFlushTimeMap(timePartitionInfo.partitionId);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Related to the concurrency comment on DataRegion#syncRecoverFilesInPartition: if degradeFlushTimeMap throws here (e.g. a ConcurrentModificationException from DeviceLastFlushTime.degradeLastFlushTime()), release(timePartitionInfo.memSize) above has already run but the entry is not removed below, so its memSize can be released again later. It might be worth making the release/remove pair robust to this (e.g. only release after a successful degrade, or use try/finally), independent of how the race itself is fixed.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: the entry is now released and removed only after degradeFlushTimeMap succeeds. If degradation throws, a warning is logged, the entry and its memory accounting stay as they are (so it can be degraded later), and the loop moves on to the next candidate. Test: TimePartitionManagerTest#testFailedDegradeKeepsTimePartitionInfoAndMemory. I also fixed the related accounting drift from the review summary: registerTimePartitionInfo now allocates the new entry's memSize minus the memSize of the entry it replaces (testRegisterAccountsMemoryOfReplacedTimePartitionInfo).

Comment on lines +144 to +146
Mockito.verify(mockDataRegion, Mockito.times(1)).degradeFlushTimeMap(10L);
Assert.assertNull(timePartitionManager.getTimePartitionInfo(dataRegionId, 10L));
Assert.assertNotNull(timePartitionManager.getTimePartitionInfo(dataRegionId, 11L));

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few test suggestions:

  • Also assert Mockito.verify(mockDataRegion, Mockito.never()).degradeFlushTimeMap(11L); so the test pins exactly which partition gets degraded.
  • If the lookup order is changed as suggested in TimePartitionManager, add a case where StorageEngine holds a different region with the same id, and verify that the region stored in TimePartitionInfo is the one degraded.
  • This test only covers the fallback in isolation. A test on the real recovery path would be more convincing: e.g. in DataRegionTest, set a small TimePartitionInfo memory threshold, create TsFiles across several partitions, re-construct the DataRegion, and assert that the early partitions are degraded (getLastFlushTimeMap().getMemSize(p) == Long.BYTES).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All three are added: (1) verify(..., never()).degradeFlushTimeMap(11L); (2) testDegradePrefersRegisteredDataRegionOverStorageEngine, where StorageEngine holds a different region with the same id; (3) LastFlushTimeMapTest#testDegradeDuringRecovery, which creates TsFiles in 3 partitions, sets a one-device memory threshold, re-constructs the DataRegion, and asserts that partitions 0 and 1 are degraded (getMemSize == Long.BYTES) with flush times kept, while partition 2 keeps its device-level map.

boolean isActive,
long lastSystemFlushTime,
long memsize) {
this(dataRegionId, partitionId, isActive, lastSystemFlushTime, memsize, null);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: after this PR, no main code uses the 5-argument constructor anymore (all call sites in DataRegion pass this). Consider marking it @TestOnly, or removing it and passing null in tests, so new production call sites don't silently lose the fallback reference.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Marked the 5-argument constructor @TestOnly and added a Javadoc note that production code must pass the owning DataRegion.

@JackieTien97 JackieTien97 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I verified the write-routing impact of the async-upgrade observation in the earlier review. The inline comment includes the base and PR results for the same restart.

DataRegion dataRegion =
StorageEngine.getInstance().getDataRegion(timePartitionInfo.dataRegionId);
if (dataRegion == null) {
dataRegion = timePartitionInfo.getDataRegion();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve the partition maximum when async recovery finishes after degradation

I reproduced this with three sealed TsFiles in one DataRegion. In partition 0, a sequence file ends at 100 and an unsequence file for the same device ends at 200. Only the unsequence file has a FileTimeIndexCache entry. With a 300-byte time-partition memory budget, recovering partition 1 triggers this fallback and degrades partition 0 before its queued recovery task runs. upgradeAndUpdateMultiDeviceFlushedTime() then computes 200 and leaves the live PartitionLastFlushTime at 100.

After async recovery finished, inserting 150 opened an unsequence writer on the base (c4e0c8b6) and a sequence writer on this commit (bbae646e). Please merge the recovered maximum into the live partition value while keeping the map degraded, and cover the 150 write in a single-region restart test.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed: when the partition is already a PartitionLastFlushTime (recovered from FileTimeIndexCache, or degraded), upgradeAndUpdateMultiDeviceFlushedTime keeps it degraded and merges the recovered maximum into the live value. It no longer adds memory cost for a device map that is never stored. Added your scenario as a single-region restart test, LastFlushTimeMapTest#testAsyncRecoveryAfterDegradeKeepsPartitionMaximum: the seq file ends at 100, the unseq file ends at 200 and is the only file in the FileTimeIndexCache, and recovering partition 1 degrades partition 0 under a one-device budget. After the async task runs, the partition flush time is 200, the memory cost stays Long.BYTES, and inserting 150 opens an unsequence writer. With only this change reverted, the test fails with expected:<200> but was:<100>.

- HashLastFlushTimeMap: perform every mutation of an ILastFlushTime (and of
  its memory cost) inside partitionLatestFlushedTime.compute(partitionId, ...),
  so it is serialized with the degradation (computeIfPresent). This avoids
  ConcurrentModificationException and lost updates when another DataRegion's
  recovery thread degrades a partition that is still being recovered.
- upgradeAndUpdateMultiDeviceFlushedTime: when the partition is already a
  PartitionLastFlushTime (recovered from FileTimeIndexCache or degraded), keep
  it degraded but merge the recovered maximum into it, instead of dropping it.
- TimePartitionManager: prefer the DataRegion stored in TimePartitionInfo and
  only fall back to StorageEngine, so that a new region replacing an old one
  with the same id (snapshot load) is the one degraded; release/remove the
  entry only after a successful degradation; account the memory of an entry
  replaced by registerTimePartitionInfo.
- Mark the TimePartitionInfo constructor without DataRegion as @testonly and
  make DataRegion#lastFlushTimeMap final.
- Add tests for the lookup order, failed degradation, registration
  accounting, concurrent update/degrade, degradation on the real recovery
  path, and async recovery finishing after degradation.
@JackieTien97

Copy link
Copy Markdown
Contributor Author

Addressed all review comments in 18d6d07 (replies are in each thread). From the review summary:

  • Concurrency during parallel recovery: fixed by serializing all ILastFlushTime mutations per partition with compute.
  • Lookup order on the snapshot-load path: the stored region is now preferred.
  • Leaking this from the constructor: lastFlushTimeMap is now final, with a comment on why publishing this during recover() is safe.
  • Async upgrade is a no-op: the PartitionLastFlushTime branch now merges the recovered maximum and keeps the partition degraded.
  • Registration memory drift: registerTimePartitionInfo now accounts memSize minus the memSize of the replaced entry.

@JackieTien97 JackieTien97 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I rechecked 18d6d078ff against c4e0c8b6. The earlier parallel recovery, async recovery, and snapshot owner cases now pass. I would address the two regressions below before merging.

// Account the memory of the registered partition, and release the memory of the entry it
// replaces (e.g. an entry of a replaced DataRegion with the same id), so that the memory
// block stays consistent with the memSize of the registered entries.
long memSizeDelta = timePartitionInfo.memSize - (previous == null ? 0 : previous.memSize);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Keep the old flush-time map accounted for during snapshot replacement

setDataRegionForSnapshotLoad() keeps the old region in StorageEngine until the replacement finishes recovery. Subtracting previous.memSize when the replacement registers the same partition makes that budget available again while the old device map is still live.

I loaded a snapshot with 1,000 devices into a region that already had 1,000 devices in the same partition, with a 309,000-byte budget. Immediately before the swap, getMemSize(0) reported 206,000 bytes on each region (412,000 combined), while the manager accounted for 206,000 bytes. On the base commit the old map had degraded to 8 bytes, leaving 206,008 bytes combined.

Please keep the old map charged until it is released or degraded. A regression test can check the combined size while the old region is still registered and the replacement has finished loading.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in fe13f4c. When registerTimePartitionInfo replaces an entry owned by a different DataRegion that is still alive (the old region kept in StorageEngine during setDataRegionForSnapshotLoad), it now calls the old region's degradeFlushTimeMap(partition) and only then releases the old entry's accounting. If that degradation throws, the old memory stays accounted. Entries re-registered by the same region, or whose region has already been garbage collected, are released as before. In your scenario the combined size before the swap is again memSize + Long.BYTES, same as the base commit.

Regression tests:

  • LastFlushTimeMapTest#testReplacementRegionDegradesOldRegionMap: recovers an old region from disk, registers it in StorageEngine, then recovers the replacement while the old region is still registered. It asserts old getMemSize(0) == Long.BYTES, flush time kept, and the replacement holds the full map. With only this change reverted it fails with expected:<8> but was:<2060>.
  • TimePartitionManagerTest#testReplacedByAnotherRegionDegradesOldRegion, #testReplacedRegionKeepsAccountedIfDegradeFails, #testReRegisteredBySameRegionDoesNotDegrade.

return partitionLatestFlushedTime.putIfAbsent(
timePartitionId,
usingDeviceFlushTime
? new DeviceLastFlushTime()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Avoid allocating a device map on every partition hit

DataRegion.initFlushTimeMap() calls this method for each single-row insert when sequence separation is enabled. Java constructs DeviceLastFlushTime and its backing HashMap before putIfAbsent can return the existing entry. In a warmed-up loop of 2,000,000 hits on eight existing partitions, both JDK 17 and 21 allocated 128,000,000 extra bytes relative to the base commit (64 bytes per hit).

Please return early when the key already exists, then construct the value and use putIfAbsent on a miss. This keeps creation atomic when two threads encounter a new partition together.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in fe13f4c: checkAndCreateFlushedTimePartition returns early on containsKey, and constructs the value plus putIfAbsent only on a miss, so creation stays atomic when threads hit a new partition together.

…tion hits

- TimePartitionManager#registerTimePartitionInfo: when the replaced entry
  belongs to another DataRegion with the same id that is still alive (e.g. the
  old region kept in StorageEngine during snapshot loading), degrade its
  LastFlushTimeMap before releasing its accounting. If the degradation fails,
  keep the memory accounted. Entries re-registered by the same region, or
  whose region has been garbage collected, are released as before.
- HashLastFlushTimeMap#checkAndCreateFlushedTimePartition: return early when
  the partition exists, and only construct the value and putIfAbsent on a
  miss, so that each insertion no longer allocates a DeviceLastFlushTime.

@JackieTien97 JackieTien97 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I rechecked fe13f4c921. Snapshot replacement and allocation on existing-partition writes now match the base commit in the earlier reproductions. One cleanup case remains when degradation of the old region throws.

previous.dataRegionId,
previous.partitionId,
e);
return false;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Retain a way to release the old partition's memory charge after degradation fails

By the time this returns false, registerTimePartitionInfo() has overwritten previous in the partition map. Its memory stays charged while the old owner is live, but neither the next eviction pass nor removeTimePartitionInfo() can find the old entry to retry degradation or release the charge.

I injected an exception on the old region's first degradeFlushTimeMap(0) call. After removing the region and confirming through a weak reference that the old owner had been collected, the manager had zero tracked regions and still reported 206 bytes used. With a 309-byte budget it then degraded an unrelated region's 206-byte device map to 8 bytes. Without the injected failure, the count returned to zero and the unrelated map stayed at 206 bytes.

Please keep the replaced entry available for cleanup until degradation succeeds or its owner is collected, and release its charge exactly once. Extending testReplacedRegionKeepsAccountedIfDegradeFails through region removal and registration of an unrelated partition would cover the full lifecycle.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b851162. If degrading the old region fails, registerTimePartitionInfo now keeps the replaced entry in TimePartitionManager#replacedTimePartitionInfos, still charged, and releases its charge exactly once:

  • the next eviction pass retries degrading replaced entries before the registered ones, and releases an entry once its map is degraded. The StorageEngine fallback is not used for them, because the region registered there is the replacement;
  • an entry is released once its DataRegion has been garbage collected (checked in updateAfterFlushing and during eviction);
  • removeTimePartitionInfo(id) releases the replaced entries of that region id.

Tests in TimePartitionManagerTest:

  • testReplacedRegionKeepsAccountedIfDegradeFails now continues through region removal (used memory goes back to 0) and registers an unrelated partition, which is not degraded.
  • testReplacedRegionIsDegradedByLaterEviction: degradation fails once and succeeds on the next eviction, before any unrelated partition is touched.
  • testReplacedRegionIsReleasedAfterCollected: the old owner is collected (checked with a weak reference), and its charge is released without degrading other partitions.

All three fail on fe13f4c (e.g. expected:<0> but was:<60>).

…eased

When registerTimePartitionInfo replaces an entry of another live region and
fails to degrade its LastFlushTimeMap, the entry was overwritten in the
partition map while its memory stayed charged, so it could never be degraded
or released again.

Keep such entries in TimePartitionManager#replacedTimePartitionInfos, still
charged, and release each of them exactly once:
- an eviction pass retries degrading them before the registered entries, and
  releases them once degraded;
- they are released when their DataRegion has been garbage collected;
- removeTimePartitionInfo releases the replaced entries of the region id.
@sonarqubecloud

sonarqubecloud Bot commented Dec 5, 2026

Copy link
Copy Markdown

@shihchengwei-lab

shihchengwei-lab commented Dec 5, 2026 •

Copy link
Copy Markdown

The global eviction TreeSet can silently drop a recovered partition from another DataRegion, so this fix can still return with the last-flush-time memory above its limit. At b851162, the following method can be pasted into TimePartitionManagerTest; it expects both 60-byte entries to be degraded under a 50-byte limit, but fails with expected:<0> but was:<60> and leaves one entry registered.

@Test
public void testEqualPriorityAcrossDataRegions() {
  DataRegionId firstId = new DataRegionId(1001);
  DataRegionId secondId = new DataRegionId(1002);
  DataRegion firstRegion = Mockito.mock(DataRegion.class);
  DataRegion secondRegion = Mockito.mock(DataRegion.class);

  timePartitionManager.setTimePartitionInfoMemoryThreshold(1_000L);
  timePartitionManager.registerTimePartitionInfo(
      new TimePartitionInfo(firstId, 10L, false, Long.MAX_VALUE, 0L, firstRegion));
  timePartitionManager.registerTimePartitionInfo(
      new TimePartitionInfo(secondId, 10L, false, Long.MAX_VALUE, 0L, secondRegion));
  timePartitionManager.updateAfterFlushing(firstId, 10L, 100L, 60L, false);
  timePartitionManager.updateAfterFlushing(secondId, 10L, 100L, 60L, false);

  timePartitionManager.setTimePartitionInfoMemoryThreshold(50L);
  timePartitionManager.updateAfterFlushing(firstId, 10L, 100L, 60L, false);

  Assert.assertEquals(
      0L, timePartitionManager.timePartitionInfoMemoryBlock.getUsedMemoryInBytes());
  Assert.assertNull(timePartitionManager.getTimePartitionInfo(firstId, 10L));
  Assert.assertNull(timePartitionManager.getTimePartitionInfo(secondId, 10L));
}

comparePriority() only compares active state, partition ID, and flush time, so TreeSet treats these distinct (dataRegionId, partitionId) entries as the same element. Normal parallel recovery can produce this because both sync and async recovery use shared partition IDs plus millisecond-resolution System.currentTimeMillis(), while the current multi-region test avoids the collision with timestamps 100 through 104. Although the comparator predates this PR, this case is within its stated recovery-OOM fix. Could you add dataRegionId as the final tie-breaker and cover two regions with identical priority keys?

AI assistance: inspected the fixed-head code paths, generated the reproduction, and drafted this comment.

…on candidates

comparePriority() only compared the active state, the partition id and the
last flush time, so the TreeSet used by degradeLastFlushTime() treated entries
of different DataRegions with the same partition id and flush time (common
when regions are recovered in parallel within one millisecond) as one element
and silently dropped the others, leaving the memory above the limit.

Add the data region id as the final tie-breaker. Also split
degradeLastFlushTime() into smaller methods without changing its behavior,
and shorten two new i18n constant names to keep lines within 100 chars.
@JackieTien97

Copy link
Copy Markdown
Contributor Author

@shihchengwei-lab Thanks, good catch. Fixed in 994ad6b: TimePartitionInfo#comparePriority now uses the data region id as the final tie-breaker, so the eviction TreeSet keeps entries of different regions that share the partition id and flush time. Your reproduction is now TimePartitionManagerTest#testEqualPriorityAcrossDataRegions, which also verifies that both regions are degraded. testComparePriorityTieBreaksByDataRegion checks the comparator directly. Both fail if the tie-breaker is removed.

The same commit also addresses the SonarCloud findings: degradeLastFlushTime() is split into smaller methods with no behavior change, and two new i18n constant names are shortened so the lines stay within 100 characters.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants