This is an automated email from the ASF dual-hosted git repository.

xiangfu0 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 2567a0c292a Validate configured extension types before initialization 
(#20455)
2567a0c292a is described below

commit 2567a0c292a38b0d2cc63f931fd350eb44aa7778
Author: Xiang Fu <[email protected]>
AuthorDate: Fri Dec 4 21:04:10 2026 -0800

    Validate configured extension types before initialization (#20455)
    
    * Validate configured extension types before initialization
    
    * Remove unused parser lookups and cover extension type checks
    
    * Validate analyzer argument types and cover custom extension construction
    
    * Validate realtime offset reset handler types before initialization
---
 .../validation/RealtimeOffsetAutoResetManager.java | 14 ++--
 .../RealtimeOffsetAutoResetManagerTest.java        | 23 ++++++
 .../dedup/TableDedupMetadataManagerFactory.java    |  6 +-
 .../MultiColumnRealtimeLuceneTextIndex.java        | 21 -----
 .../invertedindex/RealtimeLuceneTextIndex.java     | 21 -----
 .../local/segment/store/TextIndexUtils.java        | 67 ++++++++--------
 .../upsert/TableUpsertMetadataManagerFactory.java  |  6 +-
 .../upsert/merger/PartialUpsertMergerFactory.java  |  6 +-
 .../TableDedupMetadataManagerFactoryTest.java      | 48 +++++++++++
 .../local/segment/store/TextIndexUtilsTest.java    | 92 ++++++++++++++++++++++
 .../TableUpsertMetadataManagerFactoryTest.java     | 41 ++++++++++
 .../merger/PartialUpsertMergerFactoryTest.java     | 43 ++++++++--
 .../pinot/spi/utils/PinotReflectionUtils.java      |  7 ++
 13 files changed, 300 insertions(+), 95 deletions(-)

diff --git 
a/pinot-controller/src/main/java/org/apache/pinot/controller/validation/RealtimeOffsetAutoResetManager.java
 
b/pinot-controller/src/main/java/org/apache/pinot/controller/validation/RealtimeOffsetAutoResetManager.java
index 5ecc4776757..f6134228728 100644
--- 
a/pinot-controller/src/main/java/org/apache/pinot/controller/validation/RealtimeOffsetAutoResetManager.java
+++ 
b/pinot-controller/src/main/java/org/apache/pinot/controller/validation/RealtimeOffsetAutoResetManager.java
@@ -38,6 +38,7 @@ import 
org.apache.pinot.controller.helix.core.realtime.PinotLLCRealtimeSegmentMa
 import org.apache.pinot.spi.config.table.TableConfig;
 import org.apache.pinot.spi.stream.StreamConfig;
 import org.apache.pinot.spi.utils.IngestionConfigUtils;
+import org.apache.pinot.spi.utils.PinotReflectionUtils;
 import org.apache.pinot.spi.utils.builder.TableNameBuilder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -212,21 +213,24 @@ public class RealtimeOffsetAutoResetManager extends 
ControllerPeriodicTask<Realt
       return null;
     }
     try {
-      Class<?> clazz = Class.forName(className);
-      if (!RealtimeOffsetAutoResetHandler.class.isAssignableFrom(clazz)) {
+      Class<? extends RealtimeOffsetAutoResetHandler> clazz;
+      try {
+        clazz = PinotReflectionUtils.loadClassWithoutInitializing(className, 
RealtimeOffsetAutoResetHandler.class,
+            RealtimeOffsetAutoResetManager.class.getClassLoader());
+      } catch (ClassCastException e) {
         throw new ReflectiveOperationException("Custom handler must implement "
-            + RealtimeOffsetAutoResetHandler.class.getCanonicalName());
+            + RealtimeOffsetAutoResetHandler.class.getCanonicalName(), e);
       }
       try {
         // Preferred: no-arg constructor + explicit init()
-        handler = (RealtimeOffsetAutoResetHandler) 
clazz.getConstructor().newInstance();
+        handler = clazz.getConstructor().newInstance();
         handler.init(_llcRealtimeSegmentManager, _pinotHelixResourceManager);
       } catch (NoSuchMethodException e) {
         // Backward-compatibility fallback: 2-arg constructor (deprecated SPI 
contract).
         // Handlers compiled against the previous contract called init() from 
their own constructor.
         LOGGER.warn("Handler class {} has no no-arg constructor; falling back 
to deprecated 2-arg constructor. "
             + "Please migrate to a no-arg constructor + init() pattern.", 
className);
-        handler = (RealtimeOffsetAutoResetHandler) clazz.getConstructor(
+        handler = clazz.getConstructor(
             PinotLLCRealtimeSegmentManager.class, 
PinotHelixResourceManager.class)
             .newInstance(_llcRealtimeSegmentManager, 
_pinotHelixResourceManager);
       }
diff --git 
a/pinot-controller/src/test/java/org/apache/pinot/controller/validation/RealtimeOffsetAutoResetManagerTest.java
 
b/pinot-controller/src/test/java/org/apache/pinot/controller/validation/RealtimeOffsetAutoResetManagerTest.java
index 0d1b8ac16c4..107ac28885b 100644
--- 
a/pinot-controller/src/test/java/org/apache/pinot/controller/validation/RealtimeOffsetAutoResetManagerTest.java
+++ 
b/pinot-controller/src/test/java/org/apache/pinot/controller/validation/RealtimeOffsetAutoResetManagerTest.java
@@ -74,6 +74,8 @@ public class RealtimeOffsetAutoResetManagerTest {
   @Mock
   private RealtimeOffsetAutoResetHandler _mockHandler;
 
+  private static boolean _unrelatedHandlerTypeInitialized;
+
   private AutoCloseable _mocks;
   private RealtimeOffsetAutoResetManager _realtimeOffsetAutoResetManager;
   private ControllerConf _controllerConf;
@@ -178,6 +180,20 @@ public class RealtimeOffsetAutoResetManagerTest {
     Assert.assertNull(handler);
   }
 
+  @Test
+  public void testRejectsAnUnrelatedHandlerTypeBeforeInitialization() {
+    TableConfig tableConfig = createTableConfigWithoutHandlerClass();
+    tableConfig.getIngestionConfig().getStreamIngestionConfig()
+        
.setRealtimeOffsetAutoResetHandlerClass(UnrelatedHandlerType.class.getName());
+    
when(_pinotHelixResourceManager.getTableConfig(REALTIME_TABLE_NAME)).thenReturn(tableConfig);
+
+    _realtimeOffsetAutoResetManager.processTable(REALTIME_TABLE_NAME,
+        _realtimeOffsetAutoResetManager.preprocess(new Properties()));
+
+    
Assert.assertNull(_realtimeOffsetAutoResetManager.getTableHandler(REALTIME_TABLE_NAME));
+    Assert.assertFalse(_unrelatedHandlerTypeInitialized);
+  }
+
   @Test
   public void testProcessTableWithRealtimeTableValidHandler() {
     RealtimeOffsetAutoResetManager.Context context = 
_realtimeOffsetAutoResetManager.preprocess(_properties);
@@ -332,6 +348,13 @@ public class RealtimeOffsetAutoResetManagerTest {
     return tableConfig;
   }
 
+  /// Records initialization without implementing the handler interface.
+  private static class UnrelatedHandlerType {
+    static {
+      _unrelatedHandlerTypeInitialized = true;
+    }
+  }
+
   /// Test implementation of RealtimeOffsetAutoResetHandler for testing 
purposes
   public static class TestRealtimeOffsetAutoResetHandler implements 
RealtimeOffsetAutoResetHandler {
 
diff --git 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/dedup/TableDedupMetadataManagerFactory.java
 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/dedup/TableDedupMetadataManagerFactory.java
index cb61a20be93..812bc4b4654 100644
--- 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/dedup/TableDedupMetadataManagerFactory.java
+++ 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/dedup/TableDedupMetadataManagerFactory.java
@@ -28,6 +28,7 @@ import org.apache.pinot.spi.config.table.TableConfig;
 import org.apache.pinot.spi.data.Schema;
 import org.apache.pinot.spi.env.PinotConfiguration;
 import org.apache.pinot.spi.utils.CommonConstants.Server.Dedup;
+import org.apache.pinot.spi.utils.PinotReflectionUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -55,8 +56,9 @@ public class TableDedupMetadataManagerFactory {
       LOGGER.info("Creating TableDedupMetadataManager with class: {} for 
table: {}", metadataManagerClass,
           tableNameWithType);
       try {
-        metadataManager =
-            (TableDedupMetadataManager) 
Class.forName(metadataManagerClass).getConstructor().newInstance();
+        metadataManager = 
PinotReflectionUtils.loadClassWithoutInitializing(metadataManagerClass,
+                TableDedupMetadataManager.class, 
TableDedupMetadataManagerFactory.class.getClassLoader())
+            .getConstructor().newInstance();
       } catch (Exception e) {
         throw new RuntimeException(
             String.format("Caught exception while constructing 
TableDedupMetadataManager with class: %s for table: %s",
diff --git 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/invertedindex/MultiColumnRealtimeLuceneTextIndex.java
 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/invertedindex/MultiColumnRealtimeLuceneTextIndex.java
index 7b276af67c0..73167f2b91c 100644
--- 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/invertedindex/MultiColumnRealtimeLuceneTextIndex.java
+++ 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/invertedindex/MultiColumnRealtimeLuceneTextIndex.java
@@ -395,27 +395,6 @@ public class MultiColumnRealtimeLuceneTextIndex implements 
MultiColumnTextIndexR
     return actualDocIDs;
   }
 
-  private Constructor<QueryParserBase> 
getQueryParserWithStringAndAnalyzerTypeConstructor(String queryParserClassName)
-      throws ReflectiveOperationException {
-    // Fail-fast if the query parser is specified class is not QueryParseBase 
class
-    final Class<?> queryParserClass = Class.forName(queryParserClassName);
-    if (!QueryParserBase.class.isAssignableFrom(queryParserClass)) {
-      throw new ReflectiveOperationException("The specified lucene query 
parser class " + queryParserClassName
-          + " is not assignable from " + QueryParserBase.class.getName());
-    }
-    // Fail-fast if the query parser does not have the required constructor 
used by this class
-    try {
-      queryParserClass.getConstructor(String.class, Analyzer.class);
-    } catch (NoSuchMethodException ex) {
-      throw new NoSuchMethodException("The specified lucene query parser class 
" + queryParserClassName
-          + " is not assignable because the class does not have the required 
constructor method with parameter "
-          + "type [String.class, Analyzer.class]"
-      );
-    }
-
-    return (Constructor<QueryParserBase>) 
queryParserClass.getConstructor(String.class, Analyzer.class);
-  }
-
   public void commit() {
     if (!_reuseMutableIndex) {
       return;
diff --git 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/invertedindex/RealtimeLuceneTextIndex.java
 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/invertedindex/RealtimeLuceneTextIndex.java
index e65ece1f984..f84bbf4cca5 100644
--- 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/invertedindex/RealtimeLuceneTextIndex.java
+++ 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/invertedindex/RealtimeLuceneTextIndex.java
@@ -360,27 +360,6 @@ public class RealtimeLuceneTextIndex implements 
MutableTextIndex {
     return actualDocIDs;
   }
 
-  private Constructor<QueryParserBase> 
getQueryParserWithStringAndAnalyzerTypeConstructor(String queryParserClassName)
-          throws ReflectiveOperationException {
-    // Fail-fast if the query parser is specified class is not QueryParseBase 
class
-    final Class<?> queryParserClass = Class.forName(queryParserClassName);
-    if (!QueryParserBase.class.isAssignableFrom(queryParserClass)) {
-      throw new ReflectiveOperationException("The specified lucene query 
parser class " + queryParserClassName
-              + " is not assignable from " + QueryParserBase.class.getName());
-    }
-    // Fail-fast if the query parser does not have the required constructor 
used by this class
-    try {
-      queryParserClass.getConstructor(String.class, Analyzer.class);
-    } catch (NoSuchMethodException ex) {
-      throw new NoSuchMethodException("The specified lucene query parser class 
" + queryParserClassName
-              + " is not assignable because the class does not have the 
required constructor method with parameter "
-              + "type [String.class, Analyzer.class]"
-      );
-    }
-
-    return (Constructor<QueryParserBase>) 
queryParserClass.getConstructor(String.class, Analyzer.class);
-  }
-
   @Override
   public void commit() {
     if (!_reuseMutableIndex) {
diff --git 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/store/TextIndexUtils.java
 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/store/TextIndexUtils.java
index ea40d058c23..e8d14dd2518 100644
--- 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/store/TextIndexUtils.java
+++ 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/store/TextIndexUtils.java
@@ -64,6 +64,7 @@ import 
org.apache.pinot.spi.config.provider.PinotClusterConfigChangeListener;
 import org.apache.pinot.spi.config.table.FieldConfig;
 import org.apache.pinot.spi.env.CommonsConfigurationUtils;
 import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.PinotReflectionUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -381,16 +382,17 @@ public class TextIndexUtils {
       argValues.add(parseSupportedTypeValues(luceneAnalyzerClassArgs.get(i), 
argClasses.get(i)));
     }
 
-    // Initialize the custom analyzer class with custom analyzer args
-    Class<?> luceneAnalyzerClass = Class.forName(luceneAnalyzerClassName);
-    if (!Analyzer.class.isAssignableFrom(luceneAnalyzerClass)) {
+    Class<? extends Analyzer> luceneAnalyzerClass;
+    try {
+      luceneAnalyzerClass = 
PinotReflectionUtils.loadClassWithoutInitializing(luceneAnalyzerClassName, 
Analyzer.class,
+          TextIndexUtils.class.getClassLoader());
+    } catch (ClassCastException e) {
       String exceptionMessage = "Custom analyzer must be a child of " + 
Analyzer.class.getCanonicalName();
       LOGGER.error(exceptionMessage);
-      throw new ReflectiveOperationException(exceptionMessage);
+      throw new ReflectiveOperationException(exceptionMessage, e);
     }
 
-    // Return a new instance of custom lucene analyzer class
-    return (Analyzer) 
luceneAnalyzerClass.getConstructor(argClasses.toArray(new Class<?>[0]))
+    return luceneAnalyzerClass.getConstructor(argClasses.toArray(new 
Class<?>[0]))
         .newInstance(argValues.toArray(new Object[0]));
   }
 
@@ -402,38 +404,31 @@ public class TextIndexUtils {
     return v2;
   }
 
-  /// Parse the Java value type specified in the type string
-  /// @param valueTypeString FQCN of the value type class or the name of the 
primitive value type
-  /// @return Class object of the value type
+  /// Resolves the supported analyzer constructor argument type names.
+  /// @param valueTypeString Fully qualified class name for String or a boxed 
primitive, or a primitive's TYPE name
   /// @throws ClassNotFoundException when the value type is not supported
   public static Class<?> parseSupportedTypes(String valueTypeString)
       throws ClassNotFoundException {
-    try {
-      // Support both primitive types + class
-      switch (valueTypeString) {
-        case "java.lang.Byte.TYPE":
-          return Byte.TYPE;
-        case "java.lang.Short.TYPE":
-          return Short.TYPE;
-        case "java.lang.Integer.TYPE":
-          return Integer.TYPE;
-        case "java.lang.Long.TYPE":
-          return Long.TYPE;
-        case "java.lang.Float.TYPE":
-          return Float.TYPE;
-        case "java.lang.Double.TYPE":
-          return Double.TYPE;
-        case "java.lang.Boolean.TYPE":
-          return Boolean.TYPE;
-        case "java.lang.Character.TYPE":
-          return Character.TYPE;
-        default:
-          return Class.forName(valueTypeString);
-      }
-    } catch (ClassNotFoundException ex) {
-      LOGGER.error("Analyzer argument class type not found: " + 
valueTypeString);
-      throw ex;
-    }
+    return switch (valueTypeString) {
+      case "java.lang.String" -> String.class;
+      case "java.lang.Byte" -> Byte.class;
+      case "java.lang.Short" -> Short.class;
+      case "java.lang.Integer" -> Integer.class;
+      case "java.lang.Long" -> Long.class;
+      case "java.lang.Float" -> Float.class;
+      case "java.lang.Double" -> Double.class;
+      case "java.lang.Boolean" -> Boolean.class;
+      case "java.lang.Character" -> Character.class;
+      case "java.lang.Byte.TYPE" -> byte.class;
+      case "java.lang.Short.TYPE" -> short.class;
+      case "java.lang.Integer.TYPE" -> int.class;
+      case "java.lang.Long.TYPE" -> long.class;
+      case "java.lang.Float.TYPE" -> float.class;
+      case "java.lang.Double.TYPE" -> double.class;
+      case "java.lang.Boolean.TYPE" -> boolean.class;
+      case "java.lang.Character.TYPE" -> char.class;
+      default -> throw new ClassNotFoundException("Unsupported analyzer 
argument type: " + valueTypeString);
+    };
   }
 
   /// Attempt to coerce string into supported value type
@@ -506,7 +501,7 @@ public class TextIndexUtils {
       String queryParserClassName)
       throws ReflectiveOperationException {
     // Fail-fast if the query parser is specified class is not QueryParseBase 
class
-    Class<?> queryParserClass = Class.forName(queryParserClassName);
+    Class<?> queryParserClass = Class.forName(queryParserClassName, false, 
TextIndexUtils.class.getClassLoader());
     if (queryParserClass == QueryParser.class) {
       queryParserClass = BoundedRegexpQueryParser.class;
     } else if (queryParserClass == ComplexPhraseQueryParser.class) {
diff --git 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/TableUpsertMetadataManagerFactory.java
 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/TableUpsertMetadataManagerFactory.java
index 2058ffcdada..b3dc0a9ac6e 100644
--- 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/TableUpsertMetadataManagerFactory.java
+++ 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/TableUpsertMetadataManagerFactory.java
@@ -27,6 +27,7 @@ import org.apache.pinot.spi.config.table.UpsertConfig;
 import org.apache.pinot.spi.data.Schema;
 import org.apache.pinot.spi.env.PinotConfiguration;
 import org.apache.pinot.spi.utils.CommonConstants.Server.Upsert;
+import org.apache.pinot.spi.utils.PinotReflectionUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -54,8 +55,9 @@ public class TableUpsertMetadataManagerFactory {
       LOGGER.info("Creating TableUpsertMetadataManager with class: {} for 
table: {}", metadataManagerClass,
           tableNameWithType);
       try {
-        metadataManager =
-            (TableUpsertMetadataManager) 
Class.forName(metadataManagerClass).getConstructor().newInstance();
+        metadataManager = 
PinotReflectionUtils.loadClassWithoutInitializing(metadataManagerClass,
+                TableUpsertMetadataManager.class, 
TableUpsertMetadataManagerFactory.class.getClassLoader())
+            .getConstructor().newInstance();
       } catch (Exception e) {
         throw new RuntimeException(
             String.format("Caught exception while constructing 
TableUpsertMetadataManager with class: %s for table: %s",
diff --git 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/merger/PartialUpsertMergerFactory.java
 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/merger/PartialUpsertMergerFactory.java
index f6203b686ee..f8d08478154 100644
--- 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/merger/PartialUpsertMergerFactory.java
+++ 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/merger/PartialUpsertMergerFactory.java
@@ -21,6 +21,7 @@ package org.apache.pinot.segment.local.upsert.merger;
 import java.util.List;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.pinot.spi.config.table.UpsertConfig;
+import org.apache.pinot.spi.utils.PinotReflectionUtils;
 
 
 public class PartialUpsertMergerFactory {
@@ -34,8 +35,9 @@ public class PartialUpsertMergerFactory {
     // If a custom implementation is provided in config, initialize an 
implementation and return.
     if (StringUtils.isNotBlank(customMergerClassName)) {
       try {
-        Class<?> partialUpsertMergerClass = 
Class.forName(customMergerClassName);
-        return (PartialUpsertMerger) 
partialUpsertMergerClass.getConstructor(List.class, List.class, 
UpsertConfig.class)
+        return 
PinotReflectionUtils.loadClassWithoutInitializing(customMergerClassName, 
PartialUpsertMerger.class,
+                PartialUpsertMergerFactory.class.getClassLoader())
+            .getConstructor(List.class, List.class, UpsertConfig.class)
             .newInstance(primaryKeyColumns, comparisonColumns, upsertConfig);
       } catch (Exception e) {
         throw new RuntimeException(
diff --git 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/dedup/TableDedupMetadataManagerFactoryTest.java
 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/dedup/TableDedupMetadataManagerFactoryTest.java
index 02e82df1434..5e6eaa34bd8 100644
--- 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/dedup/TableDedupMetadataManagerFactoryTest.java
+++ 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/dedup/TableDedupMetadataManagerFactoryTest.java
@@ -21,6 +21,7 @@ package org.apache.pinot.segment.local.dedup;
 import com.google.common.collect.Lists;
 import java.io.File;
 import java.io.IOException;
+import java.util.List;
 import java.util.concurrent.ExecutorService;
 import org.apache.pinot.segment.local.data.manager.TableDataManager;
 import org.apache.pinot.spi.config.table.DedupConfig;
@@ -37,9 +38,56 @@ import org.testng.annotations.Test;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.expectThrows;
+import static org.testng.Assert.fail;
 
 
 public class TableDedupMetadataManagerFactoryTest {
+  private static boolean _customManagerInitialized;
+
+  /// Test implementation that records class initialization.
+  public static class CustomDedupMetadataManager extends 
ConcurrentMapTableDedupMetadataManager {
+    static {
+      _customManagerInitialized = true;
+    }
+  }
+
+  private static class UnrelatedType {
+    static {
+      fail("An unrelated type must not be initialized");
+    }
+  }
+
+  @Test
+  public void testRejectsUnrelatedTypeBeforeInitialization() {
+    DedupConfig config = new DedupConfig();
+    config.setMetadataManagerClass(UnrelatedType.class.getName());
+    TableConfig tableConfig = new 
TableConfigBuilder(TableType.REALTIME).setTableName("dedup")
+        .setDedupConfig(config).build();
+    RuntimeException error = expectThrows(RuntimeException.class, () -> 
TableDedupMetadataManagerFactory.create(
+        new PinotConfiguration(), tableConfig, mock(Schema.class), 
mock(TableDataManager.class), null));
+    assertEquals(error.getCause().getClass(), ClassCastException.class);
+  }
+
+  @Test
+  public void testCreateForCustomManagerClass()
+      throws IOException {
+    DedupConfig config = new DedupConfig();
+    config.setMetadataManagerClass(CustomDedupMetadataManager.class.getName());
+    TableConfig tableConfig = new 
TableConfigBuilder(TableType.REALTIME).setTableName("dedup")
+        .setDedupConfig(config).build();
+    Schema schema = new Schema.SchemaBuilder().setSchemaName("dedup")
+        .addSingleValueDimension("pk", 
FieldSpec.DataType.STRING).setPrimaryKeyColumns(List.of("pk")).build();
+
+    assertFalse(_customManagerInitialized);
+    try (TableDedupMetadataManager manager = 
TableDedupMetadataManagerFactory.create(new PinotConfiguration(),
+        tableConfig, schema, mock(TableDataManager.class), null)) {
+      assertEquals(manager.getClass(), CustomDedupMetadataManager.class);
+      assertTrue(_customManagerInitialized);
+    }
+  }
 
   @Test
   public void testEnablePreload()
diff --git 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/store/TextIndexUtilsTest.java
 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/store/TextIndexUtilsTest.java
index 637174c052b..cfadf60cd13 100644
--- 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/store/TextIndexUtilsTest.java
+++ 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/store/TextIndexUtilsTest.java
@@ -19,10 +19,15 @@
 package org.apache.pinot.segment.local.segment.store;
 
 import java.io.File;
+import java.lang.reflect.Constructor;
 import java.util.Arrays;
 import java.util.List;
 import java.util.Set;
 import org.apache.commons.io.FileUtils;
+import org.apache.lucene.analysis.Analyzer;
+import org.apache.lucene.analysis.core.KeywordTokenizer;
+import org.apache.lucene.queryparser.classic.QueryParser;
+import org.apache.lucene.queryparser.classic.QueryParserBase;
 import 
org.apache.pinot.segment.local.segment.index.text.TextIndexConfigBuilder;
 import org.apache.pinot.segment.spi.V1Constants;
 import org.apache.pinot.segment.spi.index.TextIndexConfig;
@@ -30,10 +35,97 @@ import org.apache.pinot.spi.utils.JsonUtils;
 import org.testng.annotations.Test;
 
 import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertSame;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.expectThrows;
 
 
 public class TextIndexUtilsTest {
   private static final File TEMP_DIR = new File(FileUtils.getTempDirectory(), 
"TextIndexUtilsTest");
+  private static boolean _unrelatedTypeInitialized;
+  private static boolean _customAnalyzerInitialized;
+  private static boolean _customParserInitialized;
+
+  @Test
+  public void testTextIndexClassValidationDoesNotInitializeUnrelatedTypes()
+      throws Exception {
+    String className = UnrelatedType.class.getName();
+    expectThrows(ClassNotFoundException.class, () -> 
TextIndexUtils.parseSupportedTypes(className));
+    assertFalse(_unrelatedTypeInitialized);
+    TextIndexConfig config = new 
TextIndexConfigBuilder().withLuceneAnalyzerClass(className).build();
+    expectThrows(ReflectiveOperationException.class, () -> 
TextIndexUtils.getAnalyzer(config));
+    assertFalse(_unrelatedTypeInitialized);
+    expectThrows(ReflectiveOperationException.class,
+        () -> 
TextIndexUtils.getQueryParserWithStringAndAnalyzerTypeConstructor(className));
+    assertFalse(_unrelatedTypeInitialized);
+  }
+
+  private static class UnrelatedType {
+    static {
+      _unrelatedTypeInitialized = true;
+    }
+  }
+
+  @Test
+  public void testSupportedAnalyzerArgumentTypeNames()
+      throws Exception {
+    assertSame(TextIndexUtils.parseSupportedTypes(String.class.getName()), 
String.class);
+    for (Class<?> boxedType : List.of(Byte.class, Short.class, Integer.class, 
Long.class, Float.class, Double.class,
+        Boolean.class, Character.class)) {
+      String typeName = boxedType.getName();
+      assertSame(TextIndexUtils.parseSupportedTypes(typeName), boxedType);
+      assertSame(TextIndexUtils.parseSupportedTypes(typeName + ".TYPE"), 
boxedType.getField("TYPE").get(null));
+    }
+  }
+
+  @Test
+  public void testCustomAnalyzerAndParserInitializeOnConstruction()
+      throws Exception {
+    TextIndexConfig config = new 
TextIndexConfigBuilder().withLuceneAnalyzerClass(CustomAnalyzer.class.getName())
+        
.withLuceneAnalyzerClassArgs(List.of("42")).withLuceneAnalyzerClassArgTypes(List.of("java.lang.Integer.TYPE"))
+        .build();
+    assertFalse(_customAnalyzerInitialized);
+    try (Analyzer analyzer = TextIndexUtils.getAnalyzer(config)) {
+      assertTrue(_customAnalyzerInitialized);
+      assertEquals(((CustomAnalyzer) analyzer)._value, 42);
+
+      Constructor<QueryParserBase> constructor =
+          
TextIndexUtils.getQueryParserWithStringAndAnalyzerTypeConstructor(CustomParser.class.getName());
+      assertFalse(_customParserInitialized);
+      assertSame(constructor.newInstance("column", analyzer).getClass(), 
CustomParser.class);
+      assertTrue(_customParserInitialized);
+    }
+  }
+
+  /// Analyzer fixture that records initialization and accepts a configured 
constructor argument.
+  public static class CustomAnalyzer extends Analyzer {
+    static {
+      _customAnalyzerInitialized = true;
+    }
+
+    private final int _value;
+
+    public CustomAnalyzer(int value) {
+      _value = value;
+    }
+
+    @Override
+    protected TokenStreamComponents createComponents(String fieldName) {
+      return new TokenStreamComponents(new KeywordTokenizer());
+    }
+  }
+
+  /// Parser fixture that records initialization.
+  public static class CustomParser extends QueryParser {
+    static {
+      _customParserInitialized = true;
+    }
+
+    public CustomParser(String fieldName, Analyzer analyzer) {
+      super(fieldName, analyzer);
+    }
+  }
 
   @Test
   public void testRoundTripProperties()
diff --git 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/upsert/TableUpsertMetadataManagerFactoryTest.java
 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/upsert/TableUpsertMetadataManagerFactoryTest.java
index 0d062e1f8cb..616b794d0af 100644
--- 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/upsert/TableUpsertMetadataManagerFactoryTest.java
+++ 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/upsert/TableUpsertMetadataManagerFactoryTest.java
@@ -37,9 +37,11 @@ import org.testng.annotations.Test;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
 import static org.testng.Assert.assertNotNull;
 import static org.testng.Assert.assertTrue;
 import static org.testng.Assert.expectThrows;
+import static org.testng.Assert.fail;
 
 
 public class TableUpsertMetadataManagerFactoryTest {
@@ -50,6 +52,14 @@ public class TableUpsertMetadataManagerFactoryTest {
       .addDateTimeField("timeCol", DataType.LONG, "TIMESTAMP", 
"1:MILLISECONDS")
       .setPrimaryKeyColumns(List.of("myCol"))
       .build();
+  private static boolean _customManagerInitialized;
+
+  /// Test implementation that records class initialization.
+  public static class CustomUpsertMetadataManager extends 
ConcurrentMapTableUpsertMetadataManager {
+    static {
+      _customManagerInitialized = true;
+    }
+  }
 
   private TableConfig createTableConfig(UpsertConfig upsertConfig) {
     return new TableConfigBuilder(TableType.REALTIME)
@@ -59,6 +69,37 @@ public class TableUpsertMetadataManagerFactoryTest {
         .build();
   }
 
+  private static class UnrelatedType {
+    static {
+      fail("An unrelated type must not be initialized");
+    }
+  }
+
+  @Test
+  public void testRejectsUnrelatedTypeBeforeInitialization() {
+    UpsertConfig config = new UpsertConfig(UpsertConfig.Mode.FULL);
+    config.setMetadataManagerClass(UnrelatedType.class.getName());
+    RuntimeException error = expectThrows(RuntimeException.class, () -> 
TableUpsertMetadataManagerFactory.create(
+        new PinotConfiguration(), createTableConfig(config), SCHEMA, 
mock(TableDataManager.class), null));
+    assertEquals(error.getCause().getClass(), ClassCastException.class);
+  }
+
+  @Test
+  public void testCreateForCustomManagerClass()
+      throws IOException {
+    UpsertConfig config = new UpsertConfig(UpsertConfig.Mode.FULL);
+    
config.setMetadataManagerClass(CustomUpsertMetadataManager.class.getName());
+    TableDataManager tableDataManager = mock(TableDataManager.class);
+    when(tableDataManager.getTableDataDir()).thenReturn(new 
File(RAW_TABLE_NAME));
+
+    assertFalse(_customManagerInitialized);
+    try (TableUpsertMetadataManager manager = 
TableUpsertMetadataManagerFactory.create(new PinotConfiguration(),
+        createTableConfig(config), SCHEMA, tableDataManager, null)) {
+      assertEquals(manager.getClass(), CustomUpsertMetadataManager.class);
+      assertTrue(_customManagerInitialized);
+    }
+  }
+
   @Test
   public void testCreateForDefaultManagerClass() {
     UpsertConfig upsertConfig = new UpsertConfig(UpsertConfig.Mode.FULL);
diff --git 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/upsert/merger/PartialUpsertMergerFactoryTest.java
 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/upsert/merger/PartialUpsertMergerFactoryTest.java
index fab9c78bb5a..12327f5e296 100644
--- 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/upsert/merger/PartialUpsertMergerFactoryTest.java
+++ 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/upsert/merger/PartialUpsertMergerFactoryTest.java
@@ -27,14 +27,45 @@ import org.apache.pinot.spi.data.FieldSpec;
 import org.apache.pinot.spi.data.Schema;
 import org.testng.annotations.Test;
 
-import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
 import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.expectThrows;
+import static org.testng.Assert.fail;
 
 
 public class PartialUpsertMergerFactoryTest {
+  private static boolean _customMergerInitialized;
+
+  /// Test implementation that records class initialization.
+  public static class CustomPartialUpsertMerger extends 
PartialUpsertColumnarMerger {
+    static {
+      _customMergerInitialized = true;
+    }
+
+    public CustomPartialUpsertMerger(List<String> primaryKeyColumns, 
List<String> comparisonColumns,
+        UpsertConfig upsertConfig) {
+      super(primaryKeyColumns, comparisonColumns, upsertConfig);
+    }
+  }
+
+  private static class UnrelatedType {
+    static {
+      fail("An unrelated type must not be initialized");
+    }
+  }
+
+  @Test
+  public void testRejectsUnrelatedTypeBeforeInitialization() {
+    UpsertConfig config = new UpsertConfig(UpsertConfig.Mode.PARTIAL);
+    config.setPartialUpsertMergerClass(UnrelatedType.class.getName());
+    RuntimeException error = expectThrows(RuntimeException.class,
+        () -> PartialUpsertMergerFactory.getPartialUpsertMerger(List.of("pk"), 
List.of("ts"), config));
+    assertEquals(error.getCause().getClass(), ClassCastException.class);
+  }
 
   @Test
-  public void testGetPartialUpsertMerger() {
+  public void testGetCustomPartialUpsertMerger() {
     Schema schema = new Schema.SchemaBuilder().addSingleValueDimension("pk", 
FieldSpec.DataType.STRING)
         .addSingleValueDimension("field1", 
FieldSpec.DataType.LONG).addMetric("field2", FieldSpec.DataType.LONG)
         .addDateTime("hoursSinceEpoch", FieldSpec.DataType.LONG, 
"1:HOURS:EPOCH", "1:HOURS")
@@ -45,14 +76,14 @@ public class PartialUpsertMergerFactoryTest {
     partialUpsertStrategies.put("field1", UpsertConfig.Strategy.OVERWRITE);
     upsertConfig.setPartialUpsertStrategies(partialUpsertStrategies);
     upsertConfig.setDefaultPartialUpsertStrategy(UpsertConfig.Strategy.IGNORE);
-    upsertConfig.setPartialUpsertMergerClass(
-        
"org.apache.pinot.segment.local.upsert.merger.PartialUpsertColumnarMerger");
+    
upsertConfig.setPartialUpsertMergerClass(CustomPartialUpsertMerger.class.getName());
 
+    assertFalse(_customMergerInitialized);
     PartialUpsertMerger partialUpsertMerger =
         
PartialUpsertMergerFactory.getPartialUpsertMerger(schema.getPrimaryKeyColumns(),
             List.of("hoursSinceEpoch"), upsertConfig);
 
-    assertNotNull(partialUpsertMerger);
-    assertTrue(partialUpsertMerger instanceof PartialUpsertColumnarMerger);
+    assertEquals(partialUpsertMerger.getClass(), 
CustomPartialUpsertMerger.class);
+    assertTrue(_customMergerInitialized);
   }
 }
diff --git 
a/pinot-spi/src/main/java/org/apache/pinot/spi/utils/PinotReflectionUtils.java 
b/pinot-spi/src/main/java/org/apache/pinot/spi/utils/PinotReflectionUtils.java
index 5ec308688d1..9498e964e02 100644
--- 
a/pinot-spi/src/main/java/org/apache/pinot/spi/utils/PinotReflectionUtils.java
+++ 
b/pinot-spi/src/main/java/org/apache/pinot/spi/utils/PinotReflectionUtils.java
@@ -108,6 +108,13 @@ public class PinotReflectionUtils {
     }
   }
 
+  /// Loads a class through the supplied loader and verifies its type before 
initialization.
+  public static <T> Class<? extends T> loadClassWithoutInitializing(String 
className, Class<T> expectedType,
+      ClassLoader classLoader)
+      throws ClassNotFoundException {
+    return Class.forName(className, false, 
classLoader).asSubclass(expectedType);
+  }
+
   /// Executes the given runnable within the reflection lock.
   public static void runWithLock(Runnable runnable) {
     synchronized (REFLECTION_LOCK) {


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to