You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pinot.apache.org by "xiangfu0 (via GitHub)" <gi...@apache.org> on 2026/05/08 20:25:25 UTC

[PR] Make PartitionFunction registry dynamic; move impls to pinot-common [pinot]

xiangfu0 opened a new pull request, #18446:
URL: https://github.com/apache/pinot/pull/18446

   ## Summary
   
   Replaces the closed `PartitionFunctionFactory` enum/switch with an annotation-based dynamic registry so plug-in partition functions no longer require touching `pinot-segment-spi`.
   
   - New `@PartitionFunctionType(names = {...})` annotation in `pinot-spi`. Multiple aliases supported (e.g. `Murmur` / `Murmur2`).
   - `PartitionFunctionFactory` becomes a classpath-scanning registry (regex `.*\.partition\.function\..*`); the factory keeps its same static API, all callers unchanged. New `init()` mirrors `FunctionRegistry.init()` and is wired into broker / server / controller starters.
   - The seven built-in impls (`Modulo`, `Murmur` / `Murmur2`, `Murmur3`, `Fnv`, `HashCode`, `ByteArray`, `BoundedColumnValue`) move out of `pinot-segment-spi` into `org.apache.pinot.common.partition.function.*`, standardize on `(int numPartitions, Map<String,String> functionConfig)` constructor, and gain the annotation.
   - `PartitionFunction` interface gains a default `getPartitionIdNormalizer()` method, and a new `PartitionIntNormalizer` enum (`POSITIVE_MODULO` / `ABS` / `MASK`) lands in `pinot-segment-spi`. Each impl reports the closest-match normalizer name. The framework uses this only for identity / staleness matching between config-side and segment-side metadata; legacy impls still compute their own modulo internally. Javadoc spells out the descriptive-only nature for legacy functions. (This pulls in just the `getPartitionIdNormalizer` slice from #18165 so it can land independently.)
   
   ## Why
   
   Today, registering a custom partition function requires editing `PartitionFunctionFactory.PartitionFunctionType` and the `switch` block in the same SPI module. After this change, plug-ins drop a class on the classpath under `*.partition.function.*`, implement `PartitionFunction` with the standard ctor, and annotate `@PartitionFunctionType(names = "MyFn")` β€” the registry picks it up at startup.
   
   The `getPartitionIdNormalizer()` slice gives the framework a uniform way to describe int-to-partition-id semantics, paving the way for the expression-mode partition pipeline in #18165 to land cleanly without churning legacy impls again.
   
   ## Backward compatibility
   
   **This change is `backward-incompat`** for any external code that referenced the moved classes:
   
   - The seven impl classes' fully-qualified names changed: `org.apache.pinot.segment.spi.partition.*` β†’ `org.apache.pinot.common.partition.function.*`.
   - The legacy single-arg constructors on `ModuloPartitionFunction`, `HashCodePartitionFunction`, and `ByteArrayPartitionFunction` are gone; all impls now use `(int numPartitions, Map<String, String> functionConfig)` (config may be `null`).
   - `PartitionFunctionFactory.PartitionFunctionType` enum is removed (it was an internal switch helper).
   
   **Segment-on-disk format is unaffected.** `getName()` strings (`Modulo`, `Murmur`, `Murmur3`, `FNV`, `HashCode`, `ByteArray`, `BoundedColumnValue`) are unchanged, so existing segment metadata resolves through the new registry by name.
   
   ## Plug-in path going forward
   
   ```java
   package com.acme.partition.function;
   
   @PartitionFunctionType(names = "MyFn")
   public class MyPartitionFunction implements PartitionFunction {
     public MyPartitionFunction(int numPartitions, @Nullable Map<String, String> config) { ... }
     // ...
   }
   ```
   
   Drop the jar on broker / server / controller / minion classpaths β€” done.
   
   ## Test plan
   
   - [x] `./mvnw spotless:apply checkstyle:check license:format license:check -pl pinot-spi,pinot-segment-spi,pinot-common,pinot-broker,pinot-server,pinot-controller,pinot-segment-local`
   - [x] `./mvnw -pl pinot-common -am -Dtest=PartitionFunctionTest,PartitionFunctionFactoryTest,PartitionIntNormalizerTest -Dsurefire.failIfNoSpecifiedTests=false test` (33 tests pass)
   - [x] `./mvnw -pl pinot-segment-local -am -Dtest=SegmentPartitionTest,ColumnMetadataTest,MutableSegmentImplDropRecordOnPartitionMismatchTest -Dsurefire.failIfNoSpecifiedTests=false test` (18 tests pass)
   - [x] `./mvnw -pl pinot-core -am -Dtest=ColumnValueSegmentPrunerTest -Dsurefire.failIfNoSpecifiedTests=false test` (3 tests pass)
   - [x] `./mvnw -pl pinot-broker,pinot-server,pinot-controller,pinot-segment-local,pinot-core,pinot-tools -am test-compile` (full test-compile clean)
   
   New regression coverage:
   - `PartitionFunctionFactoryTest`: registration completeness across all 7 impls; alias resolution (`Murmur` / `Murmur2`); case-insensitive lookup; idempotent `init()`; unknown-name rejection; per-impl `getPartitionIdNormalizer()` label.
   - `PartitionIntNormalizerTest`: per-normalizer math at `Integer.MIN_VALUE` / `Integer.MAX_VALUE` / negative / `Long.MIN_VALUE`; range invariant `[0, numPartitions)` across all normalizers and a sweep of partition counts; `fromConfigString` round-trip, blank / null rejection, unknown-name rejection.
   
   πŸ€– Generated with [Claude Code](https://claude.com/claude-code)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Dynamic PartitionFunction registry; unify int-to-id mapping via PartitionIdNormalizer [pinot]

Posted by "xiangfu0 (via GitHub)" <gi...@apache.org>.
xiangfu0 commented on code in PR #18446:
URL: https://github.com/apache/pinot/pull/18446#discussion_r3211713083


##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionFunctionFactory.java:
##########
@@ -18,86 +18,154 @@
  */
 package org.apache.pinot.segment.spi.partition;
 
+import com.google.common.base.Preconditions;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Modifier;
+import java.util.Collections;
 import java.util.HashMap;
+import java.util.Locale;
 import java.util.Map;
+import java.util.Set;
 import javax.annotation.Nullable;
 import org.apache.pinot.segment.spi.partition.metadata.ColumnPartitionMetadata;
+import org.apache.pinot.spi.annotations.PartitionFunctionType;
 import org.apache.pinot.spi.config.table.ColumnPartitionConfig;
-
-
-/**
- * Factory to build instances of {@link PartitionFunction}.
- */
+import org.apache.pinot.spi.utils.PinotReflectionUtils;
+import org.reflections.Reflections;
+import org.reflections.scanners.SubTypesScanner;
+import org.reflections.util.ClasspathHelper;
+import org.reflections.util.ConfigurationBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/// Dynamic registry for [PartitionFunction] implementations.
+///
+/// Discovery walks every public, concrete [PartitionFunction] subtype on the classpath under the
+/// `org.apache.pinot.*` package tree, then registers each under its canonical name(s):
+///
+/// - If the class is annotated with [PartitionFunctionType] (and `enabled()` is true), the
+///   annotation's `names()` are used. Multiple aliases register the same constructor under each
+///   name (e.g. `Murmur` and `Murmur2` for `MurmurPartitionFunction`).
+/// - Otherwise, the registry probes [PartitionFunction#getName()] by instantiating the class with
+///   `(numPartitions=1, functionConfig=null)` and registers under the value returned. This lets
+///   existing partition functions work without adding the annotation.
+///
+/// Each registrable class must be public, concrete, and expose a public constructor with signature
+/// `(int numPartitions, Map<String, String> functionConfig)` β€” the constructor the registry calls
+/// when [#getPartitionFunction(String, int, Map)] is invoked.
+///
+/// The static block scans the classpath once and builds an immutable (canonicalized name β†’
+/// constructor) map. To force eager initialization (e.g. so the scan happens before the first
+/// segment is read), call [#init()] from broker / server / controller startup.
 public class PartitionFunctionFactory {
-  // Enum for various partition functions to be added.
-  public enum PartitionFunctionType {
-    Modulo, Murmur, Murmur2, Murmur3, Fnv, ByteArray, HashCode, BoundedColumnValue;
-    // Add more functions here.
+  private PartitionFunctionFactory() {
+  }
+
+  private static final Logger LOGGER = LoggerFactory.getLogger(PartitionFunctionFactory.class);
+  private static final String SCAN_PACKAGE = "org.apache.pinot";
 
-    private static final Map<String, PartitionFunctionType> VALUE_MAP = new HashMap<>();
+  private static final Map<String, Constructor<? extends PartitionFunction>> REGISTRY;
 
-    static {
-      for (PartitionFunctionType functionType : PartitionFunctionType.values()) {
-        VALUE_MAP.put(functionType.name().toLowerCase(), functionType);
+  static {
+    long startTimeMs = System.currentTimeMillis();
+    Map<String, Constructor<? extends PartitionFunction>> registry = new HashMap<>();
+    Set<Class<? extends PartitionFunction>> subtypes = scanSubtypes();
+    for (Class<? extends PartitionFunction> clazz : subtypes) {
+      int mods = clazz.getModifiers();
+      if (!Modifier.isPublic(mods) || Modifier.isAbstract(mods) || clazz.isInterface()) {
+        continue;
+      }
+      PartitionFunctionType annotation = clazz.getAnnotation(PartitionFunctionType.class);
+      if (annotation != null && !annotation.enabled()) {
+        continue;
+      }
+      Constructor<? extends PartitionFunction> constructor;
+      try {
+        constructor = clazz.getConstructor(int.class, Map.class);
+      } catch (NoSuchMethodException e) {
+        LOGGER.warn("Skipping {}: missing public constructor (int, Map<String, String>)", clazz.getName());
+        continue;
+      }
+      String[] names = resolveNames(clazz, annotation, constructor);
+      if (names == null) {
+        continue;
+      }
+      for (String name : names) {
+        String canonical = canonicalize(name);
+        Constructor<? extends PartitionFunction> existing = registry.put(canonical, constructor);
+        Preconditions.checkState(existing == null || existing.getDeclaringClass().equals(clazz),
+            "Partition function name '%s' is registered to both %s and %s", name,
+            existing == null ? null : existing.getDeclaringClass().getName(), clazz.getName());
       }

Review Comment:
   Done in 182d8d1 β€” `resolveNames()` now trims each annotation entry, drops blanks, and falls back to `getName()` (with a warning log) when all declared aliases are blank. Prevents an empty canonical name from poisoning the registry.



##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionIdNormalizer.java:
##########
@@ -0,0 +1,112 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.spi.partition;
+
+import com.google.common.base.Preconditions;
+import java.util.Locale;
+
+
+/// Maps a raw signed integer hash output to a non-negative partition id in `[0, numPartitions)`.
+///
+/// [PartitionFunction] implementations apply the configured normalizer in their
+/// `getPartition(...)` body and report it via [PartitionFunction#getPartitionIdNormalizer()].
+/// The framework also uses the reported value for identity / staleness matching between
+/// config-side and segment-side partition metadata.
+public enum PartitionIdNormalizer {
+  /// Compute the remainder, then shift negative remainders into the valid range with `+ numPartitions`.
+  POSITIVE_MODULO {
+    @Override
+    int toPartitionId(int value, int numPartitions) {
+      int partition = value % numPartitions;
+      return partition < 0 ? partition + numPartitions : partition;
+    }
+
+    @Override
+    int toPartitionId(long value, int numPartitions) {
+      long partition = value % numPartitions;
+      return (int) (partition < 0 ? partition + numPartitions : partition);
+    }
+  },
+  /// Compute the remainder, then take its absolute value.
+  ABS {
+    @Override
+    int toPartitionId(int value, int numPartitions) {
+      int partition = value % numPartitions;
+      return partition < 0 ? -partition : partition;
+    }
+
+    @Override
+    int toPartitionId(long value, int numPartitions) {
+      long partition = value % numPartitions;
+      return (int) (partition < 0 ? -partition : partition);
+    }
+  },
+  /// Mask the sign bit before applying modulo.
+  MASK {
+    @Override
+    int toPartitionId(int value, int numPartitions) {
+      return (value & Integer.MAX_VALUE) % numPartitions;
+    }
+
+    @Override
+    int toPartitionId(long value, int numPartitions) {
+      return (int) ((value & Long.MAX_VALUE) % numPartitions);
+    }
+  },
+  /// Pre-modulo abs (Kafka-style) `abs(value) % numPartitions` that handles `Integer.MIN_VALUE -> 0`
+  /// (and `Long.MIN_VALUE -> 0`) to avoid the `Math.abs` overflow corner. Matches the
+  /// legacy semantics of `HashCodePartitionFunction` and `ByteArrayPartitionFunction`.
+  PRE_MODULO_ABS {
+    @Override
+    int toPartitionId(int value, int numPartitions) {
+      int abs = (value == Integer.MIN_VALUE) ? 0 : Math.abs(value);
+      return abs % numPartitions;
+    }
+
+    @Override
+    int toPartitionId(long value, int numPartitions) {
+      long abs = (value == Long.MIN_VALUE) ? 0L : Math.abs(value);
+      return (int) (abs % numPartitions);
+    }
+  };

Review Comment:
   Good catch β€” PR description has been updated to use `PRE_MODULO_ABS` consistently throughout. The enum constant and config-string value are both `PRE_MODULO_ABS`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Dynamic PartitionFunction registry; unify int-to-id mapping via PartitionIdNormalizer [pinot]

Posted by "xiangfu0 (via GitHub)" <gi...@apache.org>.
xiangfu0 merged PR #18446:
URL: https://github.com/apache/pinot/pull/18446


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Make PartitionFunction registry dynamic; move impls to pinot-common [pinot]

Posted by "xiangfu0 (via GitHub)" <gi...@apache.org>.
xiangfu0 commented on code in PR #18446:
URL: https://github.com/apache/pinot/pull/18446#discussion_r3211631223


##########
pinot-common/src/main/java/org/apache/pinot/common/partition/function/BoundedColumnValuePartitionFunction.java:
##########
@@ -16,15 +16,18 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-package org.apache.pinot.segment.spi.partition;
+package org.apache.pinot.common.partition.function;
 
 import com.google.common.base.Preconditions;
 import java.util.Map;
 import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.segment.spi.partition.PartitionFunction;
+import org.apache.pinot.segment.spi.partition.PartitionIntNormalizer;
+import org.apache.pinot.spi.annotations.PartitionFunctionType;
 
 
 /**
- * Implementation of {@link PartitionFunction} which partitions based configured column values.
+ * Implementation of {@link PartitionFunction} which partitions based on configured column values.

Review Comment:
   Done β€” converted all new Javadoc to JEP 467 `///` markdown syntax in commit 31ce6ba and again touched up here.



##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionFunction.java:
##########
@@ -57,4 +59,19 @@ public interface PartitionFunction extends Serializable {
   default Map<String, String> getFunctionConfig() {
     return null;
   }
+
+  /**
+   * Reports the {@link PartitionIntNormalizer} that drives this partition function's int-to-id
+   * mapping. The built-in implementations now apply the named normalizer directly, so the value is
+   * authoritative β€” recomputing a partition via
+   * {@code PartitionIntNormalizer.valueOf(getPartitionIdNormalizer()).getPartitionId(rawHash, numPartitions)}
+   * yields the same result as {@link #getPartition(String)} for the same raw hash input.
+   *
+   * <p>Used by the framework for identity / staleness matching between config-side and segment-side
+   * partition metadata. Each implementation must declare its own value β€” there is intentionally no
+   * default. Plug-ins whose output is already in {@code [0, numPartitions)} should return
+   * {@link PartitionIntNormalizer#POSITIVE_MODULO} (a no-op label).
+   */
+  @JsonIgnore

Review Comment:
   Done β€” `@JsonIgnore` removed and the return type is now `PartitionIdNormalizer` (the enum) instead of `String`. The `testBasicProperties` JSON-shape assertion was updated to expect the new `partitionIdNormalizer` field.



##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionFunctionFactory.java:
##########
@@ -18,86 +18,118 @@
  */
 package org.apache.pinot.segment.spi.partition;
 
+import com.google.common.base.Preconditions;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Modifier;
+import java.util.Collections;
 import java.util.HashMap;
+import java.util.Locale;
 import java.util.Map;
 import javax.annotation.Nullable;
 import org.apache.pinot.segment.spi.partition.metadata.ColumnPartitionMetadata;
+import org.apache.pinot.spi.annotations.PartitionFunctionType;
 import org.apache.pinot.spi.config.table.ColumnPartitionConfig;
+import org.apache.pinot.spi.utils.PinotReflectionUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 
 /**
- * Factory to build instances of {@link PartitionFunction}.
+ * Dynamic registry for {@link PartitionFunction} implementations.
+ *
+ * <p>Discovery is driven by classpath scanning for classes annotated with
+ * {@link PartitionFunctionType}. Annotated classes must:
+ * <ul>
+ *   <li>be public and implement {@link PartitionFunction}</li>
+ *   <li>live under a package matching the regex {@code .*\.partition\.function\..*}
+ *       (e.g. {@code org.apache.pinot.common.partition.function} or any plugin package
+ *       that follows the same convention)</li>
+ *   <li>expose a public constructor with signature
+ *       {@code (int numPartitions, Map<String, String> functionConfig)}</li>
+ * </ul>
+ *
+ * <p>The static block scans the classpath once and builds an immutable
+ * (canonicalized name β†’ constructor) map. Instances are created on demand by
+ * {@link #getPartitionFunction(String, int, Map)}.
+ *
+ * <p>To force eager initialization (e.g. so the scan happens before the first segment
+ * is read), call {@link #init()} from broker/server/controller startup.
  */
 public class PartitionFunctionFactory {
-  // Enum for various partition functions to be added.
-  public enum PartitionFunctionType {
-    Modulo, Murmur, Murmur2, Murmur3, Fnv, ByteArray, HashCode, BoundedColumnValue;
-    // Add more functions here.
+  private PartitionFunctionFactory() {
+  }
 
-    private static final Map<String, PartitionFunctionType> VALUE_MAP = new HashMap<>();
+  private static final Logger LOGGER = LoggerFactory.getLogger(PartitionFunctionFactory.class);
+  private static final String SCAN_REGEX = ".*\\.partition\\.function\\..*";
 
-    static {
-      for (PartitionFunctionType functionType : PartitionFunctionType.values()) {
-        VALUE_MAP.put(functionType.name().toLowerCase(), functionType);
-      }
-    }
-
-    public static PartitionFunctionType fromString(String name) {
-      PartitionFunctionType functionType = VALUE_MAP.get(name.toLowerCase());
+  private static final Map<String, Constructor<? extends PartitionFunction>> REGISTRY;
 
-      if (functionType == null) {
-        throw new IllegalArgumentException("No enum constant for: " + name);
+  static {
+    long startTimeMs = System.currentTimeMillis();
+    Map<String, Constructor<? extends PartitionFunction>> registry = new HashMap<>();
+    for (Class<?> clazz : PinotReflectionUtils.getClassesThroughReflection(SCAN_REGEX, PartitionFunctionType.class)) {
+      if (!Modifier.isPublic(clazz.getModifiers()) || !PartitionFunction.class.isAssignableFrom(clazz)) {

Review Comment:
   Acknowledged β€” clarified the Javadoc to state that scanning is rooted at `org.apache.pinot.*`. Per Pinot's plugin convention, third-party plugins live under that tree, so the documented behavior now matches the implementation. (See follow-up commit.)



##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionFunctionFactory.java:
##########
@@ -108,4 +140,8 @@ public static PartitionFunction getPartitionFunction(ColumnPartitionConfig confi
   public static PartitionFunction getPartitionFunction(ColumnPartitionMetadata metadata) {
     return getPartitionFunction(metadata.getFunctionName(), metadata.getNumPartitions(), metadata.getFunctionConfig());
   }
+
+  private static String canonicalize(String name) {
+    return name.toLowerCase(Locale.ROOT);

Review Comment:
   Done β€” Javadoc updated to drop the "stripping underscores" claim. Lookup is just lower-case canonicalization.



##########
pinot-spi/src/main/java/org/apache/pinot/spi/annotations/PartitionFunctionType.java:
##########
@@ -0,0 +1,62 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.spi.annotations;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+
+/**
+ * Marker annotation for plug-in {@code PartitionFunction} implementations.
+ *
+ * <p>Classes annotated with this annotation are auto-discovered at startup by
+ * {@code PartitionFunctionFactory} via classpath scanning. Each annotated class must:
+ * <ul>
+ *   <li>Implement {@code org.apache.pinot.segment.spi.partition.PartitionFunction}</li>
+ *   <li>Be public</li>
+ *   <li>Live under a package matching {@code .*\.partition\.function\..*} (e.g.
+ *       {@code org.apache.pinot.common.partition.function} or any plugin package
+ *       that follows the same convention)</li>

Review Comment:
   Done β€” annotation-based scan is no longer the only entry point. The factory now scans for `PartitionFunction` subtypes and falls back to `getName()` when the annotation is absent (see Jackie's review thread on the same point). Existing `PartitionFunction` impls without the annotation work.



##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionFunction.java:
##########
@@ -57,4 +59,19 @@ public interface PartitionFunction extends Serializable {
   default Map<String, String> getFunctionConfig() {
     return null;
   }
+
+  /**
+   * Reports the {@link PartitionIntNormalizer} that drives this partition function's int-to-id
+   * mapping. The built-in implementations now apply the named normalizer directly, so the value is
+   * authoritative β€” recomputing a partition via
+   * {@code PartitionIntNormalizer.valueOf(getPartitionIdNormalizer()).getPartitionId(rawHash, numPartitions)}
+   * yields the same result as {@link #getPartition(String)} for the same raw hash input.
+   *
+   * <p>Used by the framework for identity / staleness matching between config-side and segment-side
+   * partition metadata. Each implementation must declare its own value β€” there is intentionally no
+   * default. Plug-ins whose output is already in {@code [0, numPartitions)} should return
+   * {@link PartitionIntNormalizer#POSITIVE_MODULO} (a no-op label).
+   */
+  @JsonIgnore
+  String getPartitionIdNormalizer();

Review Comment:
   Resolved by Jackie's request that every implementation declare its own normalizer. Method stays abstract; built-ins all override. Existing third-party impls without the annotation are still discoverable via the new `getName()` fallback in the factory, but they too must implement the abstract method (acceptable break per the PR's `backward-incompat` label).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Dynamic PartitionFunction registry; unify int-to-id mapping via PartitionIdNormalizer [pinot]

Posted by "Jackie-Jiang (via GitHub)" <gi...@apache.org>.
Jackie-Jiang commented on code in PR #18446:
URL: https://github.com/apache/pinot/pull/18446#discussion_r3211796874


##########
pinot-common/src/main/java/org/apache/pinot/common/partition/function/BoundedColumnValuePartitionFunction.java:
##########
@@ -16,29 +16,34 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-package org.apache.pinot.segment.spi.partition;
+package org.apache.pinot.common.partition.function;
 
 import com.google.common.base.Preconditions;
 import java.util.Map;
 import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.segment.spi.partition.PartitionFunction;
+import org.apache.pinot.segment.spi.partition.PartitionIdNormalizer;
+import org.apache.pinot.spi.annotations.PartitionFunctionType;
 
 
-/**
- * Implementation of {@link PartitionFunction} which partitions based configured column values.
- *
- * "columnPartitionMap": {
- *   "subject": {
- *     "functionName": "BoundedColumnValue",
- *     "functionConfig": {
- *       "columnValues": "Maths|English|Chemistry",
- *       "columnValuesDelimiter": "|"
- *     },
- *     "numPartitions": 4
- *   }
- * }
- * With this partition config on column "subject", partitionId would be 1 for Maths, 2 for English and 3 for Chemistry.
- * partitionId would be "0" for all other values which may occur, therefore 'numPartitions' is set to 4.
- */
+/// Implementation of [PartitionFunction] which partitions based on configured column values.
+///
+/// ```json
+/// "columnPartitionMap": {
+///   "subject": {
+///     "functionName": "BoundedColumnValue",
+///     "functionConfig": {
+///       "columnValues": "Maths|English|Chemistry",
+///       "columnValuesDelimiter": "|"
+///     },
+///     "numPartitions": 4
+///   }
+/// }
+/// ```
+///
+/// With this partition config on column "subject", `partitionId` is `1` for Maths, `2` for English and `3` for
+/// Chemistry. `partitionId` is `0` for all other values which may occur, therefore `numPartitions` is set to `4`.
+@PartitionFunctionType(names = "BoundedColumnValue")

Review Comment:
   We don't really need this annotation. Consider replacing it by adding:
   ```
     default List<String> getNames() {
       return List.of(getName());
     }
   ```



##########
pinot-common/src/main/java/org/apache/pinot/common/partition/function/BoundedColumnValuePartitionFunction.java:
##########
@@ -91,6 +94,12 @@ public Map<String, String> getFunctionConfig() {
     return _functionConfig;
   }
 
+  @Override
+  public PartitionIdNormalizer getPartitionIdNormalizer() {
+    // Output is a fixed mapping in [0, numPartitions); POSITIVE_MODULO is a no-op label.
+    return PartitionIdNormalizer.POSITIVE_MODULO;

Review Comment:
   Consider adding an explicit NO_OP normalizer



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Make PartitionFunction registry dynamic; move impls to pinot-common [pinot]

Posted by "xiangfu0 (via GitHub)" <gi...@apache.org>.
xiangfu0 commented on code in PR #18446:
URL: https://github.com/apache/pinot/pull/18446#discussion_r3211631941


##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionIntNormalizer.java:
##########
@@ -0,0 +1,116 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.spi.partition;
+
+import com.google.common.base.Preconditions;
+import java.util.Locale;
+
+
+/**
+ * Maps a raw signed integer hash output to a non-negative partition id in {@code [0, numPartitions)}.
+ *
+ * <p>{@link PartitionFunction} implementations report which normalizer matches their internal modulo
+ * semantics via {@link PartitionFunction#getPartitionIdNormalizer()}. The framework uses this label
+ * for identity / staleness matching between config-side and segment-side partition metadata; legacy
+ * functions perform their own modulo internally and the value is purely descriptive for them.
+ */
+public enum PartitionIntNormalizer {
+  /** Compute the remainder, then shift negative remainders into the valid range with {@code + numPartitions}. */
+  POSITIVE_MODULO {
+    @Override
+    int toPartitionId(int value, int numPartitions) {
+      int partition = value % numPartitions;
+      return partition < 0 ? partition + numPartitions : partition;
+    }
+
+    @Override
+    int toPartitionId(long value, int numPartitions) {
+      long partition = value % numPartitions;
+      return (int) (partition < 0 ? partition + numPartitions : partition);
+    }
+  },
+  /** Compute the remainder, then take its absolute value. */
+  ABS {
+    @Override
+    int toPartitionId(int value, int numPartitions) {
+      int partition = value % numPartitions;
+      return partition < 0 ? -partition : partition;
+    }
+
+    @Override
+    int toPartitionId(long value, int numPartitions) {
+      long partition = value % numPartitions;
+      return (int) (partition < 0 ? -partition : partition);
+    }
+  },
+  /** Mask the sign bit before applying modulo. */
+  MASK {
+    @Override
+    int toPartitionId(int value, int numPartitions) {
+      return (value & Integer.MAX_VALUE) % numPartitions;
+    }
+
+    @Override
+    int toPartitionId(long value, int numPartitions) {
+      return (int) ((value & Long.MAX_VALUE) % numPartitions);
+    }
+  },
+  /**
+   * Kafka-style {@code abs(value) % numPartitions} that handles {@code Integer.MIN_VALUE -> 0}
+   * (and {@code Long.MIN_VALUE -> 0}) to avoid the {@code Math.abs} overflow corner. Matches the
+   * legacy semantics of {@code HashCodePartitionFunction} and {@code ByteArrayPartitionFunction}.
+   */
+  KAFKA_ABS {

Review Comment:
   Done β€” renamed `KAFKA_ABS` to `PRE_MODULO_ABS` to make the pre-vs-post-modulo distinction with `ABS` explicit.



##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionIntNormalizer.java:
##########
@@ -0,0 +1,116 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.spi.partition;
+
+import com.google.common.base.Preconditions;
+import java.util.Locale;
+
+
+/**
+ * Maps a raw signed integer hash output to a non-negative partition id in {@code [0, numPartitions)}.
+ *
+ * <p>{@link PartitionFunction} implementations report which normalizer matches their internal modulo
+ * semantics via {@link PartitionFunction#getPartitionIdNormalizer()}. The framework uses this label
+ * for identity / staleness matching between config-side and segment-side partition metadata; legacy
+ * functions perform their own modulo internally and the value is purely descriptive for them.
+ */
+public enum PartitionIntNormalizer {

Review Comment:
   Done β€” renamed to `PartitionIdNormalizer`.



##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionFunctionFactory.java:
##########
@@ -18,86 +18,118 @@
  */
 package org.apache.pinot.segment.spi.partition;
 
+import com.google.common.base.Preconditions;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Modifier;
+import java.util.Collections;
 import java.util.HashMap;
+import java.util.Locale;
 import java.util.Map;
 import javax.annotation.Nullable;
 import org.apache.pinot.segment.spi.partition.metadata.ColumnPartitionMetadata;
+import org.apache.pinot.spi.annotations.PartitionFunctionType;
 import org.apache.pinot.spi.config.table.ColumnPartitionConfig;
+import org.apache.pinot.spi.utils.PinotReflectionUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 
 /**
- * Factory to build instances of {@link PartitionFunction}.
+ * Dynamic registry for {@link PartitionFunction} implementations.
+ *
+ * <p>Discovery is driven by classpath scanning for classes annotated with
+ * {@link PartitionFunctionType}. Annotated classes must:
+ * <ul>
+ *   <li>be public and implement {@link PartitionFunction}</li>
+ *   <li>live under a package matching the regex {@code .*\.partition\.function\..*}
+ *       (e.g. {@code org.apache.pinot.common.partition.function} or any plugin package
+ *       that follows the same convention)</li>
+ *   <li>expose a public constructor with signature
+ *       {@code (int numPartitions, Map<String, String> functionConfig)}</li>
+ * </ul>
+ *
+ * <p>The static block scans the classpath once and builds an immutable
+ * (canonicalized name β†’ constructor) map. Instances are created on demand by
+ * {@link #getPartitionFunction(String, int, Map)}.
+ *
+ * <p>To force eager initialization (e.g. so the scan happens before the first segment
+ * is read), call {@link #init()} from broker/server/controller startup.
  */
 public class PartitionFunctionFactory {
-  // Enum for various partition functions to be added.
-  public enum PartitionFunctionType {
-    Modulo, Murmur, Murmur2, Murmur3, Fnv, ByteArray, HashCode, BoundedColumnValue;
-    // Add more functions here.
+  private PartitionFunctionFactory() {
+  }
 
-    private static final Map<String, PartitionFunctionType> VALUE_MAP = new HashMap<>();
+  private static final Logger LOGGER = LoggerFactory.getLogger(PartitionFunctionFactory.class);
+  private static final String SCAN_REGEX = ".*\\.partition\\.function\\..*";
 
-    static {
-      for (PartitionFunctionType functionType : PartitionFunctionType.values()) {
-        VALUE_MAP.put(functionType.name().toLowerCase(), functionType);
-      }
-    }
-
-    public static PartitionFunctionType fromString(String name) {
-      PartitionFunctionType functionType = VALUE_MAP.get(name.toLowerCase());
+  private static final Map<String, Constructor<? extends PartitionFunction>> REGISTRY;
 
-      if (functionType == null) {
-        throw new IllegalArgumentException("No enum constant for: " + name);
+  static {
+    long startTimeMs = System.currentTimeMillis();
+    Map<String, Constructor<? extends PartitionFunction>> registry = new HashMap<>();
+    for (Class<?> clazz : PinotReflectionUtils.getClassesThroughReflection(SCAN_REGEX, PartitionFunctionType.class)) {
+      if (!Modifier.isPublic(clazz.getModifiers()) || !PartitionFunction.class.isAssignableFrom(clazz)) {
+        continue;
+      }
+      PartitionFunctionType annotation = clazz.getAnnotation(PartitionFunctionType.class);
+      if (!annotation.enabled()) {
+        continue;
+      }
+      String[] names = annotation.names();
+      Preconditions.checkState(names.length > 0,

Review Comment:
   Done β€” annotation is now optional. Factory scans every public, concrete `PartitionFunction` subtype under `org.apache.pinot.*`. When the annotation is absent (or its `names()` is empty), the registry instantiates the class with `(1, null)` and registers under `getName()`. Added `UnannotatedTestPartitionFunction` fixture + test for the fallback path.



##########
pinot-common/src/main/java/org/apache/pinot/common/partition/function/BoundedColumnValuePartitionFunction.java:
##########
@@ -38,15 +41,23 @@
  * }
  * With this partition config on column "subject", partitionId would be 1 for Maths, 2 for English and 3 for Chemistry.
  * partitionId would be "0" for all other values which may occur, therefore 'numPartitions' is set to 4.
+ *
+ * <p>The mapping output is already in {@code [0, numPartitions)}, so the configured
+ * {@link PartitionIntNormalizer} (default {@link PartitionIntNormalizer#POSITIVE_MODULO}) is a
+ * no-op for in-range values; it is still applied so the field is uniform across all partition
+ * functions.
  */
+@PartitionFunctionType(names = "BoundedColumnValue")

Review Comment:
   Done β€” dropped the `_normalizer` field from `BoundedColumnValuePartitionFunction`. The class returns `PartitionIdNormalizer.POSITIVE_MODULO` directly (no-op label since its output is already a fixed mapping in `[0, numPartitions)`).



##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionFunction.java:
##########
@@ -57,4 +59,19 @@ public interface PartitionFunction extends Serializable {
   default Map<String, String> getFunctionConfig() {
     return null;
   }
+
+  /**
+   * Reports the {@link PartitionIntNormalizer} that drives this partition function's int-to-id
+   * mapping. The built-in implementations now apply the named normalizer directly, so the value is
+   * authoritative β€” recomputing a partition via
+   * {@code PartitionIntNormalizer.valueOf(getPartitionIdNormalizer()).getPartitionId(rawHash, numPartitions)}
+   * yields the same result as {@link #getPartition(String)} for the same raw hash input.
+   *
+   * <p>Used by the framework for identity / staleness matching between config-side and segment-side
+   * partition metadata. Each implementation must declare its own value β€” there is intentionally no
+   * default. Plug-ins whose output is already in {@code [0, numPartitions)} should return
+   * {@link PartitionIntNormalizer#POSITIVE_MODULO} (a no-op label).
+   */
+  @JsonIgnore
+  String getPartitionIdNormalizer();

Review Comment:
   Per offline discussion: keeping the method abstract so every `PartitionFunction` implementation explicitly declares its int-to-id semantics. This makes config-side / segment-side staleness matching authoritative. Plug-in impls that don't map onto a standard normalizer can return `POSITIVE_MODULO` (no-op when output is already in `[0, N)`).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Dynamic PartitionFunction registry; unify int-to-id mapping via PartitionIdNormalizer [pinot]

Posted by "xiangfu0 (via GitHub)" <gi...@apache.org>.
xiangfu0 commented on PR #18446:
URL: https://github.com/apache/pinot/pull/18446#issuecomment-4412962490

   Docs follow-up: pinot-contrib/pinot-docs#805 documents the updated partition function registry, built-in normalizer defaults, `Murmur2` aliasing, and `BoundedColumnValue` guidance. The docs PR has already merged into `latest`: https://github.com/pinot-contrib/pinot-docs/pull/805


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Make PartitionFunction registry dynamic; move impls to pinot-common [pinot]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #18446:
URL: https://github.com/apache/pinot/pull/18446#discussion_r3211472560


##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionFunctionFactory.java:
##########
@@ -18,86 +18,118 @@
  */
 package org.apache.pinot.segment.spi.partition;
 
+import com.google.common.base.Preconditions;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Modifier;
+import java.util.Collections;
 import java.util.HashMap;
+import java.util.Locale;
 import java.util.Map;
 import javax.annotation.Nullable;
 import org.apache.pinot.segment.spi.partition.metadata.ColumnPartitionMetadata;
+import org.apache.pinot.spi.annotations.PartitionFunctionType;
 import org.apache.pinot.spi.config.table.ColumnPartitionConfig;
+import org.apache.pinot.spi.utils.PinotReflectionUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 
 /**
- * Factory to build instances of {@link PartitionFunction}.
+ * Dynamic registry for {@link PartitionFunction} implementations.
+ *
+ * <p>Discovery is driven by classpath scanning for classes annotated with
+ * {@link PartitionFunctionType}. Annotated classes must:
+ * <ul>
+ *   <li>be public and implement {@link PartitionFunction}</li>
+ *   <li>live under a package matching the regex {@code .*\.partition\.function\..*}
+ *       (e.g. {@code org.apache.pinot.common.partition.function} or any plugin package
+ *       that follows the same convention)</li>
+ *   <li>expose a public constructor with signature
+ *       {@code (int numPartitions, Map<String, String> functionConfig)}</li>
+ * </ul>
+ *
+ * <p>The static block scans the classpath once and builds an immutable
+ * (canonicalized name β†’ constructor) map. Instances are created on demand by
+ * {@link #getPartitionFunction(String, int, Map)}.
+ *
+ * <p>To force eager initialization (e.g. so the scan happens before the first segment
+ * is read), call {@link #init()} from broker/server/controller startup.
  */
 public class PartitionFunctionFactory {
-  // Enum for various partition functions to be added.
-  public enum PartitionFunctionType {
-    Modulo, Murmur, Murmur2, Murmur3, Fnv, ByteArray, HashCode, BoundedColumnValue;
-    // Add more functions here.
+  private PartitionFunctionFactory() {
+  }
 
-    private static final Map<String, PartitionFunctionType> VALUE_MAP = new HashMap<>();
+  private static final Logger LOGGER = LoggerFactory.getLogger(PartitionFunctionFactory.class);
+  private static final String SCAN_REGEX = ".*\\.partition\\.function\\..*";
 
-    static {
-      for (PartitionFunctionType functionType : PartitionFunctionType.values()) {
-        VALUE_MAP.put(functionType.name().toLowerCase(), functionType);
-      }
-    }
-
-    public static PartitionFunctionType fromString(String name) {
-      PartitionFunctionType functionType = VALUE_MAP.get(name.toLowerCase());
+  private static final Map<String, Constructor<? extends PartitionFunction>> REGISTRY;
 
-      if (functionType == null) {
-        throw new IllegalArgumentException("No enum constant for: " + name);
+  static {
+    long startTimeMs = System.currentTimeMillis();
+    Map<String, Constructor<? extends PartitionFunction>> registry = new HashMap<>();
+    for (Class<?> clazz : PinotReflectionUtils.getClassesThroughReflection(SCAN_REGEX, PartitionFunctionType.class)) {
+      if (!Modifier.isPublic(clazz.getModifiers()) || !PartitionFunction.class.isAssignableFrom(clazz)) {

Review Comment:
   `PartitionFunctionFactory` discovery currently calls `PinotReflectionUtils.getClassesThroughReflection(SCAN_REGEX, ...)`, which only scans under the hard-coded base package `org.apache.pinot` (see `PinotReflectionUtils.PINOT_PACKAGE_NAME`). That means third-party partition functions in external packages (e.g. `com.acme.partition.function.*`) will never be discovered, despite the annotation/Javadoc implying they will. Consider either (a) scanning additional configurable base packages (similar to other registries that accept a package list), or (b) updating the plugin contract/Javadoc to explicitly require `org.apache.pinot.*` packages.



##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionFunctionFactory.java:
##########
@@ -108,4 +140,8 @@ public static PartitionFunction getPartitionFunction(ColumnPartitionConfig confi
   public static PartitionFunction getPartitionFunction(ColumnPartitionMetadata metadata) {
     return getPartitionFunction(metadata.getFunctionName(), metadata.getNumPartitions(), metadata.getFunctionConfig());
   }
+
+  private static String canonicalize(String name) {
+    return name.toLowerCase(Locale.ROOT);

Review Comment:
   The Javadoc for `functionName` says lookup is case-insensitive β€œafter stripping underscores”, but `canonicalize()` currently only lower-cases the name. Either implement the underscore-stripping behavior (and consider trimming) or update the Javadoc to match the actual normalization.
   



##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionFunction.java:
##########
@@ -57,4 +59,19 @@ public interface PartitionFunction extends Serializable {
   default Map<String, String> getFunctionConfig() {
     return null;
   }
+
+  /**
+   * Reports the {@link PartitionIntNormalizer} that drives this partition function's int-to-id
+   * mapping. The built-in implementations now apply the named normalizer directly, so the value is
+   * authoritative β€” recomputing a partition via
+   * {@code PartitionIntNormalizer.valueOf(getPartitionIdNormalizer()).getPartitionId(rawHash, numPartitions)}
+   * yields the same result as {@link #getPartition(String)} for the same raw hash input.
+   *
+   * <p>Used by the framework for identity / staleness matching between config-side and segment-side
+   * partition metadata. Each implementation must declare its own value β€” there is intentionally no
+   * default. Plug-ins whose output is already in {@code [0, numPartitions)} should return
+   * {@link PartitionIntNormalizer#POSITIVE_MODULO} (a no-op label).
+   */
+  @JsonIgnore
+  String getPartitionIdNormalizer();

Review Comment:
   `PartitionFunction` adds `getPartitionIdNormalizer()` as a new abstract method. Because this is a public SPI interface, making it abstract is source/binary incompatible for any existing external `PartitionFunction` implementations (they will fail to compile or can hit `AbstractMethodError` at runtime). If backward compatibility is desired (as stated in the PR description), make this a `default` method (e.g., returning `PartitionIntNormalizer.POSITIVE_MODULO.name()`), and let built-ins override it.
   



##########
pinot-spi/src/main/java/org/apache/pinot/spi/annotations/PartitionFunctionType.java:
##########
@@ -0,0 +1,62 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.spi.annotations;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+
+/**
+ * Marker annotation for plug-in {@code PartitionFunction} implementations.
+ *
+ * <p>Classes annotated with this annotation are auto-discovered at startup by
+ * {@code PartitionFunctionFactory} via classpath scanning. Each annotated class must:
+ * <ul>
+ *   <li>Implement {@code org.apache.pinot.segment.spi.partition.PartitionFunction}</li>
+ *   <li>Be public</li>
+ *   <li>Live under a package matching {@code .*\.partition\.function\..*} (e.g.
+ *       {@code org.apache.pinot.common.partition.function} or any plugin package
+ *       that follows the same convention)</li>

Review Comment:
   `@PartitionFunctionType` Javadoc states implementations can live in β€œany plugin package that follows the same convention”, but the current factory implementation scans only within `org.apache.pinot` (via `PinotReflectionUtils.getClassesThroughReflection(...)`). Either adjust discovery to include non-`org.apache.pinot` packages, or update this Javadoc to avoid advertising unsupported plugin locations.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Make PartitionFunction registry dynamic; move impls to pinot-common [pinot]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #18446:
URL: https://github.com/apache/pinot/pull/18446#discussion_r3211690169


##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionIdNormalizer.java:
##########
@@ -0,0 +1,112 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.spi.partition;
+
+import com.google.common.base.Preconditions;
+import java.util.Locale;
+
+
+/// Maps a raw signed integer hash output to a non-negative partition id in `[0, numPartitions)`.
+///
+/// [PartitionFunction] implementations apply the configured normalizer in their
+/// `getPartition(...)` body and report it via [PartitionFunction#getPartitionIdNormalizer()].
+/// The framework also uses the reported value for identity / staleness matching between
+/// config-side and segment-side partition metadata.
+public enum PartitionIdNormalizer {
+  /// Compute the remainder, then shift negative remainders into the valid range with `+ numPartitions`.
+  POSITIVE_MODULO {
+    @Override
+    int toPartitionId(int value, int numPartitions) {
+      int partition = value % numPartitions;
+      return partition < 0 ? partition + numPartitions : partition;
+    }
+
+    @Override
+    int toPartitionId(long value, int numPartitions) {
+      long partition = value % numPartitions;
+      return (int) (partition < 0 ? partition + numPartitions : partition);
+    }
+  },
+  /// Compute the remainder, then take its absolute value.
+  ABS {
+    @Override
+    int toPartitionId(int value, int numPartitions) {
+      int partition = value % numPartitions;
+      return partition < 0 ? -partition : partition;
+    }
+
+    @Override
+    int toPartitionId(long value, int numPartitions) {
+      long partition = value % numPartitions;
+      return (int) (partition < 0 ? -partition : partition);
+    }
+  },
+  /// Mask the sign bit before applying modulo.
+  MASK {
+    @Override
+    int toPartitionId(int value, int numPartitions) {
+      return (value & Integer.MAX_VALUE) % numPartitions;
+    }
+
+    @Override
+    int toPartitionId(long value, int numPartitions) {
+      return (int) ((value & Long.MAX_VALUE) % numPartitions);
+    }
+  },
+  /// Pre-modulo abs (Kafka-style) `abs(value) % numPartitions` that handles `Integer.MIN_VALUE -> 0`
+  /// (and `Long.MIN_VALUE -> 0`) to avoid the `Math.abs` overflow corner. Matches the
+  /// legacy semantics of `HashCodePartitionFunction` and `ByteArrayPartitionFunction`.
+  PRE_MODULO_ABS {
+    @Override
+    int toPartitionId(int value, int numPartitions) {
+      int abs = (value == Integer.MIN_VALUE) ? 0 : Math.abs(value);
+      return abs % numPartitions;
+    }
+
+    @Override
+    int toPartitionId(long value, int numPartitions) {
+      long abs = (value == Long.MIN_VALUE) ? 0L : Math.abs(value);
+      return (int) (abs % numPartitions);
+    }
+  };

Review Comment:
   PR description/examples refer to the Kafka-style normalizer as `KAFKA_ABS`, but the actual enum constant/config value introduced here is `PRE_MODULO_ABS`. To avoid user confusion and misconfiguration (since `fromConfigString` only accepts enum names), either align the constant name (or add an accepted alias like `KAFKA_ABS`) or update the PR/docs to consistently use `PRE_MODULO_ABS`.



##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionFunctionFactory.java:
##########
@@ -18,86 +18,154 @@
  */
 package org.apache.pinot.segment.spi.partition;
 
+import com.google.common.base.Preconditions;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Modifier;
+import java.util.Collections;
 import java.util.HashMap;
+import java.util.Locale;
 import java.util.Map;
+import java.util.Set;
 import javax.annotation.Nullable;
 import org.apache.pinot.segment.spi.partition.metadata.ColumnPartitionMetadata;
+import org.apache.pinot.spi.annotations.PartitionFunctionType;
 import org.apache.pinot.spi.config.table.ColumnPartitionConfig;
-
-
-/**
- * Factory to build instances of {@link PartitionFunction}.
- */
+import org.apache.pinot.spi.utils.PinotReflectionUtils;
+import org.reflections.Reflections;
+import org.reflections.scanners.SubTypesScanner;
+import org.reflections.util.ClasspathHelper;
+import org.reflections.util.ConfigurationBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/// Dynamic registry for [PartitionFunction] implementations.
+///
+/// Discovery walks every public, concrete [PartitionFunction] subtype on the classpath under the
+/// `org.apache.pinot.*` package tree, then registers each under its canonical name(s):
+///
+/// - If the class is annotated with [PartitionFunctionType] (and `enabled()` is true), the
+///   annotation's `names()` are used. Multiple aliases register the same constructor under each
+///   name (e.g. `Murmur` and `Murmur2` for `MurmurPartitionFunction`).
+/// - Otherwise, the registry probes [PartitionFunction#getName()] by instantiating the class with
+///   `(numPartitions=1, functionConfig=null)` and registers under the value returned. This lets
+///   existing partition functions work without adding the annotation.
+///
+/// Each registrable class must be public, concrete, and expose a public constructor with signature
+/// `(int numPartitions, Map<String, String> functionConfig)` β€” the constructor the registry calls
+/// when [#getPartitionFunction(String, int, Map)] is invoked.
+///
+/// The static block scans the classpath once and builds an immutable (canonicalized name β†’
+/// constructor) map. To force eager initialization (e.g. so the scan happens before the first
+/// segment is read), call [#init()] from broker / server / controller startup.
 public class PartitionFunctionFactory {
-  // Enum for various partition functions to be added.
-  public enum PartitionFunctionType {
-    Modulo, Murmur, Murmur2, Murmur3, Fnv, ByteArray, HashCode, BoundedColumnValue;
-    // Add more functions here.
+  private PartitionFunctionFactory() {
+  }
+
+  private static final Logger LOGGER = LoggerFactory.getLogger(PartitionFunctionFactory.class);
+  private static final String SCAN_PACKAGE = "org.apache.pinot";
 
-    private static final Map<String, PartitionFunctionType> VALUE_MAP = new HashMap<>();
+  private static final Map<String, Constructor<? extends PartitionFunction>> REGISTRY;
 
-    static {
-      for (PartitionFunctionType functionType : PartitionFunctionType.values()) {
-        VALUE_MAP.put(functionType.name().toLowerCase(), functionType);
+  static {
+    long startTimeMs = System.currentTimeMillis();
+    Map<String, Constructor<? extends PartitionFunction>> registry = new HashMap<>();
+    Set<Class<? extends PartitionFunction>> subtypes = scanSubtypes();
+    for (Class<? extends PartitionFunction> clazz : subtypes) {
+      int mods = clazz.getModifiers();
+      if (!Modifier.isPublic(mods) || Modifier.isAbstract(mods) || clazz.isInterface()) {
+        continue;
+      }
+      PartitionFunctionType annotation = clazz.getAnnotation(PartitionFunctionType.class);
+      if (annotation != null && !annotation.enabled()) {
+        continue;
+      }
+      Constructor<? extends PartitionFunction> constructor;
+      try {
+        constructor = clazz.getConstructor(int.class, Map.class);
+      } catch (NoSuchMethodException e) {
+        LOGGER.warn("Skipping {}: missing public constructor (int, Map<String, String>)", clazz.getName());
+        continue;
+      }
+      String[] names = resolveNames(clazz, annotation, constructor);
+      if (names == null) {
+        continue;
+      }
+      for (String name : names) {
+        String canonical = canonicalize(name);
+        Constructor<? extends PartitionFunction> existing = registry.put(canonical, constructor);
+        Preconditions.checkState(existing == null || existing.getDeclaringClass().equals(clazz),
+            "Partition function name '%s' is registered to both %s and %s", name,
+            existing == null ? null : existing.getDeclaringClass().getName(), clazz.getName());
       }

Review Comment:
   `resolveNames()` can return annotation-provided aliases without validation. If a class is annotated with `@PartitionFunctionType(names=...)` containing blank/whitespace-only entries, the factory will register an empty canonical name (or a name with spaces) and skip the `getName()` fallback, making the function effectively undiscoverable under its intended name. Consider trimming each alias and rejecting blanks (or falling back to `getName()` when all aliases are blank) so a misconfigured annotation can’t silently poison the registry during static initialization.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Dynamic PartitionFunction registry; unify int-to-id mapping via PartitionIdNormalizer [pinot]

Posted by "xiangfu0 (via GitHub)" <gi...@apache.org>.
xiangfu0 commented on code in PR #18446:
URL: https://github.com/apache/pinot/pull/18446#discussion_r3212003845


##########
pinot-common/src/main/java/org/apache/pinot/common/partition/function/BoundedColumnValuePartitionFunction.java:
##########
@@ -91,6 +94,12 @@ public Map<String, String> getFunctionConfig() {
     return _functionConfig;
   }
 
+  @Override
+  public PartitionIdNormalizer getPartitionIdNormalizer() {
+    // Output is a fixed mapping in [0, numPartitions); POSITIVE_MODULO is a no-op label.
+    return PartitionIdNormalizer.POSITIVE_MODULO;

Review Comment:
   Done in 1b3e70e β€” added an explicit `NO_OP` value to `PartitionIdNormalizer` (identity, no validation). `BoundedColumnValuePartitionFunction.getPartitionIdNormalizer()` now returns `NO_OP`. The range-invariant test correctly skips `NO_OP` and a new `testNoOpIsIdentity` locks the pass-through semantics.



##########
pinot-common/src/main/java/org/apache/pinot/common/partition/function/BoundedColumnValuePartitionFunction.java:
##########
@@ -16,29 +16,34 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-package org.apache.pinot.segment.spi.partition;
+package org.apache.pinot.common.partition.function;
 
 import com.google.common.base.Preconditions;
 import java.util.Map;
 import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.segment.spi.partition.PartitionFunction;
+import org.apache.pinot.segment.spi.partition.PartitionIdNormalizer;
+import org.apache.pinot.spi.annotations.PartitionFunctionType;
 
 
-/**
- * Implementation of {@link PartitionFunction} which partitions based configured column values.
- *
- * "columnPartitionMap": {
- *   "subject": {
- *     "functionName": "BoundedColumnValue",
- *     "functionConfig": {
- *       "columnValues": "Maths|English|Chemistry",
- *       "columnValuesDelimiter": "|"
- *     },
- *     "numPartitions": 4
- *   }
- * }
- * With this partition config on column "subject", partitionId would be 1 for Maths, 2 for English and 3 for Chemistry.
- * partitionId would be "0" for all other values which may occur, therefore 'numPartitions' is set to 4.
- */
+/// Implementation of [PartitionFunction] which partitions based on configured column values.
+///
+/// ```json
+/// "columnPartitionMap": {
+///   "subject": {
+///     "functionName": "BoundedColumnValue",
+///     "functionConfig": {
+///       "columnValues": "Maths|English|Chemistry",
+///       "columnValuesDelimiter": "|"
+///     },
+///     "numPartitions": 4
+///   }
+/// }
+/// ```
+///
+/// With this partition config on column "subject", `partitionId` is `1` for Maths, `2` for English and `3` for
+/// Chemistry. `partitionId` is `0` for all other values which may occur, therefore `numPartitions` is set to `4`.
+@PartitionFunctionType(names = "BoundedColumnValue")

Review Comment:
   Done in 8bb35d7 β€” annotation deleted entirely; `PartitionFunction` now has a `default List<String> getNames() { return Collections.singletonList(getName()); }` and the factory drives discovery off it. Only `MurmurPartitionFunction` overrides (returns `["Murmur", "Murmur2"]`).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Dynamic PartitionFunction registry; unify int-to-id mapping via PartitionIdNormalizer [pinot]

Posted by "codecov-commenter (via GitHub)" <gi...@apache.org>.
codecov-commenter commented on PR #18446:
URL: https://github.com/apache/pinot/pull/18446#issuecomment-4410547721

   ## [Codecov](https://app.codecov.io/gh/apache/pinot/pull/18446?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `74.81481%` with `34 lines` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 55.73%. Comparing base ([`4863cdc`](https://app.codecov.io/gh/apache/pinot/commit/4863cdcd821ea85b88cdd6ba7fc10c34679724e3?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`182d8d1`](https://app.codecov.io/gh/apache/pinot/commit/182d8d1c3378676a8d239f8b5162e13f545e0929?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   :warning: Report is 2 commits behind head on master.
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/pinot/pull/18446?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [...egment/spi/partition/PartitionFunctionFactory.java](https://app.codecov.io/gh/apache/pinot/pull/18446?src=pr&el=tree&filepath=pinot-segment-spi%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fpinot%2Fsegment%2Fspi%2Fpartition%2FPartitionFunctionFactory.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-cGlub3Qtc2VnbWVudC1zcGkvc3JjL21haW4vamF2YS9vcmcvYXBhY2hlL3Bpbm90L3NlZ21lbnQvc3BpL3BhcnRpdGlvbi9QYXJ0aXRpb25GdW5jdGlvbkZhY3RvcnkuamF2YQ==) | 56.06% | [21 Missing and 8 partials :warning: ](https://app.codecov.io/gh/apache/pinot/pull/18446?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [...t/segment/spi/partition/PartitionIdNormalizer.java](https://app.codecov.io/gh/apache/pinot/pull/18446?src=pr&el=tree&filepath=pinot-segment-spi%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fpinot%2Fsegment%2Fspi%2Fpartition%2FPartitionIdNormalizer.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-cGlub3Qtc2VnbWVudC1zcGkvc3JjL21haW4vamF2YS9vcmcvYXBhY2hlL3Bpbm90L3NlZ21lbnQvc3BpL3BhcnRpdGlvbi9QYXJ0aXRpb25JZE5vcm1hbGl6ZXIuamF2YQ==) | 92.59% | [0 Missing and 2 partials :warning: ](https://app.codecov.io/gh/apache/pinot/pull/18446?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [...partition/function/ByteArrayPartitionFunction.java](https://app.codecov.io/gh/apache/pinot/pull/18446?src=pr&el=tree&filepath=pinot-common%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fpinot%2Fcommon%2Fpartition%2Ffunction%2FByteArrayPartitionFunction.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vcGFydGl0aW9uL2Z1bmN0aW9uL0J5dGVBcnJheVBhcnRpdGlvbkZ1bmN0aW9uLmphdmE=) | 83.33% | [0 Missing and 1 partial :warning: ](https://app.codecov.io/gh/apache/pinot/pull/18446?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [.../partition/function/HashCodePartitionFunction.java](https://app.codecov.io/gh/apache/pinot/pull/18446?src=pr&el=tree&filepath=pinot-common%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fpinot%2Fcommon%2Fpartition%2Ffunction%2FHashCodePartitionFunction.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vcGFydGl0aW9uL2Z1bmN0aW9uL0hhc2hDb2RlUGFydGl0aW9uRnVuY3Rpb24uamF2YQ==) | 83.33% | [0 Missing and 1 partial :warning: ](https://app.codecov.io/gh/apache/pinot/pull/18446?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [...on/partition/function/ModuloPartitionFunction.java](https://app.codecov.io/gh/apache/pinot/pull/18446?src=pr&el=tree&filepath=pinot-common%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fpinot%2Fcommon%2Fpartition%2Ffunction%2FModuloPartitionFunction.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vcGFydGl0aW9uL2Z1bmN0aW9uL01vZHVsb1BhcnRpdGlvbkZ1bmN0aW9uLmphdmE=) | 83.33% | [0 Missing and 1 partial :warning: ](https://app.codecov.io/gh/apache/pinot/pull/18446?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   > :exclamation:  There is a different number of reports uploaded between BASE (4863cdc) and HEAD (182d8d1). Click for more details.
   > 
   > <details><summary>HEAD has 16 uploads less than BASE</summary>
   >
   >| Flag | BASE (4863cdc) | HEAD (182d8d1) |
   >|------|------|------|
   >|java-21|5|1|
   >|unittests|2|1|
   >|temurin|5|1|
   >|unittests2|1|0|
   >|integration|3|0|
   >|integration2|1|0|
   >|integration1|1|0|
   >|custom-integration1|1|0|
   ></details>
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@             Coverage Diff              @@
   ##             master   #18446      +/-   ##
   ============================================
   - Coverage     63.65%   55.73%   -7.92%     
   + Complexity     1735      817     -918     
   ============================================
     Files          3254     2545     -709     
     Lines        199446   148037   -51409     
     Branches      30977    23933    -7044     
   ============================================
   - Hits         126953    82506   -44447     
   + Misses        62356    58467    -3889     
   + Partials      10137     7064    -3073     
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/pinot/pull/18446/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Ξ” | |
   |---|---|---|
   | [custom-integration1](https://app.codecov.io/gh/apache/pinot/pull/18446/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [integration](https://app.codecov.io/gh/apache/pinot/pull/18446/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [integration1](https://app.codecov.io/gh/apache/pinot/pull/18446/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [integration2](https://app.codecov.io/gh/apache/pinot/pull/18446/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [java-21](https://app.codecov.io/gh/apache/pinot/pull/18446/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `55.73% <74.81%> (-7.92%)` | :arrow_down: |
   | [temurin](https://app.codecov.io/gh/apache/pinot/pull/18446/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `55.73% <74.81%> (-7.92%)` | :arrow_down: |
   | [unittests](https://app.codecov.io/gh/apache/pinot/pull/18446/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `55.73% <74.81%> (-7.92%)` | :arrow_down: |
   | [unittests1](https://app.codecov.io/gh/apache/pinot/pull/18446/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `55.73% <74.81%> (+0.02%)` | :arrow_up: |
   | [unittests2](https://app.codecov.io/gh/apache/pinot/pull/18446/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
   </details>
   
   [:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/apache/pinot/pull/18446?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Re: [PR] Make PartitionFunction registry dynamic; move impls to pinot-common [pinot]

Posted by "Jackie-Jiang (via GitHub)" <gi...@apache.org>.
Jackie-Jiang commented on code in PR #18446:
URL: https://github.com/apache/pinot/pull/18446#discussion_r3211455687


##########
pinot-common/src/main/java/org/apache/pinot/common/partition/function/BoundedColumnValuePartitionFunction.java:
##########
@@ -16,15 +16,18 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-package org.apache.pinot.segment.spi.partition;
+package org.apache.pinot.common.partition.function;
 
 import com.google.common.base.Preconditions;
 import java.util.Map;
 import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.segment.spi.partition.PartitionFunction;
+import org.apache.pinot.segment.spi.partition.PartitionIntNormalizer;
+import org.apache.pinot.spi.annotations.PartitionFunctionType;
 
 
 /**
- * Implementation of {@link PartitionFunction} which partitions based configured column values.
+ * Implementation of {@link PartitionFunction} which partitions based on configured column values.

Review Comment:
   (minor) markdown style. Same for other places



##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionIntNormalizer.java:
##########
@@ -0,0 +1,116 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.spi.partition;
+
+import com.google.common.base.Preconditions;
+import java.util.Locale;
+
+
+/**
+ * Maps a raw signed integer hash output to a non-negative partition id in {@code [0, numPartitions)}.
+ *
+ * <p>{@link PartitionFunction} implementations report which normalizer matches their internal modulo
+ * semantics via {@link PartitionFunction#getPartitionIdNormalizer()}. The framework uses this label
+ * for identity / staleness matching between config-side and segment-side partition metadata; legacy
+ * functions perform their own modulo internally and the value is purely descriptive for them.
+ */
+public enum PartitionIntNormalizer {

Review Comment:
   ```suggestion
   public enum PartitionIdNormalizer {
   ```



##########
pinot-common/src/main/java/org/apache/pinot/common/partition/function/BoundedColumnValuePartitionFunction.java:
##########
@@ -38,15 +41,23 @@
  * }
  * With this partition config on column "subject", partitionId would be 1 for Maths, 2 for English and 3 for Chemistry.
  * partitionId would be "0" for all other values which may occur, therefore 'numPartitions' is set to 4.
+ *
+ * <p>The mapping output is already in {@code [0, numPartitions)}, so the configured
+ * {@link PartitionIntNormalizer} (default {@link PartitionIntNormalizer#POSITIVE_MODULO}) is a
+ * no-op for in-range values; it is still applied so the field is uniform across all partition
+ * functions.
  */
+@PartitionFunctionType(names = "BoundedColumnValue")

Review Comment:
   See the comments in `PartitionFunctionFactory`, this change shouldn't be needed. Existing partition function should just work without change



##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionIntNormalizer.java:
##########
@@ -0,0 +1,116 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.spi.partition;
+
+import com.google.common.base.Preconditions;
+import java.util.Locale;
+
+
+/**
+ * Maps a raw signed integer hash output to a non-negative partition id in {@code [0, numPartitions)}.
+ *
+ * <p>{@link PartitionFunction} implementations report which normalizer matches their internal modulo
+ * semantics via {@link PartitionFunction#getPartitionIdNormalizer()}. The framework uses this label
+ * for identity / staleness matching between config-side and segment-side partition metadata; legacy
+ * functions perform their own modulo internally and the value is purely descriptive for them.
+ */
+public enum PartitionIntNormalizer {
+  /** Compute the remainder, then shift negative remainders into the valid range with {@code + numPartitions}. */
+  POSITIVE_MODULO {
+    @Override
+    int toPartitionId(int value, int numPartitions) {
+      int partition = value % numPartitions;
+      return partition < 0 ? partition + numPartitions : partition;
+    }
+
+    @Override
+    int toPartitionId(long value, int numPartitions) {
+      long partition = value % numPartitions;
+      return (int) (partition < 0 ? partition + numPartitions : partition);
+    }
+  },
+  /** Compute the remainder, then take its absolute value. */
+  ABS {
+    @Override
+    int toPartitionId(int value, int numPartitions) {
+      int partition = value % numPartitions;
+      return partition < 0 ? -partition : partition;
+    }
+
+    @Override
+    int toPartitionId(long value, int numPartitions) {
+      long partition = value % numPartitions;
+      return (int) (partition < 0 ? -partition : partition);
+    }
+  },
+  /** Mask the sign bit before applying modulo. */
+  MASK {
+    @Override
+    int toPartitionId(int value, int numPartitions) {
+      return (value & Integer.MAX_VALUE) % numPartitions;
+    }
+
+    @Override
+    int toPartitionId(long value, int numPartitions) {
+      return (int) ((value & Long.MAX_VALUE) % numPartitions);
+    }
+  },
+  /**
+   * Kafka-style {@code abs(value) % numPartitions} that handles {@code Integer.MIN_VALUE -> 0}
+   * (and {@code Long.MIN_VALUE -> 0}) to avoid the {@code Math.abs} overflow corner. Matches the
+   * legacy semantics of {@code HashCodePartitionFunction} and {@code ByteArrayPartitionFunction}.
+   */
+  KAFKA_ABS {

Review Comment:
   If `ABS` is standard, consider calling this one `PRE_MODULO_ABS`?



##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionFunction.java:
##########
@@ -57,4 +59,19 @@ public interface PartitionFunction extends Serializable {
   default Map<String, String> getFunctionConfig() {
     return null;
   }
+
+  /**
+   * Reports the {@link PartitionIntNormalizer} that drives this partition function's int-to-id
+   * mapping. The built-in implementations now apply the named normalizer directly, so the value is
+   * authoritative β€” recomputing a partition via
+   * {@code PartitionIntNormalizer.valueOf(getPartitionIdNormalizer()).getPartitionId(rawHash, numPartitions)}
+   * yields the same result as {@link #getPartition(String)} for the same raw hash input.
+   *
+   * <p>Used by the framework for identity / staleness matching between config-side and segment-side
+   * partition metadata. Each implementation must declare its own value β€” there is intentionally no
+   * default. Plug-ins whose output is already in {@code [0, numPartitions)} should return
+   * {@link PartitionIntNormalizer#POSITIVE_MODULO} (a no-op label).
+   */
+  @JsonIgnore

Review Comment:
   Why marking it json ignored? This comes from config right?
   Also, should PartitionFunction ever be serialized? I think it should be a logical wrapper, where we can directly return `PartitionIdNormalizer` class here



##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionFunction.java:
##########
@@ -57,4 +59,19 @@ public interface PartitionFunction extends Serializable {
   default Map<String, String> getFunctionConfig() {
     return null;
   }
+
+  /**
+   * Reports the {@link PartitionIntNormalizer} that drives this partition function's int-to-id
+   * mapping. The built-in implementations now apply the named normalizer directly, so the value is
+   * authoritative β€” recomputing a partition via
+   * {@code PartitionIntNormalizer.valueOf(getPartitionIdNormalizer()).getPartitionId(rawHash, numPartitions)}
+   * yields the same result as {@link #getPartition(String)} for the same raw hash input.
+   *
+   * <p>Used by the framework for identity / staleness matching between config-side and segment-side
+   * partition metadata. Each implementation must declare its own value β€” there is intentionally no
+   * default. Plug-ins whose output is already in {@code [0, numPartitions)} should return
+   * {@link PartitionIntNormalizer#POSITIVE_MODULO} (a no-op label).
+   */
+  @JsonIgnore
+  String getPartitionIdNormalizer();

Review Comment:
   Let's make it return `null` by default, which indicates we don't need to normalize the value



##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/partition/PartitionFunctionFactory.java:
##########
@@ -18,86 +18,118 @@
  */
 package org.apache.pinot.segment.spi.partition;
 
+import com.google.common.base.Preconditions;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Modifier;
+import java.util.Collections;
 import java.util.HashMap;
+import java.util.Locale;
 import java.util.Map;
 import javax.annotation.Nullable;
 import org.apache.pinot.segment.spi.partition.metadata.ColumnPartitionMetadata;
+import org.apache.pinot.spi.annotations.PartitionFunctionType;
 import org.apache.pinot.spi.config.table.ColumnPartitionConfig;
+import org.apache.pinot.spi.utils.PinotReflectionUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 
 /**
- * Factory to build instances of {@link PartitionFunction}.
+ * Dynamic registry for {@link PartitionFunction} implementations.
+ *
+ * <p>Discovery is driven by classpath scanning for classes annotated with
+ * {@link PartitionFunctionType}. Annotated classes must:
+ * <ul>
+ *   <li>be public and implement {@link PartitionFunction}</li>
+ *   <li>live under a package matching the regex {@code .*\.partition\.function\..*}
+ *       (e.g. {@code org.apache.pinot.common.partition.function} or any plugin package
+ *       that follows the same convention)</li>
+ *   <li>expose a public constructor with signature
+ *       {@code (int numPartitions, Map<String, String> functionConfig)}</li>
+ * </ul>
+ *
+ * <p>The static block scans the classpath once and builds an immutable
+ * (canonicalized name β†’ constructor) map. Instances are created on demand by
+ * {@link #getPartitionFunction(String, int, Map)}.
+ *
+ * <p>To force eager initialization (e.g. so the scan happens before the first segment
+ * is read), call {@link #init()} from broker/server/controller startup.
  */
 public class PartitionFunctionFactory {
-  // Enum for various partition functions to be added.
-  public enum PartitionFunctionType {
-    Modulo, Murmur, Murmur2, Murmur3, Fnv, ByteArray, HashCode, BoundedColumnValue;
-    // Add more functions here.
+  private PartitionFunctionFactory() {
+  }
 
-    private static final Map<String, PartitionFunctionType> VALUE_MAP = new HashMap<>();
+  private static final Logger LOGGER = LoggerFactory.getLogger(PartitionFunctionFactory.class);
+  private static final String SCAN_REGEX = ".*\\.partition\\.function\\..*";
 
-    static {
-      for (PartitionFunctionType functionType : PartitionFunctionType.values()) {
-        VALUE_MAP.put(functionType.name().toLowerCase(), functionType);
-      }
-    }
-
-    public static PartitionFunctionType fromString(String name) {
-      PartitionFunctionType functionType = VALUE_MAP.get(name.toLowerCase());
+  private static final Map<String, Constructor<? extends PartitionFunction>> REGISTRY;
 
-      if (functionType == null) {
-        throw new IllegalArgumentException("No enum constant for: " + name);
+  static {
+    long startTimeMs = System.currentTimeMillis();
+    Map<String, Constructor<? extends PartitionFunction>> registry = new HashMap<>();
+    for (Class<?> clazz : PinotReflectionUtils.getClassesThroughReflection(SCAN_REGEX, PartitionFunctionType.class)) {
+      if (!Modifier.isPublic(clazz.getModifiers()) || !PartitionFunction.class.isAssignableFrom(clazz)) {
+        continue;
+      }
+      PartitionFunctionType annotation = clazz.getAnnotation(PartitionFunctionType.class);
+      if (!annotation.enabled()) {
+        continue;
+      }
+      String[] names = annotation.names();
+      Preconditions.checkState(names.length > 0,

Review Comment:
   When annotation doesn't exist, we should take `PartitionFunction.getName()`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org