Skip to content

Pipe: stabilize historical TsFile extraction during concurrent write or compaction - #19508

Open
Caideyipi wants to merge 11 commits into
apache:masterfrom
Caideyipi:fix/pipe-historical-refresh-tsfile-close
Open

Caideyipi wants to merge 11 commits into
apache:masterfrom
Caideyipi:fix/pipe-historical-refresh-tsfile-close

Conversation

@Caideyipi

@Caideyipi Caideyipi commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

Purpose

  • Refresh and re-identify the snapshot when concurrent writes could cause a pinned TsFile to be mistakenly merged.
  • Flush files recaptured by the refreshed snapshot so newly created TsFiles do not remain unflushed and block a later wait for TsFile closure.
  • Production flush requests use the processor-closing path; the non-closing TsFileProcessor.asyncFlush() path has no production call sites and is exercised only by tests.

@Caideyipi

Copy link
Copy Markdown
Collaborator Author

Initial self-review summary (reviewed commit ea4ca640f79ec4b610f06011556b93dbf4353486):

  • Reviewed the full change and relevant locking and flush lifecycle context; found no actionable issues.
  • Fixes during this round: none.
  • Validation: Spotless passed; 39 targeted tests passed with 0 failures, 0 errors, and 0 skips. All new tests ran locally.
  • Independent review remains pending.

@Caideyipi

Copy link
Copy Markdown
Collaborator Author

Follow-up self-review summary (reviewed commit ea4ca640f79ec4b610f06011556b93dbf4353486):

  • Finding: the 200 ms lock assertion could pass before the replacement task had started, so the test could falsely pass without exercising contention.
  • Fix: added a CountDownLatch start barrier before awaiting the replacement future.
  • Validation: Spotless passed. Clean reactor tests for PipeHistoricalDataRegionTsFileAndDeletionSourceTest and DataRegionTest completed with 98 passed, 0 failures, 0 errors, and 1 existing skip (testDeleteStorageGroupWhenCompacting). All new tests ran locally.
  • Final local commit: abf8df7122d8c3395b4223862e43f78f7107166b.
  • Confirmed source branch and PR head: abf8df7122d8c3395b4223862e43f78f7107166b.

@Caideyipi
Caideyipi marked this pull request as ready for review December 3, 2026 02:33
@Caideyipi Caideyipi changed the title Pipe: stabilize historical TsFile extraction during compaction Pipe: stabilize historical TsFile extraction during concurrent write or compaction Dec 3, 2026
tsFileProcessor.asyncFlush();
final Future<?> ordinaryFlushFuture = tsFileProcessor.getCloseFuture();
Assert.assertNotNull(ordinaryFlushFuture);
ordinaryFlushFuture.get();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

minor iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/DataRegionTest.java:3117 — New test never exercises the full-flush close retry loop it claims to cover

testAsyncFullFlushClosesSpecifiedProcessorAfterOrdinaryAsyncFlush awaits ordinaryFlushFuture.get() before calling asyncCloseOneTsFileProcessorForFullFlush, so managedByFlushManager is already false (FlushManager.FlushThread calls setManagedByFlushManager(false) before the task future completes) and shouldClose is set on the first iteration. The retry branch added in the new wrapper (DataRegion.java:2996-2999: future.get() + waitUntilFlushManagerReleased() + re-loop) is never executed, so a regression there stays undetected.

Fix: Invoke asyncCloseOneTsFileProcessorForFullFlush while an ordinary flush is still blocked (FlushListener latch as in testFullFlushWaitsForRunningOrdinaryAsyncFlush), then release it and assert the processor closes.

@Caideyipi Caideyipi Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

There are no ordinary flushes in the production code

@Caideyipi

Copy link
Copy Markdown
Collaborator Author

Comment follow-up for the review on DataRegionTest.java:

  • Finding: the test awaited the ordinary flush before requesting full-flush close, so it did not exercise the retry path.
  • Fix: the updated test holds the ordinary flush, starts the close request while flush-manager ownership is active, then releases the flush and asserts the resource closes and the processor leaves the working set.
  • Validation: spotless:apply -P with-integration-tests -pl iotdb-core/datanode -am exited 0; the clean targeted reactor test executed 1 test with 0 failures, 0 errors, and 0 skipped.
  • Final local and confirmed PR head: 1591114316c52b658a659b2975ff3bd280ce85a1.
  • The PR remains open, and the discussion remains unresolved.

return CompletableFuture.completedFuture(null);
}

while (!tsFileProcessor.alreadyMarkedClosing()) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

major iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/DataRegion.java:2983 — Removing the blocking wait turns the full-flush close retry into a lock-hammering busy spin

While an ordinary async flush owns the processor (managedByFlushManager==true) the inner call returns the flush future without setting shouldClose, so this loop re-iterates immediately, re-taking the DataRegion insertLock write lock and flushQueryLock with no park until the flush ends: a core spins and inserts starve. If asyncClose keeps failing (it only logs, shouldClose stays false) the loop never terminates. The deleted future.get()/waitUntilFlushManagerReleased() blocked outside the locks, per TsFileProcessor#asyncCloseForFullFlush.

Fix: Restore the blocking wait outside the locks before re-looping, as done in syncCloseAllWorkingAndClosingTsFileProcessors: if (future != null) future.get(); tsFileProcessor.waitUntilFlushManagerReleased();

@Caideyipi Caideyipi Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

There are no ordinary flushes in the production code

@luoluoyuyu

Copy link
Copy Markdown
Member

major iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/source/dataregion/historical/PipeHistoricalDataRegionTsFileAndDeletionSourceTest.java:401 — Snapshot-refresh tests no longer trigger any refresh, so replaced-snapshot assertions cannot hold

extractTsFiles now refreshes only when attempt 1 reports pinFailedCount>0 (line 836 of the source), but these setups swap the manager content and every pin succeeds, so the refresh/fallback branch is never entered: originalResources still holds the stale resource and this assertion (also line 510) fails; the renamed tests at line 652 additionally block for 10s waiting for refreshedReadLockEntered. Commit 66c96e3 dropped the isTsFilePartitionSnapshotCurrent trigger without updating them.

Fix: Either keep a snapshot-currency refresh trigger, or make the first attempt fail to pin (e.g. wrap the stale resource in CanonicalPathFailingFile) in testHistoricalExtractionRefreshesReplacedPartitionSnapshot/RefreshesPartitionReplacedDuringScan and assertHistoricalExtractionFallsBackToLockedSnapshot.

@Caideyipi
Caideyipi force-pushed the fix/pipe-historical-refresh-tsfile-close branch from 1591114 to 0243c54 Compare December 3, 2026 03:46
}

if (currentResult.snapshotInvalid) {
if (currentResult.statistics.pinFailedCount > 0) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

major iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/source/dataregion/historical/PipeHistoricalDataRegionTsFileAndDeletionSource.java:836 — pinFailedCount>0 escalates retryable pin failures into a fatal PipeException

A single pin failure is now treated as a stale snapshot. Attempt 1 fails the pin for an unclosed resource (deliberately kept for retry at extractTsFileResource:1062) or for a rolled-back mod pin, the refreshed attempt and the locked-snapshot attempt fail identically, so throw new PipeException(snapshotChangedMessage) aborts the whole historical extraction. testActiveUnclosedTsFilePinFailureKeepsResourceForRetry (invoke at line 232) and testHistoricalModPinFailureRollsBackTsFilePin (line 790) now throw.

Fix: Only treat a pin failure as a stale snapshot when the file really vanished (separate counter for missing-file pins, or skip refresh when !resource.isClosed()); keep retryable unclosed/mod pin failures on the existing supply-time retry path.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Thanks for the report. I kept production behavior unchanged and aligned the legacy tests with the current retry path: if an unclosed TsFile or mod-file pin keeps failing across refresh/fallback attempts, historical extraction propagates PipeException, and successfully acquired partial pins are rolled back. The snapshot-recovery test now triggers refresh with actual pin failures instead of a manager snapshot change alone. The focused historical extraction test class passes (37 tests).

@Caideyipi

Copy link
Copy Markdown
Collaborator Author

Historical extraction test update

  • Updated snapshot replacement tests to reflect that manager changes alone do not trigger a refresh.
  • Made the refresh and locked-snapshot fallback scenarios exercise actual pin failures; persistent failures now assert PipeException and rollback of partial pins.
  • Kept production code unchanged.
  • Verification: Spotless passed; the focused historical extraction suite passed (37 tests, 0 failures, 0 errors); git diff --check passed.
  • Reviewed pre-update head: a4468e74aec1a853e1e6aa833472bac9118d7247. Final local and confirmed remote head: 803736c29e2df94d973d1fe45ff972921b86ba2c.

}

try {
dataRegion.asyncCloseOneTsFileProcessorForFullFlush(processor);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

major iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/source/dataregion/historical/PipeHistoricalDataRegionTsFileAndDeletionSource.java:1012 — Close of refreshed unclosed TsFile is not awaited, so every retry pins the still-open file

closeUnclosedTsFileOnSnapshotRefresh discards the Future returned by DataRegion.asyncCloseOneTsFileProcessorForFullFlush, which returns once shouldClose is set (DataRegionTest line 3171 must await closeFuture.get() for the actual closure). The retry at line 858 and the fallback at line 872 thus extract while the TsFile is still open; a file whose pipe-dir hardlink cannot be created while unclosed (PipeTsFileResourceManager:462-476) fails the pin in all three attempts, so line 883 throws PipeException although the region was just asked to close the file.

Fix: Capture and wait for the close Future (future.get(), or poll resource.isClosed()) before re-extracting, and request the close before the fallback extraction at line 872 instead of after it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in d9bb43042b3c. The refresh now requests close futures for all unclosed resources, then waits for them before pinning; the wait happens outside the TsFileManager read lock. This wait is intentional: when a hard link cannot be created (for example, across file systems), the fallback copies the TsFile, so copying before close completes can produce an incomplete file and stall synchronization. The regression test verifies that all requested futures complete before extraction proceeds, and already-closed resources are not closed again.

extractTsFilesInPartitionWithTsFileManagerReadLock(tsFileManager, timePartition);
closeUnclosedTsFilesOnSnapshotRefresh(dataRegion, currentResult.resources);
if (currentResult.statistics.pinFailedCount > 0
|| currentResult.statistics.skippedDeletedCount > 0) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

minor iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/source/dataregion/historical/PipeHistoricalDataRegionTsFileAndDeletionSource.java:876 — skippedDeletedCount>0 aborts the locked fallback although deleted TsFiles are normally skipped

Only the locked fallback treats skippedDeletedCount>0 as fatal. A TsFile marked DELETED but not yet removed from the list (DataRegion.java:4363 marks the status, then deleteDataDirectlyInFile calls tsFileManager.remove) is visible during the fallback scan, which holds only the tsFileManager read lock, so the removal blocks. The code then throws PipeException and aborts historical extraction, while attempts 1-2 just skip such resources; under the read lock the counter cannot indicate snapshot staleness.

Fix: Remove the skippedDeletedCount condition from the fallback check and keep only pinFailedCount, so deleted-but-not-removed TsFiles are skipped as in the earlier attempts.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed. skippedDeletedCount records resources marked deleted when extraction examines them; it does not prove that physical deletion has completed. The locked fallback now treats only pin failures as fatal and keeps marked-deleted resources out of the selected and pinned set, so they are not synchronized. Added regression coverage for this case.

@Caideyipi

Copy link
Copy Markdown
Collaborator Author

Review summary (reviewed base SHA: 803736c29e2df94d973d1fe45ff972921b86ba2c; final local SHA: d9bb43042b3c513b852dadf22708b1be29b134b5; confirmed source branch and PR head SHA: d9bb43042b3c513b852dadf22708b1be29b134b5).

Both review comments are addressed. Snapshot refresh now captures asynchronous close futures and waits outside the TsFileManager read lock before pinning. This avoids copying an incompletely flushed TsFile when hard links cannot be used. The fallback validates the snapshot after waiting and skips resources marked deleted instead of treating skippedDeletedCount as fatal. Already-closed resources remain untouched.

Added regression coverage for close-future completion, already-closed resources, and deleted-resource fallback. Verification passed: Spotless and the focused Maven test class (39 tests, 0 failures, 0 errors, 0 skipped).

|| !areSameTsFileResources(resources.unsequenceResources, currentSnapshot.right)) {
throw new PipeException(snapshotChangedMessage);
}
return extractTsFilesInPartition(resources);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

major iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/source/dataregion/historical/PipeHistoricalDataRegionTsFileAndDeletionSource.java:1001 — Locked fallback pins/copies TsFiles while holding the TsFileManager read lock, stalling region writes

extractTsFilesInPartition(resources) runs under tsFileManager.readLock(), and it pins every selected file: pinTsFileResource copies the whole TsFile when the pipe-dir hard link cannot be created (PipeTsFileResourceManager.createHardLinkOrCopy:479). TsFileManager.add/remove/replace need the write lock, and the insert path holds the DataRegion write lock while calling add (DataRegion.java:2404 via getOrCreateTsFileProcessor:1730), so one large copy under the read lock blocks new-processor creation, deletes and compaction for the whole region.

Fix: Hold the read lock only for the snapshot capture and the membership re-validation, and perform pinning (hard link/copy) after releasing it, re-checking membership or holding per-resource read locks instead.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Thanks for the detailed review. The retry path now reuses references for files that remain selected after the refreshed snapshot is filtered, unpins only resources that are no longer selected, and pins only newly selected resources. If a reused TsFile needs a mod-file reference that was not present earlier, that reference is acquired separately without pinning the TsFile again. This avoids most redundant pinning, hard-linking, and copying for files unaffected by compaction.

The final locked fallback remains a last-resort progress path. Turning every pin race into an exception and relying on a later Pipe Meta Sync retry would make pipe creation latency unpredictable and could require multiple meta sync rounds.

Dedicated lifetime protection for these snapshot files could eventually let copying happen outside the manager lock, but coordinating file replacement, deletion, and reference ownership adds complexity. That optimization is out of scope for this PR; this change retains the fallback while reducing its work through difference-based reuse.

return future;
}
}
return tsFileProcessor.getCloseFuture();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

minor iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/DataRegion.java:2997 — asyncCloseOneTsFileProcessorForFullFlush can return a null close future while another thread is closing

TsFileProcessor.asyncClose publishes shouldClose=true (line 1837) before closeFuture (line 1838), both volatile and read without flushQueryLock. If a concurrent closer (another pipe's flush, mem-control or time-partition rolling) is inside that window, the wrapper skips its loop and returns getCloseFuture()==null; requestCloseOfUnclosedTsFileOnSnapshotRefresh (line 1061) then throws PipeException("Failed to get the close future...") although the TsFile is closing normally, aborting the whole historical extraction.

Fix: Assign closeFuture before shouldClose in TsFileProcessor.asyncClose so shouldClose==true implies a non-null future, and/or retry in the pipe instead of throwing when the future is still null.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in a2852f67fb. TsFileProcessor.asyncClose now publishes closeFuture before setting the volatile shouldClose flag. A caller that observes the closing flag can see the published close future, avoiding the race in which historical extraction receives a null future. The focused clean reactor run passed all 41 tests, including historical extraction and the DataRegion full-flush and already-closing-processor cases.

@Caideyipi

Copy link
Copy Markdown
Collaborator Author

Close-future comment follow-up

The scoped review of the latest minor comment confirmed a publication-order race in TsFileProcessor.asyncClose. The fix publishes the close future before the volatile closing flag.

  • Reviewed head d9bb43042b3c513b852dadf22708b1be29b134b5.
  • Final local commit and confirmed source branch/PR head a2852f67fbf7ed31aa74b0dc21282f3139df2a7b.
  • Spotless and the clean targeted reactor run passed. Fresh Surefire reports recorded 41 tests, with no failures, errors, or skips.
  • The PR remains open and non-draft. CI for the updated head is separate from the targeted verification.

return null;
});

Assert.assertFalse(closeWait.isDone());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

minor iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/source/dataregion/historical/PipeHistoricalDataRegionTsFileAndDeletionSourceTest.java:447 — Close-wait test asserts before the waiting task starts, so it cannot catch a non-blocking wait

closeWait is submitted and immediately asserted not-done, with no start barrier (compare replacementStarted/fullFlushCloseStarted). If waitForTsFileCloseFuturesOnSnapshotRefresh did not wait at all, the worker may still not have run when both assertFalse(closeWait.isDone()) checks execute, and closeWait.get(10s) still succeeds, so the regression the test targets stays undetected.

Fix: Have the worker count down a latch before invoking the method and await it before the assertions, or assert TimeoutException from closeWait.get(100ms) before completing the futures.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Thanks for catching this. The worker now signals a start latch before invoking the close-wait method, and the test expects a timed wait to expire before either close future completes. It then verifies that the task is still pending after only the first future completes. This makes the test exercise the blocking behavior rather than relying only on task scheduling.

@Caideyipi

Copy link
Copy Markdown
Collaborator Author

Review summary

  • Major: the retry path reuses references for resources still selected after a refreshed snapshot, pins only newly selected files (or a missing mod-file reference), and releases resources no longer selected. The final locked fallback remains to avoid making pipe creation depend entirely on later metadata-sync retries; dedicated file-lifetime protection remains follow-up work.
  • Minor: made the close-wait regression test deterministic with a worker-start latch and a timed wait before completing the close futures.
  • Verification: Spotless passed. The clean offline Maven test run passed with 40 historical-source tests and 2 DataRegion close tests (42 total; 0 failures, errors, or skips); fresh Surefire XML reports were checked.
  • Review baseline: a2852f67fbf7ed31aa74b0dc21282f3139df2a7b. Final local SHA: fe24c1fe3bad1b2239522370765eebc9b9452e1b. Confirmed source-branch and PR head: fe24c1fe3bad1b2239522370765eebc9b9452e1b. The PR remains open.

try {
final Pair<List<TsFileResource>, List<TsFileResource>> currentSnapshot =
tsFileManager.getAllTsFileListForQuery(Collections.singletonList(timePartition), null);
if (!areSameTsFileResources(resources.sequenceResources, currentSnapshot.left)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

major iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/source/dataregion/historical/PipeHistoricalDataRegionTsFileAndDeletionSource.java:998 — Locked fallback validates an exact snapshot after closing its own captured TsFiles, so its close aborts the extraction

extractTsFilesInPartitionWithTsFileManagerReadLock captures the partition snapshot (line 980), requests close of its unclosed TsFiles (line 991), then still requires areSameTsFileResources to hold (line 998). Closing drops the processor from workSequenceTsFileProcessors (DataRegion.java:3029), so the next insert adds a new TsFile to that partition (DataRegion.java:2404), and closing an empty TsFile removes one from the manager (DataRegion.java:4424). Any such write/removal during the close wait makes the check fail and throws PipeException, aborting the whole historical extraction.

Fix: Request the closes before capturing the snapshot used for the equality check, or re-validate only that the captured resources are still present (containment) instead of requiring the list to be identical.

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.

3 participants