Repository navigation
Fix LastFlushTimeMap degradation skipped during DataRegion recovery - #19545
JackieTien97 wants to merge 4 commits into
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #19545 +/- ##
============================================
+ Coverage 50.99% 51.01% +0.02%
Complexity 145 145
============================================
Files 5797 5797
Lines 430347 430352 +5
Branches 57344 57350 +6
============================================
+ Hits 219459 219563 +104
+ Misses 210888 210789 -99 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
JackieTien97
left a comment
There was a problem hiding this comment.
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):
- 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 itsDeviceLastFlushTime(a plainHashMap). This may cause aConcurrentModificationException(leavingTimePartitionManageraccounting inconsistent and failing A's recovery) or lost updates (an under-estimated partition flush time, which can cause overlapping sequence files). - Lookup order defeats the fix on the snapshot-load path. In
StorageEngine.setDataRegionForSnapshotLoad, the old region with the same id is still indataRegionMapwhile the new region is being constructed and recovered, soStorageEngine.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
thisfrom the constructor is safe here becauselastFlushTimeMapis assigned beforerecover()and both registration and degradation synchronize ontimePartitionInfoMap. A short comment, or makinglastFlushTimeMapfinal(it is assigned only once), would make this explicit. - Pre-existing:
HashLastFlushTimeMap.upgradeAndUpdateMultiDeviceFlushedTimebuildsnewDeviceLastFlushTimein thePartitionLastFlushTimebranch but never puts it back intopartitionLatestFlushedTime(it only increasesmemCostForEachPartition), 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 intimePartitionInfoMemoryBlock(only the delta inupdateAfterFlushingis), so the accounting can drift.
| Long.MAX_VALUE, | ||
| lastFlushTimeMap.getMemSize(partitionId))); | ||
| lastFlushTimeMap.getMemSize(partitionId), | ||
| this)); |
There was a problem hiding this comment.
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:
ConcurrentModificationExceptionthrown in thread A.recover()only catchesIOException, so A's region recovery fails, andTimePartitionManageris left withrelease()done but the entry not removed.- Lost updates: B keeps writing into the stale
DaftercomputeIfPresenthas swapped in aPartitionLastFlushTime. 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:
Note that this does not cover
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);
recoverUnsealedTsFileCallBack->updateDeviceLastFlushTime, or theDeviceLastFlushTimebranch ofupgradeAndUpdateMultiDeviceFlushedTimein the async tasks, which mutate already-registered partitions. - (b) More robust: in
HashLastFlushTimeMap, perform every mutation of anILastFlushTimeinsidepartitionLatestFlushedTime.compute(partitionId, ...), so it is serialized per partition withdegradeLastFlushTime'scomputeIfPresent. This would also close the pre-existing runtime race noted ondegradeFlushTimeMap("may not hold the write lock").
There was a problem hiding this comment.
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.
| if (dataRegion == null) { | ||
| dataRegion = timePartitionInfo.getDataRegion(); | ||
| } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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).
| Mockito.verify(mockDataRegion, Mockito.times(1)).degradeFlushTimeMap(10L); | ||
| Assert.assertNull(timePartitionManager.getTimePartitionInfo(dataRegionId, 10L)); | ||
| Assert.assertNotNull(timePartitionManager.getTimePartitionInfo(dataRegionId, 11L)); |
There was a problem hiding this comment.
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 whereStorageEngineholds a different region with the same id, and verify that the region stored inTimePartitionInfois 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 smallTimePartitionInfomemory threshold, create TsFiles across several partitions, re-construct theDataRegion, and assert that the early partitions are degraded (getLastFlushTimeMap().getMemSize(p) == Long.BYTES).
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Marked the 5-argument constructor @TestOnly and added a Javadoc note that production code must pass the owning DataRegion.
JackieTien97
left a comment
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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.
|
Addressed all review comments in 18d6d07 (replies are in each thread). From the review summary:
|
|
JackieTien97
left a comment
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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 inStorageEngine, then recovers the replacement while the old region is still registered. It asserts oldgetMemSize(0) == Long.BYTES, flush time kept, and the replacement holds the full map. With only this change reverted it fails withexpected:<8> but was:<2060>.TimePartitionManagerTest#testReplacedByAnotherRegionDegradesOldRegion,#testReplacedRegionKeepsAccountedIfDegradeFails,#testReRegisteredBySameRegionDoesNotDegrade.
| return partitionLatestFlushedTime.putIfAbsent( | ||
| timePartitionId, | ||
| usingDeviceFlushTime | ||
| ? new DeviceLastFlushTime() |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
[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.
…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.



Problem
During
DataRegionconstruction/recovery (StorageEngine.buildNewDataRegion()->new DataRegion(...)->recover()), theDataRegioninstance has not yet been inserted intoStorageEngine.dataRegionMap.When
syncRecoverFilesInPartition()(orasyncRecoverFilesInPartition()) registers time partitions inTimePartitionManagerand callsupdateAfterFlushing(...), iftimePartitionInfoMemoryBlockexceeds its memory threshold,TimePartitionManager.degradeLastFlushTime()executes:timePartitionInfoMemoryBlock.release(timePartitionInfo.memSize);DataRegion dataRegion = StorageEngine.getInstance().getDataRegion(timePartitionInfo.dataRegionId);— returnsnullduringDataRegionconstruction!if (dataRegion != null) { dataRegion.degradeFlushTimeMap(timePartitionInfo.partitionId); ... }— skipped!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
DeviceLastFlushTimemap 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
WeakReference<DataRegion>inTimePartitionInfoand passthisfrom everyDataRegioncall site. The weak reference means a region whose construction failed is not pinned in memory. The constructor without a region is now@TestOnly.TimePartitionManager.degradeLastFlushTime(), use the region stored inTimePartitionInfofirst and only fall back toStorageEngine.getDataRegion(id). During snapshot load, the old region with the same id is still inStorageEnginewhile the new region recovers, so this order makes sure the new region is the one degraded.TimePartitionInfoonly afterdegradeFlushTimeMapsucceeds. If it fails, keep the entry and its memory accounting so it can be degraded later. WhenregisterTimePartitionInforeplaces 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.HashLastFlushTimeMapruns every mutation of anILastFlushTimeand its memory cost insidepartitionLatestFlushedTime.compute(partitionId, ...). This serializes mutations with the degradation'scomputeIfPresent, so there is noConcurrentModificationExceptionand no lost update to a replacedDeviceLastFlushTime.PartitionLastFlushTime(recovered from FileTimeIndexCache or degraded),upgradeAndUpdateMultiDeviceFlushedTimenow 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) andDataRegionTest(60) pass.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 (inserting150after a restart where the seq file ends at100and the unseq file ends at200now goes to an unsequence file). Each new test fails without the change it covers.