Skip to content

Fix LastFlushTimeMap degradation skipped during DataRegion recovery - #19545

Merged
JackieTien97 merged 7 commits into
masterfrom
ty/fix-recovery-last-flush-time-degrade
Dec 6, 2026
Merged

JackieTien97 merged 7 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 95.98214% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 51.09%. Comparing base (c4e0c8b) to head (329d7bc).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
.../iotdb/db/storageengine/dataregion/DataRegion.java 85.71% 6 Missing ⚠️
...storageengine/dataregion/HashLastFlushTimeMap.java 96.42% 2 Missing ⚠️
...rageengine/rescon/memory/TimePartitionManager.java 99.04% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master   #19545      +/-   ##
============================================
+ Coverage     50.99%   51.09%   +0.09%     
  Complexity      145      145              
============================================
  Files          5797     5797              
  Lines        430347   430554     +207     
  Branches      57344    57394      +50     
============================================
+ Hits         219459   219981     +522     
+ Misses       210888   210573     -315     

☔ 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.
@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.

@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.

Reviewed 994ad6bb5d for correctness, concurrency safety, and performance impact. Steady-state insert and flush hot paths look good, and the lock hierarchy (DataRegion.writeLock -> TimePartitionManager.timePartitionInfoMap -> partitionLatestFlushedTime bin -> memCostForEachPartition bin) is cycle-free.

Left 4 inline comments covering remaining recovery/concurrency bugs and a recovery-path performance/logging regression that should be addressed before merging.

Comment on lines +120 to +128
lastFlushTime == null ? new PartitionLastFlushTime(maxFlushedTime) : lastFlushTime;
if (flushTimeMapForPartition instanceof PartitionLastFlushTime) {
flushTimeMapForPartition.updateLastFlushTime(null, maxFlushedTime);
memCostForEachPartition.putIfAbsent(id, (long) Long.BYTES);
}
// Otherwise the DeviceLastFlushTime was recovered by wal recovery or sync recovery, and
// the device flush times of these resources are merged into it by
// upgradeAndUpdateMultiDeviceFlushedTime after the async recovery.
return flushTimeMapForPartition;

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] Degrade existing DeviceLastFlushTime in updatePartitionFlushedTime and avoid async-recovery data races / unaccounted growth

In DataRegion.recover(), partitionTmpSeqTsFiles is recovered before partitionTmpUnseqTsFiles. When a partition has at least one sync-recovered sequence file (creating a DeviceLastFlushTime) and at least one async-recovered unsequence file in FileTimeIndexCache, skipping maxFlushedTime here causes three coupled issues:

  1. Seq/unseq misrouting before async recovery completes: StorageEngine.start() sets isReadyForReadAndWrite = true before launching asyncRecoverTsFileResource(). Until the async task runs, getFlushedTime ignores the FileTimeIndexCache maximum (this is visible in LastFlushTimeMapTest#testAsyncRecoveryAfterDegradeKeepsPartitionMaximum, where getFlushedTime(0, device) is 100L instead of 200L right after DummyDataRegion recovery). A client write at timestamp 150 arriving in that window sees 100L and is routed to a sequence writer.
  2. Unaccounted memory & bypassed degradation: If the partition was not degraded during recover() (e.g., the sync-recovered seq file had only one device), upgradeAndUpdateMultiDeviceFlushedTime (lines 98–108) enters the else branch and populates DeviceLastFlushTime with all devices from the async-recovered files, but DataRegion.asyncRecoverFilesInPartition's Callable never calls TimePartitionManager.updateAfterFlushing(...).
  3. Data races with concurrent inserts: asyncRecoverTsFileResource() runs in background threads without DataRegion.writeLock, while insert* threads call getFlushedTime() via lock-free partitionLatestFlushedTime.get(id).getLastFlushTime(device). Mutating/resizing DeviceLastFlushTime's plain HashMap in the else branch races with HashMap.containsKey/get, and mutating non-volatile PartitionLastFlushTime.partitionLastFlushTime in lines 95–97 races with getLastFlushTime.

Suggested fix:

  • In updatePartitionFlushedTime, degrade an existing DeviceLastFlushTime via lastFlushTime.degradeLastFlushTime(), merge maxFlushedTime, and set memCostForEachPartition to Long.BYTES (since per-device end times of async files are unknown until .resource files are read).
  • Make PartitionLastFlushTime.partitionLastFlushTime volatile.
  • In DataRegion.upgradeAndUpdateDeviceLastFlushTime, avoid building a full temporary HashMap<IDeviceID, Long> endTimeMap when the partition is already a PartitionLastFlushTime (resource.getTimeIndex().getMaxEndTime() gives the max in O(1) without extra heap churn during parallel async recovery), and call updateAfterFlushing if a DeviceLastFlushTime can still grow.

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 6be390d:

  • HashLastFlushTimeMap#updatePartitionFlushedTime now degrades any existing DeviceLastFlushTime via lastFlushTime.degradeLastFlushTime(), merges maxFlushedTime, and sets memCostForEachPartition to Long.BYTES inside compute(). asyncRecoverFilesInPartition then updates TimePartitionManager via updateAfterFlushing with Long.BYTES.
  • PartitionLastFlushTime.partitionLastFlushTime is now volatile so lock-free getFlushedTime() reads from insert threads observe async-recovery updates without data races.
  • DataRegion#upgradeAndUpdateDeviceLastFlushTime checks lastFlushTimeMap.isPartitionLastFlushTime(timePartitionId) and merges resource.getTimeIndex().getMaxEndTime() in O(1) without allocating a temporary HashMap<IDeviceID, Long>. In the fallback DeviceLastFlushTime branch, it takes writeLock (preserving the lock hierarchy writeLock -> TimePartitionManager -> partitionLatestFlushedTime -> memCostForEachPartition) and calls TimePartitionManager.updateAfterFlushing(...).

Tests in LastFlushTimeMapTest:

  • Updated testAsyncRecoveryAfterDegradeKeepsPartitionMaximum to assert getFlushedTime(0, device) == 200L and unsequence routing for 150 immediately after DummyDataRegion recovery (before async tasks run), as well as after async recovery.
  • Added testUpdatePartitionFlushedTimeDegradesExistingDeviceMapWithoutEviction (large budget, sync seq + async unseq in partition 0: verifies immediate degradation to Long.BYTES and TimePartitionManager accounting staying Long.BYTES before and after async tasks) and testUpgradeOnPartitionLastFlushTimeUsesTimeIndexWithoutDeviceScan (verifies resource.getDevices() is never called).

Comment on lines 838 to 842
lastFlushTimeMap.getMemSize(latestPartitionId),
this));
}
}
// wait until all unsealed TsFiles have been recovered

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] Account/degrade WAL-recovered unsealed TsFiles and avoid stale-memSize TOCTOU re-registration on latestPartitionId

Two recovery gaps remain around these lines:

  1. Unsealed TsFiles recovered right below (in recoverUnsealedTsFileCallBack): UnsealedTsFileRecoverPerformer.endRecovery() closes every recovered unsealed file (!recoverPerformer.canWrite()), and recoverUnsealedTsFileCallBack calls updateDeviceLastFlushTime(tsFileResource) without calling checkAndCreateFlushedTimePartition + registerTimePartitionInfo(..., this) or TimePartitionManager.updateAfterFlushing(...). On crash/OOM recovery, partitions that only had unsealed TsFiles (whose sealed file lists were emptied earlier in recover()) are never registered unless they happen to be latestPartitionId, and even latestPartitionId never updates its memSize or triggers degradeLastFlushTime() after unsealed files populate its DeviceLastFlushTime.
  2. TOCTOU race on lastFlushTimeMap.getMemSize(latestPartitionId) (line 838): getMemSize(latestPartitionId) is evaluated before entering synchronized (timePartitionInfoMap) in registerTimePartitionInfo. During parallel region recovery, another thread can degrade (this, latestPartitionId) to Long.BYTES, release its memory, and remove it from timePartitionInfoMap before this thread acquires the monitor. registerTimePartitionInfo then sees previous == null and re-charges the pre-degradation memSize (without checking isMemoryExceeded()) for a partition whose map is already 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.

Fixed in 6be390d:

  • recoverUnsealedTsFileCallBack now registers and accounts WAL-recovered unsealed TsFiles via updateAndRegisterDeviceLastFlushTime() (checkAndCreateFlushedTimePartition + registerTimePartitionInfo(..., 0, this) + updateDeviceLastFlushTime + updateAfterFlushing), and calls initFlushTimeMap in the canWrite() branch as well.
  • Removed the redundant latestPartitionId re-registration block in DataRegion#recover() (all partitions with sealed files are already registered in asyncRecoverFilesInPartition/syncRecoverFilesInPartition, and unsealed-only partitions are now registered in recoverUnsealedTsFileCallBack), eliminating the stale-memSize TOCTOU race and preventing already-degraded partitions from being re-registered. Also updated the remaining newly-created-partition registerTimePartitionInfo sites in DataRegion to pass 0 directly.

Tests in LastFlushTimeMapTest:

  • testUnsealedTsFileRecoveryRegistersAndDegradesPartitions (end-to-end WAL recovery of two unsealed-only partitions under a 1-device budget: partition 0 is degraded to Long.BYTES and evicted, partition 1 is registered and accounted in TimePartitionManager).
  • testSingleOversizedPartitionStaysDegradedAfterRecovery (single oversized partition stays degraded and un-registered with 0 used memory after recover()).

Comment on lines +262 to +265
DataRegion dataRegion = timePartitionInfo.getDataRegion();
if (dataRegion == null) {
dataRegion = StorageEngine.getInstance().getDataRegion(timePartitionInfo.dataRegionId);
}

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] Distinguish a garbage-collected owner from @TestOnly null owner, and sweep collected entries in timePartitionInfoMap before evicting live partitions

  1. Wrong-region fallback: timePartitionInfo.getDataRegion() returns null both when dataRegionRef == null (@TestOnly 5-arg constructor) and when dataRegionRef != null && dataRegionRef.get() == null (the owning DataRegion was garbage collected — e.g., failed mid-recovery, or oldRegion after setDataRegionForSnapshotLoad had older/TTL-expired partitions absent from the loaded snapshot so they stayed in timePartitionInfoMap). In the latter case, falling back to StorageEngine.getInstance().getDataRegion(...) resolves to the replacement DataRegion with the same DataRegionId and degrades the wrong region's partition.
  2. Phantom memory in timePartitionInfoMap evicts live partitions: releaseCollectedReplacedTimePartitionInfos() only sweeps replacedTimePartitionInfos, not timePartitionInfoMap. If a failed/old GC'd region left (region1, partition=100) (240 bytes) in timePartitionInfoMap, and a live region flushes (region2, partition=50) (200 bytes) under a 350-byte threshold, comparePriority orders partition 50 before partition 100 and degrades the live (region2, 50) map even though live usage is 200 <= 350.

Please distinguish dataRegionRef == null vs dataRegionRef.get() == null on TimePartitionInfo (never falling back to StorageEngine when dataRegionRef != null), and release/remove collected entries while iterating timePartitionInfoMap in degradeLastFlushTime() (lines 217–220) before evicting live entries.

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 6be390d:

  • Added TimePartitionInfo#hasDataRegionRef() and isDataRegionCollected() to distinguish the @TestOnly 5-arg constructor (dataRegionRef == null) from a garbage-collected owner (dataRegionRef != null && dataRegionRef.get() == null). degradeTimePartitionInfo() never falls back to StorageEngine when hasDataRegionRef() is true.
  • In degradeLastFlushTime(), collectLiveTimePartitionInfosAndReleaseCollected() sweeps collected entries out of timePartitionInfoMap (releasing their memory and pruning empty region maps) before evicting any live partition, and degradeLastFlushTime() also returns early if retrying replacedTimePartitionInfos already brought memory within budget.

Tests in TimePartitionManagerTest:

  • testCollectedOwnerInMapReleasedWithoutEvictingLiveOrFallingBackToStorageEngine: reproduces the exact 240 + 200 under 350-byte threshold scenario with a replacement region in StorageEngine and asserts neither the replacement region nor the live lower-partitionId region is degraded, collected entry is removed, and used memory is 200.
  • testLegacyNullDataRegionRefFallsBackToStorageEngine: verifies the @TestOnly 5-arg constructor still falls back to StorageEngine.

Comment on lines +268 to +289
dataRegion.degradeFlushTimeMap(timePartitionInfo.partitionId);
} catch (RuntimeException e) {
// The LastFlushTimeMap is not degraded, so its memory is still occupied. Keep the entry
// and its memory accounting, it can be degraded again later.
logger.warn(
StorageEngineMessages.STORAGE_LOG_FAILED_TO_DEGRADE_LASTFLUSHTIMEMAP_OF_2B2924D0,
timePartitionInfo.dataRegionId,
timePartitionInfo.partitionId,
e);
return false;
}
}
timePartitionInfoMemoryBlock.release(timePartitionInfo.memSize);
if (dataRegion != null) {
logger.info(
StorageEngineMessages
.STORAGE_LOG_DEGRADE_LASTFLUSHTIMEMAP_OF_OLD_TIMEPARTITIONINFO_MEM_SIZE_BED053EE,
timePartitionInfo.dataRegionId,
timePartitionInfo.partitionId,
timePartitionInfo.memSize,
timePartitionInfoMemoryBlock.getUsedMemoryInBytes());
}

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] Skip redundant degradation and INFO log storms under the global monitor for already-degraded FileTimeIndexCache partitions

On master, StorageEngine.getDataRegion(...) returned null during recover(), so evicting historical partitions neither called degradeFlushTimeMap nor emitted INFO logs. With dataRegion now non-null during recover(), all historical partitions registered by asyncRecoverFilesInPartition (FileTimeIndexCache) already hold a PartitionLastFlushTime (memSize == 8), yet when a newer sync-recovered partition exceeds the threshold, degradeLastFlushTime() polls every historical 8-byte partition in ascending partitionId order while holding synchronized (timePartitionInfoMap), running a no-op computeIfPresent + memCostForEachPartition.put and synchronously writing an INFO log line (mem size is 8) for each one.

Consider having degradeFlushTimeMap / degradeLastFlushTime(partitionId) return boolean (true only when a DeviceLastFlushTime was actually degraded to PartitionLastFlushTime) so already-degraded partitions avoid redundant map writes and INFO log amplification under the global lock.

(Minor: guarding releaseCollectedReplacedTimePartitionInfos() at line 188 with if (replacedTimePartitionInfos.isEmpty()) return; and HashLastFlushTimeMap.updateMultiDeviceFlushedTime at line 60 with if (flushedTimeMap.isEmpty()) return; also avoids unnecessary work on empty inputs.)

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 6be390d:

  • ILastFlushTimeMap#degradeLastFlushTime(long) and DataRegion#degradeFlushTimeMap(long) now return boolean (true only when a DeviceLastFlushTime was actually degraded to PartitionLastFlushTime). HashLastFlushTimeMap#degradeLastFlushTime fast-paths absent or already-degraded partitions via a lock-free get() check before entering computeIfPresent.
  • TimePartitionManager only logs the INFO degradation message when degradeFlushTimeMap returns true (while still releasing memory and removing the entry).
  • Added the empty-input early-return guards in releaseCollectedReplacedTimePartitionInfos(), HashLastFlushTimeMap#updateMultiDeviceFlushedTime, and upgradeAndUpdateMultiDeviceFlushedTime.

Test: LastFlushTimeMapTest#testDegradeLastFlushTimeReturnsBoolean.

…ep, and no-op degrade logs

- HashLastFlushTimeMap#updatePartitionFlushedTime: degrade an existing
  DeviceLastFlushTime (e.g. from sync-recovered seq files in the same
  partition) to PartitionLastFlushTime, merge maxFlushedTime, and set
  memCostForEachPartition to Long.BYTES so concurrent writes arriving before
  async recovery finishes see the FileTimeIndexCache max and async recovery
  cannot grow DeviceLastFlushTime unaccounted.
- PartitionLastFlushTime: make partitionLastFlushTime volatile for lock-free
  reads from insert threads during async recovery.
- DataRegion#upgradeAndUpdateDeviceLastFlushTime: when the partition is already
  a PartitionLastFlushTime, merge resource.getTimeIndex().getMaxEndTime() in
  O(1) without allocating a per-device map; if a DeviceLastFlushTime still
  exists, take writeLock and call TimePartitionManager#updateAfterFlushing.
- DataRegion#recover & recoverUnsealedTsFileCallBack: remove the redundant
  latestPartitionId re-registration (eliminating the stale-memSize TOCTOU race
  and un-eviction of degraded partitions), register/account WAL-recovered
  unsealed TsFiles, and pass 0 for newly created partitions in
  registerTimePartitionInfo.
- TimePartitionInfo & TimePartitionManager: distinguish a cleared
  WeakReference from the @testonly null-owner constructor (never falling back
  to StorageEngine when dataRegionRef != null), and sweep collected entries
  from timePartitionInfoMap before evicting live partitions.
- ILastFlushTimeMap / HashLastFlushTimeMap / DataRegion: return boolean from
  degradeLastFlushTime / degradeFlushTimeMap (fast-pathing absent or already
  degraded partitions) so TimePartitionManager skips redundant map writes and
  INFO log storms for already-degraded FileTimeIndexCache partitions. Also
  guard empty inputs in updateMultiDeviceFlushedTime,
  upgradeAndUpdateMultiDeviceFlushedTime, and
  releaseCollectedReplacedTimePartitionInfos.
- PartitionLastFlushTime: rename field partitionLastFlushTime -> lastFlushTime
  (java:S1700) and update it atomically via AtomicLongFieldUpdater CAS
  instead of a non-atomic read-modify-write on a volatile long (java:S3078),
  keeping zero extra heap allocation per partition.
- HashLastFlushTimeMap: deduplicate updateMultiDeviceFlushedTime and
  upgradeAndUpdateMultiDeviceFlushedTime via mergeMultiDeviceFlushedTime and
  updateDeviceLastFlushTimeAndMemCost helpers to reduce Cognitive Complexity
  below Sonar's 15 limit (java:S3776).
@sonarqubecloud

sonarqubecloud Bot commented Dec 6, 2026

Copy link
Copy Markdown

@JackieTien97
JackieTien97 merged commit e16faaa into master Dec 6, 2026
42 checks passed
@JackieTien97
JackieTien97 deleted the ty/fix-recovery-last-flush-time-degrade branch December 6, 2026 06:13
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