This is an automated email from the ASF dual-hosted git repository.
Jackie-Jiang pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pinot.git
The following commit(s) were added to refs/heads/master by this push:
new 0864e80b14c Return reusable directory instead in segment reload path
(#20367)
0864e80b14c is described below
commit 0864e80b14cb02bb1b1dc92902df6115c9e22180
Author: Jhow <[email protected]>
AuthorDate: Sun Nov 29 13:17:56 2026 +0800
Return reusable directory instead in segment reload path (#20367)
---
.../core/data/manager/BaseTableDataManager.java | 121 ++++++++++++++++-
.../data/manager/BaseTableDataManagerTest.java | 148 +++++++++++++++++++++
2 files changed, 262 insertions(+), 7 deletions(-)
diff --git
a/pinot-core/src/main/java/org/apache/pinot/core/data/manager/BaseTableDataManager.java
b/pinot-core/src/main/java/org/apache/pinot/core/data/manager/BaseTableDataManager.java
index 8242cc127a3..dd071e21695 100644
---
a/pinot-core/src/main/java/org/apache/pinot/core/data/manager/BaseTableDataManager.java
+++
b/pinot-core/src/main/java/org/apache/pinot/core/data/manager/BaseTableDataManager.java
@@ -1370,7 +1370,15 @@ public abstract class BaseTableDataManager implements
TableDataManager {
SegmentDirectory segmentDirectory =
initSegmentDirectory(segmentName, zkMetadata.getCrc(),
indexLoadingConfig, zkMetadata);
// We should first try to reuse existing segment directory
- if (canReuseExistingDirectoryForReload(zkMetadata, segmentTier,
segmentDirectory, indexLoadingConfig)) {
+ SegmentDirectory reusableDirectory;
+ try {
+ reusableDirectory =
+ getReusableDirectoryForReload(zkMetadata, segmentTier,
segmentDirectory, indexLoadingConfig);
+ } catch (Exception e) {
+ closeSegmentDirectoryQuietly(segmentDirectory);
+ throw e;
+ }
+ if (reusableDirectory == segmentDirectory) {
_logger.info("Reloading segment: {} using existing segment
directory as no reprocessing needed",
segmentName);
// No reprocessing needed, reuse the same segment
@@ -1378,6 +1386,15 @@ public abstract class BaseTableDataManager implements
TableDataManager {
addSegment(segment, zkMetadata);
return;
}
+ if (reusableDirectory != null) {
+ if (restoreValidDocIdsOnDiskBitmap) {
+ // The validDocIds bitmap lives only in the local copy, so the
reload must carry it over by copying.
+ closeSegmentDirectoryQuietly(reusableDirectory);
+ } else if (tryLoadReusedDirectory(indexDir, segmentDirectory,
reusableDirectory, indexLoadingConfig,
+ zkMetadata)) {
+ return;
+ }
+ }
// Create backup directory to handle failure of segment reloading.
createBackup(indexDir);
// The indexDir is empty after calling createBackup, as it's renamed
to a backup directory.
@@ -1426,6 +1443,39 @@ public abstract class BaseTableDataManager implements
TableDataManager {
|| zkMetadata.getStatus() ==
CommonConstants.Segment.Realtime.Status.UPLOADED;
}
+ /// Returns a directory that a reload without download can load as is, or
null when the reload must copy the current
+ /// directory out and reprocess it, e.g. to move the segment to another tier.
+ ///
+ /// `currentDirectory` is the segment's directory on its current tier. The
default returns it when the segment stays
+ /// on that tier and needs no reprocessing.
+ ///
+ /// Extensions may return another directory, e.g. a copy of the segment that
another replica already prepared on the
+ /// target tier. Such a directory must hold the segment with the CRC in
`zkMetadata`, be opened for the target tier
+ /// (`zkMetadata.getTier()`), and need no reprocessing for it. Extensions
should return one only when
+ /// `currentDirectory` also has that CRC: a reload that gets here with
another CRC keeps the local copy on purpose,
+ /// e.g. with CRC checking on segment load disabled. The reload loads the
returned directory, and only once it has
+ /// loaded, closes `currentDirectory` and removes the local copy on the
current tier. If it fails to load, the reload
+ /// copies `currentDirectory` out and reprocesses it instead. A table that
restores the validDocIds bitmap on reload
+ /// never loads another directory, since the bitmap lives only in the local
copy.
+ ///
+ /// The default returns `currentDirectory` when
[#canReuseExistingDirectoryForReload] returns true, and null
+ /// otherwise, so that existing overrides of that method keep working.
+ ///
+ /// Called under the segment lock.
+ @Nullable
+ protected SegmentDirectory getReusableDirectoryForReload(SegmentZKMetadata
zkMetadata,
+ @Nullable String currentSegmentTier, SegmentDirectory currentDirectory,
IndexLoadingConfig indexLoadingConfig)
+ throws Exception {
+ return canReuseExistingDirectoryForReload(zkMetadata, currentSegmentTier,
currentDirectory, indexLoadingConfig)
+ ? currentDirectory : null;
+ }
+
+ /// Returns whether a reload without download can load the current directory
as is: the segment stays on its tier
+ /// and needs no reprocessing.
+ ///
+ /// @deprecated Override [#getReusableDirectoryForReload] instead, which can
also return another directory to load.
+ /// Its default implementation still calls this method.
+ @Deprecated
protected boolean canReuseExistingDirectoryForReload(SegmentZKMetadata
segmentZKMetadata, String currentSegmentTier,
SegmentDirectory segmentDirectory, IndexLoadingConfig indexLoadingConfig)
throws Exception {
@@ -1435,6 +1485,55 @@ public abstract class BaseTableDataManager implements
TableDataManager {
&& !ImmutableSegmentLoader.needPreprocess(segmentDirectory,
indexLoadingConfig);
}
+ /// Loads a directory other than the current one, returned by
[#getReusableDirectoryForReload], in place of the
+ /// segment, and returns true once the segment is replaced. The directory
serves the segment on its target tier, so
+ /// the local copy on the current tier is then removed, so that no later
load of the segment finds it.
+ ///
+ /// The local copy and `currentDirectory` stay as they are until the
directory has loaded. If it fails to load, e.g.
+ /// because an index in it is unreadable although it needs no reprocessing,
it is closed and this returns false, so
+ /// that the reload copies `currentDirectory` out and reprocesses it instead
of failing on the same directory every
+ /// time. An interrupt propagates, after closing both directories.
+ private boolean tryLoadReusedDirectory(File indexDir, SegmentDirectory
currentDirectory,
+ SegmentDirectory reusableDirectory, IndexLoadingConfig
indexLoadingConfig, SegmentZKMetadata zkMetadata)
+ throws Exception {
+ String segmentName = zkMetadata.getSegmentName();
+ String targetTier =
TierConfigUtils.normalizeTierName(zkMetadata.getTier());
+ _logger.info("Reloading segment: {} using the directory already prepared
on tier: {}", segmentName, targetTier);
+ ImmutableSegment segment;
+ try {
+ segment = ImmutableSegmentLoader.load(reusableDirectory,
+ indexLoadingConfig.copyWithSegmentTier(zkMetadata.getTier()));
+ } catch (Exception e) {
+ closeSegmentDirectoryQuietly(reusableDirectory);
+ if (e instanceof InterruptedException ||
Thread.currentThread().isInterrupted()) {
+ closeSegmentDirectoryQuietly(currentDirectory);
+ throw e;
+ }
+ _logger.warn("Failed to load the directory prepared on tier: {} for
segment: {}, reprocessing the local copy "
+ + "instead", targetTier, segmentName, e);
+ return false;
+ }
+ closeSegmentDirectoryQuietly(currentDirectory);
+ addSegment(segment, zkMetadata);
+ removeLocalCopy(indexDir);
+ return true;
+ }
+
+ /// Removes the segment's local directory once the segment no longer serves
from it. Renaming it to the temporary
+ /// directory first is atomic, so a failure part way through the delete
leaves only the temporary directory, which
+ /// the next reload failure recovery deletes, and never a partial index
directory.
+ private static void removeLocalCopy(File indexDir)
+ throws IOException {
+ if (!indexDir.exists()) {
+ return;
+ }
+ File segmentTempDir =
+ new File(indexDir.getParentFile(), indexDir.getName() +
CommonConstants.Segment.SEGMENT_TEMP_DIR_SUFFIX);
+ Preconditions.checkState(indexDir.renameTo(segmentTempDir),
+ "Failed to rename index directory: %s to segment temporary directory:
%s", indexDir, segmentTempDir);
+ FileUtils.deleteDirectory(segmentTempDir);
+ }
+
/// \_segmentDataManagerMap is used for fetching segments that need to be
queried. If a new segment is created,
/// calling this method ensures that all queries in the future can use the
new segment. This method may replace an
/// existing segment with the same name.
@@ -2193,6 +2292,18 @@ public abstract class BaseTableDataManager implements
TableDataManager {
protected SegmentDirectory initSegmentDirectory(String segmentName, long
segmentCrc,
IndexLoadingConfig indexLoadingConfig, @Nullable SegmentZKMetadata
zkMetadata)
throws Exception {
+ SegmentDirectoryLoader segmentDirectoryLoader =
+
SegmentDirectoryLoaderRegistry.getSegmentDirectoryLoader(indexLoadingConfig.getSegmentDirectoryLoader());
+ File indexDir =
+ getSegmentDataDir(segmentName, indexLoadingConfig.getSegmentTier(),
indexLoadingConfig.getTableConfig());
+ return segmentDirectoryLoader.load(indexDir.toURI(),
+ createSegmentDirectoryLoaderContext(segmentName, segmentCrc,
indexLoadingConfig, zkMetadata));
+ }
+
+ /// Creates the context with which [#initSegmentDirectory] loads the
segment's directory on the tier of
+ /// `indexLoadingConfig`.
+ protected SegmentDirectoryLoaderContext
createSegmentDirectoryLoaderContext(String segmentName, long segmentCrc,
+ IndexLoadingConfig indexLoadingConfig, @Nullable SegmentZKMetadata
zkMetadata) {
SegmentDirectoryLoaderContext loaderContext = new
SegmentDirectoryLoaderContext.Builder()
.setReadMode(indexLoadingConfig.getReadMode())
.setTableConfig(indexLoadingConfig.getTableConfig())
@@ -2205,12 +2316,8 @@ public abstract class BaseTableDataManager implements
TableDataManager {
.setInstanceTierConfigs(indexLoadingConfig.getInstanceTierConfigs())
.setSegmentCustomConfigs(zkMetadata != null ?
zkMetadata.getCustomMap() : Map.of())
.build();
- SegmentDirectoryLoader segmentDirectoryLoader =
-
SegmentDirectoryLoaderRegistry.getSegmentDirectoryLoader(indexLoadingConfig.getSegmentDirectoryLoader());
- File indexDir =
- getSegmentDataDir(segmentName, indexLoadingConfig.getSegmentTier(),
indexLoadingConfig.getTableConfig());
- return segmentDirectoryLoader.load(indexDir.toURI(),
indexLoadingConfig.isMappedSegmentMetadataEnabled()
- ? loaderContext.withMappedMetadataEnabled() : loaderContext);
+ return indexLoadingConfig.isMappedSegmentMetadataEnabled() ?
loaderContext.withMappedMetadataEnabled()
+ : loaderContext;
}
// CRC check can be performed on both segment CRC and data CRC (if
available) based on the ZK property value of
diff --git
a/pinot-core/src/test/java/org/apache/pinot/core/data/manager/BaseTableDataManagerTest.java
b/pinot-core/src/test/java/org/apache/pinot/core/data/manager/BaseTableDataManagerTest.java
index 4c855d56c27..007e475cccc 100644
---
a/pinot-core/src/test/java/org/apache/pinot/core/data/manager/BaseTableDataManagerTest.java
+++
b/pinot-core/src/test/java/org/apache/pinot/core/data/manager/BaseTableDataManagerTest.java
@@ -75,6 +75,7 @@ import org.apache.pinot.segment.spi.creator.SegmentVersion;
import org.apache.pinot.segment.spi.index.StandardIndexes;
import org.apache.pinot.segment.spi.index.metadata.SegmentMetadataImpl;
import org.apache.pinot.segment.spi.loader.SegmentDirectoryLoader;
+import org.apache.pinot.segment.spi.loader.SegmentDirectoryLoaderContext;
import org.apache.pinot.segment.spi.loader.SegmentDirectoryLoaderRegistry;
import org.apache.pinot.segment.spi.store.SegmentDirectory;
import org.apache.pinot.segment.spi.store.SegmentDirectoryPaths;
@@ -92,6 +93,7 @@ import org.apache.pinot.spi.data.Schema;
import org.apache.pinot.spi.data.readers.GenericRow;
import org.apache.pinot.spi.env.PinotConfiguration;
import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.ReadMode;
import org.apache.pinot.spi.utils.builder.TableConfigBuilder;
import org.apache.pinot.spi.utils.builder.TableNameBuilder;
import org.apache.pinot.spi.utils.retry.AttemptsExceededException;
@@ -493,6 +495,152 @@ public class BaseTableDataManagerTest {
assertEquals(new SegmentMetadataImpl(tierDataDir).getTotalDocs(), 5);
}
+ /// A reload that moves the segment to another tier loads the directory
[BaseTableDataManager
+ /// #getReusableDirectoryForReload] returns for that tier, instead of
copying the local segment over, and removes the
+ /// local copy on the current tier so that no later load finds it.
+ @Test
+ public void testReloadSegmentNewTierLoadsReusableDirectory()
+ throws Exception {
+ File indexDir = createSegment(SegmentVersion.v3, 5);
+ long crc = getCRC(indexDir);
+ File preparedDir = new File(new File(TEMP_DIR, "prepared"), SEGMENT_NAME);
+ FileUtils.copyDirectory(indexDir, preparedDir);
+ SegmentZKMetadata zkMetadata = new SegmentZKMetadata(SEGMENT_NAME);
+ zkMetadata.setCrc(crc);
+ zkMetadata.setTier(TIER_NAME);
+
+ BaseTableDataManager tableDataManager = spy(createTableManager());
+ tableDataManager.registerSegment(SEGMENT_NAME,
createImmutableSegmentDataManager(SEGMENT_NAME, crc));
+ seedZKMetadata(tableDataManager, SEGMENT_NAME, zkMetadata);
+ doAnswer(invocation -> createTierIndexLoadingConfig(TIER_TABLE_CONFIG))
+ .when(tableDataManager).fetchIndexLoadingConfig();
+ SegmentDirectory preparedDirectory = loadSegmentDirectory(preparedDir,
TIER_NAME);
+ doAnswer(invocation -> {
+ SegmentDirectory reusableDirectory = (SegmentDirectory)
invocation.callRealMethod();
+ assertNull(reusableDirectory, "The default must not reuse the
current-tier directory across tiers");
+ return preparedDirectory;
+ }).when(tableDataManager).getReusableDirectoryForReload(any(), any(),
any(), any());
+
+ tableDataManager.reloadSegment(SEGMENT_NAME, false, null);
+ ImmutableSegment segment = (ImmutableSegment)
tableDataManager.getSegmentDataManager(SEGMENT_NAME).getSegment();
+ assertEquals(segment.getTier(), TIER_NAME);
+ assertEquals(segment.getSegmentMetadata().getIndexDir(), preparedDir);
+ assertFalse(indexDir.exists());
+ assertFalse(tableDataManager.getSegmentDataDir(SEGMENT_NAME, TIER_NAME,
TIER_TABLE_CONFIG).exists());
+ assertFalse(tableDataManager.getSegmentDataDir(SEGMENT_NAME +
CommonConstants.Segment.SEGMENT_BACKUP_DIR_SUFFIX)
+ .exists());
+ verify(tableDataManager, never()).downloadSegment(any());
+ }
+
+ /// When the directory [BaseTableDataManager#getReusableDirectoryForReload]
returns fails to load, the reload closes
+ /// it and migrates the local copy instead, as it would without that
directory, so that a retry does not fail on the
+ /// same directory every time.
+ @Test
+ public void
testReloadSegmentFallsBackToLocalCopyWhenReusableDirectoryFailsToLoad()
+ throws Exception {
+ File indexDir = createSegment(SegmentVersion.v3, 5);
+ long crc = getCRC(indexDir);
+ SegmentZKMetadata zkMetadata = new SegmentZKMetadata(SEGMENT_NAME);
+ zkMetadata.setCrc(crc);
+ zkMetadata.setTier(TIER_NAME);
+
+ BaseTableDataManager tableDataManager = spy(createTableManager());
+ tableDataManager.registerSegment(SEGMENT_NAME,
createImmutableSegmentDataManager(SEGMENT_NAME, crc));
+ seedZKMetadata(tableDataManager, SEGMENT_NAME, zkMetadata);
+ doAnswer(invocation -> createTierIndexLoadingConfig(TIER_TABLE_CONFIG))
+ .when(tableDataManager).fetchIndexLoadingConfig();
+ SegmentDirectory brokenDirectory = mock(SegmentDirectory.class);
+ when(brokenDirectory.getSegmentMetadata()).thenThrow(new
IllegalStateException("broken copy"));
+
doReturn(brokenDirectory).when(tableDataManager).getReusableDirectoryForReload(any(),
any(), any(), any());
+
+ tableDataManager.reloadSegment(SEGMENT_NAME, false, null);
+ verify(brokenDirectory).close();
+ File tierDataDir = tableDataManager.getSegmentDataDir(SEGMENT_NAME,
TIER_NAME, TIER_TABLE_CONFIG);
+ ImmutableSegment segment = (ImmutableSegment)
tableDataManager.getSegmentDataManager(SEGMENT_NAME).getSegment();
+ assertEquals(segment.getTier(), TIER_NAME);
+ assertEquals(segment.getSegmentMetadata().getIndexDir(), tierDataDir);
+ assertEquals(new SegmentMetadataImpl(tierDataDir).getTotalDocs(), 5);
+ assertEquals(getCRC(tierDataDir), crc);
+ assertFalse(indexDir.exists());
+ assertFalse(tableDataManager.getSegmentDataDir(SEGMENT_NAME +
CommonConstants.Segment.SEGMENT_BACKUP_DIR_SUFFIX)
+ .exists());
+ }
+
+ /// An interrupt while loading the directory
[BaseTableDataManager#getReusableDirectoryForReload] returns is not a
+ /// load failure to recover from: the reload fails with the interrupt flag
still set, and keeps the local copy.
+ @Test
+ public void testReloadSegmentStopsWhenInterruptedLoadingReusableDirectory()
+ throws Exception {
+ File indexDir = createSegment(SegmentVersion.v3, 5);
+ long crc = getCRC(indexDir);
+ SegmentZKMetadata zkMetadata = new SegmentZKMetadata(SEGMENT_NAME);
+ zkMetadata.setCrc(crc);
+ zkMetadata.setTier(TIER_NAME);
+
+ BaseTableDataManager tableDataManager = spy(createTableManager());
+ tableDataManager.registerSegment(SEGMENT_NAME,
createImmutableSegmentDataManager(SEGMENT_NAME, crc));
+ seedZKMetadata(tableDataManager, SEGMENT_NAME, zkMetadata);
+ doAnswer(invocation -> createTierIndexLoadingConfig(TIER_TABLE_CONFIG))
+ .when(tableDataManager).fetchIndexLoadingConfig();
+ SegmentDirectory interruptedDirectory = mock(SegmentDirectory.class);
+ when(interruptedDirectory.getSegmentMetadata()).thenAnswer(invocation -> {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException("interrupted while reading");
+ });
+
doReturn(interruptedDirectory).when(tableDataManager).getReusableDirectoryForReload(any(),
any(), any(), any());
+
+ try {
+ expectThrows(IllegalStateException.class, () ->
tableDataManager.reloadSegment(SEGMENT_NAME, false, null));
+ // Thread.interrupted() also clears the flag, so it does not leak into
other tests
+ assertTrue(Thread.interrupted());
+ } finally {
+ Thread.interrupted();
+ }
+ verify(interruptedDirectory).close();
+ verify(tableDataManager, never()).createBackup(any());
+ assertTrue(indexDir.exists());
+ assertEquals(getCRC(indexDir), crc);
+ assertFalse(tableDataManager.getSegmentDataDir(SEGMENT_NAME, TIER_NAME,
TIER_TABLE_CONFIG).exists());
+ }
+
+ /// A table data manager that still overrides the deprecated
+ /// [BaseTableDataManager#canReuseExistingDirectoryForReload] keeps deciding
whether a reload reuses the current
+ /// directory.
+ @Test
+ @SuppressWarnings("deprecation")
+ public void testReloadSegmentHonorsDeprecatedCanReuseOverride()
+ throws Exception {
+ File indexDir = createSegment(SegmentVersion.v3, 5);
+ long crc = getCRC(indexDir);
+ SegmentZKMetadata zkMetadata = new SegmentZKMetadata(SEGMENT_NAME);
+ zkMetadata.setCrc(crc);
+
+ BaseTableDataManager tableDataManager = spy(createTableManager());
+ tableDataManager.registerSegment(SEGMENT_NAME,
createImmutableSegmentDataManager(SEGMENT_NAME, crc));
+ seedZKMetadata(tableDataManager, SEGMENT_NAME, zkMetadata);
+ doAnswer(invocation -> createTierIndexLoadingConfig(DEFAULT_TABLE_CONFIG))
+ .when(tableDataManager).fetchIndexLoadingConfig();
+
+ // Same tier and nothing to reprocess: the default reuses the current
directory.
+ tableDataManager.reloadSegment(SEGMENT_NAME, false, null);
+ verify(tableDataManager, never()).createBackup(indexDir);
+
+ // An override that declines makes the reload copy the current directory
out instead.
+
doReturn(false).when(tableDataManager).canReuseExistingDirectoryForReload(any(),
any(), any(), any());
+ tableDataManager.reloadSegment(SEGMENT_NAME, false, null);
+ verify(tableDataManager).createBackup(indexDir);
+ assertEquals(getCRC(indexDir), crc);
+ }
+
+ private static SegmentDirectory loadSegmentDirectory(File indexDir, String
tier)
+ throws Exception {
+ SegmentDirectory segmentDirectory =
SegmentDirectoryLoaderRegistry.getDefaultSegmentDirectoryLoader().load(
+ indexDir.toURI(), new
SegmentDirectoryLoaderContext.Builder().setTableConfig(DEFAULT_TABLE_CONFIG)
+
.setSchema(SCHEMA).setSegmentName(SEGMENT_NAME).setReadMode(ReadMode.mmap).build());
+ segmentDirectory.setTier(tier);
+ return segmentDirectory;
+ }
+
/// Regression test for https://github.com/apache/pinot/issues/18164: the
table-level config passed into reload is
/// shared by all segments, so reloading one segment must not set its tier
on the shared config.
@Test
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]